text:
Q: imagick php5 addon on ubuntu 64bit isn't working I have a lampp webserver and i need to edit animated gif files.
I have tried to install imagick with this tutorial.
But at the "make" commad i get the error
can't read /usr/lib/x86_64-linux-gnu/libjpeg.la: No such file or directory

i already managed to install the 32bit version, but the server gives me an error:
Warning: PHP Startup: Unable to load dynamic library '/opt/lampp/lib/php/extensions/no-debug-non-zts-20090626/imagick.so' - /opt/lampp/lib/php/extensions/no-debug-non-zts-20090626/imagick.so: wrong ELF class: ELFCLASS64 in Unknown on line 0

I googeld the error and someone said, that the server want a 64bit version of the file...
I'm new to compiling files and never installed addons on my webserver...
If you  need aditional informations, logs or some file, please tell me
(Sorry for my bad english :D)

A: It is now bit too late, but here I come with the proper solution to install iMagick with LAMP or XAMPP Server on Linux based systems. It is only the iMagick extension of PECL that works with PHP. So you don't have to worry for Image Magick and Magick Wand to install.
First of all remove everything you have tried to make it work. Uninstall ImageMagick with the following command:
sudo apt-get remove imagemagick

Remove ImageMagick and all its dependencies with the following command:
sudo apt-get remove --auto-remove imagemagick

Purge the config file of ImageMagick with the following command:
sudo apt-get purge imagemagick

Or similarly, like this:
sudo apt-get purge --auto-remove imagemagick

Well, all your previous installation files are just gone.
Now Install it purely and perfectly without any conflict or file modification. Enter the following two commands:
sudo apt-get install imagemagick
sudo apt-get install php5-imagick

That was way too easy - thanks interwebs!
Remember to restart/reload your webserver..
sudo service apache2 graceful

That's all. Check your php.ini or test with any simple script.


text:
Q: Creating a simple HTTP python server to handle broken pipe I create a simple python http server and I want it to display only files from a directory I want to, thus changing always returning "Hello world!" and also how could I handle the broken pipe errors? I tried to do a try catch there but I'm not sure if it's working:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 8089

#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):

    #Handler for the GET requests
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        self.wfile.write("Hello World !")
        return

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started http server on port ' , PORT_NUMBER

    #Wait forever for incoming http requests
    server.serve_forever()

except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()
except socket.error:
    pass

This is my Error:
someIP - - [25/Dec/2019 09:17:11] "GET someFILE HTTP/1.0" 200 -
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 293, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 657, in __init__
    self.finish()
  File "/usr/lib/python2.7/SocketServer.py", line 716, in finish
    self.wfile.close()
  File "/usr/lib/python2.7/socket.py", line 283, in close
    self.flush()
  File "/usr/lib/python2.7/socket.py", line 307, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe

A: Example which follows is the basic example of creating basic web server for serving the static files. Additional comments you can find inside the code, with one additional note: 403 Forbidden implementation can be replaced with file indexing page, for what you need to do the additional generation of it (according to your question, this is out of scope for now.)
from http.server import HTTPServer, BaseHTTPRequestHandler
from os import curdir, sep, path

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200) #Request received, sending OK status
        self.end_headers()
        try:
            if(path.isdir(self.path)): #Checking if user requested access to dirrectory (not to a particular file)
                self.send_response(403)
                self.wfile.write(str.encode("Listing of directories not permited on this server")) #Preventing directory listing, in case you dont want to allow file indexing.
            else: #If user is requesting access to a file, file content is read and displayed.
                f = open(curdir + sep + self.path, 'rb')
                self.wfile.write(f.read())
                f.close()
        except IOError: #Covering the 404 error, in case user requested non-existing file
            print("File "+self.path+" not found")
            self.send_response(404)

httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
httpd.serve_forever()

A: I used to get the same error earlier
My Code :
from signal import signal, SIGPIPE, SIG_DFL

signal(SIGPIPE,SIG_DFL)

Paste it in the end and it should work!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Testing replaceWith in directive with jasmine Can anyone please tell me on how I can test directives whose element is replaced? I am facing an issue where when I  pass in a directive element to be compiled in jasmine, the compiler doesn't return the replaced element but returns the uncompiled one instead. Is there any proper way to test these types of directives? Thanks.
My code:
var svgDirective = angular.module('svgDirective', ['adFactory']);
svgDirective.directive("svg", ['$compile', '$timeout', '$http', 'ad' , function ($compile, $timeout, $http, ad) {
  return {
    restrict: 'EA',
    link: function (scope, elem, attr) {
      var refreshAd = function (id, missingFile) {
        ad.notProcessed(missingFile).then(function () {
          var timer = $timeout(function () {
            refreshAd(id, missingFile)
          }, 2000);
          scope.$on("$destroy", function () {
            $timeout.cancel(timer);
          });
        }, function () {
          $http.get("/ads/" + id + ".json", {
            cache: false
          }).then(function (data) {
            if (data["data"]["svg_image"]["url"] && missingFile.split('.').pop() === 'svg') {
              elem.replaceWith("<object style='width: 75px;height:75px' data=" + data["data"]["svg_image"]["url"] + "></object>");

            }
            if (data["data"]["json_image"]["url"] && missingFile.split('.').pop() === 'json') {
              scope.ad.json_image.url = data["data"]["json_image"]["url"];
            }
          });
        });
      };

      if (scope.ad.is_svg_processed) {
        elem.replaceWith("<object style='width:75px;height:75px' data=" + scope.ad.svg_image.url + "><object>");
      } else {
        refreshAd(attr.class, scope.ad.svg_file);
      }

      if (!scope.ad.is_json_processed) {
        refreshAd(attr.class, scope.ad.json_file);
      }
    }
  }
}]);

My test code:
describe("svg Directive", function(){

  var $compile, $scope, $templateCache, $timeout, $http, ad, element;

  beforeEach(angular.mock.module("svgDirective"));
  beforeEach(module("templates"));

  beforeEach(inject(function(_$compile_,_$rootScope_,_$templateCache_,_$timeout_, _$http_, _ad_){

    $compile = _$compile_;
    $scope = _$rootScope_.$new();
    $templateCache = _$templateCache_;
    $timeout = _$timeout_;
    $http = _$http_;
    ad = _ad_;

    element = '<svg></svg>'

  }));

  it("should show svg images for ads whose svg images are processed", function(){

    $scope.ad = {is_svg_processed:true,is_json_processed:true, svg_image:{url:"https://dicerocket.s3.amazonaws.com/ad/svg_image/622/1_1398608090_28021105597015874837455612979611260004.svg"}};
    element = $compile(element)($scope);
    $scope.$digest();

    console.log(element);

  });

});

When console.log(element) I am getting <svg class="ng-scope"></svg> instead of the object tag that I want replaced. Can anyone tell me why?
The directive runs correctly but I can't seem to test it. Thanks.

A: There is a similar question here: https://stackoverflow.com/a/18898115/424783
In summary, you need to wrap the directive in other element like a DIV
element = '
<svg></svg>
';


text:
Q: How to create a checkbox for multiple choice on PHP I have an input field I changed it to a checkbox for multiple choices.
The worry here I can't add the checkbox, I mean that my user should click on Ctrl and select on the same time several choices. You can see it in this Image:

This following my code of the form:
$app->get('/Chart/{currency}/{year}/{zone}/{lru}....... , function(Request $request,...... $repsite, $lru, $contract, $forecast) use ($app) {
if ($app['security']->isGranted('ROLE_USER')) {
    ///start form
    $user = $app['security']->getToken()->getUser();
    $form = $app['form.factory']->createBuilder('form')->setMethod('GET')
    .
    .
    .
    .
 ->add('lru', 'choice', array(
                    'choices' => array(

                    '\'ATSU\'' => 'ATSU',
                    '\'APCC\'' => 'APCC',
                       .....
                     ),

                    'required' => FALSE,
                    'empty_value' => 'ALL',
                    'empty_data' => NULL,
                    'multiple' => TRUE
                    //'expanded' => TRUE
                ))

I want do a classic checkbox like this on the right:

I did a research on forums I found that I should use multiple and expanded and to set them to TRUE. When I add expanded=TRUE list became very "ugly", I give you a screensheet:

Can you please tell me how can I change my code to do a checkbox for multiple choicelike in the picture above.
I hope that I find solution. Thank you.

A: you can do this, this is implemented in this with code.
you will require jquery to do this.
change this code according to your use
https://codepen.io/elmahdim/pen/hlmri

/*
 Dropdown with Multiple checkbox select with jQuery - May 27, 2013
 (c) 2013 @ElmahdiMahmoud
 license: https://www.opensource.org/licenses/mit-license.php
*/

$(".dropdown dt a").on('click', function() {
  $(".dropdown dd ul").slideToggle('fast');
});

$(".dropdown dd ul li a").on('click', function() {
  $(".dropdown dd ul").hide();
});

function getSelectedValue(id) {
  return $("#" + id).find("dt a span.value").html();
}

$(document).bind('click', function(e) {
  var $clicked = $(e.target);
  if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
});

$('.mutliSelect input[type="checkbox"]').on('click', function() {

  var title = $(this).closest('.mutliSelect').find('input[type="checkbox"]').val(),
    title = $(this).val() + ",";

  if ($(this).is(':checked')) {
    var html = '' + title + '';
    $('.multiSel').append(html);
    $(".hida").hide();
  } else {
    $('span[title="' + title + '"]').remove();
    var ret = $(".hida");
    $('.dropdown dt a').append(ret);

  }
});
body {
  font: normal 14px/100% "Andale Mono", AndaleMono, monospace;
  color: #fff;
  padding: 50px;
  width: 300px;
  margin: 0 auto;
  background-color: #374954;
}

.dropdown {
  position: absolute;
  top:50%;
  transform: translateY(-50%);
}

a {
  color: #fff;
}

.dropdown dd,
.dropdown dt {
  margin: 0px;
  padding: 0px;
}

.dropdown ul {
  margin: -1px 0 0 0;
}

.dropdown dd {
  position: relative;
}

.dropdown a,
.dropdown a:visited {
  color: #fff;
  text-decoration: none;
  outline: none;
  font-size: 12px;
}

.dropdown dt a {
  background-color: #4F6877;
  display: block;
  padding: 8px 20px 5px 10px;
  min-height: 25px;
  line-height: 24px;
  overflow: hidden;
  border: 0;
  width: 272px;
}

.dropdown dt a span,
.multiSel span {
  cursor: pointer;
  display: inline-block;
  padding: 0 3px 2px 0;
}

.dropdown dd ul {
  background-color: #4F6877;
  border: 0;
  color: #fff;
  display: none;
  left: 0px;
  padding: 2px 15px 2px 5px;
  position: absolute;
  top: 2px;
  width: 280px;
  list-style: none;
  height: 100px;
  overflow: auto;
}

.dropdown span.value {
  display: none;
}

.dropdown dd ul li a {
  padding: 5px;
  display: block;
}

.dropdown dd ul li a:hover {
  background-color: #fff;
}

button {
  background-color: #6BBE92;
  width: 302px;
  border: 0;
  padding: 10px 0;
  margin: 5px 0;
  text-align: center;
  color: #fff;
  font-weight: bold;
}

      Select

                    <input type="checkbox" value="Apple" />Apple

                    <input type="checkbox" value="Blackberry" />Blackberry

                    <input type="checkbox" value="HTC" />HTC

                    <input type="checkbox" value="Sony Ericson" />Sony Ericson

                    <input type="checkbox" value="Motorola" />Motorola

                    <input type="checkbox" value="Nokia" />Nokia

  <button>Filter</button>

Hope this helps


text:
Q: React Native Redirect to application if installed, otherwise to App Store or PlayStore I want to redirect on press of app link as:-

*

*To playstore or AppStore if app is not installed.

*Open my app (with deep linking) if app is installed.

What I have done till now:-
I have achieved requirement 2 using deep linking of react navigation 5.
As:-
import constants from '../../constants';

 const config = {
screens: {
    //SignInScreen: "SignInScreen",
    SignupScreen: {
        path: `${constants.Screens.SignUpScreen.name}/:id`,
        parse: {
            id: (id) => `${id}`,
        },
    }
},
 };

 const linking = {
prefixes: ["http://com.app"],
config,
  };

 export default linking;

App.js:-
<NavigationContainer linking={linking} ref={navigationRef}>
        {
            props.global.switchApp.isLoading ?
                <SplashStack />
                :
                (
                    props.global.user.accessToken !== null ?
                        <AppStack /> :
                        <AuthStack />
                )
        }
    </NavigationContainer>

And with respective changes in AndroidManifest.xml as:-
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data
      android:host="com.app"
      android:scheme="http" />
  </intent-filter>

and adding url type in target of project.
And In Appdelegate.m file as:-
- (BOOL)application:(UIApplication *)application
        openURL:(NSURL *)url
        options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

 // Add any custom logic here.
 BOOL deepLinking =  [RCTLinkingManager application:application openURL:url options:options];
return  deepLinking;
}

How can I achieve requirement 1 while using this?
Thanks!!!

A: To open an app or open an app store or play store, on an app link click if the app not installed, try the firebase dynamic linking feature.
Check out the docs for more info.
https://rnfirebase.io/dynamic-links/usage


text:
Q: Encountering runtime error " attempt to insert nil object " I am trying to write a simple multiplayers Swift program using Xcode 7 beta 5. I encountered the following error at runtime:
[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack

And then I tried and error and found that this piece of code somehow introduced this error:
func setupMatchHandler() {
    /* This function handles invite as sent by other users */

    GKMatchmaker.sharedMatchmaker().matchForInvite(GKInvite().self , completionHandler: { (invitedMatch , invitationError) -> Void in

        if invitationError != nil {
            // error out
            print("Game Center error: \(invitationError)")
        }

        if invitedMatch != nil {
            // success
            print("invitation received!")
        }
    })

}

I wonder can any expert here shed light on what went wrong here? Thanks a million!
sam

A: Maybe a check for (GKInvite().self != nil) could help?
It seems that it's the only thing that you are inserting via matchForInvite is this one


text:
Q: Docker Error: failed to register layer: Error processing tar file(exit status 1): "...msader15.dll.mui: no such file or directory" I am trying to build my ASP.NET 4.7.2 WEB Services into a docker file, however when I run
docker build -t manufacturing-portal-api:latest .

I get the following error:
failed to register layer: Error processing tar file(exit status 1): link /Files/Program Files/common files/system/ado/en-US/msader15.dll.mui /Files/Program Files (x86)/common files/system/ado/en-US/msader15.dll.mui: no such file or directory=> => sha256:d9e8b01179bfc94a5bdb1810fbd76b999aa52016001ace2d3a4c4bc7065a9601 1.66GB / 1.66GB                     0.0s

This is my docker file

FROM microsoft/dotnet-framework:4.7.2-sdk-windowsservercore-1803 AS build
WORKDIR /app

# copy csproj and restore as distinct layers
COPY *.sln .
COPY WebPortalAPI/*.csproj ./WebPortalAPI/
COPY WebPortalAPI/*.config ./WebPortalAPI/
COPY ./instantclient_11_2 .
ENV PATH=./instantclient_11_2
ENV TNS_ADMIN=./instantclient_11_2/network/admin
RUN nuget restore

# copy everything else and build app
COPY WebPortalAPI/. ./WebPortalAPI/
WORKDIR /app/WebPortalAPI
RUN msbuild /p:Configuration=Release

FROM microsoft/aspnet:4.7.2-windowsservercore-1803 AS runtime
WORKDIR /inetpub/wwwroot
COPY --from=build /app/WebPortalAPI/. ./

please advise

A: Your Docker host is likely configured to run Linux containers inside of a VM. To run Windows containers, you need to "Switch to Windows containers" in the Docker menu. Documentation on that is available here.


text:
Q: Compilation warning OpenCL Matrix Multplication Why is this not vectorizing?
__attribute__((num_simd_work_items(4)))
__attribute__((num_compute_units(2)))
__attribute__((reqd_work_group_size(16,16,1)))
__kernel void matrix_multiplication(const int fDIM,const int gDIM, const int hDIM,
__global float*  A, __global float* B, __global float* C) {
    int k;
    int i = get_global_id(0);
    int j = get_global_id(1);
    float temp_result;
    if((i < gDIM) && (j<fDIM)){
      temp_result= 0.0f;
        for(k = 0; k<hDIM;k++) {
          temp_result+= A[i*gDIM+k] * B[k*hDIM+j];

        }
      C[i*gDIM+j] = temp_result;

    }
}

Compiler Warning:

Kernel Vectorization: branching is thread ID dependent ... cannot vectorize.

A:
Q : Why is this not vectorizing?

The evil is the "branching…cannot vectorize" - it relates to this instruction:
if( ( i < gDIM ) && ( j < fDIM ) ){ ... }
Efficient SIMD-instructions based vectorisation means all code-execution flows are not "divergent" (branched) and do "execute" the very same data/instruction (i.e. data elements SIMD-"glued" into Vectors of DATA, put into wide-enough, CPU, SIMD-friendly, registers, that get computed at once by a single SIMD-friendly instruction - i.e. the very same for each thread-in-a-pack SIMD-friendly instruction, i.e. not if(){...}else{...}-diverged into different, "divergent" flow-of different sequences of different instructions for different data-elements
It is principally impossible to want do different operations for different parts of the data, aligned into the SIMD-friendly CPU register - one and only one SIMD-friendly instruction can be executed at once for all vector-components stored into the SIMD-friendly CPU-register.
Hardware details on integer and floats SIMD-vector instructions vary, as does the resulting micro-ops latency, SIMD-processor specific details form compilator do matter a lot, yet the principle of avoiding divergent paths is common for the automated SIMD-vectorisation in the compiler phase. For more deails on SIMD-instructions and their further performance-limiting properties may read and learn from Agner


text:
Q: Is the model with the lowest AIC value always the preferred one? I have a question regarding model selection based on the AIC criterion. I have 5 predictor variables that I include in my models (no interactions are included) and create all possible model combinations.
After, I calculate the AIC values for each model and thought I should select the model with the lowest AIC value, which already penalizes for the number of parameters included. However, when I test between the model with the lowest AIC value (that contains four parameters) and the second lowest AIC value (that contains three parameteres) using the anova() function in R, it seems that the preferred model is the one with the second lowest AIC value (three parameters) because it seems that the more complex model is not explaining significantly greater variance than the less complex model, even if the former has the lowest AIC value. I'm confused as to what model should actually be selected. Can someone clarify this discrepancy for me?


text:
Q: nginx-ingress sending traffic to nginx in pod but not returning assets Basically, I'm having difficulty getting nginx to serve the npm build from a CRA web app that is at the subpath /new-admin.
I do have in the package.json "homepage": "/new-admin" and <Route basename={process.env.PUBLIC_URL}> in the index.js. Works fine in development, but now that I'm trying to make a staging/production copy it isn't and I'm pretty sure it is due to the ./nginx/default.conf. Of the various configurations I've tried, none have worked and I either get:

*

*500 Internal Server Error

*<Uncaught SyntaxError: Unexpected token '<'
This is what I have:
# ingress.yaml

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/proxy-body-size: "0"
    nginx.org/client-max-body-size: "500m"
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/configuration-snippet: |
      rewrite ^(/admin)$ $1/ permanent;
  name: ingress-service-dev-admin
  namespace: default
spec:
  rules:
    - http:
        paths:
          - path: /admin/?(.*)
            backend:
              serviceName: admin-old-cluster-ip-service-dev
              servicePort: 4000
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      rewrite ^(/new-admin)$ $1/ permanent;
  name: ingress-service-dev
  namespace: default
spec:
  rules:
    - http:
        paths:
          - path: /new-admin/
            backend:
              serviceName: admin-new-cluster-ip-service-dev
              servicePort: 4001
          - path: /api/
            backend:
              serviceName: api-cluster-ip-service-dev
              servicePort: 5000
          - path: /
            backend:
              serviceName: client-cluster-ip-service-dev
              servicePort: 3000

# Dockerfile for /new-admin/

FROM node:13-alpine as builder
WORKDIR /app
COPY ./package.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx
EXPOSE 4001
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/build /usr/share/nginx/html

This version of the default.conf results in a 500 Internal Server Error:
# ./nginx/default.conf

server {
  listen 4001;
  root /usr/share/nginx/html;
  index index.html index.htm;

  location /new-admin {
    try_files $uri $uri/ /new-admin/index.html;
  }
}

This is the associated nginx log:
[admin-new] 2020/10/05 20:31:49 [error] 28#28: *9 rewrite or internal redirection cycle while internally redirecting to "/new-admin/index.html", client: 172.17.0.4, server: , request: "GET /new-admin/ HTTP/1.1", host: "192.168.64.5"
[admin-new] 172.17.0.4 - - [05/Oct/2020:20:31:49 +0000] "GET /new-admin/ HTTP/1.1" 500 579 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" "192.168.64.1"

This version results in <Uncaught SyntaxError: Unexpected token '<':
# ./nginx/default.conf

server {
  listen 4001;
  root /usr/share/nginx/html;
  index index.html index.htm;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

This seems closest to being correct given it serves the index.html, just not the CSS and JS assets. It does show in the index.html, which should be correct:
<script src="/new-admin/static/js/2.c6b4376b.chunk.js"></script>
<script src="/new-admin/static/js/main.c24347bf.chunk.js"></script>

I've also noticed when it starts the Pod it says, despite the fact it is building the images from scratch.
[admin-new] /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
[admin-new] /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
[admin-new] /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
[admin-new] 10-listen-on-ipv6-by-default.sh: Getting the checksum of /etc/nginx/conf.d/default.conf
[admin-new] 10-listen-on-ipv6-by-default.sh: error: /etc/nginx/conf.d/default.conf differs from the packaged version
[admin-new] /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
[admin-new] /docker-entrypoint.sh: Configuration complete; ready for start up

A: Actually, came across this answer which was pretty much the exact issue I was experiencing:
React & nginx routing to subdirectory
So my final ./nginx/default.conf looked like this:
server {
  listen 4001;
  root /usr/share/nginx/html;
  index index.html index.htm;

  location = /new-admin {
    try_files $uri $uri/ /index.html =404;
  }

  location ~ ^/new-admin(.*) {
    try_files $1 $1/ /index.html =404;
  }
}


text:
Q: Restrict access to the owner of an object in DDD Let's say there is an object TaskList which can be edited and deleted only by its owner. Other users should only by able to take a task and update its status.
The following options come to my mind:

*

*check the ownership and access in the controller of the web application

*let the repository return proxy object which throws exception on certain operations, but the controller (or view) would still need to know which actions (in form of links or form fields) should be visible

*pass the caller (user) to the method of the domain object, so that the domain object can itself check whether the caller ist allowed or not.

The used technology is Java.
Any other/better ideas?
Interesting articles about security and DDD

*

*Domain Object Security with the Spring framework

*Security in Domain-Driven Design
I have accepted my own answer now, because that is what I actually use, but further suggestions are welcome.

A: I would not encode the ownership/permissions model into the TaskList domain object.  That sort of business logic should be external.  I also don't like the idea of a proxy object.  Although it would certainly work, it would confuse debugging and is, in this case at least, unnecessarily complex.  I would also not check it in the controller.
Instead I would create a business logic object which oversees the permissions for TaskList.  So the TaskList would have an owner field but you would have something like:
public class TaskListAccessor {
    private TaskList taskList;
    private User reader;

    public void updateStatus(Status status) {
        // everyone can do this
        taskList.updateStatus(status);
    }

    /** Return true if delete operation is allowed else false */
    public boolean isDeleteAllowed() {
        return taskList.getOwner().equals(reader);
    }

    /** Delete the task.  Only owners can do this.  Returns true if worked else false */
    public boolean delete() {
        if (isDeleteAllowed()) {
           taskList.delete();
           return true;
        } else {
           return false;
        }
    }
    // ... other accessors with other is*Allowed methods
}

If you need to require that all operations on TaskList objects go through accessors then you could create a factory class which is the only one who creates TaskList using package constructors or something.  Maybe the factory is the only one who would use the DAO to look up the TaskList from the data store.
However, if there are too many methods to control in this fashion then a proxy might be easier.  In both cases having TaskList be an interface would be recommended, with the implementation class hidden by the proxy or the accessor.

A: I found it unnecessarily complex to create accessor classes for each protected domain class as suggested by 'Gray'. My solution is probably not perfect, but simple to use and - more important - robust. You cannot forget to use a certain object or to check conditions outside.
public class TaskList {

    private SystemUser owner;
    private List<Task> tasks = new ArrayList<>();

    public TastList(SystemUser owner) {
        this.owner = owner;
    }

    public void Add(Task task) {
        Guard.allowFor(owner);
        tasks.add(task);
    }
}

The Guard knows the current user (from a thread local for example) and compares it to the owner passed as parameter to allowFor(owner). If access is denied a security exception will be thrown.
That is simple, robust and even easy to maintain since only the guard has to be changed if the underlying authentication changes.


text:
Q: Issue while fetching app details on lasso server instance I am getting following error(error snapshot attached below) while trying to access LassoApps section under lasso server instance. I am using lasso 9.2 with LassoLab and Apache Web server 2.2 on a windows 8 machine.
error in lasso app section:

Also, here is the entry in lassospitfire.out.txt file. Hope this could help in someway.
211:22 http_server.lasso
211:22 http_server.lasso
101:4 http_server.lasso
440:10 lassospitfire.lasso
251:13 lassospitfire.lasso
473:9 http_server.lasso
471:4 http_server.lasso
471:4 http_server.lasso
465:4 http_server.lasso
464:16 http_server.lasso
A Failure: 995 The I/O operation has been aborted because of either a thread            exit or an application request.

Need assistance in resolving this issue. Thanks in advance!!

A: That looks like Lasso 9.3. Make sure you're using the latest Windows build, and if it still doesn't work, try removing LJAPI.dll from the main LassoModules folder.


text:
Q: What is the most populous race in the Alpha and Beta quadrants? In the Alpha and Beta Quadrants we encounter many different alien races. Was it ever commented on which race had the highest population? We know both the Klingon and Romulan empires had fleets to match the Federation, comprised primarily of their respective races, while the Federation incorporates many different alien species.
Out of the alien races we know of, which is the most populous in these 2 quadrants?
Would like
specifically looking for, what we could say as sentient lifeforms(klingons, humans, vulcans, ect).
But tribble or other answers
 welcome if you have accurate counts

A: Echoing my answer here
Geoffrey Mandel's "Star Trek : Star Charts" (which isn't generally considered truly canon but was at least 'advised on' by Senior Trek Designer Michael Okuda) indicates that the Ferengi homeworld (Ferenginar) has a popuation of over 78 billion:

Of the Federation worlds, Andoria has a population of 38.2 Billion, representing some 3.2% of the total population of the Federation.

By comparison, Vulcan has a population of 6 billion, Romulus has a population over just over 18 billion and Kronos (Qo'noS) has a population of just under 3.5 billion. This of course doesn't take into account the relative sizes of their empires/colonies. For example, there's a mention that during an alternate timeline war with the Federation, Klingon casualties may have numberered into the tens of billions.

Purely as a matter of interest, per this excellent answer we can reasonably assert that the Human population (including Earth and its associated colonies) was anything between 12 and 20 Billion in the same time period.


text:
Q: Merging two files column and row-wise in bash I would like to merge two files, column and row-wise but am having difficulty doing so with bash. Here is what I would like to do.
File1:
1 2 3
4 5 6
7 8 9

File2:
2 3 4
5 6 7
8 9 1

Expected output file:
1/2 2/3 3/4
4/5 5/6 6/7
7/8 8/9 9/1

This is just an example. The actual files are two 1000x1000 data matrices.
Any thoughts on how to do this? Thanks!

A: Or use paste + awk
paste file1 file2 | awk '{ n=NF/2; for(i=1; i<=n; i++) printf "%s/%s ", $i, $(i+n); printf "\n"; }'

Note that this script adds a trailing space after the last value. This can be avoided with a more complicated awk script or by piping the output through an additional command, e.g.
paste file1 file2 | awk '{ n=NF/2; for(i=1; i<=n; i++) printf "%s/%s ", $i, $(i+n); printf "\n"; }' | sed 's/ $//'

awk solution without additional sed. Thanks to Jonathan Leffler. (I knew it is possible but was too lazy to think about this.)
awk '{ n=NF/2; pad=""; for(i=1; i<=n; i++) { printf "%s%s/%s", pad, $i, $(i+n); pad=" "; } printf "\n"; }'

A: paste + perl version that works with an arbitrary number of columns without having to hold an entire file in memory:
paste file1.txt file2.txt | perl -MList::MoreUtils=pairwise -lane '
    my @a = @F[0 .. (@F/2 - 1)]; # The values from file1
    my @b = @F[(@F/2) .. $#F]; # The values from file2
    print join(" ", pairwise { "$a/$b" } @a, @b); # Merge them together again'

It uses the non-standard but useful List::MoreUtils module; install through your OS package manager or favorite CPAN client.

A: Assumptions:

*

*no blank lines in files

*both files have the same number of rows

*both files have the same number of fieldds

*no idea how many rows and/or fields we'll have to deal with

One awk solution:
awk '

# first file (FNR==NR):

FNR==NR { for ( i=1 ; i<=NF ; i++)          # loop through fields
              { line[FNR,i]=$(i) }          # store field in array; array index = row number (FNR) + field number (i)
          next                              # skip to next line in file
        }

# second file:

        { pfx=""                            # init printf prefix as empty string
          for ( i=1 ; i<=NF ; i++)          # loop through fields
              { printf "%s%s/%s",           # print our results:
                    pfx, line[FNR,i], $(i)  # prefix, corresponding field from file #1, "/", current field
                pfx=" "                     # prefix for rest of fields in this line is a space
              }
          printf "\n"                       # append linefeed on end of current line
        }
' file1 file2

NOTES:

*

*remove comments to declutter code

*memory usage will climb as the size of the matrix increases (probably not an issue for the smallish fields and OPs comment about a 1000 x 1000 matrix)

The above generates:
1/2 2/3 3/4
4/5 5/6 6/7
7/8 8/9 9/1


text:
Q: Activity has leaked window that was originally added with progress dialog I have this code here:  I have this code here:  I have this code here:
public class MainTask extends Activity {

private boolean flag=false;
private Context context;
private String url;
private ProgressDialog pd;
private View view;

public MainTask(Context context,String url,View view) {
    this.url=url;
    this.view=view;
    this.context=context;
    BitmapDownloaderTask task = new BitmapDownloaderTask();
    task.execute();
}

private Void MainThread() {
    int  leave=0;
    int  pass=0;

    while(true){

        if(leave==-1){
            flag=true;
            break;
        }
        else if(pass==Preferences.vcheckimage.size())
            break;

        for(int i=0;i<Preferences.vcheckimage.size();i++){

            if(Preferences.vcheckimage.get(i).equals("-1")){
                leave=-1;
                break;
            }
            else{
                pass++;
            }
        }
    return null;
}

private class BitmapDownloaderTask extends AsyncTask<Void, Void, Void> {

    public BitmapDownloaderTask() {

    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        view.setEnabled(false);
        pd = new ProgressDialog(context);
        pd.setTitle("Processing...");
        pd.setMessage("Please wait.");
        pd.setCancelable(false);
        pd.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        pd.setIndeterminate(true);
        pd.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        return MainThread();
    }

     @Override
     protected void onPostExecute(Void result) {

        pd.dismiss();

        if(flag){
         Toast.makeText(context,"Image is not available yet.", Toast.LENGTH_LONG).show();

        }

    }
}
 }

but when i run this i get the following error:
 05-17 18:24:57.069: ERROR/WindowManager(18850): Activity com.mypkg.myP has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44c46ff0 that was originally added here
    05-17 18:24:57.069: ERROR/WindowManager(18850): android.view.WindowLeaked: Activity ccom.mypkg.myP has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44c46ff0 that was originally added here
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.view.ViewRoot.<init>(ViewRoot.java:231)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.Dialog.show(Dialog.java:239)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at com.mypkg.myP$PreparePairingLinkageData.onPreExecute(viewP.java:183)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.os.AsyncTask.execute(AsyncTask.java:391)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at com.mypkg.myP.onCreate(viewP.java:94)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread.access$2200(ActivityThread.java:126)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.os.Handler.dispatchMessage(Handler.java:99)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.os.Looper.loop(Looper.java:123)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread.main(ActivityThread.java:4595)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at java.lang.reflect.Method.invokeNative(Native Method)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at java.lang.reflect.Method.invoke(Method.java:521)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    05-17 18:24:57.069: ERROR/WindowManager(18850):     at dalvik.system.NativeStart.main(Native Method)

Has anyone idea why is this happen? I saw and other posts but didn't help me.

A: I guess the BitmapDownloaderTask
being internal to MainThread
is the whole problem. Try matching the brackets the issue should be resolved.
EDIT:
Last bit from my side. My MainThread code would be this
private Void MainThread() {
        int leave = 0;
        int pass = 0;

        while(true) {

            if(leave==-1) {
                flag=true;
                break;
            }
            else if(pass==Preferences.vcheckimage.size())
                break;

            for(int i=0;i<Preferences.vcheckimage.size();i++) {
                if(Preferences.vcheckimage.get(i).equals("-1")) {
                    leave=-1;
                    break;
                } else {
                    pass++;
                }
            }
            break;
        }
        return null;
    }


text:
Q: Air resistance for practical purposes? Doing a physics experiment where we are required to calculate the acceleration from gravity, for a simple high school assignment. And as part of an extended discussion, I would like to take into account air resistance aswell.
But looking into the formula, I notice that there are a lot of variables included in it. Such as drag coefficient, rho, velocity, and area.
Which are the best values to assume for these variables if I want to get an average value for the effect of air resistance on gravity?
Context: Dropping a 1.5cm diameter marble from a ceiling onto floor, in a room of about 20 degrees Celcius. And the main aim is to calculate the gravity of earth using the constant acceleration formula. All I need this air resistance value for is to manipulate the equation of acceleration to get it closer to the value of 10m/s^2, constant of gravity.
Formula I'm talking about:  Cd * .5 * rho * V^2 * A
Also what does the velocity part in the formula mean? The initial velocity, the final velocity of the marble?

A: Since this was a "simple school assignment", taking air resistance into account is probably not appropriate. If the drop height was only a few meters, the effect of air resistance on a marble is unlikely to make a significant impact on your results. (If the object was a ping pong ball, air resistance would be significant over a few metres.) Other errors in your method are likely to be much larger. There is no point making a correction for it. It might appear smart, but it is only smart when the correction is significant.
It is much more useful to investigate the real errors in your experiment, which are likely to be due to timing.
The article When does air resistance become significant in free fall (The Physics Teacher, AAPT 2011) concludes :

... Blaming air resistance for errors in free‐fall experiments in introductory physics laboratories is almost never justified.

Rather than try to apply a correction (which is not straightforward - see below) you could do a calculation to show that air resistance is much smaller than the gravity force on the marble. You have the correct formula. You can measure cross-sectional area $A=\pi r^2$. You can estimate the final velocity $v=\sqrt{2gh}$ when air resistance is greatest. And you can look up values for air density $\rho$ at 20C and drag coefficient for a sphere.

The velocity used in the formula is instantaneous velocity. In your experiment the velocity is continuously increasing so the air resistance is continuously increasing hence also the deceleration it causes. Worse still, if air resistance is significant then you cannot know what the velocity will be until you have taken air resistance into account - a kind of Catch 22 situation. You would need to solve a differential equation - perhaps numerically - in order to find what the fall time would be with air resistance. However, you can get an over-estimate of the effect by using the final velocity.


text:
Q: Add html with jquery/javascript I have made a agenda system with weeks but I want an option that can make the user add as much weeks as he wants
html

Agenda

WEEK 1

Hier staat meer informatie. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore

et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        <form>
          <input class="stop" type="text">
          <input id="btnsubmit" class="stop" type="submit"></input>
        </form>

WEEK 2

Hier staat meer informatie. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

WEEK 3

Hier staat meer informatie. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

for jquery I have
  $(document).ready(function() {
    $(".balkje").on("click", function(event) {
      $(this).stop(true, true).toggleClass('open dicht', 250);
    });

    $(".stop").on("click", function(event){
        event.stopPropagation();
    });
  })

css
http://pastebin.com/17UEgk4b
now I was wondering if it's possible to make an input field as example add 2 weeks en then instead of 3 weeks there would be 5
thanks

A: You need to modify a bit your html to this :

Agenda

<form id="addWeek" action="#">
    <input class="stop" type="text"/>
    <input id="btnsubmit" class="stop" type="submit"/>
</form>

WEEK 1

Hier staat meer informatie. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore

et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

WEEK 2

Hier staat meer informatie. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

and put some JQuery :
$("#addWeek").submit(function() {
    var iter = $(this).find(".stop").val();
    for (var i = 0; i < iter; i++) {
        $("#weeks").append("
\

WEEK
\

\

Hier staat meer informatie. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore

\

et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

\

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

\

\

");
    }
});

DEMO JSFiddle


text:
Q: Wifi connection dropping and/or slow after upgrading to 14.10 I just recently upgraded from 14.04 to 14.10 and immediately started having issues with the wifi on my Dell XPS 13 laptop.  It'll work fine for a while (something like 30 min to an hour?) but then the connection starts to go slow (packet loss 25% to 75%) and then it eventually stops.  Sometimes it comes back on its own but most times I have to toggle the hardware wifi button (fn + F2).
When filtering logged messages for iwlwifi, seeing a possible error message fail to flush all tx fifo queues Q 0 and multiple messages for Q 4 is inactive and mapped to fifo 0 ra_tid:
$ dmesg | grep iwl
[ 9802.709772] iwlwifi 0000:02:00.0: fail to flush all tx fifo queues Q 0
[ 9802.709778] iwlwifi 0000:02:00.0: Current SW read_ptr 81 write_ptr 84
[ 9802.709813] iwl data: 00000000: 00 00 0e 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[ 9802.709835] iwlwifi 0000:02:00.0: FH TRBs(0) = 0x80003052
[ 9802.709856] iwlwifi 0000:02:00.0: FH TRBs(1) = 0x801020a1
[ 9802.709868] iwlwifi 0000:02:00.0: FH TRBs(2) = 0x00000000
[ 9802.709881] iwlwifi 0000:02:00.0: FH TRBs(3) = 0x80300053
[ 9802.709893] iwlwifi 0000:02:00.0: FH TRBs(4) = 0x00000000
[ 9802.709907] iwlwifi 0000:02:00.0: FH TRBs(5) = 0x00000000
[ 9802.709921] iwlwifi 0000:02:00.0: FH TRBs(6) = 0x00000000
[ 9802.709933] iwlwifi 0000:02:00.0: FH TRBs(7) = 0x007090ef
[ 9802.709982] iwlwifi 0000:02:00.0: Q 0 is active and mapped to fifo 3 ra_tid 0x0000 [81,84]
[ 9802.710031] iwlwifi 0000:02:00.0: Q 1 is active and mapped to fifo 2 ra_tid 0x0000 [0,0]
[ 9802.710080] iwlwifi 0000:02:00.0: Q 2 is active and mapped to fifo 1 ra_tid 0x0000 [146,199]
[ 9802.710128] iwlwifi 0000:02:00.0: Q 3 is active and mapped to fifo 0 ra_tid 0x0000 [83,83]
[ 9802.710177] iwlwifi 0000:02:00.0: Q 4 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710226] iwlwifi 0000:02:00.0: Q 5 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710274] iwlwifi 0000:02:00.0: Q 6 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710323] iwlwifi 0000:02:00.0: Q 7 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710371] iwlwifi 0000:02:00.0: Q 8 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710420] iwlwifi 0000:02:00.0: Q 9 is active and mapped to fifo 7 ra_tid 0x0000 [240,240]
[ 9802.710469] iwlwifi 0000:02:00.0: Q 10 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710517] iwlwifi 0000:02:00.0: Q 11 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710566] iwlwifi 0000:02:00.0: Q 12 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710614] iwlwifi 0000:02:00.0: Q 13 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710663] iwlwifi 0000:02:00.0: Q 14 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710712] iwlwifi 0000:02:00.0: Q 15 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710761] iwlwifi 0000:02:00.0: Q 16 is inactive and mapped to fifo 1 ra_tid 0x0000 [63,63]
[ 9802.710809] iwlwifi 0000:02:00.0: Q 17 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710858] iwlwifi 0000:02:00.0: Q 18 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]
[ 9802.710906] iwlwifi 0000:02:00.0: Q 19 is inactive and mapped to fifo 0 ra_tid 0x0000 [0,0]

Some more info about my machine:
$ uname -a
Linux 3.16.0-25-generic #33-Ubuntu SMP Tue Nov 4 12:06:54 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
$ uname -r
3.16.0-25-generic

$ lspci -nn | grep 0280
02:00.0 Network controller [0280]: Intel Corporation Wireless 7260 [8086:08b1] (rev 6b)

Not sure why having these issues now (Never had problems in the past when doing any release upgrades particularly with wifi)
Perhaps it thinks the laptop is idle/standby when it's not? I confirmed that the Power Management setting is off.
Not certain but seems to happen more frequently when using VPN.
Any thoughts? Suggestions?

A: It seems a patch has been made to the kernel 3.16 to fix this wifi issue:
Bug 56581 - iwlwifi iwldvm fail to flush Tx queue
and is also being tracked as/linked to an Ubuntu bug:
iwlwifi 0000:01:00.0: fail to flush all tx fifo queues Q 2
but as of 11/11/2014 has not been yet been released as part of an Ubuntu update:

Seth Forshee (sforshee) wrote on 2014-11-11:  #14
The patch hasn't made it through to the released Ubuntu kernels yet.
  I'll check on the status and try to accelerate the process if needed,
  but it always takes several weeks for updates to get released due to
  the amount of regression testing new kernels are subjected to before
  they are released.

but it's planned to be

Seth Forshee (sforshee) wrote on 2014-11-11:  #17
I checked, and the patch is already queued for both trusty and utopic
  in the next SRU cycle. This means that it won't be in the next kernel
  update, but the one after that. The next update is already undergoing
  regression testing so it is too late to get it in for the next kernel
  update.

Unfortunately, I had to re-install the previous version of Ubuntu 14.04 LTS (from 14.10) on my machine which resolved the issue with the wifi back to working as expected.  I plan to hold off upgrading until this bug has been fixed and released.


text:
Q: How can I resolve the "Didn't find class 'com.google.android.gms.auth.GoogleAuthUtil'" error? I am trying to use the Google Calendar API for the first time in Android Studio, and this class is crashing once it gets to the
mService.events().insert("primary", event).execute();

line.
The error say
"Didn't find class "com.google.android.gms.auth.GoogleAuthUtil" on path: DexPathList"

    public class CalendarRequestTask extends AsyncTask<Task, Void, Boolean> {
    private com.google.api.services.calendar.Calendar mService = null;
    private Exception mLastError = null;

    public CalendarRequestTask(GoogleAccountCredential credential) {
        HttpTransport transport = AndroidHttp.newCompatibleTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        mService = new com.google.api.services.calendar.Calendar.Builder(
                transport, jsonFactory, credential)
                .setApplicationName("Task Tracker")
                .build();
    }

    /**
     * Background task to call Google Calendar API.
     * @tasks has the date, title, summary of the event.
     */
    @Override
    protected Boolean doInBackground(Task... tasks) {
        try {
            setEventInApi(tasks);
            return true;
        } catch (Exception e) {
            mLastError = e;
            cancel(true);
            return false;
        }
    }

    private void setEventInApi(Task... tasks) throws IOException {
        // Insert an event into the Google Calendar

        for (Task task: tasks) {
            Event event = new Event()
                    .setSummary(task.getTitle())
                    .setDescription(task.getDescription());
            DateTime startTime = new DateTime(task.getDueDate());
            EventDateTime start = new EventDateTime()
                    .setDateTime(startTime);
            event.setStart(start);
            mService.events().insert("primary", event).execute();
        }
    }
}

A: I solved it.
Add the following in app build.gradle (Module:app)
dependencies{
..
compile 'com.google.android.gms:play-services-auth:9.0.2'
}

Add the following in project build.gradle (Project:ProjectName)
dependencies {
classpath 'com.google.gms:google-services:1.5.0'
}

Clean and Rebuild.


text:
Q: Entity Data Model Parent Child relationship in Visual Studio 2012 I have just upgraded to Visual Studio 2012, I created an entity data model, I was suprised that this was not immediately available in Data Sources, So I added it as an object, is this correct?
Secondly, I did the above and then dragged 2 data grids (which have a parent / child relationship ) onto my WPF window, there is no data in either grid nor a relationship between the 2 grids (tables). The code that is generates is...
System.Windows.Data.CollectionViewSource countPartsEntitiesViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("countPartsEntitiesViewSource")));
            // Load data by setting the CollectionViewSource.Source property:
            // countPartsEntitiesViewSource.Source = [generic data source]

Visual Studio 2010 provided data in both tables and the parent child link.
Am I missing something?


text:
Q: Using std::transform and tr1::bind to transform a vector of std::complex Given a std::vector of std::complex, I would like to transform it to a vector containing only the real part of the complex, divided by some constant coefficient.
Right now, I do that:
std::vector<std::complex<double> > vec;
std::vector<double> realVec;
double norm = 2.0;
...
for (std::vector<std::complex<double> >::iterator it = vec.begin(), itEnd = vec.end(); it != itEnd; ++it)
    realVec.push_back((*it).real() / norm);

This works fine of course, but I am looking for a way to use std::transform to do the same thing. I tried:
transform(vec.begin(), vec.end(), back_inserter(realVec), tr1::bind(divides<double>(), tr1::bind(&complex<double>::real, tr1::placeholders::_1), norm));

But it won't work. I have this error:
erreur: no matching function for call to 'bind(<unresolved overloaded function type>, std::tr1::_Placeholder<1>&)'|

I don't understand why there is a "unresolved overloaded function type".
Could someone explain to me what is wrong?

A: Unfortunately, you can't do this, at least not directly.  The types of Standard Library member functions (like complex<double>::real) are left unspecified, so an implementation may provide additional overloads and the functions that are there may have additional parameters with default arguments.
In effect, there is no portable way to take the address of a Standard Library member function.
Your best bet would be to write a helper function:
template <typename T>
T get_real(const std::complex<T>& c) { return c.real(); }

and bind to that:
std::tr1::bind(&get_real<double>, std::tr1::placeholders::_1)

A: std::complex<>::real() is overloaded (cf. C++11 [complex]).
template <typename T>
class complex {
    // ...
    T real() const; // getter
    void real( T ); // setter
    // ...
};

C++ requires a disambiguation when you take the address of an overloaded function. In your case, you have to say:
tr1::bind( static_cast<double(std::complex<double>::*)()const>( &std::complex<double>::real ),
           tr1::placeholders::_1 )

Yes, this is ugly.


text:
Q: Could not reserve enough space for object heap - Alfresco build from source I am trying to build Alfresco from source and I am following the instructions from this link. But whenever I try to execute below command:
ant build-tomcat

I am getting below error:
[mkdir] Created dir: E:\Pradeep\Alfresco\Alfresco   Source\root\projects\core\build\classes
[javac] Compiling 159 source files to E:\Pradeep\Alfresco\Alfresco   Source\root\projects\core\build\classes
[javac] Error occurred during initialization of VM
[javac] Error: Could not create the Java Virtual Machine.
[javac] Error: A fatal exception has occurred. Program will exit.
[javac] Could not reserve enough space for object heap

I tried setting heap size using following environment variable:
JAVA_OPTS = -Xms256m -Xmx512m

I played with various values like 1333M, 1024M, 64M etc. But still I get same error. As an alternative I tried to execute using maven also by mvn clean install, but even that won't run, I get following error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.16:test (default-test) on project alfresco-core: Execution default-test of goal org.apache.ma
  erminated without saying properly goodbye. VM crash or System.exit called ?

Edit: For Maven surefire plugin, this is the memory configuration I have:

-Xmx2G -XX:MaxPermSize=256m -Duser.language=en -Dcom.sun.management.jmxremote

My system configuration is: Windows 7 32 Bit, Dual Core, 4GB RAM.
Can anyone kindly help me how do I resolve this error?

A: Try increasing heap size for maven build by
export MAVEN_OPTS="-Xmx1500m"


text:
Q: PyQt5 GUI can't be close from Spyder I am trying to create a simple GUI using PyQt5. I am running my code in windows 10 from Spyder(Anaconda latest version, python 3.7). Here is my code:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button test'
        self.left = 50
        self.top = 50
        self.width = 720
        self.height = 800
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100,70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):
        print('PyQt5 button click')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    app.exec_()

A window pop up. Now if I close the GUI by clicking on closing button(top right corner of the GUI),Spyder IP console does not return to normal condition. It freezes. What should I use in code to solve the issue?
Thanks,
Moni

A: Closing the window doesn't appear to close the QApplication object. To do this, override the closeEvent function of the main window by adding these two lines after the on_Click definition
  def closeEvent(self,event):
     QApplication.quit()

This will close the window and the QApplication object as well and control should return to the console

A: You can try and look at the answer in the following thread:
Can't Kill PyQT Window after closing it. Which requires me to restart the kernal
Seems to have resemblance to your problem and a solution.


text:
Q: Python: Iterate through YAML file and output all relevant settings from hierarchy I'm new to python and am looking for the best way to import a YAML file into Python and iterate through it to collect relevant appsettings for a specific instance of an app.
For example this YAML structure:
UAT:
    Configuration:
    #config relevant to all servers on UAT
    - appSettings:
        AWSAccessKey: ExampleKey
        AWSSecretKey: ExampleSecret
        AWSRegion: ExampleRegion
    Servers:
    - Server1:
        #config relevant to all apps on UAT>Server1
        Configuration:
        - appSettings:
            Key1: true
            Key2: '123'
        Apps:
        - Engine1:
            #config relevant to all Apps of type UAT>Server1>Engine1
            version: 1.2
            appSettings:
                Key3: 'abc'
                Key4: 'def'
                Key5: 'abc-123'
            Instance:
            - Instance1:
                path: 'examplepath'
                appSettings:
                    Key6: 'A1B1C1'
                    Key7: true
            - Instance2:
                appSettings:
                    Key6: 'A2B2C2'
                    Key7: false
            - Instance3:
                appSettings:
                    Key6: 'A3B3C3'
                    Key7: true
        - Engine2:
            version: 'example'
            appSettings: 'example'
        - Engine3:
            path: 'example'
            version: 'example'
            appSettings:
    - Server2:
        Configuration:
        - AppSettings:
            Apps:
            - App1:
                Instance:
                - Instance1: 'example'
                - Instance2: 'example'
    - Server3: 'example'

I would like to be able to digest this and for example get all the relevant appsettings for Instance3 of Engine1 on Server1 on UAT. The expected output for UAT>Server1>Engine1>Instance3 would be:
        AWSAccessKey: ExampleKey
        AWSSecretKey: ExampleSecret
        AWSRegion: ExampleRegion
            Key1: true
            Key2: '123'
                Key3: 'abc'
                Key4: 'def'
                Key5: 'abc-123'
                    Key6: 'A3B3C3'
                    Key7: true

I'm not concerned with the formatting of the outcome I would just like to be able to spit out all the relevant key value pairs.
As  a start I have imported the YAML file as a dictionary and been able to output all of the app settings but cannot work out how to specify the specific level I would like to stop at.
import sys
from pathlib import Path
import ruamel.yaml

in_file = Path('Example.yml')

yaml = ruamel.yaml.YAML()
data = yaml.load(in_file)

def lookup(sk, d, path=[]):
   # lookup the values for key(s) sk return as list the tuple (path to the value, value)
   if isinstance(d, dict):
       for k, v in d.items():
           if k == sk:
               yield (path + [k], v)
           for res in lookup(sk, v, path + [k]):
               yield res
   elif isinstance(d, list):
       for item in d:
           for res in lookup(sk, item, path + [item]):
               yield res

for path, value in lookup("appSettings", data):
   print(value)

Looking further into this I am not sure if a matrix/array would be better than a dictionary as this maintains the order? Any help with this would be MUCH appreciated

A: I don't think there is a particular YAML format that would work better, this often
has to do with what you want to be together. Given a particular structure that
has some regularity (like yours) you should be able to get out of it what you want.
However you don't load this YAML into a dictionary. You load this, and the toplevel mapping is
created as a Python dictionary.
In order to reach your target Instance3, you would use:
data['UAT']['Servers'][0]['Server1']['Apps'][0]['Engine1']['Instance'][2]['Instance3']

You simply leave out all the list/sequence indexes by changing your lookup, but
you cannot easily ignore intermediate keys when matching the path UAT>Server1>Engine1>Instance3 (
it would be easier to look for
UAT>Servers>Server1>Apps>Engine1>Instance>Instance3
instead). But you seem to want to
skip adding a key to your path if the value for that key is a sequence/list.
Once you do that you can match your "current path" to your path to match, of course
only for the length you have gathered so far:
import sys
from pathlib import Path
import ruamel.yaml

in_file = Path('input.yaml')
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
data = yaml.load(in_file)

def lookup(d, sk, target, path=None):
    if path is None:
        path = []
    if target[:len(path)] != path:
        return
    if isinstance(d, dict):
        for k, v in d.items():
            if k == sk:
                if isinstance(v, dict):
                    for k1, v1 in v.items():
                        yield path + [k1], v1
                else:
                    yield path, v  # there is an appSetting that doesn't have a dict as value
            newpath = path[:] if isinstance(v, list) else path + [k]
            for res in lookup(v, sk, target, newpath):
                yield res
    elif isinstance(d, list):
        for item in d:
            for res in lookup(item, sk, target, path[:]):  # don't add item to path here, but still need a copy
                yield res

target = 'UAT>Server1>Engine1>Instance3'.split('>')
dout = {key[-1]: value for key, value in lookup(data, sk='appSettings', target=target)}
yaml.dump(dout, sys.stdout)

which gives:
AWSAccessKey: ExampleKey
AWSSecretKey: ExampleSecret
AWSRegion: ExampleRegion
Key1: true
Key2: '123'
Key3: 'abc'
Key4: 'def'
Key5: 'abc-123'
Key6: 'A3B3C3'
Key7: true


text:
Q: Change each symbol excluding variables in bash using sed & regex I need to change string like
Example \%^ $variable ${array[$element]}
Into string like
\E\x\a\m\p\l\e\ \\\%\^\ $variable\ ${array[$element]}
So, I need to escape EACH symbol except for variables in those 2 cases.
Also, and this is tricky, I need to escape them twice, so that the result will be achieved by using command:
string='Example \%^ $variable ${array[$element]}'
echo `echo $string | sed 'MAGIC'
Also, I have achieved escaping ALL the characters:
echo $(echo $string | sed -r -e 's/(.)/\\\\\1/g')
So, the question is how to NOT escape $variables?
I am pretty good at regex, so just working example will suffice. But any explanations are welcome. Also, I'll post the answer here if I'd find it faster than any of you. I think it's an interesting puzzle to solve :)

A: If you can use perl then it can be done easily like this:
s='Example \%^ $variable"abc" ${array[$element]} ${var}this'
perl -pe 's/\$(?:{.*?}|\w+)(*SKIP)(*F)|(.)/\\$1/g' <<< "$s"

Output:
\E\x\a\m\p\l\e\ \\\%\^\ $variable\"\a\b\c\"\ ${array[$element]}\ ${var}\t\h\i\s

RegEx Demo

Update: Here is how this can be done using gnu-awk:
awk -v RS='\\$({.*?}|[[:alnum:]_]+)' '{gsub(/./, "\\\\&"); printf "%s%s", $0, RT}' <<< "$s"
\E\x\a\m\p\l\e\ \\\%\^\ $variable\"\a\b\c\"\ ${array[$element]} ${var}\t\h\i\s\


text:
Q: Triggering a paragraph in Apache Zeppelin using z.run() I am having some problems with Apache Zeppelin and I am not sure what I am missing, basically
I am trying to trigger a paragraph from another paragraph in Apache Zeppelin using z.run. When I run the paragraph with z.run I get no error, but the paragraph I specified is also not run. On the other hand, if I enter the wrong paragraphID on purpose, I get an error that this paragraph doesn't exit.
I have tried using z.runParagraph, z.run with spark and z.z.run with pyspark. However, when I copy the code from here angular_frontend.html
I am able to run another paragraph when filling in the paragraphID and clicking  "run paragraph".
What I am trying is the following:
%spark
z.run("paragraphID")

%pyspark
print("Hello World")

I expect the "Hello World" will be printed, but it is not.


text:
Q: Does any well-known license require to make modifications available when only derived *output* is published? Is there a way to make sure that modifications to free software are released even when no binaries of modified code are conveyed? Though it may sound odd and from what I understand, e.g., GPL requires to distribute source only if binary is conveyed to other parties thus making it possible for unlimited private use as it does not fall into propagation.
I would like to make sure that if someone publishes a final finding in a scientific literature derived with the aim of a modified code, then those modifications are made available.
Does any well-known license have these provisions? If not, why would it be bad? From what I understand if I add those provisions explicitly, it would limit the freedom, e.g., rendering result non-GPLish.
From one of the answers that disappeared, I guess I can add an Additional Term but would not it be a further restriction that can be simply ignored

If the Program as you received it, or any part of it, contains a
  notice stating that it is governed by this License along with a term
  that is a further restriction, you may remove that term.

From what I understand it looks like it depends on how I state it. If I require to make private modification used to derived a result that was published to make available, then it would be okay, otherwise it would be a further restriction if I prohibit from privately using and not making modified code available.
Example
A implements a super duper algorithm but they is bad with BLAS and it takes a long time for the simulation. B claims that they refined the code using CUDA or whatever and can easily get results within second. Based on their work they found this and that from simulations and got it published. And that is it. No GPL violation and no better code for community.
Another example
Imagine if some animation studio took Blender, implemented an improved version of Cycles that allows them to render things way faster and with less problems. So now they have an advantage as they can deliver animations to clients faster. No software conveyance, no GPL violation, no improvements sharing.

A: I'm no lawyer, but this seems quite difficult. Let's begin at the GPL FAQ on program output. The particular question is not exactly what you ask in your question, but the answer is perfectly relevant:

Is there some way that I can GPL the output people get from use of my program? For example, if my program is used to develop hardware designs, can I require that these designs must be free?
In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert his own data, the copyright on the output belongs to him, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.
So the only way you have a say in the use of the output is if substantial parts of the output are copied (more or less) from text in your program. For instance, part of the output of Bison (see above) would be covered by the GNU GPL, if we had not made an exception in this specific case.

So, it varies from domain to domain, but generally, you cannot impose conditions on the output of software using only a license on that software itself. Instead, you'll need to force the user to enter into a contract with you that imposes restrictions on future works that they create using your software, even if those works are not direct derivatives of your software. I'm not sure of the legal intricacies involves there (so talk to a lawyer), but I know that, personally, if I wanted to use software that required an agreement to allow someone else to control creative works that I'd not yet created, I'd stay far away from that software.
Note that the Affero GPL handles a small subset of this case: when no binary is transferred but the program is used over a network, each user must be given access to the source.

A: The simplest way is to modify one of the major licenses (eg GPL) to do that. I took a quick glance at it and very little discusses conveyed works. The modifications would be few. I'd advise getting skilled help on the legal language though. Here's a few ideas for you:

*

*Pay a lawyer to do it.

*Pay less to a top notch college law student (who already knows contracts) to do it.

*Pay less to someone who knows contracts in and out, often handling them professionally, but isn't an expensive lawyer.

For the non-lawyers, you might give them incentive of buying them a really good lunch and/or mentioning it's an unusual thing they might like. Modifying the number one FOSS license is probably more interesting than the average homework assignment for many law students. ;)


text:
Q: Conditional show text block in .docx using OpenTBS based on variable value In my project I use TinyButStrong / OpenTBS to generate Word documents from templates. First I load a variable like myuser in the document.
[onload;tplvars;myuser=user]

The document is provided with the required variables, so I can add tags like this where the name is placed on the variable:
Hello [myuser.firstName]!

Also conditional values work fine:
[onshow;block=tbs:p;when [myuser.firstName]='John'] This is a paragraph just for John.

But when I have multiple paragraphs that I want to show/hide, it's not easy to select the correct paragraphs (or change the template and add a paragraph). Is it possible to create blocks that have a 'begin' and 'end' that are shown based on a value? Something like this (pseudocode):
Paragraph 1
[if [myuser.firstName] = 'John']
    (insert random number of paragraphs and maybe tables/other stuff here)
[end if]
Paragraph n

I could not find any of this in the TBS/OpenTBS docs. Does someone know a method to do this?
Thanks!
Niels

A: TBS has a block syntax [onshow;block=being]...[onshow;block=end] but it's a bad practice with OpenTBS because in fact in the inner XML those two tags are placed in a two separated <w:p> entities. So those entities will be split in two and it's a luck if they match with the newly merged contents.
One solution is to protect the begin/end tags with a paragraph entity.
[onshow;block=begin;enlarge=tbs:p;when ....] This paragraph will be deleted
Some text here.
Some text there.
[onshow;block=end;enlarge=tbs:p] This paragraph will be deleted

Another solution is to define a block on several paragraphs:
This block is defined on 3 paragraphs:
[onshow;block=tbs:p+tbs:p+tbs:p;when ...] Paragraph 1 - inside the block
Paragraph 2 - inside  the block
Paragraph 3 - inside  the block
Paragraph 4 - outside the block

The other solution is


text:
Q: How to draw checkbox onto message box in hook procedure? I am making a custom message box in Win32 api. So, I created the hook procedure and things, following the tutorial from here.
I successfully changed the button text, but, when I draw a checkbox onto the message box, and I press one of the messagebox buttons, the checkbox gets drawn onto the main window!
My code:
typedef void (*mbxdraw)(HWND);
static HHOOK hMsgHk;        // internal linkage; local to this file
static mbxdraw drawproc;    // internal linkage

LRESULT CALLBACK CBTProc(int nCode, WPARAM wp, LPARAM lp)
{
    HWND hwndMsgbx;
    if (nCode < 0)
        return CallNextHookEx(hMsgHk, nCode, wp, lp);
    switch (nCode) {
    case HCBT_ACTIVATE:
        // obtain the message box handle
        hwndMsgbx = (HWND) wp;
        drawproc(hwndMsgbx);    // calls function pointer
        return 0;
    }
    return CallNextHookEx(hMsgHk, nCode, wp, lp);
}

int msgbox(HWND hOwner, char *text, char *cap, UINT flags, mbxdraw md)
{
    int ret;

    hMsgHk = SetWindowsHookEx(WH_CBT, CBTProc, NULL, GetCurrentThreadId());

    drawproc = md;

    ret = MessageBox(hOwner, text, cap, flags);

    UnhookWindowsHookEx(hMsgHk);
    return ret;
}

In the function that I pass (main.cpp):
void draw(HWND hMsg)
{
    // this is the checkbox:
    CreateWindow("BUTTON", "Check", WS_CHILD | WS_VISIBLE | BS_CHECKBOX,
                 10, 70, 65, 10, hMsg, (HMENU) CHKID, GetModuleHandle(NULL), NULL);
    SetWindowText(GetDlgItem(hMsg, IDYES), "Save Changes");
}

The checkbox gets drawn onto the main window as soon as I press one of the two buttons on the message box. It even gets drawn with the same exact X- and Y- coordinates, and the same width, and height and text.
I thought maybe I was obtaining the message box handle the wrong way, but I saw that the address of the message box handle was not equal to the handle of the main window.
The reason I am passing the function pointer rather than just writing the code,  is because later, when this will actually work, I will put this in a c++ wrapper class.

A: Your code embodies the wrong approach. You want to make a native message dialog with a check box. The TaskDialogIndirect is provided for that purpose.
Your approach, even if you fix it, it not robust to changes in implementation in future Windows releases. Use the system provided API.

A: It works if I test it in this simple program:
#include <windows.h>
#include <stdio.h>

#pragma comment(lib,"user32.lib")

#define CHKID 100

typedef void (*mbxdraw)(HWND);
static HHOOK hMsgHk;        // internal linkage; local to this file
static mbxdraw drawproc;    // internal linkage

LRESULT CALLBACK CBTProc(int nCode, WPARAM wp, LPARAM lp)
{
    HWND hwndMsgbx;
    if (nCode < 0)
        return CallNextHookEx(hMsgHk, nCode, wp, lp);
    switch (nCode) {
    case HCBT_ACTIVATE:
        // obtain the message box handle
        hwndMsgbx = (HWND) wp;
        drawproc(hwndMsgbx);    // calls function pointer
        return 0;
    }
    return CallNextHookEx(hMsgHk, nCode, wp, lp);
}

void draw(HWND hMsg)
{
    // this is the checkbox:
    CreateWindow("BUTTON", "Check", WS_CHILD | WS_VISIBLE | BS_CHECKBOX,
                 10, 70, 65, 10, hMsg, (HMENU) CHKID, GetModuleHandle(NULL), NULL);
    SetWindowText(GetDlgItem(hMsg, IDYES), "Save Changes");
}

int msgbox(HWND hOwner, char *text, char *cap, UINT flags, mbxdraw md)
{
    int ret;

    hMsgHk = SetWindowsHookEx(WH_CBT, CBTProc, NULL, GetCurrentThreadId());

    drawproc = md;

    ret = MessageBox(hOwner, text, cap, flags);

    UnhookWindowsHookEx(hMsgHk);
    return ret;
}

int main(int argc, char *argv[])
{

    msgbox(NULL, "The quick brown fox jumps over the lazy dog", "The brown fox", MB_YESNO, draw);
    Sleep(2000);
    return 0;
}

Maybe you create some other window in the same thread before to remove the hook?


text:
Q: Don't resolve DNS wildcards for a domain on local network I've set up a local Mageia Linux server as a gateway, with local DHCP dhcpd and DNS bind9 servers.
The DNS server is also used for a domain name domain.tld, which has a wildcard A/AAAA record.
But I wanted to be able to access all my computers at .domain.tld, that's why I configured a DDNS with dhcpd and bind9, and a domain-search set to "domain.tld".
It works as it should : when I try to resolve a domain name with no tld, it automatically searches it as a subdomain of domain.tld, and since the wildcard catches all subdomains, it'll always find a record and point to domain.tld.
Now the problem is this one : I would like the wildcard to doesn't resolve on the local network br0 but only on wan0, to be able to send a random request and get a domain not found error, instead of it being resolved as domain.tld. This actually causes a problem for people who just type "foobar" in their browser's address bar, because instead of being redirected to their preffered search engine, they're redirected to domain.tld.
Or even better, to only resolve the wildcard when it is accessed by domain.tld directly, but since domain-search is used client side, I don't think it's possible.
Thanks in advance.
PS: I'm sorry for my bad english.

A: Without knowing additional details, what you are seeking is the "view" feature.  Take a look at the following two links.  Pay attention to the "acl" and "view" statements.

*

*http://www.howtoforge.com/two_in_one_dns_bind9_views

*http://www.knowplace.org/pages/howtos/split_view_with_bind_9_howto.php
Hope this helps.
R/ Tim


text:
Q: Could not load file or assembly System.ComponentModel.Annotations, Version=4.2.0.0 I realise this question has been asked, but I have tried all of the suggested solutions I can find.
I have a Load Testing project (with a .loadtest file and class that inherits from Microsoft.VisualStudio.TestTools.WebTesting.WebTest). It has to target the .Net Framework (version 4.6.1) as opposed to .Net Core.
It references a project that targets .Net Standard 2.0, and both the load project and the .Net Standard project have the System.ComponentModel.Annotations (version 4.5.0) Nuget packages added.
When I try to run the Load Test itself, I receive the following exception:
System.IO.FileNotFoundException
  Message=Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I have tried adding an app.config file to the Load Test project with a binding redirect in, but it made no difference to the exception.
I can't move down to version 4.4.1 of the NuGet package, because other projects elsewhere depend on it being version 4.5.
I have read that there is a problem with the versioning in this package. And indeed when I inspect the dependencies of the built .Net Standard project dll, it seems to target not the 4.5.0 as specified, but version 4.2.0.0.

Now I am able to force the project to the proper version (which appears to be 4.2.1.0) by removing the NuGet package reference and adding a manual reference to the dll in the Packages folder, but then another project down the chain refuses to accept the hintPath I give it, and defaults to a different location and version:

So I can't force all projects I need to to use the actual version and location of the dll that I want.
Just wondering if anyone can suggest any course of action that might help here, as I'm at a bit of a loss as to how to force the whole thing to use the proper version. Either via binding redirects, or getting all projects to accept the paths to dlls that I'm giving them.

A: This also happened to me recently. I fixed this error by increasing .NET framework to target >= 4.7.2 and by setting AutoGenerateBindingRedirects, GenerateBindingRedirectsOutputType to true.
<PropertyGroup>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>

So if it is still relevant consider changing target framework.

A: I got the issue because i was using System.ComponentModel.Annotations on model project where i have used Attribute validation. This project is shared between ASP.NET API project as well as wpf porject. After updating System.COmponentModel.ANnotations to v4.7.0, it fixed the problem.

A: For anyone coming across this in the future, I did end up solving this via binding redirect in the end. A re-read of the github thread I linked to made me realise that there isn't actually technically a problem with the version numbers in the package, and that binding redirect was the "correct" solution.
So the actual problem I was having was that the Microsoft Load Testing framework doesn't load any app.config you add to the project, and instead uses a QTAgent_40.exe.Config file somewhere in the Program Files folder. So I had to resolve assemblies manually upon Load Test initialisation. This blog has the code to do it: http://macmillan.scot/post/visual-studio-web--load-tests-can%E2%80%99t-access-appconfig
But I modified the code a bit to include version checking:
public static void Resolve()
{
    LoadConfig();
    AppDomain.CurrentDomain.AssemblyResolve +=  delegate (object sender, ResolveEventArgs e)
    {
        var requestedName = new AssemblyName(e.Name);

        foreach (XmlNode assembly in assemblyBindingFromAppContext)
        {
            var assemblyIdentityNameNode = assembly.SelectSingleNode("./bindings:assemblyIdentity/@name", docNamepace);
            var bindingRedirectNewVersionNode = assembly.SelectSingleNode("./bindings:bindingRedirect/@newVersion", docNamepace);

            if (assemblyIdentityNameNode != null && bindingRedirectNewVersionNode != null)
            {
                var assemblyName = assemblyIdentityNameNode.Value;
                var specifiedVersion = bindingRedirectNewVersionNode.Value;

                if (string.Equals(requestedName.Name, assemblyName, StringComparison.OrdinalIgnoreCase))
                {
                    var resolvedAssembly = Assembly.LoadFrom(Invariant($"{assemblyName}.dll"));
                    var resolvedAssemblyVersion = resolvedAssembly.GetName().Version;

                    if (string.Equals(resolvedAssemblyVersion.ToString(), specifiedVersion, StringComparison.OrdinalIgnoreCase))
                    {
                        return resolvedAssembly;
                    }
                }
            }
        }

        return null;
    };
}

private static void LoadConfig()
{
    var configFileName = Path.Combine(Environment.CurrentDirectory, Invariant($"{Assembly.GetExecutingAssembly().ManifestModule.Name}.config"));
    var xmlDoc = new XmlDocument();
    xmlDoc.Load(configFileName);

    docNamepace = new XmlNamespaceManager(xmlDoc.NameTable);
    docNamepace.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1");

    if (xmlDoc.DocumentElement != null)
    {
        assemblyBindingFromAppContext = xmlDoc.DocumentElement.SelectNodes("//bindings:dependentAssembly", docNamepace);
    }
}


text:
Q: Why does my custom Swing component repaint faster when I move the mouse? (Java) I am trying to make a 2D game with Java and Swing, and the window refreshes too slow.  But if I move the mouse or press keys, the window refreshes as fast as it should!
Here is a GIF showing how the window refreshes quickly only when I move the mouse.

Why does the window refresh slowly like that?  Why does the mouse and keyboard affect its refresh rate?  How, if possible, do I make it refresh quickly all the time?
Background Info
I use a javax.swing.Timer to update the game state every 1/25 seconds, after which it calls repaint() on the game panel to redraw the scene.
I understand that a Timer might not always delay for exactly 1/25 of a second.
I also understand that calling repaint() just requests the window to be repainted ASAP and does not repaint the window immediately.
My graphics card does not support OpenGL 2+ or hardware accelerated 3D graphics, which is why I am not using libgdx or JME for game development.
System Info

*

*Operating system: Linux Mint 19 Tara

*JDK version: OpenJDK 11.0.4

*Graphics card: Intel Corporation 82945G/GZ

Research
This Stack Overflow user describes the same problem I have, but the author reportedly solved the issue by calling repaint() repeatedly on a separate timer.  I tried this, and it does make the window refresh somewhat faster, but even then it is a slower than I want.  In this case, wiggling the mouse on the window still improves the refresh rate.  Therefore, it seems like that post did not truly solve the issue.
Another Stack Overflow user also encountered the issue, but they use a continuous while-loop instead of a Timer for their game loop.  Apparently, this user solved the problem by using Thread.sleep() in their while loop.  However, my code accomplishes the delay using a Timer, so I do not know how Thread.sleep() could solve my problem, or even where I would put it.
I've read through Painting with AWT and Swing to figure out whether I just misunderstood the concept of repainting, but nothing in that document elucidates the issue for me.  I call repaint() whenever the game updates, and the window only refreshes quickly when mouse or keyboard input is happening.
I have searched the web for several days now trying to find an answer, but nothing seems to help!
Code
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

class Game {
        public static final int screenWidth = 160;
        public static final int screenHeight = 140;

        /**
         * Create and show the GUI.
         */
        private static void createAndShowGUI() {
                /* Create the GUI. */
                JFrame frame = new JFrame("Example");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setResizable(false);
                frame.getContentPane().add(new GamePanel());
                frame.pack();

                /* Show the GUI. */
                frame.setVisible(true);
        }

        /**
         * Run the game.
         *
         * @param args  the list of command-line arguments
         */
        public static void main(String[] args) {
                /* Schedule the GUI to be created on the EDT. */
                SwingUtilities.invokeLater(() -> createAndShowGUI());
        }

}

/**
 * A GamePanel widget updates and shows the game scene.
 */
class GamePanel extends JPanel {
        private Square square;

        /**
         * Create a game panel and start its update-and-draw cycle
         */
        public GamePanel() {
                super();

                /* Set the size of the game screen. */
                setPreferredSize(
                        new Dimension(
                                Game.screenWidth,
                                Game.screenHeight));

                /* Create the square in the game world. */
                square = new Square(0, 0, 32, 32, Square.Direction.LEFT);

                /* Update the scene every 40 milliseconds. */
                Timer timer = new Timer(40, (e) -> updateScene());
                timer.start();
        }

        /**
         * Paint the game scene using a graphics context.
         *
         * @param g  the graphics context
         */
        @Override
        protected void paintComponent(Graphics g) {
                super.paintComponent(g);

                /* Clear the screen. */
                g.setColor(Color.WHITE);
                g.fillRect(0, 0, Game.screenWidth, Game.screenHeight);

                /* Draw all objects in the scene. */
                square.draw(g);
        }

        /**
         * Update the game state.
         */
        private void updateScene() {
                /* Update all objects in the scene. */
                square.update();

                /* Request the scene to be repainted. */
                repaint();
        }

}

/**
 * A Square is a game object which looks like a square.
 */
class Square {
        public static enum Direction { LEFT, RIGHT };

        private int x;
        private int y;
        private int width;
        private int height;
        private Direction direction;

        /**
         * Create a square game object.
         *
         * @param x          the square's x position
         * @param y          the square's y position
         * @param width      the square's width (in pixels)
         * @param height     the square's height (in pixels)
         * @param direction  the square's direction of movement
         */
        public Square(int x,
                      int y,
                      int width,
                      int height,
                      Direction direction) {
                this.x = x;
                this.y = y;
                this.width = width;
                this.height = height;
                this.direction = direction;
        }

        /**
         * Draw the square using a graphics context.
         *
         * @param g  the graphics context
         */
        public void draw(Graphics g) {
                g.setColor(Color.RED);
                g.fillRect(x, y, width, height);
                g.setColor(Color.BLACK);
                g.drawRect(x, y, width, height);
        }

        /**
         * Update the square's state.
         *
         * The square slides horizontally
         * until it reaches the edge of the screen,
         * at which point it begins sliding in the
         * opposite direction.
         *
         * This should be called once per frame.
         */
        public void update() {
                if (direction == Direction.LEFT) {
                        x--;

                        if (x <= 0) {
                                direction = Direction.RIGHT;
                        }
                } else if (direction == Direction.RIGHT) {
                        x++;

                        if (x + width >= Game.screenWidth) {
                                direction = Direction.LEFT;
                        }
                }
        }
}

A: I guess you probably cannot solve your issue by enabling OpenGL, since your gpu does not support it, a possible silly workaround could be to fire a kind of event manually in each timer's iteration.
/* Update the scene every 40 milliseconds. */
final Robot robot = new Robot();
Timer timer = new Timer(40, (e) -> {
    robot.mouseRelease(0); //some event
    updateScene();
});
timer.start();

(And the only place you can Thread.sleep() in a Swing Application is inside a SwingWorker's doInBackground method. If you call it in EDT the whole GUI will freeze since events cannot take place.)

A: I ran into the same issue. The solution is quite simple. Call revalidate() immediately after you call repaint():
private void updateScene() {
            /* Update all objects in the scene. */
            square.update();

            /* Request the scene to be repainted. */
            repaint();

            revalidate(); // <-- this will now repaint as fast as you wanted it to
    }


text:
Q: Vuetify - CRUD operations on objects in Data Table Based on the desserts-example from Vuetify, I have added a new object to implement one-to-many relations on a data table:
ingredients:
    [
      {
        ingName: 'Yogurt',
        amount: 100,
        measure: 'gramm'
      },
      {
        ingName: 'Ice',
        amount: 50,
        measure: 'ml'
      }
    ]

The example is here:
https://codepen.io/rasenkantenstein/pen/MWYEvzK
I am having trouble to add a new or edit a given ingredient. I have added a new v-row (line 50):
 <v-row v-for="(ingredient, i) in editedItem.ingredients">

The text fields allow me to display the content. I can also edit it. But: The changes made on a given field are immediately visible even outside the v-dialog and even when clicking "Cancel", the changes are not omitted.
Also, when I add a new item and several ingredients on that, the empty arrays are not removed from editedItem.

A: So I figured it out. They keyword "Deep Copy" helped me here.
I changed
this.editedItem = Object.assign({}, item)

to
this.editedItem = JSON.parse(JSON.stringify( item ))

Some background I found here was also useful:
https://medium.com/@gamshan001/javascript-deep-copy-for-array-and-object-97e3d4bc401a


text:
Q: iconv in Mac OS X 10.7.3 does nothing I am trying to convert a php file (client.php) from utf-8 to iso-8859-1 and the following command does nothing on the file:

iconv -f UTF-8 -t ISO-8859-1 client.php

Upon execution the original file contents are displayed.
In fact, when I check for the file's encoding after executing iconv with:

file -I client.php

The same old utf-8 is shown:

client.php:           text/x-php; charset=utf-8

A: The iconv utility shall convert the encoding of characters in file from one codeset to another and write the results to standard output.
Here's a solution :
Write stdout to a temporary file and rename the temporary file
iconv -f UTF-8 -t ISO_8859-1 client.php > client_temp.php && mv -f client_temp.php client.php

A: ASCII, UTF-8 and ISO-8859 are 100% identical encodings for the lowest 128 characters. If your file only contains characters in that range (which is basically the set of characters you find on a common US English keyboard), there's no difference between these encodings.
My guess what's happening: A plain text file has no associated encoding meta data. You cannot know the encoding of a plain text file just by looking at it. What the file utility is doing is simply giving its best guess, and since there's no difference it prefers to tell you the file is UTF-8 encoded, which technically it may well be.

A: In addition to jackjr300 with the following One-Liner you can do it for all php files in the current folder:
for filename in *.php; do  iconv -f ISO_8859-1 -t UTF-8 $filename > temp_$filename && mv -f ./temp_$filename ./$filename; done