text:
Q: In scala 2, can macro or any language feature be used to rewrite the abstract type reification mechanism in all subclasses? How about scala 3? It is known in scala 2 that macros are strictly local and are only executed once, when the class is defined. This feature seems particularly weak when combining with abstract type, as the process to convert abstract types into concrete one generally bypasses macro and uses its own primitive rules.
One simple example that demonstrates a counter-intuitive outcome is in the following test code:
  trait BB {

    def ttag = implicitly[TypeTag[this.type]]
  }

  case class AA() extends BB

  it("can TypeTag") {

    val kk = AA()

    TypeViz(kk.ttag).peek // this function visualise the full type tree of the type tag
  }

if executed, the type of kk turns out to be:
-+ BB.this.type
 !-+ InfoCTSpec.this.BB
   !-+ Object
     !-- Any

Oops, the type AA is completely ignored, because implicitly[TypeTag[this.type]] is backed by a built-in macro implicit, which is only executed ONCE when BB is defined, not when AA is defined and reify the actual kk.this.type. I find it quite unwieldy and prone to cause some other features (e.g. pattern matching, type lambda) to degrade due to runtime type erasure.
I'd like to write/use a language extension to, e.g. make TypeTag[this.type] a subtype of AA, WITHOUT introducing runtime overhead & out-of-scope context objects (so, NO IMPLICIT). How can I do this with the least amount of hacking? I'm open to very hardcore solutions like compiler extension and macro, but an elegant work-around that can be smoothly carried over to scala 3/dotty is obviously preferred.
P.S. it appears that the dotty "inline/compiletime" feature has partially implemented what I have envisioned. Is this the correct impression?

A: You are free to write macros and compiler plugins but the conventional mechanism to postpone implicit resolution from definition site to call site is to replace implicitly with an implicit parameter
trait BB {
  def ttag(implicit tt: TypeTag[this.type]) = tt
}

When doing implicit resolution with type parameters, why does val placement matter?

WITHOUT introducing runtime overhead & out-of-scope context objects (so, NO IMPLICIT).

It's not clear why you want to avoid implicits. Implicits are resolved at compile time. If you replace this with macros or compiler plugins then anyway you'll kind of resolve implicits manually at compile time.

Alternatively you can postpone implicit resolution with a macro (this is like inlining in Scala 3)
import scala.language.experimental.macros
import scala.reflect.macros.whitebox

trait BB {
  def ttag: Any = macro Macros.ttagImpl
}

object Macros {
  def ttagImpl(c: whitebox.Context): c.Tree = {
    import c.universe._
    q"_root_.scala.Predef.implicitly[_root_.scala.reflect.runtime.universe.TypeTag[this.type]]"
  }
}

or
import scala.reflect.runtime.{universe => ru}

object Macros {
  def ttagImpl(c: whitebox.Context): c.Tree = {
    import c.universe._
    c.inferImplicitValue(appliedType(typeOf[ru.TypeTag[_]].typeConstructor, internal.thisType(c.internal.enclosingOwner.owner/*c.macroApplication.symbol*/)), silent = false)
  }
}

Implicit Json Formatter for value classes in Scala


text:
Q: Random Messages Not Being Handled in Rebus I have an odd issue with my implementation of Rebus which has been working for the past couple of years without any issue, and I am trying to figure out the scope of the problem and where to focus my troubleshooting effort. A little context:

*

*We have been running version 0.99.66

*Moved to version 3.1.5 last week, then saw the issues appear

*Rolled back to 0.99.66, issues continue

*Using MSMQ for the transport

*Running Windows Server 2016

*Identical code running on other server instances without issue

So, we are experiencing seemingly random instances where messages are failing, ending up in the error queue with a Rebus error saying that the message could not be dispatched to any handlers. This could happen once, but then when an identical message type comes through the next time, it gets handled correctly.
Here is a snippet of the code in question:
public class ProcessManagerService
{
    public ProcessManagerService()
    {
        ...

        BusAdapter = new BuiltinHandlerActivator();
        BusAdapter.Handle<FileEventMessage>(async msg => await StartProcess(msg));
        BusAdapter.Handle<ProcessRequest>(async msg => await StartProcess(msg));

        Bus = Configure.With(BusAdapter)
                .Logging(l => l.ColoredConsole(LogLevel.Error))
                .Transport(t => t.UseMsmq(ConfigurationManager.AppSettings["Queue"]))
                .Start();
    }

    ...

    public async Task StartProcess(FileEventMessage msg)
    {
        var svc = new StepManager() { FileEvent = msg.FileEvent };
        await svc.Run();
    }

    public async Task StartProcess(ProcessRequest msg)
    {
        var svc = new StepManager();
        await svc.Run(msg);
    }
}

And here is an example of the exception that is thrown:

5 unhandled exceptions: 12/18/2018 7:53:00 AM -06:00:
  Rebus.Exceptions.RebusApplicationException: Message with ID
  c72a8b6d-e31c-4a88-937e-612bf1db8b11 and type
  ClearStone.Messages.Monitoring.File.FileEventMessage,
  ClearStone.Messages could not be dispatched to any handlers    at
  Rebus.Pipeline.Receive.DispatchIncomingMessageStep.d__1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at Rebus.Sagas.LoadSagaDataStep.d__7.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Rebus.Pipeline.Receive.ActivateHandlersStep.d__3.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Rebus.Pipeline.Receive.DeserializeIncomingMessageStep.d__2.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Rebus.Pipeline.Receive.HandleDeferredMessagesStep.d__12.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Rebus.Retry.Simple.SimpleRetryStrategyStep.d__8.MoveNext()

UPDATE: Here is a more detailed stack trace after wiring in Rebus source:

5 unhandled exceptions: 12/20/2018 9:39:05 AM -06:00: Rebus.Exceptions.RebusApplicationException: Message with ID 84c3605a-41de-4300-9596-97e7288d2bcb and type ClearStone.Messages.Monitoring.File.FileEventMessage, ClearStone.Messages could not be dispatched to any handlers
     at Rebus.Pipeline.Receive.DispatchIncomingMessageStep.d__1.MoveNext() in C:\Temp\rebus_0_99_66_archive\Rebus\Pipeline\Receive\DispatchIncomingMessageStep.cs:line 61
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
     at Rebus.Sagas.LoadSagaDataStep.d__7.MoveNext() in C:\Temp\rebus_0_99_66_archive\Rebus\Sagas\LoadSagaDataStep.cs:line 77
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
     at Rebus.Pipeline.Receive.ActivateHandlersStep.d__3.MoveNext() in C:\Temp\rebus_0_99_66_archive\Rebus\Pipeline\Receive\ActivateHandlersStep.cs:line 48
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
     at Rebus.Pipeline.Receive.DeserializeIncomingMessageStep.d__2.MoveNext() in C:\Temp\rebus_0_99_66_archive\Rebus\Pipeline\Receive\DeserializeIncomingMessageStep.cs:line 36
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
     at Rebus.Pipeline.Receive.HandleDeferredMessagesStep.d__12.MoveNext() in C:\Temp\rebus_0_99_66_archive\Rebus\Pipeline\Receive\HandleDeferredMessagesStep.cs:line 114
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
     at Rebus.Retry.Simple.SimpleRetryStrategyStep.d__8.MoveNext() in C:\Temp\rebus_0_99_66_archive\Rebus\Retry\Simple\SimpleRetryStrategyStep.cs:line 105

Assuming the obvious and that it is something in this particular server instance/enviornment, I am trying to figure out why Rebus is behaving this way, and what in my environment may be causing this. Any direction as to where to start looking would be greatly appreciated!

A: Sounds pretty weird :) when people have this problem, it's almost always because they have somehow set up multiple Rebus instances to consume messages off of the same queue.
In some rare cases, it's because .Start() is called on the bus before handlers are added to the container/built-in handler activator, but that doesn't seem to be the problem in your case.
Can you tell me more about your setup? If it's about as simple as what you're showing above, maybe you can reproduce it in a separate application?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python image analysis - Check whether picture matches video frames I have a problem, not so easy to solve i guess. In general, I have a database of frames from different videos and I want to find for a given picture (which is not necessarily one of the frames but from some same source video) the matching source video.
So lets say I have some videos and extracted frames each x seconds. The frames are stored in the db.
My guess would now be to loop over all video frames in the db and try to find matching features. So I would somehow have to find features in the source image and then try to find these in the frames stored in the db.
My question is how can I achieve this? The problem is that camera angle and vieweing distance can be quite different when the picture in question was not taken quite close to the time the frame was extracted previously.
Is this even feasible?
I'm working with Python and OpenCV.
Thanks and best regards


text:
Q: Route from netns through a veth link I have created a network namespace (with ip netns add) and a pair of veth links, virt-a and virt-b. The physical link in the root namespace is named eth0. virt-a is in the root namespace and virt-b is in the newly created one.
IP addresses:
eth0:   192.168.1.100/24
virt-a: 192.168.1.101/24
virt-b: 192.168.1.102/24

Routing table in the root namespace:
default via 192.168.1.1 dev eth0
192.168.1.102 dev virt-a proto kernel scope link src 192.168.1.101
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.100

Routing table in the new namespace:
default dev virt-b scope link src 192.168.1.102

I can ping 192.168.1.102 from the root namespace and can ping 192.168.1.100 and 192.168.1.101 from the new namespace. However, I'm not able to ping other physical machines on the lan (eg 192.168.1.1).
I log incoming packets to the root namespace (with iptables -t raw -A PREROUTING -i virt-a -j LOG --log-prefix "[raw-PRE] " --log-level 7) and nothing makes it into the root namespace.
What am I misunderstanding about veth or namespaces?
EDIT:
I think I have misunderstood how veth works. Creating a bridge in the root namespace and making it the master of both eth0 and virt-a makes so I can can ping external devices from the new namespace.
Why is this? If I have two physical NICs and receive incoming traffic from one it can be forwarded to the other without a bridge. Shouldn't veth work the same way?
Any tips on where I can read more about the different link types in iproute? I'm having a hard time finding documentation.

A: The misunderstanding is about routing, not network namespaces: you're supposed to route IPv4 between different IPv4 networks.
Here you're trying to route IPs belonging to the same network: from 192.168.1.0/24 to 192.168.1.0/24: this doesn't get routed at all, unless special settings are made (like proxy arp and similar), which doesn't make much sense for your test case.
Use a different IP LAN, eg 192.168.2.0/24 for the veth-* network. Also the route in the network namespace has to use veth-a's IP as default gateway, not "just" the device. You might also need to add a NAT rule with iptables for outside systems around not aware of this other private network to interact properly, as well as enable ip forwarding.


text:
Q: Primefaces Slider component Is there a way to do not use InputText in association with Primefaces Slider component (for attribute) ?
I just want to have only the slide bar.
I can use InputHidden component but is it another convenient way ?
Extending component ?

A: The problem is that the slider in Primefaces doesn't hold any values.
You could try to extend the component or create the one you want but it seems like a difficult work when you can use the InputHidden. The component translate to a div tag so it doesn't hold any values so, in any case, you'd have to add a field that posts its value with the form (if you create or extend the component).
What is the problem with InputHidden? Why don't you want to use it?


text:
Q: I'm really bad at math and I want to do a binary operation I have the following piece of code:
    public void AddHash( int val )
    {
        m_Hash ^= (val & 0x3FFFFFF);
        m_Hash ^= (val >> 26) & 0x3F;
    }

I would like very much to know what the heck it does, but I would be satisfied to know how to build a bool HasHash( int val ) that tells me whether m_Hash has that number or not...
something like this?
    public bool HasHash( int val )
    {
        return (m_Hash & val) == 0;
    }

A: What the code does
It takes the last 26 bits of val and combines it with m_Hash using XOR. After that, it combines this with the first 6 bits of val. So an integer with 32 bits length will be reduced to 26 bits. According to the pigeonhole principle, this is not reversible.
HasHash function
So you won't be able to create a HasHash function even if you only called AddHash just once, because multiple input values in val will result in the same m_hash value.

A: EDIT to fix the bug that @schnaader found: What it does? This code probably wants to rotate val leftwards (clockwise) by 6 bits and form the ones-complement sum (edit: not the product, as I'd said before) -- the xor -- of that rotated value and the current value of m_Hash to yield a new m_Hash. That new m_Hash will be used the next time AddHash( ) is called.
However, the code as written has a bug: it rotates only the high-order 6 bits of val leftwards, leaving in place the low-order 26 bits of val. The code then xors together three values:

*

*the new low-order (old high-order) 6 bits of val;

*the original, unshifted low-order 26 bits of val; and

*the current value of m_Hash
leaving the result in m_Hash.
How does it do it? You can just map it out and emulate it:

*

*val & 0x3FFFFFF means extract the low-order 26 bits of val.

*xor those 26 bits with the current value of m_Hash

*now shift val rightwards such that the low-order 26 bits drop off the low-order end, leaving what used to be the high-order 6 bits of val in the low-order 6 bits of val.

*Mask with 0x3f to extract only those low-order 6 bits (in case some extraneous bits got shifted into the high order part of val).

*xor those low-order 6 bits with the current value of m_Hash to give the new m_Hash.

You know that rotating and exclusive-oring are common operations in calculating a hash.
EDIT: @schnaader pointed out the bug in the original code: that code forgot to do the other leg of the rotate: shifting the low-order 26 bits left by 6. To fix that, the code should read something like:
public void AddHash( int val )
{
  m_Hash ^= ((val & 0x3FFFFFF) << 6);
  m_Hash ^= (val >> 26) & 0x3F;
}

As to your HasHash( ) function: you should know that saying
return (m_Hash & val) == 0;
will return TRUE under many conditions, including some you might not want. For example, the function will return TRUE if m_Hash == 0xC0 and val == 0x03.


text:
Q: Refreshing ViewController after popViewControllerAnimated I have a root ViewController (RootViewController) that calls pushViewController to display another ViewController (DetailViewController). In DetailViewController I make edits that affect the contents displayed in the root ViewController. So I need to redraw the view in RootViewController after the DetailViewController is removed via popViewControllerAnimated.
The problem is that setNeedsDisplay does not seem to work in this scenario. In the viewWillAppear method of RootViewController, I call:
[self.view setNeedsDisplay]

However, the contents of the RootViewController view does not update. So I am wondering if there is something about Navigation Controllers that prevents setNeedsDisplay from working.
The only workaround I could find is that the following code, which forces a call to viewDidLoad, which redraws the entire view
self.view = nil;

A: You can update your view in viewWillAppear instead of viewDidLoad. You don't need to call setNeedsDisplay.


text:
Q: Using Localstorage with Redux in React I am working on an ecommerce site in React/Redux. I want to save the user's cart into the localstorage each time after an action has been dispatched in Redux. My code for that looks like this -
import { createSlice } from "@reduxjs/toolkit";

export const cartSlice = createSlice({
  name: "cart",
  initialState: {
    cart: [],
  },
  reducers: {
    addToCart: (state, action) => {
      state.cart = [...state.cart, action.payload];
      localStorage.setItem("Cart", JSON.stringify(state.cart));
    },
    removeFromCart: (state, action) => {
      state.cart = [];
    },
  },
});

export const { addToCart, removeFromCart } = cartSlice.actions;

export const selectCart = (state) => state.cart.cart;

export default cartSlice.reducer;

I did this to solve the problem of the cart getting empty whenever the site refreshes (because I was storing cart in state).
But here, everything works fine until the site refreshes. The products get added to the localstorage.
Now, when I refresh my site, since I am setting localstorage to the state of the cart, each time I refresh, the previous localstorage gets deleted and is overridden by the new state of the cart (because even the state of cart gets changed after refresh).
Is there any other way around it?
I tried by best to explain what I'm facing. Hope it's understandable.
Thanks in advance.


text:
Q: AngularJS variable from controller to directive I would like to ask you if it is possible, and if yes, then how can I pass some variable from controller to directive.
Here is a bit of my code:
app.js
var VirtualGallery = angular.module('virtualGallery', ['VirtualGalleryControllers', 'ngRoute']);

VirtualGallery.constant('apiURL', 'roomPicture');

VirtualGallery.run(['$rootScope', function ($rootScope) {
    $rootScope.roomPictures = [];
}]);

var VirtualGalleryControllers = angular.module('VirtualGalleryControllers', ['ngRoute']);

VirtualGalleryControllers.controller('AppCtrl', function ($http, $rootScope, $scope, apiURL, $q) {
$scope.getallrooms = function () {
    $http.get(apiURL)
        .success(function (data) {
            $rootScope.roomPictures = data; //idk whether to use $scope or $rootScope
        });
    };
});

In this app.js I'm trying to get some data from DB, and that data I need to use in directive.
Directive
angular.module('virtualGallery')
    .directive('ngWebgl', function () {
    return {
        restrict: 'A',
        scope: {
            'getallrooms': '=',
            'roomPictures': '='
        },
        link: function postLink(scope, element, attrs) {
            scope.init = function () {
                //here I would like to be able to access $scope or $rootScope from app.js file.
             };
          }
       };
    });

In directive I need to gain access to $scope or $rootScope in function init() where I need to use that data.
HTML

In html I'm trying to pass that data from app.js to directive.
Im quite new to Angular and this is even my first directive, so I am bit confused. Every help will be appreciated. Thanks guys :)

A: You can inject $rootScope to your directive ( like you did in your controller ) and then access that rootScope variable.

A: In your app.js use the controller like this
VirtualGalleryControllers.controller('AppCtrl', function ($http, $rootScope, $scope, apiURL, $q) {
$scope.getallrooms = function () {
    $http.get(apiURL)
        .success(function (data) {
            $scope.roomPictures = data; //use $scope instead of  $rootScope
        });
    };
});

Then for your directive:
angular.module('virtualGallery')
.directive('ngWebgl', function () {
  return {
    restrict: 'A',
    scope: {
        pictures: '=virtualGallery'
    },
    link: function postLink(scope, element, attrs) {
        scope.init = function () {
            // you can access the variable through the scope
            scope.pictures;
         };
    }
  };
});

Or you could simply make the http request in your directive and manipulate the data there.


text:
Q: Logstash stopped processing because of an error: (SystemExit) exit We are trying to index Nginx access and error log separately in Elasticsearch. for that we have created Filbeat and Logstash config as below.
Below is our /etc/filebeat/filebeat.yml configuration
filebeat.inputs:
- type: log
  paths:
    - /var/log/nginx/*access*.log
  exclude_files: ['\.gz$']
  exclude_lines: ['*ELB-HealthChecker*']
  fields:
    log_type: type1
- type: log
  paths:
    - /var/log/nginx/*error*.log
  exclude_files: ['\.gz$']
  exclude_lines: ['*ELB-HealthChecker*']
  fields:
    log_type: type2

output.logstash:
  hosts: ["10.227.XXX.XXX:5400"]

Our logstash file /etc/logstash/conf.d/logstash-nginx-es.conf config is as below
input {
    beats {
        port => 5400
    }
}

filter {
  if ([fields][log_type] == "type1") {
    grok {
      match => [ "message" , "%{NGINXACCESS}+%{GREEDYDATA:extra_fields}"]
      overwrite => [ "message" ]
    }
    mutate {
      convert => ["response", "integer"]
      convert => ["bytes", "integer"]
      convert => ["responsetime", "float"]
    }
    geoip {
      source => "clientip"
      target => "geoip"
      add_tag => [ "nginx-geoip" ]
    }
    date {
      match => [ "timestamp" , "dd/MMM/YYYY:HH:mm:ss Z" ]
      remove_field => [ "timestamp" ]
    }
    useragent {
      source => "user_agent"
    }
  } else {
      grok {
        match => [ "message" , "(?<timestamp>%{YEAR}[./]%{MONTHNUM}[./]%{MONTHDAY} %{TIME}) \[%{LOGLEVEL:severity}\] %{POSINT:pid}#%{NUMBER:threadid}\: \*%{NUMBER:connectionid} %{GREEDYDATA:message}, client: %{IP:client}, server: %{GREEDYDATA:server}, request: "(?:%{WORD:verb} %{NOTSPACE:request}(?: HTTP/%{NUMBER:httpversion}))"(, upstream: "%{GREEDYDATA:upstream}")?, host: "%{DATA:host}"(, referrer: "%{GREEDYDATA:referrer}")?"]
        overwrite => [ "message" ]
      }
      mutate {
        convert => ["response", "integer"]
        convert => ["bytes", "integer"]
        convert => ["responsetime", "float"]
      }
      geoip {
        source => "clientip"
        target => "geoip"
        add_tag => [ "nginx-geoip" ]
      }
      date {
        match => [ "timestamp" , "dd/MMM/YYYY:HH:mm:ss Z" ]
        remove_field => [ "timestamp" ]
      }
      useragent {
        source => "user_agent"
      }
    }
}

output {
  if ([fields][log_type] == "type1") {
    amazon_es {
      hosts => ["vpc-XXXX-XXXX.ap-southeast-1.es.amazonaws.com"]
      region => "ap-southeast-1"
      aws_access_key_id => 'XXXX'
      aws_secret_access_key => 'XXXX'
      index => "nginx-access-logs-%{+YYYY.MM.dd}"
    }
} else {
    amazon_es {
      hosts => ["vpc-XXXX-XXXX.ap-southeast-1.es.amazonaws.com"]
      region => "ap-southeast-1"
      aws_access_key_id => 'XXXX'
      aws_secret_access_key => 'XXXX'
      index => "nginx-error-logs-%{+YYYY.MM.dd}"
    }
  }
    stdout {
      codec => rubydebug
    }
}

And we are receiving below error while starting logstash.
[2020-10-12T06:05:39,183][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"7.9.2", "jruby.version"=>"jruby 9.2.13.0 (2.5.7) 2020-08-03 9a89c94bcc OpenJDK 64-Bit Server VM 25.265-b01 on 1.8.0_265-b01 +indy +jit [linux-x86_64]"}
[2020-10-12T06:05:39,861][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2020-10-12T06:05:41,454][ERROR][logstash.agent           ] Failed to execute action {:action=>LogStash::PipelineAction::Create/pipeline_id:main, :exception=>"LogStash::ConfigurationError", :message=>"Expected one of [ \\t\\r\\n], \"#\", \"{\", \",\", \"]\" at line 32, column 263 (byte 918) after filter {\n  if ([fields][log_type] == \"type1\") {\n    grok {\n      match => [ \"message\" , \"%{NGINXACCESS}+%{GREEDYDATA:extra_fields}\"]\n      overwrite => [ \"message\" ]\n    }\n    mutate {\n      convert => [\"response\", \"integer\"]\n      convert => [\"bytes\", \"integer\"]\n      convert => [\"responsetime\", \"float\"]\n    }\n    geoip {\n      source => \"clientip\"\n      target => \"geoip\"\n      add_tag => [ \"nginx-geoip\" ]\n    }\n    date {\n      match => [ \"timestamp\" , \"dd/MMM/YYYY:HH:mm:ss Z\" ]\n      remove_field => [ \"timestamp\" ]\n    }\n    useragent {\n      source => \"user_agent\"\n    }\n  } else {\n      grok {\n        match => [ \"message\" , \"(?<timestamp>%{YEAR}[./]%{MONTHNUM}[./]%{MONTHDAY} %{TIME}) \\[%{LOGLEVEL:severity}\\] %{POSINT:pid}#%{NUMBER:threadid}\\: \\*%{NUMBER:connectionid} %{GREEDYDATA:message}, client: %{IP:client}, server: %{GREEDYDATA:server}, request: \"", :backtrace=>["/usr/share/logstash/logstash-core/lib/logstash/compiler.rb:32:in `compile_imperative'", "org/logstash/execution/AbstractPipelineExt.java:183:in `initialize'", "org/logstash/execution/JavaBasePipelineExt.java:69:in `initialize'", "/usr/share/logstash/logstash-core/lib/logstash/java_pipeline.rb:44:in `initialize'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline_action/create.rb:52:in `execute'", "/usr/share/logstash/logstash-core/lib/logstash/agent.rb:357:in `block in converge_state'"]}
[2020-10-12T06:05:41,795][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
[2020-10-12T06:05:46,685][INFO ][logstash.runner          ] Logstash shut down.
[2020-10-12T06:05:46,706][ERROR][org.logstash.Logstash    ] java.lang.IllegalStateException: Logstash stopped processing because of an error: (SystemExit) exit

There seems to be some formatting issue. Please help what is the problem
=================================UPDATE===================================
For all those who are looking for a robust grok filter for nginx access and error logs ... please try below filter patterns.
Access_Logs - %{IPORHOST:remote_ip} - %{DATA:user_name} \[%{HTTPDATE:access_time}\] \"%{WORD:http_method} %{URIPATHPARAM:url} HTTP/%{NUMBER:http_version}\" %{NUMBER:response_code} %{NUMBER:body_sent_bytes} \"%{SPACE:referrer}\" \"%{DATA:agent}\" %{NUMBER:duration} req_header:\"%{DATA:req_header}\" req_body:\"%{DATA:req_body}\" resp_header:\"%{DATA:resp_header}\" resp_body:\"%{GREEDYDATA:resp_body}\"
Error_Logs - (?<timestamp>%{YEAR}[./]%{MONTHNUM}[./]%{MONTHDAY} %{TIME}) \[%{LOGLEVEL:severity}\] %{POSINT:pid}#%{NUMBER:threadid}\: \*%{NUMBER:connectionid} %{DATA:errormessage}, client: %{IP:client}, server: %{IP:server}, request: \"(?<httprequest>%{WORD:httpcommand} %{NOTSPACE:httpfile} HTTP/(?<httpversion>[0-9.]*))\", host: \"%{NOTSPACE:host}\"(, referrer: \"%{NOTSPACE:referrer}\")?

A: Grok pattern on line 32 is the issue. Need to escape all " characters.
Below is an escaped version of the GROK.
grok {
        match => [ "message" , "(?<timestamp>%{YEAR}[./]%{MONTHNUM}[./]%{MONTHDAY} %{TIME})\[%{LOGLEVEL:severity}\] %{POSINT:pid}#%{NUMBER:threadid}\: \*%{NUMBER:connectionid} %{GREEDYDATA:message}, client: %{IP:client}, server: %{GREEDYDATA:server}, request: \"(?:%{WORD:verb} %{NOTSPACE:request}(?: HTTP/%{NUMBER:httpversion}))\"(, upstream: \"%{GREEDYDATA:upstream}\")?, host: \"%{DATA:host}\"(, referrer: \"%{GREEDYDATA:referrer}\")?"]
        overwrite => [ "message" ]
      }


text:
Q: Sould I build the html up wih only fetch requests? a normal, static html file looks like that:
<!DOCTYPE html>
[..]
<body>
<header>
<!-- here is my header content. -->
</header>
</body>
</html>

But often you have multiple Files, obviously every single one with the same header, then you would just include the header with php:
<!DOCTYPE html>
[..]
<body>
<?php
require 'header.php';
?>
</body>
</html>

But here you have to make sure, that every single file has the header included via php.
Now here is my question: Would it make sense, to fetch the header via Javascript with the fetch api?
Not only the header of course, but everything.
Thank you!


text:
Q: Is a device broken if it fails to show up under lsusb? I purchased a usb wifi adapter that doesn't work or show up in lsusb. Here are the possible reasons I can think of why it wouldn't show up in lsusb:

*

*The usb port is broken

*The device is broken

*There's something wrong with lsusb

Are there any other possibilities?
I've tested all my USB ports, and they are not at fault.
I've also tried it on two computers with the same results.
It seems unlikely that lsusb would fail.
Unless there is another possible source of error, I must assume that the adapter itself is broken.
edit: the device shows up in Windows device manager, although I'm not able to install the driver. This suggest that the device isn't actually broken, which is even more confusing.

A: The thing is probably dead, lsusb should list devices that are unresponcive but might not. The fact that you can see it in windows just means windows knows somthing's connected to the port, but not that it works.
Pull up the properties on the device in windows and see if you can find the system messages for it; it should, if functional, come up with a device name and the logs should show a device install request which would imply it's working and you should find drivers for it. Windows may also tell you that the device blew an error (giving you evidence it's faulty) should tell you something like "error: 43" if windows thinks it's screwed
GL

A: The other possibility is that your operating system (in this case Ubuntu) doesn't have the necessary drivers to get that device to work or even recognize it.
These questions might be helpful to you:
Wifi Dongle not appearing in lsusb
My WiFi adapter is not working at all, how to troubleshoot?


text:
Q: Python: Incorrect number of bindings supplied when EXECUTEMANY Trying to pick up some python. I'm quite new to it at the moment.
I created the code below, but it returns an error.
I am able to get it to work when creating a second column and write multiple values to the db but a single value doesn't seem to work. Probably a list, tuple thing, but can not figure out what exactly.
Error:
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    cursor.executemany("INSERT INTO combination VALUES (?)", combination)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.

Code:
import sqlite3

conn = sqlite3.connect("combinations.db")
cursor = conn.cursor()

cursor.execute(r"create table if not exists combination (string text)")

combination = []
chars = "abcd"

for char1 in chars:
    for char2 in chars:
        combination.append((char1+char2))

cursor.executemany("INSERT INTO combination VALUES (?)", combination)

conn.commit()

A: You missed making the string into a tuple when adding to the list. The argument to executemany expects a list of iterables, so if you pass it a single string 'ab' in the list, it will treat it as a 2-item iterator of a & b - hence the error.
You need to make the string 'ab' into a 1-item tuple like ('ab',). You do this by adding a trailing comma to the expression you're appending:
combination.append((char1+char2,))

Full code:
import sqlite3

conn = sqlite3.connect("combinations.db")
cursor = conn.cursor()

cursor.execute(r"create table if not exists combination (string text)")

combination = []
chars = "abcd"

for char1 in chars:
    for char2 in chars:
        combination.append((char1+char2,))  # ('ab',) etc.

cursor.executemany("INSERT INTO combination VALUES (?)", combination)

conn.commit()


text:
Q: Algorithm for converting Category Tree to Flat List I am trying to convert a Categories Tree to a flat list.
In the Categories any category can have n levels of subcategories.
For Ex.:

Category1
-SubCategory1
-SubCategory2
--SubCategor1
---SubCategory1
---SubCategory2
----SubCategory1
----SubCategory2
---SubCategory3
--SubCategory2
-SubCategory3

Category2
-SubCategory1
--SubCategory1
---SubCategory1
----SubCategory1
---SubCategory3
-SubCategory3

...etc and so on.

Language is not a barrier I am just trying to formulate loops/nested loops to create this logic to convert it into a flattened list.
Any help will be highly appreciated.
Thanks in Advance

A: Each entry to your flat List will be a node of your Tree as that is visited according to Depth First Search. For more information please see here
Edit:
The original post was edited a couple of times. Initially, it looked like the OP was after a flat list as that would be the output of BFS but after a later edit it looked like the OP was after a flat list as that would be the output of DFS. The more general case then would be that "Each entry to the flat list will be a node of the Tree as that is visited by some traversal function (such as BFS or DFS)."

A: I don't know what you mean by a flat list, but you can use a stack (implementation wise, it can be STL vector) to store the current progress while recursively visiting the sub categories.
"The current progress" that I mentioned above should store which subcategory that you are currently visiting, so that you can continue to visit other subcategory when you return.
If you can formulate a recursive algorithm, you can rewrite it in this form.

A: You can easily make this using recursion + std::copy function.


text:
Q: Does anyone know how I can get rid of this additional pixel at the top of my table? There is a 1px difference between the "player" columns (on the right) and the "heading" column (on the left) which ideally shouldn't be there.
I've tried everything I can think of to get rid of this but have had no success.  If anyone can tell me where this pixel has come from and also how I might be able to get rid of it I would be extremely grateful.  I am also fairly new to web development in general so if by any chance you see any bad practices or messy code while nosing around any help would, again, be greatly appreciated.
website: https://yahtzee-scoresheet.netlify.app/
github repo: https://github.com/Smickbart/Yahtzee-Scoresheet

A: the problem lies in base.scss:30
Open page in Chrome . hit F12 - then highlite affected area - check styles ...
try adding this to your stylesheet:
<style>
    table {
        border: 0px solid #000;
    }
</style>

A: Due to border property coming from _base.scss file
table, td, th {
    border: 1px solid #000; /* This is where it is coming from */
    border-collapse: collapse;
}


text:
Q: How to Get Multiple 'Keys' For a Command How do I set multiple inputs for a command:
while True:
    option = input('What Units Are You Using? (Q to Quit) ').lower()
    if option == ['millimeters' , 'mm']:
        a = int(input('Enter Your number: '))
        while True:
            b = a / 10 # centimeters
            c = a / 1000 # meters
            print('Okay- Heres what we got:', b,'centimeters(cm) and', c,' meters (m)')
            break

So for: if option == ['millimeters' , 'mm']:   How do I get it to run both millimeters and mm?
(Python 3.33)
Thanks

A: You can use in operator (which checks the member existence), like this
if option in ['millimeters' , 'mm']:

Now, the if condition will be satisfied if option is either millimeters or mm.
Suggestions:

*

*You don't need an infinite loop here.

*You can use format method to compose strings.

So, your improved program looks like this
while True:
    option = input('What Units Are You Using? (Q to Quit) ').lower()
    if option in ['millimeters' , 'mm']:
        a = int(input('Enter Your number: '))
        b, c = a / 10, a / 1000
        print('Okay- Heres what we got: {} centimeters(cm) and {} meters (m)'.format(b, c))

A: while True:
    option = input('What Units Are You Using? (Q to Quit) ').lower()

    if option == 'millimeters' or  option == 'mm':

        a = int(input('Enter Your number: '))

        while True:

            b = a / 10 # centimeters

            c = a / 1000 # meters

            print('Okay- Heres what we got:', b,'centimeters(cm) and', c,' meters (m)')
            break

A: Here's an extended version:
import sys

if sys.hexversion < 0x3000000:
    inp = raw_input     # Python 2.x
else:
    inp = input         # Python 3.x

class Unit:
    def __init__(self, short_singular, short_plural, long_singular, long_plural, per_meter):
        self.ss = short_singular
        self.sp = short_plural
        self.ls = long_singular
        self.lp = long_plural
        self.per_meter = per_meter
        self.names = {short_singular, short_plural, long_singular, long_plural}

    def match(self, name):
        return name in self.names

    def to_meters(self, amt):
        return amt / self.per_meter

    def from_meters(self, amt):
        return amt * self.per_meter

    def to_str(self, amt, sig=3, short=False):
        if amt == 1.0:
            s = self.ss if short else self.ls
        else:
            s = self.sp if short else self.lp
        return "{{:0.{}f}} {{}}".format(sig).format(amt, s)

units = [
    Unit('in', 'ins', 'inch',       'inches',    39.3701),
    Unit('ft', 'ft',  'foot',       'feet',      3.28084),
    Unit('yd', 'yds', 'yard',       'yards',     1.09361),
    Unit('mi', 'mi',  'mile',       'miles', 0.000621371),
    Unit('mm', 'mm',  'millimeter', 'millimeters', 1000.),
    Unit('cm', 'cm',  'centimeter', 'centimeters',  100.),
    Unit('m',  'm',   'meter',      'meters',         1.),
    Unit('km', 'km',  'kilometer',  'kilometers',  0.001)
]

def get_unit(prompt):
    while True:
        name = inp(prompt).strip().lower()
        for unit in units:
            if unit.match(name):
                return unit
        print("I don't know that one.")

def get_float(prompt):
    while True:
        try:
            return float(inp(prompt))
        except ValueError:
            pass

def main():
    a   = get_unit("Convert from what unit? ")
    b   = get_unit("To what unit? ")
    amt = get_float("How many {}? ".format(a.lp))
    res = b.from_meters(a.to_meters(amt))
    print("The result is {}.".format(b.to_str(res)))

if __name__=="__main__":
    main()

which runs like
Convert from what unit? km
To what unit? in
How many kilometers? 4.3
The result is 169291.430 inches.


text:
Q: Unit testing for usql applier and scripts I have a custom USql applier which extends the IApplier class.
[SqlUserDefinedApplier]
public class CsvApplier : IApplier
{
    public CsvApplier()
    {
        //totalcount = count;
    }
    public override IEnumerable<IRow> Apply(IRow input, IUpdatableRow output)
    {
        //....custom logic
        //yield return or yield break
    }
}

This applier is then used from Usql script as
@log =
SELECT t.ultimateID,
t.siteID,
.
.
.
t.eTime,
t.hours
FROM @logWithCount
CROSS APPLY
new BSWBigData.USQLApplier.CsvApplier() AS t(ultimateID string, siteID string, .... , eTime string, hours double, count long?);

I have been able to write unit tests/ATPs for decoupled parts of applier.
How can i write tests for C# code of Apply method and the custom logic dependent on input/output?
How can i automate testing of usql scripts with defined inputs and outputs such that no data lake account is needed?

A: As @Michael Rys mentioned, currently it can be done by using the U-SQL local run, but not necessarily in Visual Studio.
We are trying to address this by providing you a "U-SQL Local Run SDK", which you can use as a way to run your scripts locally. Then you can utilize it to test the U-SQL scripts by writing some C# unit test wrappers and then run those unit tests in your CI system/build servers.
We are in the process of publishing this SDK via NuGet, but if you are interested in it, you can drop me an email at xiaoyzhu at Microsoft dot com and we can send you the bits we are trying to release.
Thanks
Xiaoyong Zhu from Azure Data Lake Team

A: Before we ship the standalone U-SQL Localrun SDK package,  please get the needed files from where you installed the ADLA Tool for VS.
In VS2015,  all the dependencies needed for local run are in  "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Microsoft Azure Data Lake DRI Tools for Visual Studio 2015\2.0.XXXX.0\LocalRunSDK.  You will also need "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Microsoft Azure Data Lake DRI Tools for Visual Studio 2015\2.0.XXXX.0\CppSDK"
Just copy files from these two folders and place them somewhere like:
C:\USQLLocalRunSDK
Then you can use "LocalRunHelper.exe" to compile and run your u-sql scripts locally.  On the compilation commandline, you need two options:
  -DataRoot "Where your local metadata and data are stored", the same as that setup option in ADLA Tool.
  -CppSDK  "Where you copied the CppSDK files"
That tool will return -1 upon error (compile or run) and 0 on success.
Just run the tool to see the list of command line options.

A: The ADL Tools for VisualStudio have a local mode so you can do local execution also of UDOs. Although you may not get the full parallel processing locally, you should be able to test your code in the local run.


text:
Q: Spring boot, entity cached issue? I'm using a PostgreSQL db in the background and Spring Boot with Spring Data.
I have a @Controller that;

*

*Calls a Service layer method that has an @Transactional(readOnly = false) on it. This method builds an Entity object from scratch and saves it to the db using the Spring Data built in entityRepository.saveAndFlush(entity);

*Then calls via a RestTemplate a remote API that shares the same database, passing the generate Id of the previously saved Entity. This server does some legacy processing and updates the database values.

*Calls a Service layer method that reads the previously saved Entity and finally returns that as the response to the overall Request.

The trouble is, the changes made by the remote API in step 2 aren't reflected in the db get from step 3.
The @Transaction is only around step 1 so I would have assumed, particularly with the saveAndFlush call, that the transaction ends as that method is exited?
I can call another @Controller method to just perform step 3 afterwards and the result is perfect with the changes from the remote API reflected fine.
It seems that Spring Boot/Data is somewhere caching the result of the initial save for the entire Request, which is not what I want. Any ideas?

A: You're seeing the effects of OpenEntityManagerInViewFilter keeping the EntityManager bound to your request for the duration of all 3 steps. The EntityManager in your request is oblivious to the database changes you make in step 2.
Assuming you don't have any race conditions (i.e, step 3 runs before step finishes), you could evict the entity cache.
// inject the entityManager into a custom repository, and
entityManager.getEntityManagerFactory().getCache().evict(YourEntity.class, id)


text:
Q: Stuck on calling Twitch.tv API in jQuery I am stuck on calling twicth.tv API. I mean I get all the channel and could display it. But when I do it for a live stream, I'm getting a 404 error.
(document).ready(function() {
            var masterChannel = "freecodecamp";
            var followersUrl = "https://wind-bow.glitch.me/twitch-
            api / users / "+masterChannel+" / follows / channels ";
            var channelsUrl = "https://wind-bow.glitch.me/twitch-api/channels/";
            var streamsUrl = "https://wind-bow.glitch.me/twitch-api/streams/";
            $.getJSON(streamsUrl + masterChannel).done(function(live) {
                        $("#fccstatus").html(!live.stream ? "Freecodecamp is currenty
                            OFFLINE ":"
                            Freecodecamp is currenty ONLINE ");
                        }); $.getJSON(followersUrl).done(function(followers) {
                        for (var i = 0; i < followers.follows.length; i++) {
                            var followerName = followers.follows[i].channel.name;
                            $.getJSON(channelsUrl + followerName).done(function(channel) {
                                    var channelUrl = channel.url;
                                    var channelName = channel.name;
                                    var channelUsername = channel.logo;
                                    $.getJSON(streamsUrl + channelName).done(function(live) {
                                            var status = !live.stream ? 'Offline' : 'Online';
                                            $("#followerinfo").prepend("
" + "
"+""+"
"+"
"+" <
                                                a href = "+channelUrl+" > "+channelUrl+" "+"
 "+"
"+status+"
"+"
");
                                            });
                                    });
                            }
                        }); $("#online").click(function() {
                            $.getJSON(followersUrl).done(function(followers1) {
                                    for (var i = 0; i < followers1.follows.length; i++) {
                                        var followerName1 = followers1.follows[i].channel.name;
                                        $.getJSON(channelsUrl + followerName1).done(function(channel1) {
                                                var channelUrl1 = channel1.url;
                                                var channelName1 = channel1.name;
                                                var channelUsername1 = channel1.logo;
                                                $.getJSON(streamsUrl + channelName1).done(function(live1) {
                                                        var status1 = !live1.stream ? 'Offline' : 'Online';
                                                        if (status1 == "Online") {
                                                            $("#followerinfo").empty();
                                                            $("#followerinfo").prepend("
" + "
"+""+"
"+"
"+""+channelUrl1+""+"
"+"
 "+status1+"
"+"
 ");
                                                            }
                                                        });
                                                });
                                        }
                                    });
                            })
                    });

See the code..The first part is working.But when i do it for online click button it isnt working a 404 error is thrown.


text:
Q: How do I dodge/block attacks with a Force Master? I've recently started playing the game, and one thing that ticks me, comparing to tera is that, for the love of my life, I can't avoid any damage at all!
This leads me to die in less than 1 minute with 2 enemies.
I am aware of SS, but it is very clucky, slow, delayed and it has 10 seconds of cooldown, leading to the same situation as before.
But, sometimes, out of nowhere, I see that the damage was blocked.
I really don't understand how that happens. I just slowly move to it's back or something.
In short, the question is: How do I dodge/block attacks with a Force Master?

A: In addition to SS, you can also use Q and E. These require you to have a target, but you will quickly move behind your target a few meters away. It moves you a surprisingly long distance. I don't know if it has iframes, but I know it's an option.
Edit:
Note also you can use ice shield (TAB), even though it isn't a dodge. There is also random chance to block damage, that's probably what you saw. But you will have no control over that.

A: Save the backstep since it has a 36 second cooldown, and you can eventually level it up to the frost step in which you can freeze the area you step out of. Use q and e to escape damage, and at level 13 there's really not much to say since most of your skills for heal and cc aren't out yet, plus you don't have that many points in the skill tree.
I hit 45 about a week ago, and the best thing to do against blade dancers is to kite them. Use the right click frost for slow, and 2 for daze, 3 for freeze and follow up with 1 to knock back stun. I'm not sure if the fire stance x skills came out for you yet or not, but as you level up you can eventually insta cast it. I use mostly that and the frost stance z and x for slow, cc, and burst. Control the TAB key frost and your frost stance c and v for survival. C is a really powerful skill if you add the points right.
Honestly fm have pretty powerful burst and cc, you just have to have pvp experience. Took me 60 rounds of ranked to get enough experience to get to gold


text:
Q: Unable to locate package Nginx-module-GeoIP I am working on Debian Jessie 9. I have installed Nginx but there is no GeoIP module.
so I decided to install it but "apt-get install nginx-module-geoip" not working giving an error like E: Unable to locate package Nginx-module-GeoIP
how I can install GeoIP module in Nginx

A: From the documentation it looks like the command for Debian/Ubuntu is this:
apt-get install nginx-plus-module-geoip2

Note that NGINX plus needs to be installed, not just regular NGINX
I've been using the MaxMind free geolite2 database module, but it hasn't been updated since 2015 and only runs on Python2.  Is the NGINX module more recent?


text:
Q: OnActionReceived not being called I am trying to override the OnActionReceived method of the Agent class. But I don't think that the function is getting called and it doesn't give me any error.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;

public class MoveCar : Agent
{
    // more code here

    public override void OnActionReceived(ActionBuffers actions)
    {
        // Get the acceleration, brake, and steer actions from the ML-Agents system
        float acceleration = actions.ContinuousActions[0];
        float brake = Mathf.Clamp(actions.ContinuousActions[1], 0, 1);
        float steer = actions.ContinuousActions[2];

        Debug.Log(acceleration);

        nowAcceleration = motorMax * acceleration;
        nowBrake = brakeMax * brake;
        nowSteer = steerMax * steer;

        // Apply the actions to the car
        wheelBackLeft.motorTorque = nowAcceleration;
        wheelBackRight.motorTorque = nowAcceleration;

        wheelBackLeft.brakeTorque = nowBrake;
        wheelBackRight.brakeTorque = nowBrake;
        // wheelFrontLeft.brakeTorque = nowBrake;
        // wheelFrontRight.brakeTorque = nowBrake;

        wheelFrontLeft.steerAngle = nowSteer;
        wheelFrontRight.steerAngle = nowSteer;

        updateWheel(wheelFrontLeft, frontLeftTransform);
        updateWheel(wheelFrontRight, frontRightTransform);
        updateWheel(wheelBackLeft, backLeftTransform);
        updateWheel(wheelBackRight, backRightTransform);
    }

    // more code here
}

I wanted the car to move and to see my acceleration in the Unity3d console but the car does nothing and nothing is printed in the console.


text:
Q: Displaying variables in view from the controller I would like to display these values from the controller to the view
Here is a snippet of my controller function:
        $i = 0;

        foreach($data['main']->result() as $list):

           $list_id = $list[$i]['check_id'];

           //I concatinate the 'extra' and $i so it would have a unique name
           $data['extra'.$i] = $this->MyModel->getExtra($list_id);

           $i++;

        endforeach;

        //I store it on data so I would know the max number in the view
        $data['max'] = $i;

        $this->load->view('Main/viewList',$data);

No errors there. Also checked the variables if all are successfully stored.
I would like now to display it on the view.
                <?php
                  for($i=0; $i<$max; $i++) {

                    foreach(($extra.$i)->result() as $list):
                      echo $list->name;

                    endforeach;
                  }
                ?>

$extra.$i doesnt work on the view. It has an parsing error of unexpected '->' (T_OBJECT_OPERATOR)

A: Change from
<?php
     for($i=0; $i<$max; $i++) {
         foreach(($extra.$i)->result() as $list):
                echo $list->name;
                endforeach;
     }
?>

to
<?php
         for($i=0; $i<$max; $i++) {
             $extra = ${'extra' . $i};
             foreach($extra->result() as $list):
                    echo $list->name;
                    endforeach;
         }
    ?>


text:
Q: Query DynamoDB with IN Clause I am new to DynamoDB and wanted to know how can we query on a table in DynamoDB with IN clause using Java.
I have a table named items. It`s schema is
1. Product (Partition Key of type String)
2. ID (Sort Key of type int)
3. Date ( attribute of type String)

I want to query similar to
SELECT ID FROM items WHERE Product IN ("apple","orange").

or
SELECT Product FROM items WHERE ID IN (100,200).

A: As the requirement is to get the products without the partition key, there are two options available.
1) Create GSI (Global Secondary Index) on sort key attribute Id to use the Query API
2) Scan the entire table to get the products - not very efficient as it scans the full table
Both the options use the IN operator available on DynamoDB.
Sample code for Scan using ID:-
Map<String, AttributeValue> attributeValues = new HashMap<>();
attributeValues.put(":id1", new AttributeValue().withN("100"));
attributeValues.put(":id2", new AttributeValue().withN("200"));

DynamoDBScanExpression dynamoDBScanExpression = new DynamoDBScanExpression()
                                                    .withFilterExpression("ID IN (:id1, :id2)")
                                                    .withExpressionAttributeValues(attributeValues);

PaginatedScanList<yourModelClass> scanList = dynamoDBMapper.scan(yourModelClass.class, dynamoDBScanExpression,
        new DynamoDBMapperConfig(DynamoDBMapperConfig.ConsistentReads.CONSISTENT));

Iterator<yourModelClass> iterator = scanList.iterator();

while (iterator.hasNext()) {
    System.out.println(iterator.next().getTitle());
}

Query by product:-
1) Cannot use IN operator for partition key
2) Cannot use batchLoad API without knowing the sort key
Conclusion:-
The efficient solution is to create GSI (without sort key) on attribute Id and use batchLoad API.
Note: The partition key of GSI need not be unique


text:
Q: Why isn't equals() method working on Threads? public class Test {
    public static void main(String[] args) {
        Thread t1 = new Thread();
        Thread t2 = new Thread();
        Thread t3 = t1;

        String s1 = new String();
        String s2 = new String();

        System.out.println(t1 == t3);  //true
        System.out.println(t1 == t2);  //false

        **System.out.println(t1.equals(t2));  //false**
        System.out.println(s1.equals(s2)); //true
    }
}

As we know, Object.equals() method is used for checking the content rather than the reference. So when you create two threads and perform equals() on them, what exactly is happening?
I assumed threads work differently. (I'm a beginner)
How do they work?

A: You seem to misunderstand what equals does.
I suppose that you learned that equals can be used to compare strings on a character by character basis instead of comparing them by their references. Then you thought, okay, so equals can compare stuff like that!
And then, you thought that these two threads are the same:
Thread t1 = new Thread();
Thread t2 = new Thread();

"because look! They are created the same way - with new Thread(). So they should be equal!" you thought.
However, equals does not think the two threads are equal. In fact, Thread does not even override equals (String does)! Therefore, it uses the equals implementation from its superclass, Object, which compares the references.
Therefore, equals is not like some "magical" thing that compares objects "logically". It has to be overridden in subclasses. It does not always work where you want it to.
Another example would be Scanner, which does not override equals either.
Scanner s1 = new Scanner("Hello");
Scanner s2 = new Scanner("Hello");
System.out.println(s1.equals(s2)); // false

s1 and s2 has exactly the same string to scan and they are at exactly the same position of the string, yet they are not equal when you compare them with equals.


text:
Q: Deleted OAUTH client for production flutter app I am using flutter for developing an application with google_sign_in package. We had some unnecesary clients in our google cloud console. I accidentaly deleted the one used for the production app. I created a new one with the same SHA-1 fingerprint as the old one, but the oauth client gives the following error.
PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null)

If I generate a new keystore file and add it to the cloud console, the login works. But I can't upload the application to the play store because the keystore file has changed.
We should roll out an update in the next few days, what are my options?


text:
Q: Exception when compiling with ant I hope no-one has asked this before (I couldn't find anything, but that may just be poor searching).  I am compiling by running ant in my root directory.  However, I get this error:
class file has wrong version 50.0, should be 49.0

I know this is because it wants Java 1.6, and is using 1.5, but my mac has Java 1.6 as well (I've checked in /System/Library/Frameworks/JavaVM.framework/Versions).  How can I get ant to run with 1.6 so that I can compile?
EDIT:
I've added the correct path of Java 1.6 to /etc/profile, and
export PATH=$JAVA_HOME/bin:$PATH, after this line.  Executing java -version gives the correct version (1.6.0), but running ant -v still produces the same error, and states that Java 1.5 is being used.
Does anyone know how I can force ant to use Java 1.6?!

A: One easy way is to set JAVA_HOME environment variable to point to the jdk you want to use.
There're many ways to do that. E.g., if you're on mac/linux, you could add this to /etc/profile
export JAVA_HOME=/path/to/java

On windows, IIRC, there's a menu in My Computer/properties.


text:
Q: reading XML File from URL in Android I experimented with several ways of opening an XML file from the link, but all the roads did not do any good.
In order to make sure that parsing XML File is good, I downloaded the file and put it in Asset folder to make parsing all of this good.
We can deduce from this the error in reading from url
URL is http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httppost);
InputStream in=response.getEntity().getContent();

OR
HttpURLConnection con=(HttpURLConnection)url.openConnection();
InputStream in=con.getInputStream();

OR
InputStream in =url.openStream();

please help me
My Problem solved thanx to all for your help.I should use AsyncTask class when i get File from Url

A: public void xmlReader() {

        try {

            URL url = new URL("http://feeds.bbci.co.uk/sport/0/football/rss.xml");

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory
                    .newDocumentBuilder();
            Document document = documentBuilder.parse(new InputSource(url
                    .openStream()));

            nodlist = document.getElementsByTagName("Youritem");

            for (int i = 0; i < nodlist.getLength(); i++) {
                Element element = (Element) nodlist.item(i);

                NodeList nodlistid = element.getElementsByTagName("Id");
                Element id = (Element) nodlistid.item(0);

                NodeList nodlistBaslik = element.getElementsByTagName("tagname1");
                Element baslik = (Element) nodlistBaslik.item(0);

                NodeList nodlistDetay = element.getElementsByTagName("tagname2");
                Element detay = (Element) nodlistDetay.item(0);

                NodeList nodlistKaynak = element.getElementsByTagName("tagname3");
                Element lat = (Element) nodlistKaynak.item(0);

                NodeList nodelistMedia = element.getElementsByTagName("tagname4");
                Element longi = (Element) nodelistMedia.item(0);

                NodeList nodelistTur = element.getElementsByTagName("tagname5");
                Element tur = (Element) nodelistTur.item(0);
                // String resimURL =
                // resim.getAttributes().getNamedItem("url").getNodeValue();

                NodeList nodelistMedia1 = element.getElementsByTagName("enclosure");
                Element picture= (Element) nodelistMedia1.item(0);
                String pictureURL = resim.getAttributes().getNamedItem("picturetagname").getNodeValue();

                xmltagname1.add(tagname1.getChildNodes().item(0).getNodeValue());
                xmltagname2.add(tagname2.getChildNodes().item(0).getNodeValue());
                xmltagname3.add(tagname3.getChildNodes().item(0).getNodeValue());
                xmltagname4.add(tagname4.getChildNodes().item(0).getNodeValue());
                xmltagname5.add(tagname5.getChildNodes().item(0).getNodeValue());

            }

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

    }

I think this method helps you.. Take it easy

A:
  String TextHolder = "", TextHolder2 = "";
public class GetNotePadFileFromServer extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog.show();
    }
    @Override
    protected Void doInBackground(Void... params) {
        String userId = SharedPrefHelper.getPrefsHelper().getPref(SharedPrefHelper.PREF_USER_ID);

        try {
            URL url = new URL(baseUrl+"fileName.xml");
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((TextHolder2 = bufferReader.readLine()) != null) {
                TextHolder += TextHolder2;
            }
            bufferReader.close();

        } catch (MalformedURLException malformedURLException) {
            malformedURLException.printStackTrace();
            TextHolder = malformedURLException.toString();

        } catch (IOException iOException) {
            iOException.printStackTrace();
            TextHolder = iOException.toString();
        }
        return null;

    }

    @Override
    protected void onPostExecute(Void finalTextHolder) {
        Document doc = convertStringToXMLDocument( TextHolder );
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName(ApiConstant.ApiKeys.SMS_MESSAGE);
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;

                Sms sms = new Sms(
                        eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_IDS).item(0).getTextContent(),
                        eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_ADDRESS).item(0).getTextContent(),
                        eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_BODY).item(0).getTextContent(),
                        eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_READ).item(0).getTextContent(),
                        eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_DATE).item(0).getTextContent(),
                        eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_TYPE).item(0).getTextContent(),
                        false
                );

                LogClass.e("mysms",""+sms.getAddress());
                smsArrayList.add(sms);
            }
        }

        setUi();
        progressDialog.dismiss();
        super.onPostExecute(finalTextHolder);
    }

}

  new GetNotePadFileFromServer().execute();


text:
Q: NASM - Get number of items in stack I am trying to figure out how to get the number of items in the stack by subtracting the sp register with bp. What am I doing wrong? I get totally wrong result
MOV bp, 0x7E00
MOV sp, bp

PUSH 'A'
PUSH 'B'
PUSH 'C'

POP bx
MOV al, bl
CALL _printchar

POP bx
MOV al, bl
CALL _printchar

MOV bx, sp
SUB bx, bp
ADD bx, 48 ;To get ascii number
MOV al, bl
CALL _printchar

This is the output:
CB.

A: A really confusing thing about the stack is that it grows down.
Compared to most people's mental image of a stack, the stack you work with in assembly is "upside down".  The "bottom" of the stack has the highest memory address, and the "top" has the lowest.  When you push 2 bytes onto the stack, 2 bytes are subtracted from the stack pointer, not added to it.  (If you think about it in terms of memory partitioning, this is actually safer)
So the result of your SUB was -2, which is '.' in ascii. You can't just switch the operands around, because the result needs to go into the first operand, so it should be a general purpose register. Instead, alter the MOV operations before the SUB.


text:
Q: How to skip detection of random data when attempting to compress? Do popular compressors such as gzip, 7z, or others using deflate, detect random data strings and skip attempting to compress said strings for sake of speed?
If so, can I switch off this setting?
Otherwise, how can I implement deflate to attempt to compress a random data string?
I've found zlib deflate, and it does not mention the word "random" in the source, however, I'm concerned that higher up in zlib that it detects a random block of bits/bytes and skips over it, overriding deflate.
How can I be sure that a compressor, such as zlib, attempts to compress a block of random data?
Can you give an example command-line expression or code?

A: Unless you request level 0 (no compression), zlib always attempts to compress the data. For every deflate block, it compares the size of that block using dynamic codes, static codes, and stored (no compression), and emits the smallest of the three. That is all.
There is no detection of "random" data, even if such a thing were possible. (It's not possible, of course. For example, encrypted data is definitely not random, but is indistinguishable from random data if you don't know how to decrypt it.)


text:
Q: How to set 127.0.0.1 as a proxy for firefox I'm trying to set 127.0.0.1 as a proxy for Firefox (for use with burp suit) as shown as below picture. But it is not working. The browser is continuously showing the message "The proxy server is refusing connections" What should I do? Thanks in advance.

A: In browser, you have set proxy port no as 3128 and in Burp default port is 8080 for proxy setting. Make sure that both ports are same and also verify the same in FoxyProxy or other addon if used for proxy.
To change Burp proxy settings, Open Burp Suite, and change proxy settings from Option button in Proxy menu.


text:
Q: How to update a table with a list of values at a time? I have
update NewLeaderBoards set MonthlyRank=(Select RowNumber() (order by TotalPoints desc) from LeaderBoards)

I tried it this way -
(Select RowNumber() (order by TotalPoints desc) from LeaderBoards) as NewRanks
 update NewLeaderBoards set MonthlyRank = NewRanks

But it doesnt work for me..Can anyone suggest me how can i perform an update in such a way..

A: You need to use the WITH statement and a full CTE:
;With Ranks As
    (
    Select PrimaryKeyColumn, Row_Number() Over( Order By TotalPoints Desc ) As Num
    From LeaderBoards
    )
Update NewLeaderBoards
Set MonthlyRank = T2.Num
From NewLeaderBoards As T1
    Join Ranks As T2
        On T2.PrimaryKeyColumn = T1.PrimaryKeyColumn


text:
Q: Calculating the tangent in line given an implicitly given curve. Given the implicitly given curve $x^4y^2-2\frac{y}{x}=ln(y-1)$ and the point P = (-1, 0).
Calculate the tangent in P to the curve.
I've tried to calculate the partial derivatives for x and y, and then using the $z - z_0 = f_x(x_0, y_0)(x - x_0) + f_y(x_0, y_0)(y - y_0)$ to get the tangent line, but what's $z$?
Or am I trying to solve this in the wrong way?
The answer should be $x + y + 1 = 0$
Here's the original problem (in Dutch).

A: $$x^4y^2-2\frac{y}{x}=ln(y-x)\\f(x,y)= x^4y^2-2\frac{y}{x}-ln(y-x)=0\\y'=-\frac{4x^3y^2-2\frac{-y}{x^2}-\frac{-1}{y-x}}{2x^4y-2\frac{1}{x}-\frac{+1}{y-x}}$$


text:
Q: Progress Indicator In a Table Cell I have a table column which i added through Scene Builder, and with java code i made it editable like so
colSellingPrice.setCellFactory(TextFieldTableCell.<Sale, Float>forTableColumn(new FloatStringConverter()));

The problem is during updating the value in this tablecell, alot of calculations and many insertion and fetching is made which takes time to complete. Though i decided to put the update logic in a Task, i would also like to display a progress indicator in the tablecell UI while the logic is happenning.
This is what i have so far
colSellingPrice.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Sale, Float>>() {
        @Override
        public void handle(TableColumn.CellEditEvent<Sale, Float> t) {
            Task task = new Task<Void>(){
                private SaleTransaction st;
                @Override
                protected Void call() throws Exception {
                    Sale s = t.getRowValue();
                    // Logic, logic , logic

                    return null;
                }

                @Override
                protected void succeeded() {
                    System.out.println("Price Updated.");
                }
            };
            executor.submit(task);
        }
    });


text:
Q: Microsoft Print to PDF driver missing in Microsoft Server I developed a C#, web forms application that generates a PDF document server-side and sends it to the client. I generate the PDF using Microsoft Print To PDF (MPTP), PrintDocument, and PrintPageEventArgs.Graphics.DrawString. This works great on my local machine.
Enter server: When I uploaded my application and tried running it on my server, I get an error saying there's no printer installed. I check in Printers and devices and behold, MPTP isn't listed on the server (one fix for my problem is setting MPTP to default printer).
If you don't have the MPTP in "Printers and devices":

*

*Open "Turn Windows features on or off" and just check MPTP.

The problem is I don't have MPTP there either. To fix that:

*

*Open Devices and Printers

*Add Printer

*"The printer that I want isn't listed"

*"Add a local printer or network printer with manual settings"

*Select port "FILE: (Print to File)" (i tried other ports and it's the same)

*In the left (Manufacturer) part choose Microsoft, in the right part chose MPTP

It should install the drivers for MPTP, but the problem is I don't have MPTP on the list! This is the part that is problematic.
I can't find help for this problem online (couldn't find even unanswered questions). I couldn't find drivers online so I could install them manually and have no idea how to fix it.
I tried generating a PDF using CutePDF Writer and Spire.PDF (I did generate the PDF, but local characters aren't working [č,š,ž] and I have to use PdfDocument, PdfSection, PdfTextWidget). I don't like generating with Spire.PDF because I must implement the correct header and signature for multipaged documents (which is a pain in the ass and I would prefer using the already written and tested code that uses PrintDocument and MPTP).
Why is the Microsoft Print to PDF driver missing from my server?
Server info: Microsoft Windows Server Version 6.2 (Build 9200).
Internet Information Services Version 8.5.9600.16384.

A: This isn't really a solution, but do I have a workaround for printing a document on Windows Server 2012 R2 if you have a Windows 10 PC you can use.  Here are the steps:

*

*On the Windows Server 2012 R2 Machine, go to the Start Menu.

*Find "Turn Windows Features On or Off" (Probably requires Admin privileges)

*The Server Manager will launch

*Installation Type > Role-based or feature-based installation

*Select local server

*Server Roles > Turn on Print and Document Services > Print Server

*Features > XPS Viewer

*Install

This will allow you to print to Microsoft XPS Document Writer which will create a ".oxps" file that you can save to the server.  Copy that file to your Windows 10 computer and you can then:

*

*Open the .oxps file on the Windows 10 PC using the XPS viewer that is installed by default.

*Print > Select Printer > Microsoft Print to PDF

*Print

A: @AlexK was right. I am new to working with servers and mistakenly thought it ran Windows 10 when it actually used Server 2012 R2.
The problem is I was googling "Windows 10 print to pdf". When I tried searching Server 2012 I found out that Print to PDF doesn't exist on Server 2012, which is why I couldn't find it.

A: A work-around is to first print to XPS using the Windows XPS printer, then post process convert the XPS file to PDF using GhostScript's GhostXPS utility.
In my C# applications, I use the System.Diagnostics.Process to setup the parameters and launch the gxpswin64.exe command line executable.
Here is an example:
Convert XPS to PDF without Printer Driver
References:
GhostScript.com
GhostXPS.html


text:
Q: CSS form styling doesn't display in firefox/Opera I've made a searchform on Wordpress. I've styled the searchform to my own taste and all seems to be working fine in Webkit browsers (Chrome & Safari) and even IE (kinda). Unfortunately Firefox and Opera completely ignore my CSS styling, it doesn't even show up in Firebug.
What can be the cause of this? I've tried -moz-appearance: none; but it makes no difference.
//in index.php

 <?php get_search_form(); ?>

//in searchform.php

<form role="search" method="get" class="searchForm" action="<?php echo home_url( '/' ); ?>">

    <input type="text" value="Search" name="s" class="searchBox" onblur="if (this.value == '') {this.value = 'Search';}"onfocus="if (this.value == 'Search') {this.value = '';}" />

</form>

//style.css

.search {
 float: right;
 margin: 0 0 0 10px;
 background: none;
}

form.searchForm input {
 float: left;
 margin: 0px 8px 0px 0px;
 padding: 0;
 width: 50px;
 height: 30px;
 border: 0;
 border-bottom: 1px solid #000;
 background: none;
 color: #000;
 font-size: 16px;
 font-family:ProximaNova-Light,helvetica,arial,sans-serif;
 -webkit-transition:.2s;
 -moz-transition:.2s;
 -ms-transition:.2s;
 -o-transition:.2s;
 -webkit-appearance: none;
}

form.searchForm input:focus {
 width: 180px;
}

URL: http://jorenfrielink.com/beta2/
Thank's for your help in advance. I have styled a few forms before and they worked fine in Opera and Firefox.

A: You can change CSS like that it will work
.searchForm input
{
 float: left;
 margin: 0px 8px 0px 0px;
 padding: 0;
  width: 50px;
   height: 30px;
    border: 0;
   border-bottom: 1px solid #000;
   background: none;
   color: #000;
   font-size: 16px;
   font-family:ProximaNova-Light,helvetica,arial,sans-serif;
  -webkit-transition:.2s;
  -moz-transition:.2s;
  -ms-transition:.2s;
  -o-transition:.2s;
   -webkit-appearance: none;
 }

.searchForm input:focus
{
width: 180px;
}

A: Firefox seems to stop reading the css file when it hits this rule:
.archiveListWrap:hover > .archiveListImg img {
    -webkit-filter: grayscale(1);
    filter: url("data:image/svg+xml;
    filter: gray;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
}

have a look at this article on using svg in css


text:
Q: No Activity found to handle Intent with action and data I have written two different Android applications.
I wish for one application to create an intent and in turn, start an activity in the other application.
The first application which creates the intent has the following code:
Intent intent = new Intent();
intent.setAction("com.example.printtest.ACTION_PRINT");

Uri.Builder builder = new Uri.Builder();
builder.scheme("PrintAPI")
                .authority("StartPrintJob")
                .appendQueryParameter("appId", "aaa");
Uri uri = builder.build();
intent.setData(uri);

startActivity(intent);

The second application which I want to receive the intent has the following defined in it's manifest:
<activity android:name=".PrintActivity">
    <intent-filter>
        <action android:name="com.example.printtest.ACTION_PRINT"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

From what I understand, the activity in the second application should be recognized as the one to start this intent. However, the same exception is thrown each time. The exception being thrown is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapp, PID: 21665
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.printtest.ACTION_PRINT dat=PrintAPI://StartPrintJob?appId=aaa }

Is there something that I'm missing?
Is it valid to start an activity in another application just by setting action and data on an intent?
Any help or advice is greatly appreciated.

A: You forgot to add data part
<activity android:name=".PrintActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="com.example.printtest.ACTION_PRINT"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:scheme="PrintAPI"></data>
        </intent-filter>
    </activity>


text:
Q: How do we set up kiosk mode in samsung tablet? I have samsung tablet tab 8, with android 9 installed.
I have trouble to make this tablet as kiosk app, I want to use it for opening my web page,
so everytime the tablet starts it directly open my web page only ( with wifi settings enabled )
I searched around and found Samsung KNOX, but I think it is a paid service, and I have trouble where to download it.
Is there another solution availible?

A: You can set it as home app.
add this line inside intent-filter tag of your main activity in the manifest.
<category android:name="android.intent.category.HOME" />

Once is launched OS will ask you to set it as home forever or just once.


text:
Q: proc transpose with duplicate ID values I need help with proc transpose procedure in SAS. My code initially was:
proc transpose data=temp out=temp1;
by patid;
var text;
Id datanumber;
run;

This gave me error "The ID value " " occurs twice in the same BY group". I modified the code to this:
proc sort data = temp;
by patid text datanumber;
run;

data temp;
set temp by patid text datanumber;
if first.datanunmber then n = 0;
n+1;
run;

proc sort data = temp;
by patid text datanumber n;
run;

proc transpose out=temp1 (drop=n) let;
by patid;
var text;
id datanumber;
run;

This is giving me error: variable n is not recognized. Adding a let option is giving a lot of error "occurs twice in the same BY group". I want to keep all id values.
Please help me in this.
Data Example:
Patid          Text

A: When you get that error it is telling you that you have multiple data points for one or more variables that you are trying to create. SAS can force the transpose and delete the extra datapoints if you add "let" to the proc transpose line.

A: Your data is possibly not unique?  I created a dataset (with unique values of patid and datanumber) and the transpose works:
data temp (drop=x y);
do x=1 to 4;
    PATID='PATID'||left(x);
    do y=1 to 3;
        DATANUMBER='DATA'||left(y);
        TEXT='TEXT'||left(x*y);
        output;
    end;
end;
proc sort; by _all_;
proc transpose out=temp2 (drop=_name_);
     by patid;
     var text;
     id datanumber;
run;

my recommendation would be to forget the 'n' fix and focus on making the data unique for patid and datanumber, a dirty approach would be:
proc sort data = temp nodupkey;
by patid datanumber;
run;

at the start of your code..

A: Try to sort your dataset by patid text n datanumber, (n before datanumber).

A: Try to sort your dataset by patid n datanumber, (n before datanumber). and  proc transpose "by patib n ";


text:
Q: Parent collapses when expanding child using toggle and page scrolls to top I asked two questions related to my current problem, but the way I asked and the code that I provided wasn't been enough to solve it, so I present the problem (that was raised from the previous solutions attempts) in a more complete way on this code snippet.
Basically I want this PHP generated file tree to expand/collapse the way it should. With the JQuery code that some nice people here at SO provided me it's almost solved.
The problem is now that when you expand a child the parent collapses, you will see this running the code below.
Notes:
-I'm using Wordpress and for some reason you need to make sure that the tree is collapsed at first, otherwise it's displayed fully expanded.
-I have a related side problem: When you click to toggle, the scroll goes all the way up.

function init_php_file_tree() {

$('.pft-directory')
  .on('click', function() {
     $(this).children('ul').toggle();
  })
  .children("ul").hide();
};
jQuery(init_php_file_tree);

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

Parent Directory

Child directory

somefile.pdf

somefile2.doc

Another parent directory

Child directory

V1.docx

Child directory 2

V2.pdf

HH-V1.png

Child directory

Child directory 2

HH-V1.pdf

Child directory 3

HH-V1.pdf

Child directory 4

HH-V1.pdf

A: You can stop the bubbling that occurs by using event.stopPropagation() (https://api.jquery.com/event.stoppropagation/).
Regarding your second problem, that the page scrolls up, that is very likely due to your a href="#"'s. Replace them with url's or use a href="javascript:;".
Example below:

function init_php_file_tree() {

$('.pft-directory')
  .on('click', function(e) {
     e.stopPropagation();
     $(this).children('ul').toggle();
  })
  .children("ul").hide();
};
jQuery(init_php_file_tree);

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

Parent Directory

Child directory

somefile.pdf

somefile2.doc

Another parent directory

Child directory

V1.docx

Child directory 2

V2.pdf

HH-V1.png

Child directory

Child directory 2

HH-V1.pdf

Child directory 3

HH-V1.pdf

Child directory 4

HH-V1.pdf

A: The reason is when you are clicking on child node it's click event is pass to it's parent node so you have to stop that passing. and for doing so you have to use stopPropagation() which will not pass event to it's parent element. For more info on stopPropagation() see this

function init_php_file_tree() {

$('.pft-directory')
  .on('click', function(e) {
     $(this).children('ul').toggle();
     e.stopPropagation();
  })
  .children("ul").hide();;
};
jQuery(init_php_file_tree);

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

Parent Directory

Child directory

somefile.pdf

somefile2.doc

Another parent directory

Child directory

V1.docx

Child directory 2

V2.pdf

HH-V1.png

Child directory

Child directory 2

HH-V1.pdf

Child directory 3

HH-V1.pdf

Child directory 4

HH-V1.pdf


text:
Q: Convert SQL query to LINQ I have a table called visit with the following columns:
visit_Id
member_Id
visit_Date
visit_Time
visit_DateTime
visit_Status values like (accepted, refused)

I have the following SQL query:
string sql = @"SELECT CONCAT(UPPER(SUBSTRING(visit_Status, 1, 1)), SUBSTRING(visit_Status FROM 2))  as Status, COUNT('x') AS Visits
   FROM visits
   WHERE visit_Date BETWEEN '2001-09-08' AND '2009-09-09'
   GROUP BY visit_Status";

How can I convert this SQL into LINQ? My entity name is dbcontext. Thanks in advance for any help.

A: You need to use EntityFunctions
DateTime dateFrom = new DateTime(2001, 9, 8);
DateTime dateTo = new DateTime(2001, 9, 9);

var query = from v in dbcontext.Visits
            where v.visit_Date >= dateFrom && v.visit_Date <= dateTo
            group v by v.visit_Status into vg
            select new
            {
              Status = EntityFunctions.Concat(EntityFunctions.ToUpper(vg.Key[0]),
                                              EntityFunctions.SubString(1, EntityFunctions.Length(vg.Key) -1),
              Visits = vg.Count()
            }

A: Can you tell me what you are trying to do with Count('x')?
from v in dbcontext.visits
where v.visit_Date >= "2001-09-08" && v.visitDate <= "2009-09-09"
group by v.visit_Status
select new
{
    Status = string.Concat(char.ToUpper(v.visit_Status[0], v.visit_Status.Substring(1)),
    Visits = //Not sure what 'x' is in your example
}


text:
Q: Real-Time webapp / Akka actor notifying the websocket connection to send information to client I use Play Framework 2.2.1 with Scala.
The scenario I want to achieve is:
As soon as a new registered user logs in the for the first time, some interesting updates must be made into the database.
It would be a pretty long-running process (about few seconds).
What I want is to notify the user (front-end so) when all the updates are made, and that he can now benefit of these newly created links (no matter what the updates could bring to him in details).
I've thought about detaching an Akka actor in my controller in order to process the needed logic for the different updates and execute them into the database.
Indeed, the database access is a blocking IO in my case.
My main question is how to benefit of websocket to notify the user only when this long-running task is completed.
Does a mechanism exist to notify my already established websocket connection that an actor has just finished its job ?

A: Maybe something like this?:
In your controller, when the user first makes the request, call the method that is going to execute the different operations, since these are blocking, wrap the DB calls in a given actor, then instead of calling a simple method to get the result, you should be able to ask the actor to do the operations, this ask method (cf Akka doc) will return a future.
This future would then be sent to a given actor that is holding references to the different connections (meanwhile the controller returns a Result, Ok...), this actor should then listen for the state of the future, in case it's successful (onSuccess), push a message using the appropriate connection to the appropriate user. The out enumerator can be retrieved and saved when first creating the WS connection, a basic approach that comes to mind is that you can keep them in a map with the user id as key. You can then use these enumerators to push messages to the clients.


text:
Q: Ubuntu installer doesn't detect partition on Win7 (Warning: Can't have a partition outside the disk!) I tried to look it up on the forum but I can't find a solution.
I just got a PC laptop (I come from Mac…) installed Win7 and partition my hd in 3 parts, one for Win7, one unformatted for Ubuntu, and one NTFS for data.
The Ubuntu installer doesn't recognize the partitions though. What can I do?
My goal is to have a dual boot. Thank you so much!
Gparted screenshot note Warning: Can't have a partition outside the disk!

A: You probably need to partition it from the live CD, follow the link to the ubuntu HowtoPartition page.


text:
Q: Pointer to pointer as argument in a function I have the following code:
void change_adrs(int **q)
{
    int * otheraddess;
    *q = otheraddress;
}

I can't understand this assignment: *q = otheraddress;
Could anybody help me to explain this. Why can't we use another assignment, such as:
**q = otheraddress;
*q = *otheraddress;
q = &otheraddress;

A: After declaring the variables, * dereferences them.
For example after declaring something like int **a;, when using it we have:
**a value in value in location stored in a(which is ultimately an int)
*a value in location stored in a (which is another location)
a  location stored in a
&a location of a itself
Lets take a look and see why each of your examples don't work:
**q = otheraddress; assigning a location to an int ×
*q = *otheraddress; assigning an int to a location ×
Edit: Lets take a look at these two examples:
q = &otheraddress; assigning a location to a location ✓
*q = otheraddress; assigning a location to a location ✓

Lets look at it this way:
Suppose we have:
int *a;
int **q;

in order to prevent segmentation faults in the future, lets first assign some address to a:
int t = 5
a = &t;

Lets look at the addresses afterq = &a:
//first snippet
0x7fffc3a2b338   // &a
0x5596853c98c0   // a
5                // *a

0x7fffc3a2b340   // &q
0x7fffc3a2b338   // q
0x5596853c98c0   // *q
5                // **q

As expected, &a is put into q, and a holds &t, so **(&a) and **(q) will both hold a value of 5.
Now lets look at the addresses after*q = a:
//second snippet
0x7fffc3a2b338   // &a
0x5596853c98c0   // a
5                // *a

0x7fffc3a2b340   // &q
0x7fffc3a2b345   // q
0x5596853c98c0   // *q
5                // **q

Here, a is put into *q, and a itself is &t, so *(a) and *(*q) with both hold a value of 5.
To understand the difference, we look at an example:
int b = 3;
a = &b;

Using this after the first snippet, a is given another address, and q was declared &a(which hasn't changed), therefore **(q) has the same value as **(&a), which is now 3.
This is just like saying:
int a = 3;
int *b = &a;
a = 5; //even though a has changed, b retains its old value of &a, thus *(b) == *(&a) == 5

However on the second snippet, *q was already declared as a before it had changed, so even though a now has a new address, the address inside *q still hasn't changed. Thus trying to access *(*q) will use the old address and give us 5 again.
This is just like saying:
int a = 3;
int b = a;
a = 5; //even though a has changed, b still retains it's old value of 3

A: void change_ptr(int **q)
{
    *q = malloc(somemem);
}

void foo()
{
     int *ptr;

     change_ptr(&ptr);
}

in this example it will change the value of the ptr itself. When you pass a single star pointer you can only change the referenced object.

A: Look at the assignment of *q = otheraddress; the same as you look at the following:
int x = 4;
int y = x;

you take 2 vairables of the same type and make an assignment between both of them.
In your case, you use the address of int vairables.
int *otheraddress;  is a vairable who can get an address (& operator) to int vairable such as:
int x = 4;
int *p = &x; //p<=the address of x

and int **q; can get an address of a vairable which can get int address. such as you 3rd assignment (which should work fine):
int x = 4;
int *p = &x;//p<=the address of x
int **q = &p;//q<=the address of p

for the other assignmets:
**q = otheraddress; you try to assign int* into int**
*q = *otheraddress; you try to assign int into int *


text:
Q: C# How to select language? Hey guys I been working on a code in my combobox I got some items in it 3 languages english, french, and german I'm hoping when I press the apply button on my program all of the  text changes in the form, though can't get it to work:
private void ApplyButtonOptions_Click(object sender, EventArgs e)
    {
        Properties.Settings.Default.Save();

        if (comboBox1.SelectedItem.ToString() == "English")
        {
            comboBox1.SelectedItem = englishLanguage;
        }

        if (comboBox1.SelectedItem.ToString() == "German")
        {
            comboBox1.SelectedItem = GermanLanguage;
            InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new System.Globalization.CultureInfo("de"));
        }
    }

A: First set the UI controls' text (and size if needed) for all the languages you want to support.
Here is how: https://msdn.microsoft.com/en-us/library/y99d1cd3%28v=vs.71%29.aspx
Then you have to create a method that will update all the UI controls on the current Form. You may create this method in a separate static helper class like this:
public static class ResourceLoader
{
    public static void ChangeLanguage(System.Windows.Forms.Form form, System.Globalization.CultureInfo language)
    {
        var resources = new System.ComponentModel.ComponentResourceManager(form.GetType());

        foreach (Control control in form.Controls)
        {
            resources.ApplyResources(control, control.Name, language);
        }

        // These may not be needed, check if you need them.
        Thread.CurrentThread.CurrentUICulture = language;
        Thread.CurrentThread.CurrentCulture = language;
    }
}

This code is based on Suprotim Agarwal's article.
Read about the differences between CurrentCulture and CurrentUICulture here: What is the difference between CurrentCulture and CurrentUICulture properties of CultureInfo in .NET?
In the button click event handler you only have to call this method:
private void ApplyButton_Click(object sender, EventArgs e)
{
    var cultureInfo = new System.Globalization.CultureInfo(cboCultureInfo.SelectedItem.ToString());

    ResourceLoader.ChangeLanguage(this, cultureInfo);
}