Q: LineChart with annotations and multiple graph lines I'm using Google Charts to try and create a line chart that looks like the first one labelled Example:
https://developers.google.com/chart/interactive/docs/gallery/linechart
However, I cannot use google.visualization.arrayToDataTable() as shown in the 1st example.
The problem is I want to add annotations and annotationText to each plotted point.  The documentation says I must use:
google.visualization.DataTable()
In order to do that, i must do the following:
    var data1 = [
      [ 'C'   ,4, 'o', 'note'],
      [ 'D'   ,6, 'o', 'note'],
      [ 'O'   ,4, 'o', 'note']
    ];
    var chartData = new google.visualization.DataTable();

    chartData.addColumn('string', 'X'); // Implicit series 1 data col.
    chartData.addColumn('number', 'DOGS'); // Implicit domain label col.
    chartData.addColumn({type:'string', role:'annotation'});
    chartData.addColumn({type:'string', role:'annotationText'});

    chartData.addRows(data1);
    var chart = new
          google.visualization.LineChart(document.getElementById('visualization'));

    var options = {
             title: "My Title",
    };
    chart.draw(chartData,options);

This gives me one line of plotted data.
How do I adapt this to allow me to add a 2nd line of plotted data?goo

A: You have to add additional columns and expand your data. For example:
    chartData.addColumn('string', 'X'); // Implicit series 1 data col.
    chartData.addColumn('number', 'DOGS'); // Implicit domain label col.
    chartData.addColumn({type:'string', role:'annotation'});
    chartData.addColumn({type:'string', role:'annotationText'});
    chartData.addColumn('number', 'CATS'); // Implicit domain label col.
    chartData.addColumn({type:'string', role:'annotation'});
    chartData.addColumn({type:'string', role:'annotationText'});

    var data1 = [
        [ 'C', 4, 'Dog1', 'Dog1 note',  7, 'Cat1', 'Cat1 note'],
        [ 'D', 6, 'Dog2', 'Dog2 note', 11, 'Cat2', 'Cat3 note'],
        [ 'O', 4, 'Dog3', 'Dog3 note', 13, 'Cat3', 'Cat3 note']
    ];

    chartData.addColumn('string', 'X'); // Implicit series 1 data col.
    chartData.addColumn('number', 'DOGS'); // Implicit domain label col.
    chartData.addColumn({type:'string', role:'annotation'});
    chartData.addColumn({type:'string', role:'annotationText'});
    chartData.addColumn('number', 'CATS'); // Implicit domain label col.
    chartData.addColumn({type:'string', role:'annotation'});
    chartData.addColumn({type:'string', role:'annotationText'});

    var data1 = [
        [ 'C', 4, 'Dog1', 'Dog1 note',  7, 'Cat1', 'Cat1 note'],
        [ 'D', 6, 'Dog2', 'Dog2 note', 11, 'Cat2', 'Cat3 note'],
        [ 'O', 4, 'Dog3', 'Dog3 note', 13, 'Cat3', 'Cat3 note']
    ];

    chartData.addRows(data1);

See example at jsBin


Q: how to sample from multiple lists (numbers? I would like to sample, let's say the ages of 100 persons above 65 years old,
and the probabilities for the age groups are as follows:
65-74<- 0.56
75-84<- 0.30
85<- 0.24

I know the existence of the sample function and I tried it as follows,but that didn't work unfortunately
list65_74<-range(65,74)
list75_84<-range(75,84)
list85<-range(85,100)

age<-sample(c(list65_74,list75_84,list85),size=10,replace=TRUE,prob =c(0.56,0.30,0.24 ))I get the following error

I got then the following error
 Error in sample.int(length(x), size, replace, prob) :
      incorrect number of probabilities

So I was wondering what is the proper way to sample from multiple lists.
Thank you very much in advance!

A: First, let's I'll call those three objects groups instead since they don't use the list function.
The way you define them could be fine, but it's somewhat more direct to go with, e.g., 65:74 rather than c(65, 74). So, ultimately I put the three groups in the following list:
groups <- list(group65_74 = 65:74, group75_84 = 75:84, group85 = 85:100)

Now the first problem with the usage of sample was your x argument value, which is

either a vector of one or more elements from which to choose, or a
  positive integer. See ‘Details.’

Meanwhile, you x was just
c(list65_74, list75_84, list85)
# [1]  65  74  75  84  85 100

Lastly, the value of prob is inappropriate. You supply 3 number to a vector of 6 candidates to sample from. Doesn't sound right. Instead, you need to assign an appropriate probability to each age from each group as in
rep(c(0.56, 0.30, 0.24), times = sapply(groups, length))

So that the result is
sample(unlist(groups), size = 10, replace = TRUE,
       prob = rep(c(0.56, 0.30, 0.24), times = sapply(groups, length)))
# [1] 82 72 69 74 72 72 69 70 74 70


Q: What happens if I use CClientDC in OnPaint() function? I am new to MFC and Windows programming in general and this is something I haven't understood
Everywhere I have been reading it says not to use CClientDC in OnPaint and only use CPaintDC
In my code, I append my rectangle drawing functions to the default OnPaint() handler created when I make a dialog based MFC application using the wizard
void Cgraph_on_dlgboxDlg::OnPaint()
{
    CPaintDC dc(this); // ----------------------------> LINE 1
    if (IsIconic())
    {
        // CPaintDC dc(this); // device context for painting // ----------------------------> LINE 2

        SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;

        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialogEx::OnPaint();
    }

    COLORREF pencolour = RGB(0, 0, 0);
    COLORREF brushcolour = RGB(0, 0, 255);
    CPen pen(PS_SOLID, 5, pencolour);
    CBrush brush(HS_CROSS, brushcolour);
     // CPaintDC Dc(this);      // ----------------------------> LINE 3
     // CClientDC Dc(this);     // ----------------------------> LINE 4
    dc.SetBkMode(TRANSPARENT);
/****
get rectangle coordinates and properties
****/
    dc.Rectangle(CRect(point1, point2));
}

In this code, originally, LINE 1 doesn't exist. In this case, the program draws a rectangle if CClientDC is declared in LINE 4, but does not draw anything in CPaintDC in LINE 3 is enabled. If the CPaintDC in LINE 2 is removed to LINE 1 and LINE 3 and 4 are commented out, it works. Why is this happening? From what I understood, CClientDC should not work at all here, or am I missing something?
Again, shouldn't the CPaintDC in LINE 2 have it's scope within the if block only? Why does declaring CPaintDC twice create no output at all?

A: The CPaintDC constructor calls BeginPaint to get a DC that is clipped to the invalid area (the area that needs painting). Constructing a second CPaintDC gets an empty invalid area, so it can't paint anything.
The default code constructs a CPaintDC only at line 2 because it is not going to call CDialogEx::OnPaint when the dialog is minimized. When the dialog is not minimized then CDialogEx::OnPaint will construct a CPaintDC. One and only one CPaintDC can be used for any particlular call to OnPaint.
You can use CClientDC to paint your rectangle, as long as you leave the original treatment of CPaintDC as it was.


Q: My CSS works in the inline section but not as an external stylesheet I am currently trying to use CSS to stylize my application in Apex 5. The problem I am having is that when I write my CSS code in the "inline" section of any page in the application, then the CSS code works, but if I write the CSS code on Notepad and then upload the file and reference the file within my application, then the CSS code does not work. I have written several lines of CSS code, so I'll just post one small section of it as a sample so that you all can see my format:
body{
  font: bold 12px/16px "Times New Roman";
}

I have uploaded the file in the Static Application Files section of the Shared Components page of the application. I have then tried referencing the file in different places, such as at the page level and user interface level, but nothing has worked so far. I'm very new to CSS, so any insight would be greatly appreciated. Thank you in advance!

A: After uploading the file have to be displayed in the list of static files. The list of files have a column Reference, which contain a string like this: #APP_IMAGES#test.css. Copy this string and put it, for example, on the page in the section CSS - File URLs. This should work.
Then make sure that file reference works. Open your page and take a look on a list of CSS files. The same functionality is present in all browsers, but it is accessible by different ways. In IE:

*

*Press F12.

*Open Network tab.

*Press "Enable network traffic capturing" (a green triangle in the left top corner).

*Reload the page. A list of files appears.

*Find your file in a list:

*

*If the file is not present, then you copied an incorrect link, or you copied it into an incorrect place, etc.

*If the file is present, normally it should have status 200 (the Result column). If a status is not 200, there could be a lot of reasons (depending on the status).

*If the file is present with the status 200, your CSS property doesn't work, because it is overridden with another CSS. To define with which one, go to the Dom Explorer tab.

A: You can try this approach:

*

*On server, go to ORACHE_HOME/apex/images/css (path can be different, but you can find it by .css extension)

*Put you file here

*Id editor, in page properties, go to the CSS -> File URLs section

*Write path like this: /i/css/new.css (i - in general, alias for your images directory)


Q: Rendering VTK visualization using OpenCV instead Is it possible to get a rendered frame from a VTK visualization and pass it to OpenCV as an image without actually rendering a VTK window?
Looks like I should be able to follow this answer to get the rendered VTK frame from a window and then pass it to OpenCV code, but I don't want to render the VTK window. (I want to render a PLY mesh using VTK to control the camera pose, then output the rendered view to OpenCV so I can distort it for an Oculus Rift application).
Can I do this using the vtkRenderer class and not the vtkRenderWindow class?
Also, I'm hoping to do this all using the OpenCV VTK module if that is possible.
EDIT: I'm starting to think I should just be doing this with VTK functions alone since there is plenty of attention being paid to VTK and Oculus Rift paired together. I would still prefer to use OpenCV since that side of the code is complete and works nicely already.

A: You must make your render windows to render offline like this:
renderWindow->SetOffScreenRendering( 1 );
Then use a vtkWindowToImageFilter:
vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter =
   vtkSmartPointer<vtkWindowToImageFilter>::New();
windowToImageFilter->SetInput(renderWindow);
windowToImageFilter->Update();

This is called Offscreen Rendering in VTK. Here is a complete example

A: You can render the image offscreen as mentioned by El Marce and then convert the image to OpenCV cv::Mat using
unsigned char* Ptr = static_cast<unsigned char*>(windowToImageFilter->GetOutput()->GetScalarPointer(0, 0, 0));

cv::Mat RGBImage(dims[1], dims[0], CV_8UC3, Ptr);


Q: What's the Intent to open DND settings? I'm sure I'm overlooking something in the Settings class documentation. What Intent can open the Settings app in the "Do not disturb" section?
I expected it to be the ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS action, but that is only for the screen which lists which apps have requested DND access.

A: Update
Looking at the AndroidManifest.xml for the Settings app there is an Activity Settings$ZenModeSettingsActivity already from Android 5.0.
To send the user to the "Do not disturb" screen you can use the action android.settings.ZEN_MODE_SETTINGS like this:
try {
    startActivity(new Intent("android.settings.ZEN_MODE_SETTINGS"));
} catch (ActivityNotFoundException e) {
    // TODO: Handle activity not found
}

Original answer
It looks like there are no screens in the Settings app (at least on Android 6+7) where you can enable/disable DND. It seems like this is only available through the settings tile (and can be disabled in the dialog when changing the volume).
I have a Samsung S6 (Android 6.0.1) which has this screen, but this is probably some custom Samsung changes. The screen is represented by the class com.android.settings.Settings$ZenModeDNDSettingsActivity which can be started by any app. This might be of help for some people out there.
AndroidManifest.xml for Settings app for Android 6+7:

*

*https://android.googlesource.com/platform/packages/apps/Settings/+/android-6.0.1_r68/AndroidManifest.xml

*https://android.googlesource.com/platform/packages/apps/Settings/+/android-7.0.0_r6/AndroidManifest.xml

A: You have to use the following Intent: ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE and then pass a boolean through EXTRA_DO_NOT_DISTURB_MODE_ENABLED.
Make note that the documentation specifies the following: This intent MUST be started using startVoiceActivity.


Q: Complicated MySQL Query with distinct Here is the table I am getting the data from "actually it's a view of two different tables"

*

*The first table is the users table the holds everything about the user.

*The second is a log table that logs who viewed the video and when they viewed it.
log_views.id,
log_views.user_id,
log_views.video_id,
log_views.date,
users.user_key,
users.name_display,
users.img_key

What I am trying to is display the last 18 users to view a video but I don't want any duplicate users. So if a user shows up twice in the last 18 I only want his latest view and then skip all the others.
I tried using the DISTINCT keyword but I am getting more than one column so it didn't work.

A: Have a look at these for some pointers:
MySQL Group By with top N number of each kind
http://explainextended.com/2009/03/06/advanced-row-sampling/

A: This is what i ended up using.
recent_video_viewers is the name of the view I made so i didn't have to do any joins
SELECT id, MAX(date), user_id, img_key, random_key
FROM recent_video_viewers
WHERE video_id = '$vr[id]' AND img_key != ''
GROUP BY user_id
ORDER BY MAX(date) DESC
LIMIT 18

I'm not sure if this is the best way to do this but it works.

A: Here is a query that works. It assume that you need logs only for a given video id (@video_id):
SELECT log_date, user_id, name_display
FROM (
  SELECT MAX(l.date) AS log_date, user_id
  FROM log_views AS l
  WHERE (l.video_id=@video_id)
  GROUP BY user_id
  ORDER BY log_date DESC
  LIMIT 18
) AS top
INNER JOIN users AS u ON (u.user_key=top.user_id)


Q: error for "apply" in kotlin on android studio I was following a tutorial on android studio and wrote the following lines:
RecyclerView.apply {this:RecyclerView!
            var layoutManager = LinearLayoutManager(activity)

but the "apply" was giving me an error and when I did Alt+Enter I saw two options for import that I did not really understand. they had to do with something called "auto-import" and i saw the word "gravity gradle". The suggestions went away for some reason after i messed around with the settings that came up, but the error is still there.

A: "apply" is available to Any object in kotlin. You don't need to import anything to use "apply"
Apply in Kotlin
But, if IDE is suggesting you to import anything for apply, that means kotlin library is not properly configured.
Check your app/build.gradle dependencies whether kotlin-stdlib exists or not.
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

A: that is because RecyclerView is not an instance. You can't use "apply" on a class.
You may want to do something like this
val recyclerView = findViewById<RecyclerView>(R.id.your_recycler)
recyclerView.apply {
    layoutManager = LinearLayoutManager(activity)
}

A: Here's how apply works:
val recyclerView = RecyclerView(context)
recyclerView.adapter = MyAdapter()
recyclerView.layoutManager = LinearLayoutManager()
recyclerView.hasFixedSize = true

vs
val recyclerView = RecyclerView(context).apply {
    adapter = MyAdapter()
    layoutManager = LinearLayoutManager()
    hasFixedSize = true
}

you run it on an instance of an object, which becomes this in the lambda, so you can do all the calls on the object without referring to it by name. And the original object pops out of the end, so you can assign the whole thing to val recyclerView - it gets the RecyclerView() you created, with a few settings applyed to it. So it's common to configure objects like this.
So like people have said, you weren't calling apply on a RecyclerView instance, you were calling it on the class itself, which doesn't work. You need to create a thing. Kotlin synthetic binding is magic code that automatically creates objects for you, from the XML it inflates, and assigns them to a variable named after the view's ID in the XML. So your tutorial is referring to an instance, using a variable name that the synthetics declared in the background. It's confusing if you're not aware of it, and I wonder if that's part of the reason it's deprecated.
Sinner of the System's answer is the easiest (and normal) way to grab an object from your layout, by looking it up by ID yourself.


Q: Browsing a MySQL database on AWS servers I have just installed MySQL on to my AWS EC2 server, I have also imported my existing SQL file so that my new MySQL db is now populated. I would like to be able to browse my database somehow.
In the past I used phpmyadmin and it was great, should I install phpmyadmin and then access it through my browser somehow? or am I looking down the wrong road.
Cheers

A: No reason you cant install phpmyadmin on your new EC2 server. Just remember to open up the necessary ports through amazons security group, and if you dont want the whole world to be able to access it, you can restrict the ports to only IP addresses you use.
AWS SECURITY GROUPS


Q: Dragging multiple html elements at once I would like to be able to drag an image next to some text and have the text move with it, the problem is that I can either move the image or move the text not have one move the other my current code for that is:

sample

sample2

how would I make it so that I can drag the image and have it move the text?

A: How to drag (and drop) an image back and forth between two  elements:
<!DOCTYPE HTML>

Drag and Drop

Drag the image back and forth between the two div elements.

i am not sure if this is what you are looking for if not, please provide an example of what you need
or you can refer to this link for dragging multiple items:
https://codepen.io/SitePoint/pen/gbdwjj


Q: Get past request without waiting for response (Angular 2 +) I am looking for data in an API via Get request, I need the data inside my OnInit to use in composing other data. The problem is that the method is being called but it is as an async method (without await), it passes everywhere but when the return is obtained the excution of the main method has already been finished with no results. I tried the implementation of asynchronous methods but it did not solve.
service:
getObjects(): MyClass[] {
let objects = new Array<MyClass>();

this.obterTodos<MyClass>(this.uriApi)
    .map(res => res.map(x => new MyClass(x.Description, x.Id)))
    .subscribe(entities => {
         objects = entities;
    });

    return objects ;
}

get request
public getObjects<TEntity>(url: string): Observable<TEntity[]> {
    return this.httpService
      .get(this.serviceUrl + url, this.options)
      .map(res => res.json())
      .catch(this.handleError);
}

component:
ngOnInit() {
    this.myObjects= this.setorService.obterSetores();
    console.log('this.myObjects is empty here');
}

A: so you'll want to subscribe to your observable in the component. This is typically done so the component can determine when the http request should be ran & so the component can wait for the http request to finish (and follow with some logic).
// subscribe to observable somewhere in your component (like ngOnInit)
this.setorService.obterSetores().subscribe(
    res => {
        this.myObjects = res;
    },
    err => {}
)

now the component knows when the http request finishes


Q: celery 4.4.2 and django 3.0.2 raising self.notregistered error but calling the function in python manage.py shell works fine I am trying to add celery to my django project.
everything works fine when i run it from the manage.py shell, my celery worker returns the result of the add() function.
when i call this function from my view it raises a not registered error and a module object not callable error on celery/base.py line 1253
celery/app/base.py", line 1253, in loaderreturn get_loader_cls(self.loader_cls)(app=self)
TypeError: 'module' object is not callable

raise self.NotRegistered(key)
celery.exceptions.NotRegistered: 'home.tasks.add'

both are from the apache error log
my home.tasks.py looks like this
from celery import shared_task
from celery.schedules import crontab
from django.db import connection
from django.utils import timezone, translation
#import pandas as pd
from home.models import *
from residence_management.models import *
from sqlalchemy import *
from django.conf import settings
from django.contrib.auth.models import User
from decimal import Decimal

@shared_task
def add(x, y):
    return x + y

my view where i call the task has the import: from home.tasks import add
in the view itself i just call add(9, 5) and it fails with the above error (without the @shared_task decorator it works fine).
when calling the function in the shell, even with the @shared_task decorator it works fine, i can start the celery worker without problems as well.
[2020-05-13 08:47:23,862: INFO/MainProcess] Received task: home.tasks.add[f7e50f7d-4e3d-4372-bf3e-e1c7175c7a2a]
[2020-05-13 08:47:23,879: INFO/ForkPoolWorker-8] Task home.tasks.add[f7e50f7d-4e3d-4372-bf3e-e1c7175c7a2a] succeeded in 0.015277621999999713s: 14

any ideas where the problem might be? i use redis for the broker and result backend

A: You can check docs and comments for shared_task on github https://github.com/celery/celery/blob/9d49d90074445ff2c550585a055aa222151653aa/celery/app/init.py
I think for some reasons you do not run creating of celery app. It is better in this case use explicit app.
from .celery import app
@app.task()
def add(x, y):
    return x + y


Q: bash script - escape characters in eval vs running command directly I am writing a bash script to count number of files given user parameters of path and exclude path. I construct a command using my bash script, where the last few line looks like this
command="find . $exclude | wc -l"
echo $command

So for example, it might result in
find .

Or if I set exclude to be '-not \( -path "./special_dir" -prune \)', then the command would be
find .   -not \( -path "./special_directory" -prune \)

Both commands I can copy and paste into a command line and everything is fine.
The problem comes when I try to run it.
exclude=""
command="find $. $exclude | wc -l"
echo $command
results=$($command)
echo "result=$results"

Above works, but the snippet below would fail.
exclude='-not \( -path "./special_dir" -prune \)'
command="find $. $exclude | wc -l"
echo $command
results=$($command)
echo "result=$results"

returns
find . -not \( -path "./special_dir" -prune \) | wc -l
find: paths must precede expression: \(
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

But if I use eval to run command, even the exclude is fine
exclude='-not \( -path "./special_dir" -prune \)'
command="find $. $exclude | wc -l"
echo $command
results=$(eval $command)
echo "result=$results"

Returns
find .   -not \( -path "./special_dir" -prune \)  | wc -l
result=872

I don't understand what's wrong with just running the command with exclude directory. My guess is it has to do some with kind of escaping special characters?

A:
what's wrong with just running the command with exclude directory.

Pipeline | is parsed before variables are expanded.
Unquoted variable expansion undergo word splitting and filename expansion. This is irrelevant of quotes and backslashes inside the string - you can put as many backslashes as you want, the result of the expansion still will be split on spaces. https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions

y guess is it has to do some with kind of escaping special characters?

No, it does not matter what is the content of the variable. It's important how you use the variable.

Above works, but the snippet below would fail.

Yes, \( is an invalid argument for find, it should be (. The result of expansion is not parsed for escape sequences, they are preserved literally, so \( stays to be \(, two characters. In comparison, when the line is parsed, then quoting is parsed. https://www.gnu.org/software/bash/manual/bash.html#Shell-Operation
In either case, you want to be using Bash arrays and want to do a lot of experimenting with quoting and expansion in shell. The following could be enough to get you started:
findargs=( -not \( -path "./special_directory" -prune \) )
find . "${findargs[@]}"

Check your scripts with shellcheck. Do not store commands in variables - use functions and bash arrays. Quote variable expansions. eval is very unsafe, and if the path comes from the user, shouldn't be used. Use printf "%q" to quote a string for re-eval-ing. See https://mywiki.wooledge.org/BashFAQ/050 , https://mywiki.wooledge.org/BashFAQ/048 , and read many introductions to bash arrays.

A: The reason you typically have to escape the parentheses in a find command is that parentheses have special meaning in bash. Bash sees a command like find . -not ( -path "./special_dir" -prune ) and tries to interpret those parentheses as shell syntax instead of literal characters that you want to pass to your command. It can't do that in this context, so it complains. The simple fix is to escape the parentheses to tell bash to treat them literally.
To reiterate: those backslashes are NOT syntax to the find command, they are there to tell bash not to treat a character specially even if it normally has special meaning. Bash removes those backslashes from the command line before executing the command so the find program never sees any backslashes.
Now in your use case, you're putting the command in a variable. Variable expansion happens after bash has parsed the contents of the command line, so escape characters inside the variable (like '\') won't be treated like escapes. They'll be treated like any normal character. This means your backslashes are being passed as literal characters to your command, and find doesn't actually know what to do with them because they aren't part of that command's syntax.
Further reading on the bash parser
The simplest thing you can do: Just don't include the backslashes. Something like this will work fine:
exclude='-not ( -path ./special_dir -prune )'
command="find . $exclude"
$command

The parentheses don't actually need to be escaped here because the parsing step that would interpret them as special characters happens before variable expansion, so they'll just be treated literally.
But really, you might be better off using a function. Variables are meant to hold data, functions are meant to hold code. This will save you a lot of headaches trying to understand and work around the parsing rules.
A simple example might be:
normal_find() {
  find .
}

find_with_exclude() {
  find . -not \( -path ./special_dir -prune \)
}

my_command=normal_find
#my_command=find_with_exclude #toggle between these however you like

results=$( $my_command | wc -l )
echo "results=$results"


Q: Can't access variable in my helper from application controller in Rails engine I created a gem that extends a Rails Engine. I am using Rails 4. Everything works fine except i cant access instance variable in application controller from helpers. Here is my code...what am i doing wrong?
app/controllers/application_controller.rb
   class ApplicationController < ActionController::Base

    protect_from_forgery with: :exception

    def get_context
    @variable  = "variable"
    end
    end

app/helpers/evaluate_helper.rb
      module EvaluateHelper

      def app_name
      @variable   #=> nothing here
      end
      end

lib/evaluate/version.rb
      require "rails"
      require "evaluate/version"

     module Evaluate
      VERSION = "0.0.1"

     class Engine < ::Rails::Engine
      end
    end

evaluate.gemspec
    lib = File.expand_path('../lib', __FILE__)
    $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
    require 'evaluate/version'

    Gem::Specification.new do |spec|
    spec.name          = "evaluate"
    spec.version       = Evaluate::VERSION
    spec.authors       = ["My name"]
    spec.email         = ["myemail"]
    spec.summary       = %q{Evaluation}
    spec.description   = %q{Evaluation and analysis of application usage.}
    spec.homepage      = ""
    spec.license       = "MIT"

    spec.files         = `git ls-files -z`.split("\x0")
    spec.executables   = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
    spec.test_files    = spec.files.grep(%r{^(test|spec|features)/})
    spec.require_paths = ["lib"]

    spec.add_development_dependency "rails", ">= 3.1"
    spec.add_development_dependency "bundler", "~> 1.6"
    spec.add_development_dependency "rake"
    spec.add_development_dependency "browser"
    end


Q: Converting 1D numpy array into top triangle of matrix Is it possible to take a 1D numpy array containing 171 values and place these values into the top triangle of an 18X18 matrix?
I feel like I should be able to use np.triu_indices to do this somehow but I can't quite figure it out!
Thanks!

A: See What is the most efficient way to get this kind of matrix from a 1D numpy array? and Copy flat list of upper triangle entries to full matrix?
Roughly the approach is
result = np.zeros(...)
ind = np.triu_indices(...)
result[ind] = values

Details depend on the size of the target array, and the layout of your values in the target.
In [680]: ind = np.triu_indices(4)
In [681]: values = np.arange(16).reshape(4,4)[ind]
In [682]: result = np.zeros((4,4),int)
In [683]: result[ind]=values
In [684]: values
Out[684]: array([ 0,  1,  2,  3,  5,  6,  7, 10, 11, 15])
In [685]: result
Out[685]:
array([[ 0,  1,  2,  3],
       [ 0,  5,  6,  7],
       [ 0,  0, 10, 11],
       [ 0,  0,  0, 15]])


Q: Fatal error on Android 7.1.2(API 25) after execution of Garbage Collection If use app 3 to 4 min, I always end up with Fatal error which comes after the execution of Garbage collection.
I have almost optimised memory usage, however, my app crashes with Fatal error.
Here is the log,
08-30 04:59:48.603 W/InputEventReceiver(29468): Attempted to finish an input event but the input event receiver has already been disposed.
08-30 04:59:48.943 I/SearchCardActivity(29468): onDestroy
08-30 04:59:48.944 I/art     (29468): Starting a blocking GC Explicit
08-30 04:59:49.054 I/art     (29468): Explicit concurrent mark sweep GC freed 37724(2MB) AllocSpace objects, 17(2020KB) LOS objects, 40% free, 23MB/39MB, paused 1.180ms total 109.379ms
--------- beginning of crash
08-30 04:59:49.083 F/libc    (29468): Fatal signal 11 (SIGSEGV), code 1, fault addr 0x44789914 in tid 29475 (FinalizerDaemon)

Thanks in advance!


Q: rails 4.2.1 server error Hi I am new to rails and every time I try to view the server i get this
testapp$ rails s
/home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/execjs-2.5.2/lib/execjs/runtimes.rb:48:in `autodetect': Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/execjs-2.5.2/lib/execjs.rb:5:in `<module:ExecJS>'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/execjs-2.5.2/lib/execjs.rb:4:in `<top (required)>'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/uglifier-2.7.1/lib/uglifier.rb:3:in `require'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/uglifier-2.7.1/lib/uglifier.rb:3:in `<top (required)>'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:76:in `require'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:72:in `each'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:72:in `block in require'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:61:in `each'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:61:in `require'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler.rb:134:in `require'
    from /home/sky/testapp/config/application.rb:7:in `<top (required)>'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:78:in `require'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:78:in `block in server'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands.rb:17:in `<top (required)>'
    from /home/sky/testapp/bin/rails:8:in `require'
    from /home/sky/testapp/bin/rails:8:in `<top (required)>'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/client/rails.rb:28:in `load'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/client/rails.rb:28:in `call'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/client/command.rb:7:in `call'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/client.rb:26:in `run'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/bin/spring:48:in `<top (required)>'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/binstub.rb:11:in `load'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/binstub.rb:11:in `<top (required)>'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /home/sky/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /home/sky/testapp/bin/spring:13:in `<top (required)>'
    from bin/rails:3:in `load'
    from bin/rails:3:in `<main>'

what do?

A: You should ensure that you have a JS runtime declared in your Gemfile.
Try adding:
gem 'therubyracer'

or
gem 'execjs'

to your Gemfile and run:
bundle install

A: As mentioned above you need a JavaScript runtime. If you are unsure of which to choose, I've always been told to use Node.js


Q: New file created inside Django App to seed data I've created an application inside my django project called SeedData. I've added then a file called import_data.py where I will be reading csv files and adding them to my database.
-SeedData
--__pycache__
--migrations
--__init__.py
--admin.py
--apps.py
--import_data.py
-- etc..

But whenever i do the following:
from Product.models import Product
from Category.models import Category
from SubCategory.models import SubCategory
from Brand.models import Brand
import pandas as pd

I get this error
File "C:\Users\...\SeedData\import_data.py", line 9, in <module>
    from Product.models import Product
ModuleNotFoundError: No module named 'Product'

It's the same for Category, SubCategory and Brand.
I'd also like to say that the project is fully functional and all the mentioned projects above works perfectly fine.


Q: Is this if statement correct, or is it redundant? I've a simple question about if statement in Objective - C.
Is this if statement correct, or is it redundant and I don't need to specify ==YES ?
NSNumber *boolean = [NSNumber numberWithBool:YES];
if (boolean == YES) ...

thanks

A: You compare pointer and integer, which won't lead you to the result you want.
Example:
NSNumber *boolean1 = [NSNumber numberWithBool:YES];
if (boolean1) {
    // true
}

NSNumber *boolean2 = [NSNumber numberWithBool:NO];
if (boolean2) {
    // this is also true
}

if ([boolean1 boolValue] && ![boolean2 boolValue]) {
    // true
}

A: No, it isn't correct and it isn't going to generate the output you think it is. NSNumber * boolean is a pointer to an object in memory while YES is a scalar value; they should not be compared with ==.
If you type this code you'll also get the following warning:

The correct way to do it would be:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if ( [boolean boolValue] ) {
  // do something
}

But this statement itself does not make much sense, since you should be comparing the BOOLs and not NSNumber -- there is no need to use the NSNumber in there.

A: This won't work. An instance of NSBoolean is an object, and will be non-NULL whether YES or NO.
There's two good ways to check the value of a NSBoolean.
The first is to use boolValue:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if ([boolean boolValue] == YES) ...
if ([boolean boolValue]) ... // simpler

The second is to use the identity of the object returned:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if (boolean == (id)kCFBooleanTrue) ...

The latter is faster; it relies on there being only one each of NSBoolean YES and NSBoolean NO on the system. These have the same values as kCFBooleanTrue and kCFBooleanFalse. I've read this is safe forever, but I'm not sure it's part of Apple's published documentation.


Q: Why does regex require triple backslash to match a single backslash? I was trying to match a backslash using regex and thought that this could be done by using two double backslashes, using the former to escape the latter. However, when I run the code

path_str = r"\Animal_1-"
Match_backslash = re.search("[\\]", path_str)
print(Match_backslash)

I get the error message:
error: unterminated character set at position 0

But, when I use triple backslash:

path_str = r"\Animal_1-"
Match_backslash = re.search("[\\\]", path_str)
print(Match_backslash)

it for some reason works, can anyone explain why triple backslash is needed and why double backslash isn´t sufficient?


Q: Start text animation on button click, clear and start animation again if button is clicked again I've taken this snippet of code from a project I'm working on with a few friends and I'm looking for a bit of knowledge on getting a function to not activate until a button is clicked. Also, If the animation could be restarted every time the button is clicked, that would be great.
I made an attempt at using:
//  $('#savebtn').onClick(function(){
//  $('#setupTypewriter').addClass('typewriter');
//  });

and
$('#savebtn').onClick(function(){
setupTypewriter('typewriter');
});

in the js file to no avail. I'm probably missing something severely obvious that a second set of eyes will pick up as I am an amateur coder.
Also, if you notice random elements/code calling to something else in the snippets I've posted, they're probably unnecessary but I did just rip all of this code out of the bigger project like I mentioned :P

function setupTypewriter(t) {
  var HTML = t.innerHTML;

  t.innerHTML = "";

  var cursorPosition = 0,
    tag = "",
    writingTag = false,
    tagOpen = false,
    typeSpeed = 1,
    tempTypeSpeed = 0;

  var type = function() {

    if (writingTag === true) {
      tag += HTML[cursorPosition];
    }

    if (HTML[cursorPosition] === "<") {
      tempTypeSpeed = 0;
      if (tagOpen) {
        tagOpen = false;
        writingTag = true;
      } else {
        tag = "";
        tagOpen = true;
        writingTag = true;
        tag += HTML[cursorPosition];
      }
    }
    if (!writingTag && tagOpen) {
      tag.innerHTML += HTML[cursorPosition];
    }
    if (!writingTag && !tagOpen) {
      if (HTML[cursorPosition] === " ") {
        tempTypeSpeed = 0;
      } else {
        tempTypeSpeed = (Math.random() * typeSpeed) + 0;
      }
      t.innerHTML += HTML[cursorPosition];
    }
    if (writingTag === true && HTML[cursorPosition] === ">") {
      tempTypeSpeed = (Math.random() * typeSpeed) + 0;
      writingTag = false;
      if (tagOpen) {
        var newSpan = document.createElement("span");
        t.appendChild(newSpan);
        newSpan.innerHTML = tag;
        tag = newSpan.firstChild;
      }
    }

    cursorPosition += 1;
    if (cursorPosition < HTML.length - 1) {
      setTimeout(type, tempTypeSpeed);
    }

  };

  return {
    type: type
  };
}

var typer = document.getElementById('typewriter');

typewriter = setupTypewriter(typewriter);

typewriter.type();
.colbtns {
  left: 115px;
  bottom: 37.5px;
  position: relative;
  width: 140px;
  z-index: 3;
}

.colbtnd {
  left: 115px;
  bottom: 37px;
  position: relative;
  width: 140px;
  z-index: 3;
}

.ecutext-container {
  background-color: #000000;
  border-radius: .25rem;
  position: relative;
  height: 235px;
  width: 380px;
  left: 413px;
  bottom: 0px;
  z-index: 1;
}

.col {
  color: #fff;
}

.text-muted {
  color: #fff!important;
}

.btn-success {
  color: #fff;
  background-color: #1a75ff;
  border-color: #1a75ff;
}

.btn-success:hover {
  color: #fff;
  background-color: #005ce6;
  border-color: #005ce6;
}

.btn-success:active {
  color: #fff;
  background-color: #005ce6;
  border-color: #005ce6;
}

.btn-success:focus {
  color: #fff;
  background-color: #005ce6;
  border-color: #005ce6;
}

.ui-widget-content {
  border: 1px solid;
  border-color: #fff;
  background-color: #1a75ff;
  background: none;
}

.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default {
  border: 1px solid #fff;
}

.slider {
  border: 1px solid;
  border-color: #fff;
  background-color: #fff;
}

#boost {
  color: #fff;
}

.var-highlight {
  color: #008ae6;
}

.string-highlight {
  color: #008ae6;
}

#typewriter {
  padding-top: 5px;
  font-size: 10px;
  color: #fff;
  margin: 0;
  overflow: hidden;
  font-family: "Lucida Sans Typewriter", "Lucida Console", Monaco, "Bitstream Vera Sans Mono", monospace;
  &:after {
    content: "|";
    animation: blink 500ms linear infinite alternate;
  }
}

@-webkit-keyframes blink {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-moz-keyframes blink {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes blink {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" type="text/css" href="index.css">
  <link href="https://code.jquery.com/ui/1.10.4/themes/ui-darkness/jquery-ui.css" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="custom.css">
  <link rel="stylesheet" type="text/css" href="textanim.css">

 Init lmECU.exe = {
--------------------------------
 lmECU:\ validating engineer key
 lmECU:\ validation success
 lmECU:\ accessing sensors
 lmECU:\ parsing senslog.xml
 lmECU-senslog:\ running diagnostics
     - {0 faults detected
 lmECU:\ applying Modifications...
 lmECU:\ generating senslog.xml
 lmECU:\ parsing senslog.xml
 lmECU-senslog:\ running diagnostics
   - {0 faults detected
 lmECU:\  ECU remap successful
 lmECU:\  end lmECU.exe

<button class="btn btn-success form-control" id="savebtn">SAVE</button>

<button class="btn btn-success form-control" id="defaultbtn">DEFAULT</button>


Q: Dropzone JS not able to upload file I'm using Dropzone JS and from my frontend (localhost:9000), I'm calling a upload.php where I get the images and then upload it on the backend (localhost:80)in a folder.
here is my html :
 <form action="localhost:80/ProgettoTimelinegit/api/upload.php" class="dropzone" id="my-dropzone" enctype="multipart/form-data">

 </form>

my javascript :
Dropzone.autoDiscover = false;
$("#my-dropzone").options = {
    maxFilesize: 4, // MB
    url:"http://localhost:80/ProgettoTimelinegit/api/upload.php",
    addRemoveLinks : true,
    uploadMultiple:true,
    paramName:"file",
    parallelUploads: 2,
    maxFiles: 10,
    autoProcessQueue: true,
    headers: {
        // remove Cache-Control and X-Requested-With
        // to be sent along with the request
        'Cache-Control': null,
        'X-Requested-With': null
    }
};

and upload.php
$ds = DIRECTORY_SEPARATOR;  //1
$storeFolder = '/xampp/htdocs/images/';   //2

if(!empty($_FILES)) {
    // START // CREATE DESTINATION FOLDER
    define('DESTINATION_FOLDER','../api/upload/');

    if (!@file_exists(DESTINATION_FOLDER)) {
        if (!mkdir(DESTINATION_FOLDER, 0777, true)) {
            $errors[] = "Destination folder does not exist or no permissions to see it.";
        }

        // END // CREATE DESTINATION FOLDER
        $temp = $_FILES['file[]']['tmp_name'];
        $dir_seperator = "fold/";

        //$destination_path = dirname(__FILE__).$dir_seperator.$folder.$dir_seperator;
        $destination_path = DESTINATION_FOLDER.$dir_seperator;
        $target_path = $destination_path.(rand(10000, 99999)."_".$_FILES['file']['name']);
        move_uploaded_file($temp, $target_path);
    }
}

If I upload the image, in console (for every browser)
it
POST localhost:80/ProgettoTimelinegit/api/upload.php net::ERR_UNKNOWN_URL_SCHEME

What I want to do is to load the image in localhost:80/progettoTimelinegit/api/upload/

A: Your upload.php-file is already in the api-folder, just change this line:
define('DESTINATION_FOLDER','../api/upload/');
to:
define('DESTINATION_FOLDER','upload/');
And it should work. You have quite a few weird variables, unused variables etc., so there might be other things wrong as well.

A: I've managed to make it work, it costed me 4 days of work but now it works :
you have to be careful in some part of your code :
Html
Do not add enctype="multipart/form-data" or if you do remember to add rewrite rule

"multipart/form-data" make dropzone AUTOMATICALLY set Options REQUEST
virtual host or a .ini / .htAccess with Xampp/wampp/vagrant
VirtualHost *:80>
    DocumentRoot "#folderOfyourWebsite"
    ServerName yoursite.name
     <Directory "#path To The HTML of Your Index Page">
         Options Indexes FollowSymLinks MultiViews ExecCGI
         AllowOverride Authconfig FileInfo
         Require all granted
        </Directory>
        Header set Access-Control-Allow-Origin "*"
        Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
        Header set Access-Control-Max-Age "1000"
        Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
        RewriteEngine On
        RewriteCond %{REQUEST_METHOD} OPTIONS
        RewriteRule ^(.*)$ $1 [R=200,L]
  </VirtualHost>

In rewrite engine we're telling him : ok,if you receive An options request, rewrite it with a 200 (successfull post)
So your TO-DO list can be recapped with this :

*

*check your html dropzone Form, if you have enctype you'll have to write
a Rewrite Rule in your vhost or htaccess

*Did you write a Rewrite Rule in order to make cors Successfull?

*Make sure your path have all permissions and your upload folder exists

*Check your static paths wherever you are doing an http request


Q: Vue : How to use async await accordingly in a function array of which can have two functions for Promise.all? I want to use await where I marked [here] in 1.vue. However, if I use await there then it emits error Unexpected reserved word 'await'. If I want to use async useFunctionToAllServers() sequentially after [Promise.all] then, where to put async or how to change async useFunctionToAllServers()? Or need to change submitToTheOthers()?
1.vue
<template>

      <button class="point">upload</button>

    <input
      type="file"
      class="input-file"
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo')"
    />

      <button class="point">upload1</button>

    <input
      type="file"
      class="input-file"
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo1')"
    />

    <button @click="useFunctionToAllServers">BUTTON</button>

</template>

2.js
import axios from 'axios'
export const headers = {
  'Content-Type': 'application/json',
  'header1' : 'header1',
  'header2' : 'header2',
}

export function updateGeneralInfoToOther(id, data, serverAddress) {
  data.serverAddress = serverAddress
  return axios.put(`/u/r/l/${id}`, data, { headers })
}

export function updateGeneralInfo(id, data) {
  return axios.put(`/extra/u/r/l/${id}`, data, { headers })
}

export function createUploadToOther(data) {
  return axios.post('/u/r/l', data, { headers })
}

A: To use await in those callbacks, each callback function itself needs to be async:
export default {
  methods: {
    submitToTheOthers(){
      ⋮
      return this.idxs.map( (_entry, i) => {
        return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then(async (res) => { // [here2]
            ✅
          await someAsyncMethod()

          if (res.status == 200) {
            ⋮
            if (logoData.logo) {
              this.sendFileToOther(/*...*/).then(async (res) => { // [here]
                  ✅
                await someAsyncMethod()
              })
            }
            if (logoData.logo1) {
              this.sendFileToOther(/*...*/).then(async (res) => { // [here]
                  ✅
                await someAsyncMethod()
              })
            }
          }
        })
      })
    },
  },
}


Q: Is it possible to get a remote computer process and waitForInputIdle over it? c# So I would like to run something similar to the following on a remote computer:
 process = Process.Start("notepad.exe");
 process.WaitForInputIdle();

I have no problem connecting via WMI, executing processes and running query on them but I cant find a way to WaitForInputIdle on these remote processes. (or any other method that tells me that the process has finished loading)
Any ideas how it can be done?


Q: Remove changes from a commit hash in a given file git I have a 3 month old commit, lets say commit A which touchs 3 files
Over the last 3 months, a lot more commits have gone in, some of which have added new code below changes from commit A
I want to remove (not revert) the changes from commit A in 1 of the 3 files.
remove as in blank line instead of code
I tried
git show < commit hash of A > file_path | git apply -R -3
this removes extra code (which is outside the scope of commit A: details below if interested)
One way i can think of is using git blame on file, wherever hash matches, remove the lines
but seems to be very iterative process and time consuming.
Any pointers would be helpful..
Thanks in advance
Extra code removed from file which is out of scope of commit A:

*

*Commit A was added at the end of file

*New commits added more code after commit A (below changes from commit A) at the end of file

*now when we reverse the changes in commit A (using git apply -R -3), it cleans from start of commit A till end of file because to git, the code was originally added at the end of file

A: I would still try git-revert to remove lines in commit A.
Next you want to restore the other two files which don’t need revert. git checkout HEAD^ - file1 file2 is the way to recover to the original file content.
Finally commit amend to overwrite nicer message than “Revert …”


Q: Is there a limit to the file size you can upload with GWT FormPanel and FileUpload? I recall seeing somewhere that there was a limit of 10MB upload in GWT when using FormPanel and FileUpload, but I can't seem to find any reference to a limit now. Is there one?

A: There is no reasonable limit* on the client side (or in GWT) of a <input type=file>. That said, it is quite likely that your server has a limit on the size of an upload, so be sure to configure whatever server (and optionally any reverse proxy in use) to use a high enough limit.
* technically, it appears there is a limit - the file cannot be larger than 2^64 bytes (about 18 million terabytes), at least according to MDN.


Q: Android Switch widget inside AlertDialog, not showing thumb image (on/off instead) I have a rather simple dialog with an ArrayAdapter inside. The adapter inflates the following layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp">

    <TextView
        android:id="@+id/txt_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_toStartOf="@+id/calendar_selection_switch"
        android:ellipsize="end"
        android:text="test test"
        android:textColor="@color/black"
        android:textSize="20sp" />

    <Switch
        android:id="@id/calendar_selection_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:layout_gravity="end|center_vertical"
        android:layout_marginStart="10dp"
        android:minHeight="40dp"
        android:minWidth="80dp" />
</RelativeLayout>

When I show this dialog, this is what I get:

Notice the words "on" and "off" in tiny letters. No custom graphics or classes here, just out-of-the-box.
When I do this in an Activity I don't get that. Instead I get the normal thumb image, which is exactly what I want:

Even if I grow the size of the Switch it doesn't make any difference. It just makes the list's rows larger.
Here's the code to build and show the dialog:
AlertDialog.Builder builderSingle = new AlertDialog.Builder(this);
builderSingle.setTitle(R.string.cal_title);

builderSingle.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});

final CalendarListAdapter cla = new CalendarListAdapter(this, calendarList, null);
builderSingle.setAdapter(cla, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        cla.toggleSelect(which);
    }
});
builderSingle.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (saveCalendars(cla)) {
            dialog.dismiss();
        }
    }
});
AlertDialog dialog = builderSingle.create();
dialog.show();

The CalendarListAdapter is a simple ArrayAdapter:
public class CalendarListAdapter extends ArrayAdapter<Calendar> {

There's no difference between the Activity version and the AlertDialog version for this class though.
I'm puzzled. What I do here is not very complicated. Please help.

A: Try this:
    <Switch
        android:id="@+id/calendar_selection_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:layout_gravity="end|center_vertical"
        android:layout_marginStart="10dp"
        android:minHeight="40dp"
        android:minWidth="80dp"
        android:textOn=""
        android:textOff=""
        android:switchMinWidth="48.0sp"
        android:thumb="@drawable/switch_selector"
        android:track="@drawable/switch_track"
        android:checked="false"/>

switch_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true">
        <shape
            android:shape="rectangle"
            android:visible="true"
            android:useLevel="false">
            <gradient
                android:startColor="@color/white"
                android:endColor="@color/white"
                android:angle="270"/>
            <corners
                android:radius="14.0sp"/>
            <size
                android:width="28.0sp"
                android:height="28.0sp" />
            <stroke
                android:width="4.0sp"
                android:color="#11000000"/>
        </shape>
    </item>
    <item android:state_checked="false">
        <shape
            android:shape="rectangle"
            android:visible="true"
            android:dither="true"
            android:useLevel="false">
            <gradient
                android:startColor="@color/white"
                android:endColor="@color/white"
                android:angle="270"/>
            <corners
                android:radius="16.0sp"/>
            <size
                android:width="28.0sp"
                android:height="28.0sp" />
            <stroke
                android:width="2.0sp"
                android:color="#11000000"/>
        </shape>
    </item>
</selector>

switch_track.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:visible="true"
    android:useLevel="false">
    <gradient
        android:startColor="@color/white"
        android:endColor="@color/white"
        android:angle="270"/>
    <stroke
        android:width="2.0sp"
        android:color="#11000000"/>
    <corners
        android:radius="14.0sp"/>
    <size
        android:width="42.0sp"
        android:height="28.0sp" />
</shape>

Then in code you can do:
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    aSwitch.setTrackResource(R.drawable.switch_track_off);
                } else {
                    aSwitch.setTrackResource(R.drawable.switch_track);
                }
            }
        });

switch_track_off.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:visible="true"
    android:useLevel="false">
    <gradient
        android:startColor="#00A4FD"
        android:endColor="#00A4FD"
        android:angle="270"/>
    <stroke
        android:width="2.0sp"
        android:color="#00A4FC"/>
    <corners
        android:radius="14.0sp"/>
    <size
        android:width="42.0sp"
        android:height="28.0sp" />
</shape>

You can change the colors and other styles as you wish.
As far as I know this is the only reliable way to make Switch look and feel same in all Android versions anywhere in the app.
Please leave a comment if there is any better suggestion.

A: Use this
    <Switch
        android:id="@+id/switchCalls"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:textOff=""
        android:textOn=""
         />


Q: Redshift query results incorrect before VACUUM When Redshift uses an index to run a query (say counts), does it exclude counting the rows in the unsorted region?
I had copied a lot a data using the COPY command, but did not VACUUM the table afterwords. On running my query (involving joins with several tables), the results of the query were wrong - the newly copied rows in the unsorted region weren't counted.
Then, after vacuuming the table, the query began returning the correct results. Is this expected behavior, or is this a bug introduced by Amazon?

A: Vacuuming won't have any effect on COPYed rows, which are effectively inserts. Vacuum physically deletes rows previously deleted with an SQL delete statement, which only marks the rows as deleted, so they don't participate in subsequent queries but still consume disk space.
Redshift is an eventually consistent database, so even if your COPY command had completed, the rows may not yet be visible to queries.
Running vacuum is basically a defrag, which requires all rows to be reorganized. This (probably) causes the table to be brought into a consistent state, ie all rows are visible to queries.


Q: Google Chrome moves div out of document flow when using internal links Look at the two links below in Chrome:
Working: http://www.datesphere.com/boards/showthread.php?tid=46
Broken: http://www.datesphere.com/boards/showthread.php?tid=46&pid=345#pid345
Notice how the navigation breadcrumb and "thread rating" section render correctly in the "working" link, but are jammed up under the user panel in the "broken" link. I've spent a lot of time trying to figure out why this is happening (asked on mybb.com and a couple other forums, reported a bug to Google Chrome team, etc.) but haven't had any luck, so am hoping Stackoverflow comes through once again.
Here's what I know:

*

*This only happens in Google Chrome, and as far as I can tell only on permalinked posts where you have an internal link -- pages ending with  "pid=[number]#pid[number]"

*I believe it's happening because the "wrapper" div that starts the content section is being rendered up at the same place as the user panel instead of below it, where it belongs in the document flow.

*Adding a clearing div ("style=clear:both;") before the "content" div fixes the problem in Chrome Developer Tools, but when you add it to the actual code nothing happens.

This is the most baffling and frustrating thing I've come across in html / css. Does anyone have any idea why this is happening, and how I might fix it?
Thanks,
Chris

A: Here's your culprit.
#content {
  overflow: hidden;
}

This is exactly the reason why you shouldn't use overflow hidden for clearing floats. Anchor links will cause overflowed elements to scroll in certain situations.
Look into clearfix for clearing floats instead.
Run this javascript in your console for a demonstration on the problem:
document.getElementById("content").scrollTop = 0


Q: Is there an easy way to include RackTest methods in Capybara tests? Capybara 2 removed these and suggests to separate them, but we have some situations where we'd like to use both in a test (enabling an api key through the view, then hitting the api, etc).
I tried including include ::Rack::Test::Methods but I'm getting:
undefined local variable or method `app' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x007fb737932ba0>

A: I ran into the same error using Rails and RSpec to test an API.  I found a helpful blog post for Rails 2.3: http://eddorre.com/posts/using-rack-test-and-rspec-to-test-a-restful-api-in-rails-23x
module ApiHelper
  require 'rack/test'
  include Rack::Test::Methods

  def app
    ActionController::Dispatcher.new
  end
end

My solution for Rails 3.2 was (look in config.ru for MyAppName):
module ApiHelper
  require 'rack/test'
  include Rack::Test::Methods

  def app
    MyAppName::Application
  end
end

A: try this
def app
  Rails.application
end

A: For anyone else banging their heads against the wall getting the "NameError: undefined local variable or method `app'" error. It also happens when you are running all your tests at once (multiple files) and one of them does an include Rack::Test::Methods - the include "infects" the other tests. So the symptom is that all tests pass when the files are run individually, but then they fail with the "no app" error when run together. At least this happens with rails 3.0.9 and rspec 3.0
The solution to this issue is to remove the includes. Alternatively you might try something like @ultrasaurus' answer to make sure the includes are properly contained to only the examples that need it.


Q: java.lang.RuntimeException: Could not inject members I'm trying since some time to get Arquillian running with JPA.
I had some DAO tests working, but while a continued to write the remaining tests this error started and affected both the ones I was writing and the ones that were fine before.
java.lang.RuntimeException: Could not inject members
at org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher.injectClass(CDIInjectionEnricher.java:117)
at org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher.enrich(CDIInjectionEnricher.java:71)
at org.jboss.arquillian.test.impl.TestInstanceEnricher.enrich(TestInstanceEnricher.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:116)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.before(EventTestRunnerAdaptor.java:115)
at org.jboss.arquillian.junit.Arquillian$4.evaluate(Arquillian.java:200)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:350)
at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:215)
at org.jboss.arquillian.junit.Arquillian$7$1.invoke(Arquillian.java:279)
at org.jboss.arquillian.container.test.impl.execution.BeforeLifecycleEventExecuter.on(BeforeLifecycleEventExecuter.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:116)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.fireCustomLifecycle(EventTestRunnerAdaptor.java:159)
at org.jboss.arquillian.junit.Arquillian$7.evaluate(Arquillian.java:273)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:166)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:350)
at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:115)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.jboss.arquillian.junit.container.JUnitTestRunner.execute(JUnitTestRunner.java:61)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.executeTest(ServletTestRunner.java:139)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.execute(ServletTestRunner.java:117)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.doGet(ServletTestRunner.java:86)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:360)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1349)
at java.lang.Thread.run(Thread.java:748)

Caused by: org.jboss.arquillian.test.spi.ArquillianProxyException: org.jboss.weld.exceptions.IllegalArgumentException : WELD-001408: Unsatisfied dependencies for type MorphologicalAnalysisPersistenceFacade with qualifiers @Default
  at injection point [BackedAnnotatedField] @Inject br.com.cpmh.beacon.persistence.MorphologicalAnalysisPersistenceFacadeTest.morphologicalAnalysisPersistenceFacade
  at br.com.cpmh.beacon.persistence.MorphologicalAnalysisPersistenceFacadeTest.morphologicalAnalysisPersistenceFacade(MorphologicalAnalysisPersistenceFacadeTest.java:0)
 [Proxied because : Original exception caused: class java.lang.ClassNotFoundException: org.jboss.weld.exceptions.IllegalArgumentException]
    at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:83)
    at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:70)
    at org.jboss.weld.manager.BeanManagerImpl.createInjectionTarget(BeanManagerImpl.java:1025)
    at org.jboss.weld.util.ForwardingBeanManager.createInjectionTarget(ForwardingBeanManager.java:204)
    at org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher.injectNonContextualInstance(CDIInjectionEnricher.java:124)
    at org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher.injectClass(CDIInjectionEnricher.java:110)
    ... 135 more
Caused by: org.jboss.arquillian.test.spi.ArquillianProxyException: org.jboss.weld.exceptions.DeploymentException : WELD-001408: Unsatisfied dependencies for type MorphologicalAnalysisPersistenceFacade with qualifiers @Default
  at injection point [BackedAnnotatedField] @Inject br.com.cpmh.beacon.persistence.MorphologicalAnalysisPersistenceFacadeTest.morphologicalAnalysisPersistenceFacade
  at br.com.cpmh.beacon.persistence.MorphologicalAnalysisPersistenceFacadeTest.morphologicalAnalysisPersistenceFacade(MorphologicalAnalysisPersistenceFacadeTest.java:0)
 [Proxied because : Original exception caused: class java.lang.ClassNotFoundException: org.jboss.weld.exceptions.DeploymentException]
    at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:378)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:290)
    at org.jboss.weld.bootstrap.Validator.validateProducer(Validator.java:425)
    at org.jboss.weld.injection.producer.InjectionTargetService.validateProducer(InjectionTargetService.java:36)
    at org.jboss.weld.manager.InjectionTargetFactoryImpl.validate(InjectionTargetFactoryImpl.java:153)
    at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:81)
    ... 140 more
My tests look all the same:
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;

@RunWith(Arquillian.class)
public class MorphologicalAnalysisPersistenceFacadeTest
{
    @Inject
    MorphologicalAnalysisPersistenceFacade morphologicalAnalysisPersistenceFacade;

    @Inject
    private UserTransaction userTransaction;

    @PersistenceContext(unitName = "BeaconAnalysis")
    EntityManager entityManager;

    @Deployment
    public static Archive<?> createDeployment()
    {
        JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "morphological-analysis-data-access-object-test.jar");
        archive.addPackages(true, "br.com.cpmh.beacon");
        archive.addAsResource("test-persistence.xml", "META-INF/persistence.xml");
        archive.addAsResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));

        return archive;
    }

    @Before
    public void setUp() throws Exception
    {
        //morphologicalAnalysisPersistenceFacade = new MorphologicalAnalysisPersistenceFacade();
    }

    @After
    public void tearDown() throws Exception
    {
    }

    @Test
    public void create()
    {
    }

A: I think the most important part in this stacktrace is:

WELD-001408: Unsatisfied dependencies for type MorphologicalAnalysisPersistenceFacade

This usually means that not all required dependencies for MorphologicalAnalysisPersistenceFacade are deployed to the Weld-container. To debug this I would suggest temporarily rewriting your deployment method to:
@Deployment
public static Archive<?> createDeployment() {
    JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "morphological-analysis-data-access-object-test.jar")
    .addPackages(true, "br.com.cpmh.beacon")
    .addAsResource("test-persistence.xml", "META-INF/persistence.xml")
    .addAsResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));

    // print all included packages
    System.out.println(archive.toString(true));

    return archive;
}

This will print out all the classes which are deployed to the container. With that, you can investigate if any required class does not get deployed and include that class or package manually in your createDeployment method.


Q: OAuth 2.0 In Microservices: When a resource server communicates with another resource server Currently, the user is passing the access token, with [Scope A] to the web portal.
Once the user requests to view a resource, the token is passed to the resource server [Web App A] to obtain the resource. However, to obtain the resource, the resource server must communicate with [Web App B] to obtain a subset of information, therefore it requires [Scope B]. Since the user only authorized [Scope A] the call will fail.
Below are scenarios of fixes that could be applied:

*

*Scenario 1: The user is requested to authorize [Scope A] and [Scope B]. The problem here is that the user might not want the [Web Portal] to access [Web App B] directly.

*Scenario 2: [Web App A] becomes the client of [Web App B], using it's own access token to request resources from [Web App B]. The problem here is that the user context is lost.

I am looking for the standard solution, I might be doing something wrong from my end.

A few other questions I would like to ask:

*

*Should the access token be passed around microservices?

*Should there be a different authorization framework for internal requests?

A: If these are different applications (to the user) then yes, user should be asked to confirm if he is willing to authorise A to access B. If he does not want to that, then A has no biz talking to B on behalf of the said user.
If this is set of microservices then user need to interact with via Web Page and any subsequent calls if being made to n different services is something that user should not be concerned with. As such he is trusting the web page and asking web page for some data. You have set of microservices sitting behind to answer that, is not of concern for user and his token.
So you can make use of second option. Talking about user context, well that can shared in some other forms like passing via headers.

Should the access token be passed around microservices?

Yes, there should be no harm in that. It adds to the payload but certainly can be done. Important thing to note is that users access token can be used by services to mimic a user call to another service. If such calls are threat to your design then you should reconsider. But mostly we feel that what ever you do within your boundary is safe and you can trust other services in that boundary and hence can pass it along.

Should there be a different authorization framework for internal requests?

It depends, if you want to separate it for security reason, you can, if you want to do it for load reason you can.
You can also think of stripping tokens at the gateway (verify the token at the entrypoint) and let go off it. For systems where you can trust other services (amongst your microservices) and ensure no on one can access them directly, other than the API gateways, you can just let the token go.
You loose authorization bit, but again our point is we trust services and believe they know what they are doing, so we do not put restrictions to such calls.


Q: How to change the default output folder for generated apk files? When I use the gradle task to create an android .apk file it outputs it the the build\javafxports\android folder of the project (both the regular and unaligned files). I couldn't find a setting to change the output folder.
When I export a jar in eclipse I can specify a destination folder. How can I do that with apk files too?
Here is my build.gradle file:
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.1.1'
    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'com.gluonapplication.GluonApplication'

dependencies {
    compile 'com.gluonhq:charm:4.0.1'
}

jfxmobile {
    downConfig {
        version = '3.0.0'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        compileSdkVersion = 24
        manifest = 'src/android/AndroidManifest.xml'
        androidSdk = 'C:/Users/Mark/AppData/Local/Android/sdk'
    }
    ios {
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

A: The jfxmobile plugin allows changing the path where the apk will be created.
Use installDirectory:
jfxmobile {
    downConfig {
        version = '3.0.0'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        installDirectory = file('/full/path/of/custom/folder')
        manifest = 'src/android/AndroidManifest.xml'
    }
}

Be aware that the folder should exist before running android task. Currently the plugin manages that for the default installation folder (removing it, and the apk, if exists and creating it again on every run). So you have to do it yourself, otherwise the task will skip it.
EDIT
The list of global variables that are intended to be modified if necessary are here, but the full list of variables currently included in the plugin can be found in the plugin source code.
Variables like installDirectory are used internally by the plugin and they are initialized with a default value, perform some actions like deleting the previous directory and creating it again (so Gradle performs the task). In case of overriding, these actions won't be executed, so you should take care of that yourself (or create a task for that).

A: This works for the standard android plugin to change the directory of the generated APKs:
android {
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.outputFile = file("/some/dir/" + variant.name + "/" + archivesBaseName + ".apk")
        }
    }
}


Q: Location of the built python module Hey people I built caffe module for nvidia jetson tx2 succesfully. But when I import caffe python throws  no module named caffe error. I have libcaffe.a libcaffe.so libcaffe.so.1.0.0 under the build directory. Where should I copy these files to make sure that python is able to import module.

A: When I have compiled from source, after running "cmake" I had to:

*

*cd into "python" folder (you shloud see the folder in the path you ran the "cmake") and run "pip install -e ."

*or, you will need to run make install.


Q: Handling JavaScript exceptions from Silverlight I'm having trouble adding proper exception handling to existing code that makes heavy use of Silverlight - JavaScript interoperability. In this case, my JavaScript can throw an exception that I want to handle meaningfully in Silverlight.
From Silverlight, I'm creating an instance of a JavaScript object, then later I'm calling a method on that object:
public class MyWrapper
{
    dynamic _myJSObject;

    public MyWrapper()
    {
        _myJSObject = HtmlPage.Window.CreateInstance("MyJSObject");
    }

    public int MyMethod()
    {
        try
        {
            int result = (int)_myJSObject.MyMethod();
        }
        catch (Exception ex)
        {
            // I want to add meaningful exception handling here
        }
    }
}

Whenever MyJSObject.MyMethod throws an exception, there are two problems:

*

*The browser shows a message that an exception has occurred.

*Information about the exception is not passed to my managed code. Instead I get a RuntimeBinderException which just says "Cannot invoke a non-delegate type" and contains no other information whatsoever. This does not seem to match what is described here; I'd expect an InvalidOperationException.

I've tried avoiding to cast the returned value of the method:
object tmp= _myJSObject.MyMethod();

This makes no difference. Changing the type of exception thrown on the JavaScript side has no effect either.
MyJSObject.prototype.MyMethod = function ()
                                {
                                    throw "Hello Silverlight!";
                                }

The only solution I can think of right now is abusing the function's return value to pass information about the exception, but that will make my code a whole lot uglier... so:
Why is the behavior I'm seeing different from what is described in documentation? Does it have to do with my use of dynamic somehow? How can I properly handle exceptions that occur in JavaScript in my managed code?

A: After quite a bit of experimentation, I concluded that there is no way to directly handle the JavaScript exception from Silverlight. In order to be able to process the exception, the JavaScript code needs to be changed slightly.
Instead of throwing the error, I return it:
function MyMethod()
{
    try
    {
        // Possible exception here
    }
    catch (ex)
    {
        return new Error(ex);
    }
}

Then on the Silverlight side, I use a wrapper around ScriptObject to turn the return value into an exception again. The key here is the TryInvokeMember method:
public class ScriptObjectWrapper : DynamicObject
{
    private ScriptObject _scriptObject;

    public ScriptObjectWrapper(ScriptObject scriptObject)
    {
        _scriptObject = scriptObject;
    }

    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        result = _scriptObject.Invoke(binder.Name, args);

        ScriptObject s = result as ScriptObject;
        if (s != null)
        {
            // The JavaScript Error object defines name and message properties.
            string name = s.GetProperty("name") as string;
            string message = s.GetProperty("message") as string;
            if (name != null && message != null && name.EndsWith("Error"))
            {
                // Customize this to throw a more specific exception type
                // that also exposed the name property.
                throw new Exception(message);
            }
        }

        return true;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        try
        {
            _scriptObject.SetProperty(binder.Name, value);
            return true;
        }
        catch
        {
            return false;
        }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        try
        {
            result = _scriptObject.GetProperty(binder.Name);
            return true;
        }
        catch
        {
            result = null;
            return false;
        }
    }

}

Potentially you could improve this wrapper so it actually injects the JavaScript try-catch mechanism transparently, however in my case I had direct control over the JavaScript source code, so there was no need to do this.
Instead of using the built in JavaScript Error object, it's possible to use your custom objects, as long as the name property ends with Error.
To use the wrapper, the original code would change to:
public MyWrapper()
{
    _myJSObject = new ScriptObjectWrapper(
                  HtmlPage.Window.CreateInstance("MyJSObject"));
}


Q: UITable View cellForRowAtIndexPath: How to return no cell I am trying to delete a cell from the table from the table view when no data is returned from Parse. But no matter what I try I can't find any solution to keep from having a blank cell (Cell when no data is passed) ahead of the cell with content.
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object

static NSString *simpleTableIdentifier = @"RecipeCell";

    NSString *identifier;
    if (indexPath.row == 0) {
        identifier = @"Cell";
    } else if (indexPath.row == 1) {
        identifier = @"Cell2";
    }

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];

    }

// Configure the cell

if (![@"test"  isEqual: [object objectForKey:@"teacher"]]){

    UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
    nameLabel.text = @"";

    UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
    prepTimeLabel.text = @"";

return cell;

} else {

    UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
    nameLabel.text = [object objectForKey:@"message"];

    UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
    prepTimeLabel.text = [object objectForKey:@"teacher"];

    return cell;

}
}

Thanks for any help given!

A: You cannot control the number of cells in a UITableView from the cellForRowAtIndexPath method - You need to return the correct value from the numberOfRowsInSection method.  Refer to the UITableViewDataSource protocol reference and the Table View Programming Guide
Addtionally, this code block -
if (indexPath.row == 0) {
    identifier = @"Cell";
} else if (indexPath.row == 1) {
    identifier = @"Cell2";
}

is somewhat redundant - all of your cells are UITableViewCellStyleDefault, so they are interchangeable.  Using two different identifiers is not necessary - If you intend to use different custom cell types in the future then you can keep this concept, but you probably wouldn't use the indexPath.row directly, rather you would be driven by the data type in your model for the row in question.


Q: Kendo Chart not performing as expected My understanding of Kendo bar charts in series is that the data value should sum up per item, but in this screen shot each set of bars is an interval, and based on interval 1 input data I should have 3 colors(services)summing to a total of 22, instead I just have the largest service displaying it's portion of the bar, what am I missing here?
Sandbox link: https://codesandbox.io/s/festive-saha-hg8oq3
Imgur link to image

A: Self solved, was grouping on wrong variable


Q: Java - Check if user input partialy matches another string? I have a problem where i want to see if the input user has enterd partially matches, or as long as majority matches with the answer, if it does then it should print out "Almost correct".
For example lets say the answer is Football, but user instead puts in Footbol. It should then print out Almost correct.
here is what i tried. But the problem is that it just checks if the whole word is containd in ENG otherwise if even one Char is missing it doesnt work.
     if (Answer.equalsIgnoreCase(ENG)){
        r = "Correct";
    }
    else if (Answer.toLowerCase().contains(ENG.toLowerCase().)){
        r = "Almost correct";
    }
    else {
        r = "Wrong";
    }
    System.out.println(r)

A: This code is certainly not perfect, but it basically compares the Strings and saves how many characters matched the corresponding character in the other String. This of course leads to it not really working that well with different sized Strings, as it will treat everything after the missing letter as false (unless it matches the character by chance). But maybe it helps regardless:
String match = "example";
String input = "exnaplr";
int smaller;
if (match.length() < input.length())
    smaller = match.length(); else smaller = input.length();
int correct = 0;
for (int i = 0; i < smaller; i++) {
    if (match.charAt(i) == input.charAt(i)) correct++;
}
int percentage = (int) ((double) correct / match.length() * 100);

System.out.println("Input was " + percentage + "% correct!");