text:
Q: Согласование gulpfile.js и webpack.config.js для Webpack После ответа на этот вопрос я решил, что пусть за всё, что связано с JavaScript (сборка модулей, Babel-конвертация, а также конкатенация и минификация JS-кода для продакшен-сборки) отвечает Webpack, а за всё остальное (например, компиляция sass и jade) пусть отвечает gulp.
Посмотрев документацию пакета gulp-webpack, я понял, что теперь все настройки webpack прописываются в gulpfile.js, а не в webpack.config.js, как при использовании "чистого" webpack. В этом вопросе я бы хотел рассмотреть случай, когда все настройки webpack останутся в webpack.config.js, а в gulpfile мы лишь пропишем запуск команды webpack для development-сборки JavaScript, и запуск продакшен-сборки JS.
На данный момент, пользуюсь примерно такой конфигурацией webpack.config.js:
const NODE_ENV = process.env.NODE_ENV || 'development';
const webpack = require('webpack');

module.exports = {

    context: __dirname + '/app',

    entry: "./main",

    output: {
        path: __dirname + '/public/js',
        filename: 'index.js'
    },

    watch: NODE_ENV === 'development',

    watchOptions: {
        aggregateTimeout: 100
    },

    devtool:NODE_ENV === 'development' ? 'cheap-inline-module-source-map' : null,

    plugins: [
        new webpack.DefinePlugin({
            NODE_ENV: JSON.stringify(NODE_ENV)
        })
    ],

    resolve: {
        modulesDirectories: ['node_modules'],
        extentions: ['', '.js']
    },

    resolveLoader: {
        modulesDirectories: ['node_modules'],
        moduleTemplates: ['*-loader', '*'],
        extentions: ['', '.js']
    },

    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader?presets[]=es2015',
            optional: 'runtime'
        }]
    }
};

if (NODE_ENV === 'production') {
    module.exports.plugins.push(
        new webpack.optimize.UglifyJsPlugin({
            compress:{
                warnings: false,
                drop_console: true,
                unsafe: true
            }
        })
    );
}

*

*Консольная комманда webpack запускает сборку модулей, при этом осуществляется конвертация в старый JS с помощью Babel. NODE_ENV по умолчанию имеет значение development и принимает это значение при запуске webpack.

*Продакшен-сборка выполняет также минификацию файла. Для запуска продакшен-сборки в Windows необходимо выполнить консольную команду SET NODE_ENV=production и затем - webpack.

Так как теперь за watching отвечает gulp, то соответствующие настройки из webpack.config.js можно убрать, а в gulpfile.js будет что-то вроде
gulp.task('watch', ['browser-sync', 'sass', 'jade', 'webpack'], function() {
    gulp.watch('development/jade/*.jade', ['jade']);
    gulp.watch('development/sass/*.+(sass|scss)', ['sass']);
    gulp.watch('development/es6/*.js', ['webpack']);
});

gulp.task('default', ['watch']);

Вопрос
Как будут выглядеть следующие два gulp-таска?

*

*Таск, выполнение которого эквивалентно выполнению консольной команды webpack для development-сборки JS-файлов.

*Таск, выполнение которого эквивалентно выполнению консольных комманд SET NODE_ENV=production → webpack для продакшен-сборки JS-файлов.

Wathcing файлов берёт на себя gulp. Все настройки webpack - в webpack.config.js; из gulpfile.js мы только запускаем нужные комманды вместо того, чтобы делать это из консоли.
Заготовка кода для ответа
Я добавлю заготовку gulpfile.js, чтобы Вам было писать меньше кода:
var  gulp = require('gulp'),
        webpack = require('gulp-webpack'),
        jade = require('gulp-jade'),
        sass = require('gulp-sass'),
        browserSync  = require('browser-sync'),
        autoprefixer = require('gulp-autoprefixer');

gulp.task('jade', function() {
    // не по теме
});

gulp.task('sass', function(){
    // не по теме
});

gulp.task('webpack', function() {
  return gulp.src('development/es6/entry.js')
    .pipe(webpack()) // запуск development-сборки JS-файлов в соответствии с настройками в webpack.config.js
    .pipe(gulp.dest('development/'));
});

gulp.task('browser-sync', function() {
    // не по теме
});

gulp.task('watch', ['browser-sync', 'sass', 'webpack'], function() {
    gulp.watch('development/es6/*.js', ['webpack']); // watching берёт на себя gulp
    gulp.watch('development/jade/*.jade', ['jade']);
    gulp.watch('development/sass/*.+(sass|scss)', ['sass']);
});

// development-сборка проекта; включает в себя вызов development-сборки webpack, что ранее делалось через консоль
gulp.task('default', ['watch']);

// production-сборка проекта, включает в себя вызов production-сборки webpack, что ранее делалось через консоль
gulp.task('build', ['sass', 'webpack'], function() {

    // Нужен таск, эквивалентный вызову из консоли  SET NODE_ENV=production -> webpack

    // ...

});

Обновление
Таск webpack не запускается с помощью exec = require('child_process').exec. Никаких ошибок нет; судя по выводу в консоль, выполнение gulp-таска происходит в обычном режиме, как будто я не писал никаких иструкций, связанных с webpack.
gulpfile.js
var gulp = require('gulp'),
    // ...
    exec = require('child_process').exec,
    // ...
    autoprefixer = require('gulp-autoprefixer');

// ...

gulp.task('webpack', function(cb){
    exec('webpack');
});

gulp.task('watch', ['browser-sync', 'jade', 'sass'], function() {
    gulp.watch('development/01_jade/**/*.jade', ['jade']);
    gulp.watch('development/02_sass/*.+(sass|scss)', ['sass']);
    gulp.watch('development/03_es6/*.js', ['webpack']);
});

gulp.task('default', ['watch']);

webpack.config.js (Используется webpack2)
'use strict';
const NODE_ENV = process.env.NODE_ENV || 'development';

module.exports = {

    context: __dirname + '/development',

    entry: './03_es6/main.js',

    output: {
        path: __dirname + '/development/js/',
        filename: 'index.js'
    },

    module: {
            rules: [
                {
                    test: /\.jsx?$/,
                    exclude: /node_modules/,
                    use: ['babel-loader']
                }
            ]
        }

    //watch: NODE_ENV === 'development'
};

A: 0) Nota Bene! Работу Вебпака можна модифицировать 2 способами 1-консольно (cli) и 2-в конфигах Вебпака
1) нужно решить где изменять настройки сборки, тоесть
а) хранить в .env в свойстве NODE_ENV и читать process.env.NODE_ENV
б) забить на это и делать модификацыю конфига Вебпака на лету
в) с Галпа запускать консольные команды спомощью exec = require('child_process').exec;
Лично я пользуюсь методом б)
```
var gulpWebpack = require('gulp-webpack');

...some code

gulp.task('webpack', function (done) {
    let webpackConfig = require('./webpack.config.js');

    //модифицируем конфиг как нам нужно, и если нужно
    webpackConfig.devtool = 'cheap-inline-module-source-map'; //исходя из 'development' ? 'cheap-inline-module-source-map' : null,
    webpackConfig.progress = true; // выводит прогресс

    //подключаем нжуные плагины
    //не забываем о тех что уже подклбчены в конфиге
    webpackConfig.plugins.push(
        new webpack.ProgressPlugin(function (percentage, msg) {
            // выводим в консоль Галпа Прогресс Вебпака в виде какой нам нравится
            // для удобства был использован сторонний модуль
            var log = require('color-log');
            log.single.info('----', Math.round(percentage * 100) + '%', msg)
        })
    );

    //если нужно удалить плагин, например CommonsChunk Plugin
    webpackConfig.plugins.map(function (plugin, index) {
       if (!!plugin.ident && !!plugin.ident.match('CommonsChunkPlugin')) {
            webpackConfig.plugins.splice(index, 1);
        }
    });

     gulp.src(['development/es6/entry.js', 'массив энтри поинтов', '...'])
          .pipe(gulpWebpack(webpackConfig))
          .on('error', () => {
             //код при ошибке
          })
          .pipe(gulp.dest('development/'))
          .on('end', () => {
                //код при окончании
                //например сказать об окончании Gulp Таска
                done();
          });
});

```
во 2 случае вам нужно будет поменять webpackConfig.devtool = null, так что можно просто создать 2 Таска Гапла где будет меняться этот параметр и вызывать 1 и ту же функцию сборки. В дальнейшем можно еще более разнообразить сборки


text:
Q: Bookmarklet to swap (live and testing) URLs in browser I used to use the following bookmarklet code to swap URLs between my site's staging server and live server, so I could test that staged pages had been successfully pushed live:
Staging URL: www.stage.site.com/folder/page.html
Live URL: www.site.com/folder/page.html
Here's the code for that bookmarklet; the script works in both directions: stage to live and live to stage:
javascript:if(location.host=='www.site.com')(location.href='http://www.stage.site.com'+location.pathname);if(location.host=='www.stage.site.com')(location.href='http://www.site.com'+location.pathname);
However, my site architecture has changed (CMS) and the staging URL is now quite different from the live URL:
Authoring URL: author.site.com/bucket1/bucket2/bucket3/folder/page.html
Live URL: www.site.com/folder/page.html
I haven't been able to figure out how to rewrite that bookmarklet code so it can handle the truncated pathname.

A: Try
javascript:if(location.host=='www.site.com')(location.href='http://author.site.com/bucket1/bucket2/bucket3'+location.pathname);if(location.host=='author.site.com')(location.href='http://www.site.com'+(location.pathname.split('/').slice(4).join('/')));

I'm assuming that bucket1/bucket2/bucket3/ remains constant, or else you'll need to figure out some devilishly clever way of storing that information.
You could also do a string replace on location.pathname, but I just felt like using split/slice/join.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android shell user has no access to /data/local/tmp even though it is the owner of that folder Some background info:
My phone is on android 9 and is rooted.
I am trying to build a flutter android app. When I execute flutter run, it fails with this error:
❯ flutter run
adb shell failed to write the SHA hash: ProcessException: Process "/home/wscp/Android/Sdk/platform-tools/adb" exited abnormally:
/system/bin/sh: can't create /data/local/tmp/sky.com.example.test_app.sha1: Permission denied
  Command: /home/wscp/Android/Sdk/platform-tools/adb -s da0d543 shell echo -n 75cf727e0e3b43efd656faf8cb2e4c779755b261 >
  /data/local/tmp/sky.com.example.test_app.sha1.
Error launching application on Redmi Note 7.

When I try running adb shell independently, I find that I cannot access /data/local/tmp.
I was able to perform the following actions since I have rooted my phone:
❯ adb shell
lavender:/ $ whoami
shell
lavender:/ $ ls -la /data/local/tmp
ls: /data/local/tmp: Permission denied
1|lavender:/ $ su
lavender:/ # ls -la /data/local/tmp
total 24
drwxrwxrwx 2 shell shell 4096 2019-10-25 10:23 .             <====== !!!
drwxr-x--x 4 root  root  4096 2019-10-12 16:29 ..
-rw-rw-rw- 1 root  root  9726 2019-10-12 16:29 build.prop
-rw-rw-rw- 1 root  root   968 2019-10-12 16:29 cmdline

The directory /data/local/tmp seems to belong to shell but shell itself is not able to access that directory!
I also attempted to use the scrcpy tool, which I have successfully used on another device of mine, and it resulted in a similar error:
❯ scrcpy
INFO: scrcpy 1.11 <https://github.com/Genymobile/scrcpy>
adb: error: failed to copy '/usr/local/share/scrcpy/scrcpy-server' to '/data/local/tmp/scrcpy-server': remote couldn't create file: Permission denied
/usr/local/share/scrcpy/scrcpy-server: 0 files pushed. 2.0 MB/s (25454 bytes in 0.012s)
ERROR: "adb push" returned with value 1

Why does this happen, and is there a fix?

A: It turns out to a selinux issue. I have having a similar problem with flutter and scrcpy. So, I went around online finding a solution and ended up on this gist,
https://gist.github.com/AwaisKing/009a64d92d476da33036efd61c961a7a
The trick is to rename the selinux context from system_data_file to shell_data_file, You will need a rooted android device for it. The exact command that worked for me was,
chcon -R u:object_r:shell_data_file:s0 /data/local/tmp


text:
Q: Looking for the simplest way to get elevation for a give wgs84 coordinate I started a project and write an application in java using geotools. I have an simple geoobject with the attributes latitude, longitude and altitude. Now i have to determine, wheather the geoobject is an aircraft or a car on a road.
I modeled my roads as LineStrings an my geoobjects a circle polygones. So i run a simple test, if the geoobject touchs or intersects the linestring, at the given coordinate. So far it works.
But some roads have an elevation. I found sample digital elevation model files, but don't know to handle them. Is there an easy way to get elevation data respectively is there another simple way? Need i software like postgis or somethin else?

A: You can download elevation data in raster format from this url
Load each tif into postgres with:-
 raster2pgsql -d -s 4326 -t 50x50 <TIFF>.tif <YOUR TABLE> | psql -n <YOUR DATABASE>

Then get an elevation with:-
SELECT ST_Value(rast,1,
                ST_GEOMFROMEWKT('SRID=4326;POINT('||lon||' '||lat||')')
               )

This abstracts most of the geometry stuff for you. You will need gdal, a postgres database with postgis installed and a connection from java.

A: Have a look at the GeoTools image tutorial to show you how to load a raster (which is what your DEM is)
    AbstractGridFormat format = GridFormatFinder.findFormat( rasterFile );
    //this is a bit hacky but does make more geotiffs work
    Hints hints = new Hints();
    if (format instanceof GeoTiffFormat) {
        hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
    }
    reader = format.getReader(rasterFile, hints);
    Layer rasterLayer = new GridReaderLayer(reader, rasterStyle);

You can use the evaluate methods on the coverage to get back the raster value(s) at a point.


text:
Q: Mocking a REST service There "will" be a REST API written in Java that I should connect to it from my Rails application. So I need the client and I am using Net::HTTP. But the problem is that the Java service is not written yet! It is in progress by other co-workers! But still I don't want to be blocked and want to somehow mock it or something and write my code.
I do know what the service uri will look like, what params it will have, what JSON response it will return, etc... but I just don't have the real working service to connect to.
Is there a way I can mock it and keep coding for my side? What do you suggest?

A: look at http://tomashanacek.github.io/mock-server/ - simple mock server for REST API

A: I would find another operating REST service that you can connect to and get data from.  Once you have that code written, just adapt it to the service that your co-workers are writing afterwards.

A: Try my mock server:
https://mockserver.codeplex.com/
It's easy to use and extend.


text:
Q: Exception coming with HttpUrlConnection in android I am trying the following code to post a json.
It has worked once but now it is throwing the following Exception message: "failed to connect to /xx.xx.xx.xx (port XXXXX) after 5000ms"
What is the problem here?
public void sendToDp(PayloadEntity pEntity) {

    URL url = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(PreferenceHelper.getInstance().getBaseUrl());
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(5000);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        OutputStream os = new BufferedOutputStream(connection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(pEntity.getJsonString());
        writer.flush();
        writer.close();
        os.close();
        int responseCode = connection.getResponseCode();
        listener.onReceive(responseCode == HttpsURLConnection.HTTP_OK, pEntity);
    } catch (MalformedURLException mue) {
        listener.onReceive(false, pEntity);
    } catch (Exception e) {
        listener.onReceive(false, pEntity);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

Edit: Adding the stacktrace:
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err: java.net.SocketTimeoutException: failed to connect to /10.41.66.248 (port 11890) after 5000ms
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:169)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at java.net.Socket.connect(Socket.java:882)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:139)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:152)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:208)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.NetworkHelper.sendToDp(NetworkHelper.java:56)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager$LooperThread$1.handleMessage(QueueManager.java:129)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager.onReceive(QueueManager.java:97)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.NetworkHelper.sendToDp(NetworkHelper.java:71)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager$LooperThread$1.handleMessage(QueueManager.java:129)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager.onReceive(QueueManager.java:97)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.NetworkHelper.sendToDp(NetworkHelper.java:71)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager$LooperThread$1.handleMessage(QueueManager.java:129)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager.onReceive(QueueManager.java:97)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.NetworkHelper.sendToDp(NetworkHelper.java:71)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager$LooperThread$1.handleMessage(QueueManager.java:129)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager.onReceive(QueueManager.java:97)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.NetworkHelper.sendToDp(NetworkHelper.java:71)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager$LooperThread$1.handleMessage(QueueManager.java:129)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager.onReceive(QueueManager.java:97)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.NetworkHelper.sendToDp(NetworkHelper.java:71)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager$LooperThread$1.handleMessage(QueueManager.java:129)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager.onReceive(QueueManager.java:97)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.NetworkHelper.sendToDp(NetworkHelper.java:71)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager$LooperThread$1.handleMessage(QueueManager.java:129)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager.onReceive(QueueManager.java:97)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.NetworkHelper.sendToDp(NetworkHelper.java:71)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager$LooperThread$1.handleMessage(QueueManager.java:129)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.QueueManager.startUpload(QueueManager.java:62)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at network.Logger.logUpdates(Logger.java:59)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at service.PullHelper.init(PullHelper.java:61)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at service.SyncService.onHandleIntent(SyncService.java:26)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.Looper.loop(Looper.java:135)
03-02 17:22:34.793 24578-24758/com.vkc.main W/System.err:     at android.os.HandlerThread.run(HandlerThread.java:61)

A: Try to use a better http library, like Volley, it's faster to run and simpler to debug than HttpUrlConnection.
Your code will be look like:

JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, urlLink, new JsonObject(pEntity.getJsonString()), new Response.Listener() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    //RESPONSE
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                   //ERROR
                }
            });

Volley
About Volley be faster

A: The problem is that your app cannot get through the network and access the URL. The problem may be:

*

*Your network connection is offline.

*The site which you are trying to access is down.

*You are facing either firewall or proxy issues.

A: It is throwing java.net.SocketTimeoutException because you have set connection time out to some value
        connection.setConnectTimeout(5000);
System try to establish connection to Your Url till the timeout value.If it fail to establish the connection with in the time you have set it will throw the "SocketTimeoutException"

A: I think this problem coming in your case(as I was facing) because your service is running on localhost(failed to connect to /10.41.66.248 (port 11890) after 5000ms ). I mean on local network and you are trying to connect from outer network(Like mobile data). But local network doesn't give access to other network just because some security reasons.
So connect your device to local wi-fi network(same localhost internet connection), then run your app.
Hope this will solve your problem....


text:
Q: Postgresql regex replace numbers to asterisks I use Postgresql and need to replace numbers to asterisk at database layer. Howerver I'm new to learn regex and seems to be hard to do this with my current knowledge.
I will have in my database 16 numbers varchar and I need to replace middle numbers with asterisk.
Example.
123467812345678 -> 12**********5678
Could someone tell me how regex for this should look like in postgresql ?
Thanks in advance

A: Thanks to @Wiktor Stribiżew:
SELECT regexp_replace('123467812345678', '(?<=..).(?=....)', '*','g');


text:
Q: MySQL 5.7 - Error on linked list query - expression was expected near "(" Here is my query to display the orderd list :
SELECT  @r := (
        SELECT  id
        FROM    t_list
        WHERE   parent = @r
        ) AS id
FROM    (
        SELECT  @r := 0
        ) vars,
        t_list

Static analysis:
2 errors were found during analysis.
An expression was expected. (near "(" at position 115)
Unexpected token. (near "(" at position 115)
This for the second FROM.
(https://explainextended.com/2009/03/25/sorting-lists/)


text:
Q: Django - how to update elements within a list in a single pUT request I am looking to update the objects in a list as one PUT request, how would I go about doing it? I've made some progress but I can't seem to figure it out.
The list to PUT to perform updates could be some of the objects in the table, or all of them. But I am aiming to, in one request, submit a list of share elements, and have all the elements that match those in the table be updated with the new values, if any, of the elements within the list of this one PUT request.
Models.py
class Share(models.Model):
    ShareName = models.CharField(max_length=100, unique=True, default="N/A")
    ISINCode = models.CharField(max_length=100, primary_key=True, default="N/A")
    Price = models.DecimalField(decimal_places=6, max_digits=9, default=0.000000)

Serializers.py
class ShareSerializer(serializers.ModelSerializer):
    """
    Serializer for Share
    """

    class Meta:
        model = Share
        fields = ('ShareName', 'ISINCode', 'Price')

Views.py
class ShareViewSet(ModelViewSet):
    authentication_classes = []
    permission_classes = []
    queryset = Share.objects.all().order_by('ISINCode')
    # serializer_class = ShareSerializer
    paginator = None

    def get_serializer(self, *args, **kwargs):
        if "data" in kwargs:
            data = kwargs["data"]

            # enable list posting
            if isinstance(data, list):
                kwargs["many"] = True

        return super(ShareViewSet, self).get_serializer(*args, **kwargs)

I've read through the docs here https://www.django-rest-framework.org/api-guide/serializers/#listserializer and also figured out one way to probably go about it is to override get_serializer_class, add a new listSerializer and add the logic to read the elements within, but I can't seem to figure that part out.
Override in ShareModelViewSet
def get_serializer_class(self):
    serializer = ShareSerializer
    if self.action == 'perform_update':
        serializer = ShareListSerializer
    return serializer

What I currently have as a ListSerializer, not sure I am doing this right.
class ShareListSerializer(serializers.ListSerializer):
    def update(self, validated_data, instance):

        list_of_instances = []

        for each_update in validated_data:
            ISINCode = each_update.get("ISINCode")

            Share_object: Share = Share.objects.filter(
                pk=ISINCode
            ).first()

            del validated_data["ISINCode"]

            if Share_object:
                list_of_instances.append(
                    Share.objects.update(Share_object, validated_data)
                )

            else:
                list_of_instances.append(Share.objects.create(validated_data))

        return list_of_instances

How the PUT URL will work?
On another but related topic, for getting and posting and for updating individual elements outside of a list, manipulating the url http://localhost:8000/api/share was how it was to be done, but how would it work for elements within a list? http://localhost:8000/api/share/ would work for updating a single share element, but for a list, how would you reference it in a PUT request? http://localhost:8000/api/share/ just tries to apply the changes in one pk to every element in the list. http://localhost:8000/api/share doesn't work for PUT requests like that.
Example of how the JSON in the PUT request I want to work is formatted.
[
    {
        "ShareName": "Shareabc,
        "ISINCode": "123456",
        "Price": 23.35
    },
    {
        "ShareName": "Sharedef,
        "ISINCode": "253525",
        "Price": 11.61
    },

]


text:
Q: Django 1.8.3 Running test fails on database creation I am trying to run "manage.py test" but i get the following error message:
(env)user@comp:~/Documents/repo/cloud/webapp$ python manage.py test
Creating test database for alias 'default'...
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
    super(Command, self).execute(*args, **options)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
    failures = test_runner.run_tests(test_labels)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/test/runner.py", line 210, in run_tests
    old_config = self.setup_databases()
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/test/runner.py", line 166, in setup_databases
    **kwargs
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/test/runner.py", line 370, in setup_databases
    serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 368, in create_test_db
    test_flush=not keepdb,
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
    return command.execute(*args, **defaults)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle
    created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps
    cursor.execute(statement)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/user/.virtualenvs/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "auth_user" does not exist

I have a custom user model. I have read that this problem occurs because Django migrates your app before it migrates auth which causes an error because the custom user model references the auth.user model. However i didn't find a fix for this.

A: You have a model in an app without migrations, with a foreign key to auth.User. As noted in the docs:

Be aware, however, that unmigrated apps cannot depend on migrated apps, by the very nature of not having migrations. This means that it is not generally possible to have an unmigrated app have a ForeignKey or ManyToManyField to a migrated app; some cases may work, but it will eventually fail.

You have to add migrations for the app with a foreign key to your user model.

A: Try doing the below commands first:
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py syncdb

If you make any changes to your model definitions in models.py you have to run SQL migration queries to move your database to your new model.


text:
Q: Filtering DAX to another table using current row's value I have three tables, one a standard date table and two children tables, one budget and one forecast.  I am using power pivot and would like to have a listing of the years / months across the top, and multiple brands going down the rows with the forecast and budget displayed in the grid.  When I create the measure on the forecast table to sum the budget, it sums it correctly down to the month but when I view the pivot table, I get the summed value across all brands instead of filtering to the current row's brand:
    2017
    October
Row Labels  forecast    Budget
Brand A $950,000.15         ($3,884,649.00)
Brand B $3,500,000.00       ($3,884,649.00)
Brand C $1,650,000.00       ($3,884,649.00)
Brand D $980,000.00         ($3,884,649.00)
Brand E $100,000.00         ($3,884,649.00)
Brand F $183,465.00         ($3,884,649.00)
Grand Total $7,363,465.15   ($3,884,649.00)

My DAX formula looks like this:
Budget:=CALCULATE(Sum(Budget[SummedAmount]), values(Budget[Brand Code])= ForecastEntries[Brand Code])

How can I get the ~3,884,649 summing just over the current brand's brand code?

A: The simplest way to achieve what you want is to add a dimension table Brands to the model which contains one row for each brand and then relate the Budget and Forecast tables to it on [Brand Code].
The hard way to do it is to set up your measure like this:
Budget:=CALCULATE(
            SUM(Budget[SummedAmount]),
            FILTER(
                Budget,
                Budget[Brand Code] =
                    IF(HASONEVALUE(Forecast[Brand Code]),
                       VALUES(Forecast[Brand Code]),
                       Budget[Brand Code])
            )
         )

The second approach quickly becomes messy as there are more dimensions.


text:
Q: How to check server configuration?
Possible Duplicate:
Documenting server details

How do I check server configuruation such as Ram, processor, disks etc I'm using CentOS?

A: Generically, you'd use dmidecode. There's quite a bit of output, so a more specific output can come from the script documented here:
#!/bin/bash
# hwcollect.sh - Collect general system information

# Hostname
echo -e "$HOSTNAME \n"

# Display system manufacturer, model, serial and other attributes
dmidecode -t 1 | egrep '(Manufacturer|Product|Serial)'
dmidecode -t 3 | egrep '(Height)';
dmidecode  -t processor| egrep '(Socket|Version)'
# Calculate installed RAM
dmidecode -t 17 | awk '( /Size/ && $2 ~ /^[0-9]+$/ ) { x+=$2 } END{ print "\t" "Installed Ram: " x "MB"}'

echo " "
echo "Disk Information"
# Filesystem mounts
df -h
# Display disk partition table
fdisk -l

That will produce results that look like:
[root@xetra ~]# ./hwcollect.sh
Pseudo-terminal will not be allocated because stdin is not a terminal.
Test_Server

        Manufacturer: HP
        Product Name: ProLiant DL380 G6
        Serial Number: 2UX12345KT
        Height: 2 U
        Socket Designation: Proc 1
        Version: Intel(R) Xeon(R) CPU X5570 @ 2.93GHz
        Upgrade: Socket LGA1366
        Socket Designation: Proc 2
        Version: Intel(R) Xeon(R) CPU X5570 @ 2.93GHz
        Upgrade: Socket LGA1366
        Installed Ram: 32768MB


text:
Q: testing dao with hibernate genericdao pattern with spring.Headache in my journey of learning hibernate i came across an article on hibernate site. i' learning spring too and wanted to do certain things to discover the flexibility of spring by letting you implement you own session.yes i don't want to use the hibernateTemplate(for experiment). and i'm now having a problem and even the test class.I followed the article on the hibernate site especially the section an "implementation with hibernate"
so we have the generic dao interface :
public interface GenericDAO<T, ID extends Serializable> {

T findById(ID id, boolean lock);

List<T> findAll();

List<T> findByExample(T exampleInstance);

T makePersistent(T entity);

void makeTransient(T entity);

}
it's implementation in an abstract class that is the same as the one on the web site.Please refer to it from the link i provide.i'll like to save this post to be too long
now come my dao's messagedao interface
package com.project.core.dao;

import com.project.core.model.MessageDetails;
import java.util.List;

public interface MessageDAO  extends GenericDAO<MessageDetails, Long>{
//Message class is on of my pojo
public List<Message> GetAllByStatus(String status);

}

its implementation is messagedaoimpl:
public class MessageDAOImpl extends GenericDAOImpl <Message, Long> implements MessageDAO {

// mySContainer is an interface which my HibernateUtils implement
  mySContainer sessionManager;

/**
 *
 */
public MessageDAOImpl(){}

/**
 *
 * @param sessionManager
 */
public MessageDAOImpl(HibernateUtils sessionManager){
this.sessionManager = sessionManager;
 }
 //........ plus other methods
}

here is my HibernatUtils
public class HibernateUtils implements SessionContainer {
private final SessionFactory sessionFactory;
private Session session;

public HibernateUtils() {
    this.sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}

public HibernateUtils(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

/**
 *
 * this is the function that return a session.So i'm free to implements any type of session in here.
 */
public Session requestSession() {
//        if (session != null || session.isOpen()) {
//            return session;
//        } else {
        session = sessionFactory.openSession();

//        }
    return session;
  }
}

So in my understanding while using spring(will provide the conf), i'ld wire sessionFactory to my HiberbernateUtils and then wire its method RequestSession to the Session Property of the GenericDAOImpl (the one from the link provided).

here is my spring config core.xml
<bean id="sessionManager" class="com.project.core.dao.hibernate.HibernateUtils">
    <constructor-arg ref="sessionFactory" />
</bean>
<bean id="messageDao" class="com.project.core.dao.hibernate.MessageDAOImpl">
    <constructor-arg ref="sessionManager"/>

    </bean>
<bean id="genericDAOimpl" class="com.project.core.dao.GenericDAO">
    <property name="session" ref="mySession"/>
    </bean>
    <bean id="mySession" factory-bean="com.project.core.dao.SessionContainer" factory-method="requestSession"/>

now my test is this
public class MessageDetailsDAOImplTest  extends AbstractDependencyInjectionSpringContextTests{

 HibernateUtils sessionManager = (HibernateUtils) applicationContext.getBean("sessionManager");
MessageDAO messagedao  =(MessageDAO) applicationContext.getBean("messageDao");

static Message[] message = new Message[]
{
    new Message("text",1,"test for dummies 1","1234567890","Pending",new Date()),
    new Message("text",2,"test for dummies 2","334455669990","Delivered",new Date())
};

public MessageDAOImplTest() {
}

@Override
protected String[] getConfigLocations(){
    return new String[]{"file:src/main/resources/core.xml"};
}

  @Test
  public void testMakePersistent() {
      System.out.println("MakePersistent");
     messagedao.makePersistent(message[0]);
     Session session = sessionManager.RequestSession();
     session.beginTransaction();
     MessageDetails fromdb = ( Message) session.load(Message.class, message[0].getMessageId());
     assertEquals(fromdb.getMessageId(), message[0].getMessageId());
     assertEquals(fromdb.getDateSent(),message.getDateSent());
     assertEquals(fromdb.getGlobalStatus(),message.getGlobalStatus());
     assertEquals(fromdb.getNumberOfPages(),message.getNumberOfPages());

  }

i'm having this error

exception in constructor testMakePersistent(java.lang.NullPointerException at com.project.core.dao.hibernate.MessageDAOImplTest)

with this stack :        at com.project.core.dao.hibernate.MessageDAOImplTest.(MessageDAOImplTest.java:28)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at junit.framework.TestSuite.createTest(TestSuite.java:61)
        at junit.framework.TestSuite.addTestMethod(TestSuite.java:283)
        at junit.framework.TestSuite.(TestSuite.java:146)
        at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:481)
        at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1031)
        at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:888)
))
How to actually make this one work.I know this is a lot to stuffs and i'm thanking you for reading it.Please give me a solution.How would you do this? thanks

A: Greetings... I think you are making it more complicated than it is. :)
If you are using Spring and Hibernate (which you are), you don't really need to create your own HibernateUtils to manage the session. HibernateUtils is almost required if you don't use Spring, or else it seems redundant. It is tedious, it is one extra code you need to maintain, and you probably are not going to get it right. Your HibernateUtils doesn't seem to be implemented correctly, by the way.
Here's how I would do it:-

*

*You need to create a sessionFactory bean:-
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
    <list>
        <value>// .. hbm files, omitted for brevity</value>
    </list>
</property>
<property name="hibernateProperties">
    // .. dialect, etc... omitted for brevity
</property>
</bean>

*Wire this sessionFactory into your DAO (, and you need a setter in your DAO too):-
<bean id="messageDao" class="com.project.core.dao.hibernate.MessageDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

*To acquire the connection in your dao, just do sessionFactory.getCurrentSession(). That's it.
You do the same thing by wiring the sessionFactory into your testcase.
Here's some reference if you wish to know how to integrate Spring with Hibernate:
http://static.springsource.org/spring/docs/2.5.x/reference/orm.html

A: It seems to be failing to invoke the MessageDAOImplTest constructor, but since it is empty, I'm guessing the problem actually lies in the initialization of the member variables. Which line is line 28? You can try moving the initialization logic to the constructor body and step through it with a debugger to pinpoint the problem.
By the way, your approach has a problem in that the DAOs are singletons shared among all threads, but Hibernate sessions must not be shared across threads, so you need to store them as a ThreadLocal. If you use Spring for session management, this happens automatically. Maybe this isn't important to you because this is an "experiment", but I thought I'd bring it up.

A: The first problem I can see, is that class GenericDaoImpl is supposed to be abstract (according to the hibernate link you provided), and you try to instantiate it in your spring config (by declaring bean 'genericDAOImpl').
You can set the session property directly on the 'messageDao' bean (obviously because MessageDAOImpl extends GenericDAOImpl). So I guess your spring config should look more like this:
<bean id="sessionManager" class="com.project.core.dao.hibernate.HibernateUtils">
  <constructor-arg ref="sessionFactory" />
</bean>
<bean id="messageDao" class="com.project.core.dao.hibernate.MessageDAOImpl">
  <constructor-arg ref="sessionManager"/>
  <property name="session" ref="mySession"/>
</bean>
<bean id="mySession" factory-bean="com.project.core.dao.SessionContainer" factory-method="requestSession"/>

I hope this helps. This was my first answer on SO :-).


text:
Q: How generate an M..N range with a wrapper for RandomRange 0..N-1? Understanding an existing implementation Need help with creating an improved version of the RandomRange procedure called BetterRandomRange. RandomRange produces an integer between 0 and N - 1. For the BetterRandomRange procedure, I have to make it generate a number between M and N (m is passed in EBX, and N in EAX).
I found a code block from the internet, but I don't understand what's happening in it. Can anyone please explain it?
.code

main PROC

mov ebx, -300       ; lower bound (m)
mov  eax, 100       ; upper bound (n)
call BetterRandomRange
call WriteInt

;; Editor's note: missing ret
;; so main falls through into a tailcall to BetterRandomRange

BetterRandomRange PROC
    sub ebx, eax
    xchg ebx, eax
    call RandomRange
    neg ebx
    sub eax, ebx
    call writeint
    ret
BetterRandomRange ENDP

Why is the "neg ebx" instruction necessary? Why do we need to make EBX negative?


text:
Q: GridView gravity won't change I am trying to change the gravity of a GridView whenever I click a button but the app crashes when deployed. I'm not sure why this occurs when the GridView has been declared in the XML layout.

Attempt to invoke virtual method 'android.view.ViewGroup$LayoutParams android.widget.GridView.getLayoutParams()' on a null object reference

sw600dp/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/btn_moveup"
        android:text="move up"
        android:background="@android:color/transparent"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_gravity="top"
        android:onClick="moveup_click"
        />

    <GridView
        android:id="@+id/abslistview_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:numColumns="auto_fit"
        />

    <Button
        android:id="@+id/btn_movedown"
        android:text="move down"
        android:background="@android:color/transparent"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_gravity="bottom"
        android:onClick="movedown_click"
        />
</LinearLayout>

MainActivity.java
    public class MainActivity extends Activity {
    Activity mActivity;
    private Button btnUp;
    private Button btnDown;
    private GridView gridMain;

    private AbsListView absListView;
    private ArrayAdapter<MainItem> adapter;
    private ArrayList<MainItem> mainArrayList;

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

        absListView = findViewById(R.id.abslistview_main);
        settingData();

        adapter = new AbsListViewAdapter(this, R.layout.item_abslistview, mainArrayList);
        absListView.setAdapter(adapter);
    }

    private void settingData() {
        mainArrayList = new ArrayList<>();

        mainArrayList.add(new MainItem(R.drawable.ic_circle, getResources().getString(R.string.item_1)));
        mainArrayList.add(new MainItem(R.drawable.ic_star, getResources().getString(R.string.item_2)));
        mainArrayList.add(new MainItem(R.drawable.ic_square, getResources().getString(R.string.item_3)));
        mainArrayList.add(new MainItem(R.drawable.ic_triangle, getResources().getString(R.string.item_4)));
        mainArrayList.add(new MainItem(R.drawable.ic_rectangle, getResources().getString(R.string.item_5)));
        mainArrayList.add(new MainItem(R.drawable.ic_crescent, getResources().getString(R.string.item_6)));
    }

    public void moveup_click(View view) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) gridMain.getLayoutParams();
        gridMain = findViewById(R.id.abslistview_main);
        if (params.gravity == Gravity.BOTTOM) {
            gridMain.setGravity(Gravity.CENTER_VERTICAL);
            btnDown.setVisibility(View.VISIBLE);
        } else if (params.gravity == Gravity.CENTER_VERTICAL) {
            gridMain.setGravity(Gravity.TOP);
            btnUp.setVisibility(View.GONE);
        }
    }
}

A: You have buttons that fire the moveup_click() function.
In that function, you first want LayoutParams of GridView and after that you initialise the gridview itself.
This is not the right sequence.
To solve it, you can move the gridMain = findViewById(R.id.abslistview_main);the oncreate function or BEFORE LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) gridMain.getLayoutParams();.
 -

A: You have also made a mistake in the create method
absListView = findViewById(R.id.abslistview_main);

Remove this line with
gridMain = findViewById(R.id.abslistview_main);


text:
Q: Connectedness of a metric space implies connectedness of the corresponding Hausdorff hyperspace
If $(X,d)$ is a connected metric space, show that $(\mathscr H(X),h)$ is also connected.

where h is the Hausdorff distance, define by max$\{d(A,B),d(B,A)\}$
and $d(A,B):=$max$\{$min$\{d(a,b)|a\in A\}|b\in B\}$
$\mathscr H(X)$ is the collection of all compact subset of $X$.

I know what connected means, but it's too hard for me to figure out what is connected actually means in fractal geometry.

A: Here is a complete proof. It follows the idea in my comment of Hagen von Eitzen's answer. It is more complicated, but I also steamline his idea, so in the end it is not too long.
Let $(X,d)$ be a connected metric space. Let $n \geq 1$. Then $(X^n, d_n)$ is a connected metric space, where $d_n (x, y) = \max_i d (x_i, y_i)$. Let $\pi_n : \ X^n \mapsto \mathcal{H} (X)$ be defined by:
$$\pi_n (x) = \bigcup_{i=1}^n \{x_i\}.$$
Then $\pi_n$ is $1$-Lipschitz, and as such is continuous. Hence, $\pi_n (X^n)$ is a connected space. But $\pi_n (X^n)$ is exactly the set of compact subsets of $X$ of cardinal at most $n$.
Let $\mathcal{U}$ be the connected component which contains $\pi_1 (X^1)$. Then it contain $\pi_n (X^n)$ for all $n$ (since the intersection of $\pi_n (X^n)$ with $\mathcal{U}$ is non-empty, $\pi_n (X^n)$ is connected, and $\mathcal{U}$ is a connected component). Hence, $\mathcal{U}$ contains $\bigcup_n \pi_n (X^n)$. Since $\mathcal{U}$ is closed, it also contains $\overline{\bigcup_n \pi_n (X^n)}$.
But $\overline{\bigcup_n \pi_n (X^n)} = \mathcal{H} (X)$ ! Hence, $\mathcal{H} (X)$ is connected.
NB: Hagen von Eitzen's answer can essentially be written in a much shorter fashion:
"The map $x \mapsto \{x\}$ is an isometry from $X$ to $\mathcal{H} (X)$. Since, $X$ is connected, its image is also connected."

A: Assume $\mathscr H(X)=\mathscr U\cup \mathscr V$ with disjoint $h$-open sets $\mathscr U,\mathscr V$. Let $U=\{\,x\in X\mid \{x\}\in \mathscr U\,\}$, $V=\{\,x\in X\mid \{x\}\in \mathscr V\,\}$. Then $U\cap V=\emptyset$ and (since singletons sets are compact) $X=U\cup V$.
If $x\in U$ then there exists $\epsilon>0$ such that $A\in\mathscr U$ for any compact $A$ with $h(A,\{x\})<\epsilon$. Specifically $\{y\} \in \mathscr U$ whenever $d(y,x)<\epsilon$. We conclude that $U$ is open and by the same argument $V$ is open.
By connectedness, one of $U,V$ must be empty, say $U=\emptyset$.
Remains to show that $\mathscr U$ is empty...


text:
Q: BehaviorSpace Netlogo- Measure runs using these reporters I am simulating a classroom and calculating the energy consumed by lights, fans and ACs. Now I am running my simulation in behavior space so that after each run the energy consumed is shown. The energy consumed is in a procedure.
to energy-calculation

ask lights [ ifelse ( l-on? )  [ set l-energy (light-on-duration * light-
wattage) ][ set l-energy 0 ] ]
ask fans [ ifelse ( f-on? ) [ set f-energy ( fan-on-duration * fan-wattage
)] [ set f-energy 0 ] ]
ask acs [ ifelse ( a-on? ) [ set a-energy (ac-on-duration * ac-wattage) ] [
set a-energy 0 ] ]

let light-e sum [l-energy] of lights
let fan-e sum [f-energy] of fans
let ac-e sum [a-energy] of acs

set t-light ( light-e / (60000))
set t-fan ( fan-e / (60000))
set t-ac ( ac-e / ( 60000 ) )

show (word "sum of ac energy = " ac-e )

set t-energy ( t-light + t-fan + t-ac )

end

In the 'Measure runs using these reporters' section if I am giving energy-calculation then it shows error experiment aborted due to syntax error.
What should I do to solve this?


text:
Q: Discord.py rewrite have bot respond to DMs I am trying to have my bot respond to a DM message that accepts the rules.
Here is what I have so far:
@bot.event
async def on_member_join(member):
  role = discord.utils.get(member.servers.roles, name='Newcomers') #get role
  await bot.add_roles(member, role) #give the role to the user
  await bot.member.send("Welcome to the Moderator Bot Server! I will need you to first read the rules then accept by using the `mbs accept` in this DM")#send a message
  #wait for accept

A: Here is my code for your query:
role = discord.utils.get(member.guild.roles, name='Newcomers') #get role
await member.add_roles(role) #give the role to the user
await member.send("Welcome to the Moderator Bot Server! I will need you to first read the rules then accept by using the `mbs accept` in this DM")#send a message

def check(m):
    return isinstance(m.channel, discord.DMChannel) and m.author == member and m.content == "mbs accept"

await bot.wait_for("message", check=check)
#do stuff here; this line runs once the user types `mbs accept` in the DM (maybe you want to send the user a message that thanks them for accepting the rules?)

The first 3 lines are what you provided us, although I updated them so they work for discord.py-rewrite (read more on the discord.py rewrite docs here.
Check Function
Then, the check function first checks if the channel the message was sent in is a DM, it checks if the author is the member, and it checks if the message content is mbs accept.
Wait For Function
Then, it waits_for the message, using the check we provided. Read more on the wait_for function here.
PS: Sorry for the late response, if you have any unforeseen errors or have questions, feel free to follow up!


text:
Q: How to iterate over a dictionary for Ansible's win_nssm module? Ansible v2.10.x
I'm trying to use Ansible to start our Windows application services using win_nssm.
I want to use win_nssm. I have a dictionary that looks like this now (but ic can change based on the answer).
web_services:
  Web:
    description: "Web service"
    app_dir: "C:\\Myfolder\\Web"
    app_command: "app.js Web env=%NODE_ENVIRONMENT% port=8080 ssl_port=8443"
    dependency: ""
  PrintService:
    description: "Print service"
    app_dir: "C:\\Myfolder\\Web"
    app_command: "app_service.js SERVICE_NAME=PRINTSERVICE"
    dependency: "Web"

How can I iterate over the above dictionary for win_nssm?
- name: Create services
  win_nssm:
    name: "{{ the item key }}"
    app_parameters_free_form: "Description={{ item description value }}"
    application: "{{ item app_dir value }}/{{ item app_command value }}"
    dependency: "{{ item dependency value }}"
  loop: ????

Does that make sense?

A: With your updated data structure, you could write something like this:
    - name: Create services
      win_nssm:
        name: "{{ item.0 }}"
        app_parameters_free_form: "Description={{ item.1.description }}"
        application: "{{ item.1.app_dir }}/{{ item.1.app_command }}"
        dependency: "{{ item.1.dependency }}"
      loop: "{{ web_services.items() }}"

The .items() method on a dictionary returns a list of (key, value)
pairs, so within the task, item.0 (aka item[0]) is the key, and
item.1 is the associated dictionary.


text:
Q: What does "fall for a bluff" mean? New York Times (August 6) reported under the title, "25 years after Gardner Museum heist, video raises questions" that Federal officials released a video tape recording a guardsman, Richard Abath's actions on his duty at the Isabella Stewart Gardner Museum in the morning of March 18, 1990, the day 13 artworks including three Rembrandts and a Vermeer were stolen from the Museum. It reads:

In 1990, Richard Abath, a 23-year-old who, while moonlighting as a security guard, allowed two thieves posing as police officers to enter the Isabella Stewart Gardner Museum here. For 25 years, his decision to buzz in the men who carted away $500 million worth of art has been largely treated as the hapless act of a rookie watchman who fell for a bluff.

I can understand "fall from a bluff," but I don't know what "fall for a bluff" means. By Googling, I barely found "fell for a  bluff" in the Sport Rack's article (March 15, 2015):

"The Stormers finally surrendered their unbeaten record when they were defeated 28-19 by the visiting New Zealand side, the Chiefs, in the Super Rugby match at Newlands on Saturday afternoon. After the match, Stormers captain Duane Vermeulen said his side fell for a Chiefs bluff."

I don't find "fall for a bluff" as an idiom in English dictionaries at hand, nor its currency on Google Ngram. What does it mean? Is this a popular English idiom?

A: It's a reference to the card game poker. To bluff (from Wikipedia) is to

In the card game of poker, a bluff is a bet or raise made with a hand which is not thought to be the best hand. To bluff is to make such a bet.

To fall for a bluff is to fall for a deceitful proposition.

A: Bluff definition from Google:

An attempt to deceive someone into believing that one can or is going
  to do something.

So basically it is saying that a rookie watchman fell for a bluff (fell for an attempt to deceive him).


text:
Q: Splitting javascript object to normal String with = sign How can I dynamically convert a json object to the following manner
I do have
{ eligible: true, qualified:true }

but I need to make it like this
eligible= true, qualified=true

A: You can use Object.entries to get a two dimensional array of object and then use Array.prototype.map to join the array element (key, value) with an =.
Finally join the array with a , to get the expected output.

var x = { eligible: true, qualified:true };

var newX = Object.entries(x).map(el => el.join("=")).join(", ");

console.log(newX);

A: If we can assume the string is a valid JSON object (yours is missing the quotes) you can parse the string as JSON and then use Object.entries to get the key value pairs which can then be mapped and joined down to your desired string output.

const jsonStr = '{ "eligible": true, "qualified":true }'
const jsonObj = JSON.parse(jsonStr)

console.log(Object.entries(jsonObj).map(e => e.join('=')).join(', '))

A: You can get entries of object and change the key/value to string using reduce

let obj = { eligible: true, qualified:true }

let str = Object.entries(obj).reduce((op,[key,value],index,arr)=>{
  op+= `${key}=${value}${index !== arr.length-1 ? ',' : ''} `
  return op
},'')

console.log(str.trim())


text:
Q: Linux : How to detect a process that consumes the maximum memory and kill it? Linux : How to detect a process that consumes the maximum memory and kill it using std::thread? I am new to C++ coding, therefore an explanation with C++ code to implement the function would be highly appreciated.
The exact text of the assignment is to write a C++ code that monitors the memory usage of the device and it shall be aware of the device reached in its targeted maximum memory usage. When the thread detects this condition, it shall be able to identify the process which is taking more memory and do the following actions, Check the process against application priority list. If the process is in low priority category, stop the process and restart. Otherwise, inform the user about the memory over run is happened because of the identified process, take the restart based on the user confirmation. Restart shall be device restart or process restart, that will be decided based on the nature of process which is caused this condition · The details shall be captured in the logging file

A: You might want to look at the Linux OOM (Out-of-memory) killer.
From this link:

It is the job of the linux 'oom killer' to sacrifice one or more processes in order to free up memory for the system when all else fails.

So, technically, you don't need to do anything about it. ;-)
But, if you still want to write it yourself according to your own criteria for choosing and killing the victim process, you may create a Linux service (which run in the background all the time) to do that. The sample code is there in the linked article.
Regarding your std::thread point, if you already have an executable and you want to spawn a dedicated thread to do this, yes, you can do that also. The logic will simply move into that thread.
Additional reading:
How to Configure the Linux Out-of-Memory Killer


text:
Q: How to run a function with a setTimeout() callback inside iframe when this setTimeout() calls another setTimeout() in parent? I have a dynamically created iframe on my page. Like this:
var iframe = document.createElement('iframe');
iframe.setAttribute("id","myIframe");
iframe.src = "iframePage.html";
document.body.appendChild(iframe);

Inside the "iframePage.html", I have the same scriptfile.js that runs on mainPage.html. So, I can call all the functions inside one or another page.
In this scriptfile.js, I have this function that is called by a button on "iframePage.html". The function removes the iframe from DOM in 1 second! Just like this:
function closeAndRemoveIframe() {
   setTimeout(function() {
      var myIframe = window.parent.document.getElementById("myIframe");
      myIframe.parentNode.removeChild(myIframe);
   },1000);
}

Ok.
But I added to this function a call to another function. But this function contains a setTimeout that generates a 3 second delay.
Just like this:
function closeAndRemoveIframe() {
   setTimeout(function() {
      var myIframe = window.parent.document.getElementById("myIframe");
      myIframe.parentNode.removeChild(myIframe);
      myNewFunction();
   },1000);
}

The problem is:
This new function has a longer runtime setTimeout (3000 ms).
function myNewFunction() {
   setTimeout(function() {
      console.log("Hello world");
   },3000);
}

The iframe is the one calling the "myNewFunction ()" function. And once it is removed from the DOM after 1 second, the new function doesn't happen because it has a 3 second delay!
The only solution I found was to put the same time in the setTimeout of the first function! But this is not the desirable behavior!
So, is there any way to solve this without having to increase the settimeout time of the first function?
P.s: I'm using vanilla JS.
Thanks a lot!

A: have you tried moving the myNewFunction call before the removeChild function call?


text:
Q: Querying multiple tables and returning a combined queryset in Django while hitting the database once Lets say I have the following models setup:
class X(models.Model):
     ...

class Y(models.Model):
     x = models.ForeignKey(X)

class Z(models.Model):
     x = models.ForeignKey(X)

Now, in a method, I want to get all the Y objects and Z objects that are related to a given X object. I want to hit my database once, and return a combined queryset. Right now, I am doing it like this:
x = X.objects.get(pk=1)
queryset = []
for cls in [Y, Z]:
    queryset += list(cls.objects.filter(x=x))

Note: running it through a loop is important because there are quite a few models in my actual code, so looping keeps the whole thing DRY. How can I do this? Thanks.

A: If you need to merge to querysets from different models, the best/fastest way is by using itertools. Keep in mind this converts it from a QuerySet to an ordinary List.
from itertools import chain
x = X.objects.get(pk=1)
y = Y.objects.filter(x=x)
z = Z.objects.filter(x=x)
result_list = list(chain(y, z))

As far as I know, there isn't a way to query two different models that way, even with select_related or prefetch_related.


text:
Q: I get error when i login to my project and then go back to the base url I'm getting error when  login to my project and then goto the base url. The below is the error which i get

My Login page [ see the url ]

After logging in , if i remove the highlighted segments[pls see below image] after which i get the above error

I know these error are due to headers so can somebody help me in saying what error am i making in header. An also say how to make good use of session so that the form is to resubmitted when i refresh after logging in. Below are the header codes.
login header
<?php if(isset($this->session->userdata['logged'])){
    header("location: http://localhost/capacity_planner/login/login_check");
}
?>

admin dashboard[after logging in header]
<?php if(isset($this->session->userdata['logged'])){
    $email = ($this->session->userdata['logged']['email']);
}else{
  header("location: http://localhost/capacity_planner/login");
}
?>

controller side
public function login_check(){
            $data['base_url'] = base_url();
            $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
            if ($this->form_validation->run($this) == false) {

                $this->index();

            } else {

               if(isset($this->session->userdata['logged'])) {
                $data['login_bg'] = $this->input->post('login_bg');
                $this->load->view("admin_db", $data);
            }
            }

function check_database($password){

        $email= $this->input->post('email');

        $user = $this->user->loginCheck($email, $password);

        if($user[1] == 1){
            $result = $this->user->user_details($email);
            if($result != false) {
            $session_data = array(
            'id' => $result[0]->id,
            'email' => $result[0]->cp_email,
            );
            $this->session->set_userdata('logged', $session_data);
            return true;
            }
        } else{
             $this->form_validation->set_message('check_database', $user[0]);
        return false;
        }

    }

A: ERR_TOO_MANY_REDIRECTS is caused when strucked up in a conditional loop
I assume you want to redirect to admin dashboard if you go to index after logged in..
Try adding these lines in your public function index()
public function index(){
        if(isset($this->session->userdata['logged'])) {
                    //admin_db display function eg.redirect('admindashboard');
            }
        else{
           //load your index view
           this->load->view('your_index_view');
          }
}

or you can check reverse way in admin dashboard function like this
public function dashboard(){
if($this->session->userdata('logged') == ''){
            redirect('index');
            }
            else{

            $this->load->view('dashboard view');
            }
}

This is my assumption.Kindly check it.


text:
Q: How do I place a script with SNAP svg into a div I'm trying to place a SNAP svg script into a div and am lost as to how I should do this.
Right now here is the html I am working with:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>OH SNAP SVG 2014</title>
<script src="Snap.svg-0.1.0/dist/snap.svg-min.js"></script>
<style>
body{
    background:#FFF;
}
</style>

</head>

<body>

<script>

var paper= Snap(700,600);

var c = paper.image("clock machine.svg", 200,100,500,480);

var b = paper.image("new years ball.svg", 406,20,200,200);

var p = paper.image("button.svg", 258,508,35,35);

var l = paper.image("lights.svg",406,20,200,200);

var g = paper.group(b,l);

 var clickFunc= p.click
g.transform("R90");
p.click(function(){
        g.animate({transform : "t0,227" }, 5000, mina.easein );
        T.animate({transform : "t-2557,0,"}, 4900,mina.linear);
});

    g.attr({x:250})

var T = paper.image("LCD Text.svg", 620,453,2500,85).attr({
fill: "#3FFF9B"

});

var c = paper.rect(365, 454, 263, 85, 3).attr({mask:T,
fill:"#3FFF9B"
});

</script>

</body>
</html>

That is what I have so far. Does anybody know how I would specifically put this into a div? I read the documentation and have tried a couple of things, but my results have been futile.
Any help would be much obliged.

A: You can put an svg tag inside the div and attach to that, so it would look something like...
<div id="mydiv">
    <svg id="mysvg"></svg>
</div>

s = Snap("#mysvg");
s.rect(100,100,200,200);

example jsfiddle here showing the above with css on the div.


text:
Q: How to save an MMC console with remote computer snap in's I made an MMC console and added several snap ins to manage computers on my network. I saved it to my desktop and when I open it again every snap in is giving me information about the local computer instead of the remote computer I set up earlier. Is there any way to save the reference to the remote computer or do I have to re-connect manually every time ?
EDIT : I checked and this seems to only do this when I'm using the Performance Monitor snap in. The firewall/services/task scheduler/etc seems to retain their referenced computer.

A: With trial and error I managed to find the solution, here are the steps if other people encounter the same problem :

*

*Open all the ports necessary, in this case Performance Logs and Alerts and Windows Management Instrumentation.

*Start the services Remote Procedure Call(alongside RPC Endpoint Mapper) and Remote Registry

*When when connecting to a computer on the Performance Monitor snap in, open the Performance(local) and then right-click connect to another computer.

When adding performance counters, I have a problem when adding % Processor Time, it simply doesn't show up. A solution to that is to select all the fields in the Processor group and then remove them one by one until % Processor Time remains. There seems to be a problem when adding only % Processor Time.

A: You must run the MMC snapin in author mode and save it. Now copy the saved file to the system32 folder and override the old one. But when you do this, sfc will always tell you that files are damaged.


text:
Q: Can I use unmanaged C++ code to reduce calculation costs in a C# project? I want to use a c++ project to do some calculations for a c# project and return the results.
I was wondering if I would benefit a more efficient calculation speed in c++ if I do so?
Would still be efficient if I wrapped the native code in c++/cli?
Are there any examples out there?
Just as simple example say you have two double values A and B in C#, how would you have c++ project to receive A and B and a string value "plus" or "times" to calculate and return A + B or A * B?

A: Use Process.Start(); to spawn your optimized program.  You will be able to pass parameters and even read the output.  Start here: https://msdn.microsoft.com/en-us/library/53ezey2s(v=vs.110).aspx

A: You've got two separate issues in your question: "How do I", and "Should I".
If you're having problems with the "How do I", please post a question with the specific code you have, and what problems you're having.
"Should I" is somewhat of a nebulous question: It depends a lot on the type of calculations you're trying to do. These questions often have no one right answer. (Also note that this type of question is often offtopic for Stack Overflow for that very reason, so this question may be closed.)
For some types of calculations, the C++ compiler might produce more efficient code than the .Net Jitter. For some types, it won't make a difference. C++ would also let you do things like using the GPU to perform the calculations.
Also, consider how long it will take you to write this optimized code, and how often you're going to run it. If this needs to run overnight once a month, maybe a couple hours to run is fine.


text:
Q: JComponent partially hidden due to scrollpane in a BoxLayout I want to add the possibility for my users to add a comment on a form. To display them, I created JPanel inside a simple JScrollPane. I set the layout of this JPanel to BoxLayout because I wish to add them all in only one column and it seemed to be the easiest way by calling BoxLayout.Y_AXIS in the constructor. I also tried GridLayout and GridBagLayout but it was not what I was looking for.
My problem is that when a JPanel has the BoxLayout layout, it's width automatically is the same as it's container, but my container is a JScrollPane and the caret hides the right side of my comment!

You can see the JTextField and a JButton on the bottom left, here's the code on the click event :
private void btnAjoutCommentaireActionPerformed(java.awt.event.ActionEvent evt) {
    //I take the text from the JTextField and format it to html
    String formattedComment = "

" +
            txtArCommentaire.getText().replaceAll("\n", "
") +
            "

";

    JLabel label = new JLabel(formattedComment);
    //I add a blue border
    label.setBorder(new TitledBorder(new EtchedBorder(Color.lightGray, Color.blue), ConfigUser.getCu().toString()));
    //this below doesn't work
    label.setSize(280, 200);

    //I tried adding a JPanel in between but it didn't really worked out
    //JPanel panel = new JPanel();
    //panel.setLayout(new GridLayout(1, 1));
    //panel.setSize(297, 200);
    //panel.add(label);

    ///pnlCommentaire is the JPanel inside the JScrollPane

    pnlCommentaire.setLayout(new BoxLayout(pnlCommentaire, BoxLayout.Y_AXIS));

    pnlCommentaire.add(label);

    pnlCommentaire.revalidate();
    pnlCommentaire.repaint();
}

As you can see I tried to adust the size in html using style='width:280px'and on the JLabel using label.setSize(280, 200); but none of them worked.
Do you have any idea on how I could resize this Jlabel?
EDIT :
I added a margin-right property to the div so that I can at least fully see the text in the JLabel but the right border is still hidden.
 String formattedComment = "

" +
            txtArCommentaire.getText().replaceAll("\n", "
") +
            "

";


text:
Q: fwupd service is slowing the boot time on my PCIe SSD. Why is it doing that, and how can I fix it? My system is currently showing some strange behavior on boot. The GUI login appears seconds after hitting the power button, but my keyboard and mouse remain unpowered for about a minute. systemd-analyze indicates fwupd.service is the problem:
$ systemd-analyze time
Startup finished in 12.573s (firmware) + 293ms (loader) + 3.710s (kernel) + 1min 2.907s (userspace) = 1min 19.485s
graphical.target reached after 5.434s in userspace

$ systemd-analyze blame
1min 705ms fwupd.service
    4.083s plymouth-quit-wait.service
    1.028s gpu-manager.service
     925ms systemd-logind.service
     708ms systemd-resolved.service
     507ms accounts-daemon.service
     490ms networkd-dispatcher.service
     488ms system76-power.service
     470ms fancontrol.service
     437ms ModemManager.service
     301ms systemd-journald.service
...

journalctl -u indicates that fwupd is getting hung up on some device:
Jun 25 21:25:49 pop_os systemd[1]: Starting Firmware update daemon...
Jun 25 21:25:50 pop_os fwupd[1501]: 01:25:50:0156 FuPluginUefi         failed to add /sys/firmware/efi/esrt/entries/entry0: ESRT GUID '00000000-0000-0000-0000-000000000000' was not valid
Jun 25 21:26:50 pop_os systemd[1]: Started Firmware update daemon.

I tried putting the specified GUID of 00000000-0000-0000-0000-000000000000 in the BlacklistDevices variable in /etc/fwupd/daemon.conf, but that had no effect on the boot time. I also looked in the /sys/firmware/efi/esrt/entries/entry0 directory, and the file fw_class in that directory contained the above GUID.
Here is the output of fwupdmgr get-devices:
$ fwupdmgr get-devices
To Be Filled By O.E.M.
│
├─PCIe SSD:
│     Device ID:           71b677ca0f1bc2c5b804fa1d59e52064ce589293
│     Summary:             NVM Express Solid State Drive
│     Current version:     ECFM12.3
│     Vendor:              Phison Electronics Corporation (NVME:0x1987)
│     GUIDs:               8cb1e2fe-eb01-5508-9fb3-98add4bb7c34
│                          a44eb54c-5441-56f2-8cc0-5e48964c6457
│                          8d128eab-f266-513f-81e7-910de65fd73a
│     Device Flags:        • Internal device
│                          • Updatable
│                          • Requires AC power
│                          • Supported on remote server
│                          • Needs shutdown after installation
│                          • Device is usable for the duration of the update
│
└─PS Audio USB Audio 2.0:
      Device ID:           aff287d984fc4f1ed8f1ab3b35e4650b1b1f6c22
      Current version:     6.152
      Vendor:              PS Audio (USB:0x2616)
      GUIDs:               0f7b0016-25d6-5bc5-a6e0-423dba203c62
                           1fd717ad-32ef-5d86-a59a-71fd73ed6aae
      Device Flags:        • Updatable

My understanding here is that fwupd.service is getting hung up on this ESRT GUID entry for a whole minute before giving up and moving on. My question is: What the heck is that entry, and how can I stop it from slowing down my boot?
Edit: It turns out that it was not fwupd at all, but rather the Xbox One wireless adapter that was slowing everything down. Booting without the adapter plugged in completely solves the problem.

A: Short answer: your system's UEFI firmware claims to support the "UEFI firmware update capsule" mechanism that allows an unified way for all operating systems to provide system firmware updates (also known as "BIOS updates"). But your current firmware version apparently provides a null GUID in the ESRT information table instead of properly identifying the updateable system firmware, so the attempt to check whether or not newer firmware versions are available at Linux Vendor Firmware Service is failing.
The name of the fwupd plugin responsible for reading the ESRT information table from the system firmware and querying for the availability of that type of firmware update is uefi, so you might try editing the BlacklistPlugins line in your /etc/fwupd/daemon.conf to:
BlacklistPlugins=test;uefi

(assuming that your configuration file already includes default blacklisting for the test plugin, like it does on my Debian 10)
The fwupd.service is entirely optional, so it should be no problem to disable it altogether (with systemctl mask fwupd.service to prevent it auto-starting even if other services request it), if you prefer that solution. But then you'll need to find any firmware updates applicable to your system yourself, in the old-fashioned way. :-)
With luck, the system vendor may have fixed it in an updated UEFI firmware version, so updating your UEFI firmware to the latest available version just might fix the problem.


text:
Q: OpenCV Mat::row assignment cv::Vec<double, 9> 4;
for(int j = 0; j <3; ++j) {
   r[3 * j] = x[j];
   r[3 * j + 1] = y[j];
   r[3 * j + 2] = z[j];
}
vector<double> xi_, yi_, zi_;
        for (int j = 0; j < n; ++j) {
            xi_.push_back(obj_pts.at<double>(0, j));
            yi_.push_back(obj_pts.at<double>(1, j));
            zi_.push_back(obj_pts.at<double>(2, j));
        }
    cv::Mat Xi[xi_];
    cv::Mat Yi[yi_];
    cv::Mat Zi[zi_];
    cv::Mat XXcs(3, n,CV_64F), XXc, mo;
    mo = cv::Mat::ones(1, n, CV_64F);
(297th)        XXcs.row(0) = r[0] * Xi.t() + (r[1] * c + r[2] * s) * Yi.t() + (-r[1] * s + r[2] * c) * Zi.t() + t_[0] * mo;
        XXcs.row(1) = r[3] * Xi.t() + (r[4] * c + r[5] * s) * Yi.t() + (-r[4] * s + r[5] * c) * Zi.t() + t_[1] * mo;
        XXcs.row(2) = r[6] * Xi.t() + (r[7] * c + r[8] * s) * Yi.t() + (-r[7] * s + r[8] * c) * Zi.t() + t_[2] * mo;

I tried to debug my program, the err appear when execute to the 292th  statement.
The information is `
The inferior stopped because it received a signal from the operating system.

Signal name :
SIGSEGV
Signal meaning :
Segmentation fault

`
How to fix it? Thank u

A: I already solved the problem by the vconcat() function


text:
Q: Set Camera Focus On Tap Point With Swift The API for using the camera in swift seems a but different and I am having a hard time focusing the camera on a point. When the user taps the screen I want the camera to focus on that point
This is my code:
 func focusCamera(point:CGPoint)
    {
        var screenRect:CGRect = bounds
        var focusX = Float(point.x/screenRect.width)
        var focusY = Float(point.y/screenRect.height)

        _currentDevice.lockForConfiguration(nil)
        _currentDevice.setFocusModeLockedWithLensPosition(focusX)
        {
            time in
            self._currentDevice.unlockForConfiguration()
        }

        _currentDevice.setFocusModeLockedWithLensPosition(focusY)
        {
                time in
                self._currentDevice.unlockForConfiguration()
        }
    }

But it doesnt seem to work.
Any suggestions are more than welcome!

A: Better solution, as it works correctly for all videoGravity modes, also when the preview layer aspect ratio is different from the device ratio:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    guard let touchPoint = touches.first else { return }

    // precondition: the videoView contains the previewLayer, and the frames of the two are being kept equal
    let touchPointInPreviewLayer = touchPoint.location(in: videoView)
    let focusPoint = previewLayer.captureDevicePointOfInterest(for: touchPointInPreviewLayer)

    // etc
}

A: Updated answer from @Code for Swift 2.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let screenSize = videoView.bounds.size
    if let touchPoint = touches.first {
        let x = touchPoint.locationInView(videoView).y / screenSize.height
        let y = 1.0 - touchPoint.locationInView(videoView).x / screenSize.width
        let focusPoint = CGPoint(x: x, y: y)

        if let device = captureDevice {
            do {
                try device.lockForConfiguration()

                device.focusPointOfInterest = focusPoint
                //device.focusMode = .ContinuousAutoFocus
                device.focusMode = .AutoFocus
                //device.focusMode = .Locked
                device.exposurePointOfInterest = focusPoint
                device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure
                device.unlockForConfiguration()
            }
            catch {
                // just ignore
            }
        }
    }
}

A: Swift 2.0
if let device = captureDevice {
  do {
    try device.lockForConfiguration()
    device.focusPointOfInterest = focusPoint
    device.focusMode = AVCaptureFocusMode.ContinuousAutoFocus
    device.exposurePointOfInterest = focusPoint
    device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure
  } catch let error as NSError {
    print(error.localizedDescription)
  }
}

A: I used AVFoundation library and a wrapper that Camera Manager.
I am sharing to code sample. You can adapt your project.
By the way, you cannot focus the camera using front-camera. It doesn't support it. You can only adjust exposure for front-camera. By rare-camera, you can do it.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let screenSize = cameraView.bounds.size
    let frameSize:CGSize = view.frame.size
    if let touchPoint = touches.first {

        var location:CGPoint = touchPoint.locationInView(cameraView)

        if cameraManager.cameraDevice == .Front {
            print("Front camera is used")

            location.x = frameSize.width - location.x;
        }
        else {
            print("Back camera is used")
        }

        let x = location.x / frameSize.width
        let y = 1.0 - (location.x / frameSize.width)

        let focusPoint = CGPoint(x: x, y: y)

        print("POINT : X: \(x), Y: \(y)")

        let captureDevice = (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice]).filter{$0.position == .Back}.first

        if let device = captureDevice {
            do {
                try device.lockForConfiguration()

                let support:Bool = device.focusPointOfInterestSupported

                if support  {

                    print("focusPointOfInterestSupported: \(support)")

                    device.focusPointOfInterest = focusPoint

                    // device.focusMode = .ContinuousAutoFocus
                    device.focusMode = .AutoFocus
                    // device.focusMode = .Locked

                    device.unlockForConfiguration()

                    print("Focus point was set successfully")
                }
                else{
                    print("focusPointOfInterestSupported is not supported: \(support)")
                }
            }
            catch {
                // just ignore
                print("Focus point error")
            }
        }
    }
}

A: Updated answer from @ryantxr for Swift 3:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let screenSize = videoView.bounds.size
        if let touchPoint = touches.first {
            let x = touchPoint.location(in: videoView).y / screenSize.height
            let y = 1.0 - touchPoint.location(in: videoView).x / screenSize.width
            let focusPoint = CGPoint(x: x, y: y)

            if let device = captureDevice {
                do {
                    try device.lockForConfiguration()

                    device.focusPointOfInterest = focusPoint
                    //device.focusMode = .continuousAutoFocus
                    device.focusMode = .autoFocus
                    //device.focusMode = .locked
                    device.exposurePointOfInterest = focusPoint
                    device.exposureMode = AVCaptureExposureMode.continuousAutoExposure
                    device.unlockForConfiguration()
                }
                catch {
                    // just ignore
                }
            }
        }
    }

A: Turns out its very simple:
_currentDevice.lockForConfiguration(nil)
_currentDevice.focusPointOfInterest = tap.locationInView(self)
_currentDevice.unlockForConfiguration()

A: This question maybe is a duplicate of iOS tap to focus, where I posted this (hopefully explicit) solution that worked for me:
With a videoView: UIView displaying the video, and cameraDevice: AVCaptureDevice, the following seems to work for me:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touchPoint = touches.first as! UITouch
    var screenSize = videoView.bounds.size
    var focusPoint = CGPoint(x: touchPoint.locationInView(videoView).y / screenSize.height, y: 1.0 - touchPoint.locationInView(videoView.x / screenSize.width)

    if let device = cameraDevice {
        if(device.lockForConfiguration(nil)) {
            device.focusPointOfInterest = focusPoint
            device.focusMode = AVCaptureFocusMode.ContinuousAutoExposure
            device.exposurePointOfInterest = focusPoint
            device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure
            device.unlockForConfiguration()
        }
    }
}

Note that I had to swap the x and y coordinates, and remap the x coord from 1 to 0 instead of 0 to 1 — not sure why that should be the case but it seems to be necessary to get it to work right (though it's a little tricky to test it too).


text:
Q: R won't read in numeric values of CSV in data frame I am a beginner in R, so please bear with me! I have a csv read into R, it shows the relative abundance of different species at 9 sites. I am trying to get a summation of the rows, however R will not read the numerical values as such, which is going to lead to more issues as I try to run an NMDS ordination analysis. Here are some details about my data:
class(MSBees.spp)

[1] "data.frame"

First few rows of what str() prints:
str(MSBees.spp)

'data.frame':   9 obs. of  29 variables:
 $ X     : chr  "Site 1" "Site 2" "Site 3" "Site 4" ...
 $ COLALG: num  0.02013 0.00997 0 0 0 ...
 $ COLCAL: num  0 0 0 0 0 0 0 0 0
 $ COLCON: num  0 0 0 0 0 0 0.00339 0 0
 $ COLFUL: num  0 0 0 0 0 0.00361 0 0 0
 $ COLOBS: num  0.00671 0.00664 0.00755 0.00292 0 ...

What my code looks like so far:
MSBees.spp <- read.csv("data_transposed.csv", header = TRUE)
MSBees.env <- read.csv("data_transposed.env.csv", header = TRUE, row.names = 1)
MSBees_PA.spp <- read.csv("data_transposed.csv", header = TRUE, row.names = 1)
MSBees_abund.spp <- read.csv("data_transposed.csv", header = TRUE, row.names = 1)
sum.of.rows <- apply(MSBees.spp, 1, sum)

which returns:
Error in FUN(newX[, i], ...) : invalid 'type' (character) of argument
I have tried to coerce them to be numeric with:
as.numeric (MSBees.spp)

and
data.frame(lapply(MSBees.spp [2:9, 2:29], as.numeric))

but no luck in being able to run the apply() function successfully.
Am I sure I am just not reading the csv in properly or coercing them properly, but just can't get it right. Any tips? Please and thank you!

A: The row wise sum
apply(MSBees.spp, 1, sum)

is an issue because the first column based on the str is character.
$ X     : chr  "Site 1" "Site 2" "Site 3" "Site 4" ...

We need to exclude the first column
apply(MSBees.spp[-1], 1, sum)

and get the sum or use vectorized rowSums
rowSums(MSBees.spp[-1], na.rm = TRUE)

Also, there is no need to reconvert the dataset to numeric as the data is correctly read as numeric column types.  In addition, as.numeric expects a vector as input where as MSBees.spp is a data.frame i.e. as.numeric(MSBees.spp[[2]]) works as it is a vector


text:
Q: NSDateFormatter IOS Bug i have a function to convert into NSDate by using NSDateFormatter.
+(NSDate*)getDateFromCurrentTimestamp:(NSString*)currentTimestamp{
//    currentTimestamp= @"28-Feb-2012 16:42:19 PM";

    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDoesRelativeDateFormatting:NO];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    [dateFormatter setFormatterBehavior:NSDateFormatterShortStyle];
    //[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault];
    [dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss a"];

    return [dateFormatter dateFromString:currentTimestamp];
}

IOS 5.x is returned correct NSDate.
when run on 4.1 & 4.2 also returned correct NSDate.
when run on 4.3.2 & 4.3.3, it's returned null.
how is it possible? any workaround of this?

EDIT
This is not caused by iOS bug. this is related to phone itself. some phone has different locale set in device. so we had to force it to use one locale.

A: It looks like someone ran into this issue before. A workaround is written up here: NSDateFormatter is returning null for date in ios 4.3.3

A: From our discussion in the comments:
Are your region and locale set for the 4.3.2 & 4.3.3 devices? See if this SO question helps.
Relevant code:
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease]];