text:
Q: How to distinguish which version of OpenSSL is installed? Nginx's error log shows some OpenSSL Handshake errors and while searching for the cause I found confusing outputs of what OpenSSL version is used.
Details:
Debian Jessie 8.7 64 Bit

# apt-cache policy openssl
openssl:
  Installed: 1.0.1t-1+deb8u6
  Candidate: 1.0.1t-1+deb8u6
  Version table:
     1.0.2k-1~bpo8+1 0
        100 http://ftp.debian.org/debian/ jessie-backports/main amd64 Packages
 *** 1.0.1t-1+deb8u6 0
        500 http://security.debian.org/ jessie/updates/main amd64 Packages
        100 /var/lib/dpkg/status
     1.0.1t-1+deb8u5 0
        500 http://mirror.hetzner.de/debian/packages/ jessie/main amd64 Packages
        500 http://http.debian.net/debian/ jessie/main amd64 Packages

# apt-cache policy nginx
nginx:
  Installed: 1.9.10-1~bpo8+4
  Candidate: 1.10.3-1~bpo8+1
  Version table:
     1.10.3-1~bpo8+1 0
        100 http://ftp.debian.org/debian/ jessie-backports/main amd64 Packages
 *** 1.9.10-1~bpo8+4 0
        100 /var/lib/dpkg/status
     1.6.2-5+deb8u4 0
        500 http://mirror.hetzner.de/debian/packages/ jessie/main amd64 Packages
        500 http://http.debian.net/debian/ jessie/main amd64 Packages
        500 http://security.debian.org/ jessie/updates/main amd64 Packages

# nginx -V
nginx version: nginx/1.9.10
built with OpenSSL 1.0.2j  26 Sep 2016 (running with OpenSSL 1.0.2k  26 Jan 2017)

# openssl version -a
OpenSSL 1.0.1t  3 May 2016 (Library: OpenSSL 1.0.2k  26 Jan 2017)

How can nginx runs with openssl 1.0.2k and openssl version -a says that the Library is OpenSSL 1.0.2k but apt-cache policy openssl says installed is 1.0.1t ?
Could someone shed some light, please?

A: The openssl package contains the front-end binary, not the library. You're tracking Jessie for that package (with its security updates).
The library itself is libssl1.0.0, and you're tracking Jessie backports for that package (along with Nginx; you're just a few versions behind for the latter). This is what Nginx uses, and is the library version identified by the openssl front-end. You can see the version of the library on your system with
apt-cache policy libssl1.0.0

(as well as the availability of newer versions, if any).

A: I suspect that nginx -V shows which version of openssl was used to build the kernel, and that it is also showing you the version on the system that it's using.


text:
Q: Git/Github: How to transfer changes from one repository to another Steps I have made:

*

*I found a project in Github that I thought I could contribute.

*I cloned it directly without creating a Fork.

*I made my changes

*Now that I want to upload my changes, I realized that I was not working in a fork.

How do I manage to upload my changes to the repository of the fork in order to do a Pull Request from the fork to the original repository?

A: Add another git remote with your repo URL and then push to it:
git remote add myrepo git@github.com:your-user/repo
git push myrepo master

You can push to master or to any remote branch you want.
Both repos should share the root tree, which is the case if you have forked it.
As an alternative, you could change your current origin remote and then push normally to origin:
git remote set-url origin git@github.com:your-user/repo
git push origin master

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read and compare the value of CKRecord? Is there have any solution to read and compare the value of CKRecord? In a word, something like:
if valueOfRecord("Country") == "Taiwan" {
// code
}

A: Faster way,

if (object("Country") as! NSString) == "Taiwan" {
// code
}

Safer Way
if let countryName = object("Country") as? NSString {
     if countryName == "Taiwan" {
      // code
     }
} else {
    // object("Country") in not a string type record
}


text:
Q: Agregar consecutivos "CR-0000052" a la base de datos Deseo agregar un consecutivo cada vez qué se ingresan datos a una tabla factura. Es decir un autoincremental en el cúal contiene letras y números. Por lo cuál primero estoy creando Querys probando la funcionalidad. Pero tengo problemas con los if dentro del Query de postgreSQL.
   DECLARE
   rec record ;
   consecutivo varchar := 'CR-0000001';
   consecutivoNum varchar ;
   consecutivoLet varchar ;
   consecutivoNuevo varchar := 'CR-';
   numero integer := 0  ;
   BEGIN

       consecutivoLet := SPLIT_PART(consecutivo, '-', 1 );
       consecutivoNum := SPLIT_PART(consecutivo, '-', 2 );

       numero := consecutivoNum AS INTEGER ;
       RAISE NOTICE 'Consecutivo anterior %', numero ;
       numero := numero  + 1 ;

       IF numero < 10 THEN
           consecutivoNuevo := CONCAT(consecutivoLet, '000000', numero);

       ELSE IF numero < 100 THEN
           consecutivoNuevo := CONCAT(consecutivoNuevo, '00000', numero);
       ELSE IF numero < 1000 THEN
           consecutivoNuevo := CONCAT(consecutivoNuevo, '0000', numero);
       ELSE IF numero < 10000 THEN
           consecutivoNuevo := CONCAT(consecutivoNuevo, '000', numero);
       ELSE IF numero < 100000 THEN
           consecutivoNuevo := CONCAT(consecutivoNuevo, '00', numero);
       ELSE IF numero < 1000000 THEN
           consecutivoNuevo := CONCAT(consecutivoNuevo, '0', numero);
       ELSE IF numero < 10000000 THEN
           consecutivoNuevo := CONCAT(consecutivoNuevo, numero);
       END IF

       RAISE NOTICE  '%',consecutivoNuevo ;

   END
   $$ LANGUAGE plpgsql;

Por ahora estoy haciendo una prueba, en que ya tengo un consecutivo y separó las letras de los números con el simbolo '-', después incremento el número y lo concateno para obtener el nuevo consecutivo. El problema es qué los IF-ELSE statement estna generando un error.
LINE 23:  END
          ^
SQL state: 42601
Character: 578```

Gracias

A: No veo la necesidad de los IFs en primer lugar, bastaría con un:
CONCAT('CR-',RIGHT(CONCAT('0000000',numero),7))
o similar


text:
Q: Animating polygon style over time in QGIS? I have a shapefile, consisting of polygons. I can join a layer to a database file, and use an attribute (database value) to "style" (color in) the polygons to give me a visual representation of the data.
But the data is different for every day, so I can look at the representation for various days but I'd like to animate the progression.
I'm using QGIS and Microsoft Access.

A: You can use Time Manager Plugin to animate your polygons based on time field. Also you can refer to this answer on how to setup the data to be used in time manager.

A: Thanks for the help. I think I've got it. To help anyone in the future, what I did was to join the database file with my existing shapefile map. Then i saved the Database file as a .csv with xy geometry. I had to edit the .csv file in excel to make sure the Date Format was correct. Then I saved the .csv file as a shapefile in QGIS because Timemanager only works with shapefiles. Then i edited the atribute table so that my SDperHa columb was a decimal number format. Set the style to graduated on the SDperHa layer. Then added the layer to Timemanager an it works. Hope this helps someone else looking to do something similar


text:
Q: Unknown Provider: $scopeProvider <-$scope <- QueryBuilderController I am currently trying to test my angular application and i'm running into a problem with my test failing but the code is working...I can't get the controller to actually be created. I'm using Karma with Phantomjs through gulp. The error i'm getting is this:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <-QueryBuilderController

Here is my test:
describe('QueryBuilderController', function(){
 var controller;
  beforeEach(function(){
  bard.appModule('app.query');
  bard.inject(this,'$controller');
  controller = $controller('QueryBuilderController');
 });

 it('should exist', function(){
  expect(controller).to.exist;
 });
});

The interesting thing about this is I have a nearly identical test that does work and load that looks like this:
describe('ShellController', function(){
 var controller;

 beforeEach(function(){
 bard.appModule('app.shell');
 bard.inject('$controller');
 controller = $controller('ShellController');
});

it('should exist', function(){
 expect(controller).to.exist;
});
});

Here is the QueryBuilderController:
(function () {
 'use strict';
  angular.module('app.query')
      .controller('QueryBuilderController', QueryBuilderController);
  QueryBuilderController.$inject = ['QueryFactory', '$scope'];

  function QueryBuilderController (QueryFactory, $scope){
   var vm = this;
   vm.displayQuery = true;
  }
}) ();

And here is the module that the controller belongs to:
 (function() {
 'use strict';

 angular
    .module('app.query', [
        'app.core',
        'elasticsearch',
        'angular-elastic-builder',
        'angularUtils.directives.dirPagination'
    ]);
})();

Here is the gulp task:
gulp.task('test', ['vet'], function(done){
 startTests(true, done);
});
///////
function startTests(singleRun, done) {
var child;
var excludeFiles = [];
var fork = require('child_process').fork;
var karma = require('karma').server;
var serverSpecs = config.serverIntegrationSpecs;

if (args.startServers) {
    console.log('Starting servers');
    var savedEnv = process.env;
    savedEnv.NODE_ENV = 'dev';
    savedEnv.PORT = 8888;
    child = fork(config.nodeServer);
} else {
    if (serverSpecs && serverSpecs.length) {
        excludeFiles = serverSpecs;
    }
}

karma.start({
    configFile: __dirname + '/karma.conf.js',
    exclude: excludeFiles,
    singleRun: !!singleRun
}, karmaCompleted);

////////////////

function karmaCompleted(karmaResult) {
    console.log('Karma completed');
    if (child) {
        console.log('shutting down the child process');
        child.kill();
    }
    if (karmaResult === 1) {
        done('karma: tests failed with code ' + karmaResult);
    } else {
        done();
    }
 }
}

And the GulpConfig:
module.exports = function(){
var client = './src/client/';
var clientApp = client + 'app/';
var temp = './.tmp/';
var server = './src/server/';
var report = './report/';
var wiredep = require('wiredep');
var bowerFiles = wiredep({devDependencies: true})['js'];
var root = './';
var config = {
// File Paths
temp: './.tmp/',
alljs: [
  './src/**/*.js',
  './*.js'
],
htmlTemplates: clientApp + '**/*.html',
html: clientApp + '**/*.html',
client: client,
index: client + 'index.html',
build: './static/',
fonts: './bower_components/font-awesome/fonts/**/*.*',
images: client + 'images/**/*.*',
js: [
  clientApp + '**/*.module.js',
  clientApp + '**/*.js',
  '!' + clientApp + '**/*.spec.js'
],
templateCache: {
  file: 'templates.js',
  options: {
    module: 'app.core',
    standAlone: false,
    root: 'app/'
  }
},
sass: client + 'styles/styles.sass',
css: [temp + 'styles.css', client + 'assetts/*.css'],
// Bower and NPM locations
bower: {
  json: require('./bower.json'),
  directory: './bower_components/',
  ignorePath: '../..'
},
specHelpers: client +'specHelpers/*.js',
// Node Settings
nodeServer: './src/server/dev_server.js',
port: 3000,
server: server,
// Optimized File Names
optimized: {
  app: 'app.js',
  lib: 'lib.js'
},
// Packages for bower and NPM
packages: [
  './package.json',
  './bower.json'
],
root: root
};
config.getWiredepDefaultOptions = function(){
var options = {
  bowerJson: config.bower.json,
  directory: config.bower.directory,
  ignorePath: config.bower.ignorePath
};
 return options;
};
config.karma = getKarmaOptions();
return config;
///////////////////////////////

function getKarmaOptions() {
  var options = {
      files: [].concat(
          bowerFiles,
          config.specHelpers,
          clientApp + '**/*.module.js',
          clientApp + '**/*.js'
          // config.serverIntegrationSpecs
      ),
      exclude: [],
      coverage: {
          dir: report + 'coverage',
          reporters: [
              // reporters not supporting the `file` property
              {type: 'html', subdir: 'report-html'},
              {type: 'lcov', subdir: 'report-lcov'},
              {type: 'text-summary'} //, subdir: '.', file: 'text-
summary.txt'}
          ]
      },
      preprocessors: {}
  };
  options.preprocessors[clientApp + '**/!(*.spec)+(.js)'] = ['coverage'];
  return options;
}
};

Karma.Conf:
module.exports = function(config){
var gulpConfig = require('./gulp.config')();
config.set({
 basePath: './',
 files: gulpConfig.karma.files,
 exclude: gulpConfig.karma.exclude,
 proxies: {
    '/': 'http://localhost:8888/'
},
// preprocessors: gulpConfig.karma.preprocessors,

reporters: ['progress', 'coverage'],

coverageReporter: {
       dir: gulpConfig.karma.coverage.dir,
       reporters: gulpConfig.karma.coverage.reporters
   },
// web server port
port: 9876,
plugins: [
  'karma-mocha',
  'karma-chai',
  'karma-sinon',
  'karma-sinon-chai',
  'karma-phantomjs-launcher',
  'karma-coverage'
],
// enable / disable colors in the output (reporters and logs)
colors: true,

logLevel: config.LOG_INFO,

autoWatch: true,

frameworks: ['mocha', 'chai', 'sinon', 'sinon-chai'],

browsers: ['PhantomJS'],

singleRun: false

});
};

And last but not least, the project structure:
    Project
|-- gulpfile.js
|-- gulp.config.js
|-- karma.conf.js
|-- package.json
|-- bower.json
`-- src
    `-- client
        |-- assetts
        |-- images
        |-- specHelpers
        |-- styles
        |-- index.html
        |-- specs.html
            `-- app
            |-- angular-elastic-builder.js
            |-- app.module.js
            |-- blocks
            |   |-- exception
            |   |   |-- exception-handler.provider
            |   |   |-- exception.js
            |   |   `-- exception.module.js
            |   |-- logger
            |   |   |-- logger.js
            |   |   `-- logger.module.js
            |   `-- router
            |       |-- router.module.js
            |       `-- router-helper.provider.js
            |-- core
            |-- dashboard
            |-- query
            |   |-- querybuilder.controller.js
            |   |-- querybuilder.html
            |   |-- query.module.js
            |   `-- querycontroller.spec.js
            `-- shell
                |-- shell.module.js
                |-- shell.controller.spec.js
                |-- shell.controller.js
                `-- shell.html

Sorry for all of the information, tried to include all of the relative information. All help is appreciated, thank you in advance!
UPDATE: When I don't use bard it seems to get past this, is it possible that bard.js is causing some sort of issue with one of my module dependencies?
/* jshint -W117, -W030 */
    describe('QueryBuilderController', function(){

  // beforeEach(function(){
  //   module('app.query');
  //   bard.inject('$controller');
  //   controller = $controller('QueryBuilderController');
  // });
  beforeEach(module('app.query'));
  var $controller;
  beforeEach(inject(function(_$controller_){
    $controller = _$controller_;
  }));

  it('should exist', function(){
    var $scope = {};
    var controller = $controller('QueryBuilderController', { $scope: $scope  });
expect(controller).to.exist;
  });
});

A: Are you injecting your dependencies correctly? According to the docs you need to do something like this:
angular.module('myApp', [])
.controller('MyController', ['myService', function (myService) {
  // Do something with myService
}]);

I've only encountered this issue when my code has been minified if I didn't declare my dependencies correctly, but I wonder if it's the same thing in your case.


text:
Q: Read all the values in a node in xml with key value pairand print them in seperate line in I have an XML file with key/value pairs.
XML file which I am using:
<?xml version="1.0" encoding="UTF-8"?>
<MAN_J6_Variant>
    <play_music_media_HK>
        <key name ="Media_Press" value="echo 'Media::1' >> /pps/can/test_pps"/>
        <key name ="Media_Release" value="echo 'Media::0' >> /pps/can/test_pps"/>
        <key name ="Media_Source" value ="./fs/etfs/Touch_new -X=258 -Y=26 -display=4 -relTimeout=0.5 " />
        <key name ="USB" value ="./fs/etfs/Touch_new -X=480 -Y=134 -display=4 -relTimeout=0.5 " />
    </play_music_media_HK>
    <softkeys>
        <key name ="Media_SK" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
  </softkeys>
    <play_music_media_SK>
        <key name ="bottom_home" value ="./fs/etfs/Touch_new -X=755 -Y=455 -display=4 -relTimeout=0.5 " />
        <key name ="HS3" value ="./fs/etfs/Touch_new -X=464 -Y=27 -display= -relTimeout= " />
        <key name ="Media_Source" value ="./fs/etfs/Touch_new -X=258 -Y=26 -display=4 -relTimeout=0.5 " />
        <key name ="USB" value ="./fs/etfs/Touch_new -X=480 -Y=134 -display=4 -relTimeout=0.5 " />
    </play_music_media_SK>
    <Inside_media>
        <key name ="Media_Source" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
        <key name ="Browse" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
        <key name ="Audio_playing" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
    </Inside_media>
    <Inside_Media_source>
        <key name ="USB" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
        <key name ="SD1" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
        <key name ="SD2" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
        <key name ="USB1" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
        <key name ="IPOD" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
    </Inside_Media_source>
    <Inside_Media_Browse>
        <key name ="Artist" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
        <key name ="Albums" value ="./fs/etfs/Touch_new -X= -Y = -display= -relTimeout= " />
    </Inside_Media_Browse>
 </MAN_J6_Variant>

I need to print all the values in node play_music_media_SK in seperate line.
I wrote the below code in linq:
 var play_music_media_SK = doc.Descendants("play_music_media_SK").Select(x => new { play_music_media_SK = x.Attribute("name").Value, name = x.Attribute("value").ToString() });

//TestSetup.LogFile.WriteMsg("values in softkey"+taps);

  foreach (var value in play_music_media_SK)
  {
    console.writeline(value);
  }

But this is not working.

A: This should give you correct results:-
var result = doc.Root.Element("play_music_media_SK")
                      .Elements("key").Select(x => (string)x.Attribute("value"));

  foreach (var item in result)
  {
      Console.WriteLine(item);
  }

Approach: From the root node search for play_music_media_SK element, inside that look for key elements (using Elements since all are direct child of play_music_media_SK) then finally project the attribute value.


text:
Q: Cassandra nodes in multiple data centers http://www.cs.cornell.edu/projects/ladis2009/papers/lakshman-ladis2009.pdf : "Cassandra is configured such that each row is replicated across multiple data centers."
So in that case is it good to have almost same number of Cassandra nodes in each data center. If not, would that generate key hotspots?

A: See answer here: http://n2.nabble.com/Cassandra-nodes-in-multiple-data-centers-tp4125377p4126052.html


text:
Q: MySQL is only downloading in zip format. How to fix it? Or how to open? Yesterday I went to download MySQL, and I managed to install it, when the download finished, I double-clicked and the program opened normally. I created an account just for testing, so I didn't save the password, so I deleted MySQL to create another account... However when I go to download, now only the option to download in Compressed (zipped) Folder format appears, and I have no idea how to open any type of download in that format, I've tried following the steps taught in the videos and I couldn't either.
Is there a way to fix this? Because yesterday MySQL was downloading normally (as in the image below) and I had no difficulty opening it.

But now the download is just like this (as in the image), and I can no longer open the program.

Note: I use the 64 bit version of Windows 10.

A: I assume you're downloading MySQL community server from it's official page here: https://dev.mysql.com/downloads/mysql/
If you are, then you can see in the page there are 3 blue buttons

I assume that you are downloading from the "Other Downloads" section (no.2 in image).

A: could you share the link to the source where you downloaded MySQL?
Usually you should be able to unzip the contents of any .zip file by right clicking the archive in a explorer and choosing extract (not sure what the exact buttons in Windows are called since I don't use it).
Maybe your file got corrupted while you downloaded it (connection issues), have you tried re-downloading it?
I've just searched for the download and started it from the official website
(https://cdn.mysql.com//Downloads/MySQLInstaller/mysql-installer-community-8.0.32.0.msi). This starts the download of an .msi file in my case. Can you confirm that this still starts the download of a .zip file?


text:
Q: How can I minify an html template file without destroying the structure? I have a handlebars template file that I'd like to minify.  I found a couple questions that were related to my issue on StackOverflow, but nothing exactly like it that had an answer.  My issue is that spaces that are within the templated values are getting removed when I run the code through a minifier.
Example:
I have this line of code in my template file:

{{{displayName}}} - {{cost}}

When I use the un-minified file to render the page, I get entries like:
ProductName - $5.50
which is what I want.  After running the template through an html minifier, my template line now looks like this:

{{{displayName}}}-{{cost}}

and the entries on the rendered page look like:
ProductName-$5.50
Not optimal.  Now, I understand that I could just run through the template and put in non-breaking spaces into all the places where I'd like spaces to be.  Nice.  Simple.  Easy... relatively.
But.
A secondary, and larger, issue comes into play (and what's the point of going through and putting in all those non-breaking spaces into my template file to avoid this situation with the html minifier if there are more issues) when I'm selectively adding attributes or classes to a given html element.
Example:
I also have lines in my template files that look like:

On the condition where my template (handlebars) variable "paymentSelected" is true the html shows as:

After minification, however the minified template file contains:

which makes the html on the page show as:

which, consequently, messes up all of my css and javascript because there is now one unrecognized class on the element instead of two correct classes.
Again, there is a way of getting around this.  I could just place all of the class definitions into the template variables.  So, my new template would be:

This kind of goes against the idea of removing redundancy though.  So I don't like it.  And this is a fairly simple case, with only two possible classes.
I'm sure there are more possibilities for hassle with html minification of template files, but I think I've shown my point.
Now, all of that explanation comes to my question:
Is there a tool out there that will minify html but ignore spaces that are between opening and closing template tags?  For me, those spaces are similar to the spaces between words.  I don't want all the spaces between the words of a sentence removed any more than I want the spaces within my template tags to be removed.
I also went searching for a generic sed solution, but didn't find anything in that direction either.

A: Could you just use &ampnbsp;?

A: Okay, so I figured out a better option, and this may be incredibly obvious to some but I'm pretty new to the whole Handlebars gig.
A better solution to minifying the html templates would be to precompile the templates and to then minify the resulting javascript.  This way, I also get the savings of no compilation time on the browser side and (because I'm using Handlebars as my templating language) loading the smaller runtime script.
Granted, this solution doesn't explicitly answer the question I posed, it does solve the ultimate problem I'm trying to solve, which is to minimize the page-load time on a browser by doing everything I can to the necessary assets prior to a browser downloading them.


text:
Q: 2D Fourier transform of a diffraction pattern Mathematica vs FourierPainter We are trying to make sense of the numbers provided by the PC program FourierPainter for a 2D Fourier Transform of a diffraction pattern.

We would like to evaluate the ratio of the zeroth harmonic to the first harmonic intensities. Refer to the Notebook here. There are references to other Mathematica Stack Exchange Posts here and here in it as well as our analysis.  Here is a sample of our code (two$D$image is the import of our image):
fftshift[dat_?ArrayQ, k : (_Integer?Positive | All) : All] :=Module[{dims = Dimensions[dat]}, RotateRight[dat,If[k === All, Quotient[dims, 2], Quotient[dims[[k]], 2] UnitVector[Length[dims], k]]]]

img = ColorConvert[two$D$image, "Grayscale"];

(tst = Abs[fftshift[
      Fourier[ImageData[img], FourierParameters -> {1, -1}]]]^2);

(tst$arg = Arg[fftshift[Fourier[ImageData[img], FourierParameters -> {1, -1}]]]);

abs = Log[1 + tst]

Manipulate[DynamicModule[{b = {}, i = slice},Do[AppendTo[b, {j - (2616/2), abs[[j, i]]}],{j, 1, Dimensions[abs][[1]]}];ListPlot[Total[#] & /@ Partition[b, group], PlotLabel -> "Pixels referenced to center " <> ToString[(3488/2) - i], PlotRange -> {Full, Full}]],{{slice, 3488/2}, 1, 3488, 1}, {{group, 1}, InputField}]

FourierPainter gives numbers for this pattern of the order of 5000/3000 for the intensities of the harmonics while Mathematica gives numbers of the order of 10$^{13}$/10$^{11}$ for the power spectrum of the same file. How to reconcile these numbers?


text:
Q: What is the use of a shared variable in VB.NET? What is the use of a Shared variable in VB.NET?

A: Simply whenever you want to have single instance of variable for entire application, shared between objects of your class. Instead of 1-per-object.

A: It is the same as static in C# and most other languages. It means that every object in the class uses the same copy of the variable, property or method. When used with a method as it is static you don't need an object instance.
MyClass.DoSomething()

rather than
Dim oObject as New MyClass()
oObject.DoSomething()

A: The "Shared" keyword in VB.NET is the equivalent of the "static" keyword in C#.
In VB.NET, the Shared keyword can be applied to Dim, Event, Function, Operator, Property, and Sub statements within a class; however, in C#, the static keyword can be applied both to these statements within a normal class, and also at the class level to make the entire class static.
A "Shared" or "static" method acts upon the "type" (that is, the class) rather than acting upon an instance of the type/class. Since Shared methods (or variables) act upon the type rather than an instance, there can only ever be one "copy" of the variable or method as opposed to many copies (one for each instance) in the case of non-shared (i.e., instance) methods or variables.
For example: If you have a class, let's call it MyClass with a single non-shared method called MyMethod.
Public Class MyClass
    Public Sub MyMethod()
        ' Do something in the method
    End Sub
End Class

In order to call that method you would need an instance of the class in order to call the method. Something like:
Dim myvar As MyClass = New MyClass()
myvar.MyMethod()

If this method was then made into a "shared" method (by adding the "Shared" qualifier on the method definition, you no longer need an instance of the class to call the method.
Public Class MyClass
    Public Shared Sub MyMethod()
        ' Do something in the method
    End Sub
End Class

And then:
MyClass.MyMethod()

You can also see examples of this in the .NET framework itself. For example, the "string" type has many static/shared methods. I.e.
' Using an instance method (i.e. Non-shared) of the string type/class.
Dim s As String = "hello"
s.Replace("h", "j")

' Using a static/shared method of the string type/class.
s = String.Concat(s, " there!");

Here's a good article that explains it further:
Shared Members and Instance Members in VB.NET


text:
Q: Windows fread unexpected behavior So fread is behaving unexpectedly on Win7 x64.
file = fopen(path, "rb");
fseek(file, 0, SEEK_END);
fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
buffer = malloc(fileSize);
length = fread(buffer, fileSize, 1, file);

fread will return 1 byte as being read whereas (ferror and feof both return 0)
length = fread(buffer, 1, fileSize, file);

fread will return the same number of bytes read as fileSize. MSDN says "The fread function reads up to count items of size bytes from the input stream and stores them in buffer." Which I interpret as meaning that that either piece of code should read the same amount of data. Does anyone know why fread isnt working as I expect it to?

A: They do read the same amount of data. The number of bytes read is the size parameter times the count parameter. What is returned is the count of items read.
So in the first case you asked for 1 item of size fileSize and it returned 1.
In the second case you asked for fileSize items of size 1 and it returned fileSize.

A: fread returns "the number of full items actually read", not the number of bytes read.
With fread(buffer, fileSize, 1, file); you're reading one item of size fileSize (and fread will thus return 1 on success) whereas with fread(buffer, 1, fileSize, file); you're reading fileSize items of size 1 and it will return the number of bytes read (as you're expecting).


text:
Q: Django: retrieve distinct QuerySet I've got the following models in my app. The Addition model is used to govern the many-to-many relationship between the Book model and the Collection model, since I need to include extra fields on the intermediate model.
class Book(models.Model):
    name = models.CharField(max_length=200)
    picture = models.ImageField(upload_to='img', max_length=1000)
    price = models.DecimalField(max_digits=8, decimal_places=2)

class Collection(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    books = models.ManyToManyField(Book, through='Addition')
    subscribers = models.ManyToManyField(User, related_name='collection_subscriptions', blank=True, null=True)

class Addition(models.Model):
    user = models.ForeignKey(User)
    book = models.ForeignKey(Book)
    collection = models.ForeignKey(Collection)
    created = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=True)

In my app users can add books to collections that they create (for example fiction, history, etc.). Other users can then follow those collections that they like.
When a user logs into the site, I'd like to display all of the books that have been recently added to the collections that they follow. With each book, I'd also like to display the name of the person who added it, and the name of the collection it's in.
I can get all of the additions as follows...
additions = Addition.objects.filter(collection__subscribers=user).select_related()

... but this results in duplicate books being retrieved and displayed to the user, often side by side.
If there a way to retrieve a distinct list of books that are in collections the user is following?
I'm using Django 1.3 + MySQL.
Thanks.
UPDATE
I should add that in general I'm not looking for any 'loop through the results and de-duplicate that way' solutions, for a couple of reasons.
There are likely to be tens or even hundreds of thousands of additions (I am also displaying this information on pages that list all new additions added by users), and response time is extremely important.
This solution may become more practical when limiting the initial result set, but it creates problems with pagination, which is also required. Namely how do you paginate the entire result set while also de-duplicating only a small portion of that set. I'm open to any ideas here that may solve this problem.
UPDATE
I should also mention that if the same book gets added by multiple users, I actually don't have a preference for which addition gets used, either the original or the most recent addition would work fine.

A: How about the following - it's not a pure SQL solution, and it'll cost you an extra database query and some loop time, but it should still perform ok, and it'll give you a lot more control over which additions take precedence over others:
def filter_additions(additions):
    # Use a ValuesQuerySet for performance
    additions_values = additions.values()

    # The following code just eliminates duplicates. You could do
    # something much more powerful/interesting here if you like,
    # e.g. give preference to additions by a user`s friends

    book_pk_registry = {}
    excluded_addition_pks = []

    for addition in additions_values:
        addition_pk = addition['id']
        book_pk = addition['book_id']
        if book_pk not in book_pk_registry:
            book_pk_registry[book_pk] = True
        else:
            excluded_addition_pks.append(addition_pk)

    additions = additions.exclude(pk__in=excluded_addition_pks)

additions = Addition.objects.filter(collection__subscribers=user)
additions = filter_additions(additions)

If there are likely to be more than a thousand or so books involved, you may want to put a limit on the initial additions query. Passing massive lists of ids over in the exclude isn't such a great idea. Using 'values()' is quite important, because Python can cycle through a basic list of dicts a LOT faster than a queryset and it uses a lot less memory.

A: Assuming there won`t be huge amounts of additions to display, this could easily to the trick:
# duplicated..
additions = Addition.objects.filter(collection__subscribers=user, created__gt=DATE_LAST_LOGIN).select_related()

# remove duplication
added_books = {}
for addition in additions:
    added_books[addition.book] = True
added_books = added_books.keys()

By the description you gave of the problem, performance would not be a problem.

A: additions = Addition.objects.filter(collection__subscribers=user).values('book').annotate(user=Min('user'), collection=Min('collection')).order_by()

This query will give you list of unique books with their users and collections. Books, collections, users will be pk's, not objects. But I hope you will store them in cache so that won't be a problem.
But for your workload I'd think about denormalization. My query is very heavy, and it isn't easy to cache its results if you will have frequent additions. My first approach will be to add latest_additions field to Collection model and to update with signals (not adding duplicates). The format of this field is up to you.

A: Sometimes it's OK to drop into SQL, especially when the ORM-only solution is not performant. It's easy to get the non-duplicate Addition row IDs in SQL, and then you can switch back to the ORM to select the data. It's two queries, but will outperform any of the single query solutions I've seen so far.
from django.db import connection
from operator import itemgetter
cursor = connection.cursor()

# Select non-duplicate book additions, preferring for most recently updated
query = '''SELECT id, MAX(updated) FROM %s
    GROUP BY book_id''' % Addition._meta.db_table
cursor.execute(query)

# Flatten the results to an id list
addition_ids = map(itemgetter(0), cursor.fetchall())

additions = Addition.objects.filter(
    collection__subscribers=user, id__in=addition_ids).select_related()


text:
Q: Setting Blazor Server Application JsonSerializerOptions When you have an MVC application you can append services.AddMvc().AddJsonOptions(options => ... and that will set the Json options for all the controllers.
What is the equivalent for a Blazor Server App? I tried
services.AddRazorPages().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNameCaseInsensitive = true); and while the compiler didn't complain it didn't seem to have the desired effect and i still have to do the following to deserialize correctly:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var list = await JsonSerializer.DeserializeAsync<IEnumerable<CustomerSearchResultDto>>(await response.Content.ReadAsStreamAsync(), options);

Any ideas? Thanks in advance.


text:
Q: Weird functionality using tkinter scale with iter(loader).next() Hi All I have noise_scale function which gets the current value of the scale (scale has 3 levels - 0, 10, 20) and then performs some test by feeding a randomly sampled image and label. The iter(testloader).next() is used to sample a random image and corresponding label. If I use the iter(testloader).next() outside the function and print the (image,label) pair, it prints just one image and label, however if I use the iter(testloader).next() inside the function and prints the (image,label) pair, I get three images and their respective labels. I can't seem to figure out what's causing that. Below is my sample code for review:
test= data_utils.TensorDataset(torch.from_numpy(test_set),torch.from_numpy(label_set))
loader = data_utils.DataLoader(test,batch_size=1,shuffle=True)
image, label = iter(loader).next()

print(image)  # this prints only one image
print(label)  # this prints the corresponding label

def noise_scale(scale_value=0):

    image, label = iter(loader).next()
    print(image)  # this prints three images
    print(label)  # this prints three labels of images above

    if (scale.get()) == 0:
        for i in range(1):
            do_something()

    elif (scale.get()) == 10:
        for i in range(1):
            do_something()

    elif (scale.get()) == 20:
        for i in range(1):
            do_something()

## Scale ##
var3 = StringVar()
scale = tk.Scale(root, variable=var3, from_=0, to=20, tickinterval=10, orient='horizontal', resolution=10, length=200, command=noise_scale)


text:
Q: Why is it so hard to build a mobile OS? I'm wondering what makes it so hard for companies to be on time when delivering mobile software? I partly understand why it takes time to shell out a first version of an OS (you have to take care of all the low level stuff), but once you have all the APIs in place, why does it take months to deliver simple UI iterations (like copy&paste in case of Windows Phone 7). Why do Symbian UI updates take so long? I'm not familiar with Android.
Especially in the case of Meego & Bada which already base on Linux, I have trouble understanding how it can take > 1 year to simply make a running product. I'm sure there are good reasons, I don't want to be ignorant, that's why I'm asking.
Is it maybe because performance is very hard to achieve? I'm not sure, but my experience with doing "low level" DirectX API stuff is, that it's fairly easy to achieve fast 2D graphics.

A: Because writing (good or bad) software is hard. I think you are trivializing how much work actually goes into these projects. I'm not trying to be critical, but I think you just haven't tried to deliver a large project on time, on budget, and to specification, nor do you have a real understanding of the complexities of the features you pan off as simple.
For academic exercise, try re-implementing cut-n-paste across every windows control without using the OS hooks. Now make it work with office content, or images, or any other advanced content


text:
Q: TextField and Warning I have a UITextField object and take input from the textfield. If length of the input is shorter than 2, I want to give warning sign in the textfield bar.
Is this impossible ?
If it is so, how can I handle that ?
EDIT:
I just handled it. I put a label in the textfield and run auto layout. Then, I chose delegate of textfield and make InputViewController conform to UITextFieldDelegate protocol. Finally, I use func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

A: Implement UITextFieldDelegate in your view controller and use textFieldDidEndEditing to check text length.
func textFieldDidEndEditing(_ textField: UITextField) {
    if let textFieldText = textField.text {
       print("textFieldText length - \(textFieldText.count)")
       if (textFieldText.count < 2) {
          showWarning(message: "Your message here")
       }
    }
}

func showWarning(message: String?){
   // show warning message using UIAlertController here.
}

A: You can use a custom class inherited from UIView and pack UITextField(No border style) and Iconic Font UILabel inside it.


text:
Q: How to connect sqlite with mysql database using ionic framework? now I'm working on hybrid mobile application with SQLite. This application just only retrieve the data from database. The data come from MYSQL database, but I want to store the large amount of data into local storage which is SQLite so when the user don't have the internet, they can retrieve the data from local storage. So,is there a way to connect mysql db and sqlite? I have been following the tutorial from this site
but I do not know how to connect sqlite with mysql db. So,anyone can help me to solve my problem ?


text:
Q: Left Join Data.Frame to XTS object on Date (Index) I have an xts object (indexed by Dates)
start <- as.Date('2016-06-30')
end <- as.Date('2016-12-31')
dt_len <- as.integer(end - start)

x <- matrix(rep(NA, 8 * dt_len), ncol = 8)
colnames(x) <- c("baseline", "cumul_baseline",
                 "scenario_1", "cumul_scenario_1",
                 "scenario_2", "cumul_scenario_2",
                 "scenario_3", "cumul_scenario_3")

dt_ts <- xts(x, start + 1:as.integer(dt_len))

Into which I insert a baseline measure of sales.  The purpose is to build out 3 different scenarios of sales and compare the actual sales to those scenarios, IOT know "which" of these scenarios we think we're "in."
# baseline sales (constant)
b_daily <- 1561

dt_ts$baseline <- b_daily

I then make some "actual" (hypothetical) sales data over the same date range.
eg_data <- data.frame(Date = seq.Date(from = as.Date("2016-07-01"), by = "day", length.out = dt_len), Sales = sample(1000:2000, dt_len))

But if I am trying to join my hypothetical eg_data object to the xts object with my scenarios...
left_join(dt_ts, eg_data, by = "Date")
Error in UseMethod("left_join") :
  no applicable method for 'left_join' applied to an object of class "c('xts', 'zoo')"

My question is: if I have a data.frame I want to left_join to an object I'd like to keep cast as an xts, how to I join them?  I'd like to assume that the row-dates don't line up necessarily, thus requiring a call to join or merge...

A: The simple answer to your question is "don't". Either convert them both to xts or data.frame.
Here's how to do it with both objects as xts, since storing time series in a data.frame makes me feel icky.
xts_data <- merge(dt_ts, Sales=with(eg_data, xts(Sales, Date)), join="left")


text:
Q: Bernoulli-measure on sup- and subspace: "Decompose" metric entropy? Let $X=A^{\mathbb{Z}}$ for finite set $A$ of cardinality $\text{card}(A)=k<\infty$.
Let $\tau$ denote the topology on $X$ with basis given by the set $C$ of  cylinders
$$
C_n(c_0,c_1,\ldots,c_m):=\{x\in X: x_n=c_0,\ldots,x_{n+m}=c_m\}
$$
and $B(\tau)$ the Borel $\sigma$-algebra with the uniform Bernoulli-measure,
$$
\mu(C_n(c_0,\ldots,c_m)):=k^{-(m+1)},
$$
on it.
Suppose $Y\subseteq X$ is a $T$-invariant subset, i.e. $T(Y)\subseteq Y$. Consider $S:=T_{|Y}$, the restriction of $T$ on $Y$. Similarly as above, let $\tau'$ be the topology on $Y$ with basis given by the set $C'$ of the cylinders
$$
Y\cap C_n(c_0,c_1,\ldots,c_m).
$$
Let $B(\tau')$ be the Borel $\sigma$-algebra with uniform Bernoulli-measure $\lambda$ on it.

I have two questions concerning measure theory/ dynamics:
(1) Am I right that $B(\tau')\subseteq B(\tau)$ and $\lambda=\mu_{|B(\tau')}$?
(2) For the measure-theoretical entropy, do we have a statement or property telling that we can "split" it like
    $$
h_{\mu}(T)=h_{\lambda}(S)+h_{\mu_{|B(\tau')^C}}(T_{|Y^C})?
$$

(1) I think this follows by $\tau'\subseteq \tau$, hence $B(\tau')=\sigma(\tau')\subseteq\sigma(\tau)=B(\tau)$. Moreoever, both $(X,\tau)$ and $(Y,\tau')$ are separable, hence $B(\tau)=\sigma(C)$ and $B(\tau')=\sigma(C')$, meaning that the Borel $\sigma$-algebras coincide with the product $\sigma$-algebras (= cylinder $\sigma$-algebras). Moreover, $\mu=\lambda$ on $C'$ and $C'$ is invariant under intersection. By uniqueness theorem, $\mu=\lambda$ on $\sigma(C')$.
(2) The reason why I am asking this is because I have an example where I can argue that $h_{\lambda}(S)=0$ and for further investigation I would like to know if this implies that $h_{\mu}(T)$ can be determined by neglecting "what $S$ and $\lambda$ do".  I have no idea...
In case the splitting above is not correct, maybe there is another formula connecting $h_{\mu}(T)$ and $h_{\lambda}(S)$?


text:
Q: How to stop RelativeLayout from changing its height automatically? I am trying to create an app, that has a RelativeLayout inside a ScrollView with the help of Android Studio.
I added all of the buttons, text fields and spinners that I need to make the app look just like I want it to look like.
However, after debugging the app, the RelativeLayout changed its height automatically, making the buttons, text fields and spinners unusable.
This is a picture of the app after debugging:

The XML file is as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            tools:context="fadi_christoph.pizzadeliveryapp.MainActivity">

            <TextView
                android:id="@+id/tvAnrede"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/ET_Name"
                android:layout_alignParentStart="true"
                android:text="Anrede"
                android:textAlignment="textStart"
                android:textAllCaps="false"
                android:textSize="14sp" />

            <RadioGroup
                android:id="@+id/rgAnrede"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_alignStart="@+id/ET_Name"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/rbHerr"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Herr"
                    android:textSize="14sp" />

                <RadioButton
                    android:id="@+id/rbFrau"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Frau"
                    android:textSize="14sp" />

            </RadioGroup>

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/ET_Name"
                android:layout_alignBottom="@+id/ET_Name"
                android:layout_alignParentStart="true"
                android:text="Vor- und Nachname"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/tfName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_below="@+id/RG_Anrede"
                android:layout_toEndOf="@+id/TV_Name"
                android:ems="10"
                android:hint="Vor- und Nachname"
                android:inputType="textPersonName"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/tvPost"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/ET_Post"
                android:layout_alignBottom="@+id/ET_Post"
                android:layout_alignParentStart="true"
                android:text="Postleitzahl"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/tfPost"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignStart="@+id/ET_Name"
                android:layout_below="@+id/ET_Name"
                android:ems="10"
                android:hint="Postleitzahl"
                android:inputType="numberDecimal"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/tvOrt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/ET_Ort"
                android:layout_alignBottom="@+id/ET_Ort"
                android:layout_alignParentStart="true"
                android:text="Ort"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/tfOrt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignStart="@+id/ET_Post"
                android:layout_below="@+id/ET_Post"
                android:ems="10"
                android:hint="Ort"
                android:inputType="textPersonName"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/tvStrasse"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/ET_Strasse"
                android:layout_alignBottom="@+id/ET_Strasse"
                android:layout_alignParentStart="true"
                android:text="Straße"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/tfStrasse"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignStart="@+id/ET_Ort"
                android:layout_below="@+id/ET_Ort"
                android:ems="10"
                android:hint="Straße"
                android:inputType="textPersonName"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/tvHausnummer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/ET_Hausnummer"
                android:layout_alignBottom="@+id/ET_Hausnummer"
                android:layout_alignParentStart="true"
                android:text="Hausnummer"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/tfHausnummer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignStart="@+id/ET_Strasse"
                android:layout_below="@+id/ET_Strasse"
                android:ems="10"
                android:hint="Hausnummer"
                android:inputType="textPersonName"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/tvRechnung"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/ET_Hausnummer"
                android:text="Rechnung"
                android:textSize="14sp" />

            <RadioGroup
                android:id="@+id/rgRechnung"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignStart="@+id/ET_Hausnummer"
                android:layout_below="@+id/ET_Hausnummer"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/rbPost"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="per Post"
                    android:textSize="14sp" />

                <RadioButton
                    android:id="@+id/rbEmail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="per Email"
                    android:textSize="14sp" />

            </RadioGroup>

            <TextView
                android:id="@+id/tvFilter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/SP_Filter"
                android:layout_alignParentStart="true"
                android:text="suche nach"
                android:textSize="14sp" />

            <Spinner
                android:id="@+id/spinnerFilter"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignStart="@+id/RG_Rechnung"
                android:layout_below="@+id/RG_Rechnung" />

            <TextView
                android:id="@+id/tvPizza"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/SP_Pizza"
                android:layout_alignParentStart="true"
                android:text="Auswahl der Pizza"
                android:textSize="14sp" />

            <Spinner
                android:id="@+id/spinnerPizza"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignStart="@+id/SP_Filter"
                android:layout_below="@+id/SP_Filter"
                android:spinnerMode="dialog" />

            <TextView
                android:id="@+id/tvZusaetzen"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/RG_Bezahlen"
                android:layout_alignParentStart="true"
                android:text="Zusätzen"
                android:textSize="14sp" />

            <Spinner
                android:id="@+id/spinnerZusaetzen"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignStart="@+id/SP_Pizza"
                android:layout_below="@+id/SP_Pizza"
                android:spinnerMode="dialog" />

            <TextView
                android:id="@+id/tvBezahlen"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/SP_Zusaetzen"
                android:layout_marginTop="11dp"
                android:text="bezahlen"
                android:textSize="14sp" />

            <RadioGroup
                android:id="@+id/rgBezahlen"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignStart="@+id/SP_Zusaetzen"
                android:layout_below="@+id/SP_Zusaetzen">

                <RadioButton
                    android:id="@+id/rbBar"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="bar bei Abholung"
                    android:textSize="14sp" />

                <RadioButton
                    android:id="@+id/rbKreditkarte"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Kreditkarte"
                    android:textSize="14sp" />

                <RadioButton
                    android:id="@+id/rbSofort"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Sofortüberweisung"
                    android:textSize="14sp" />

            </RadioGroup>

            <TextView
                android:id="@+id/tvPreis"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/RG_Bezahlen"
                android:layout_marginTop="16dp"
                android:text="Preis" />

            <TextView
                android:id="@+id/tvEuro"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/TV_Preis"
                android:layout_alignBottom="@+id/TV_Preis"
                android:layout_alignStart="@+id/RG_Bezahlen"
                android:text="0,00 €"
                android:textSize="24sp" />

            <Button
                android:id="@+id/btnSenden"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/TV_Euro"
                android:layout_marginTop="18dp"
                android:text="Senden" />

            <Button
                android:id="@+id/btnZuruecksetzen"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/BT_Senden"
                android:layout_alignBottom="@+id/BT_Senden"
                android:layout_toEndOf="@+id/BT_Senden"
                android:text="Zurücksetzen" />

        </RelativeLayout>

    </ScrollView>

A partial code of my program is as follows:
    package fadi_christoph.pizzadeliveryapp;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.view.View;
    import android.widget.*;
    import java.lang.String;

    public class MainActivity extends AppCompatActivity {

        private TextView tv_Anrede, tv_Name, tv_Post, tv_Ort, tv_Strasse, tv_Hausnummer, tv_Rechnung, tv_Filter, tv_Pizza, tv_Zusaetzen, tv_Bezahlen, tv_Preis, tv_Euro;
        private RadioGroup rg_Anrede, rg_Rechnung, rg_Bezahlen;
        private RadioButton rb_Herr, rb_Frau, rb_Post, rb_Email, rb_Bar, rb_Kreditkarte, rb_Sofort;
        private EditText tf_Name, tf_Post, tf_Ort, tf_Strasse, tf_Hausnummer;
        private Spinner spinner_Filter, spinner_Pizza, spinner_Zusaetzen;
        private Button btn_Senden, btn_Zuruecksetzen;

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

        private void InitializeApp() {
            tv_Anrede = (TextView) findViewById(R.id.tvAnrede);
            tv_Name = (TextView) findViewById(R.id.tvName);
            tv_Post = (TextView) findViewById(R.id.tvPost);
            tv_Ort = (TextView) findViewById(R.id.tvOrt);
            tv_Strasse = (TextView) findViewById(R.id.tvStrasse);
            tv_Hausnummer = (TextView) findViewById(R.id.tvHausnummer);
            tv_Rechnung = (TextView) findViewById(R.id.tvRechnung);
            tv_Filter = (TextView) findViewById(R.id.tvFilter);
            tv_Pizza = (TextView) findViewById(R.id.tvPizza);
            tv_Zusaetzen = (TextView) findViewById(R.id.tvZusaetzen);
            tv_Bezahlen = (TextView) findViewById(R.id.tvBezahlen);
            tv_Preis = (TextView) findViewById(R.id.tvPreis);
            tv_Euro = (TextView) findViewById(R.id.tvEuro);
            rg_Anrede = (RadioGroup) findViewById(R.id.rgAnrede);
            rg_Rechnung = (RadioGroup) findViewById(R.id.rgRechnung);
            rg_Bezahlen = (RadioGroup) findViewById(R.id.rgBezahlen);
            rb_Herr = (RadioButton) findViewById(R.id.rbHerr);
            rb_Frau = (RadioButton) findViewById(R.id.rbFrau);
            rb_Post = (RadioButton) findViewById(R.id.rbPost);
            rb_Email = (RadioButton) findViewById(R.id.rbEmail);
            rb_Bar = (RadioButton) findViewById(R.id.rbBar);
            rb_Kreditkarte = (RadioButton) findViewById(R.id.rbKreditkarte);
            rb_Sofort = (RadioButton) findViewById(R.id.rbSofort);
            tf_Name = (EditText) findViewById(R.id.tfName);
            tf_Post = (EditText) findViewById(R.id.tfPost);
            tf_Ort = (EditText) findViewById(R.id.tfOrt);
            tf_Strasse = (EditText) findViewById(R.id.tfStrasse);
            tf_Hausnummer = (EditText) findViewById(R.id.tfHausnummer);
            spinner_Filter = (Spinner) findViewById(R.id.spinnerFilter);
            spinner_Pizza = (Spinner) findViewById(R.id.spinnerPizza);
            spinner_Zusaetzen = (Spinner) findViewById(R.id.spinnerZusaetzen);
            btn_Senden = (Button) findViewById(R.id.btnSenden);
            btn_Zuruecksetzen = (Button) findViewById(R.id.btnZuruecksetzen);

            SPFilterSelectedLine();
        }

        //Determine the chosen position of the filter spinner, convert its text to a string and pass it along:
        private void SPFilterSelectedLine() {
            //implement XML file "strings.xml" found in "app\src\main\res\values"
            //ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.filter,android.R.layout.simple_spinner_item);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.filter));
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner_Filter.setAdapter(adapter);

            //Get the position of the chosen element, convert it to text and pass it along
            spinner_Filter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (!(view instanceof TextView))
                        return;
                    TextView item = (TextView) view;
                    String TypeOfPizza = item.getText().toString();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        }
    }

The strings.xml file that I use for the ArrayAdapter is as follows:
        <resources>
        <string name="app_name">Pizza Delivery App</string>

        <string-array name="filter">
            <item>vegetarische Pizzen</item>
            <item>fischhaltige Pizzen</item>
            <item>fleischhaltige Pizzen</item>
            <item>fischhaltige und fleischhaltige Pizzen</item>
        </string-array>

        <string-array name="vegetarisch">
            <item>vegetarische Pizza 1</item>
            <item>vegetarische Pizza 2</item>
            <item>vegetarische Pizza 3</item>
            <item>vegetarische Pizza 4</item>
        </string-array>

        <string-array name="fischhaltig">
            <item>fischhaltige Pizza 1</item>
            <item>fischhaltige Pizza 2</item>
            <item>fischhaltige Pizza 3</item>
            <item>fischhaltige Pizza 4</item>
        </string-array>

        <string-array name="fleischhaltig">
            <item>fleischhaltige Pizza 1</item>
            <item>fleischhaltige Pizza 2</item>
            <item>fleischhaltige Pizza 3</item>
            <item>fleischhaltige Pizza 4</item>
        </string-array>

        <string-array name="fischhaltig_und_fleischhaltig">
            <item>fischhaltige und fleischhaltige Pizza 1</item>
            <item>fischhaltige und fleischhaltige Pizza 2</item>
            <item>fischhaltige und fleischhaltige Pizza 3</item>
            <item>fischhaltige und fleischhaltige Pizza 4</item>
        </string-array>
    </resources>

I will be greatful if anyone can help me to figure out what the problem seems to be.

A: I tried your xml code. I Changed your root element in the ScrollView from RelativeLayout to LinearLayout with orientation vertical and it looked fine. You will have to remove some RelativeLayout properties.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context="fadi_christoph.pizzadeliveryapp.MainActivity">

        ...

    </LinearLayout>

</ScrollView>

A: You should try edit height from a different place. Sometimes Android Studio gives me also the error for a missed \ before ' , the only way i figured out to stay away from this type of error is edit it from a normal reader like block notes.


text:
Q: DeepStreaming on digitalocean I'm working on setting up deepstearm.io using this guide.
However, I get the following error:

PLUGIN_ERROR | storage wasn't initialised in time

Able to ping mongodb serever from deepstream server
I tried changing dependencyInitialisationTimeout to 20000. It didn't work.
I Attached the command and error message for your reference:

A: I solved this by adding a firewall rule on the mongodb node allowing incoming connections to port 27017
ufw allow  27017

Maybe it is even better to just allow the deepstream node ip


text:
Q: How to use a MessageBox in a function I am trying to get function to take in two strings and show message box:
public void Myfunction (string str1, string str2)
     {
         MessageBox.Show("your message was " + str1 + Environment.NewLine + str2);
     }

private void Btn_Display_Click(object sender, RoutedEventArgs e)
    {
        string today;
        today = DateTime.Now.ToString("dd/MM/yyyy");
        myfunction(TextBox_Msg.Text, today);
    }

A: It's not clear what's going on, say, what myfunction is supposed to do? Functions compute values.
I suggest showing message in one go:
    private void Btn_Display_Click(object sender, RoutedEventArgs e) {
      // Show message - MessageBox.Show
      // of several lines - string.Join(Environment.NewLine
      //   1st line "your message was" + TextBox_Msg.Text
      //   2nd line DateTime.Now in "dd/MM/yyyy" format
      MessageBox.Show(string.Join(Environment.NewLine,
        $"your message was {TextBox_Msg.Text}",
          DateTime.Now.ToString("dd/MM/yyyy")));
    }

If you insist on extracting method then, let's first rename it - ShowMessageLines:
// Let's show arbitrary many lines (whe only 2?)
// Let's accept all types (not necessary strings)
public static void ShowMessageLines(params object[] lines) {
  // public method - input arguments validation
  if (null == lines)
    throw new ArgumentNullException(nameof(lines));

  // Combine all lines into textToShow
  // First line must have a prefix - "your message was "
  string textToShow = string.Join(Environment.NewLine, lines
    .Select((text, index) => index == 0
       ? $"your message was {text}"
       :   text?.ToString()));

  MessageBox.Show(textToShow);
}

...

private void Btn_Display_Click(object sender, RoutedEventArgs e) {
  ShowMessageLines(
    TextBox_Msg.Text,
    DateTime.Now.ToString("dd/MM/yyyy"));
}


text:
Q: Metal programming- all transparent textures coming out as though 1-bit alpha masked So we've been banging at this for a few hours now.
All transparent textures we use, regardless of format we've tried (TGA, PNG, etc.) exhibit a solid outline where the alpha channel begins to fade in; like a 1-bit alpha mask (think hard outline). It's not a border around the image, just a hard silhouette around where any alpha blending occurs, and nothing else. No real blending happening.
We've tried every manner of blend function combination referenced online for proper alpha blending without avail. They all change the blending style, but nothing makes the lost information (for blending gradations) appear.
Even using the blend functions listed in the solution here:
Metal MTLTexture replaces semi-transparent areas with black when alpha values that aren't 1 or 0
doesn't help it.
Thoughts?
Thanks!


text:
Q: How to trigger Alert after Server Error Response with Dropzone.js I want to trigger a javascript alert from dropzone.js when the server returns an error. (in json).
Here is my function/method.  It seems to be working fine.
public function file_upload($account_id,$bid_id) {
    $path = FMREPO . "/account-" . $account_id . "/bid-project-" .$bid_id . "/";
    if (file_exists ( $path )){
        if (!empty($_FILES)) {
            $tempFile = $_FILES['file']['tmp_name'];
            $fileName = $_FILES['file']['name'];
            $targetPath = $path . "diagram-" . $bid_id . "-";
            $targetFile = $targetPath . $fileName ;
            move_uploaded_file($tempFile, $targetFile);
                // $this->load->database(); // load database
                // $this->db->insert('file_table',array('file_name' => $fileName));
        }
    } else{
        header('HTTP/1.1 500 Internal Server Directory Not Found');
        header('Content-Type: application/json; charset=UTF-8');
        die(json_encode(array('error' => 'File Could Not Be Saved')));
    }
}

Here is my Dropzone options. This is the part I don't know how to do or make it work. The "error:" is what I added but it always triggers an alert, even when the file upload was successfull.  What do I need to do here?
Dropzone.options.diagramDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 6, // MB
maxFiles: 2,
thumbnailWidth: 100,
thumbnailHeight: 100,
error: function(){
    alert('error');
},
init: function() {
    this.on("maxfilesexceeded", function(file){
        alert("No more files please!");
        console.log(file);
        this.removeFile(file);
    });
}

}
Edit: I just realized this
error: function(){
       //alert here
    },
should be
error: function(response){
        //alert here
},
so now that is working!  But the with alert(response) I get [object].  So now the question is how do I alert my string?

A: You can set up you alert inside the init option like this:
init: function() {
    this.on("maxfilesexceeded", function(file){
        alert("No more files please!");
        console.log(file);
        this.removeFile(file);
    }),
    this.on("error", function(file, errorMessage, xhr) {
        alert(errorMessage);
    ])
}


text:
Q: How to hide all children div except a specific one with jQuery?

    ...

$('#target').children().hide(); will hide all.

A: I believe that  $('#target > div').not('#exclude').hide() should do what you want.
Or alternately if you want sub-children that are divs too, $('#target div').not('#exclude').hide()

A: What you're wanting to do is hide all of the siblings of a particular element. That's relatively simple with jQuery using the .siblings method:
$("#exclude").siblings().hide();

This will hide all elements on the same level, in the same parent element.

A: Use the :not selector

A: $('#target').children().hide();
$('#exclude').show();

A: Have you tried using the "not" selector with the id that you want to exclude?
http://docs.jquery.com/Selectors/not#selector
Also, the obvious answer would be to follow it with a $('#exclude').show()


text:
Q: Unable to get refresh token for google Oauth2 with xamarin android I am trying to implement google authentication in my xamarin android app.  I am using OAuth2Authenticator to authenticate my user and after authentication it only returns access_token.How do i get refresh_token so that the user dont have to login each time he opens the app?
I have been using the following code to authenticate the user
 var auth = new OAuth2Authenticator(
            clientId: "***************************.apps.googleusercontent.com",
            scope: "https://www.googleapis.com/auth/userinfo.profile",
            authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
            redirectUrl: new Uri("https://www.googleapis.com/plus/v1/people/me"),
            accessTokenUrl: newUri("https://www.googleapis.com/oauth2/v4/token"),
            clientSecret: "*********************",
            getUsernameAsync: null);

auth.Completed += async (sender, e) =>
            {
                if (!e.IsAuthenticated)
                {
                    Toast.MakeText(this, "Fail to authenticate!", ToastLength.Short).Show();
                    return;
                }
                string access_token;
                e.Account.Properties.TryGetValue("access_token", out access_token);
}

A: It seems there are some issues with Xamarin.Auth and Google due to Google no longer recommending using the app's built in WebView for login and instead one should use the devices browser. See Google's article on this:
https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html
If you do use a WebView built in to the app, as Xamarin.Auth does by default, you will not get a refresh token as (per the article linked above):

In contrast, the outdated method of using embedded browsers for OAuth means a user must sign-in to Google each time, instead of using the existing logged-in session from the device.

A: Xamarin Auth doesn't support refresh_token
https://github.com/xamarin/Xamarin.Auth/pull/79
I implemeted an inherated class you can find on my gist
It works for my custom identity provider (refresh_token is returned in params).
You can try my solution.
Hi!
Lewix


text:
Q: unpacking Tuples in dict So i'm making a game, and I have a dictionary of tuples containing the coordinates of the objects on the playing field that looks like this (for example):
location = {player : (1, 4), monster : (3, 2), escape : (4, 0)}

later in my code, I want to change the coordinates to easier to understand areas. The first defining part would be a corresponding letter, and then the second a number, looking like this: player would be in B4, monster in C2, and so on. the top right 'area' is represented by the tuple (4, 4), and the bottom left 'area' is represented by the tuple (0, 0). The only thing I have been able to think of that might work is something like this:
location = {player : (1, 4), monster : (3, 2), escape : (4, 0)}
letters = ["A", "B", "C", "D", "E"]
playerArea = "{}{}".format(letters[int(location[player[0]])+1], location[player[1]])

In short, it didn't work. I think the problem is in unpacking the tuples from the dictionary and using it as the number to get the letter from the list letters. Sorry is this was confusing, i'll try to answer all your questions.

A: The core of the question is how to convert numerical row/column coordinates to something more readable (battleship-style).  Here is a simple and fast function to do just that:
>>> def rc_to_abc(x, y):
        return 'ABCDEFGHIJKLOMOPQRSTUVWXYZ'[x] + str(y)

>>> rc_to_abc(1, 4)
'B4'
>>> rc_to_abc(3, 2)
'D2'
>>> rc_to_abc(4, 0)
'E0'

A: Use a dictionary comprehension using string formatting to build the new values. Unpacking the value-tuples is easily done:
location = {k: '{}{}'.format(letters[x-1], y) for k, (x, y) in location.items()}
print(location)
# {'player': 'A4', 'monster': 'C2', 'escape': 'D0'}

Also, you can use string.ascii_uppercase instead of defining a list of alphabets manually.
OTOH, since your board supposedly has a (0, 0) not sure what you intend to make of index 0 since A is already taken as 1.

A: You can use string.ascii_uppercase to get a full list of the alphabet to use for each coordinate:
from string import ascii_uppercase as alphabet

location = {"player":(1, 4), "monster":(3, 2), "escape":(4, 0)}

new_location = {a:alphabet[b[0]-1]+str(b[-1]) for a, b in location.items()}

print(new_location)

Output:
{'player': 'A4', 'monster': 'C2', 'escape': 'D0'}


text:
Q: Problem with Amavis and Relayhost on Postfix I'm new to all this.
I try to set up Postfix on Ubuntu Server 16.04TLS
My situation requires to use a relay server to send external mails
Main.cf:
#RELAY STUFF
#enable SASL authentication
smtp_sasl_auth_enable = yes
# disallow methods that allow anonymous authentication.
smtp_sasl_security_options = noanonymous
# where to find sasl_passwd
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
# Enable STARTTLS encryption
smtp_use_tls = yes
# where to find CA certificates
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

smtp_tls_wrappermode = yes
smtp_tls_security_level = encrypt

relayhost = [mailgate.myisp.net]:465

This configuration works fine and I can send and receive mails both locally and to other domains.
However as soon as I try to activate Amavis with the following line:
content_filter = amavis:[127.0.0.1]:10024

I get errors on my log:
Dec 20 13:21:41 iserv postfix/qmgr[4628]: 54AFB8408F7: from=<mail1@mydomain.net>, size=358, nrcpt=1 (queue active)
Dec 20 13:21:41 iserv postfix/smtp[4678]: SSL_connect error to 127.0.0.1[127.0.0.1]:10024: -1
Dec 20 13:21:41 iserv postfix/smtp[4678]: warning: TLS library problem: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:794:
Dec 20 13:21:41 iserv postfix/smtp[4678]: 54AFB8408F7: to=<mail2@mydomain.net>, relay=127.0.0.1[127.0.0.1]:10024, delay=33, delays=33/0.03/0.01/0, dsn=4.7.5, status=deferred (Cannot start TLS: handshake failure)
Dec 20 13:21:44 iserv postfix/smtpd[4674]: disconnect from localhost[::1] ehlo=1 mail=1 rcpt=1 data=1 quit=1 commands=5smtp[7450]: warning: TLS library problem: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:794:

Does anyone knows any solution to this ?
It seems that postfix tries to use TLS with Amavis as well.
On my Master.cf I tried:
amavis    unix    -       -       -       -       2       smtp
    -o smtp_tls_security_level=none
    -o smtpd_tls_security_level=none
    -o smtp_data_done_timeout=1200
    -o smtp_send_xforward_command=yes
    -o disable_dns_lookups=yes
    -o max_use=20
127.0.0.1:10025 inet    n       -       -       -       -       smtpd
    -o content_filter=
    -o smtpd_tls_security_level=none
    -o smtp_tls_security_level=none
    -o local_recipient_maps=
    -o relay_recipient_maps=
    -o smtpd_restriction_classes=
    -o smtpd_delay_reject=no
    -o smtpd_client_restrictions=permit_mynetworks,reject
    -o smtpd_helo_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o smtpd_data_restrictions=reject_unauth_pipelining
    -o smtpd_end_of_data_restrictions=
    -o mynetworks=127.0.0.0/8
    -o smtpd_error_sleep_time=0
    -o smtpd_soft_error_limit=1001
    -o smtpd_hard_error_limit=1000
    -o smtpd_client_connection_count_limit=0
    -o smtpd_client_connection_rate_limit=0
    -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks

As you can see I tried to override amavis with
-o smtp_tls_security_level=none
-o smtpd_tls_security_level=none

I also tried to modify smtps:
smtps     inet  n       -       y       -       -       smtpd
#  -o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtp_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING

Now I get these errors:
Dec 20 17:06:05 iserv postfix/smtpd[11186]: connect from localhost[::1]
Dec 20 17:06:41 iserv postfix/smtpd[11186]: DA28F840BD8: client=localhost[::1]
Dec 20 17:06:51 iserv postfix/cleanup[11190]: DA28F840BD8: message-id=<20161220150641.DA28F840BD8@mail.mydomain.net>
Dec 20 17:06:51 iserv postfix/qmgr[11142]: DA28F840BD8: from=<mail1@mydomain.net>, size=333, nrcpt=1 (queue active)
Dec 20 17:06:51 iserv postfix/smtp[11191]: warning: smtp_tls_wrappermode requires "smtp_tls_security_level = encrypt" (or stronger)
Dec 20 17:06:51 iserv postfix/smtp[11191]: DA28F840BD8: to=<mail2@mydomain.net>, relay=none, delay=22, delays=22/0.02/0/0, dsn=4.3.0, status=deferred (server unavailable or unable to receive mail)
Dec 20 17:07:32 iserv postfix/smtpd[11186]: 79388840BDA: client=localhost[::1]
Dec 20 17:07:41 iserv postfix/cleanup[11190]: 79388840BDA: message-id=<20161220150732.79388840BDA@mail.mydomain.net>
Dec 20 17:07:41 iserv postfix/qmgr[11142]: 79388840BDA: from=<mail1@mydomain.net>, size=334, nrcpt=1 (queue active)
Dec 20 17:07:41 iserv postfix/smtp[11191]: warning: smtp_tls_wrappermode requires "smtp_tls_security_level = encrypt" (or stronger)
Dec 20 17:07:41 iserv postfix/smtp[11191]: 79388840BDA: to=<myemail@gmail.com>, relay=none, delay=20, delays=20/0/0/0, dsn=4.3.0, status=deferred (server unavailable or unable to receive mail)
Dec 20 17:07:44 iserv postfix/smtpd[11186]: disconnect from localhost[::1] ehlo=1 mail=2/3 rcpt=2 data=2 quit=1 commands=8/9

If I remove amavis
#content_filter = amavis:[127.0.0.1]:10024

Then it all works!
PS: If I don't setup the relay server and use the "default" values for Amavis that I find all over the net then everything works besides sending mail to external domains.
After more searching it seems that it's the
smpt_tls_wrappermode=yes

option that brakes things up.
Without it my mail server works but I get an error when trying to communicate with the relay server:
Dec 20 19:43:36 iserv postfix/smtp[18270]: SMTPS wrappermode (TCP port 465) requires setting "smtp_tls_wrappermode = yes", and "smtp_tls_security_level = encrypt" (or stronger)
Dec 20 19:44:36 iserv postfix/smtp[18270]: 9BBD5840C1C: to=<myemail@gmail.com>, relay=mailgate.myisp.net[62.103.147.202]:465, delay=60, delays=0/0.03/60/0, dsn=4.4.2, status=deferred (conversation with mailgate.myisp.net[XXX.XXX.XXX.XXX] timed out while receiving the initial server greeting)

Any help ?
Currently I'm completely lost.
Thank you!

A: Ok, for future reference if anyone else has the same issue:
1) You MUST use smtp_tls_wrappermode =yes and smtp_tls_security_level = encrypt on main.cf
2) You must override both these settings on AMAVIS and 127.0.0.1:10025 services on master.cf
So, currently my main.cf file looks like this:
smtpd_banner = $myhostname ESMTP $mail_name
biff = no

append_dot_mydomain = no
readme_directory = no

myhostname = mail.mydomain.gr
myorigin = mydomain.gr
mydestination =
masquerade_domains = mail.mydomain.gr www.mydomain.gr
relayhost = [mailgate.myisp.gr]:465
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mynetworks_style = host
inet_interfaces = all
inet_protocols = all
mailbox_size_limit = 0
recipient_delimiter = +
local_recipient_maps =
alias_maps = hash:/etc/postfix/aliases
alias_database = hash:/etc/postfix/aliases
virtual_mailbox_base = /var/spool/mail/virtual
virtual_mailbox_maps = mysql:/etc/postfix/mysql_mailbox.cf
virtual_alias_maps = mysql:/etc/postfix/mysql_alias.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql_domains.cf
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
# transport_maps = mysql:/etc/postfix/mysql_transport.cf
content_filter = amavis:[127.0.0.1]:10024

delay_warning_time = 4h
unknown_local_recipient_reject_code = 450
maximal_queue_lifetime = 7d
minimal_backoff_time = 1000s
maximal_backoff_time = 8000s

smtp_helo_timeout = 90s
# smtp_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtp_tls_wrappermode = yes
smtp_tls_security_level = encrypt
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
# smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd

tls_random_source = dev:/dev/urandom

smtpd_helo_required = yes
smtpd_recipient_limit = 16
smtpd_soft_error_limit = 3
smtpd_hard_error_limit = 12
smtpd_helo_restrictions = permit_mynetworks, warn_if_reject reject_non_fqdn_hostname, reject_invalid_hostname, permit
smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit
smtpd_recipient_restrictions = reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, permit
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_client_restrictions = reject_rbl_client sbl.spamhaus.org, reject_rbl_client blackholes.easynet.nl
smtpd_data_restrictions = reject_unauth_pipelining
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain =
smtpd_sasl_path = smtpd
smtpd_use_tls=no
smtpd_tls_security_level = may
# smtpd_tls_auth_only = no
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
smtpd_tls_cert_file=/etc/postfix/postfix.cert
smtpd_tls_key_file=/etc/postfix/postfix.key
# smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_delay_reject = yes
disable_vrfy_command = yes
broken_sasl_auth_clients = yes

And my maps.cf file looks like this:
smtp      inet  n       -       y       -       -       smtpd
#smtp      inet  n       -       y       -       1       postscreen
#smtpd     pass  -       -       y       -       -       smtpd
#dnsblog   unix  -       -       y       -       0       dnsblog
#tlsproxy  unix  -       -       y       -       0       tlsproxy
submission inet n       -       y       -       -       smtpd
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_tls_auth_only=yes
#  -o smtpd_tls_security_level=encrypt
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject_unauth_destination,reject
  -o smtpd_sasl_security_options=noanonymous,noplaintext
  -o smtpd_sasl_tls_security_options=noanonymous
#  -o syslog_name=postfix/submission
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       y       -       -       smtpd
#  -o smtp_use_tls=yes
  -o smtp_tls_wrappermode=yes
  -o smtp_tls_security_level=encrypt
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_tls_auth_only=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_sasl_security_options=noanonymous,noplaintext
  -o smtpd_sasl_tls_security_options=noanonymous
#  -o syslog_name=postfix/smtps
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       y       -       -       qmqpd
pickup    unix  n       -       y       60      1       pickup
  -o content_filter=
  -o receive_override_options=no_header_body_checks
cleanup   unix  n       -       y       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       y       1000?   1       tlsmgr
rewrite   unix  -       -       y       -       -       trivial-rewrite
bounce    unix  -       -       y       -       0       bounce
defer     unix  -       -       y       -       0       bounce
trace     unix  -       -       y       -       0       bounce
verify    unix  -       -       y       -       1       verify
flush     unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       y       -       -       smtp
relay     unix  -       -       y       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       y       -       -       showq
error     unix  -       -       y       -       -       error
retry     unix  -       -       y       -       -       error
discard   unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
 scalemail-backend unix -   n   n   -   2   pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
 mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
#
#FOR AMAVISD
amavis    unix    -       -       y       -       2       smtp
    -o smtp_tls_security_level=none
    -o smtp_tls_wrappermode=no
#    -o smtpd_tls_security_level=none
    -o smtp_data_done_timeout=1200
    -o smtp_send_xforward_command=yes
    -o disable_dns_lookups=yes
    -o max_use=20
#
127.0.0.1:10025 inet    n       -       y       -       -       smtpd
    -o content_filter=
    -o smtpd_tls_security_level=none
    -o smtp_tls_wrappermode=no
#    -o smtp_tls_security_level=none
    -o local_recipient_maps=
    -o relay_recipient_maps=
    -o smtpd_restriction_classes=
    -o smtpd_delay_reject=no
    -o smtpd_client_restrictions=permit_mynetworks,reject
    -o smtpd_helo_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o smtpd_data_restrictions=reject_unauth_pipelining
    -o smtpd_end_of_data_restrictions=
    -o mynetworks=127.0.0.0/8
    -o smtpd_error_sleep_time=0
    -o smtpd_soft_error_limit=1001
    -o smtpd_hard_error_limit=1000
    -o smtpd_client_connection_count_limit=0
    -o smtpd_client_connection_rate_limit=0
    -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks

Now, both SMTPS for relayhost on port 465 and Amavis work fine.

A: It's smtpd_tls_wrappermode, not smtp_tls_wrappermode...
So use
smtpd_tls_wrappermode = yes


text:
Q: Correct display of data after aggregation In continuation of my question
There is a table in a CSV file format:

A
B

35480007
0695388

35480007
0695388

35407109
3324741

35407109
3324741

35250208
0695388

35250208
6104556

86730903
3360935

86730903
3360935

By applying the code for aggregation:
df.groupby("B")["A"].unique()

I get the result:
695388     [35480007, 35250208]
3324741              [35407109]
3360935              [86730903]
6104556              [35250208]

Could you  tell me please, how can I apply some kind of filter so that only those values that have a value greater than two can be displayed: that is so:
695388     [35480007, 35250208]

and how to save the result to a file, for example in txt.
I apologize in advance if my question seemed incorrect. I am very weak in the pandas library.
thank you very much!

A: It took me a second to realize that what you mean is not a value greater than two, but rather a length greater than one (or greather than or equal to two).
With that said, you can use the apply function on your Series to see which rows satisfy this property
grouped = df.groupby("B")["A"].unique()
has_multiple_elements = grouped.apply(lambda x: len(x)>1)

Which basically applies a function to each entry in your grouped series, and returns the following:
695388      True
3324741    False
3360935    False
6104556    False

Now all that's left is to use these True/False boolean values to filter your series. Luckily, this is very simple.
result = grouped[has_multiple_elements]

As for the second part of your question, writing this to a file can be done using the to_csv function:
# I usually use tab separated files in case any commas appear in your data itself
result.to_csv('output.tsv', sep='\t')


text:
Q: Jmeter - how to implement another java class Greetings all,
In another post I asked about rendering PDF in Jmeter, and it would seem the solution is to use iText.
Using iText requires installing another library and referencing it. Does anyone know how to do this? I can't find a tutorial. Much thanks. iText is also dependent upon bouncycastle
iText: http://www.1t3xt.com/downloads/index.php
iText dependency: http://www.bouncycastle.org/latest_releases.html

A: You just need to add it to your classpath when running JMeter.  Unfortunately in the jmeter.bat or jmeter.sh they run JMeter using the -jar flag which will ignore your custom classpath.  To get around this you need to simply include the ApacheJMeter jar in your class path and run the class org.apache.jmeter.NewDriver as your starting class.


text:
Q: Find and delete duplicates only if two fields have matching data Ms Access I want to create a query that would find and delete duplicates only if two fields have matching data. Not meaning those two fields match exactly, like field A and field B both have "unprocessed" but in a sense that two records in the table have "1234" in field A AND "unprocessed" in field B then that whole row of record should be deleted and only the oldest record (the one clearly closer to the column headings) will stay in the table.
Hopefully that makes sense. Thanks!

A: As always, be sure to take a backup of your access database before you do any of this deleting.
NOTE, you can create these queries by switching to "SQL" view on the query. (rather than the default 'Design' view).
Step 1 - Identify the duplicate data.  Create a make table group by query that groups by the 2 fields that you want to check for duplicates on, and then take a count and a max.  Filter to show only records that have a count > 1. Save this as "Query1".  This will create a temporary table called TEMP_DeleteThese.
SELECT Table1.CaseID, Table1.Status,
        Count(Table1.ID) AS CountOfID,
        Max(Table1.ID) AS MaxOfID
INTO TEMP_DeleteThese
FROM Table1
GROUP BY Table1.CaseID, Table1.Status
HAVING (((Count(Table1.ID))>1));

Step 2 - Create a delete query based upon TEMP_DeleteThese and a join back to the original Table, through the "Max ID" field, which will be the newest duplicate record.
DELETE DISTINCTROW Table1.*
FROM TEMP_DeleteThese INNER JOIN Table1 ON TEMP_DeleteThese.MaxOfID = Table1.ID;

Run both the make table and delete queries as many times as needed to delete all duplicates.
I made an assumption here that you have a primary key (in this case "Table1.ID") that is auto numbered starting with low numbers, and counting to higher.