text:
Q: seaborn gridplot/subplots to show one variable on the 1st column and another variable on 2nd column for the same row ID I am trying to plot a seaborn gridplot subplot such that
1. Each row of the figure/plot will have the graph of one client entity that am trying to plot.
2. The columns of this row will represent line plots of different variables of that same client.
So for instance, if there are client ABC, XYZ, PQR with historical income trend and historical expense trend,
I would like to plot
ABC's Income subplot and then expense subplot next to it
XYZ's Income subplot and then expense subplot next to it
PQRS's Income subplot and then expense subplot next to it.
I am able to plot the subplots for the same variable, however unable to include the second variable in the second column.
Any pointers would be extremely useful.
num_plots = len(clients)
fig,ax=plt.subplots(30,2,figsize=(12,96))
fig.subplots_adjust(hspace=0.4,wspace=0.4)
for x in range(num_plots):
    df = dfABC[dfABC['Client'] == clients[x]]
    row = x//2
    col = x%2
    ax_curr = ax[row,col]
    sns.lineplot(data=df,x='Year',y='Income',ax=ax_curr).set_title(clients[x])

This is creates a 30 row by 2 columns plot with each plot only representing Income.
How can i have the Expense line plot as the 2nd column ?

A: import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns

# Data generation
clients = ['ABC', 'XYZ', 'PQR']
n_points = 1000
dfABC = pd.DataFrame(
        {'Client': np.random.choice(clients, size=n_points),
         'Year': np.random.choice([2010, 2011, 2012, 2013], size=n_points),
         'Income': np.random.exponential(size=n_points)*10,
         'Expense': np.random.exponential(size=n_points)})

# Figure generation
clients = list(dfABC['Client'].unique())
n_rows = len(clients)
fig,ax=plt.subplots(n_rows,2,figsize=(12,96))
fig.subplots_adjust(hspace=0.4,wspace=0.4)
for i, client in enumerate(clients):
    df = dfABC[dfABC['Client'] == client]
    sns.lineplot(data=df,x='Year',y='Income',ax=ax[i, 0]).set_title(client)
    sns.lineplot(data=df,x='Year',y='Expense',ax=ax[i, 1]).set_title(client)


text:
Q: Get the number of received bytes in Netty for gzip chunked response I'm trying to solve a problem in a description. Currently I have this pipeline:
p.addLast(sslCtx.newHandler(ch.alloc()));
p.addLast(new HttpClientCodec());
p.addLast(new MyCustomHttpContentDecompressor());
// p.addLast(new HttpObjectAggregator(1048576));
p.addLast(businessLogicHandler);

When server returns non chunked response, it contains Content-Length header. I succeeded to retrieve this value in my custom HttpContentDecompressor just before it removes this header and performs gzip decompression.
But when server decides to send chunked response, I'm out of luck since there's no Content-Length header. I tried HttpObjectAggregator but seems that it returns the number of decompressed  bytes. I also reviewed netty traffic package, but it solves a different task.
I feel that solution is simple, but I do not know netty well. Maybe there's a way to add one more handler to pipeline (ex. before decompressor), that will read all bytes in buffer, save the number and pass them further to pipeline? Some code examples will be very helpful.

A: Solution:
public class TrafficInterceptorHandler extends ChannelInboundHandlerAdapter {

    public static final String NAME = "trafficInterceptor";
    private static Logger LOG = LoggerFactory.getLogger(TrafficInterceptorHandler.class);

    private AtomicInteger readBytes = new AtomicInteger(0);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            ByteBuf byteBuf = (ByteBuf) msg;
            readBytes.addAndGet(byteBuf.readableBytes());
        } else {
            LOG.warn("Received msg is not a ByteBuffer. Actual class: " + msg.getClass());
        }
        ctx.fireChannelRead(msg);
    }
    public int getReadBytes() {
        return readBytes.get();
    }
}

Should be added to pipeline before other handlers
p.addLast(TrafficInterceptorHandler.NAME, new TrafficInterceptorHandler());
p.addLast(sslCtx.newHandler(ch.alloc()));
p.addLast(new HttpClientCodec());
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compare two tables with same row type PostgreSQL I have two temporary tables of the same row type:
items
id - BIGINT
value - float

The two temp tables: called A and B have:
40 items in Table A
150 items in Table B

I want to compare every item in Table A with every item in Table B and return all items in which:
(a.value - b.value < 5)

into a third temporary table called Table C.
I can do this easily with loops, but I know loops are fairly slow, and I was wondering if there was an easy way to do it just with select statements.

A: Something like this?
insert into c
select * from a
where exists (select 1 from b where a.value - b.value < 5);

Or do you also want all values from table B?
In that case,
insert into c
select * from a
where exists (select 1 from b where a.value - b.value < 5)
union
select * from b
where exists (select 1 from a where a.value - b.value < 5);


text:
Q: - Titanium - basic create new window I have a newbie for Titanium. I try to create new page but i found error

[ERROR] :  Script Error = Can't find variable: module at newCard.js (line 21).
  [ERROR] :  Script Error = 'undefined' is not an object (evaluating 'Ti.include("ui/common/newCard.js").createWindow') at FirstView.js (line 46).

it's my test code
    function FirstView() {
    var self = Ti.UI.createView();

    var label = Ti.UI.createLabel({
        color:'black',
        text:String.format(L('welcome'),'(test)'),
        top:'50',
        align:'center',
        height:'auto',
        width:'auto'
    });
    self.add(label);

    var txtClick=Ti.UI.createLabel({
        text:String.format(L('txtclick'),'- click here -'),
        color:'red',
        top:'180',
        align:'center',
        height:'auto',
        width:'auto'
    });
    self.add(txtClick);

    var show=Ti.UI.createImageView({
        top:'100',
        width:'172',
        height:'52',
        image:'/images/logo.png'
    });
    self.add(show);

    txtClick.addEventListener('click', function(e) {
       var window = Ti.include("ui/common/newCard.js").createWindow({
        title:"new card a day"
       });
       window.open({
            animated:true
       });
    });

    return self;
}
module.exports = FirstView;

and cardNew.js
        function newCard(){
        var self = Ti.UI.createView({
            backgroundColor: 'black',
        });

        var show=Ti.UI.createImageView({
            top:'100',
            width:'172',
            height:'52',
            image:'/images/logo.png'
        });
        self.add(show);

        return self;
    }
module.exports = newCard;

please help me.
Thankyou

A: Try to change your code to this inside the eventlistener's callback:
var newCard = require("ui/common/newCard");
var win = new newCard();
win.open({animated:true});


text:
Q: how to add a touch sound(on/off) preference in settings activity how can i add toggle button for touch sound preference for whole app on settings..
 similar like this image

A: Save the status of the sound(on/off) in the preference of your application.
In the onclick listener get the status of the sound from preference as follows.
 PreferenceManager preferenceManager = new PreferenceManager(this);
 preferences.edit()
            .putBoolean("status", true/false)
            .apply();

get the status from the preference and update onclick listener
 boolean sound_status = preferences.getBoolean("status", false)
 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(sound_status == true){
               //play sound
            }

            // do your work
        }
    });

do this for all of your click listener


text:
Q: class members vs. static members in Vala I have seen https://wiki.gnome.org/Projects/Vala/Manual/Classes#Types_of_class_members and tested several times. As a result, I assume this
static members : can be accessed in a class & sub-classes of it & all instances of these
class members : can be accessed in all instances of (a class & sub-classes of it)
Is this right? And are there any other differences?

A: Let's check using the --ccode switch of the Vala compiler:
public class Test {
    public static int static_member;
    public class int class_member;
    public int instance_member;
}

When compiled will produce these C data structures (I only show the important parts):
struct _Test {
        gint instance_member;
};

struct _TestClass {
        gint class_member;
};

extern gint test_static_member;

The static member is not stored in any structure belonging to the class, but is a global variable. It is still scoped using the class prefix (so "test_" is prepended) to avoid name clashes with other global variables or static members of other classes.
The class member is stored in the "class structure" and the instance member is stored in the "instance structure".
The "class structure" may be extended by deriving classes, but other than that you normally only have one instance of the "class structure" for each class (which is why they are named like this).
The "instance structure" holds all the instance data everytime a new instance is created.
For the full understanding of these mechanism you have to know some C and have to read the GObject manual.


text:
Q: p4java - how to move opened files to another changelist? Say I have a file already opened in the default changelist and I want to move it to another changelist.   The Move operation allow me to specify a new changelist, but my move is ignored since the path didn't change in the filesystem.

A: While in P4V this is called "Move to Another Changelist", the p4java name is the same as the p4 command line terminology, where this is called "reopen"ing a file.  Try: IClient.reopenFiles()
client.reopenFiles(Arrays.asList(new IFileSpec[] { fileSpec }), newChanglist, null);


text:
Q: DDD: how to organize builders that bootstrap domain objects? Same Bounded Context? I'm restructuring my current project to be better in-line with DDD best practices.
As part of this setup an admin-task allows certain domain-objects / aggregates to be (re)-bootstrapped based on a config file/algo combo. I have a good use-case for this that does require it to be part of a live system as opposed only to testing (text fixtures) for example.
I'm struggling how to best model refactor this in a DDD context:
Basically: would the builders/bootstrappers be infrastructure services belonging to the same Bounded Context as the Domain Objects? Would this feel natural? The flow I see is that an admin gets access to these functions using a special Admin Application Service which in turn calls the builders to do their work.
On the other hand, this admin functionality feels like a separate part of the system so perhaps I shouldn't pollute the domain objects (or their factories) with methods to support the bootstrapping. IOW: this could mean a seperate Bounded Context, with a completely different (logic-less) domain model purely used for persisting to a DB. That however doesn't feel very DRY to me, as I might end up defining models twice (once in each BC)
What would be the best way to go about this?


text:
Q: Why does #define INVALID_VALUE -999; give a syntax error when used? I am trying to compare to a defined constants in C, and I have simplified my program to the following:
#include "stdio.h"
#include "stdlib.h"
#define INVALID_VALUE -999;

int main(void)
{
    int test=0;
    if(test==INVALID_VALUE) //The error line..
        return INVALID_VALUE;
    return 0;
}

And when I use gcc to compile, it gives out error "error: expected ')' before ';' token".
Is there any reason that this cannot be done?

A: You need to remove the ; in #define INVALID_VALUE -999;. See the fixed code.
You could have worked towards this conclusion by understanding what the error message expected ')' before ';' token was telling you. It's telling you that it expected to find a ) before the ; token, but from inspecting the line alone you don't see a ;. So maybe there's one in the definition of INVALID_VALUE? Look up at #define INVALID_VALUE -999; and there it is! Think it should be there, but not sure? So let's try remove it and see if it works. Success!
This page goes and explains why you shouldn't conclude a #define with a semicolon, even if it is needed in the use of the macro. It's good to learn as much as possible from your mistake so that you don't make it again. Quote:

Macro definitions, regardless of
  whether they expand to a single or
  multiple statements should not
  conclude with a semicolon. If
  required, the semicolon should be
  included following the macro
  expansion. Inadvertently inserting a
  semicolon at the end of the macro
  definition can unexpectedly change the
  control flow of the program.
Another way to avoid this problem is
  to prefer inline or static functions
  over function-like macros.
In general, the programmer should
  ensure that there is no semicolon at
  the end of a macro definition. The
  responsibility for having a semicolon
  where needed during the use of such a
  macro should be delegated to the
  person invoking the macro.

A: The C Preprocessor Macro Language is Distinct from C

The ; in the macro definition should be removed.
This is an understandable mistake. If C were designed today, the macro language might be more integrated with the rest of C.
But on 16-bit machines in the early 1970's when C was invented, it was unwise to write an overly complicated program. It would end up useless as there would be no memory remaining to actually run the big masterpiece program, and even simple programs ran slowly.
So C was split into a rather simple macro preprocessor that was, originally, a completely separate program, and the compiler proper.  The preprocessor program made no attempt to parse C beyond understanding the lexical analysis model.
When 32-bit machines took over, the preprocessor was typically integrated into the parser, but naturally the language needed to remain the same.

A: The semi colon at the end of
#define INVALID_VALUE -999;

Classic.

A: You do not need a semicolon after defining something. #define is actually a macro, and it will do an inline expansion on compile.
Thus,
#define IDENTIFIER 10;
int j = IDENTIFIER;

will expand as:
int j = 10;;

A: Change macro
from:
#define INVALID_VALUE -999;

to
#define INVALID_VALUE -999

Bye

A: Remove the semicolon from your INVALID_VALUE definition.
Macros are replaced lexically (character-by-character) with no understanding of the syntax around them.  Your macro INVALID_VALUE is set to -999;, so your if line expands the macro to:
if (test==-999;)

which is invalid C syntax.


text:
Q: How to change path of bundled files inside the newly generated html file See use-gulp-to-select-and-move-directories-and-their-files
, I changed my html file from dist folder to root, but I don't know how to change to path of bundled file inside the html file
I used follwing gulp task to move my html file
var filesToMove = [
    'dist/index.html',
];

gulp.task('move', function(){

gulp.src(filesToMove, { base: './' })
  .pipe(gulp.dest('./'));
});

This is the location where I want to change path of bundled file
<link rel="shortcut icon" href="favicon.ico"><link href="app.e6b85da4b9b36d023c5e.css" rel="stylesheet">

And one more place

**This is my webpack file.Here i gave my dist file file kocation  **

const webpack = require('webpack')
const webpackMerge = require('webpack-merge')
const CompressionPlugin = require('compression-webpack-plugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin')
const { AotPlugin } = require('@ngtools/webpack')
const commonConfig = require('./webpack.common.js')
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const helpers = require('./helpers')

const ENV = process.env.NODE_ENV = process.env.ENV = 'production'

module.exports = webpackMerge(commonConfig(), {

  output: {
    path: helpers.root('dist'),
    filename: '[name].[hash].js',
    chunkFilename: '[id].[hash].chunk.js'
  },

  plugins: [
    new AotPlugin({
      tsConfigPath: helpers.root('tsconfig-aot.json'),
      entryModule: helpers.root('src', 'app', 'app.module#AppModule')
    }),
    new LoaderOptionsPlugin({
      minimize: true,
      debug: false,
      options: {
        htmlLoader: {
          minimize: false
        }
      }
    }),
    new UglifyJsPlugin({
      beautify: false,
      output: {
        comments: false
      },
      mangle: {
        screw_ie8: true
      },
      compress: {
        screw_ie8: true,
        warnings: false,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
        negate_iife: false
      },
    }),
    // new CompressionPlugin({
    //   asset: '[path].gz[query]',
    //   algorithm: 'gzip',
    //   test: /\.js$|\.css$|\.html$/,
    //   threshold: 10240,
    //   minRatio: 0.8
    // }),
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(ENV)
      }
    })
  ]

})

this is my common webpack file

const webpack = require('webpack')
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const helpers = require('./helpers')

module.exports = () => {

  const isProd = process.env.ENV === 'production'

  return {

    // Array of extensions that will be used to resolve modules
    resolve: {
      extensions: ['.ts', '.js', '.json'],
      modules: [
        helpers.root('src'),
        helpers.root('node_modules')
      ],
    },

    // The entry point for the bundle
    entry: {
      'polyfills': helpers.root('src', 'polyfills.ts'),
      'ts-file':[
        helpers.root('src','app','common','samplelist.ts'),
        helpers.root('src','app','common','shared.module.ts'),
        helpers.root('src','app','app.module.ts')
             ],
      'app': [
        helpers.root('src', isProd ? 'main-aot.ts' : 'main-jit.ts'),
        helpers.root('src', 'assets', 'styles', 'main.scss')
      ]
    },

    module: {
      rules: [
        // Compiles all .ts files
        {
          test: /\.ts$/,
          use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader'],
          exclude: /\.spec\.ts$/
        },
        // Injects all html templates into their components and loads referenced assets
        {
          test: /\.html$/,
          use: 'html-loader',
          exclude: helpers.root('src', 'index.html')
        },
        // Copies all images and fonts into dist/assets
        {
          test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot)$/,
          use: 'file-loader?name=assets/[name].[ext]'
        },
        // Puts all styles from assets/styles/main.scss in a separate file
        {
          test: /\.scss$/,
          use: ExtractTextPlugin.extract(['css-loader', 'sass-loader']),
          exclude: helpers.root('src', 'app')
        },
        // Injects all angular styles into their components
        {
          test: /\.scss$/,
          use: ['raw-loader', 'sass-loader'],
          include: helpers.root('src', 'app')
        },
        // To string and css loader support for *.css files (from Angular components)
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader'],
          include: helpers.root('node_modules')
        },
        // Loads all "required" json files into their components
        {
          test: /\.json$/,
          use: 'json-loader'
        }
      ]
    },

    plugins: [
      // File name for the extracted styles
      new ExtractTextPlugin(`[name]${isProd ? '.[hash]' : ''}.css`),
      // Identifies common modules and puts them into a commons chunk
      new webpack.optimize.CommonsChunkPlugin({
        name: ['app', 'polyfills']
      }),
      // Provides context to Angular's use of System.import
      // See: https://github.com/AngularClass/angular2-webpack-starter/issues/993#issuecomment-283423040
      new ContextReplacementPlugin(
        /angular(\\|\/)core(\\|\/)@angular/,
        helpers.root('src')
      ),
      // Generates a HTML5 file that includes all webpack bundles
      new HtmlWebpackPlugin({
        template: helpers.root('src', 'index.html'),
        favicon: helpers.root('src', 'favicon.ico')
      }),
      // Copies all i18n files into dist/i18n
      // new CopyWebpackPlugin([{
      //   from: helpers.root('src', 'i18n'),
      //   to: 'i18n'
      // }]),

  ],
    performance: {
      hints: false
    }

  }

}


text:
Q: Genetic algorithm libraries for time series analysis/forecasting? I am very interested in experimenting with genetic algorithms for prediction of market time series data.
I made my own rudimentary software, but it is clunky and inefficient.
Can someone recommend a free/open source library for this sort of thing?

A: You can use GAUL. It has libraries for lots of evolutionary algorithms, Simulated Annealling etc


text:
Q: scrlttr2 documentclass options I'm "getting angry" with the documentation of scrlttr2 class.
I would see all the option I can include in that class. I have the manual of koma-script, but I can't find that doc.
Can someone help me?

A: In both versions of the KOMA-Script manual (the printed version [includes more informations] and the pdf version [texdoc scrguien or german texdoc scrguide]) you will find in the index the Class Options and the Package options.  The page numbers differs if you use the german or english, the printed or pdf version.
The KOMA-Script manual describes all options you can use, but you have to look into the index and search that one you need.
Or you can add what you need to your question.
In the German version you will find on page 453 (Chapter 21, class and package options):

All of this options and there values can be used for class scr... or KOMA-Script packages. The meaning and result is described on the page(s) you can click on in the index. The red numbers are links to the page ...


text:
Q: Characterizing cyclic group of order $n=p_1^{n_1}p_2^{n_2}\cdots p_r^{n_r}$, by Lattice isomorphisms Given a finite cyclic group $G$ with order $n=p_1^{n_1}p_2^{n_2}\cdots p_r^{n_r}$, where $p_i$s are distinct prime numbers $n_i>1$ for all $i$. Let $H$ be any group.Assume that $L(G)≅L(H)$and  Aut$(G)≅$Aut$(H)$. Is it true that $G≅H$?

A: Assume that $G$ is finite cylic, $G$ and $H$ have isomorphic lattices, and that $Aut(G)\approx Aut(H).$  Let the unique prime factorization of $\lvert G\rvert$ be $\lvert G\rvert= p_1^{a_1}\cdots p_n^{a_n}$ where $a_i>1$ and $p_i <p_{i+1}$ for all $i.$  Also, let the unique prime factorization of $\lvert H\rvert$ be $\lvert H\rvert= q_1^{b_1}\cdots q_n^{b_m}$ where $b_i>1$ and $q_i <q_{i+1}$ for all $i$.
Roland Schmidt's Subgroup Lattices of Groups Corollary 1.2.8 states that if $G$ is finite cyclic and $H$ is any group, then $L(G)\approx L(H)$ only if $H$ is also cyclic and $n=m$. Since $G$ and $H$ are cyclic, $\phi(\lvert Aut(G) \rvert)=\phi(\lvert Aut(H)\rvert)=p_1^{a_1-1}(p_1-1)\cdots p_n^{a_n-1}(p_n-1)$=
$q_1^{b_1-1}(q_1-1)\cdots q_n^{b_n-1}(q_n-1)$ were $\phi(n)$ is the Euler's totient function.
I claim that $p_n=q_n$.  If not, suppose $p_n>q_n$.  Note that $p_n\nmid [q_1^{b_1-1}(q_1-1)\cdots q_n^{b_n-1}(q_n-1)]$ which is a contradiction.
So, $p_1^{a_1-1}(p_1-1)\cdots p_n^{a_n-1}(p_n-1)=q_1^{b_1-1}(q_1-1)\cdots p_n^{b_n-1}(p_n-1).$  We also have  $a_n=b_n$ since $p_n=q_n$ is the largest prime divisor.
So, $p_1^{a_1-1}(p_1-1)\cdots p_n^{a_n-1}(p_n-1)=q_1^{b_1-1}(q_1-1)\cdots p_n^{a_n-1}(p_n-1).$ After cancelling we have $p_1^{a_1-1}(p_1-1)\cdots p_{n-1}^{a_{n-1}-1}(p-1)=q_1^{b_1-1}(q_1-1)\cdots q_{n-1}^{b_{n-1}-1}(q_{n-1}-1).$
Repeating this process gives $p_i=q_i$ and $a_i=b_i$ for all $i$.  Thus $G$ and $H$ are cyclic of the same order, and therefore, $G\approx H$.
Edit: Originally, I missed the hypothesis that the exponents were bigger than 1.  This is a different answer.


text:
Q: Spring OAuth: Resource Server with Authorization Server backend I want to develop two independent services, one for the business stuff and one for the user authentication using Spring OAuth 2
Let's call them Business-Service and OAuth-Service.
Now I want the Business-Service delegate to the OAuth-Service if a request is not authenticated. The client application (an Android app) should not know about the OAuth-Service a priori, it should only be delegated to it by the Business-Service with an 302 HTTP redirect for non-authenticated request. To be precise, I want my API landing page to provide a link to http://businessservice.com/login and when my client app decides to follow this link, it gets redirected to the OAuth-Service.
If I annotate the Business-Service with @EnableOAuth2Resource , all of its resources are protected returning a 401 when I curl them without an access token. So far so good. If I provide an access token like this:
curl -v http://localhost:8667/resource/ -H "Authorization: Bearer $TOKEN"

I can access the resource. Still good.
However if I annotate the Business-Service with @EnableOAuth2Sso for enabling the redirection to the OAuth service, it looses the capability of accessing the resources with an access token (same curl as above), it only returns a 302 to the login page http://localhost:8667/login
If I use both annotations, the @EnableOAuth2Resource always seems to "win", as the authentication works but calling http://localhost:8667/login returns a 404.
So what is the right way to create a resource server that delegates to the auth server for non-authenticated calls?

A: After trying around for hours I now found a solution.
The Business Server (Resource Server) now looks as follows:
@SpringBootApplication
@EnableOAuth2Sso
@EnableOAuth2Resource
public class BusinessService {

    public static void main(final String[] args) {
        final ConfigurableApplicationContext context = SpringApplication.run(BusinessService.class, args);
    }

}

with two configurations, one for the SSO:
@Configuration
public class OAuth2SsoConfiguration extends OAuth2SsoConfigurerAdapter {

    @Override
    public void match(final RequestMatchers matchers) {
        matchers.antMatchers("/");
    }

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
    }

}

and one for the Resource:
@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers("/resource/**").and().authorizeRequests().anyRequest().authenticated().antMatchers("/").permitAll();

    }

}

This results in the following:
curl -v http://localhost:8667/

returns
HTTP/1.1 200 OK
{"links":[{"rel":"login","href":"http://localhost:8667/login"}]}

curl -v http://localhost:8667/resource/

returns
HTTP/1.1 401 Unauthorized
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

curl -v http://localhost:8667/login

returns
HTTP/1.1 302 Found
Location: http://localhost:8666/user/oauth/authorize?client_id=clientId&redirect_uri=http%3A%2F%2Flocalhost%3A8667%2Flogin&response_type=code&state=YmmNO9

So my business servie is secured with as a resource server returning a 401 for all business resources. The root of the service is applicable for all clients so they can discover the login relation and if they follow this relation, they're redirected to the Authorization server


text:
Q: php usort error message I have a class called Link with a function called Compare. When I runt this code I keep getting an error message
foreach($filearray as $k=>$v)
{
$website = new Link($v);
$links[] = $website;
}
usort($links, array("Link","compare"));

But I get an error message and I cant figure out why...

"Warning: usort() [function.usort]: The argument should be an array"

A: If $links haven't been initialized as an array, when $filearray is empty, $links remains null.
Add $links = array(); before the loop.

A: Second parameter is the comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Check the below article
http://php.net/manual/en/function.usort.php


text:
Q: org.hibernate.criterion.Example use with CriteriaQuery I have following code that I need to refactor for use in hibernate 5. This includes removing every deprecated call.
public List<T> findByExample(T example, String... excludeProperty) {
    Criteria crit = session.createCriteria(T.class);
    Example ex = Example.create(example);
    for (String exclude : excludeProperty) {
        ex.excludeProperty(exclude);
    }
    crit.add(ex);
    return crit.list();
}

Since createCriteria is deprecated I was going to replace it with getSession().getCriteriaBuilder().createQuery(Foo.class);. This is in theory the right way to do it, but now I have no idea how to go about the Example and how it is used in the code.
Can anyone help me to use the Example with hibernate 5?


text:
Q: 3 phase computer chip I have just had a conversation with a friend who studied quantum computing. Sadly I have forgotten most of the conversation as it was far beyond my knowledge threshold.
Essentially he was saying was that current tradition computer chips are getting smaller and faster but soon we will hit the limit because as the chips shrink we have to pass less current through them. Here, there will be a trade off of chip performance against size.
So as these don't already exist, there must be a good reason why microprocessors can't be build that run on 3 phase AC rather than traditional single phase. Is this because as I understand it, microprocessors have oscillators inside them to generate their clock cycles, these oscillators wouldn't be changing state, but always be fixed, because of the constant flow of electrons? Without the peaks and troughs of single phase, I would assume an oscillator can not oscillate, is that correct?
My knowledge if electronics is pitiful at best, so there is likely some fundamental reason why this isn't mainstream because in my head, this would allow for potentially three times the computing power compared to a traditional microchip.
Thank you.

A: Microchips universally run off DC. The source of that DC can be anything: single-phase, three-phase, battery, fuel cell, whatever, so long as the DC getting to the chip is within its spec.

A: The frequency of the mains electricity is far removed from the microprocessors oscillator frequency. A rough outline of what happens is:
Lets assume the mains is single phase, 115V AC 60Hz. The peak voltage is calculated by 115V * 1.414 = ~163V, so this means it varies between +163V and -163V 60 times a second.
Since most digital electronics runs at a DC voltage of <12V, (common voltages are 5V, 3.3V, 2V, 1.5V, 1.2V, etc) this is no use as it is. So this is fed into the power supply, where it is transformed down to the lower voltages, rectified and smoothed to produce the desired DC voltages.
So that's the power supply, now how does the microprocessor run on DC?
You are correct in that it uses an oscillator, but oscillators don't need a varying supply voltage to work - the function of an oscillator is to generate a varying waveform at the desired frequency.
The oscillator (example below - input 3.3VDC, output 125MHz square wave) will usually be based around a quartz crystal and produce a frequency of up to 100MHz or so (above this is possible with SAW and other technologies)

This is still to low for a microprocessor that operated at GHz frequencies, so this signal is fed into a Phase Locked Loop (PLL) which is usually onboard the chip to multiply the frequency up to the operating frequency.
So hopefully you can see the original 60Hz AC has nothing to do with the microprocessor - the microprocessor will work as long as it gets it's rated DC voltage, which will be something like one or more of those listed above. This could come from a battery (laptop, phone, etc) solar panel or any other power source - if the power source does not output the correct voltage the power supply transforms it to the correct voltage (e.g. 115VAC -> 3.3VDC)

A: As others note, the power supply and the computer operatyion are essentially unrelated.
One improvement that sound similar to what you mention, but really isn't, is to use 3 states per bit rather than 2 as in almost all computers made.
The ideal number of levels in a data "bit" is "e" - the natural logarithm base. As e is mnon integer you won't see e level computers. But, as 3 is closer to e than 2 is a  computer with 3 level  memories has an edge in some situations.
BUT as the difficulty in  implementing 3 levels is far higher than two levels (on/off, high low) you are vanishingly unlikely to see any 3 level memory state computers. Some were built in Russia many decades ago and they worked as intended, but practical issues has consigned toem to the "interesting:" shelf of computer history - so far anyway.

A: Most chips don't run on AC, rather they use a DC power source. Computers have built-in AC to DC converters which can take the AC power from the wall and change it to the required DC power the computer needs. It's also entirely possible to run a computer using other power sources like batteries, solar cells, etc.
The oscillators inside of computers are designed to take a DC power source preferably with as little ripple as possible and change this to the high frequency clock used by the chip. If you're interested, do a search for "Pierce Oscillator" and "Phase-locked loop".
If you multiply the frequency of most 1-phase AC power lines by 3 you get a frequency of ~150-180 Hz, a far cry from the GHz range modern CPU's run at.
Consider this, though:
There are people who routinely overclock their CPU's to extreme limits (in excess of 5GHz). This means it's possible for someone to take the same CPU and theoretically pump a much higher clock through them. There are also oscillators available which can generate oscillations in the terahertz range. Why aren't these used in your computer? Because most chips will not function correctly at these high speeds under "normal" conditions. Case and point? These extremely overclocked CPU's use liquid nitrogen or other specialized cooling systems, and even then they can't be overclocked too much higher to the 10's of GHz range.
Lastly, CPU frequency isn't the only factor in overall computing power. In the early 2000's Intel was selling Pentium 4 chips which achieved ~3.8 GHz CPU clocks.
My laptop also has an Intel chip, an i5-m430. Even though this runs off of a 2.3 GHz CPU clock, I would say my laptop has much more computing power than the Pentium 4 computers.
Response to Rocketmagnet's comment:
So what would a 3-phase oscillator computer look like? Well, first you'd have to figure out how to hook up the oscillator to the CPU. I would guess you can hook up several single-phase chips between two wires of the oscillator, looking something like this (from Wikipedia):

In essence you have a triple-core chip which all have out of phase clocks. However, I fail to see how this is beneficial over a triple-core chip all sourced off of the same clock. If anything I would think synchronized clocks would be a beneficial feature when it comes time for inter-core communication.


text:
Q: String pattern in web view How to create String which includes two words and space between the. I meen I have text like this for example: The crush was on ul. Boczna and also on ul. Sucha.
And what i want to do I want make a String that would match for example "ul. Boczna"and "ul. Sucha"
I tried this:
String street = "ul" + " " + "[a-zA-Z]+"

But it doesnt work as I want.

A: You aren't taking into account the period. To search for a period in a regex expression, use "\."
Try "ul\.\s[a-zA-Z]+" or "ul\.\s\w+"
If the period isn't always there, try "ul\.?\s\w+"


text:
Q: jQuery ajax data by form fields I am processing a form with jQuery ajax.
I have the following jQuery code:
$.ajax({
  url: 'formprocess.php',
  type: 'post',
  data: $('#myForm input[type=\'text\']'),
  dataType: 'json',
  success: function(json) { alert('pass'); }
 });

And my form is:
<form id="myForm">
  <input type="text" name="parent[47]child[230][26]" value="1" />
  <input type="text" name="parent[47]child[230][27]" value="2" />
  <input type="text" name="parent[28]child[231][29]" value="3" />
  <input type="text" name="parent[28]child[231][31]" value="4" />
</form>

And it works fine for form posts over ajax.
On the php side it shows up as:
$_POST
: array =
  parent: array =
    47: array =
      child: array =
        230: array =
          26: string = "1"
          27: string = "2"
    28: array =
      child: array =
        231: array =
          29: string = "3"
          31: string = "4"

But I'd like to split it on the javascript side so that it loops and passes each parent separately. So in this case it would post back twice:
$_POST
: array =
  parent_id = 47
  child: array =
      230: array =
        26: string = "1"
        27: string = "2"

AND
$_POST
: array =
  parent_id = 28
  child: array =
       231: array =
         29: string = "3"
         31: string = "4"

So I think I need to use:
$('#myForm input[type=\'text\']').each(function(i, tbox) {
    tboxname = tbox.attr('name');
    var myregexp = /parent\[(\d+)\]child\[(\d+)\]\[(\d+)\]/;
    var match = myregexp.exec(tboxname);
    var parent_id = match[1];
    var child = 'child['+match[2]+']['+match[3]+']';
}

But now I have 2 string values and have lost my object and value.

A: You're correct - using .each() in this case is the right approach, but it'll just let you iterate over each input element, and won't really know anything about the "array" inside the name attribute for each one.  That seems to be your primary issue here; javascript is just seeing the value of your name parameter as a string, and not an array of values.
I wouldn't think of this as a multi-dimensional array in the eyes of js... the each() will just see one big list of elements that you need to invent your own logic to parse through.
Here's what I would try...
var parsedData = {};
$('#myForm input[type=\'text\']').each(function(i){
    var thisInput = $(this);
    var thisName = $(this).attr('name');

    // parse your string here, by using conditional statements or maybe by using eval()
    // ... This is where "your own logic" mentioned above would go =)

    parsedData.["someValue"+i] = thisInput.val();
});

...And from here you would use the parsedData var to pass into your $.ajax call.
Hope this helps


text:
Q: Swift - Capturing closures - Apple's swift programming guide snippet In Apple's Swift programming guide, "Automatic Reference Counting" section, at "Resolving Strong Reference Cycles for Closures",
This snippet is mentioned:
lazy var someClosure: () -> String = {
    [unowned self, weak delegate = self.delegate!] in
    // closure body goes here
}

What is the point of the exclamation mark in the assignment "weak delegate = self.delegate!"?
I mean, why do you care if there is a value or not? In either ways, you will be receiving an optional delegate inside the closure body since delegate is declared weak, which must be optional, and you will have to access it as an optional.
On the other hand, if you know for sure there 'self.delegate' wont be nil when you access it, why not declaring it as unowned?
Therefore, why is the force unwrapping necessary here?
Can someone shed some light on this?

A: As there is not really any more context in the text around this example the only person who can know for sure is the author or maintainer of the Swift programming guide.
But here are some possible reasons that I can think of (in no particular order)

*

*The author made a mistake (it happens)

*It was required in an older version of Swift and the documentation has not been updated (keeping documentation up to date is hard)

*The author wanted to make it obvious to others that creating the block if the delegate does not exist is a bug

*The author wants to make it easier to track cases when a delegate was deallocated between creating the block and calling it (maybe for analytics purposes?)


text:
Q: Difference between double equals and triple equals for String Comparison in Elixir I was reading a book on Elixir: Introducing Elixir.
On string compare it says that:

Elixir offers two options for comparing string equality, == and === operators. The == operator is generally the simplest though the other produces the same result.

Whats the purpose of having two operators if they mean the same thing?

A: One example that comes to mind is floats - which use the same comparison functions as strings:
iex> 1 == 1    #true
iex> 1 == 1.0  #true
iex> 1 === 1   #true
iex> 1 === 1.0 #false

And for !==
iex> 1 != 2    #true
iex> 1 != 1.0  #false
iex> 1 !== 2   #true
iex> 1 !== 1.0 #true

It is worth noting that these functions use the following Erlang expressions:
Elixir | Erlang
==     | ==
===    | =:=
!=     | /=
!==    | =/=

From the Erlang documentation:

When comparing an integer to a float, the term with the lesser precision is converted into the type of the other term, unless the operator is one of =:= or =/=. A float is more precise than an integer until all significant figures of the float are to the left of the decimal point. This happens when the float is larger/smaller than +/-9007199254740992.0. The conversion strategy is changed depending on the size of the float because otherwise comparison of large floats and integers would lose their transitivity.


text:
Q: List of independent RadioGroups I've looked for solution to my problem everywhere but mine is kind of specific...I need an advice on how to create list of independent radioGroups such as illustrated:
o item1     • item1'
• item2     o item2'
o item3     • item3'
In what kind of object would I store those radiogroups and how do I generate them. Also radioButtons would be generated dynamically. Do I use listview or I don't need it? Please help.

A: I think you should consider using a vertical linear layout, then placing the radiogroups as the child elements, like so
        <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <RadioGroup
            android:id="@+id/radioGroup1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/radio0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="RadioButton" />

            <RadioButton
                android:id="@+id/radio1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="RadioButton" />
        </RadioGroup>

        <RadioGroup
            android:id="@+id/radioGroup2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/radio3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="RadioButton" />

            <RadioButton
                android:id="@+id/radio4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="RadioButton" />
        </RadioGroup>
    </LinearLayout>

and you'll end up with a layout like you described.


text:
Q: How to sum the number of entries in a dataframe that are located within a geopandas boundary I have two geodataframes: One containing sightings of animals of a specific species called bird_df (with location as points), and the other detailing the boundaries of each municipality within my state called map_df.
I want to use the geopandas method .contains(x) to count the number of animals that were found in each municipality and add that total to the boundaries dataframe so i can generate a choropleth.
My pandas is a bit rusty but I've tried things like
map_df[map_df["geometry"].contains(bird_df["geometry"]) == True]
I just don't know how to wrap my head around this problem. Some help would be appreciated.
Thanks

A: I recommend using an sjoin for this.
import geopandas as gpd
import pandas as pd

# make some dummy points
df = pd.DataFrame()
df['x'] = [0.61, 0.62, 0.63, 0.64, 0.65]
df['y'] = [41.60, 41.62, 41.63, 41.64, 41.65]
points_gdf = gpd.GeoDataFrame(geometry=gpd.points_from_xy(df.x, df.y))

# buffer 2 rows of points to make some dummy polys
poly_gdf = points_gdf.head(2).copy(deep=True)
poly_gdf['geometry'] = poly_gdf['geometry'].buffer(0.02)

# do the spatial join, index right is the polygon idx values
sjoin_gdf = gpd.sjoin(points_gdf, poly_gdf)

# count the values with value counts
count_dict = sjoin_gdf['index_right'].value_counts().to_dict()

# map the count_dict back to poly_gdf as new point count column
# alternatively you could do a join here, but new col name is nice
poly_gdf['point_count'] = poly_gdf.index.map(count_dict)

Output poly_gdf:
    geometry                                            point_count
0   POLYGON ((0.63000 41.60000, 0.62990 41.59804, ...   1
1   POLYGON ((0.64000 41.62000, 0.63990 41.61804, ...   2

Viz:
cat_df = pd.concat([points_gdf, poly_gdf])
cat_df.plot(facecolor="none")


text:
Q: Complex integral over two differents closed path The first integral that I want to calculate is: $$\int_{|z-2|=5}\frac{z^3 +3}{z^2+1}\,dz$$
And the second is $$\int_{|z|=\frac{1}{2}}\frac{z^3 +3}{z^2+1}\,dz$$
The denominator can be factored into $(z+i)(z−i)$. As $z_0=i$ and  $z_1=-i$ are inside the path $|z−2|=5$ I can't use Cauchy and I don't know how to solve those integrals with other method.
In the second case $z_0$ and $z_1$ aren't inside $|z|=\frac{1}{2}$ so I can to use Cauchy

A: You can use Cauchy's Residue theorem: if $f$ is analytic in a simply connected domain $\Omega$ except at a number of poles then the integral of $f$ along a closed contour in $\Omega$ that circulates the poles just once is $2\pi i$ times the sum of the residues at the poles lying inside the contour.  The residue at a pole $z_0$ is the the coefficient to the term $1/(z-z_0)$ in the Laurent expansion of $f$ about $z_0$.
In your first integral, the contour includes two poles at $z = \pm i$.
Writing $$\frac{z^3+3}{z^2+1} = z + \frac{1}{2}\Bigg(\frac{3i-1}{z+i}-\frac{3i+1}{z-i} \Bigg)$$
you can see the residues at the two poles.  At $z=-i$ it is therefore $\frac{1}{2}(3i-1)$ and that at $z=i$ is $-\frac{1}{2}(3i+1)$.  Now apply the theorem, noting that the sum of the two residues is $-1$, to obtain,
$$\int_{|z-2|=5} \frac{z^3+3}{z^2+1} dz = -2\pi i. $$
For the second integral, neither pole lies inside the contour and therefore the same theorem implies the integral will be zero.


text:
Q: SQL db design constraints for co-belonging Here is my database structure, it contains 3 tables : School, Student, Course
Each student must belong to a school (so School ID will be a foreign key in the student table referring to the School table).
Each course also must belong to a school (so School ID will be a foreign key in the course table referring to the School table).
Finally, each student may sign up for one or more courses (pivot table with a foreign key for student and a foreign key for school), but with the restriction that the student and the course must both belong to the same school. A student cannot be allowed to sign up for a course which belongs to a different school from the student.
Is there a way to add this constraint in the pivot table, or some other way model it?
Or should the constraint be enforced in the code before each insert on the pivot table?

A: You can add the SchoolID as a part Primary keys in both Student and Course.
This will force foreign keys to those tables to also specify the SchoolID.
We use this fact in our StudentInCourse-table to force both the student and the course to belong to the same school.
CREATE TABLE School(id INT PRIMARY KEY);

CREATE TABLE Course(id int, schoolID INT
    FOREIGN KEY REFERENCES dbo.School(id),
    PRIMARY KEY(id, schoolID));

CREATE TABLE Student(id INT, schoolID INT
    FOREIGN KEY REFERENCES dbo.School(id),
    PRIMARY KEY(id, SchoolID));

CREATE TABLE StudentInCourse(StudentId INT, schoolId INT, CourseID INT,
    CONSTRAINT [fk_student]
    FOREIGN KEY (StudentId,schoolID) REFERENCES student(id, SchoolID),
    CONSTRAINT [fk_course]
    FOREIGN KEY (CourseID,schoolID) REFERENCES Course(id, SchoolID),
    );

INSERT dbo.School ( id )
VALUES  ( 1 ), ( 2 );

INSERT dbo.Student
        ( id, schoolID )
VALUES  ( 19950516, 1  );

INSERT dbo.Course
        ( id, schoolID )
VALUES  ( 77666, 1     ),
        ( 99988, 2     );

-- Student in same school as course is OK
INSERT dbo.StudentInCource
        ( StudentId, schoolId, CourseID )
VALUES  ( 19950516,  1,        77666    );

-- Student in other school as course is FAIL
INSERT dbo.StudentInCourse
        ( StudentId, schoolId, CourseID )
VALUES  ( 19950516,  2,        99988    );
INSERT dbo.StudentInCourse
        ( StudentId, schoolId, CourseID )
VALUES  ( 19950516,  1,        99988    );

A: I recommend to make :

*
The three fields Pivot(StudentID,CourseID,SchoolID) a Primary Key

*
The two fields Pivot(StudentID,SchoolID) a double Foreign Key to the Student table

*
The two fields Pivot(CourseID,SchoolID) a double Foreign Key to the Course table
So the model will be in this way:
School Table:
+----------+
| SchoolID |
+----------+
|    1     |
|    2     |
|    3     |
+----------+

where SchoolID is a Primary Key
Course Table:
+----------+----------+
| CourseID | SchoolID |
+----------+----------+
|    1     |    1     |
|    2     |    1     |
|    3     |    1     |
+----------+----------+

where SchoolID references  School(SchoolID) and (CourseID,SchoolID) a Primary Key
Student Table:
+-----------+----------+
| StudentID | SchoolID |
+-----------+----------+
|     1     |    1     |
|     2     |    1     |
|     3     |    1     |
+-----------+----------+

where SchoolID references  School(SchoolID) and (StudentID ,SchoolID) a Primary Key
Pivot Table:
+-----------+----------+----------+
| StudentID | CourseID | SchoolID |
+-----------+----------+----------+
|     1     |    1     |    1     |
|     2     |    2     |    1     |
|     3     |    3     |    1     |
+-----------+----------+----------+

where Pivot (StudentID,SchoolID) references Student (StudentID,SchoolID)
and Pivot (CourseID,SchoolID) references Course (CourseID,SchoolID)

A: IT is better to have 4 tables one each for School, Student, Course and forth table for Mapping Student to a particular  Course.
Mapping student courses in separate table will give you ability to Map single student with Multiple courses.
This is the simplest of thing you can do.
If you need to map same student with different schools then you can add Map students & Courses either in same table of separate table


text:
Q: Conditional formatting in SharePoint Online I have a datasheet view that I'm trying to apply some conditional formatting to, where depending on the content of the cell, the cell gets a certain background color (i.e., if the cell reads Critical, the background color turns red). I am unable to do so in Designer, and am not sure how to proceed.

A: Unfortunately, it's not possible, because of the datasheet view runs as an ActiveX control, not as HTML, so the customization in datasheet view is not supported, you can't perform any conditional formatting!


text:
Q: Using parenthesis when calculating I been looking around and noticed some people use parenthesis and some not when writing calculations/sums so was wondering what the difference is and what is the better option and why?
$foo = ($foobar * 100);

or
$foo = $foobar * 100;

A: There is no difference in this example. They just do it to follow BODMAS.
Using this is better as you are sure in longer calculations.

A: there is not any specific answer for this but AFAIT using braces ( will avoid confusions while calculations.
read these useful links for more information
http://www.phpdeveloper.org.uk/articles/php-coding-guidelines/
http://framework.zend.com/manual/en/coding-standard.coding-style.html
http://pear.php.net/manual/en/standards.php

A: Parenthesis control the order of operations.
For instance in $x * $y + 2, multiplication will be executed before addition, so implicitly, there are parenthesis like this: ($x * $y) + 2.
If you do not use parenthesis, operations will be carried out in the order as defined by the language, it is what is called operator precedence.
I suggest you always use parenthesis when you mix different operators in one expression (excluding assignment). Alternatively, you can break up your expression into multiple statements to give the elements that make up your calculation descriptive names.


text:
Q: Sign a file with SMIME in C# I need sign a file with sime in C#, similar to OpenSSL next command line:
openssl smime -outform der -nodetach -signer my509.crt -inkey myprivatekey.rsa -in myfile.txt -out myfile.out

In c# I useBouncy Castle library for read key file in PEM format.
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System.Security.Cryptography.Pkcs;

private void sign_TRA_alt()
{
  // Read x509
  X509Certificate2 certificate = new X509Certificate2("my598.crt");
  RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

  // Read private key
  using (TextReader privateKeyTextReader = new StringReader(File.ReadAllText("myprivate.rsa")))
  {
    AsymmetricCipherKeyPair readKeyPair = (AsymmetricCipherKeyPair)new PemReader(privateKeyTextReader).ReadObject();
    RsaPrivateCrtKeyParameters privateKeyParams = ((RsaPrivateCrtKeyParameters)readKeyPair.Private);
    RSAParameters rsa_params = DotNetUtilities.ToRSAParameters(privateKeyParams);
    rsa.ImportParameters(rsa_params);
  }

  // Join private key to x509
  certificate.PrivateKey = rsa;

  // Sign file
  String tra;

  using (StreamReader reader = new StreamReader("myfile.txt"))
  {
    tra = reader.ReadToEnd();
  }

  ContentInfo contInfo = new ContentInfo(Encoding.ASCII.GetBytes(tra));
  SignedCms signed = new SignedCms(contInfo, true);
  CmsSigner signer = new CmsSigner(certificate);

  try
  {
    signed.ComputeSignature(signer);
  }
  catch (Exception e)
  {
    log_message("Error: " + e.Message );
  }

  String dataSigned = Convert.ToBase64String(signed.Encode());
}

When execute this code an exception is fired when ComputeSignature is executed. The exception message say "The public key is invalid" ....


text:
Q: Need to compare how a table changes from prior day to current day and the table doesn't have a field to track record creation or modification in SSRS Using SSRS, I need help determining the records that were added or modified from the prior business day.  The table that contains the data doesn't have a field to track creation or modification date.
I assume I need to store the result each day and compare the stored result to the next business day that I run the report.
How can I do this?

A: Without any info on when records are created or modified this is going to be more painful than it needs to be.
As I see it you have a couple of options.

*

*Add the required column(s). For creation you can set a default value of getdate() and then add a trigger on updates to modify the updated date column. This way it will be easy to query the table for anything that has changed in the last day or over any period of time you require.

*Get the dataset query that runs in your report to make a copy of the table each time it runs into a separate table e.g. myTable_Previous. You can then query the differences between the two. There are several problems with this approach that means it's not a good idea.
a. it will only work between report executions so if the report runs 3 times in a day it will only be comparing since the last run which may have been 5 minutes ago.
b. if the report is not run for a week it will show you changes for that time period
c. you would need to have the report scheduled via a subscription to ensure it was run at the correct interval.
d. if the table you are querying is big it will mean copying a lot of data each time the report is run which will slow it down
In short, the best way is to add the required info and do it correctly, it will make any similar reports/queries easier to write in the future.


text:
Q: java array deque size vs performance in my java code I suspect that the java.util.ArrayDeque size is affecting performance, but I wanted to confirm on here if that could be the case.
while (!otherClass.getDeque().isEmpty()){
  Trajectory t1 = otherClass.getDeque.remove();
  Runnable tr1 = new TrajectoryThread();
  Thread thread1 = new Thread(tr1);
  thread1.start();

if (!otherClass.getDeque().isEmpty()){
  Trajectory t2 = otherClass.getDeque.remove();
  Runnable tr2 = new TrajectoryThread();
  Thread thread2 = new Thread(tr2);
  thread2.start();

In my code, I remove a trajectory object if the deque is not empty and initiate a simulation on a new thread until 40 simulations are running concurrently. At the end of each simulation, there is a possibility of adding more trajectories to the queue. If there are trajectories still remaining on the queue after all simulations are finished the process repeats itself.
The operations I use are remove() , add(), isEmpty(), and also getting the Deque from another class. While timing each iteration, I find that for a Deque size of 4421 objects it takes 7756 miliseconds. While for a Deque size of 103 objects, it takes 43 miliseconds.

A: When encountering performance issues such as this, the right approach most of the time is to get good performance monitoring data before speculating on what part of your program is slow. You can use a tool like VisualVM to achieve this.
If you are wondering if java.util.ArrayDeque operations are responsible for slowing down your program, then the answer is almost certainly no, because their execution time is largely dominated by the overhead of creating threads and running your simulations. ArrayDeques are very fast. They run the 3 operations you listed in your comment in constant time (more precisely, add runs in constant amortised time.); less theoretically, these operations are performed using low-level array manipulation which is very fast in practice. So I would not worry about that.
On the other hand, if you're wondering in what way your execution time is related to the size of your problem, then we'll need more insights on what happens in your TrajectoryThreads.


text:
Q: Correct way to restrict functions to specific data types I am currently working with the following data types in c++:
double, boost::interval< double >, and
boost's mpfr/mpfi types (mpfr_float, mpfr_float_50, ..., mpfi_float, mpfi_float_50, ...)
I am writing some overloaded functions for any pair of these types.  The code is identical except for the types in the declaration.
The number of pairs is rather large and I would like to know the most efficient way of taking care of all of these cases (using the vanilla form of templates isn't ideal because only these number types should be allowed).

A: I've updated the answer to deal with complex/compound types of your choice.
Handling Known Numeric Types
Perhaps you don't even care about what library implements the types:
template <typename T, typename U>
    std::enable_if_t<
        std::numeric_limits<T>::is_specialized &&
        std::numeric_limits<U>::is_specialized,
        std::common_type_t<T, U>
    > foo(T const& a, U const& b)
{
    auto product = a * b;
    std::cout << "foo(" << a << ", " << b << ") -> " << product << "\n";
    return product;
}

Note this also shows one approach to synthesizing a generic return type.
Live On Coliru
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <boost/multiprecision/number.hpp>

template <typename T, typename U>
    std::enable_if_t<
        std::numeric_limits<T>::is_specialized &&
        std::numeric_limits<U>::is_specialized,
        std::common_type_t<T, U>
    > foo(T const& a, U const& b)
{
    auto product = a * b;
    std::cout << "foo(" << a << ", " << b << ") -> " << product << "\n";
    return product;
}

int main()
{
    using namespace boost::multiprecision;
    mpfr_float_50 a = 1;
    mpfr_float_100 b = 2;
    mpfr_float_500 c = 3;
    double d = 4;

    foo(a, a); foo(b, a); foo(c, a); foo(d, a); std::cout << "\n";
    foo(a, b); foo(b, b); foo(c, b); foo(d, b); std::cout << "\n";
    foo(a, c); foo(b, c); foo(c, c); foo(d, c); std::cout << "\n";
    foo(a, d); foo(b, d); foo(c, d); foo(d, d);
}

Prints
foo(1, 1) -> 1
foo(2, 1) -> 2
foo(3, 1) -> 3
foo(4, 1) -> 4

foo(1, 2) -> 2
foo(2, 2) -> 4
foo(3, 2) -> 6
foo(4, 2) -> 8

foo(1, 3) -> 3
foo(2, 3) -> 6
foo(3, 3) -> 9
foo(4, 3) -> 12

foo(1, 4) -> 4
foo(2, 4) -> 8
foo(3, 4) -> 12
foo(4, 4) -> 16

Note: the weak point here is common_type because it may not know about your library types and hence fail to suggest a proper return type. See std::common_type trait for user defined types

Handling Complex or Compounds
In this case there is no existing type trait to rely on. Also, the types are completely unrelated, so it's not a matter of adding a single partial specialization. In such cases I'd use a custom trait.

You don't describe much about the kind of operation you'll implement, so let me stick with foo. foo-ing A and B should be implemented if A and B are foo-able together.

Let's make a trait to define what types are foo-able. If foo is commutative, you need only one "side":
#include <type_traits>

namespace mylib { namespace traits {
    //primary template
    template <typename T, typename Enable = void> struct is_fooable : std::false_type {};

    // c++14 style
    template <typename T> constexpr bool is_fooable_v = is_fooable<T>::value;
} }

Which you then specialize for whatever type you wish to support:
namespace mylib {
    namespace traits {
        template <typename Backend, boost::multiprecision::expression_template_option Et>
            struct is_fooable<boost::multiprecision::number<Backend, Et> >
                : std::true_type {};
        template <typename T>
            struct is_fooable<T, std::enable_if_t<std::is_arithmetic<T>{}> >
                : std::true_type {};
        template <typename T, typename Policies>
            struct is_fooable<boost::numeric::interval<T, Policies> >
                : std::true_type {};
        template <typename T>
            struct is_fooable<std::complex<T> >
                : std::true_type {};
    }

    template <typename T, typename U, typename = std::enable_if_t<traits::is_fooable_v<T> && traits::is_fooable_v<U> > >
    auto foo(T const& a, U const& b) {
        auto product = a * b;
        std::cout << "foo(" << a << ", " << b << ") -> " << product << "\n";
        return product;
    }
}

Full Demo
Live On Coliru
#include <type_traits>

namespace mylib { namespace traits {
    //primary template
    template <typename T, typename Enable = void> struct is_fooable : std::false_type {};

    // c++14 style
    template <typename T> constexpr bool is_fooable_v = is_fooable<T>::value;
} }

#include <iostream>
#include <sstream>
#include <complex>
#include <boost/numeric/interval.hpp>
#include <boost/numeric/interval/io.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <boost/multiprecision/number.hpp>

namespace mylib {
    namespace traits {
        template <typename Backend, boost::multiprecision::expression_template_option Et>
            struct is_fooable<boost::multiprecision::number<Backend, Et> >
                : std::true_type {};
        template <typename T>
            struct is_fooable<T, std::enable_if_t<std::is_arithmetic<T>{}> >
                : std::true_type {};
        template <typename T, typename Policies>
            struct is_fooable<boost::numeric::interval<T, Policies> >
                : std::true_type {};
        template <typename T>
            struct is_fooable<std::complex<T> >
                : std::true_type {};
    }

    template <typename T, typename U, typename = std::enable_if_t<traits::is_fooable_v<T> && traits::is_fooable_v<U> > >
    auto foo(T const& a, U const& b) {
        std::ostringstream oss;
        oss << "foo(" << a << ", " << b << ")";
        return oss.str();
    }
}

int main()
{
    using namespace boost::multiprecision;
    mpfr_float_50 a = 1;
    float c = 3;
    std::complex<double> d(4, 1);
    boost::numeric::interval<int> b(1,1);

    using mylib::foo;
    std::cout << foo(a, a) << "; " << foo(b, a) << "; " << foo(c, a) << "; " << foo(d, a) << "\n";
    std::cout << foo(a, b) << "; " << foo(b, b) << "; " << foo(c, b) << "; " << foo(d, b) << "\n";
    std::cout << foo(a, c) << "; " << foo(b, c) << "; " << foo(c, c) << "; " << foo(d, c) << "\n";
    std::cout << foo(a, d) << "; " << foo(b, d) << "; " << foo(c, d) << "; " << foo(d, d) << "\n";
}

Prints
foo(1, 1); foo([1,1], 1); foo(3, 1); foo((4,1), 1)
foo(1, [1,1]); foo([1,1], [1,1]); foo(3, [1,1]); foo((4,1), [1,1])
foo(1, 3); foo([1,1], 3); foo(3, 3); foo((4,1), 3)
foo(1, (4,1)); foo([1,1], (4,1)); foo(3, (4,1)); foo((4,1), (4,1))

A: You can take a look in boost/multiprecision/mpfr.hpp how mpfr_float_... is defined.  These types are themselves templates
typedef number<mpfr_float_backend<50> >    mpfr_float_50;
typedef number<mpfr_float_backend<100> >   mpfr_float_100;
typedef number<mpfr_float_backend<500> >   mpfr_float_500;
typedef number<mpfr_float_backend<1000> >  mpfr_float_1000;
typedef number<mpfr_float_backend<0> >     mpfr_float;

Based on this observation we can easily come up with a template which only matches those types:
#include <iostream>

#include <boost/multiprecision/mpfr.hpp>

using boost::multiprecision::number;
using boost::multiprecision::backends::mpfr_float_backend;

template < unsigned size >
void print(number<mpfr_float_backend<size>> const &num)
{
    std::cout << "mpfr_float_" << size << ": " << num << "\n";
}

int main()
{
    using namespace boost::multiprecision;
    mpfr_float_50 a = 1;
    mpfr_float_100 b = 2;
    mpfr_float_500 c = 3;
    double d = 4;

    print(a);
    print(b);
    print(c);
  //print(d); // BOOM!
}

You could of course also be a little more general and allow any Boost.Multiprecision type:
template < typename... T >
void print(boost::multiprecision::number<T...> const &num)
{
    std::cout << num << "\n";
}


text:
Q: What is the difference between these two differential equations? I know how to solve both of these problems but I don't know why I solve each of these problems differently. How can I solve the second problem the way I solved the first one? Or is that not possible?

*

*If $\frac{dy}{dx}=y\sec^2(x)$ and $y=5$ when $x=0$, then $y=$
a) $e^{\tan(x)}+4$
b) $e^{\tan(x)}+5$
c) $5e^{\tan(x)}$
d) $\tan(x)+5$
e) $\tan(x)+5e^x$
To solve this I found $\frac{dy}{dx}$ for each of the answer choices and answer choice c) gives $\frac{dx}{dy}=5e^{\tan(x)}\sec^2(x)$ and since $y=5e^{\tan x}$, this is of the form $\frac{dy}{dx}=y\sec^2 x$

*Which of the following is the solution to the differential equation $\frac{dy}{dx}=e^{y+x} $ with the initial condition $y(0)=-\ln(4)$?

a) $y=-x-\ln(4)$
b) $y=x-\ln(4)$
c) $y=-\ln(-e^x+5)$
d) $y=-\ln(e^x+3)$
e) $y=\ln(e^x+3)$
$\frac{dy}{dx}=e^y*e^x$
$\frac{dy}{y}=e^xdx$
$\int \frac{dy}{y}= \int e^xdx$
$-e^{-y}=e^x +C$
$e^{-y}=-e^x +C$
$\ln[e^{-y}]=\ln[-e^x +C]$
$-y=\ln(-e^x+C)$
$y=-\ln(-e^x+C)$
This is answer choice C.

A: You can do the same thing on the first equation as you did on the second equation.
It's called separation of variables.
Start with
$$\dfrac{dy}{y}= \sec^2(x)dx$$
and integrate both sides separately!

A: You can do the same in the second problem: $dy=-d(\ln(-e^x+5))=\frac{e^xdx}{-e^x+5}$ or
$$\frac{dy}{dx}=e^xe^y$$ because if $y=-\ln(-e^x+5)$ then $e^y=\frac{1}{-e^x+5}$


text:
Q: how to show the data in list using cursor in android I am getting the from the database using cursor but when i am trying to show the data in list, it is not showing..
the below code is for accessing the data using cursor from database:
protected void showCustomerdetails() {

    try
    {
        Cursor cursor = m_dbManager.getValues("customer", new String[]{"name","mobile_phone" }, null, null, null, null);
        if(cursor != null)
        {
            cursor.moveToFirst();
            int i = 0;
            while(cursor.isAfterLast() == false)
            {
                m_uname = cursor.getString(cursor.getColumnIndex("name"));
                Log.d("debug","getting the name from cursor");
                m_mobnum = cursor.getString(cursor.getColumnIndex("mobile_phone"));
                cursor.moveToNext();
                i++;
            }
        }
        cursor.close();
    }
    catch(SQLException e)
    {
        e.printStackTrace();
    }
}

now the below code is for adding the data in the list---
class IconicAdapter extends ArrayAdapter<String>
{
 Activity context;
 IconicAdapter(Activity context)
 {
     super(context, R.layout.custoemrs_list);
     this.context=context;
 }

 public View getView(int position, View convertView, ViewGroup parent)
 {
    View row = null;
    try
    {
            LayoutInflater inflater=context.getLayoutInflater();
            row=inflater.inflate(R.layout.custoemrs_list, null);
            TextView des=(TextView)row.findViewById(R.id.custusername);
            des.setText(m_uname);

            TextView qty=(TextView)row.findViewById(R.id.custmobnum);
            qty.setText(m_mobnum);

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return row;
 }
}

A: Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor))

A: You are iterating through the Cursor and setting the same variable over and over with a different value, until it finally reaches the end of the cursor.
Instead, you need to read it once per call in the getView() method.
look into this part:
while(cursor.isAfterLast() == false)
{
 m_uname = cursor.getString(cursor.getColumnIndex("name")); // <-- BAD!
 Log.d("debug","getting the name from cursor");
 m_mobnum = cursor.getString(cursor.getColumnIndex("mobile_phone")); // <-- BAD!
 cursor.moveToNext();
 i++; // <-- UNUSED!
}

You are not using i for anything here. Rather, you are replacing the values of m_uname and m_mobnum constantly. A simple way to make it to work is to create a couple of ArrayList and do
ArrayList<String> m_uname = new ArrayList<String>();
//

while(cursor.isAfterLast() == false)
{
 m_uname.add(cursor.getString(cursor.getColumnIndex("name")));
 Log.d("debug","getting the name from cursor");
 m_mobnum.add(cursor.getString(cursor.getColumnIndex("mobile_phone")));
 cursor.moveToNext();
}

You would then use it as
des.setText(m_uname.get(position));


text:
Q: How to get rid of OPEN_CHILDREN_LIMIT_EXCEEDED in AWS SWF test I am getting the following error when I tried to run the workflow.Start()
Configuration workflowInput = ConfigurationBuilder.getEmpty();
RemoteFilesFetchWorkflowClient workflowClient = workflowFactory.getClient();

Promise<Void> result = workflowClient.start(workflowInput);

com.amazonaws.services.simpleworkflow.flow.StartChildWorkflowFailedException: OPEN_CHILDREN_LIMIT_EXCEEDED for workflowExecution="{WorkflowId: c6948b63-4134-4b67-b69a-8ab7160b5d9a,RunId: 954ed658-b7aa-4598-a215-c2b35db298f0}" of workflowType={Name: RemoteFilesFetchWorkflow.start,Version: 1.0}

I am unable to find the cause for this and resolve this.

A: According to the documentation the default limit for the open workflow executions is 100k per domain. This includes child workflow executions. Are you trying to execute more than 100k simultaneously? If your use case requires this then submit Amazon SWF Limit Increase Form to get your limit increased.
Edit: For the unit test this exception is thrown by the following line of code. It looks like the actual error is linked to the exception as the cause. Look at the complete stack trace to see the original exception.


text:
Q: Disproportional processing time with arithmetic operations [C] Can somebody explain what is going on here with this small program?
#include<stdio.h>

int main()
{
    float a=0.577;
    float b=0.921;
    float c;
    int i;

    for (i=0;i<100000000;i+=1){
        c=0.7*a-0.2*b;
        //a=0.145*c+2.7*b;
    }

    printf ("%.3f\n",c);
}

Note, there is a line commented out.
I compiled it first without the line and then with the line. (Used gcc -O2 ...). And measured the processing time. I was very surprised to find out that execution time was 0.001s versus 2.444s. And this doesn't make much sense. Or rather, there must be some logic behind this.
Can you please explain what is going on and how to mitigate this problem?
I work on an program that process huge amount of data and it seems to me that I run into very same performance problem there.
I was considering switching from floats to integers but it seems that with integers it behaves the same.
EDIT: At the end the solution was trivial and logical. So I thank for all answers and explanations!

A: Good optimizers are very good.
Since the one-line calculation returns the same value on every iteration, there's no need to recalculate anything in the loop, so the optimizer doesn't.
When you change a too (with the two-line calculation), then it must run the loop.
Hence the difference in timing.

A: Without the commented out line, the compiler can optimize out the whole loop. The value being set doesn't change with respect to the loop.
With the commented out line, the value of a changes at each start of the loop, so the loop can't be optimized out.
That is, your program and this one:
int main()
{
    float a=0.577;
    float b=0.921;
    float c;
    int i;

    c=0.7*a-0.2*b;
    for (i=0;i<100000000;i+=1){
        //a=0.145*c+2.7*b;
    }

    printf ("%.3f\n",c);
}

produce the same answer if and only if that line is commented.

A: Here's the code I get from compiling your example with optimizations enabled:
(__TEXT,__text) section
_main:
0000000100000f20    pushq   %rbp
0000000100000f21    movq    %rsp, %rbp
0000000100000f24    leaq    61(%rip), %rdi ## literal pool for: %.3f

0000000100000f2b    movsd   45(%rip), %xmm0
0000000100000f33    movb    $1, %al
0000000100000f35    callq   0x100000f3e ## symbol stub for: _printf
0000000100000f3a    xorl    %eax, %eax
0000000100000f3c    popq    %rbp
0000000100000f3d    ret

Notice that the loop doesn't even run - the compiler has optimized it out entirely, since it can tell that the only assignment of c that matters is the last one.
In contrast, with the commented line reinserted, the loop must run, and the output code looks like:
(__TEXT,__text) section
_main:
0000000100000ea0    pushq   %rbp
0000000100000ea1    movq    %rsp, %rbp
0000000100000ea4    movss   148(%rip), %xmm5
0000000100000eac    movl    $100000000, %eax
0000000100000eb1    movsd   143(%rip), %xmm1
0000000100000eb9    movsd   143(%rip), %xmm2
0000000100000ec1    movsd   143(%rip), %xmm3
0000000100000ec9    movsd   143(%rip), %xmm4
0000000100000ed1    nopw    %cs:(%rax,%rax)
0000000100000ee0    xorps   %xmm0, %xmm0
0000000100000ee3    cvtss2sd    %xmm5, %xmm0
0000000100000ee7    mulsd   %xmm1, %xmm0
0000000100000eeb    addsd   %xmm2, %xmm0
0000000100000eef    cvtsd2ss    %xmm0, %xmm0
0000000100000ef3    cvtss2sd    %xmm0, %xmm0
0000000100000ef7    movaps  %xmm0, %xmm5
0000000100000efa    mulsd   %xmm3, %xmm5
0000000100000efe    addsd   %xmm4, %xmm5
0000000100000f02    decl    %eax
0000000100000f04    cvtsd2ss    %xmm5, %xmm5
0000000100000f08    jne 0x100000ee0
0000000100000f0a    leaq    87(%rip), %rdi ## literal pool for: %.3f

0000000100000f11    movb    $1, %al
0000000100000f13    callq   0x100000f1c ## symbol stub for: _printf
0000000100000f18    xorl    %eax, %eax
0000000100000f1a    popq    %rbp
0000000100000f1b    ret

Quite different, as you can see.

A: With the line a=0.145*c+2.7*b; commented out, the only expression inside your loop is loop-invariant. Your optimizer knows that, so it moves the computation outside the loop.  Then the optimizer notices there's nothing in the loop, so it gets rid of the loop.
When you put the line back, the expression is no longer loop-invariant.

A: In the first instance the calculated value was constant. The compiler would have calculated c = 0.7 * 0.577 - 0.2 * 0.921 at compile time. Its even free to optimize out the loop as nothing changes within it (a, b & c are invariant).
In the second instance, a and c vary for each iteration so have to be computed 100000000 times.


text:
Q: How do I parse JSON in Racket? I can't seem to figure out the {documentation}, there aren't really any examples of parsing some simple JSON data, so I was wondering if anyone here could give me some examples to get started.

A: Here's a very simple example:
(require json)
(define x (string->jsexpr "{\"foo\": \"bar\", \"bar\": \"baz\"}"))
(for (((key val) (in-hash x)))
  (printf "~a = ~a~%" key val))

Here's how you can use it with a JSON-based API:
(require net/http-client json)
(define-values (status header response)
  (http-sendrecv "httpbin.org" "/ip" #:ssl? 'tls))
(define data (read-json response))
(printf "My IP address is ~a~%" (hash-ref data 'origin))

At the OP's request, here's how you can create a JSON value from a structure type:
(require json)
(struct person (first-name last-name age country))
(define (person->jsexpr p)
  (hasheq 'first-name (person-first-name p)
          'last-name (person-last-name p)
          'age (person-age p)
          'country (person-country p)))
(define cky (person "Chris" "Jester-Young" 33 "New Zealand"))
(jsexpr->string (person->jsexpr cky))


text:
Q: Varnish Backend_health - Still sick I'm using varnish-3.0.6-1 on one host and tomcat8 on another.
Tomcat is running fine but for some reason I can't get varnish backend to be healthy.
Here's my config:
probe healthcheck {
    .url = "/openam/";
    .timeout = 3 s;
    .interval = 10 s;
    .window = 3;
    .threshold = 2;
    .expected_response = 302;
}

backend am {
    .host = "<INTERNAL-IP>";
    .port = "8090";
    .probe = healthcheck;
}

sub vcl_recv {
    if (req.request == "PURGE") {
        if (!client.ip ~ purgers) {
            error 405 "You are not permitted to PURGE";
        }

        return(lookup);
    }

    else if (req.http.host == "bla.domain.com" || req.http.host == "<EXTERNAL-IP>") {
        set req.backend = am;
    }

    else if (req.url ~ "\.(ico|gif|jpe?g|png|bmp|swf|js)$") {
        unset req.http.cookie;
        set req.backend = lighttpds;
    }

    else {
        set req.backend = apaches;
    }
}

It always shows:
Backend_health - am Still sick 4--X-R- 0 2 3 0.001956 0.000000 HTTP/1.1 302

telnet works fine to that host, the only thing that I can't figure it out is that curl returns 302 and that's because main page under 'openam' on tomcat redirects to another page.
$ curl -I http://<INTERNAL-IP>:8090/openam/
HTTP/1.1 302
Location: http://<INTERNAL-IP>:8090/openam/config/options.htm
Transfer-Encoding: chunked
Date: Tue, 12 Sep 2017 15:00:24 GMT

Is there a way to fix that problem?
Any advice appreciated,
Thanks

A: Based on the information provided, you're hitting on this bug of Varnish 3.
The reporter had 3.0.7 and that's the only one available now in packaged releases so you will likely have to build from sources.
So considering that, and Varnish 3 being quite old, I would rather recommend to upgrade to newer Varnish 4 or 5. (It's always easier to rewrite a few lines of VCL than maintaining something that was compiled from sources and the hassle associated with making sure it's always up-to-date).
Another obvious solution would be adjusting your app to send HTTP reason along the code, or perhaps point to the final redirect location which might (or not) already provide reason in HTTP status.
Check whether curl -IL http://<INTERNAL-IP>:8090/openam/config/options.htm provides a reason in the output.
If it's something like HTTP/1.1 200 OK and not just HTTP/1.1 200 then simply update your health check to that URL (naturally adjust expected response code as well).


text:
Q: Integration Testing AngularJS + Karma + Jasmine I would like to test my angular service I would like to test it with real data - a.k.a (Integration Test). I'm using Jasmine and Karma.
Here is my test:
describe('Trending Data Service', function () {
  var value = 0, originalTimeout = 0;
  var service, Enums, $httpBackend;

  // initialize module
  beforeEach(module('waterfall'));

  // initialize services
  beforeEach(inject(function ($injector) {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    $httpBackend = $injector.get('$httpBackend');
    service = $injector.get("trendingService");
    Enums = $injector.get("Enums");
    spyOn(service, 'fetch').and.callThrough();
  }));

  it('check if dependencies are defined', function () {
    expect(service).toBeDefined();
    expect(Enums).toBeDefined();
    expect(service.categories).toBeDefined();
    expect(service.fetch).toBeDefined();
  });

  it('categories array should be defined within the service', function () {
    expect(service.categories.length).toEqual(9);
    expect(service.categories).toEqual(jasmine.any(Array));
  });

  // this test is alway fails...
  it('fetch method should return initial result', function (done) {
    var promise = service.fetch(Enums.socials.viewAll, false);

    promise.then(function (result) {
      done();
    }, function() {
      expect(1).toBe(2);
      done.fail('Error occured');
    });
  });
}

This is the error:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
I tried a wide range of solutions and I haven't got any success with this.
EDIT: 29/April/2016
var trendingService = function ($q, $http) {
   var deferred = $q.defer();
   var $this = this;
   this.fetch = function (id) {
       $http.get(url).then(function (result) {
          deferred.resolve(result);
       }).catch(function(err) {
          deferred.reject(err);
       });
       return deferred.promise;
   }
   return {
      fetch: $this.fetch;
   };
};

var Enums = {
   Roles: {
      Admin: 1,
      User: 2,
      NotRegistered: 0
   }
};

angular.module('').const('Enums', Enums);

A: Karma isn't meant for integration testing. Your call to module('waterfall') is actually a reference to angular.mock.module which mocks all $https calls.
You need to use some form of end-to-end testing to test with real data. I suggest http://angular.github.io/protractor/#/.


text:
Q: Android, change fragment textview from activity I've one activity with 3 fragments,
- top fragment has a textview,
- center fragment has main content
- bottom fragment has a tabwidget
at the start I want my top fragment to display a "text", but when I click on a tab and the center fragment shows me another fragment (this is working fine), I want to display another text in my top fragment.
how can I do this?
thanks,
Pedro Simão

A: Keep a reference to each Fragment in your Activity. Then, add a method to the top Fragment to change the text. Then, call that method from your Activity.


text:
Q: Morphism of rings determined by prime ideal. Let $K_1,K_2,k,F$ be fields and suppose we have a morphism,
$$ K_1 \otimes_k K_2 \xrightarrow{\varphi} F$$
Is $\varphi$ determined by its kernel?
I was trying to give a description to the underlying set of the fibered product of schemes using the colimit of $\operatorname{Hom}(\operatorname{Spec}-,X)$ where the colimit is taken in the category of fields. To finish the description of the underlying set as described here Underlying set of the scheme theoretic fiber, I should be able to say that the only information I need about $\varphi$ is its kernel.

A: Definitely not in general: Letting $k=K_2\subseteq K_1 \subseteq F$ be a tower of extension, one has $K_1 \otimes_k K_2 =K_1$ and $\varphi$ is an embedding of $K_1$ into $F$. Any such $\varphi$ is of course injective, but there are more than one of such embeddings in general.


text:
Q: How can I hide the filter icon in Ag-grid? I'm trying to remove the filter icon in ag-grid whilst keeping the filtering box
Right now I'm trying to use pure css to hide the icon which in webpack just adds the aria-hidden="true"
CSS I've tried
* /deep/ div.ag-floating-filter-button{
    display:none !important;
}

Trying to remove this icon

I either want to completely remove the grid icon using columnsAPI or find a way with CSS to disable the icon truely.

A: This page in the docs describes how to change the icons. I suggest that you change them to an empty string, either in the gridOptions or in a css file. here is the gridOptions way with a plunker:
<ag-grid-angular
    ...
    [icons]="icons"
    ...
    ></ag-grid-angular>

this.icons = {
  filter: ' '
}

A: You can deactivate the filter icon by two ways.
1.) First way: global dactivation
Add enableFilter: false to you gridoptions.
gridOptions = {
  // turn off filtering
  enableFilter: true,
  ...
  columnDefs: [
    ...
  ]
}

2.) Second way: disable per column
Add suppressFilter: true to column definition to turn off filter for this column.
gridOptions = {
    // turn on filtering
    enableFilter: true,
    ...
    columnDefs: [
        {headerName: "Athlete", field: "athlete", filter: "agTextColumnFilter"}, // text filter
        {headerName: "Age",     field: "age",     filter: "agNumberColumnFilter"}, // number filter
        {headerName: "Sport",   field: "sport",   suppressFilter: true} // NO filter
    ]
}

For more information read official ag-grid documentation.

A: Inside of your 'columnDef' array, you should add floatingFilterComponentParams: {suppressFilterButton: true}. Also if you want to remove menu button at top of your column, you can simply create an 'icons' array and bind it to the ag-grid as an option.
What i mean:
columnDef: [
    ...
    floatingFilterComponentParams: { suppressFilterButton: true }
]

and to remove icons:
icons = {
    menu: ' ',
    filter: ' ' //optional, we have already disabled it above.
}

then
<ag-grid-angular
    ...
    [icons]="icons",
    [floatingFilter]="true">
</ag-grid-angular>

A: Use floatingFilter and  check floatingFilterComponentParams. You can hide the filter button by adding this in columnDefs in gridOptions like below
gridOptions = {
  floatingFilter: true
  columnDefs:[{
    ...
    suppressMenu: true,
    floatingFilterComponentParams: {suppressFilterButton:true}
    ...
  }]
}

A: To hide the filter icon on a particular column, add:
menuTabs: []

to the column definition.

A: For me the following css worked:
.ag-icon-filter {display: none;}

A: We have to use the below two properties to disable icons

suppressMenu: true,
floatingFilterComponentParams: {
suppressFilterButton: true }

const defaultColDef = {
        sortable: true,
        editable: false,
        flex: 1,
        filter: true,
        floatingFilter: true,
        suppressMenu: true,
        floatingFilterComponentParams: { suppressFilterButton: true },
    };

 <AgGridReact
      columnDefs={columnDefs}
      rowData={rowData}
      defaultColDef={defaultColDef}
      onGridReady={onGridReady}
 ></AgGridReact>

A: columnDefs: [ {headerName: "Athlete", field: "athlete", filter: "agTextColumnFilter",floatingFilterComponentParams: {suppressFilterButton:true}}]


text:
Q: Updates were rejected because the tip of your current branch is behind Two branches

*

*main

*local_issue_branch

*

*Time T1 - Did some changes in local_issue and pushed ( git push )

*Time T2 - Some changes were also done in the main branch by some
other fellow.

*Time T3 - Some changes are done in local_issue_branch

Now I want to push changes into remote T3

*

*git checkout main

*git pull

*git checkout local_issue_branch

*git rebase main

*git push

I am getting this message
To bitbucket.org:xyzabc/itrp.git
 ! [rejected]            bugfix/ITRP_18238-auth_issue -> bugfix/ITRP_18238-auth_issue (non-fast-forward)
error: failed to push some refs to 'bitbucket.org:xyzabc/itrp.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

I can push to local_issue_branch only with
git push --force

Is this the right approach? Why --force is required?


text:
Q: Error : Message has reached MaxDequeueCount of 5. Moving message to queue 'webjobs-blobtrigger-poison' Error : Message has reached MaxDequeueCount of 5. Moving message to queue 'webjobs-blobtrigger-poison'.
when I tried to put a new file in Container in Azure, I got 5 failed action and this message : Message has reached MaxDequeueCount of 5. Moving message to queue 'webjobs-blobtrigger-poison'.
this is my code :
using System;
using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Xml;
using System.Threading.Tasks;

namespace dynamicFileRepository
{
    [StorageAccount("BlobConnectionString")]
    public class copyBlobtoazureStorage
    {

        [FunctionName("copyBlobtoazureStorage")]
        public void Run(
            [BlobTrigger("input-file/{name}")] Stream inputBlob,
            [Blob("output-file/{name}", FileAccess.Write)] Stream outputBlob,
            string name, ILogger log, ExecutionContext context)
        {

            XmlDocument doc = new XmlDocument();
            using (XmlReader reader = XmlReader.Create(inputBlob))
            {
                doc.Load(reader);
            }
            string jsonText = JsonConvert.SerializeXmlNode(doc);
            Console.WriteLine(jsonText);

            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {inputBlob.Length} Bytes");

    }
    }
}

this is the output window :

A: I've had this issue a couple of times and the reason both times has been because I've not base64 encoded the payload I'm adding to the queue.
var queueClient = new QueueClient(connectionString, "my-queue");
var bytes = Encoding.UTF8.GetBytes(message);
await queueClient.SendMessageAsync(Convert.ToBase64String(bytes));

It's frustrating that the error message isn't more revealing. And, in fact somebody has raised this issue with the Azure team.

A: I recently having this problem too. I have a Blazor app which enqueue messages to Azure Queue and a second Azure Functions to dequeue and process it, but somehow the Azure Functions don't want to process the message and the message ends up in the poison queue.
It turns out the message encoding is different between Azure.Storage.Queue (defaults to None) and the one used in WebJobs (Function App defaults to Base64). The solution is to make sure both app uses the same encoding.
In your host.json file, add this code:
{
  "version": "2.0",
  "extensions": {
    "queues": {
      "messageEncoding": "base64" // or "none"
    }
  }
}

And in the other app where you want to publish the message, set the appropriate  encoding via QueueClientOptions
var client = new QueueClient("ConnectionString", "QueueName", new QueueClientOptions
{
    MessageEncoding = QueueMessageEncoding.Base64 // or QueueMessageEncoding.None
});

Also when you're adding a new message to the queue, don't forget to tick the Encode the message body in Base64 encoding depending on whether you want to use Base64 or not.


text:
Q: React-native [android] full page is getting scrolled when keyboard appears and so the list items getting clicked on scroll The below is the structure of my search page.
When I click on the search box, the keyboard appears, fortunately the screen is not pushed up when keyboard is displayed. But it enabled the entire page to scroll, due to this scrolling behavior the FlatList item is receiving the click event. And so, every time I scroll the item is getting clicked.
This Full page scroll is not allowing the scrollview to take effect. Well, the scrollview is working when keyboard is dismissed.
Questions

*

*How to disable this Full page scroll up behavior when keyboard appears so that ScrollView will take care of the scrolling.

*if the page scroll up is the default behavior and cannot be ignored, how to block the flat list items not receiving the click events on Full page scroll?

Please advise.  UI is shown below.
    <ScrollView contentContainerStyle={{ flex: 1, paddingTop: 22 }}>
        <FlatList
            data={[
                { key: "Devin" },
                { key: "Dan" },
                { key: "Dominic" },
                { key: "Jackson" },
                { key: "James" },
                { key: "Joel" },
                { key: "John" },
                { key: "Jillian" },
                { key: "Jimmy" },
                { key: "Julie" },
            ]}
            renderItem={({ item }) => (
                <TouchableOpacity onPress={onPressClick}>
                    <Text
                        style={{
                            padding: 10,
                            fontSize: 18,
                            height: 44,
                        }}>
                        {item.key}
                    </Text>
                </TouchableOpacity>
            )}
        />
    </ScrollView>

A: Try replace ScrollView with this:
https://github.com/wix/react-native-keyboard-aware-scrollview


text:
Q: Folding at home, NVIDIA GPU stuck in Failed/Ready/Disabled state I wasn't able to fold with GPU for some reason ...
Quick setup.

*

*Fresh install of Ubuntu 18.04.5 LTS (bionic) with third party drivers for NVIDIA (see https://pastebin.com/raw/vGrr7GXu for most packages)

*Installed latest fahclient, fahcontrol from https://foldingathome.org/start-folding (similar to https://foldingathome.org/support/faq/installation-guides/linux)

*Rebooted

18:33:12:WU01:FS02:Sending unit results: id:01 state:SEND error:FAILED project:14907 run:87 clone:0 gen:231 core:0x22 unit:0x0000012d81d59d695f526030ac6fce05
19:09:39:WU01:FS02:Sending unit results: id:01 state:SEND error:FAILED project:13429 run:9209 clone:8 gen:2 core:0x22 unit:0x0000000312bc7d9a0000000023f90008
19:30:39:WARNING:WU01:FS02:FahCore returned: WU_STALLED (127 = 0x7f)
19:30:39:WARNING:WU01:FS02:Too many errors, failing
19:30:39:WU01:FS02:Sending unit results: id:01 state:SEND error:FAILED project:13429 run:9255 clone:16 gen:2 core:0x22 unit:0x0000000312bc7d9a0000000024270010
Full log for FS02: https://pastebin.com/T4F2Ew64
I can switch GPU slot to "on idle" and back (it will show up as "Ready") but it logs it will continue to download and fail (silently to the user, because status is always "Ready").
I changed "cause preference" from "COVID-19" to "Any" and created new GPU slot (without reboot). I can see "Disabled" in GPU slot. I got this log (just one message for GPU slot):
*********************** Log Started 2020-11-30T18:28:45Z ***********************
******************************* Date: 2020-12-01 *******************************
******************************* Date: 2020-12-01 *******************************
04:52:32:WARNING:FS01:No CUDA or OpenCL 1.2+ support detected for GPU slot 01: gpu:-1:-1.  Disabling.

I see the same "Disabled" status after reboot.
Updates below:
Same status "Ready" GPU with 0% progress and many attempts after 10 days: https://pastebin.com/AcuPDfXx.
Now stuck with "Failed" state (full log https://pastebin.com/AckYSBVN).

A: I can fold with GPU again after latest NVIDIA driver and Linux kernel update. Magically resolved for me.
https://stats.foldingathome.org/project?p=14911, 2% log: https://pastebin.com/XbU03FHn
I'm not sure if I can fold https://stats.foldingathome.org/project?p=13439 on GPU...