text:
Q: In image processing, why is it recommended to loop over Y first and then X second? I've read in a few places that when processing the pixels of an image, it is recommended that you loop over Y and then X pixels because it is more likely to be memory efficient. Why is this so?

A: A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
D1 D2 D3 D4

Supposing that's your image (and some sort of coordinates to it's points), it is stored in memory in a string, just like:
A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4 D1 D2 D3 D4.

Let's simulate those options:
For X and then by Y:
A1 B1 C1 D1 A2 B2 C2 D2 A3 B3 C3 D3 A4 B4 C4 D4

Now check on the string, how messy those access would be (just like random reads, right?)
Nor, For Y and then by X
A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4 D1 D2 D3 D4

See? Straight forward read!
That's why.

A: The pixels in the image are stored left to right first and then up to down.
Exactly like the letters in a book.
It would be very tiring to read every letter in a page top to bottom first and thus slowly reconstruct the sentences.
Don't work against the machine
The reason it is faster, is because the CPU reads data into its cache in "left to right" order. Usually 8 or 16 bytes at a time into a cache line.
If you process that data in the same order it is far more efficient than if you scan data "top to bottom", the CPU will read a lot of data into the cache that will not get used before it is overwritten.
This will cause the CPU to have to reread the same data in the cache, wasting time.
Speculative reads
Also if you read left to right, the CPU can anticipate further reads and will get data into the cache pro-actively  trying to keep up with your reading. If you're following any other order it will declare your accesses as "random" and not bother.
Look up cache lines in wikipedia.
Working with the cache is key
Note that this 'rule' not only applies to images, but to all data in a computer.
Cache misses are by far the biggest time eaters in most applications.


text:
Q: Jqgrid Get postData I would like to export only the data from jqgrid.
So basically I already have a bound grid with data and I want to get the data as json string so I can call BindGridModel(data) later on and bind the data without going back to the server only from client side.
how can I get data as json string so later on I can give it to the grid as data?
this is my grid configuration:
function BindGridModel(data) {
    $('#jqgInventory').jqGrid({
        autowidth: true,
        caption: 'Inventory',
        datatype: 'json',
        forceFit: true,
        gridview: true,
        height: 500,
        hidegrid: false,
        ignoreCase: true,
        loadui: 'disable',
        pager: '#pager',
        mtype: 'post',
        rowNum: 25,
        shrinkToFit: true,
        url: '/MCI/Inventory/Inventory/GetIndexGridData',
        viewrecords: true,
        postData: {
            modelView: JSON.stringify(model),
            __RequestVerificationToken: $('[name="__RequestVerificationToken"]').val()
        },
        beforeRequest: function() {
            $('#gridScript').block();
        },
        beforeSelectRow: function(rowid, e) {
            return false;
        },
        gridComplete: function() {
            $('#lblVehicleCount').html($('#jqgInventory').getGridParam('records'));
            $('#gridScript').unblock();
            Inventory.modifyGridCellClick();
        },
        colModel: [
            {
            align: 'center',
            name: 'Select',
            label: 'SEL',
            title: true,
            width: 20,
            index: 'Select'},
        {
            align: 'left',
            name: 'Photo',
            hidden: false,
            label: 'PHOTO',
            stype: 'text',
            sortable: false,
            sorttype: 'text',
            title: true,
            width: 100,
            index: 'Photo'},
        {
            align: 'left',
            name: 'Information',
            hidden: false,
            label: 'INFO',
            stype: 'text',
            sortable: false,
            sorttype: 'text',
            title: true,
            width: 100,
            index: 'Information'},
        {
            align: 'right',
            name: 'Price',
            hidden: false,
            label: 'PRICE',
            stype: 'text',
            sortable: true,
            sorttype: function(cellValue) {
                return CustomGridSortByIntegerAsString(cellValue);
            },
            title: true,
            width: 50,
            index: 'Price'},
        {
            align: 'right',
            name: 'Mileage',
            hidden: false,
            label: 'MILEAGE',
            stype: 'text',
            sortable: true,
            sorttype: function(cellValue) {
                return CustomGridSortByIntegerAsString(cellValue);
            },
            title: true,
            width: 25,
            index: 'Mileage'},
        {
            align: 'right',
            name: 'Age',
            hidden: false,
            label: 'AGE',
            stype: 'text',
            sortable: true,
            sorttype: function(cellValue) {
                return CustomGridSortByIntegerAsString(cellValue);
            },
            title: true,
            width: 50,
            index: 'Age'},
        {
            name: 'VehicleKey',
            hidden: true,
            label: 'VEHICLEKEY',
            width: 50,
            index: 'VehicleKey'}
        ],
        data: data
    });
}

A: In the loadComplete event you have access to the data that was bound to the grid, and can JSON stringify it. I typically set that to a Jquery data property so that I have access to it outside of the event.
loadComplete: function(data) {
    $('#gridid').data('jqdata', data);//JSON stringify the data 1st if you need to
},

You can then access that data later via:
$('#gridid').data('jqdata');

redpajama_set_name: RedPajamaStackExchange


text:
Q: Конфликт кода Добрый день, уважаемые.
Имеется код.
$(document).ready(init);

function init() {
    $('.slot41').hover(hOver, hOut);
}

function hOver() {
    $('.slot4').css("background-image", "url(images/slot4.gif)");
}

function hOut() {
    $('.slot4').css("background-image", "url(images/slot4.png)");
}

На странице должно быть 6 объектов, работающих по такому коду независимо друг от друга. Проблема заключается в следующем, что если добавить еще один код, например, такой
$(document).ready(initt);

function initt() {
    $('.slot11').hover(hOver, hOut);
}

function hOver() {
    $('.slot1').css("background-image", "url(images/slot1.gif)");
}

function hOut() {
    $('.slot1').css("background-image", "url(images/slot1.png)");
}

то предыдущий перестает работать. Помогите разобраться из-за чего конфликт.
A: $(document).ready(init);

function init() {
    $('.slot41').hover(hOver4, hOut4);
    $('.slot11').hover(hOver1, hOut1);
}
function hOver4() {
    $('.slot4').css("background-image", "url(images/slot4.gif)");
}
function hOut4() {
    $('.slot4').css("background-image", "url(images/slot4.png)");
}
function hOver1() {
    $('.slot1').css("background-image", "url(images/slot1.gif)");
}
function hOut1() {
    $('.slot1').css("background-image", "url(images/slot1.png)");
}

Может так.
A:
Как сделать чтобы была не рукалицо ???

$("some element").hover(
  function () {
    //some actions
  },
  function () {
    //some actions
  }
);

в вашем случае:
$(".slot11").hover(
  function () {
    $(this).css("background-image", "url(images/slot1.gif)");
  },
  function () {
    $(this).css("background-image", "url(images/slot1.png)");
  }
);

UPD: Не верно прочел вопрос... извиняюсь!

Hover My

Hover My

З.Ы. Суть работы ясна, перекручивайте под свои потребности!
color можно заменить на image и передавать значение в виде "image.png,image.gif"
A:
slot1

slot2

slot3

slot4

теперь jQuery:
$(function(){
    $('.slot').hover(hOver, hOut);
});

function hOver() {
    var img = $(this).data('image');
    $(this).css("background-image", "url(images/" + img + ".gif)");
}

function hOut() {
    var img = $(this).data('image');
    $(this).css("background-image", "url(images/" + img + ".png)");
}


text:
Q: Why does jQuery say my ajax jsonp call is failing? Not sure what I'm missing here, if you take a look at this code - you'll see I'm making a jsonp call to flickr and getting a successful response. However, jQuery always calls the 'fail' method and not the success method.
Why?
{{ EDITED }}
$.ajax({
      url: 'http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=fun&tagmode=any',
      dataType: 'jsonp'
  })
  .done(function(data, status) {
    console.log( 'data count:', data.query.results.json.json.length );
    $('#result-count').text( JSON.stringify(data.query.results.json.json) );
  })
  .fail(function(xhr, err) {
    console.log( 'Sample of error data:', err );
    console.log("readyState: "+xhr.readyState+"\nstatus: "+xhr.status+"\nresponseText: "+xhr.responseText); });
  });

A: It's failing because you're using the wrong jsonp callback.
...
type: 'GET',
jsonpCallback: 'jsonFlickrFeed'
...

also, in recent versions of jQuery, jsonp requests don't trigger a fail callback on error, async:false is ignored for jsonp requests, and crossDomain is not necessary (jquery sets that for you).


text:
Q: How to create database schema (table) in Laravel? I'm new to Laravel.I'm trying to create database in Laravel. I tried in console with:
Schema::create

But it's giving 'command not found'. What should I install or how to create database?

A: my working example:
create new artisan command:
php artisan make:command mysql

the content of App\Console\Commands\mysql.php :
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class mysql extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mysql:createdb {name?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new mysql database schema based on the database config file';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $schemaName = $this->argument('name') ?: config("database.connections.mysql.database");
        $charset = config("database.connections.mysql.charset",'utf8mb4');
        $collation = config("database.connections.mysql.collation",'utf8mb4_unicode_ci');

        config(["database.connections.mysql.database" => null]);

        $query = "CREATE DATABASE IF NOT EXISTS $schemaName CHARACTER SET $charset COLLATE $collation;";

        DB::statement($query);

        config(["database.connections.mysql.database" => $schemaName]);

    }
}

then run: (schema_name is optionally)
php artisan mysql:createdb schema_name

A: If you want to create model with artisan do it this way:
php artisan make:model ModelName

A: First you have to set database name,username and password in database.php in config folder.it look like
'connections' => [

        'sqlite' => [
            'driver'   => 'sqlite',
            'database' => storage_path('database.sqlite'),
            'prefix'   => '',
        ],

        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'news'),
            'username'  => env('DB_USERNAME', 'root'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

        'pgsql' => [
            'driver'   => 'pgsql',
            'host'     => env('DB_HOST', 'localhost'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ],

        'sqlsrv' => [
            'driver'   => 'sqlsrv',
            'host'     => env('DB_HOST', 'localhost'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset'  => 'utf8',
            'prefix'   => '',
        ],

    ],

if you are using xampp then right click on your project folder and click on use composer here
then run following command
 php artisan migrate:install

and  you can create table like
php artisan make:migration create_users_table

Migration Structure
A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should simply reverse the operations performed by the up method.
Within both of these methods you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the Schema builder, check out its documentation. For example, let's look at a sample migration that creates a flights table:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }
}

To know all artisan command run following command
php artisan

for more read following document http://laravel.com/docs/5.1/migrations

A: Database setup in Laravel

*

*open .env file on root

example :-
  DB_CONNECTION=mysql
  DB_HOST=127.0.0.1
  DB_PORT=3306
  DB_DATABASE=dbname
  DB_USERNAME=root
  DB_PASSWORD=password

Now run command

  php artisan migrate:install
  php artisan make:migration users // for creating new table


text:
Q: How to use JavaParser to walk over all the nodes of AST (abstract syntax tree) of some Java source code? I am trying to build a translator of Java source code to other object-oriented programming languages. For this I want to traverse the whole AST (generated by JavaParser) and gather each and every component of the Java source code and then correspondingly translate them to my target language. I did not find anything related to the traversal of the complete AST in online searches, though I did find about locating specific nodes such as 'class or interface declaration', etc. Any help would be appreciated.

A: After going through the documentation, I realised that using getChildNodes() function will help us to visit each and every node of the Java source code AST from root to leaf nodes.


text:
Q: Usuário com cookies do navegador desativados Tenho um sistema e utilizo cookies para guardar temporariamente uma informação, porém notei um problema com certo usuário e ao tentar resolver o problema, notei que o mesmo tinha os cookies desabilitados (não me pergunte o porquê).
Eu seto os cookies de maneira convencional pelo php
setcookie(...);

Então, essas são minhas perguntas:

*

*Tem como eu saber se um usuário está com os cookies do navegador desabilitados?

*Se sim, como devo proceder?

A: Creio que com o PHP não será possível, mas você pode tentar em javascript, algo do tipo:
<script type="text/javascript">

var tmpcookie = new Date();

chkcookie = (tmpcookie.getTime() + '');

document.cookie = "chkcookie=" + chkcookie + "; path=/";

if( document.cookie.indexOf(chkcookie,0) < 0 )
{
    alert('Cookie desabilitado');
}
else
{
    alert('Cookie habilitado');
}

</script>

Referência


text: Q: Reference request: Fuchsian Model of compact Riemann surface Let $S$ be a compact Riemann surface with genus $\geq$ 2. Then by the Uniformization theorem it has universal covering space the upper half-plane $\mathbb{H}$(up to conformal equivalence). Now I read that we can express $S$ as $\mathbb{H}/\Gamma$, where $\Gamma$ is a stricly hyperbolic Fuchsian group. The statement sounds reasonable, but I want to have a actual proof of that. Can someone suggest a reference for that? Thanks a lot.


text:
Q: Arc Length and Differential Forms Suppose $\gamma$ is circle in $\mathbb{R}^3$ defined by coordinates $\begin{pmatrix}r\cos\theta\\r\sin\theta\\0\end{pmatrix}$, and function $F: \gamma \rightarrow \mathbb{R}^3$ is defined by $F(\gamma(\theta)) = \begin{pmatrix}-\sin\theta \\ \cos\theta\\0\end{pmatrix}$, and let 1-form in $\mathbb{R}^3$$\lambda_F = F_1dx+F_2dy+F_3dz$, where $F_i$ is the component of $F$.
Why $\int_\gamma{\lambda_F}$ is the length of the circle $\gamma$?
I know that one can do some calculation like $\int_\gamma{\lambda_F} = \int_0^{2\pi}\vert\gamma'(\theta)\vert d\theta = 2\pi r$, what I'm asking is an intuitive explanation, i.e. why when you put that specific $\lambda_F$ there, it gives you the arclength, intuitively.
Thanks.

A: Use Pythagoras.
The arc length between the points $A$ and $B$ is approximated by the length of the straight segment $AB$. If $A=(x_1,y_1,z_1)$ and $B=(x_2,y_2,z_2)$ then $AB=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2+(z_2-z_1)^2}$.
When $A$ and $B$ are close together then $x_2-x_1\sim (F\circ\gamma_1)'d\theta=F_1d\theta$. Similarly for $y_2-y_1$ and $z_2-z_1$.

A: Let $\gamma:[a,b]\longrightarrow\Bbb R^3$ be a parametrized curve. Near a point $(t_0, \gamma(t_0))$,
$$\gamma(t)\approx \gamma'(t_0)(t-t_0)+\gamma(t_0)$$
i.e.
$$\|\gamma(t)-\gamma(t_0)\|\approx\|\gamma'(t_0)\||t-t_0|$$
or,
$$\Delta(\text{length})\approx\|\gamma'(t)\|\Delta t.$$
What happens in the limit?


text:
Q: Using Azure Mobile Services Code First Generated Context class in another project I have a Windows Azure Mobile Services app that has a Code First generated database. The connection string (for when run locally) looks like this:
<add name="MS_TableConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\<database_name.mdf;Initial Catalog=<database_name>;Integrated Security=True;MultipleActiveResultSets=True"
  providerName="System.Data.SqlClient" />

I created a new Console App project, referencing the Mobile Services project, and copied this connection string to the App.config file
In Program.Main() I created a new instance of the Context class from the Designer in the Mobile Services project. But when I run the Console App, and try to access one of the DbSets made public by the Context, I get the following exception:
"An exception occurred while initializing the database. See the InnerException for details."

With an inner exception of:
"The underlying provider failed on Open."

Which in turn has an inner exception of:
"Cannot attach the file 'C:\\...\\<database_name>.mdf' as database '<database_name>'."

If I remove the AttachDbFilename part of the connection string in the Console App, I get the following exception at the same point in the code:
"Cannot create more than one clustered index on table 'dbo.<Table_Name>'. Drop the existing clustered index 'PK_dbo.<Table_Name>' before creating another"

Does anyone have any idea why it would be trying to create this new clustered index when there already appears to be one?
Or any ideas what connection string I should use just to get a normal read/write connection to the database without it doing anything weird? Is this related to database initialization?
Edit: I've had a bit more of a play around with this, this morning. I can get it working without exceptions if I remove the inheritance of "Microsoft.WindowsAzure.Mobile.Service.EntityData" from my model classes, so this appears to be pretty significant.

A: Ok I've just battled through this and got it working. Gonna type this up in case it helps anyone one day.
So the problem is something to do with the fact that my Code First model classes were inheriting from EntityData. As I said in my edit above, removing this inheritance does appear to fix the problem. I think this is because the EntityData class has both a property with a [Key] attribute and a separate property with a [Index(IsClustered = true)] attribute. Because you can't have more than one Clustered Index in a table, the database initialization fails. In the default Azure Mobile Services project, there must be some magic that means this doesn't happen somewhere - but from a separate project you get the "Cannot create more than one clustered index on table" exception.
So what I did was disable Database Initialization in the separate Console App by adding the line:
Database.SetInitializer<MobileServiceContext>(null);

...before the DbContext is instantiated.
This allows me to use the database initialized by the Mobile Services App as an existing database, without attempting to make any changes to it.
I also needed the following AppSetting in the config file of the Console App, in order for it to use the correct Schema Name:
<add key="MS_MobileServiceName" value="<CorrectSchemaName>" />


text:
Q: savechanges in ASP.NET MVC AJAX I have problem with savechanges. This code changes value after click, but it doesn't save this to database. Any ideas?
View:
@foreach (var item in Model)
{

        @Html.DisplayFor(modelItem => item.Content)
        @Ajax.ActionLink("ClickMe", "IncrementRating", new { compareId = item.ID }, new AjaxOptions
        {
          HttpMethod = "POST",
          UpdateTargetId = "Rating_" + @item.ID,
          InsertionMode = InsertionMode.Replace
        })

@Html.DisplayFor(modelItem => item.Rating

}

Controller:
[HttpPost]
public PartialViewResult IncrementRating(int compareId)
{
    var comparison = db.Comparisons.Find(compareId);
    comparison.Rating += 1;
    db.Entry(comparison).State = EntityState.Modified;
    db.Comparisons.Attach(comparison);
    db.SaveChanges();
    return PartialView("_Voting", comparison);
}

Partial view: _Voting
@model Compare.Models.Comparison
@Html.DisplayFor(model=>Model.Rating)

A: Perhaps the validation error occurs when attaching the object as you do.  Does the same error ocur when you do it somehow like this?
[HttpPost]
public PartialViewResult IncrementRating(int compareId)
{
    var comparison = db.Comparisons.SingleOrDefault(o => o.id == comapreId);

    comparison.Rating += 1;
    //Other edit sutff......
    //db.Comparisons.Attach(comparison);

    db.SaveChanges();

    return PartialView("_Voting", comparison);
}

I know, this should have been a comment rather than answer but it came out as a comment not good for reading.


text:
Q: How to make History command to record the userid, timestamp, ip address and command We have a server being visited all the time. I want to record the userid, ip address and commands being executed. Please kindly tell me how to do it? Thanks!

A: I think you're really looking for auditing. A few quick pointers:

*

*For Linux

*For FreeBSD
Basically, these frameworks can be configured to log every command executed, including the arguments given, etc.


text:
Q: flutter timezone adding database with terminal not working I'm using time zone in my project and I was trying to download the database using this command flutter pub run tool/get -s 2021d. I've redirected from external libraries and run this command from C:\flutter\.pub-cache\hosted\pub.dartlang.org\timezone-0.8.0>.
but when I run Failed to precompile timezone:get: Error: Error when reading '../../../global_packages/timezone/.dart_tool/package_config.json': The system cannot find the path specified. is thrown.
full error
    C:\flutter\.pub-cache\hosted\pub.dartlang.org\timezone-0.8.0>flutter pub run tool/get -s 2021d
Failed to precompile timezone:get:
Error: Error when reading '../../../global_packages/timezone/.dart_tool/package_config.json': The system cannot find the path specified.

Error: Couldn't resolve the package 'args' in 'package:args/args.dart'.
Error: Couldn't resolve the package 'file' in 'package:file/file.dart'.
Error: Couldn't resolve the package 'glob' in 'package:glob/glob.dart'.
Error: Couldn't resolve the package 'glob' in 'package:glob/list_local_fs.dart'.
Error: Couldn't resolve the package 'logging' in 'package:logging/logging.dart'.
Error: Couldn't resolve the package 'path' in 'package:path/path.dart'.
Error: Couldn't resolve the package 'timezone' in 'package:timezone/src/tools.dart'.
Error: Couldn't resolve the package 'timezone' in 'package:timezone/src/tzdb.dart'.
Error: Couldn't resolve the package 'timezone' in 'package:timezone/timezone.dart'.
pub finished with exit code 1

how can I fix this?
more of the thrown error
    tool/get.dart:16:8: Error: Not found: 'package:args/args.dart'
import 'package:args/args.dart';
       ^
tool/get.dart:17:8: Error: Not found: 'package:file/file.dart'
import 'package:file/file.dart' as pkg_file;
       ^
tool/get.dart:18:8: Error: Not found: 'package:glob/glob.dart'
import 'package:glob/glob.dart';
       ^
tool/get.dart:19:8: Error: Not found: 'package:glob/list_local_fs.dart'
import 'package:glob/list_local_fs.dart';
       ^
tool/get.dart:20:8: Error: Not found: 'package:logging/logging.dart'
import 'package:logging/logging.dart';
       ^
tool/get.dart:21:8: Error: Not found: 'package:path/path.dart'
import 'package:path/path.dart' as p;
       ^
tool/get.dart:23:8: Error: Not found: 'package:timezone/src/tools.dart'
import 'package:timezone/src/tools.dart';
       ^
tool/get.dart:24:8: Error: Not found: 'package:timezone/src/tzdb.dart'
import 'package:timezone/src/tzdb.dart';
       ^
tool/get.dart:25:8: Error: Not found: 'package:timezone/timezone.dart'
import 'package:timezone/timezone.dart';
       ^
tool/get.dart:26:8: Error: Not found: 'package:timezone/tzdata.dart'
import 'package:timezone/tzdata.dart' as tzfile;
       ^
tool/get.dart:45:8: Error: Type 'tzfile.Location' not found.
Future<tzfile.Location> loadTzfileLocation(String name, String path) async {
       ^^^^^^^^^^^^^^^
tool/get.dart:28:17: Error: Method not found: 'join'.
final outPath = p.join('lib', 'data');
                ^^^^
tool/get.dart:47:17: Error: Getter not found: 'Location'.
  return tzfile.Location.fromBytes(name, rawData);
                ^^^^^^^^
tool/get.dart:52:19: Error: Method not found: 'join'.
  final outPath = p.join(dest, 'tzdata$version.tar.gz');
                  ^^^^
tool/get.dart:95:3: Error: Getter not found: 'Logger'.
  Logger.root.level = Level.ALL;
  ^^^^^^
tool/get.dart:95:23: Error: Getter not found: 'Level'.
  Logger.root.level = Level.ALL;
                      ^^^^^
tool/get.dart:96:3: Error: Getter not found: 'Logger'.
  Logger.root.onRecord.listen((LogRecord rec) {
  ^^^^^^
tool/get.dart:96:32: Error: 'LogRecord' isn't a type.
  Logger.root.onRecord.listen((LogRecord rec) {
                               ^^^^^^^^^
tool/get.dart:99:15: Error: Method not found: 'Logger'.
  final log = Logger('main');
              ^^^^^^
tool/get.dart:102:18: Error: Method not found: 'ArgParser'.
  final parser = ArgParser()
                 ^^^^^^^^^
tool/get.dart:113:35: Error: 'Location' isn't a type.
  final tzfileLocations = <tzfile.Location>[];
                                  ^^^^^^^^
tool/get.dart:127:24: Error: Method not found: 'join'.
    final zicDirPath = p.join(tmpDir.path, 'zic');
                       ^^^^
tool/get.dart:133:17: Error: Method not found: 'join'.
      await zic(p.join(tmpDir.path, i), zicDirPath);
                ^^^^
tool/get.dart:137:25: Error: Method not found: 'Glob'.
    final files = await Glob('**/*').list(root: zicDirPath).toList();
                        ^^^^
tool/get.dart:139:25: Error: 'File' isn't a type.
      if (f is pkg_file.File) {
                        ^^^^
tool/get.dart:140:22: Error: Method not found: 'relative'.
        final name = p.relative(f.path, from: zicDirPath);
                     ^^^^^^^^
tool/get.dart:152:14: Error: Method not found: 'LocationDatabase'.
  final db = LocationDatabase();
             ^^^^^^^^^^^^^^^^
tool/get.dart:154:12: Error: Method not found: 'tzfileLocationToNativeLocation'.
    db.add(tzfileLocationToNativeLocation(loc));
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tool/get.dart:156:18: Error: 'FilterReport' isn't a type.
  void logReport(FilterReport r) {
                 ^^^^^^^^^^^^
tool/get.dart:166:17: Error: Method not found: 'filterTimeZoneData'.
  final allDb = filterTimeZoneData(db);
                ^^^^^^^^^^^^^^^^^^
tool/get.dart:170:60: Error: Getter not found: 'commonLocations'.
  final commonDb = filterTimeZoneData(allDb.db, locations: commonLocations);
                                                           ^^^^^^^^^^^^^^^
tool/get.dart:170:20: Error: Method not found: 'filterTimeZoneData'.
  final commonDb = filterTimeZoneData(allDb.db, locations: commonLocations);
                   ^^^^^^^^^^^^^^^^^^
tool/get.dart:177:18: Error: Getter not found: 'commonLocations'.
      locations: commonLocations);
                 ^^^^^^^^^^^^^^^
tool/get.dart:174:25: Error: Method not found: 'filterTimeZoneData'.
  final common_10y_Db = filterTimeZoneData(commonDb.db,
                        ^^^^^^^^^^^^^^^^^^
tool/get.dart:181:23: Error: Method not found: 'join'.
  final allOut = File(p.join(outPath, '${source}_all.tzf'));
                      ^^^^
tool/get.dart:182:26: Error: Method not found: 'join'.
  final commonOut = File(p.join(outPath, '$source.tzf'));
                         ^^^^
tool/get.dart:183:31: Error: Method not found: 'join'.
  final common_10y_Out = File(p.join(outPath, '${source}_10y.tzf'));
                              ^^^^
tool/get.dart:184:29: Error: Method not found: 'tzdbSerialize'.
  await allOut.writeAsBytes(tzdbSerialize(allDb.db), flush: true);
                            ^^^^^^^^^^^^^
tool/get.dart:185:32: Error: Method not found: 'tzdbSerialize'.
  await commonOut.writeAsBytes(tzdbSerialize(commonDb.db), flush: true);
                               ^^^^^^^^^^^^^
tool/get.dart:186:37: Error: Method not found: 'tzdbSerialize'.
  await common_10y_Out.writeAsBytes(tzdbSerialize(common_10y_Db.db),
                                    ^^^^^^^^^^^^^
pub finished with exit code 1


text:
Q: Visualizing discrete 3D data I have 3D data which is of the following form:
[(X1, Y1, Z1, VALUE1), (X2, Y2, Z2, VALUE2)...]

X, Y and Z are integers between 1 and 5 and value is an integer greater or equal to zero. So, for example a dataset could look like this:
import numpy as np
x = np.array(range(1,6))
y = np.array(range(1,6))
z = np.array(range(1,6))
data = np.random.randint(1,100, size=(len(x), len(y), len(z)) )

Now I would like to visualize the data in 3D. One possibility would be to plot cubes of different color to fill the space given by the arrays (x,y,z) as shown in the answer here: 3D discrete heatmap in matplotlib
The problem is that there exist 125 cubes.
Is there a better visualization for visualizing the 3D distribution of the data? Ideally, a plot would allow to inspect the different cubes but also an aggregation over some cubes could work.


text:
Q: Android ListView won't populate I'm trying to populate my ListView with values from a string array.  There are values in the string array, as I've checked to make sure.  I'm using code that, from what I've seen from previous searches, is correct.  I'm running the app through an Android emulator and have tried creating a new emulator, cleaning the project, and restarting Eclipse.  But still when the app starts up there is no data in the list.
I'm using the Galaxy Nexus emulator running Android 4.2.
MainActivity.java:
public class MainActivity extends Activity {

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

    ListView redditView = (ListView) findViewById(R.id.redditView);
    String[] redditList = readRedditFeed();

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_list_item_1, redditList);

    redditView.setAdapter(adapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public String[] readRedditFeed()
{

    return output;
}
}

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/redditView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >

</ListView>

</RelativeLayout>

A: You are parsing data in main thread it may give ANR.
Use either Thread and handler or AsyncTask.
After getting parsed result from thread use handler to set adapter in your list
OR
use AsyncTask doInbackground() method to receiving and parsing data and onPostExecute()
set adapter in your list.

A: just use an asyncTask to do the background work without blocking the UI.
private LoadingStuffTask task;
private String [] redditList;
private ArrayAdapter<String> adapter;

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

    ListView redditView = (ListView) findViewById(R.id.redditView);
     task = new LoadingStuffTask();
    task.execute("Process started!");

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

    private class LoadingStuffTask extends
            AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            redditList=readRedditFeed()
        }

        @Override
        protected void onProgressUpdate(
                String... values) {
        }

        @Override
        protected void onPostExecute(String result) {
            pdia.dismiss();
            adapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_list_item_1, redditList);
            redditView.setAdapter(adapter);

        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdia = new ProgressDialog(classificaA.this);
            pdia.setMessage("Doing background..");
            pdia.show();
        }

    }

public String[] readRedditFeed()
{
    ArrayList<String> redditList = new ArrayList<String>();

    try
    {
        URL url = new URL("http://www.reddit.com/.json");
        InputStream in = url.openStream();
        DataInputStream din = new DataInputStream(new BufferedInputStream(in));

        String line = "";
        String lines = "";
        while((line = din.readLine()) != null)
            lines += line;

        JSONObject json = (JSONObject) new JSONTokener(lines).nextValue();
        json = (JSONObject) json.getJSONObject("data");
        JSONArray jsonArr = (JSONArray) json.getJSONArray("children");

        for(int i = 0; i < 5; i++)
        {

            json = jsonArr.getJSONObject(i);
            json = (JSONObject) json.getJSONObject("data");
            redditList.add(json.get("title").toString().replaceAll("\"", ""));
        }

    }
    catch (Exception e)
    {}

    String[] output = new String[redditList.size()];
    redditList.toArray(output);
    return output;
}
}


text:
Q: Laplace transform of the square wave to solve PDE Solve $$y'' + 3y' +2y = r(t)$$ given $y(0)=0$ and $y'(0) = 0$ where $r(t)$ is the square wave, $$r(t) = u(t-1) - u(t-2)$$

I'm just going to type out the answer as I read it and tell you which parts I understand and which parts I have trouble intuitively grasping, I hope this is OK.

SOLUTION
Using Laplace transforms,
$$
\begin{array}
\ L[y'' +3y'+2y] = L[r(t)]\\
\implies L[y'' +3y' +2y] = L[u(t-1) - u(t-2)]\\
\implies [s^2 Y(s) - s y(0) - y'(0)] + 3[s Y(s) - y(0)] +2 Y(s) = \color{green}{{1 \over s} [e^{-s} - e^{-2s}]}\\
\end{array}
$$

The last part in $\color{green}{\text{green}}$ I guess comes from this result for the $\color{green}{\text{Dirac's Delta Function}}$:
  $$L[\delta (t-a)] = e^{-as}$$
  (Because the square wave is a step function?)

Now,
$$
\ Y(s) [s^2 +3s +2] = {1 \over s} [e^{-s} - e^{-2s}] = \frac{1}{(s{^2} +3s +2 s)s} [e^{-s} - e^{-2s}]\\
$$
$$F(s)= \frac{1}{(s{^2} +3s +2 s)s} = {1 \over 2s} - {1 \over {s+1}} + {1 \over s(s+2)} $$
$$ f(t) = L^{-1}[F(s)] = L^{-1}[{1 \over 2s} - {1 \over {s+1}} + {1 \over s(s+2)}] \implies f(t) = {1 \over 2} - e^t + {1 \over 2} e^{-2t}$$

Up to this point I think I can grasp what's going on. But after this, I'm not 100% sure I follow:

$$ Y(s) = L^{-1} [ F(s) e^{-s} - F(s) e^{-2s}] = \color{blue}{f(t-1)u(t-1) - f(t-2)u(t-2)}$$
$$
\color{red}{
Y(s) =
\begin{cases}
0, &0 < t< 1 \\[2ex]
{1 \over 2} - e^{-(t-1)} + {1 \over 2} e^{-2(t-1)}, &1< t<2 \\[2ex]
{1 \over 2} e^{-(t-1)} - {1 \over 2} e^{-2(t-1)} - {1 \over 2} e^{(t-2)} + {1 \over 2} e^{2(t-2)}, &t>2 \\[2ex]
\end{cases}}
$$

I have absolutely no idea how $\color{blue}{this}$ became  $\color{red}{this}$
I've looked at this result for a few days now but can't seem to get the intuition right. That's why I came here. I need to understand how this answer became this set of cases. I would appreciate your help very much!

A: For $t<1$ we have $u(t-1)=0$ and for $t<2$ we have $u(t-2)=0$. So for $t<1$ we have $f(t-1)u(t-1)=0$ and $f(t-2)u(t-2)=0$ and then $y(t)=0$.
For $t> 1$ we have $u(t-1)=1$ and for $t<2$ we have $u(t-2)=0$. So for $1<t<2$ we have $f(t-1)u(t-1)=f(t-1)$ and $f(t-2)u(t-2)=0$ and then $$y(t)=f(t-1)={1 \over 2} - e^{-(t-1)} + {1 \over 2} e^{-2(t-1)}$$.
For $t> 2$ we have $u(t-1)=1$ and for $t>2$ we have $u(t-2)=1$. So for $t>2$ we have $f(t-1)u(t-1)=f(t-1)$ and $f(t-2)u(t-2)=f(t-2)$ and then $$y(t)=f(t-1)-f(t-2)={1 \over 2} - e^{-(t-1)} + {1 \over 2} e^{-2(t-1)}-\left[{1 \over 2} - e^{-(t-1)} + {1 \over 2} e^{-2(t-1)}\right]={1 \over 2} e^{-(t-1)} - {1 \over 2} e^{-2(t-1)} - {1 \over 2} e^{(t-2)} + {1 \over 2} e^{2(t-2)}$$.

A: $$ y(t) = L^{-1} [ F(s) e^{-s} - F(s) e^{-2s}] = (t-1)u(t-1) - f(t-2)u(t-2)$$
$u(t-t_0)$ is the unit step function. It has the value $0$ for all values of $t<t_0$ and has the value $1$ for all values of $t>t_0$. Using this definition you can see that for $0<t<1$ all unit step functions vanish. Resulting in $y(t)=0$.
For $1<t<2$ only $f(t-1)$ will appear. For $t>2$ $f(t-1)-f(t-2)$ is the result.


text:
Q: VBA Copy SQL Table without Header I'm try to copy data from SQl-Server to Excel, but the result is include with headers. I want result without headers. Here my code :
    ConnectionString = "Provider=SQLOLEDB;SERVER=DWSQL\User;Database=User;Uid=User;Pwd=User;"
If Sheets("Menu").Cells(4, 4) = "SC" Then
    SQL = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '2' and process = 'ASSEMBLY' and status = 'NEW'"
ElseIf Sheets("Menu").Cells(4, 4) = "MC" Then
    SQL = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '3' and process = 'ASSEMBLY' and status = 'NEW'" 'and startby is Null"
ElseIf Sheets("Menu").Cells(4, 4) = "EV" Then
    SQL = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '5' and process = 'ASSEMBLY' and status = 'NEW' and pos_no like 'EN5%'"
End If

Connection.Open ConnectionString
rs.Open SQL, Connection, adOpenStatic, adLockReadOnly

Set QT = ActiveSheet.QueryTables.Add(rs, Sheets("Data").Cells(1, 2))
QT.Refresh:    rs.Close:    QT.Delete:    Connection.Close

Thanks.

A: Use CopyFromRecordset!
    ConnectionString = "Provider=SQLOLEDB;SERVER=DWSQL\User;Database=User;Uid=User;Pwd=User;"
If Sheets("Menu").Cells(4, 4) = "SC" Then
    Sql = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '2' and process = 'ASSEMBLY' and status = 'NEW'"
ElseIf Sheets("Menu").Cells(4, 4) = "MC" Then
    Sql = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '3' and process = 'ASSEMBLY' and status = 'NEW'" 'and startby is Null"
ElseIf Sheets("Menu").Cells(4, 4) = "EV" Then
    Sql = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '5' and process = 'ASSEMBLY' and status = 'NEW' and pos_no like 'EN5%'"
End If

Connection.Open ConnectionString
rs.Open Sql, Connection, adOpenStatic, adLockReadOnly

Range("b2").CopyFromRecordset rs
    rs.Close:    QT.Delete:    Connection.Close


text:
Q: What's the problem with this mysql query in php? I have a problem but i don't know where is a mistake?
private function getUsersPasswordByEmail($email){

        $stmt = $this->con->prepare("SELECT 'password' FROM 'user' WHERE 'email' = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->bind_result($password);
        $stmt->fetch();
        return $password;}

error is in this line -
$stmt->bind_param("s", $email);

Details
Type: Error
Message: Call to a member function bind_param() on bool
File: C:\xampp\htdocs\MyApi\includes\DbOperations.php
Line: 63

A: Try using ` backtick instead of ' single quote
$stmt = $this->con->prepare("SELECT `password` FROM `user` WHERE `email` = ?");
$stmt->bind_param("s", $email);


text:
Q: Convert UML to PHP code and vice versa I use to work using the visual studio IDE where you can use a UML editor to create a class diagram which  can be converted to code (and vice versa) and need to have that ability when working in open source PHP projects.  My question is  there any way to convert UML class diagram into PHP code and vice versa .

A: Have a look at Visual Paradigm for NetBeans IDE -
https://netbeans.org/features/uml/
It is a plugin that you can add to the NetBeans IDE. It has "Code generation features for Java, C++, PHP and more".


text:
Q: How to serve next js app using keystonejs? I have a problem with serving next js app using keystonejs. I want to achive something similar like in to do nuxt example which you can choose while creating keystone project. I used code from this link https://www.keystonejs.com/keystonejs/app-next/ in index.js file, but I get an error while trying to run the app:
ReferenceError: distDir is not defined at Object.
What should I do?

A: this is what I have in my setup
create app folder (next js code)
create next.config.js in app folder
my next.js.config file has following code
const distDir = 'dist';
module.exports = {
  distDir: `../${distDir}/www`,
  env: {
    SERVER_URL: process.env.SERVER_URL || 'http://localhost:4000',
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    // staticFolder: '/static',
  },
};

it export the build artifacts in dist/www in root of keystone project.


text:
Q: Why innerText,innerHTML property doesnt work on input tags in javascript? So i stumbled upon following code
<!DOCTYPE html>

Name: <input type="text" id="myText" value="Mickey">

Click the button to change the value of the text field.

<button onclick="myFunction()">Try it</button>

And not having used .value before in javascripte i thought to substitute it by innerText property but it just simply doesnt work !
I am having an idea that maybe as <input/> is a self closing tag that's why innerText isnt able to insert in between it ? As such to insert in between an element there atleast should be 2 tags
SO can anyone consolidate this ? Or if not then why .innerText isnt working here instead of .value

A: Because inner refers to the content that is "in between" the opening and closing tags of an element. For example:

This is the "innerText" or "textContent"

The <input> element doesn't have a closing tag, so it can never contain any "inner" content. For these elements, use the .value property to access their content.
There are other elements that do not have a closing tag, but in the following cases, the elements don't have innerText or .value because they are not designed to store any data, only to have a semantic or structural effect on the HTML:

*

*<area>

*<base>

*

*<col>

*<colgroup> when the span is present

*<command>

*<embed>

*

*

*<input>

*<keygen>

*<link>

*<meta>

*<param>

*<source>

*<track>

*<wbr>


text:
Q: Changing background color of a ContentPane I'm working on a GUI and I'm not having some trouble with panes.
My GUI is divided into two parts (topPane and bottomPane).
I have buttons and labels on both panes, but one of the button functions I wanted to change the background color, but it's not doing the job.
What I did is that I used a Container (called thisContentPane) to change the background color of my entire GUI.
Here is my current code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class TempConverter extends JFrame
{
    //Creating a contentPane down inside the inner class
    Container thisContentPane;
    //class scope variables : DO NOT CREATE THIS OBJECTS HERE.
    JButton calculateButton, clearButton;
    JTextField celsiusField, fahrenheitField, kelvinField;

    //menu
    JMenuBar menuBar = new JMenuBar();
    JMenu backgroundColor = new JMenu("Background Color");
    JMenu help = new JMenu("Help");

    JMenuItem lightGray, white, black, blue, howToUse, about;

    //constructor
    TempConverter()
    {
        super("Temperature Converter App");

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new BorderLayout());
        this.setSize(400,200);;
        this.setLocationRelativeTo(null);

        //menuBar
        this.setJMenuBar(menuBar);

        menuBar.add(backgroundColor);

        //adding JMenu to JMenuBar
        menuBar.add(backgroundColor);
        menuBar.add(help);

        //adding JMenuItems
        lightGray = backgroundColor.add("LIGHTGRAY");
        white = backgroundColor.add("WHITE");
        black = backgroundColor.add("BLACK");
        blue = backgroundColor.add("BLUE");

        howToUse = help.add("How To Use");
        about = help.add("Help");

        //babysitter
        MaryPoppins babysitter = new MaryPoppins();

        //adding action listener to the menu item
        lightGray.addActionListener(babysitter);
        white.addActionListener(babysitter);
        black.addActionListener(babysitter);
        blue.addActionListener(babysitter);
        howToUse.addActionListener(babysitter);
        about.addActionListener(babysitter);

        //building JPanels
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(3,2,0,20));

        //add this to JFrame in centerzone
        this.add(topPanel, BorderLayout.CENTER);

        //bottom panel
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new FlowLayout());

        //add this to JFrame in bottom
        this.add(bottomPanel, BorderLayout.SOUTH);

        //add components to the panels
        //add the buttons
        calculateButton = new JButton("Calculate");
        clearButton = new JButton("Clear");

        //add buttons
        bottomPanel.add(calculateButton);
        bottomPanel.add(clearButton);

        //register listeners
        calculateButton.addActionListener(babysitter);
        clearButton.addActionListener(babysitter);

        //add components to the top panel
        JLabel labelOne = new JLabel("Celsius:");
        JLabel secondOne = new JLabel("Fahrenheit:");
        JLabel thirdOne = new JLabel("Kelvin:");

        celsiusField = new JTextField("");
        fahrenheitField = new JTextField("");
        kelvinField = new JTextField("");

        //add the label and text fields
        topPanel.add(labelOne);
        topPanel.add(celsiusField);
        topPanel.add(secondOne);
        topPanel.add(fahrenheitField);
        topPanel.add(thirdOne);
        topPanel.add(kelvinField);

        this.setVisible(true);

    } // end constructor

    public static void main (String[] args) {
        new TempConverter();
    }

    private class MaryPoppins implements ActionListener
    {

        //implement  the abstract method from the interface
        public void actionPerformed(ActionEvent ev)
        {
            thisContentPane = getContentPane();

            if(ev.getActionCommand().equals("LIGHTGRAY"))
            {
                thisContentPane.setBackground(Color.lightGray);
            }
            else if (ev.getActionCommand().equals("BLUE"))
            {
                thisContentPane.setBackground(Color.BLUE);
            }
            else if(ev.getActionCommand().equals("WHITE") )
            {
                thisContentPane.setBackground(Color.WHITE);
            }
            else if (ev.getActionCommand().equals("BLACK"))
            {
                thisContentPane.setBackground(Color.BLACK);
            }else if (ev.getActionCommand().equals("Clear"))
            {
                thisContentPane.setBackground(Color.BLACK);
            }
            else if (ev.getActionCommand().equals("BLACK"))
            {
                thisContentPane.setBackground(Color.BLACK);
            }

        }//end ActionPerformed()

    }//end inner class

} // end class

When I click the buttons or menu items it doesn't do anything.

A: Your problem is that your contentPanel's background color is not "visible": your topPanel and your bottomPanel are on top of it :)
You should either do:
if (ev.getActionCommand().equals("LIGHTGRAY")) {
    thisTopPanel.setBackground(Color.lightGray);
    thisBottemPanel.setBackground(Color.lightGray);
}

... and do it for each of your if conditions (you know what I mean).
But that's not really the best way to go. An alternative that, in my opinion, makes perfect sense 'cause it reflects the exact behaviour you're looking for, would be:
topPanel.setOpaque(false);
bottomPanel.setOpaque(false);

I would obviously recommend the second option ;)

Also, since I'm at it, I prefer to use Color.LIGHTGRAY (and Color.BLACK, Color.WHITE, etc.) instead of Color.lightGrey, because these aliases respect the convention that states that constants must be upper-case.


text:
Q: Angular 7 : Multiple fields , same form control name I have the following form that lists questions and have an answer field. the questions listed by a loop from api and all of them need to have the same field name. Everything works fine, the problem is I can't submit all the form values except the last one. Is there any way to use a form control name for multiple fields.
move-maker-add-component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { ApiService } from 'src/app/shared/services/api.service';
import { AuthService } from "src/app/shared/services/auth.service";
import { Router } from '@angular/router';
@Component({
  selector: 'app-move-makers-add',
  templateUrl: './move-makers-add.component.html',
  styleUrls: ['./move-makers-add.component.scss']
})
export class MoveMakersAddComponent implements OnInit {
moveMakerForm: FormGroup;
moveMakerId:any;
moveMakers:any='';
answer:any;
id:string='';

  constructor(public authService: AuthService,private router: Router, private api: ApiService, private formBuilder: FormBuilder) { }

  ngOnInit() {
  this.getMoveMaker();
  this.moveMakerForm = this.formBuilder.group({
    'moveMakerId' : [null, Validators.required],

    'answer' : [null, Validators.required],

  });
}

getMoveMaker() {
  this.api.getMoveMakers().subscribe(data => {

this.moveMakers = data;

  });
}
onFormSubmit(form:NgForm) {

  this.api.addMoveMaker(form)
    .subscribe(res => {
        this.router.navigate(['/dashboard']);
      }, (err) => {
        console.log(err);
       });
}
}

move-maker-add.component.html
<app-header></app-header>

  <app-nav></app-nav>

{{ 'MOVE_MAKERS' | translate }}

                  <form class="forms-sample" [formGroup]="moveMakerForm" (ngSubmit)="onFormSubmit(moveMakerForm.value)">

                      {{moveMaker.question}}
                      <input type="text" class="form-control" formControlName="moveMakerId" id="exampleInputName1" value="{{moveMaker.id}}" >

                      <textarea class="form-control" id="exampleTextarea1" formControlName="answer" rows="4"></textarea>

                   <button class="btn btn-light">{{ 'CANCEL' | translate }}</button>
                    <button type="submit" class="btn btn-gradient-primary mr-2">{{ 'SAVE' | translate }}</button>

                  </form>

  <app-footer></app-footer>

MoveMaker.ts
export class UserMoveMaker {

    answer : any;
    moveMakerId : any;
  }

A: I usually add the formControlName dynamically with different values and then add the validators in the .ts file if needed.
In this case It would look like this:
move-maker-add.component.html
  <input type="text" class="form-control" [formControlName]="moveMaker.id" id="exampleInputName1" value="{{moveMaker.id}}" >

move-maker-add-component.ts
getMoveMaker() {
  this.api.getMoveMakers().subscribe(data => {
      this.moveMakers = data;
      this.moveMakers.forEach((moveMaker ) => this.moveMakerForm .addControl(moveMaker.id, new FormControl('', Validators.required)));
  });
}

A: The implementation made is the mixture of Reactive form and Template Driven.
Would be better if you could follow any one approach.
With respect to reactive form approach, this can be achieved using FormArray.
Example - https://stackblitz.com/edit/angular-material-editable-table-fazhbc?file=src%2Fapp%2Fapp.component.html
With respect to template driven forms, replace your (ngSubmit)="onFormSubmit(moveMakers)"


text:
Q: How to pass array between a master and detail component in Angular2 without directive? I would use How to do inter communication between a master and detail component in Angular2? to solve this problem but it's not allowed now to use directive. How to pass my array from first component to another?
import { Component} from '@angular/core';
import { Router } from '@angular/router';

import { MdDialog, MdDialogRef } from '@angular/material';

@Component({
  selector: 'app-flashcards',
  templateUrl: './flashcards.component.html',
  styleUrls: ['./flashcards.component.scss'],

})
export class FlashcardsComponent {
  dialogRef: MdDialogRef<MnemoDialog>;

  constructor (private router: Router,public dialog: MdDialog) {} //router in function

  mnemo = ['assets/images/family.png', 'assets/images/blood-m.png','assets/images/obrazek.jpg','assets/images/asdfas.jpg'];
  n = 0;

  myMnemo = this.mnemo[this.n];

  nextImg() {

      this.myMnemo = this.mnemo[this.n];
      n++;

    }
  }

}

@Component({
  selector: 'mnemo-dialog',
  template: `<img fxFlex="70%"  md-card-image src="{{ myMnemo }}">`
})
export class MnemoDialog {

}

A: @Component({
  selector: 'mnemo-dialog',
  template: `<img fxFlex="70%"  md-card-image src="{{ source }}">`
})
export class MnemoDialog {
    @Input()source: YOURDATATYPE;
}

And in your flashcards.component.html something like this:
 <mnemo-dialog [source]="myMnemo"></mnemo-dialog>

Or is this not allowed?


text:
Q: SonarQube 6.7.2 doesn't start because of PLSQL We upgraded from SonarQube 5.6 to 6.7.2 and also manually upgraded the plugins, including SonarPLSQL from 2.8 to 3.2.0
We are using the community version but have a valid (paid) licence for the plugin. When trying to start we get the error:
org.sonar.updatecenter.common.exception.PluginNotFoundException: The plugin 'license' required by 'plsql' is missing.

When removing the plugin from the plugins-folder SonarQube starts without problems.
Can you please help us?

A: The way licenses work have changed in the latest LTS. This is why you've got this error.
As you have a valid license of the PLSQL plugin, this means that you are a SonarSource customer so you should get in touch the SonarSource Sales representative you are in contact with to sort this out.


text:
Q: file.copy multiple files c# I'm looking to see if there is a more efficient way of copying certain files from a folder to another folder.  There are a lot of files so i'm wondering if there's an easier way.  Thank you.
Example:
file1.jpg
file1.bmp
file1.gif
file2.jpg
file2.bmp
file2.bmp
if (chkbox1.Checked)
{
   File.Copy(sourcedir + "\\file1.jpg", targetdir + "\\file1.jpg", true);
   File.Copy(sourcedir + "\\file1.bmp", targetdir + "\\file1.bmp", true);
   File.Copy(sourcedir + "\\file1.gif", targetdir + "\\file1.gif", true);
}

if (chkbox2.Checked)
{
   File.Copy(sourcedir + "\\file2.jpg", targetdir + "\\file2.jpg", true);
   File.Copy(sourcedir + "\\file2.bmp", targetdir + "\\file2.bmp", true);
   File.Copy(sourcedir + "\\file2.gif", targetdir + "\\file2.gif", true);
}

A: Here's a quick and dirty way of refactoring your code to reduce the repetition. It's not more efficient, but it will be easier to maintain:
    var file1Files = new List<string> { "file1.jpg", "file1.bmp", "file1.gif", };
    var file2Files = new List<string> { "file2.jpg", "file2.bmp", "file2.gif", };

    var files2copy = chkbox1.Checked ? file1Files : file2Files;

    foreach (var file in files2copy)
    {
        File.Copy(Path.Combine(sourcedir, file), Path.Combine(targetdir, file), true);
    }

Unlike most of my answers, I haven't tested this code.  But I'm very confident that it's correct, or very close.
This is basically @John's comment, fleshed out with some code.


text:
Q: Expected Value for Arrows game
In a game Daniel shoot arrows on a circular target with a radius of $R$.
Daniel's arrows hit the target uniformly distributed over the target.
Daniel shoots one arrow on a circular target with radius R, that is
split into $10$ circles each with similar size $((R^2\pi)/10)$ such
that the innermost circle gives $10$ points, the second innermost gives $9$ and so on till the outermost gives $1$ point. What's the expected value for the points he got?

Let D be a random variable that measures the distance from the center.
Previously I found with your help that $E(D)=(2R)/3$ from there I think I should find the circle within that radius and multiply with points. But I'm not sure how to do this formally or find that circle.

A: It is given that the arrow lands on the target uniformly. This means the probability of landing on a circle is proportional to the area of the circle. In this case we have $10$ circles of equal area, so the probability  that the arrow lands on any circle is $1/10$. The expected value of the points is$$\frac1{10}[1+2+\cdot\cdot\cdot+10]=\frac{11}2.$$


text:
Q: Trying to implement Linkedin Oauth2.0 full authentication flow I'm trying to implement the Linkedin OAuth2.0 sign in and authentication flow and I can't seem to find any resources that show step by step exactly what needs to happen.
My project is built in next.js and hosted using Zeit's now serverless deployment. So my project is essentially a bunch of lambdas both for the front end and back end.
So far I have the following flow working correctly:
1) user navigates to /login page and clicks on Sign in with Linkedin button
2) The button routes the client to the Linkedin Authentication URL where they see will see the Linkedin sign in prompt
3) User signs in and Linkedin redirects to my server callback url lambda
4) server callback lambda retrieves authorization code from the query string
5) server sends a POST to Linkedin's accessToken endpoint to retrieve the access_token
6) server receives the response and extracts the access_token.
Right now it then does a 301 redirect to redirect the user to another page.
Would should I be doing with the access_token? I understand that I need the token to access Linkedin's APIs to retrieve the user profile and any other API services. But my question is how should I store the access_token. I tried setting it in the response header as a cookie but it never shows in the session cookies. Should I be using JWT Cookies?
Here is the code for my auth callback lambda which sits at /auth/linkedin/callback
// api/login.js

const { json, send, createError, run } = require('micro');
const fetch = require('isomorphic-unfetch');
const querystring = require('querystring');
const nodeCookie = require('node-cookie');
const url = require('url');

const callback = async (req, res) => {

  let { query } = url.parse(req.url)
  let { code, state } = querystring.parse(query)

  // const redirectUri = req.redirectUri;
  let tokenUrl = `https://www.linkedin.com/oauth/v2/accessToken` + '?' +
    querystring.stringify({
      grant_type: 'authorization_code',
      code: code,
      redirect_uri: 'https://memory-app.sfkiwi.now.sh/auth/linkedin/callback',
      client_id: 'XXXXXXXXXXX',
      client_secret: 'XXXXXXXXXXXXX'
    });

  try {
    const response = await fetch(
      tokenUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'x-www-form-urlencoded'
        }
      });

    if (response.ok) {

      let { access_token, expires_in } = await response.json();

      nodeCookie.create(res, 'liauth', String(access_token));

      res.setHeader('Location', '/profile');
      send(res, 301);

    } else {
      send(res, 500, response.status);
    }

  } catch(err) {
    send(res, 500, 'Failed to retrieve access token from Auth server');
  }
};

module.exports = (req, res) => run(req, res, callback);

Front end code for login page
async handleClick(event) {
    event.preventDefault();

    let qs = querystring.stringify({
      response_type: 'code',
      client_id: 'XXXXXXXXXXXX',
      redirect_uri: this.props.apiUrl + '/auth/linkedin/callback',
      state: 'DCEeFWf45A53sdfKef424',
      scope: 'r_liteprofile r_emailaddress w_member_social'
    });

    let url = 'https://www.linkedin.com/oauth/v2/authorization' + '?' + qs

    Router.push(url);
  }

  render() {
    return (
      <Layout>
        <div className="login">
          <button onClick={this.handleClick}>Login with Linkedin</button>
        </div>
      </Layout>
    );
  }
}

export default Login

A:
Would should I be doing with the access_token?

The access token must be saved in your database or server and link it to that user, so any future access to this user's linkedin data or profile will be using this access token

But my question is how should I store the access_token

I believe you already have somesort of a database, and in it you store information about your users, so this token should be saved with the user information


text:
Q: Scrape img src with try/except in beautifulsoup images = []
    try:
        images = [img["src"] for img in soup.select(".img-lazy")]
    except:
        images = [img["src"] for img in soup.select(".img-thumb")]
    else:
        images = [img["src"] for img in soup.select(".author-bio")]

I try to scrape image src from different pages. If works fine only with try and except, but some pages have image in different class name so I add another except condition. It shows error then I add else condition. But now it only scrapes else condition data. I want that first it look for .img-lazy then for .img-thumb and in last for .author-bio class.

A: First of all: You should (almost) never use bare except clauses like that. Details about this are all over this platform.
In this case, you are shooting yourself in the foot, because you can't know what exception exactly is raised when that except is triggered.
Also, with this logic, whenever the code inside the try block executes without a problem (thus assigning the images variable), the except block is skipped and then the else block is executed. This results in the images variable being re-assigned (i.e. overwritten) in that block.
This is the logic behind try-except-else constructs. (You should read up on that.)
If I understand your requirements and the documentation for select correctly, you can just do this instead of that whole try-except mess:
images = [img["src"] for img in soup.select(".img-lazy,.img-thumb,.author-bio")]

That select call should return you all elements that match any of those class selectors.
However, I would be careful here, unless you know for certain that every HTML element with any of those classes is in fact an <img> (or more specifically, has a src attribute). Because if any of them does not have src attribute, that code will raise a KeyError at this point: img["src"]
I would suggest being as precise as possible with the selector:
images = [
    img["src"]
    for img in soup.select(
        "img[src].img-lazy,img[src].img-thumb,img[src].author-bio"
    )
]

For example, this img[src].img-lazy will only grab <img> tags that have a src attribute and the class img-lazy.


text:
Q: matplotlib vertical space in the background I've plated a bar graph where I set a default horizontal span:
plt.axhspan(0,2, color='yellow', alpha=0.25)

However it looks like that yellow area covers my original bars. How can I make a horizontal span to be in a background?

A: You can use zorder when plotting your graph.
For example with a scatter plot;
plt.axhspan(0, 2, color='yellow', alpha=0.25)
plt.scatter(X, Y, zorder=10)

This ensures your graph is on top of the axhspan.
zorder can be defined for many plt functions, just check the api, this is useful if you have many overlaying subplots for example.

A: Use zorder and set zorder of the histogram higher than zorder of the hspan:
plt.hist(x, 50, normed=1, zorder=1)
plt.axhspan(0, 0.01, facecolor='yellow', zorder=0)


text:
Q: Query Parameter vs URI path in POST Request Python Flask Service Is there a way to do something of this sort in Python Flask?
I want my URI to be in the following way:
POST /myModel/{location}/getValue
{ //Has some Data
}

Is it possible to define a API like this and determine the location or should I pass it as a query parameter?

A: Yes, it is. Look at examples for @route decorator

A: You can pass default params in your URL
@app.route('/users/', defaults={'page': 1})
@app.route('/users/page/<int:page>')
def show_users(page):
    pass

From the docs. So in your case the page route could be a flexible parameter.

A: You can define methods for your routes and handle data in Flask like so:
@app.route('/myModel/<location>/getValue', methods = ['POST'])
def my_route(location):
    request_location = location  # will contain location
    request_data = request.form  # will contain data from request
    # rest of the code goes here


text:
Q: Using canvas publisher action and intercepting the record Id of the post We have a need to do the following
a) allow the user to post using our canvas app. The post is a simple TextPost, though it could be a CanvasPost
b) After the user clicks share, get the feedItem record Id of the just posted item and do some stuff with that record.
To put it mildly I'm a n00b here, and it confuses me that there appears to be no easy way to do this?
Clarification: The canvas app is called from a publisher action

A: I don't think this is possible - I was going to say listen for the success event
{name : 'publisher.success', onData : handlers.onSuccess}
However, looking at the code we don't send anything back in the payload. (Would need to enhance the code)
One workaround is to hide the header and footer (these are options when defining the connected app).  You would then have to implement the Share functionality yourself. Not ideal, also may be tricky getting the feed to refresh after you post your message.


text:
Q: How can I understand MaterialUI styled component? I'm trying to make sense of how to inject styles into component with MaterialUI and I'm very confused! Can anyone please explain what I did wrong? i read the documentation but it honestly didn't make sense to me. What are classes? And how do I attach the const style into the component BeerList?
My code threw an error "Cannot read property of classes undefined. I know I must have pulled from the wrong props. But I don't know how to fix it...
 import React from 'react';
import BeerListItem from './BeerListItem';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import GridList from '@material-ui/core/GridList';
import GridListTile from '@material-ui/core/GridListTile';
import GridListTileBar from '@material-ui/core/GridListTileBar';
import IconButton from '@material-ui/core/IconButton';
import StarBorderIcon from '@material-ui/icons/StarBorder';

const styles = theme => ({
    root: {
      display: 'flex',
      flexWrap: 'wrap',
      justifyContent: 'space-around',
     overflow: 'hidden',
     backgroundColor: theme.palette.background.paper,
    },
    gridList: {
      width: '100%',
      height: '100%',
      transform: 'translateZ(0)',
    },
    titleBar: {
      background:
        'linear-gradient(to bottom, rgba(0,0,0,0.7) 0%, ' +
        'rgba(0,0,0,0.3) 70%, rgba(0,0,0,0) 100%)'
      },

    icon: {
      color: 'white',
    },
  });

const BeerList = ({beers}) =>{
const {classes} = beers;
    const beerItems = beers.map((beer) => {
        return <BeerListItem  key={beer.id} beer = {beer}/>
      });
      return (

       <GridList cellHeight={250} spacing={1} >
      {beerItems}
      </GridList>

);
    };

export default withStyles(styles)(BeerList);

A: classes distructured from props.
you need a little change on your components like:
const BeerList = (props) =>{
const {classes, beers} = props;

  // rest of your code
  return

    <GridList cellHeight={250} spacing={1} >
      {beerItems}
    </GridList>

};

That's it.


text:
Q: How can I profile the performance effects of pointer aliasing? My code uses a lot of repetitive and largely algebraic operations that are suitable for MATLAB/FORTRAN style vector operations.
I have been considering making a switch to std::valarray or even Blitz++ to take advantage of this. But before making the switch, how can I profile the degree to which one of the main contributors to the performance gap between C++ and FORTRAN - pointer aliasing - is effecting the performance of my code, short of declaring everything with restrict and testing the difference.
Does Visual Studio 2012 / 2013 provide some way of achieving this? Maybe a different IDE?

A: C/C++ language is not optimised and will not behave very well doing things math things. For those operation i solely recommend trying to change language or, if you really want staying with c/c++, writing with extreme caution. Different languages are designated to do what they do in best possible way, but its almost never this same thing.
For what i know there is no way of better optimisation most of already existing functions in C/C++, especially non standard packages(boost) because they are suppose to be as simple as possible. Debug packages are also overloaded with debug functions so they are slower, but i also saw some release functions that have security checks like "is object belong to me" or "subscribent out of range check". If this is about atomic functions like aliasing, autopoiters, other pointers types or stuff like that, they just cant be better, and they are made to work as best as its possible.
you can also try telling compiler that you want more compression level, this may speed something if possible, but as i said before, use language that is made for math to do math. Eventually if you can make asm object from fortran or other languages, you can link this file to your code in c/c++.


text:
Q: How to test serial / Hyperterminal integration with C#? I have to develop software for a USB scale that, when you press a button on it, sends serial communications over USB. I can see the values in HyperTerminal.
I am going to use the .NET classes for Serial communication to trap the data.
The problem is, I don't have the scale. The scale is connected to a remote computer I can RDP into. When I want to test, I can ask the client to press the button on the scale.
I can't ask the client to press the button 100 times a day, I need to have a way to develop with a reasonably good idea of what the scale will report, and only test when I think I have a solution.
I'm looking for something locally, that can mimic the scale and send to my .NET Serial classes, the same output as the scale. Ideally, if I could record the scale's data, and then play it back on another machine, it would be perfect.
How would I do this?

A: 1) Abstract away your communications code.  In test mode, feed your logic function from a data file stream rather than the serial stream.
or
2) If you have 2 serial ports (or two pcs), then setup a scale emulator app that talks out thru one port, and plug that into the other port where your software is running.

A: If you take the serial port emulation route, take a look at com0com. I use it all the time to fake communications with laboratory instruments and it works nicely. Very useful when you laptop lacks serial ports.

A: You have two problems:

*

*Test your .NET Serial classes to verify they can handle receiving data (any data) through a serial port

*Test your application to verify it can handle the specific type of data which you get from the scale

You can test 1. by attaching anything which can generate data (e.g. another PC with Hyperterminal) to your PC's local serial port.
You can test 2. by (for testing purposes) replacing your serial classes with software which acts as a "mock object" for the 'serial classes + scale' combination (i.e. which feeds into your program, using the API which your serial classes would use, the data which you expect to receive from the scale).
You can also test 1 and 2, by:

*

*Writing a program, which pretends to be the scale by sending the type of data which the scale would send

*Running this program to send data out of a serial port

*Using a null modem to connct your two serial ports back-to-back (so that the data sent out of one port is received by another into your software).


text:
Q: Can you help me with finding x values where series is convergent and not convergent
Given series:$$\sum_{n=1}^\infty (-1)^n\frac{x^n}{x^n+1}$$ for $x>0$

So what I want is the interval of $x$ where given series is convergent and the interval of $x$ where series given is not convergent.
I tried ratio test and the root test. But I could not manage to get through it.
Any explanation is highly appreciated. Thank you very much.

A: For $x \ge 1$ we have: $|(-1)^n\frac{x^n}{x^n+1}| \ge 1/2$, hence  $((-1)^n\frac{x^n}{x^n+1})$ does not converge to $0$.
Conclusion ?
For $0<x<1$ we have $|(-1)^n\frac{x^n}{x^n+1}| \le x^n$.
Conclusion ?

A: Fix $x > 0$, and let
$$a_n = (-1)^n\frac{x^n}{x^n+1}$$
A necessary condition for convergence of the given series is that
$$\lim_{n \to \infty} a_n = 0$$
If $x > 1$,
$$\lim_{n \to \infty} |a_n| = \lim_{n \to \infty} \frac{x^n}{x^n+1} = \lim_{n \to \infty} 1-\frac{1}{x^n+1} = 1 - 0 = 1$$
so the series diverges.

If $x = 1$, then $\displaystyle{|a_n|= \frac{1^n}{1^n + 1} =\frac{1}{2}}$ (for all $n$), so the series diverges.

For $0 < x < 1$,

*

*The terms alternate in sign.

*$\displaystyle{\lim_{n \to \infty} |a_n|= \lim_{n \to \infty}\frac{x^n}{x^n+1} = \frac{0}{0+1} = 0}$, so $\displaystyle{\lim_{n \to\infty}a_n =0}$.

*$\displaystyle{|a_{n}| - |a_{n+1}| = \frac{x^n}{x^n+1} - \frac{x^{n+1}}{x^{n+1}+1} = \frac{x^n - x^{n+1}}{(x^n+1)(x^{n+1}+1)}} > 0$

hence, by the alternating series test, the series converges.

A: Let $a_n = \displaystyle \frac{x^n}{x^n+1} = \displaystyle \frac{1}{1+\frac{1}{x^n}}$, then it is clear that $a_n$ is clearly monotonically decreasing.

*

*If $|x| < 1$, then $\frac{1}{x^n} \rightarrow \infty$, leaving $a_n \rightarrow 0$, as required and so we satisfy the alternating series test. And have convergence there.

*It is clear that if $|x|> 1$, then that definitely isn't the case as $\frac{1}{x^n} \rightarrow 0$, leaving $a_n \rightarrow 1$ as $n$ gets large. The alternating series test doesn't show divergence, but what does show divergence is that $(-1)^n a_n$ does not tend to 0! So we cannot have convergence here.

So we have convergence $|x| < 1$ and divergence $|x|>1$. What about at $x=1$? Well you have to test that separately. I'll leave you to deal with that case.


text:
Q: Moving the Caret with OS X Text Substitution You can set up text substitutions in OS X in the Languages and Text tab of System Preferences.
Is there a way to choose where the caret will appear after a text substitution takes place?
For example, when I type thx I want it to expand to Thank you |. where the | character represents where I would like the caret to be after the text has been substituted.
Right now when I set the shortcut thx to expand to Thank you ., and I type thx, it gets replaced with Thank you . |

A: I don't think it's possible. You might add a snippet like this in TextExpander though:
Thank you %|.

Or use DefaultKeyBinding.dict:
{
    "\UF704" = { // F1
        "t" = {
            "h" = {
                "x" = (insertText:, "Thank you .", moveBackward:);
            };
        };
    };
}


text:
Q: How to write OnClick="return Foo()" in jquery How do I write OnClick="return Foo()" in jquery to prevent the button from submitting while the function is not yet finished. TY

A: Attach a handler to the click event for your target element, pass your handler the event object as a parameter, and call preventDefault() on the event within your handler. Like so:
$('#mydiv').click(function(e) {
  // do something
  e.preventDefault();
});

For more information see click and the event object at the jQuery API.

A: It will not submit until function has finished executing anyway. If you want to prevent the button from submitting just return false from Foo().

A: Check out the jQuery docs for click. Something like this perhaps?
$('#buttonid').click(function(evt) {
    evt.preventDefault();
    Foo();
});

Keep in mind that the click event is triggered for submit buttons/inputs even when selected through a keyboard event.
jQuery has excellent documentation. Take some time to read through it and you'll get where you want faster than guess work.


text:
Q: How can I share props (two-ways) between two components of the same type with Reactjs? I'm building a music app using React, and I'm a newbie :)
My goal is to

*

*load a JSON playlist (formatted as JSPF)

*display a Playlist based on this JSON

*fill a Player's queue with the playlist tracks.

So I'm working on several components : Track, Tracklist, Playlist, and Player.

*

*Tracklists have Tracks.

*Playlist and Player have a Tracklist (and other things) : the Player's queue is a Tracklist component.

*Player is not a descendant of Playlist, it is aside.  For instance, I want to be able to queue (or unqueue) some tracks of the Playlist into the Player.

What I want is to be able to share/sync the props of a (same) Track between the Playlist and the Player :
Let's say that I have a favorited prop for a Track.
I would toggle it by clicking a button nested in the Track component.
I need to update the props of both tracks either if I click the button within the Playlist, or within the Player; and vice verca : all props should be "synced".
Can I do this with React and how ?
Thanks a lot for your advices !

A: You should have a container component and other components (Track, Tracklist, Playlist, and Player) as children of container component, container component can pass props to children and refrence of functions as props, so can have all the logic.
You can check this exmaple:
https://github.com/upretim/thinking-in-react/
In this example all the components except App component are dumb/ functional component, App is smart/ stateful or container component, which has all the logic and data. In the example value of filter is shared between child components using parent component.


text:
Q: Find minimum cut in a graph such that given vertices are disconnected Some time ago I read about the general mininum cut algorithm that takes as input a graph and removes a min. number of edges such that two disconnected components remain.
I am now working on an undirected graph with 10k+ nodes and 500k+ edges (no multiple edges between two vertices). To attribute interactions between nodes I thought about computing the minimum cut disconnecting two given vertices (or flow-related measures).
Are there efficient algorithms to come up with a value (cardinality of the min. cut set) for every pair of vertices in the graph? Being rather new to the topic, I would be deeply grateful if anyone could provide links to papers or other resources outlining algorithms which operate at a reasonable run-time complexity.
Thanks!

A: There are several algorithms (see Wiki for an introduction) that find a maximum flow in a network. Those I know (Ford-Fulkerson, Dinic, Karp-Edmond) should perform well for unit capacity ( = integer capacity equal to 1 on all edges) (variable capacities increase complexity and more problems arise with non-integer capacities)
For any pair of of vertices, you create a network from the graph by setting source/sink to this pair. You get the maximum flow using one of the algorithms, which you use to get the cut as follows:

*

*Choose any edge used by the flow. This edge will belong to the cut.

*Repeat, but now do the flow search on a graph without selected edge(s) until the flow is 0

In the end, you have the minimum cut, size of the maximum flow.
If you really want to press on the performance, you might want to have a look at this paper: Flows in Undirected Unit Capacity Networks (1997)  by Andrew V. Goldberg, Satish Rao, but I'd probably stick with the simpler ones.


text:
Q: How to tetsing completely fill the coverage of my method with java and Junit? I have a Java service that consults a DB and returns a list, into my service I call the method validacionCampos() of my Util class, this class validates if a field of the list of my service  has a null value or is 0 the value is set 0.000
My goal is to have a test case that covers all the service method and validations of the util class.
I made a test clase but it doesn't work at all because the sonarqube tool says that it is not fully covered and points to the if lines of the util class, I made two methods, one setting the null value and another method for the value 0 , but I think it's wrong or does nothing
anyone can help me please, How is the testcase done so that it enters the service and the useful class and the coverage is fully?
ServiceImpl Class
@Override
public ResponseEntity<?> consultarReportes(Integer fechaInicio, Integer fechaFin) throws Exception {
    Map<String, Object> response = new HashMap<>();
    List<EntityDa> consultarReporte = new ArrayList<EntityDa>();
    try {
        consultarReporte = bitacoraRepository
                .consultarBitacoras(fechaInicio, fechaFin);
        reporteUtil.validacionCampos(consultarReporte);

    } catch (Exception e) {
        LOGGER.error("An error ocurred looking for Entity Data");
        response.put("success", false);
        response.put("error", e.getMessage());
        return new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    response.put("success", true);
    response.put("data", consultarReporte);
    return new ResponseEntity<>(response, HttpStatus.OK);
}

Util class
private static final String DECIMAL = "0.0000";

        public List<EntityDa> validacionCampos(List<EntityDa> lista) {
        for (EntityDa details : lista) {
            if (details.getRango() == null || details.getRango().equals("0")) {
                details.setRango(DECIMAL);
            }
            if (details.getPrima() == null || details.getPrima().equals("0")) {
                details.setPrima(DECIMAL);
            }
        }
        return lista;
        }

Test class
@Mock
BitacoraRepository bitacoraRepository;

@Test
void testExitoValidaNullos() throws Exception {
    EntityDa entity = new EntityDa();
    entity.setRango(null);
    entity.setPrima(null);

    List<EntityDa> list = new ArrayList<>();
    list.add(entity);
    when(bitacoraRepository.consultarBitacoras("20220112", "20220112")).thenReturn(list);
}

@Test
void testExitoValidaVacios() throws Exception {
    EntityDa entity = new EntityDa();
    entity.setRango("0");
    entity.setPrima("0");

    List<EntityDa> list = new ArrayList<>();
    list.add(entity);
    when(bitacoraRepository.consultarBitacoras("20220112", "20220112")).thenReturn(list);
}

UPDATE
I IMPLEMENTED IT AS YOUR EXAMPLE AND IT STAYED LIKE THIS BECAUSE THE IDE ADDED A CAST TO ResponseEntity<Map<String, Object>> because my service is declarated  ResponseEntity<?>
@Test
    public void testExitoValidaNullos() throws Exception {
        // Given a repository containing an entity with "rango" and "prima" set to null
        EntityDa entity = new EntityDa();
        entity.setRango(null);
        entity.setPrima(null);

        List<EntityDa> list = new ArrayList<>();
        list.add(entity);
        when(bitacoraRepository.consultarBitacoras("20220112", "20220112")).thenReturn(list);

        // When consultarReportes is called
        ResponseEntity<Map<String, Object>> response = (ResponseEntity<Map<String, Object>> serviceImpl.consultarReportes("20220112", "20220112");

        // Then the returned entity should have "rango" and "prima" set to "0.0000"
        EntityDa returnedEntity = ((List<EntityDa>) response.getBody().get("data")).get(0);
        assertEquals("0.0000", returnedEntity.getRango());
        assertEquals("0.0000", returnedEntity.getPrima());
    }

I ran the test and it sends this:
org.opentest4j.AssertionFailedError: expected: <0.0000> but was: <41831.3>
apparently it is not taking the settings to null
UPDATE
TESTING THE UTIL CLASS DIRECTLY I GET THE ERROR NullPointerException in the line claseUtil.validacionCampos(list);
    @AutoConfigureMockMvc
    @SpringBootTest
    public class ClaseTest {

    @Autowired
    ClaseUtil claseUtil;

    @Test
    public void prepare() throws Exception {
        EntityDa entity = new EntityDa();
        entity.setRango(null);
        entity.setPrima(null);

        List<EntityDa> list = new ArrayList<EntityDa>();
        list.add(entity);

        claseUtil.validacionCampos(list);

    }
    }

A: SonarQube reports no coverage for those lines because these tests do not actually execute this code. They perform some setup, but do not call any methods on ServiceImpl.
It's useful to think of tests as having three sections, usually called given, when, and then:

*

*Given represents the context or environment of the test case

*When describes the action that is taken - the operation that is being tested

*Then describes the expected or intended outcome

It might be helpful to use written language to write out the requirements in this format, and then translate the written requirements to code.
For example, I might write the requirements for these test cases (in English):

*

*Given a repository containing an entity with a "rango" of null or "0",

*When consultarReportes is called,

*Then the returned entity should have "rango" set to "0.0000"

And:

*

*Given a repository containing an entity with a "prima" of null or "0",

*When consultarReportes is called,

*Then the returned entity should have "prima" set to "0.0000"

In terms of code:

*

*Given often translates to setting up data and sometimes mocks.

*When is a call to the method under test.

*Then is usually an assertion about the return value, or some other state affected by the method. It can also be verifications of methods called on mock objects, particularly when you are testing a method with no return value that only performs side effects.

In this case, the tests might look like this:
@Test
public void testExitoValidaNullos() throws Exception {
    // Given a repository containing an entity with "rango" and "prima" set to null
    EntityDa entity = new EntityDa();
    entity.setRango(null);
    entity.setPrima(null);

    List<EntityDa> list = new ArrayList<>();
    list.add(entity);
    BitacoraRepository bitacoraRepository = mock(BitacoraRepository.class);
    when(bitacoraRepository.consultarBitacoras("20220112", "20220112")).thenReturn(list);

    // When consultarReportes is called
    ServiceImpl serviceImpl = new ServiceImpl(bitacoraRepository);
    ResponseEntity<Map<String, Object>> response = serviceImpl.consultarReportes("20220112", "20220112");

    // Then the returned entity should have "rango" and "prima" set to "0.0000"
    EntityDa returnedEntity = ((List<EntityDa>) response.getBody().get("data")).get(0);
    assertEquals("0.0000", returnedEntity.getRango());
    assertEquals("0.0000", returnedEntity.getPrima());
}

The change to testExitoValidaVacios would be similar.
(I made a few other changes to the supplied code to allow it to compile.)
To fully cover all possibilities, you would also want to write test cases for when these fields are set to other values. You may also want to test the exception handler by stubbing bitacoraRepository.consultarBitacoras to throw an exception.
Note that it would probably be simpler to test these cases against the Util class directly. This would require much less setup (no need for mocks) and would not require unpacking the entity from the response.


text:
Q: Ubuntu - PySide module not found for python2 but works fine for python3 I had PyQt4 running fine with python2 on Ubuntu 12.04.  I then installed python-PySide.  But the installation test would give me a module not found error.  Then I installed python3-PySide and it works fine.  So obviously something to do with my environment paths, but I'm not sure what I need to do.  I'm guessing PySide is automatically checking if python3 exists and if it does then it'll use it regardless.  I need PySide to work with python2.7 because of Qt4.8 compatibility issues.  Any suggestions?
some info about my system:
which python

/usr/bin/local/python

which python3

/usr/bin/python3

EDIT:
More details about installation test.
After installation, I bring up the python console and try import PySide, as follows:
python

import PySide

ImportError: No module name PySide
But it works fine for python3:
python3

import PySide
PySide.version

'1.1.2'

A: You have two independent Python 2.7 installations, one in /usr and one in /usr/local. (And that's on top of the Python 3.x installation you also have.)
This is bound to cause confusion, especially for novices. And it has caused exactly the kind of consuion it was bound to cause.
You've installed PySide into the /usr installation, so it ended up in /usr/lib/python2.7/dist-packages. If you run /usr/bin/python, that import PySide will probably work fine. (If not, see below.)
But the default thing called python and python2.7 on your PATH is the /usr/local installation, hence which python says /usr/local/bin/python, so it can't see PySide at all. So you need to get it installed for the other Python as well.

Unless you know that you need a second Python 2.7 in /usr/local for some reason, the simplest thing to do would be to scrap it. Don't uninstall it and reinstall it; just uninstall it. You've already got a Python 2.7 in /usr, and you don't need two of them.

If you really need to get PySide working with the second 2.7…
Since you still haven't explained how you've been installing PySide despite being asked repeatedly, I can't tell you exactly how to do that. But generally, the key is to make sure to use explicit paths for all Python programs (python itself, python-config, pip, easy_install, etc.) that you have to run. For example, if the docs or blog or voices in your head tell you to run easy_install at some step, run /usr/local/bin/easy_install instead. If there is no such program, then you need to install that. The fact that you already have /usr/bin/easy_install doesn't help—in fact, it hurts.

If you can get rid of the second Python, but that doesn't fix PySide yet, uninstall, rebuild, and reinstall PySide. Or, even simpler… PySide has pre-made, working binary Ubuntu packages for all of the major Python versions that have Ubuntu packages. Just install it that way.


text:
Q: Function to calculate shift between to time series based on data points I am trying to find a function that matches two time series such that the datetime corresponds to reality.
So I need a function that minimizes the distance between the two curves shown above and outputs a new dataframe that has TAIR time-shifted towards the values of tre200h0.
From my bare eyes, it looks like this shift is about 22h.
ggplot
Best,
Fabio
I don't know a function that does this job for me.

A: Solved by Ric Villalba in the comments to OG Question.
Two R base functions to analyze time series lags are acf and pacf. i.e. given you have x and y you can use acf(y-x) and seek the zeroes in the plot (if your series have adequate seasonal behaviour), or, if you prefer, acf(y-x, plot=F) and get the data. Try which.min( acf(x-y)$acf^2 ).
Of course, it is a simplification of otherwise complex matter


text:
Q: Condition on two irrational numbers Consider two irrational numbers $a$ and $b$. Are there well known sufficent conditions on the relation between $a$ and $b$ that would allow me to conclude that there is $c \in \mathbb{R}$, $c \neq 0$, such that both $ca$ and $cb$ are rational?

A: If $a=qb$ for some $q\in\mathbb{Q}$ then the condition clearly holds. For the other implication, say there exists $0\neq c\in\mathbb{R}$ with $ca$ and $cb$ are rational. Then let $q=ca/cb$. Then $a=qb$.
Therefore there exists a $0\neq c\in\mathbb{R}$ with $ca$ and $cb$ rational iff $a=qb$ for some $q\in\mathbb{Q}$.


text:
Q: Recognizing and Replacing values matlab So I have a certain grayscale image as a binary file. After I red in the image, I tried to create a series of "if" loops in order to replace a range of values with one value, and leave the rest of the matrix untouched.
I used this code
if myimage < 20
    myimage = 0;
else if 20 < myimage <40
        myimage = 20;
    else if 40 < myimage < 60
            myimage = 40;
        else if 60<myimage<80
                myimage = 60;
            end
        end
    end
end

but for some reason it failed to load an image. After some debugging I figured out that the file was becoming a 1 x 1 matrix with the value "20" after the "else if 20...." line. Can anyone help me figure out why exactly this is happening? thanks.

A: You need to change the specific indices in myimage that have a specific value. The way your currently calling it, you're overwriting the myimage variable with a specific value. One way to find all the relevant indices is with find:
find(myimage==20)
in order to find and replace all the values with a one liner, reference the indices of interest in myimage:
myimage(find(myimage<20))=0;
and to combine multiple sets of indices (eg values >20 AND <40), use intersect:
myimage(intersect(find(myimage>20),find(myimage<40)))=20;


text:
Q: How to untar a file in hadoop hdfs I have a lot of JSON files (1 MM) in the local directory. ANd I need to move these JSON files as it is to HDFS.
Created a tar which contains all the JSON files.
tar -cvf filename.tar local_folder_name

Moved the .tar file to hdfs directory
hdfs dfs -put filename.tar hdfs://nameservice1/user/hive/warehouse/dbname.db/table_name/

I need to extract all the files from the tar in hdfs and keep them as separate JSON files in hdfs. The reason I went with the tar option is to move a single file to hdfs rather than one file at a time for each file in the 1 MM.( Which is extremely slow and not sure if it will complete)
I tried the below option and few other variants of this.
hdfs dfs -cat hdfs://nameservice1/user/hive/warehouse/dbname.db/table_name/filename.tar | tar -x | hdfs dfs -put - /user/hive/warehouse/dbname.db/table_name/untar_dest

I see a new file named untar_dest in the hdfs directory but this is of size 0 and has nothing in it.
-rwxrwx--x+  3 hive hive          0 2020-05-15 21:23 /user/hive/warehouse/dbname.db/ctable_name/untar_dest

Something is not correct and I am not able to find a way to solve this.
How can I extract the files from .tar in hdfs?

A: You can write simple java api, to untar using org.apache.hadoop.fs.FileUtil
https://hadoop.apache.org/docs/r2.4.1/api/org/apache/hadoop/fs/FileUtil.html
Few examples, you can find here
https://www.codota.com/code/java/methods/org.apache.hadoop.fs.FileUtil/unTar


text:
Q: Having trouble getting all the page numbers from a pdf file to output I'm having trouble getting all the page numbers from a pdf file.
this is my code!
I just get a one-page number that outputs I'm trying to get all the page numbers from my pdf file. How would I fix my code to get all the pdf page numbers? In total there are 20 pages.
enter image description here

A: My attempt looks something like this:
import PyPDF2
pdffileobj = open('test.pdf','rb')
pdfreader = PyPDF2.PdfFileReader(pdffileobj)
#extract the number of pages in the pdf and all text from the pdf

data = ''

#extract the text from the pdf
for i in range(pdfreader.numPages):
    pageobj = pdfreader.getPage(i)
    data += pageobj.extractText()

A: See https://pypdf2.readthedocs.io/en/latest/user/extract-text.html
from PyPDF2 import PdfReader

reader = PdfReader("example.pdf")
for page in reader.pages:
   print(page.extract_text())

print(f"pdf page count : {len(reader.pages)}")


text:
Q: Attribute return null in xmlpullparser I don't know why return null value in getAttributeValue(). I need to get some attributes from a XML file. Please help me.
case XmlPullParser.END_TAG:
  if (tagname.equalsIgnoreCase(KEY_MARKER)) {
    stackSites.add(curStackSite);
  } else if (tagname.equals(KEY_TITULO)) {
    String title = xpp.getAttributeValue(null, "provincia");
    if (title!=null){
      curStackSite.setTitulo(title);
    }else{
      curStackSite.setTitulo("Es null");
    }
    xpp.nextTag();
  } else if (tagname.equalsIgnoreCase(KEY_LINK)) {
    curStackSite.setLink(curText);
  }
break;

XML file
<?xml version="1.0" encoding="UTF-8"?>
<stack-sites>
    <marker>
        <titulo provincia="Pich">Pichincha</titulo>
        <link>http://stackoverflow.com/</link>
        <fecha>2014/08/12 14:57:59</fecha>
        <image>https://dl.dropboxusercontent.com/u/5724095/XmlParseExample/stackoverflow.png</image>
        <lat>-0.1</lat>
        <lng>-78.46</lng>
        <mag>4.1</mag>
        <depth>5</depth>
    </marker>
</stack-sites>

A: I made a change in the XML file like this <titulo provincia="Pich" /> and it worked.