text:
Q: is there any better way to handling axios error with laravel and vue js so i am creating spa web apps using laravel as my backend and vue js as the spa frontend framework. i am using laravel passport for authentication with api. and i am using vuex for controlling my application state.
first i create an api files to interact with api with axios
import { BKCU_CONFIG } from '../config.js';

export default {

  getArtikelS: function( p ){
    return axios.get( BKCU_CONFIG.API_URL + '/artikel' + `?column=${p.column}&direction=${p.direction}&per_page=${p.per_page}&page=${p.page}&search_column=${p.search_column}&search_operator=${p.search_operator}&search_query_1=${p.search_query_1}&search_query_2=${p.search_query_2}`);
  },

  getArtikelCUS: function( p, id ){
    return axios.get( BKCU_CONFIG.API_URL + '/artikel/indexCU/' + id + `?column=${p.column}&direction=${p.direction}&per_page=${p.per_page}&page=${p.page}&search_column=${p.search_column}&search_operator=${p.search_operator}&search_query_1=${p.search_query_1}&search_query_2=${p.search_query_2}`);
  },

  getArtikel: function( id ){
    return axios.get(BKCU_CONFIG.API_URL + '/artikel/' + id);
  },

  createArtikel: function(){
    return axios.get(BKCU_CONFIG.API_URL + '/artikel/create');
  },

  storeArtikel: function ( form ){
    return axios.post(BKCU_CONFIG.API_URL + '/artikel/store', form);
  },

  editArtikel: function( id ){
    return axios.get(BKCU_CONFIG.API_URL + '/artikel/edit/' + id);
  },

  updateArtikel: function ( id, form ){
    return axios.post(BKCU_CONFIG.API_URL + '/artikel/update/' + id, form);
  },

  updateTerbitkan: function( id ){
    return axios.post(BKCU_CONFIG.API_URL + '/artikel/updateTerbitkan/' + id);
  },

  updateUtamakan: function( id ){
    return axios.post(BKCU_CONFIG.API_URL + '/artikel/updateUtamakan/' + id);
  },

  deleteArtikel: function( id ){
    return axios.delete(BKCU_CONFIG.API_URL + '/artikel/' + id);
  }
}

and then i create a vuex module for each model ex. article like this:
import ArtikelAPI from '../../api/artikel.js';

export const artikel = {
  state: {
    artikelS: [],
    artikelLoadStatS: '',
    artikel: {},
    artikelLoadStat: '',
    artikelUpdate: '',
    artikelUpdateStat: '',
    artikelRules: [],
    artikelOption: [],
  },

  actions: {

    // load all
    loadArtikelS( { commit }, p ){
      commit('setArtikelLoadStatS', 'loading');

      ArtikelAPI.getArtikelS( p )
        .then( function( response ){
          commit('setArtikelS', response.data.model);
          commit('setArtikelLoadStatS', 'success');
        })
        .catch( error => {
          commit('setArtikelS', error.response);
          commit('setArtikelLoadStatS', 'fail');
        });
    },

    // load by cu
    loadArtikelCUS( { commit }, [p, id] ){
      commit('setArtikelLoadStatS', 'loading');

      ArtikelAPI.getArtikelCUS( p, id )
        .then( function( response ){
          commit('setArtikelS', response.data.model);
          commit('setArtikelLoadStatS', 'success');
        })
        .catch( error => {
          commit('setArtikelS', error.response);
          commit('setArtikelLoadStatS', 'fail');
        });
    },

    // load single data
    loadArtikel( {commit}, id ){
      commit('setArtikelLoadStat', 'loading');

      ArtikelAPI.getArtikel( id )
        .then( function( response ){
          commit('setArtikel', response.data );
          commit('setArtikelLoadStat', 'success');
        })
        .catch( error => {
          commit('setArtikelS', error.response);
          commit('setArtikelLoadStatS', 'fail');
        });
    },

    // create page
    createArtikel( {commit} ){
      commit('setArtikelLoadStat', 'loading');

      ArtikelAPI.createArtikel()
        .then( function( response ){
          commit('setArtikel', response.data.form );
          commit('setArtikelRules', response.data.rules);
          commit('setArtikelOption', response.data.option)
          commit('setArtikelLoadStat', 'success');
        })
        .catch( function(){
          commit('setArtikel', []);
          commit('setArtikelRules', []);
          commit('setArtikelOption', [])
          commit('setArtikelLoadStat', 'fail');
        });
    },

    // store data
    storeArtikel( {commit, state, dispatch}, form ){
      commit('setArtikelUpdateStat', 'loading');

      ArtikelAPI.storeArtikel( form )
        .then( function( response ){
          if(response.data.saved){
            commit('setArtikelUpdate', response.data);
            commit('setArtikelUpdateStat', 'success');
          }else{
            commit('setArtikelUpdateStat', 'fail');
          }
        })
        .catch(error => {
          if (error.response.status) {
            this.errors = error.response.data;
            commit('setArtikelUpdate', this.errors);
          }else{
            commit('setArtikelUpdate', 'Oops terjadi kesalahan :(');
          }
          commit('setArtikelUpdateStat', 'fail');
        });
    },

    // edit page
    editArtikel( {commit}, id ){
      commit('setArtikelLoadStat', 'loading');

      ArtikelAPI.editArtikel( id )
        .then( function( response ){
          commit('setArtikel', response.data.form );
          commit('setArtikelRules', response.data.rules);
          commit('setArtikelOption', response.data.option)
          commit('setArtikelLoadStat', 'success');
        })
        .catch( function(){
          commit('setArtikel', []);
          commit('setArtikelRules', []);
          commit('setArtikelOption', [])
          commit('setArtikelLoadStat', 'fail');
        });
    },

    // update data
    updateArtikel( {commit, state, dispatch}, [id, form] ){
      commit('setArtikelUpdateStat', 'loading');

      ArtikelAPI.updateArtikel( id, form )
        .then( function( response ){
          if(response.data.saved){
            commit('setArtikelUpdate', response.data);
            commit('setArtikelUpdateStat', 'success');
          }else{
            commit('setArtikelUpdateStat', 'fail');
          }
        })
        .catch(error => {
          if (error.response.status) {
            this.errors = error.response.data;
            commit('setArtikelUpdate', this.errors);
          }else{
            commit('setArtikelUpdate', 'Oops terjadi kesalahan :(');
          }
          commit('setArtikelUpdateStat', 'fail');
        });
    },
    updateArtikelTerbitkan( {commit, state, dispatch}, id ){
      commit('setArtikelUpdateStat', 'loading');

      ArtikelAPI.updateTerbitkan( id )
        .then( function( response ){
          if(response.data.saved){
            commit('setArtikelUpdate', response.data);
            commit('setArtikelUpdateStat', 'success');
          }else{
            commit('setArtikelUpdateStat', 'fail');
          }
        })
        .catch(error => {
          if (error.response.status) {
            this.errors = error.response.data;
            commit('setArtikelUpdate', this.errors);
          }else{
            commit('setArtikelUpdate', 'Oops terjadi kesalahan :(');
          }
          commit('setArtikelUpdateStat', 'fail');
        });
    },
    updateArtikelUtamakan( {commit, state, dispatch}, id ){
      commit('setArtikelUpdateStat', 'loading');

      ArtikelAPI.updateUtamakan( id )
        .then( function( response ){
          if(response.data.saved){
            commit('setArtikelUpdate', response.data);
            commit('setArtikelUpdateStat', 'success');
          }else{
            commit('setArtikelUpdateStat', 'fail');
          }
        })
        .catch(error => {
          if (error.response.status) {
            this.errors = error.response.data;
            commit('setArtikelUpdate', this.errors);
          }else{
            commit('setArtikelUpdate', 'Oops terjadi kesalahan :(');
          }
          commit('setArtikelUpdateStat', 'fail');
        });
    },

    // delete data
    deleteArtikel( {commit, state, dispatch}, id ){
      commit('setArtikelUpdateStat', 'loading');

      ArtikelAPI.deleteArtikel( id )
        .then( function( response ){
          if(response.data.saved){
            commit('setArtikelUpdate', response.data);
            commit('setArtikelUpdateStat', 'success');
          }else{
            commit('setArtikelUpdateStat', 'fail');
          }
        })
        .catch(error => {
          if (error.response.status) {
            this.errors = error.response.data;
            commit('setArtikelUpdate', this.errors);
          }else{
            commit('setArtikelUpdate', 'Oops terjadi kesalahan :(');
          }
          commit('setArtikelUpdateStat', 'fail');
        });
    },

    // reset status
    resetArtikelUpdateStat( {commit} ){
      commit('setArtikelUpdateStat', '');
    }
  },

  mutations: {
    setArtikelS ( state, artikelS ){
      state.artikelS = artikelS;
    },
    setArtikelLoadStatS( state, status ){
      state.artikelLoadStatS = status;
    },
    setArtikel ( state, artikel ){
      state.artikel = artikel;
    },
    setArtikelLoadStat( state, status ){
      state.artikelLoadStat = status;
    },
    setArtikelUpdateStat( state, status ){
      state.artikelUpdateStat = status;
    },
    setArtikelUpdate( state, data ){
      state.artikelUpdate = data;
    },
    setArtikelRules( state, rules ){
      state.artikelRules = rules;
    },
    setArtikelOption( state, option ){
      state.artikelOption = option;
    }
  },

  getters: {
    getArtikelS( state ){
      return state.artikelS;
    },
    getArtikelLoadStatS ( state ){
      return state.artikelLoadStatS;
    },
    getArtikel( state ){
      return state.artikel;
    },
    getArtikelLoadStat ( state ){
      return state.artikelLoadStat;
    },
    getArtikelUpdateStat ( state ){
      return state.artikelUpdateStat;
    },
    getArtikelUpdate ( state ){
      return state.artikelUpdate;
    },
    getArtikelRules ( state ){
      return state.artikelRules;
    },
    getArtikelOption ( state ){
      return state.artikelOption;
    }
  }
}

and as you can see, each of my action contain an error catch and it only catch the error and show the message. I find some disadvantage in this way of handling things
maybe someone can help me to improve this kind of workflow, everything is working fine and very structured but i find the error catch is lacking for example:

*

*because i am using laravel then there is the time my token expired (because user leave their pc for a period of time or other things) so it will show an authenticated error message in not very user friendly way, i want to it just redirect user to login page to relogin and then back to the page user currently on

*i think i do a lot of repeating code in here, can i just make a one single error handling for all of this axios request?

A: You could use some features from axios to get rid of this boilerplate
Use interceptors
 axios.interceptors.response.use(response => {
  return response.data;
 }, error => {
 if (error.response && error.response.data) {
  // handle your errors here.
  handleServerErrors(error.response.data);
 }
 return Promise.reject(error);
});

Use axios defaults
axios.defaults.timeout = 5000;
axios.defaults.baseURL = BKCU_CONFIG.API_URL

Don't concatenate the url anymore. Since you already set the default url, you could do
getArtikel: function( id ){
   return axios.get('/artikel/' + id);
}

Use ES6 features and axios params so you could turn this
getArtikelS: function( p ){
 return axios.get( BKCU_CONFIG.API_URL + '/artikel' + `?column=${p.column}&direction=${p.direction}&per_page=${p.per_page}&page=${p.page}&search_column=${p.search_column}&search_operator=${p.search_operator}&search_query_1=${p.search_query_1}&search_query_2=${p.search_query_2}`);
},

Into something more nice like this
   getArtikelS(p){
     return axios.get(`/artikel`, {params: p})
   }

Axios supports params as an object so you don't have to write weird query strings :)
A final tip: Don't store everything into vuex. If you don't need that data in more than 1 component, call the api directly in your components.

A:
You can use interceptor. But, the backend should care about errors and send the corresponding message to front end.

request.interceptors.response.use(response => {
  return response
}, error => {
  //Put your logic here to manage the error message coming from BE

  return Promise.reject(error )
})

For full example see how i have implemented the whole axios instance in my app:

(I have used vuetify snackbar component to display the error message)
import axios from 'axios'
import { store } from "../../store/store"
import { eventBus } from "../main";

const request = axios.create({
  baseURL: 'http://localhost:8000'
})

request.interceptors.request.use(request => {
  const token = store.state.token
  if (token) {
    request.headers.Authorization = 'Bearer ' + token
  }
  return request

}, error => {
  return Promise.reject(error)
})

request.interceptors.response.use(response => {
  return response
}, error => { //getting error from backend and display it with snackbar(vuetify component)
   eventBus.$emit('snackBar', {
     text: error.response.data.message,
     snackbarColor: 'red darken-4'
   })

  return Promise.reject(error )
})

export default request

Example error message with Laravel:
return response()->json(["message" => "You have not access to perform this action"],403);


text:
Q: telegram error node js
error: [polling_error] {"code":"ETELEGRAM","message":"ETELEGRAM: 404
Not Found"}

const token = require('./config.json')
const TelegramApi = require('node-telegram-bot-api')

const bot = new TelegramApi(token, {polling:true})

bot.on("message", msg => {
    console.log(msg)
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: sorting nodes according to its members I don't know where to start. I have a long list of nodes comprised of descendant members, for which I want to make a linked tree, a plain text database in the form of child/parent. For example:
N115713
N115713 N96394
N117904 N18574
N140517 N171639 N179536 N208718 N210073 N226737 N4647 N80403
N171639
N171639 N18574
N171639 N208718
N171639 N208718 N210073
N171639 N208718 N210073 N3690
N171639 N208718 N210073 N96585
N171639 N210073
N18574
N18574 N80403
Obviously, "N115713" will go downstream of "N115713 N96394" but I seem unable to turn that recognition into an algorithm. There are several hundred nodes having up to several dozen members. Pointers to get started? I'm using perl.
Thanks!
UPDATE: Well, I have an idea but haven't been able to implement it yet. I'm searching each line in turn for the other lines it's a "member" of then selecting that result which has the next highest number of members as its parent.

A: Since the main problem here is to check if the input data is consistent and does not have cycles, I recommend using some graph-theoretical module, for example Graph.
If your data allows a child to have multiple parents you have to check if the directed graph produced from your data does not have a cycle.
Otherwise, if your data should be a tree, you have to check that the undirected graph does not have a cycle.
I sketched up a simple script, that implements these checks and outputs child/parent pairs, it is pretty self explanatory:
use strict;use warnings;

use Graph;
my $g=Graph->new(directed=>1);
while(<>) {
    chomp;
    my @fields=split;
    # this assumes that each line starts with a parent and goes down through its descendants
    # adjust the logic to your needs
    my $parent;
    for my $child(@fields) {
        $g->add_vertex($child);
        if ($parent) {
            $g->add_edge($child,$parent);
        }
        $parent=$child;
    }
}

# check if we have a DAG
my @cycle = $g->find_a_cycle();
if (@cycle) {
    printf "The directed graph has a cycle: %s\n", join ',', @cycle
}

# check if we have a tree
my $un_g = $g->undirected_copy();
@cycle = $un_g->find_a_cycle();
if (@cycle) {
    printf "The undirected graph has a cycle: %s\n", join ',', @cycle
}

print "child,parent\n";
for my $edge(sort { $a->[0] cmp $b->[0] } $g->edges) {
    printf "%s,%s\n", $edge->[0], $edge->[1];
}

And the output for your data:
The undirected graph has a cycle: N179536,N171639,N208718
child,parent
N115713,N96394
N117904,N18574
N140517,N171639
N171639,N208718
N171639,N18574
N171639,N179536
N171639,N210073
N179536,N208718
N18574,N80403
N208718,N210073
N210073,N226737
N210073,N96585
N210073,N3690
N226737,N4647
N4647,N80403


text:
Q: How to call only php function not whole page with ajax? I want to return data only from the php function not whole page data.
Here is my demo.php file -
    <?
    echo "Whole Page data";

    $name = $_POST['name'];

    if ($name == "demo"){
        demo();
    }
    else{
        echo "No";
    }
    function demo(){
       echo "demo data";
}

?>

And my ajax funtion is this -
function myAjax () {
        $.ajax( { type : 'POST',
                url  : 'demo.php',
                data : "name=demo",
                success:function(data){
                       alert (data);
               }
       });
}

But it return whole page data with function data but I want only function data.

A: Check like,
if (!empty($_POST)) {
    $name = $_POST['name'];

    if ($name == "demo") {
        demo();
    } else {
        echo "No";
    }
    die;
}
function demo()
{
    echo "demo data";
}

This die; is important to halt execution process.
Give it a try, this should work.


text:
Q: Blocked a frame with origin "https://www.youtube.com" only on Ipad ios So, I used code from YouTube API for rendering background video on section in web page. I faced with a problem using only Ipad Model A1490 version ios 9.3.2(13F69) Chrome 63.03239.73 or Safari (and iphone 6): Blocked a frame with origin "https://www.youtube.com" from accessing a frame with origin "https://mydomain-without-leading-www.com". Protocols, domains, and ports must match.
In the result, I can see background video as black rectangle which has loading indicator:
image with black loading indicator
But on other devices - desktop or android phones/tablets - all works fine. How I use youtube api:
if ($('.videoplayer-container').length > 0) {
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var playersArray = [];
  window.onYouTubeIframeAPIReady = function () {
    var playerDefaults = {
      autoplay: 1,
      autohide: 1,
      modestbranding: 1,
      rel: 0,
      showinfo: 0,
      controls: 0,
      disablekb: 1,
      enablejsapi: 0,
      iv_load_policy: 3
    };

    $('.videoplayer-container').each(function(key, value){
      var playerId = 'videoplayer-container-' + $(value).attr('data-section');
      var divObj = value;
      var playerObj = new YT.Player( playerId,
        { videoId: $(value).attr('data-youtube-id'),
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onStateChange
          },
          playerVars: playerDefaults
        });
      playersArray.push({ playerId, playerObj, divObj });
    });

    function onPlayerReady(obj){
      if (obj.target.mute) {
        obj.target.mute();
      }
      playersArray.forEach(function(obj){
        const playerObject = obj.playerObj;
        if (playerObject.playVideo) {
          playerObject.playVideo();
          if (playerObject.isMuted && !playerObject.isMuted()) {
            playerObject.mute();
          }
        }
        rescaleVideo(obj);
      });
    }

    function onStateChange(obj){
      if (obj.data === YT.PlayerState.ENDED) {
        obj.target.playVideo();
      }
    }

    //  ....
  };
}

I tried to use origin parameter and pass different values: 'https://www.youtube.com' - don't output console error, but iframe isn't created, location.protocol + '//' + location.host - error remains. I googled about this problem, but didn't find solving of it.


text:
Q: Import sheets from xls file into separate tables SQL Is there a way to import excel file that has multiple sheets into a database? (each sheet is a separate table) Or Do I have to do that maunaly with csv?

A: Yes, when using Import Wizard you specify the source as Excel, the destination as your SQL DB and then select the sheet of the Excel workbook to use.
Please be careful with Excel in the data mapping, Excel will 'auto choose' a data type based on the first 10 (?) rows.  If you have a column with all numeric at the top, but then some text values later on that data will not load.


text:
Q: Consistently Push Data From Server to Client Using SignalR I am working on a web application where i have some charts and i want to consistently get data from the database for the charts so that the user will always have the latest picture of the data. I used signalR and on the page load of Report page i am calling a server method in hub's class which is getting chart data from database and passing it onto the client and in turn a handler at client processes the data and draws the chart. What i want is to keep getting the data consistently. What are my options for it?
What is the best way to keep calling hub's method after a fix interval of say one minute?

A: I would not poll on client or server. Instead use a service bus and publish your changes on that bus when they occur.
You can then forward these events to the client using SignalR. I have made a library for just that called SignalR.EventAggregatorProxy
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki
I wrote a blog post about it here
http://andersmalmgren.com/2014/05/27/client-server-event-aggregation-with-signalr/
You can also look at the demo
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/tree/master/SignalR.EventAggregatorProxy.Demo.MVC4
Or look at the live demo here
http://malmgrens.org/signalr/

A: SignalR makes polling the server obsolete. What you want to do is to schedule your database access. If you want to update your charts every minute, create a timer job in the server app where you collect data from database which has been added within the last minute. Then send this data to your clients. On this way your connected clients are always up to date without polling the server.


text:
Q: How to send a mail from Xampp localhost in PHP on Mac? I am trying to send an email to user once he signs up on my localhost project, I am working on Xampp and my OS is Mac, I know this function is correct:
$to_email = "receipient@gmail.com";
$subject = "Simple Email Test via PHP";
$body = "Hi,nn This is test email send by PHP Script";
$headers = "From: sender\'s email";

if (mail($to_email, $subject, $body, $headers)) {
    echo "Email successfully sent to $to_email...";
} else {
    echo "Email sending failed...";
}

But there is something to configure in SMTP i guess? however I can't find what and where to edit on MAC, thank you in advance.

A: If you want to send a mail from a local server using for example XAMPP, you will need to use the mail server in order to do it.
Do something like this:
<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "YOURMAIL@gmail.com");
$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = YourMail@address.com";
$headers = "From: YOURMAIL@gmail.com";
mail("Sending@provider.com", "Testing", $message, $headers);

You will most likely need the mail account's credentials in order to send a mail.
Also, check out Sending email with PHP from an SMTP server.


text:
Q: if statement for if logical contains at least one TRUE (R) I am creating an if statement for whether an output contains a specific string or not. I am using regular expression to do so.
I am using the grepl() function to investigate if the output contains the string 'Final evaluation: none (in check)' within the variable 'stockfish_response'. This then contains a logical matrix of FALSEs and TRUEs. E.g:
FALSE FALSE FALSE FALSE TRUE
grepl('Final evaluation: none \\(in check\\)', stockfish_response)

To incorporate this into an IF ELSE statement I need a logical process to check if a TRUE exists at least once in this matrix. Is there a function which will return TRUE if the logical matrix contains at least one TRUE and FALSE if the logical matrix contains no TRUEs.
For instance:
grepl_output <- grepl('Final evaluation: none \\(in check\\)', stockfish_response)

if (grepl_output == TRUE){
  print('the phrase \'Final evaluation: none (in check) string \' exists')
} else {
  print('the phrase \'Final evaluation: none (in check) string \' does not exist')
}

whereby grepl_output == TRUE is not just constrained to the first logical in the list and returns TRUE if any value in the list is TRUE

A: Could you use any?
if any(grepl_output == TRUE) {
  # do something ...
}

See ?any for details.


text:
Q: FluentNHibernate joined-subclass What is the current method of implementing the joined-subclass structure with FluentNHibernate? By "current", I mean by not using deprecated methods such as JoinedSubClass or AddPart.
Thanks!

A: The recommended way to map a joined-subclass is to inherit from SubclassMap much in the same way you inherit from ClassMap for your non-subclass entities.
It's described in the fluent mapping subclasses section on the wiki. For automapping please refer to Automapping Inheritance.


text:
Q: Shutdown and reboot not working in Debian 10 Buster Since I've installed Debian 10 Buster on my laptop (2009 or so ASUS) I'm not able to shutdown or reboot my computer properly. I've re-installed the OS countless times with no success. I'm using LXDE as DE. Whenever I press the shutdown or reboot buttom from the GUI or I use the terminal to type the dedicated commands my system hangs for more than twenty minutes on Reached target Power-Off or Reached target Reboot. I've edited the grub configuration file removing the quiet boot option and I've found out the last thing systemd is trying to do is Stopping disk when shutting down, or Synchronizing SCSI cache when rebooting. After reading this I tried both poweroff -f and reboot -f and none of them worked. So is this a kernel related issue? I don't know how to proceed. I've even saved my systemd shutdown log with debug options enabled.
lscpu |grep -i model reports:
Model: 23 Model name: Pentium(R) Dual-Core CPU T4400 @ 2.20GHz

A: tl;dr - I've upgraded my BIOS to fix it.
I had this same exact issue with my older Dell laptop.  I am fairly certain that it has to do with the kernel 4.19 after upgrading from 4.9 when going from Stretch to Buster.  My best guess is that the BIOS (at least mine) have a semi-broken ACPI implementation but the older kernel was able to tolerate it by sending it what it wants to change states.
If you are already on the latest BIOS for your hardware, you may be SOL and either would have to try the latest kernel or downgrade the kernel.  I am no expert in this area and thus perhaps someone with a better understanding can look into the differences between 4.9 and 4.19 in the ACPI power states handling.
I hope this helps at least someone.

A: I solved it by installing NVIDIA Proprietary Driver following
https://wiki.debian.org/NvidiaGraphicsDrivers, kernel and legacy driver from backports. That resolved the poweroff issue. The reboot freeze was solved by GRUB_CMDLINE_LINUX="reboot=pci".
On laptop Asus K70IO (2009, NVIDIA GeForce GT 120M) freshly installed with Debian 10 Buster.

A: I installed Debian buster an a ACER ASPIRE 3 series laptop and got the same problem. I solved it by updating the linux kernel to the most recent version avaiable from the debian backport repository.
I found this solution on youtube: https://www.youtube.com/watch?v=Rj1qjFwg_H8.


text:
Q: Eclipse RCP product export using a certain JDK My Eclipse Mars 4.5.1. uses JDK 8 to start-up (specified in the eclipse.ini)
My RCP project uses JDK 7. The entire workspace uses 7. I've also included the JavaFX JAR until I migrate the whole project to JDK 8, where I won't need it.
When I try to export the RCP project using the .product file, the exported version has some logs saying that certain classes using JavaFX have compile errors. Even though the exported version is started with JDK 7 (specified in the .ini file), and the JavaFX JAR surely was exported too, these UI components crash.

*

*This whole process works with Eclipse starting with JDK 7 !

*I really want to use my Eclipse with JDK 8, but ONLY the Eclipse

*How does Eclipse influence the export process? My target platform points to eclipse, but has JDK 7 set on it.

A: You can try to put a JRE 7 in your product location and test if it runs, remove the entry in the .ini file.

*

*plugins

*configurations

*jre

*...

If this works, your entry in the .ini file is probably wrong.
Another thought: "I've also included the JavaFX JAR", where did you include it? Maybe you need to include it in the JRE.


text:
Q: Using a filtered index when setting a variable I know from other questions and posts that when SQL compiles a query plan it can only use a filtered index if the filtered index is guaranteed to be able to be used every time the query runs. This means you can't use a variable in the where clause because sometimes it might be able to use the filtered index and sometimes not.
One way around this is to use OPTION(RECOMPILE), so that the times it can use it, it'll get the filtered index.
Doing some testing, I found that this query can use a filtered index (note, I'm forcing the index just to prove a point):
SELECT MAX(table1.SomeDateField)
FROM        dbo.table1 WITH(INDEX(MyFilteredIndex))
WHERE       table1.filteredColumn = @variable
OPTION (RECOMPILE)

However, if I want to assign the result to a variable, I'm bang out of luck:
SELECT @OutputVariable = MAX(table1.SomeDateField)
FROM        dbo.table1 WITH(INDEX(MyFilteredIndex))
WHERE       table1.filteredColumn = @variable
OPTION (RECOMPILE)

results in:

Msg 8622, Level 16, State 1, Line 15 Query processor could not produce
a query plan because of the hints defined in this query. Resubmit the
query without specifying any hints and without using SET FORCEPLAN.

The query can clearly use the filtered index as it runs find when I don't want to save the output to a variable.
I have ways of rewriting this query to hard-code @variable to remove the problem, but can someone explain why the first query can use the filtered index, but the 2nd query can't?

A: This should work:
declare @myVariable int
declare @variable int = 9
declare @OutputVariable date

declare @t table(MaxDate date)

insert into @t(MaxDate)
SELECT MAX(table1.SomeDateField)
FROM        dbo.table1 WITH(INDEX(MyFilteredIndex))
WHERE       table1.filteredColumn = @variable
OPTION (RECOMPILE)

select @OutputVariable MaxDate from @t

And you can always use dynamic SQL with literal values instead of trying to get a parameter to transform into a literal with OPTION (RECOMPILE).  eg
declare @variable int = 9
declare @OutputVariable date

declare @sql nvarchar(max) = concat(N'
SELECT @OutputVariable = MAX(table1.SomeDateField)
FROM        dbo.table1 WITH(INDEX(MyFilteredIndex))
WHERE       table1.filteredColumn = ', @variable)

exec sp_executesql @sql, N'@OutputVariable date out', @OutputVariable = @OutputVariable out
select @OutputVariable

A: The optimization that allows you to use the filtered index with a RECOMPILE hint is called the "parameter embedding optimization."  That's a process where the query parser replaces the variable reference with the literal value inside the variable.
See this post from Paul White for the reason why it doesn't work in your second case: Parameter Sniffing, Embedding, and the RECOMPILE Options

There is one scenario where using OPTION (RECOMPILE) will not result in the parameter embedding optimization being applied. If the statement assigns to a variable, parameter values are not embedded:

A: The reason why the optimizer can't generate a plan is because it has no way of guaranteeing that the variable's value will actually match the filter predicate. The query plan is precompiled and stored, and it is not safe for it to use that index in all cases. Unfortunately the optimizer does not at this time contain logic to bifurcate a filtered index only in the case when the filter matches, which is a shame. You can do it yourself, as SQLPro has demonstrated.
One problem with this is: filtered indexes often change, based on what the DBA thinks is best. An option I have successfully used is to cache client-side the filtered index predicate, and dynamically build the query based on that, while still passing through the variable. This avoids issues of plan cache bloat and SQL injection, as the query is still parameterized and does not change unless the index changes. You can also do this with sp_executesql from inside a stored procedure.
To get the filter predicate, run this query:
  SELECT ISNULL(
      (SELECT i.filter_definition
      FROM sys.indexes i
      WHERE i.object_id = OBJECT_ID(@tablename) AND
          i.name = @indexname AND has_filter = 1),
      '(1=1)');

This also handles the case when the filter, or indeed the whole index, is dropped.

A: You can try this query:
SELECT @OutputVariable =
(SELECT MAX(table1.SomeDateField)
FROM   dbo.table1
WHERE  table1.filteredColumn = @variable
  AND  table1.filteredColumn = the_filtered_value
UNION ALL
SELECT MAX(table1.SomeDateField)
FROM   dbo.table1
WHERE  table1.filteredColumn = @variable
  AND  NOT table1.filteredColumn = the_filtered_value)

The reason this works is because you are bifurcating the filtered index i.e. only using it in a case when the variable matches the filter predicate. The optimizer cannot use the index without this because it can't guarantee the value matches the predicate.


text:
Q: How to fix read timeout exception in spark Cassandra connector I am using spark 2.4 and scala 2.11 in azure databricks platform, DSE 6.0.7 and spark cassandra connector version 2.4.0
I am getting below error while getting the count for one of my table which has around ~100Million records. Exact row count is required for one of the applications. Below is my code -
val count = spark.read
  .format("org.apache.spark.sql.cassandra")
  .option("table", tableName)
  .option("keyspace", keyspace)
  .load()
  .count()

Below is exception -
java.io.IOException: Exception during execution of SELECT count(*) FROM "mykeyspace"."mytable" WHERE token("id") > ? AND token("id") <= ?   ALLOW FILTERING: [/host:9042] Timed out waiting for server response
  at com.datastax.spark.connector.rdd.CassandraTableScanRDD.com$datastax$spark$connector$rdd$CassandraTableScanRDD$$fetchTokenRange(CassandraTableScanRDD.scala:350)
  at com.datastax.spark.connector.rdd.CassandraTableScanRDD$$anonfun$17.apply(CassandraTableScanRDD.scala:367)
  at com.datastax.spark.connector.rdd.CassandraTableScanRDD$$anonfun$17.apply(CassandraTableScanRDD.scala:367)
  at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434)
  at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
  at com.datastax.spark.connector.util.CountingIterator.hasNext(CountingIterator.scala:12)
  at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:439)
  at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
  at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage1.agg_doAggregateWithoutKey_0$(Unknown Source)
  at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage1.processNext(Unknown Source)
  at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
  at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$13$$anon$1.hasNext(WholeStageCodegenExec.scala:634)
  at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
  at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:125)
  at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
  at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:55)
  at org.apache.spark.scheduler.Task.doRunTask(Task.scala:139)
  at org.apache.spark.scheduler.Task.run(Task.scala:112)
  at org.apache.spark.executor.Executor$TaskRunner$$anonfun$13.apply(Executor.scala:497)
  at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1432)
  at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:503)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  at java.lang.Thread.run(Thread.java:748)
Caused by: com.datastax.driver.core.exceptions.OperationTimedOutException: [/host:9042] Timed out waiting for server response


text:
Q: Cannot escape parameters inside single quotes on a JDBC PreparedStatement I want to make a query like this (note it contains some postgis functions) via JDBC:
SELECT id, name, ST_Y(location::geometry) as latitude, ST_X(location::geometry) as longitude, category_group, category
FROM pois
WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT(-5.8340534 43.3581991)'), 1000000);

so I parametrized the query to:
SELECT id, name, ST_Y(location::geometry) as latitude, ST_X(location::geometry) as longitude, category_group, category
FROM pois
WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT(? ?)'), ?);

The problem is that when executing the preparedStament it can't find the first 2 parameters, because they are inside single quotes, so it gives an error.
I also tried to escape the single quotes with \' without success:
SELECT id, name, ST_Y(location::geometry) as latitude, ST_X(location::geometry) as longitude, category_group, category
FROM pois
WHERE ST_DWithin(location, ST_GeographyFromText(\'SRID=4326;POINT(? ?)\'), ?);

For now, as a workaround, I'm not binding the parameters, just appending the query string with them, but that's susceptible to SQL Injection, so I just want to know if there is any way to escape that sentence to make parameter binding work.

A: Asking myself, I'm using string concat:
"SELECT id, name, ST_Y(location::geometry) as latitude, ST_X(location::geometry) as longitude, category_group, category
FROM pois
WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT(' || ? || ' ' || ? || ')'), ?);"

A: As a naive answer....
You can assign the parameters before the query and later concatenate it with the Query
ex:
Scanner scan = new Scanner(System.in); //don't forget to import java.util package
String par1 = scan.nextLine();
String par2 = scan.nextLine();

Later
String query = "SELECT id, name, ST_Y(location::geometry) as latitude, " +
    "ST_X(location::geometry) as longitude, category_group, category " +
    "FROM pois " +
    "WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT("+par1+" "+par2+")'), ?)";

now pass this query to the Query Creation Statement


text:
Q: How to align HoloLens holograms relative to anchors in the Unity editor I am trying to align holograms relative to WorldAnchors without manually placing them in-app. Is there any way of visualizing WorldAnchors in the Unity editor to align objects relative to their positions? I see anchor data in the Device Portal, is this at all related to WorldAnchors?
Ideal workflow being:
1) Scan a room for the first time, obtaining a room mesh .obj through Device Portal. Simultaneously run an assistant Unity app and place anchor(s) for later reference (in room corners for example).
2) Import the .obj into Unity, along with Device Portal anchors if possible.
3) Transfer these WorldAnchors to a new Unity project and align holograms relative to the anchors.
4) Run this new app for the first time on HoloLens and have holograms properly positioned in space without additional adjustment of anchors by the user.

Here is an example using Vuforia, but I would like to use WorldAnchors (or the anchors in Device Portal somehow) for a markerless solution: https://youtu.be/W7z2sggDGoo?t=1689
The script referenced here 404s: https://github.com/Microsoft/MixedRealityToolkit-Unity/issues/530
https://forums.hololens.com/discussion/10725/placing-holograms-at-predefined-locations-in-spatial-mapping-hololens almost provides a solution, but still fails to explain how anchors and the room mesh can be aligned in development for accurate placement upon opening the app.
Thank you!
Edit - Here is a similar question: Placing objects at set locations in a pre-scanned room Is there a better solution than "placing all the objects manually in some config first-run of the app"?

A: As far as I know world anchors only exist during runtime and there is no way to export them to unity or already add predefined ones in unity.
I had a similar problem and went with vuforia ImageTargets and it works quite nice.

A: It sounds like you want to make use of the WorldAnchorStore (UnityEngine.XR.WSA.Persistence). This allows anchors to be persisted on the device across sessions and between apps, and (off the top of my head) is probably the source of the anchors you see in Device Portal.
If you're using the Mixed Reality Toolkit in your project then there's a helper, WorldAnchorManager (found in Common/Scripts) that wraps the underlying functionality.


text:
Q: у меня вылазиет ошибка я не понимаю что не так я сделал программу которая вычисляет пароль от вай фай по BSSID и когда писал для неё интерфейс вылезла куча ошибок https://disk.yandex.ru/i/ua-VAIdOhYOw9w
вот мой код:

from tkinter import *
from math import floor
root=Tk()
root.title("brute")

x = root.winfo_screenwidth()
y = root.winfo_screenheight()
root.geometry('{}x{}'.format(int(x*1), int(y*1)))

My_label=Label(root,text="possible passwords",font=("Arial",50,"bold"))
My_label.pack()

name=StringVar()

BSSID = Entry(width=20,bd=5)
BSSID.place(x=x/2.3,y=y/3)

bssd1=BSSID.get().replace(":","",1)

def play():
  MAC = bssd1
  один = b = (int(MAC,16) & 0xFFFFFF) % 10000000
  a = 0
  while b:
    a += 3 * (b % 10)
    b = floor(b / 10)
    a += b % 10
    b = floor(b / 10)
  d = (один * 10) + ((10 - (a % 10)) % 10)
  c = str(int(d))
  result = c.zfill(8)

my_botton = Button(text="начать",width=112, height=5,bg="yellow",fg="gold",command = play)
my_botton.place(x=400,y=400)

root.mainloop()```


text:
Q: Hyperparameter Optimization in Tensorflow I am doing hyperparameter optimization using Bayesian Optimization in Tensorflow for my Convolutional Neural Network (CNN). And I am getting this error:

ResourceExhaustedError (see above for traceback): OOM when allocating
  tensor with shape[4136,1,180,432] and type float on
  /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc

I optimized these hyperparameters:
dim_batch_size = Integer(low=1, high=50, name='batch_size')
dim_kernel_size1 = Integer(low=1, high=75, name='kernel_size1')
dim_kernel_size2 = Integer(low=1, high=50, name='kernel_size2')
dim_depth = Integer(low=1, high=100, name='depth')
dim_num_hidden = Integer(low=5, high=1500, name='num_hidden')
dim_num_dense_layers = Integer(low=1, high=5, name='num_dense_layers')
dim_learning_rate = Real(low=1e-6, high=1e-2, prior='log-uniform',
                         name='learning_rate')
dim_activation = Categorical(categories=['relu', 'sigmoid'],
                             name='activation')
dim_max_pool = Integer(low=1, high=100, name='max_pool')

dimensions = [dim_batch_size,
              dim_kernel_size1,
              dim_kernel_size2,
              dim_depth,
              dim_num_hidden,
              dim_num_dense_layers,
              dim_learning_rate,
              dim_activation,
              dim_max_pool]

It says resource is exhausted. Why is this?
Is it because I optimized too many hyperparameters? Or there is some dimension mismatch? Or did I assign a hyperparameter range that is beyond the allowed range for correct operation?

A: OOM happened because when several hyperparameters are in high end of the range, the model becomes too large. For example, suppose the batch size is around 50 and dim_num_hidden is around 1500 and so on. The number of hyperparameters doesn't matter, only a few of them can be enough to blow the model.
The concrete tensor from the error message is [4136,1,180,432] or 1.2Gb if you're using 32-bit floats for parameters. This is a lot and it's just one of many tensors needed to do the NN training (e.g., forward and backward double the number of parameters and hence the memory). No wonder tensorflow failed with OOM.
One particular issue with Bayesian optimization for hyper-parameter tuning is that the algorithm is very likely to select the corners of the hyper-space, i.e., one point where the values are close to a minimum in a range, the other point where the values are close to a maximum in a range. See the details in this question. This means that you have to limit at least one hyper-parameter (usually the batch size) so that the model fits even when everything else is at max. Or you can be smart and calculate it precisely before running the model on each iteration, but this way the algorithm won't optimize the batch size.


text:
Q: arranging columns and sub-columns in ggplot2 using facet_wrap? I would like to know how can I group plots like the following ggplot (edited in paint): Plot
It looks like facet_wrap() and facet_grid() functions cannot be used to arrange the columns and sub-columns.
Is there any R package that I can use?
Thanks

A: You can multiply the factors used for columns and subcolumns.
library(ggplot2)

ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  facet_wrap(~ cyl * gear, labeller = label_both)

The labeller label_both here also is useful as it adds the variable name before the value in the facet header.


text:
Q: How to update input value when assigning onChange event in React? I am having problems with the total number of items in the CartHeader component. Obviously I have added the quantity of each product but the result is not as I expected ?. Can someone find the fault for me? I sincerely thank.
import ReactDOM from "react-dom";
import CartHeader from "./CartHeader";
import CartBody from "./CartBody";
import CartFooter from "./CartFooter";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [
        {
          id: 1,
          name: "Apple Watch Series 5",
          description: "Description for Apple Watch Series 5",
          img:
            "https://bachlongmobile.com/media/catalog/product/cache/2/image/040ec09b1e35df139433887a97daa66f/2/0/2076130625_1_1_1.jpg",
          price: 499.99,
          quantity: 1
        },
        {
          id: 2,
          name: "iPhone 11 Pro Max",
          description: "Description for iPhone 11 Pro Max",
          img:
            "https://cdn.fptshop.com.vn/Uploads/Originals/2019/9/11/637037687763926758_11-pro-max-xanh.png",
          price: 1099.99,
          quantity: 1
        },
        {
          id: 3,
          name: "Macbook Pro 16 inch",
          description: "Description for Macbook Pro 16 inch",
          img: "https://shopdunk.com/wp-content/uploads/2019/11/mac16inch.jpg",
          price: 2399.99,
          quantity: 1
        },
        {
          id: 4,
          name: "iPad Pro 12.9 inch",
          description: "Description for iPad Pro",
          img:
            "https://cdn.fptshop.com.vn/Uploads/Originals/2019/1/11/636828015979564724_ipad-pro-12-9-xam-1.png",
          price: 999.99,
          quantity: 1
        },
        {
          id: 5,
          name: "AirPods Pro",
          description: "Description for AirPods Pro",
          img:
            "https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/MWP22?wid=1144&hei=1144&fmt=jpeg&qlt=80&op_usm=0.5,0.5&.v=1572990352299",
          price: 249.99,
          quantity: 1
        }
      ]
    };
  }

  onRemoveProduct = id => {
    const newProducts = this.state.products;
    // Tìm vị trí sản phẩm cần xoá
    let index = newProducts.findIndex(product => product.id === id);
    // Kiểm tra nếu tìm thấy thì mới xoá
    if (index !== -1) {
      newProducts.splice(index, 1);
      this.setState({
        products: newProducts
      });
    }
  };

  handleChange = (e, id) => {
    const { products } = this.state;
    const indexProduct = products.findIndex(product => product.id === id);
    products[indexProduct].quantity = e.target.value;
    this.setState({ products });
  };

  render() {
    const products = this.state.products;
    let numberItems = 0;
    let subTotal = 0;
    products.map(product => {
      numberItems += product.quantity;
      subTotal += product.price * product.quantity;
    });

    return (
      <main>
        <CartHeader numberItems={numberItems} />
        <CartBody
          products={products}
          onRemoveProduct={this.onRemoveProduct}
          handleChange={this.handleChange}
        />
        <CartFooter subTotal={subTotal} />
      </main>
    );
  }
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

have I ever misunderstood the problem.
Link codesandbox:
https://codesandbox.io/s/thirsty-hill-6w2ex

A: You should define curry function for handleChange method like below:
  handleChange = id => e => {
    const {products} =  this.state;
    const indexProduct = products.findIndex(product => product.id === id);
    products[indexProduct].quantity = e.target.value;
    this.setState({ products: [...products] });
  };

inside CardBody:
  <input
      type="number"
      className="quantity"
      step={1}
      defaultValue={product.quantity}
      onChange={e => handleChange(product.id)(e)}
      />

Here you can find codesandbox

A: Dynamic data display is best accomplished through the React state. At the moment, you define variables within the render() function, but this area is largely for static data.
First, define the numerical values (quantity and total) as state values instead of variables. Then, define a function that handles the onChange event of each quantity input for each product. In that function, handle the accumulation of each numerical value and subsequently update the state with those values.


text:
Q: Why does window.onerror not catch stack overflow errors in IE9? I'm using window.onerror to catch and log client-side errors. I've read about the various caveats to this approach, but I haven't been able to track down any info on this particular case.
For some reason IE9 does not seem to catch stack overflow exceptions. The below example catches both errors when run in Chrome and Firefox as well as if I use devtools in IE9 and set browser mode to IE8 or IE7. However, when run in IE9 mode, it only catches the 'test' is undefined exception, but ignore the stack overflow exception.
I have put together a simple example, to demonstrate this:
window.onerror = errorHandler;

function errorHandler (msg) {
    alert(msg);
}

setTimeout(function () {
    test.test = "test";
}, 1000);

setTimeout(function stackoverflow() {
    stackoverflow();
}, 2000);

Here is a working example as well: http://jsfiddle.net/Mzvbk/1/
Can anyone shed some light on why this is?
Update August 29, 2012
I posted this question on the Internet Explorer Developer Center as well, but so far it hasn't given me much.
At this point, the best guess (as suggested by @RyanKinal in his comment) is that since the call stack size is exceeded, there is no room to put the call to the error handler on the stack.
I still like to believe that error handling is handled separately from the normal stack, as it seem to be in other browser (even older versions of IE), but if that isn't the case, it would be nice to see a reference, bug-report or statement of some kind, indicating that this actually is the case with IE9.
Update September 5, 2012
As described by Ren and Vega in their comments, Firefox 15 sometimes (seemingly random) seem to swallow that exception as well.

A: Have you tried disabling script debugging on the browser?

A common problem that bites many developers occurs when their onerror
  handler is not called because they have script debugging enabled for
  Internet Explorer. This will be the case by default if you have
  installed the Microsoft Script Debugger or Microsoft Visual Studio
  6.0® (specifically Visual InterDev 6.0™)—onerror handling is how these products launch their debugger.

Source (includes details on how to disable it).

Additional information following up on the comments:
Then I wonder is it related to this:

Internet Explorer 9 is compiled with the new C++ compiler provided
  with Visual Studio 2010. This compiler includes a feature known as
  Enhanced GS aka Stack Buffer Overrun Detection, which helps prevent
  stack buffer overruns by detecting stack corruption and avoiding
  execution if such corruption is encountered.

(Source)
Sounds like it could be that it is stopping before the overflow as a protection mechanism?


text:
Q: chacha20-poly1305 in PHP with OpenSSL I'm running PHP 7.2.8. According to openssl_get_cipher_methods chacha20-poly1305 is a supported algorithm:
echo in_array('chacha20-poly1305', openssl_get_cipher_methods()) ? 'yes' : 'no';

That outputs "yes".
So I tried to use chacha20-poly1305:
$plaintext = 'zzzzzz';
$key = str_repeat('k', 32);
$nonce = str_repeat('n', 12);
$aad = '';

$r = openssl_encrypt(
    $plaintext,
    'chacha20-poly1305',
    $key,
    OPENSSL_RAW_DATA,
    $nonce,
    $newtag,
    $aad
);

echo bin2hex($r);

That output a PHP warning:

Warning: openssl_encrypt(): The authenticated tag cannot be provided for cipher that doesn not support AEAD

$r was f4854428b8a8.
I was able to get the same output for r with chacha20 (ie. no poly1305 by doing this):
$r = openssl_encrypt(
    $plaintext,
    'chacha20',
    $key,
    OPENSSL_RAW_DATA,
    "\1\0\0\0" . $nonce
);

The fact that the output is the same means that the Poly1305 authentication code is neither being appended or prepended to the ciphertext.
My question is...  how do I get the Poly1305 authentication code using OpenSSL in PHP?
Also, I'm aware that libsodium provides chacha20-poly1305 support but I am, none-the-less, still curious as to how it's supposed to work with OpenSSL.

A: The problem with OpenSSL is still unsolved (Nov. 2020) so if you need to use
ChaCha20-Poly1305 authenticated encryption with PHP I recommend the library from
Leigh (https://github.com/lt/PHP-AEAD-ChaCha20-Poly1305) that can be implemented
very easy.
The auth-tag ($tag) is appended to the ciphertext and needs to get separated before
start the decryption.
Just a note as I'm testing the same functionality with OpenJDK 11 (Java): both functions produce the same ciphertext but different auth-tags, so they are not usable in a cross-platform environment.
output:
ChaCha20-Poly1305 encryption with leigh/aead-chacha20-poly1305
tag (16 bytes long, Base64): FK11WpqxhDuJytSgHN86tQ==
ciphertext (Base64):         1rXNtbeGF9KsMZXgPjszIeJ0Ze5ua+Uh5Aexu1ngaH4XoeldG71DwuDEAA==
decrypt: The quick brown fox jumps over the lazy dog

the code (security warning: never use a static key or nonce in production):
<?php
# make sure that you used Composer to get "leigh/aead-chacha20-poly1305"
require __DIR__ . '/vendor/autoload.php';

// ### never use static key & nonce in production, this is for testing only ###
$key = '12345678901234567890123456789012'; // 32 bytes
$nonce = '123456789012'; // 12 bytes
$plaintext = 'The quick brown fox jumps over the lazy dog';
$aad = '';

echo 'ChaCha20-Poly1305 encryption with leigh/aead-chacha20-poly1305' . PHP_EOL;
list($ciphertext, $tag) = \ChaCha20Poly1305\encrypt($key, $nonce, $aad, $plaintext);
echo 'tag (16 bytes long, Base64): ' . base64_encode($tag) . PHP_EOL;
echo 'ciphertext (Base64):         ' . base64_encode($ciphertext) . PHP_EOL;
$decrypt = \ChaCha20Poly1305\decrypt($key, $nonce, $aad, $ciphertext, $tag);
echo 'decrypt: ' . $decrypt . PHP_EOL;
?>


text:
Q: HTML5 Canvas Scale position Im trying out canvas for the first time and have a few questions about scaling.
After i scale the canvas up (half) i want to set the current position. The scale always sets the canvas to pos 0,0 (top-left).
If anyone knows how i could change the position while scaling please leave a answer!
Example
http://i.stack.imgur.com/SLG4v.png original.
http://i.imgur.com/2nmJZJH.png needed result.

A: You can use this example:

    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");

    const canvasArea = canvas.width * 2 + canvas.height * 2;
    const radius = canvasArea * 0.1;
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const color = 'blue';

    function drawCircle(context, scale, centerX, centerY, radius, color){
          context.save()
          context.beginPath();
          context.translate(centerX, centerY);
        context.scale(scale,scale);
          context.translate(-centerX,-centerY);
          context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
        context.fillStyle = color;
        context.fill();
        context.restore()
    }

    function change(el) {
      canvas.width = canvas.width;
      canvas.height = canvas.height;

        const scale = el.value / el.max;

        drawCircle(ctx, scale, centerX, centerY, radius, color);
    }

    change(document.getElementById('rangeInput'));
    <canvas id="myCanvas" width="200" height="200" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML canvas tag.</canvas>
    <br>

    <input id='rangeInput' type="range" min="0" max="100" value="100" oninput='change(this)' onchange='change(this)' style="width:200px">

A: To get what you have shown in the images.
// ctx is the canvas 2d context
// img is the image
function showImageScaled(img,scale,x,y){
    // scale is how big you want it.
    // x and y are where in the image you want the top left to be
    ctx.setTransform(scale,0,0,scale,0,0);
    ctx.drawImage(img,-x,-y); // move the image
}

So to view the top corner scaled up to twice
showImageScaled(img,2,0,0);

To show the centre in the top left and the image scaled 4 times
showImageScaled(img,4,img.width/2,img.height/2);

Hope this helps.

A: An alternative to the solution given by Blindman67
You can use this precision zoom, which scales your picture at custom central scaling point (the same way as how digital camera lcd display zooms) and draws it.
function precisionScale(img,scale,x,y){
        /** Function precisionScale
         * The function scales the image with a custom central scaling point
         * as opposed to 0,0 (top,left) default central scaling point
         */
        ctx.translate(x,y);
        ctx.scale(scale,scale);
        ctx.drawImage(img,-x,-y);
        ctx.scale(-scale,-scale);
        ctx.translate(-x,-y);
    }


text:
Q: Can a diode reverse leakage current cause error in this circuit? I want to measure C2 leakage current:

simulate this circuit – Schematic created using CircuitLab
C1 has a leakage current of its own, to prevent C1 leakage current cause error in the leakage readings of C2 I put a diode in series but the diode have a reverse leakage current itself.

*

*How do I prevent C1 leakage current affecting the C2 leakage current readings?

A: As long as BR1 can provide a much higher current than the leakage current of C1 and C2 together I would not expect a potential difference between C2 and C1. Since there is no real load, DC Voltage will be AC peak voltage minus voltage drop at BR1. (approx. 635V) Ripple should be low for the same reason.
You could use a ripple suppressor instead of D1 if you want to stabilize voltage at C2. This would give you a small but defined voltage drop from the filter capacitor to your device under test.

\$C_1\$ is the filter capacitor you already have.
\$R_1\$ and \$C_2\$ will make ripple imperceptible.
\$R_2\$ is a minimal load that will keep the circuit from floating.
If you prefer MOSFETs a circuit like the following might do, but I have not tested it myself.


text:
Q: How can I restrict arguments of methods in abstract classes for subclasses that use them? I've been trying to design a set of classes to model a classic RPG. I've found myself confused on how to solve this one issue, however: how do I force the use of character-type (e.g. Tank, Healer, DPS) specific spells/equipment, etc. in an abstract class. The example below better articulates what I mean.
I've got an abstract PlayableCharacter class which all character-types inherit from:
public abstract class PlayableCharacter {
    private Set<Spell> mSpells;

    ...

    public void addSpell(Spell spell) {
        mSpells.add(spell);
    }
}

For example:
public class Healer extends PlayableCharacter {  ...  }
public class Tank extends PlayableCharacter {  ...  }

Note the Set of Spell in the abstract class. I would like it if each subclass of PlayableCharacter could use its addSpell method but with the restriction that the type of Spell correspond to the PlayableCharacter subtype.
For example I have these Spell classes:
public abstract class Spell {  ...  }
public class HealerSpell extends Spell {  ...  }
public class TankSpell extends Spell {  ...  }

I only want Healers to use HealerSpells and Tanks to use TankSpells, etc. For example:
PlayableCharacter tank = new Tank();
tank.addSpell(new TankSpell());    // This is fine
tank.addSpell(new HealerSpell());  // I want to prevent this!

I thought of giving each subclass of PlayableCharacter it's own Set of subclass-specific Spells, but that creates a lot of code duplication.
I also tried making PlayableCharacter.addSpell marked as protected, then each subclass would have to implement an interface like this:
public interface Spellable<T extends Spell> {  void addClassSpell(T spell);  }

and each subclass that implements it would call super.addSpell(spell); but that lead to more code duplication and nothing was forcing those implementations to do the super call.
Is my strategy fundamentally flawed in some way? Any advice? I feel like this issue will keep getting worse as I add more character-type-specific equipment, traits, and so on.

A: I wouldn't do it that way (via type inheritance). It would be better to add characteristics to a Spell itself because it's a spell, which can be cast by a certain character only. Also, a specific spell can be cast to a certain character type only. These rules belong to a spell, not to a character.
Spell rules can be checked in a runtime by a separate class or by a Spell class itself inside a cast() method or another one.

A: so far what you have is good
the rest of the stuff, think more strategy pattern than super call
so abstract class can have algorithm that does step1, step2, step3 with possible parent implementation
child classes can override it, but only override parts that is different
when you call algorithm, it performs all steps
Steps themselves could be different class that has logic, if everything becomes too big

A: maybe have each subclass of playable character store the class (or classes) of subspells that are allowed. then do an if(spell instance of allowedSpell) ...


text:
Q: Unable to get newline in javascript checkerboard I looked around and can't figure out why this code isn't working.  It's simply supposed to make a checkerboard but I'm getting a single line of symbols:
Supposed to do:
 # # # #
# # #
# # # #
Is doing:
# # # # # # # etc...
Here is the code
symbol1 = " ";
symbol2 = "#";
for (i=0;i<9;i++){
for (j=0;j<9;j++){
    if (j%2 == 0){
        document.write(symbol2);
}
    else
        document.write(symbol1);
    document.write("\n");
}

}

A: Since you're outputting to an HTML document, \n doesn't mean newline, it's just whitespace. In HTML, all whitespace is just a single space in the rendered output.
To output a line break, you ouput a br element:
document.write("
");

Note that while document.write is fine for small experiments and such, it has very little place in actual web development. Using document.write adds to the document where the script tag is during the main parsing of the document, but once the main parsing is done, the document is closed. If you use document.write again (for instance, in response to an event), it will implicitly do a document.open, wiping out all of the document contents, and then write to the newly-opened document.
But again, it's fine if you're just running some code for experiments and quick learning, just beware of what it actually does. As you progress, you'll start using the DOM instead (either directly, or through a DOM library like jQuery).

A: you are writing new line to document which won't work. you need to write breakline tag to be rendered as html. something like this:
symbol1 = " ";
symbol2 = "#";
for (i=0;i<9;i++){
for (j=0;j<9;j++){
if (j%2 == 0){

    document.write(symbol2);
}
else
    document.write(symbol1);

}
document.write("
");

}


text:
Q: How do I know when a field/row in mysql updated successfully? Right now, I have my database setup so that I insert a new row. But if the row I'm trying to insert is a duplicate (based off of my primary key id), then I increment the count field by 1.
Right now I want to know when I was able to create a new row instead of having it increment count. How would I do this in an efficient/proper manner?
The current method I'm thinking of doing this, is by querying the id first and checking if it exists. But I feel like there's a faster/better way. I've also read about triggers but I've heard that they're bad/risky to use.

A: Use INSERT ... ON DUPLICATE KEY UPDATE...
Then query for affected_rows (as @Tarek Fadel suggested). MySQL will return 1 if the row was inserted, or 2 if existing row were updated.

A: Use your database AUTO INCREMENT option for your primary ID field. Only propper solution.
Here you have mysql reference, but that exist in just every database engine:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

A: How about an auto_increment on the id column?
Otherwise you might use SELECT MAX(id) FROM TABLE to retreive the highest id and add one to it, but that isn't thread-safe since another user might execute the same insert at the same time. Auto_increment fixes that for you.

A: PHP's mysql_affected_rows()


text:
Q: Android simple file upload Apparently in this world everyone only uploads images to servers, I can't seem to find anything that tells me how to upload a non image file. What I am trying to do is create an sqlite backup file and store it on my server, so that later if the user needs to they can download and use this backup to restore their data.
I have tried the following libraries as well but they don't seem to be working for anything other than an image.
implementation "net.gotev:uploadservice:3.5.2"
implementation "net.gotev:uploadservice-ftp:3.5.2"

Can someone point me in the direction I need to upload my type of files to a php script so I can store it in my directory?

A: Use retrofit2 to make network request, then a simple POST request can be seen here tutorial
in a nutshell inside a service you create a function like this
public interface FileUploadService {
    @Multipart
    @POST("upload")
    Call<ResponseBody> upload(
        @Part("description") RequestBody description,
        @Part MultipartBody.Part file
    );
}


text:
Q: How to re-add a drive when RAID is in degraded mode? I am running an unmanaged Ubuntu server and due to recent performance issue and sent a request to the provider only to receive the following response:
"Dear Client,
as requested we have checked your drives. Both drives pass a test without any error and do not show any critical value here. We noticed the RAID is degraded state so you will need to re-add the drive to array here:
-----------------%<-----------------
Personalities : [raid1]
md3 : active raid1 sda4[0]
      1839089920 blocks super 1.2 [2/1] [U_]

md2 : active raid1 sda3[0]
      1073610560 blocks super 1.2 [2/1] [U_]

md1 : active raid1 sda2[0]
      523968 blocks super 1.2 [2/1] [U_]

md0 : active raid1 sda1[0]
      16768896 blocks super 1.2 [2/1] [U_]

unused devices: <none>
-----------------%<-----------------"

Google says that U_ indicates a failed drive, which appears to be in contradiction to what the support said. How do I proceed from here?
Something like
mdadm /dev/mdX -r /dev/sdaY
mdadm /dev/mdX -a /dev/sdaY

And if so, what is X and Y for my case?  If more info is needed about my configuration, please let me know.
EDIT, more info below:
root@Ubuntu-1204-precise-64-minimal /home # df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/md2       1008G   26G  931G   3% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
udev             16G  4.0K   16G   1% /dev
tmpfs           3.2G  504K  3.2G   1% /run
none            5.0M     0  5.0M   0% /run/lock
none             16G     0   16G   0% /run/shm
none            100M     0  100M   0% /run/user
/dev/md1        488M   66M  397M  15% /boot
/dev/md3        1.7T   31G  1.6T   2% /home

root@Ubuntu-1204-precise-64-minimal /home # mdadm -D /dev/md0
/dev/md0:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:41 2013
     Raid Level : raid1
     Array Size : 16768896 (15.99 GiB 17.17 GB)
  Used Dev Size : 16768896 (15.99 GiB 17.17 GB)
   Raid Devices : 2
  Total Devices : 1
    Persistence : Superblock is persistent

    Update Time : Wed Dec 21 03:50:13 2016
          State : clean, degraded
 Active Devices : 1
Working Devices : 1
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:0
           UUID : 872ad258:c42ccb36:e9e19c96:98b55ee9
         Events : 816844

    Number   Major   Minor   RaidDevice State
       0       8        1        0      active sync   /dev/sda1
       1       0        0        1      removed

root@Ubuntu-1204-precise-64-minimal /home # mdadm -D /dev/md1
/dev/md1:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:41 2013
     Raid Level : raid1
     Array Size : 523968 (511.77 MiB 536.54 MB)
  Used Dev Size : 523968 (511.77 MiB 536.54 MB)
   Raid Devices : 2
  Total Devices : 1
    Persistence : Superblock is persistent

    Update Time : Wed Dec 21 07:30:55 2016
          State : clean, degraded
 Active Devices : 1
Working Devices : 1
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:1
           UUID : 18cb39fc:9eaea61c:0074a6c2:661b5862
         Events : 387

    Number   Major   Minor   RaidDevice State
       0       8        2        0      active sync   /dev/sda2
       1       0        0        1      removed

root@Ubuntu-1204-precise-64-minimal /home # mdadm -D /dev/md2
/dev/md2:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:42 2013
     Raid Level : raid1
     Array Size : 1073610560 (1023.87 GiB 1099.38 GB)
  Used Dev Size : 1073610560 (1023.87 GiB 1099.38 GB)
   Raid Devices : 2
  Total Devices : 1
    Persistence : Superblock is persistent

    Update Time : Wed Dec 21 07:58:52 2016
          State : active, degraded
 Active Devices : 1
Working Devices : 1
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:2
           UUID : eb9be750:7ff778b4:31fd7ce9:9d86d191
         Events : 38799724

    Number   Major   Minor   RaidDevice State
       0       8        3        0      active sync   /dev/sda3
       1       0        0        1      removed

root@Ubuntu-1204-precise-64-minimal /home # mdadm -D /dev/md3
/dev/md3:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:42 2013
     Raid Level : raid1
     Array Size : 1839089920 (1753.89 GiB 1883.23 GB)
  Used Dev Size : 1839089920 (1753.89 GiB 1883.23 GB)
   Raid Devices : 2
  Total Devices : 1
    Persistence : Superblock is persistent

    Update Time : Wed Dec 21 07:57:41 2016
          State : clean, degraded
 Active Devices : 1
Working Devices : 1
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:3
           UUID : c9b748ef:332d3bf9:5fa8fef1:5b433b0a
         Events : 7429895

    Number   Major   Minor   RaidDevice State
       0       8        4        0      active sync   /dev/sda4
       1       0        0        1      removed

A: Adding Back a RAID 1 Member
To add a RAID member back into the array, use:
mdadm <RAID Device> -a <Device to add into the array>

For example:
$ mdadm /dev/md0 -a /dev/sdc1
mdadm: re-added /dev/sdc1

If you check again using mdadm --detail , you'll see that /dev/sdc1 is shown as "rebuilding":
Number   Major   Minor   RaidDevice State
   0       8       17        0      active sync   /dev/sdb1
   2       8       33        1      spare rebuilding   /dev/sdc1

This means that the newly added member is being synchronised with the data on the other member; if you now check proc/mdstat, you can see the synchronisation progress - as a percentage and a bar chart:
$ cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid1 sdc1[2] sdb1[0]
      976759936 blocks [2/1] [U_]
      [>....................]  recovery =  1.2% (12409024/976759936) finish=195.2min speed=82312K/sec

unused devices: <none>

Verify that you can still see your files on the RAID drive following the addition of the new RAID member:
$ ls /mnt/raid1
Music  lost+found  Images Films Misc

A: I solved my own issue. I did not understand that mdX are partitions and sda and sdb are actual physical discs. So sdb was missing, so I needed to add it back. I executed the following commands:
sgdisk -R /dev/sdb /dev/sda
sgdisk -G /dev/sdb
mdadm /dev/md0 -a /dev/sdb1
mdadm /dev/md1 -a /dev/sdb2
mdadm /dev/md2 -a /dev/sdb3
mdadm /dev/md3 -a /dev/sdb4

After a day of resync (can be observed with)
cat /proc/mdstat

What I see today looks good again:
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md3 : active raid1 sdb4[2] sda4[0]
      1839089920 blocks super 1.2 [2/2] [UU]

md1 : active raid1 sdb2[2] sda2[0]
      523968 blocks super 1.2 [2/2] [UU]

md2 : active raid1 sdb3[2] sda3[0]
      1073610560 blocks super 1.2 [2/2] [UU]

md0 : active raid1 sdb1[2] sda1[0]
      16768896 blocks super 1.2 [2/2] [UU]

A: Before adding the drive as suggested by @Tolsadus its a good idea to check your drive health using smartmontools by executing short and long tests:
Initially you have to ensure that the hard disk supports SMART and is enabled:
smartctl -i /dev/sdb
short test:
smartctl -t short /dev/sdb
long test:
smartctl -l selftest /dev/sdb


text:
Q: Touchpad no longer recognized after updating BIOS and kernel While trying to fix some of my function keys, I decided to update my BIOS. Although this didn't solve my original issue, my touchpad was no longer working!
Initially, after the first reboot, it still showed up in /proc/bus/input/devices and xinput, but just didn't seem to work. Then, Ubuntu (19.10) prompted me to install a lot of new updates.
First of all, I couldn't boot into ubuntu anymore from GRUB2 (I run dual-boot with windows), although that was quickly resolved by changing my kernel to vmlinuz-5.3.0-19-generic in the entry (from 4.xx-23 I believe).
Then, after finally successfully rebooting, my touchpad doesn't show up in /proc/bus/input/devices or xinput at all anymore! The only trace I managed to find was this output in dmesg:
[    2.471492] psmouse serio4: elantech: assuming hardware version 4 (with firmware version 0x461f01)
[    2.474830] systemd[1]: /lib/systemd/system/dbus.socket:4: ListenStream= references a path below legacy directory /var/run/, updating /var/run/dbus/system_bus_socket → /run/dbus/system_bus_socket; please update the unit file accordingly.
[    2.487000] psmouse serio4: elantech: Synaptics capabilities query result 0x00, 0x16, 0x0d.
[    2.504567] psmouse serio4: elantech: Elan sample query result 01, 7b, 75
[    2.534034] systemd[1]: Listening on initctl Compatibility Named Pipe.
[    2.534644] systemd[1]: Created slice User and Session Slice.
[    2.534709] systemd[1]: Listening on udev Kernel Socket.
[    2.534797] systemd[1]: Listening on Journal Socket (/dev/log).
[    2.534806] systemd[1]: Reached target Slices.
[    2.535269] psmouse serio4: elantech: Trying to set up SMBus access
[    2.557682] EXT4-fs (sdb5): re-mounted. Opts: errors=remount-ro
[    2.560654] lp: driver loaded but no devices found
[    2.569821] ppdev: user-space parallel port driver
[    2.712339] Adding 2097148k swap on /swapfile.  Priority:-2 extents:5 across:2260988k SSFS
[    2.748547] elan_i2c 0-0015: 0-0015 supply vcc not found, using dummy regulator
[    2.756831] elan_i2c 0-0015: failed to get product ID: -71
[    2.803035] elan_i2c 0-0015: failed to get product ID: -71
[    2.847035] elan_i2c 0-0015: failed to get product ID: -71
[    2.883114] elan_i2c: probe of 0-0015 failed with error -71

Does anybody have a clue on how to fix this?

EDIT:
After LinuxSecurityFreak's suggestion I tried activating the touchpad with:
sudo rmmod elan_i2c
sudo modprobe elan_i2c

After which the touchpad does show up again in /proc/bus/input/devices and xinput! But.. It still doesn't work.
/var/log/syslog reports the following for sudo rmmod elan_i2c:
Nov 20 14:19:25 User xdg-desktop-por[1895]: Failed to get application states: GDBus.Error:org.freedesktop.portal.Error.Failed: Could not get window list: GDBus.Error:org.freedesktop.DBus.Error.AccessDenied: App introspection not allowed
Nov 20 14:20:03 User /usr/lib/gdm3/gdm-x-session[1695]: (II) config/udev: removing device Elan Touchpad
Nov 20 14:20:03 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Option "fd" "56"
Nov 20 14:20:03 User /usr/lib/gdm3/gdm-x-session[1695]: (II) event16 - Elan Touchpad: device removed
Nov 20 14:20:03 User /usr/lib/gdm3/gdm-x-session[1695]: (II) UnloadModule: "libinput"
Nov 20 14:20:03 User /usr/lib/gdm3/gdm-x-session[1695]: (II) systemd-logind: releasing fd for 13:80
Nov 20 14:20:03 User /usr/lib/gdm3/gdm-x-session[1695]: (EE) systemd-logind: failed to release device: Device not taken

and for sudo modprobe elan_i2c:
Nov 20 14:20:06 User kernel: [  359.718149] elan_i2c 0-0015: 0-0015 supply vcc not found, using dummy regulator
Nov 20 14:20:06 User kernel: [  359.726146] elan_i2c 0-0015: failed to get product ID: -71
Nov 20 14:20:06 User kernel: [  359.775575] elan_i2c 0-0015: Elan Touchpad: Module ID: 0x0000, Firmware: 0x0000, Sample: 0x0000, IAP: 0x0000
Nov 20 14:20:06 User kernel: [  359.776325] input: Elan Touchpad as /devices/pci0000:00/0000:00:1f.4/i2c-0/0-0015/input/input26
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) config/udev: Adding input device Elan Touchpad (/dev/input/mouse1)
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) No input driver specified, ignoring this device.
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) This device may have been added with another device file.
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1195]: (II) config/udev: Adding input device Elan Touchpad (/dev/input/mouse1)
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1195]: (II) No input driver specified, ignoring this device.
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1195]: (II) This device may have been added with another device file.
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) config/udev: Adding input device Elan Touchpad (/dev/input/event16)
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Elan Touchpad: Applying InputClass "libinput touchpad catchall"
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) Using input driver 'libinput' for 'Elan Touchpad'
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1195]: (II) config/udev: Adding input device Elan Touchpad (/dev/input/event16)
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1195]: (**) Elan Touchpad: Applying InputClass "libinput touchpad catchall"
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1195]: (II) Using input driver 'libinput' for 'Elan Touchpad'
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) systemd-logind: got fd for /dev/input/event16 13:80 fd 66 paused 0
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Elan Touchpad: always reports core events
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Option "Device" "/dev/input/event16"
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Option "_source" "server/udev"
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) event16 - Elan Touchpad: is tagged by udev as: Touchpad
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1195]: (II) systemd-logind: got fd for /dev/input/event16 13:80 fd 30 paused 1
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1195]: (II) systemd-logind: releasing fd for 13:80
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) event16 - Elan Touchpad: device is a touchpad
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) event16 - Elan Touchpad: device removed
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1f.4/i2c-0/0-0015/input/input26/event16"
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) XINPUT: Adding extended input device "Elan Touchpad" (type: TOUCHPAD, id 14)
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Option "AccelerationScheme" "none"
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Elan Touchpad: (accel) selected scheme none/0
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Elan Touchpad: (accel) acceleration factor: 2.000
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (**) Elan Touchpad: (accel) acceleration threshold: 4
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) event16 - Elan Touchpad: is tagged by udev as: Touchpad
Nov 20 14:20:06 User /usr/lib/gdm3/gdm-x-session[1695]: (II) event16 - Elan Touchpad: device is a touchpad

Strangely enough, running the same commands again the touchpad disappears yet again, with sudo modprobe elan_i2c giving a different output:
ov 20 14:22:19 User kernel: [  492.932593] elan_i2c 0-0015: 0-0015 supply vcc not found, using dummy regulator
Nov 20 14:22:19 User kernel: [  492.940679] elan_i2c 0-0015: failed to get product ID: -71
Nov 20 14:22:19 User kernel: [  492.986685] elan_i2c 0-0015: failed to get product ID: -71
Nov 20 14:22:19 User kernel: [  493.034988] elan_i2c 0-0015: failed to get product ID: -71
Nov 20 14:22:19 User kernel: [  493.074890] elan_i2c: probe of 0-0015 failed with error -71

A: This question on AskUbuntu seems to have been about the exact same bug, and the corresponding answer fixed my problem. In short:

*

*Run sudo sh -c 'echo -n "elantech"> /sys/bus/serio/devices/serio1/protocol' to get the touchpad working after boot, or

*Add psmouse.elantech_smbus=0 to your boot options to fix at startup.


text:
Q: How to set the checkbox in the first column based on the value in the second column? I'm automating a task using Ruby and Watir.
I want to set a checkbox (which is in the first column of a table) based on whether the value in the second column matches my input value. For example, in the following code snippet, the value "brett58" matches my input value so I want to set the checkbox associated with it.

        <input class="content-nogroove" type="checkbox" name="result[1].chked" value="true">
        <input type="hidden" value="7bd67e4d-a59f-0143-3886-22c1d205a5c1" name="result[1].col[0].stringVal">
        <input type="hidden" value="brett58" name="result[1].col[1].stringVal">

        brett58

    brett
    lee

But I'm unable to do it. In the above case, the following line serves the purpose (as my input value matches with that it first row):
browser.table(:class, "cuesTableBg").checkbox(:name, "result[1].chked").click

But it can't be used as the required value might not always be in the first row.
Looping through all the rows is one option but it's inefficient.

A: I would do:
browser.table(:class, "cuesTableBg").rows.find{ |row|
  row.cells[1].text == 'brett58'
}.checkbox.set

Basically, this is saying find the first row of the table that has "brett58" in the second column. Then set the first checkbox in that row.

A: Try something like this:
def set_checkbox(row_text_to_match)
  @browser.table(:class, "cuesTableBg").row(:text, /#{Regexp.escape(row_text_to_match)}/).checkbox(:name, "result[1].chked").set
end


text:
Q: Behaviour of try-with-resources with closable parameters Does Java-7's try-with-resources require the closable to be assigned directly to a variable? In short, is this block of code...
    try (final ObjectInputStream ois = new ObjectInputStream(
            new ByteArrayInputStream(data))) {
        return ois.readObject();
    }

Equivalent to this block?...
    try (final ByteArrayInputStream in = new ByteArrayInputStream(data);
         final ObjectInputStream ois = new ObjectInputStream(in)) {
        return ois.readObject();
    }

My understanding of Section 14.20.3 of the Java Language Specification says they are not the same and the resources must be assigned. This would be surprising from a common usage standpoint and I can't find any documentation warning against the pattern.

A: The two blocks are not equivalent in the sense that they won't generate the same code.  But since ObjectInputStream.close() will call close() on the ByteArrayInputStream that you passed it, the first block is completely fine.
EDIT: Something I forgot is that unlike reasonable constructions like new BufferedInputStream(new *InputStream(...)), the ObjectInputStream constructor actually reads from the stream you pass it and thus could reasonably throw an exception.  For that reason I'd actually recommend the second block, not the first block.

A: The code is not the same as you already mentioned, as Java will generate a close block for each variable even though it is not necessary. What is more important is this comment from the JavaDocs on AutoCloseable:

Note that unlike the close method of Closeable, this close method is
  not required to be idempotent. In other words, calling this close
  method more than once may have some visible side effect, unlike
  Closeable.close which is required to have no effect if called more
  than once. However, implementers of this interface are strongly
  encouraged to make their close methods idempotent.

Basically it means that calling close() twice should not have any effect, but it is not guaranteed. So it is recommended to avoid the 2nd construct you presented to avoid calling close twice.

A: Always use the second form. In the first form "new ObjectInputStream()" will throw an exception if the array is empty. This will leave
the ByteArrayInputStream open.


text:
Q: How to read char from standard input in Java I have to read char(one at a time) from the standard input in Java.The input will consist of numerous lines (each of about 10000 chars). I do not need to store the chars , they are processed when read.Also I need to skip the newline char .Can someone suggest me an efficient way to do this ?

A: I guess you need something like this.
Replace the # with whatever appropriate.
import java.io.InputStreamReader;

public class Test022 {

    public static void main(String[] args) throws Exception {
        InputStreamReader br = new InputStreamReader(System.in);
        char ch = ' ';
        while (true){
            ch = (char)br.read();
            if (ch == '#') break;
            else if (ch == '\n') continue;
            else if (ch == '\r') continue;

            System.out.println("Char read: " + ch);
        }
    }

}

A: Perhaps something like this will work:
import java.io.IOException;

public class Tester
{
    public static void main(String args[])
        throws IOException
    {
        int ch;
        while ((ch = System.in.read()) != -1)
        {
            if (ch != '\n' && ch != '\r')
            {
                processChar((char)ch);
            }
        }
    }

    private static void processChar(char c)
    {
        // do stuff
        System.out.println("Processing: '" + c + "'");
    }

}


text:
Q: Contact Form 7 placeholder text traslate using wpml plugin I am currently using Contact Form 7.I have created a contact form as follows:

[text* name id:name class:input-round  placeholder "Name*"]

[text subject id:subject class:input-round placeholder "Betreff"]

[email* email id:email class:input-round placeholder "E-Mail-Adresse*"]

[tel tel-632 id:phone class:input-round placeholder "Telefon"]

[text adress id:adress class:input-round placeholder "Adresse"]

[textarea message 40x4 id:message class:input-round placeholder "Nachricht"]

[submit class:submit-button class:button class:align-text-center "SENDEN"]Die eingegebene E-Mail-Adresse wird nur zum Zweck der Übertragung verwendet.

It's in Germain Language....
But I want to separate the text for that French
Now I use the WPML plugin for text translation.
But I could not make my text and change. as per the i read wpml documentation, but it did not work.
Any idea for placeholder text traslate using wpml plugin.
Contact Form 7 placeholder text traslate using wpml plugin

A: Finally I have solve this solution.
This plugin provided by WPML:
WPML's Classic or Advanced Translation Editor
No need for that one.
So you can create 2 contact forms and separate the two short-code and manage.
Please see attached image. ( contact.png )


text:
Q: How to simulate a 4-bit binary adder in C My professor assigned the class to write a C program to simulate a 32-bit adder using basic adders. I know a 32-bit adder is made up of 8 X 4-bit adders. However, I am unsure even how to simulate a 4-bit adder in C. I need to implement a 4-bit binary ripple carry adder, a 4-bit binary look-ahead carry generator, and a 4-bit look-ahead carry adder. From the truth table of a full adder and a Karnaugh map, I obtained the functions of the Sum and Carry Out outputs. For Sum I received A xor B xor Carry In. For the Carry out function, I received (A*B) + (Carry in(A xor B)). Now I am unsure where to go. I'm pretty sure I need to manipulate the integers at the bit level using bitwise operators (I have basic knowledge of bitwise operators although I have never implemented them outside of paper and pencil).
How do I break the integers up to obtain the A, B and Carry In inputs for the functions? How do I obtain the Sum and Carry Out outputs? How do I string the full adders together to obtain a 4-bit adder?
Thank you for the help!

A: Well, for a simple solution, we can take a half adder and full adder circuit diagram and abstract it a bit. From Wikipedia:
Half Adder:

Full Adder:

#include<stdio.h>

typedef char bit;
bit carry = 0;
bit halfadd( bit A, bit B ){
    carry = A & B;
    return A ^ B;
}
bit fulladd( bit A, bit B ){
    bit xor = A ^ B;
    bit ret = carry ^ xor;
    carry = (carry & xor) | (A & B);
    return ret;
}

void fillNum( int num, bit *array ){
    int i;
    for( i = 0; i < 32; ++ i ){
        array[i] = ( num >> i ) & 1;
    }
}

int main(){
    bit num1[32] = {0}, num2[32] = {0};
    int A = 64620926, B = 1531529858;
    fillNum( A, num1 );
    fillNum( B, num2 );

    int r = 0;
    bit tmp = halfadd( num1[0], num2[0] );
    putchar( tmp ? '1' : '0' );
    r = tmp;
    int i;
    for( i = 1; i < 32; ++i ){
        tmp = fulladd( num1[i], num2[i] );
        r += tmp << i;
        putchar( tmp ? '1' : '0' );
    }
    putchar( carry ? '1' : '0' );
    printf("\n%d\n\n%d + %d = %d", r, A, B, A+B);
    return 0;
}

That will output the added value with the LSB first, but it demonstrates the basic principal. This works according to Ideone. Just apply a similar approach to handling logic circuitry when simulating 4 bit adders.
If you don't want to read the integers to an array first, you can always use
#define GETBIT(num,bit)((num>>bit)&1)

For safety, you can put it in to a function call if you want

A: If I were doing this, I would simulate a 4 bit adder with a Lookup Table.  In this case it would be a 256 entry table that could be setup like a 16 x 16 array of values.
unsigned short outputs[16][16];

multOut = outputs[inA][inB];

You will have to initialize your array, but that should be pretty simple.
Use the 5th bit of each value in the array as your carry out bit.

A: To start you will need to break your larger integers into individual bits. This will depend on the endianess of your system (whether numbers are stored most, or least significant bit first). An array of bit masks would help. Assuming big endian,
int bit[]={
             1<<0, //least significant bit
             1<<1,
             1<<2,
             1<<3
};

So then to get the first  bit of a number you would do
leastSignificantBitOfA = A&bit[0];

From there you could either use some shared array to store outputs or maybe make a simple structure like:
struct fullAdderReturn{
       int sum;
       int carryOut;
}

struct fullAdderReturn oneBitAdder(int a, int b, int carryIn)
{
     struct fullAdderReturn output;

     output.sum = a&b;
     output.carryOut = (a&b) | (a&carryIn) | (b&carryIn);

     return output;
}

I put together a simple 2-bit ripple adder here http://ideone.com/NRoQMS hopefully it gives you some ideas .


text:
Q: How are the finite speed of light and the atomic nature of mater related to the end of Moore's law? In this article from 2007, Moore talks about the end of his Law. Can someone throw more light as to how the finite speed of light and the atomic nature of mater are related to the end of Moore's law?

A: The moore's (empirical) "law" states that the number of transistors in a chip increases exponentially (doubles every 2 years). So the question is : is there a hard limit in the number of transistors in a chip? Or, in other words : Are there limits on the size of a chip and on the size of transistors? Indeed there are (almost).
The matter is made of atoms, so you can't decrease the size of transistors indefinitely by just scaling down the same design (manufacturing issues aside). You can modify the design (that's what Intel & others are doing) but there is still a limit on the number of atoms : it's (seemingly) impossible to design a transistor made of a single atom...
Now, you could say "OK, let's increase the chip size instead". It turns out that it's also limited. Again, cost aside (pure silicon isn't cheap), the the signals must be transmitted across the chip in less than a clock cycle, so that the chip stays in sync. The information isn't travelling any faster than the speed of light, but what is the size of a chip that gets its information in less than 1/2 clock cycle at, say, 5GHz? That's 30mm. And that's assuming electric potential travels in silicon at speed of light in vacuum (it doesn't), and that's assuming it's OK to have signals 180° phase-shifted (it isn't).
So yes, that's quite a limit!
There is also the option to go 3D and start growing again "vertically". However the thermal flux will be the major problem here: a CPU die typically outputs 100W in a 1cm² chip. That's 1MW/m2, and that's quite a lot (and close to the limit of known materials). Now suppose you manage to double the number of "planes" every 2 years, and after 6 years you're doing 8MW/m2 (about what's allowed by copper with water cooling). After 10 years, your typical CPU would burn 3200W...


text:
Q: How do I show that this formula is $O(N)$? Let $K$ be a compact subset of $\mathbb{C}$.
Let $c,d$ be integers such that $(c,d)=1$.
Set $S_(c,d)=\max\{|cz+d|\mid z\in K\}$ (lower case (c,d) because it depends on the choice of $c$ and $d$, and existence because K is compact).
I want to show that #$\{(c,d):N\leq| S_(c,d)|\leq N+1\}=O(N)$ where # means the number of elements. Here $c$ and $d$ should be coprime.
This I think is true, but I don't know how to justify it. The difficulty for me is in dealing with $K$. Is this statement true? Can someone give me insight? Thanks!

A: $$S(u,v)=\sup_{z\in K} |uz+v|$$ is a norm on $\Bbb{R}^2$, $$S(tu,tv) = t S(u,v)$$ thus $$B_r=\iint_{S(u,v)< r} dudv= \iint_{S(u,v)< 1} d(ru)d(rv)=r^2B_1$$
Where $B_1$, the area of the unit ball of your norm, is finite non-zero.
For $S(c,d)\in [N,N+1]$ draw a unit square $[c,c+1]\times [d,d+1]$. There is $q=q_K$ such that every point of this square is in $N-q<S(u,v)<N+q$.
Whence the number of lattice points can be bounded by the area $$\sum_{c,d,N\le S(c,d)\le N+1} 1\le \int_{N-q<S(u,v)<N+q} dudv= (N+q)^2 B_1-(N-q)^2B_1=O(N)$$


text:
Q: C# scoping operator back in school, we wrote a compiler where curly braces had the default behavior of executing all expressions, and returning the last value... so you could write something like:
int foo = { printf("bar"); 1 };

Is there something equivalent in C#?  For instance, if I want to write a lambda function that has a side effect.
The point less being about the lambda side effect (just an example), more if there is this functionality... for instance in lisp, you have progn

A: There's nothing stopping you from having side-effects in a lambda expression.
Func<int> expr = () =>
{
    Console.WriteLine("bar");
    return 1;
};
int foo = expr();

A: In principle, the answer from Vlad is correct and you don't need to declare the lambda function as a delegate in advance.
Except, the situation is not as simple in C#, because the compiler cannot decide whether the syntactical lambda expression should be compiled as a delegate (e.g. Func<int>) or an expression tree (e.g. Expression<Func<int>>) and also, it can be any other compatible delegate type. So, you need to create the delegate:
int foo = new Func<int>(() => {
  Console.WriteLine("bar"); return 1; })();

You can simplify the code slightly by defining a method that simply returns the delegate and then calling the method - the C# compiler will infer the delegate type automatically:
static Func<R> Scope<R>(Func<R> f) { return f; }

// Compiler automatically compiles lambda function
// as delegate and infers the type arguments of 'Scope'
int foo = Scope(() => { Console.WriteLine("bar"); return 1; })();

I agree that this is an ugly trick that shouldn't be used :-), but it is an interesting fact that it can be done!

A: int foo = (() => { printf("bar"); return 1; })();

Edit: thanks for the constructive critique, it ought to be
int i = ((Func<int>)(() => { printf("bar"); return 1; }))();

A: We've considered making even-more-brief syntaxes than ()=>{M();} for definition of a lambda, but haven't managed to actually find a syntax that both reads nicely and is not easily confused with blocks, collection/object initializers, or array initializers.  You're stuck with lambda syntax for now.

A: You're talking about an anonymous function: http://msdn.microsoft.com/en-us/library/bb882516.aspx, I think.