text:
Q: Problem with ConfigurationStoreOptions while upgrading to Duende IdentityServer 6.0 I have some integration tests that use a real database targetting a ConfigurationDbContext.  When upgrading to Duende IdentityServer 6.0, the constructor for ConfigurationDbContext breaks (only accepts 1 arg instead of 2) because of the DbContext connection pooling feature that was added.
This code breaks:
public static ConfigurationDbContext GetConfigurationDbContext()
{
    var connectionString = Configuration.GetConnectionString("ConfigurationDbContext");
    var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
    builder.UseSqlServer(connectionString);
    var options = new ConfigurationStoreOptions
    {
        DefaultSchema = Schema.IdSrv
    };
    return new ConfigurationDbContext(builder.Options, options);
}

So I changed it to:
    return new ConfigurationDbContext(builder.Options);

Now I can build, but my tests fail with this error:
Unable to resolve service for type 'Duende.IdentityServer.EntityFramework.Options.ConfigurationStoreOptions'
How am I supposed to pass the ConfigurationStoreOptions in?  Looking at the code in Github, it looks like it relies on dependency injection.  (Getting the options from services collection).

A: OK, I figured out my own problem, but I had to hunt and peck around.  It is not listed as a breaking change in the upgrade documentation:
https://docs.duendesoftware.com/identityserver/v6/upgrades/v5.2_to_v6.0/
The solution is to upgrade your project to 6.1
<PackageReference Include="Duende.IdentityServer.EntityFramework.Storage" Version="6.1.5" />

Then you can use this code instead (StoreOptions has been made a public set property)
public static ConfigurationDbContext GetConfigurationDbContext()
{
    var connectionString = Configuration.GetConnectionString("MyIdentity");
    var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
    builder.UseSqlServer(connectionString);
    var options = new ConfigurationStoreOptions
    {
        DefaultSchema = Schema.IdSrv
    };
    var dbContext = new ConfigurationDbContext(builder.Options);
    dbContext.StoreOptions = options;
    return dbContext;
}

This will work for ConfigurationDbContext and PersistedGrantDbContext.


text:
Q: Changing Annotation Image on Maps with Mapbox Within my application I need to have four different annotation images that signify differing location types. I have looked through and have found some information on this topic, however not related to Mapbox.
Currently, the user is able to filter through the differing types of locations. This is because within my database, annotations are distinguished by type within Firebase . Type: 1 = Skateparks, Type: 2 = Street Skating etc.
Through reading information on stack overflow I believe I need to create a custom annotation, which I have done.
class SkateAnnotation: MGLPointAnnotation {

var canEdit = false
var id: String!
var type: SkateType!

}

And I have applied the type to my annotation.
  func addAnnotation(park: Skatepark) {

    let point = SkateAnnotation()

    point.coordinate = park.coordinate

    point.title = park.name

    point.id = park.id

    point.subtitle = park.subtitle

    point.canEdit = park.editable

    point.type = park.type

    mapView.addAnnotation(point)

    mapView.selectAnnotation(point, animated: true)

}

The only part I am getting confused upon is applying these types to different images. Currently my code looks like this, which just applies one image to all annotations.
    func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {

 //   return nil

    var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: "SkateAnnotation1")

    if annotationImage == nil {

        var image = UIImage(named: "SkateAnnotation1")!

        image = image.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: 0, bottom: image.size.height / 2, right: 0))

        annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: "SkateAnnotation1")

    }

    return annotationImage

}

}

Is anybody able to help with setting images to annotation by their type?
My filter annotation code:
  func sideBarDidSelectButtonAtIndex(_ index: Int) {

   mapView.removeAnnotations(mapView.annotations!)

    for park in skateparks {

        if index == 0 {
            addAnnotation(park: park)

        }

        if index == 1 && park.type == .park {
            addAnnotation(park: park)

        }

        if index == 2 && park.type == .street {
            addAnnotation(park: park)

        }

        //Change this to feature the users own personal spots they saved to firebase

        if index == 3 && park.type == .own {
            addAnnotation(park: park)

        }

    }

}

A: In my app I have two different annotations with different images for each: - CameraNotation and NoteAnnotation. I subclass MGLAnnotation for each like this:
// MGLAnnotation protocol reimplementation
class NoteAnnotation: NSObject, MGLAnnotation {

// As a reimplementation of the MGLAnnotation protocol, we have to add mutable coordinate and (sub)title properties ourselves.
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?

// Custom properties that we will use to customize the annotation.
var image: UIImage?
var reuseIdentifier: String?
var uuid: String?

init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?) {
    self.coordinate = coordinate
    self.title = title
    self.subtitle = subtitle

    self.reuseIdentifier = "noteAnnotation"
}
}

Notice the reuseIdentifier. Set a new one for each of your annotation types. Then in your viewController you can check for each like this:
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    // We're not concerned with the user annotation.
    guard annotation is CameraAnnotation || annotation is NoteAnnotation else {
        return nil
    }

    // For better performance, reuse existing annotations. To use multiple different annotation views, change the reuse identifier for each.
    if annotation is CameraAnnotation {
        if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "cameraAnnotation") {
            return annotationView
        } else {
            return DraggableAnnotationView(reuseIdentifier: "cameraAnnotation", size: CGSize(width: 39, height: 39), annotation: annotation)
        }
    } else if annotation is NoteAnnotation {
        if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "noteAnnotation") {
            return annotationView
        } else {
            return DraggableAnnotationView(reuseIdentifier: "noteAnnotation", size: CGSize(width: 39, height: 39), annotation: annotation)
        }
    }  else {
        return DraggableAnnotationView(reuseIdentifier: "draggablePoint", size: CGSize(width: 39, height: 39), annotation: annotation)
    }
}

My points are draggable hence the DraggableAnnotationView calls but you go your own way. Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I audit my audit logs in rails? I have an audit log which works great in my rails application. What is the best approach to make audits of the audit log. How can I track any changes or prevent them? Basically i am worried about the value of the audit logs if someone can tamper with them. I need to be able to audit my audit logs. And then...... audit the audits of my audit logs, so on so forth into infinity.
So far I have tried adding auditing to my audit logs. But then I run into the issue of those audit logs not being audited if they are removed or modified.


text:
Q: Unable to solve nonlinear equations in Matlab I am using Matlab Symbolic Toolbox with its solve function and attempting to solve a nonlinear system of 4 equations,
with 4 variables:
x1 y1 x2 y2

and 4 parameters
 delta1 delta2 alpha beta

The equations are described in the following image:

Here is the Matlab code:
syms x1 x2 y1 y2 alpha beta delta1 delta2

[x1,y1,x2,y2] = solve('delta1 * x1^alpha * y1^(1 - alpha) = (1 - x2)^alpha * (1 - y2)^(1-alpha)',...
    'delta2 * x2^alpha * y2^(1 - alpha) = (1 - x1)^beta* (1 - y1)^(1-beta)',...
    'alpha / (1-alpha) * (1 - y2) / (1 - x2) = beta / (1 - beta) * y2/x2',...
    'alpha / (1-alpha) * y1 / x1 = beta / (1 - beta) * (1 - y1) / (1 - x1)','x1','y1','x2','y2')

Matlab returns:

Warning: Explicit solution could not be found.
> In solve at 81

However, if I try to substitute both alpha and beta to 0.5.
[x1,y1,x2,y2] = solve('delta1 * x1^0.5 * y1^ 0.5 = (1 - x2)^0.5* (1 - y2)^0.5',...
    'delta2 * x2^0.5 * y2^0.5 = (1 - x1)^0.5* (1 - y1)^0.5',...
    '(1 - y2) / (1 - x2) = y2/x2',...
    'y1 / x1 = (1 - y1) / (1 - x1)','x1','y1','x2','y2')

then Matlab will give result.
So I wonder:

*

*Are the equations really unsolvable?

*If it can solved, am I using Matlab Symbolic Toolbox in the wrong way? Matlab can actually solve it.

*If Matlab is not capable enough to solve it, are there other tools that can solve nonlinear equation system?

A: Almost certainly, no, these are not analytically solvable. Unless alpha and beta are 1 or zero (or apparently 1/2), the equations will be equivalent to something that is too high of an order for analytical solution, though I cannot be certain of that without looking more carefully. But for general real alpha, this is too much to do.
Yes, I know that computers are big, fast, powerful. They can do anything, right? But look at what happens when you try to solve simultaneous polynomial equations like this.
For example, two quadratic equations in two unknowns will reduce to a 4th order equation when you eliminate one of the unknowns. A 4th order polynomial equation, with non-constant coefficients is solvable. But you have FOUR equations, each of which is essentially quadratic in nature. (There are products of variables in each equation.) So 4 of them will be equivalent to an eighth order polynomial, if you will try to solve it symbolically. It will have general non-constant coefficients. And we know that a 5th order polynomial or higher generally won't have an analytical solution. So while you MIGHT get lucky, perhaps for some special values of alpha & beta, almost certainly, there is no such analytical solution.
And for general real alpha, things are worse. There is no expectation at all that a solution exists. The fact that when you tried, it failed backs that up. But, hey, a bigger computer might find an answer. Sorry, but not true.

A: You should try Matlab's mupad command. It opens a symbolic programming environment similar to Maple which is much more powerful than the symbolic library. If your equations have solutions (even some imaginary ones, or if they have solutions is really specific cases) the symbolic environment will for sure find them.
Give it a try!
Edit:
seeing @woodchips answer (that seem to know much more than me on this!) you can also try solving the equations for known alpha beta ranges. You can make assumptions of what values will they have and iterate from a range. I just don't know if it will work, it is just what I would try to do in your case.
Still don't quit trying with mupad, it may work (spatially if you make assumptions, like: assume alpha real kind of commands. just check the help)


text:
Q: Should admin account be in the same user class as a customer? I learn Grails and Spring Security plugin.
I don't know how to design sample web application with two layers: customer can view product and categories and order a product (if he/she is registered and logged in) and admin who can logged in to admin panel where he/she can manage categories and products (CRUD). My question is: should all users (admin and customer)  be in one User class? I suppose that all apllication (catalog and admin panel) should be secured by Spring Security plugin.

A: If you're using the Spring Security plugin then the default behavior assumes all users are instances of the same class. You can distinguish between an administrator and a customer by checking what's returned by the roles property of the user class.
The plugin provides a service and various Grails tags that you can use to figure out whether a user is an administrator, a cusomer, is authenticated, etc.

A: yes all users should be one class. and then you assign roles to each user. for example a user can have the ROLE_USER, and another user can have the ROLE_USER,ROLE_ADMIN


text:
Q: Batch File - Get filename from directory and save as variable I am trying to read in a directory and get the filename from that directory.
I then want to save the filename as a variable and echo that filename out.
Here is the code I am using:
 for /F %%a in ('dir C:\Users\username\Documents\Training\Pentaho\Outputs\BatchFileOutput\ *.csv') do set FileName=%%a
 echo %FileName%

I am getting the following when command prompt runs:
"File not found
Directory"
Does anyone know how to resolve this or where I'm going wrong?
Thanks

A: Safer way of doing the same:
@echo off
setlocal
set "yourDir=C:\Users\username\Documents\Training\Pentaho\Outputs\BatchFileOutput\"
set "yourExt=*.csv"
pushd %yourDir%
for %%a in (%yourExt%) do echo %%a
popd
endlocal

Sets both: Your directory and the extension you are searching for, Changes the directory to the one previously setted possibly including a /drive change and then runs a loop over all files matching your extension and echo them out. To save only the last one you can use:
...do set fileName=%%a
echo %FileName%

Or to use them all within the loop you can use:
@echo off
Setlocal EnableDelayedExpansion
REM Other things done here

do (
REM Do stuff with %%a here
Set filename=%%a
echo !filename!
echo !filename:~0,6!
echo !filename:a=b!
)

If you just want to echo them, you can just go for echo %%a. If you want to do other things like string-substitution or substrings as described in the comments you need DelayedExpansion as shown above. There are a lot of questions on SO as well.
Note that you can get different "parts" of the path of your file. Have a look on this answer I always have a look on as well. Alternatively check the documentation for the for command typing for /? into the command-line.


text:
Q: How can I run a mklink system command (cmd.exe) from a delphi 7 aplpication In my application at runtime I want to run the cmd line Mklink /d (link location) (actual file/folder location).
So far I have:
symLink := PChar('/d C:\Data\'+fileName+' N:\"Database Archives"\'+fileName);

ShellExecute(0, nil, 'Mklink', symLink, nil, SW_SHOWNORMAL);

but I have also tried:
symLink := PChar('Mklink /d C:\Data\'+fileName+' N:\"Database Archives"\'+fileName);

ShellExecute(0, nil, 'cmd.exe', symLink, nil, SW_SHOWNORMAL);

Am I along the right lines?
Is there any documentation to explain each parameter required by ShellExecute?

A: Simply put, don't do this. Use the API. It's called CreateSymbolicLink. Pass the SYMBOLIC_LINK_FLAG_DIRECTORY flag.
This is much more robust and allows you to report errors properly, cope with systems that don't have cmd.exe and so on.
Do note that creating symbolic links requires the process to be elevated. I trust you already know that. Do also check for errors as described the linked documentation.
More broadly you'll need to reconsider the specific paths in your question. You cannot make cross volume symbolic links.
As regards documentation, these are Windows functions. Just type the name into a search engine and you will find the MSDN docs.

In an older Delphi you'll need to define the function because the supplied header translations don't have it.
const
  SYMBOLIC_LINK_FLAG_DIRECTORY = $00000001;

function CreateSymbolicLinkA(
  lpSymlinkFileName: PAnsiChar;
  lpTargetFileName: PAnsiChar;
  dwFlags: DWORD
): Boolean; stdcall; external 'kernel32';

function CreateSymbolicLinkW(
  lpSymlinkFileName: PWideChar;
  lpTargetFileName: PWideChar;
  dwFlags: DWORD
): Boolean; stdcall; external 'kernel32';


text:
Q: Entity framework not picking up data changes made in SSMS or LinqPad I'm using EF6 database first, and use the data in a WPF MvvmLight project. If I start the app, and display the patients list, then use either SSMS or LinqPad to change the data (say a name or date of birth), when I refresh the data via the app, it doesn't see the changes. Stopping the app and rerunning it doesn't help, nor does cleaning the solution before rerunning. Sometimes restarting Visual Studio helps, but then sometimes it only shows some of the modified data, not all.
Any ideas why this is happening? It makes it very hard to develop!


text:
Q: Enable Spring AOP or AspectJ This is following on from this question:
Spring autowired bean for @Aspect aspect is null
My initial understanding was that when using Spring AOP, classes annotated with @Aspect are created as spring managed beans, so dependency injection would work as normal.  However it seems that an object with the @Aspect annotation is created as a singleton outside the spring container, hence me having to configure it in XML like so in order to enable it as a spring managed bean:
<bean id="aspect" class="com.mysite.aspect" factory-method="aspectOf" />

This has now completely confused me.  I thought the following configuration would use spring AOP:
<context:component-scan base-package="com.mysite.aspectPackage"/>
<aop:aspectj-autoproxy/>

So it would scan for @Aspect annotations using component-scan creating aspect beans, and then autoproxy would create a beanPostProcessor which proxies all beans within my context with the appropriate advice.  I then thought to enable aspectJ I would need a completely different XML configuration (which incidentally I can't seem to find an example of in the documentation).  It would be this configuration that uses aspectJ to create aspects that would be outside of my container or which work by manipulating bytecode rather than proxying.
Note
This is not a question on the difference between spring AOP and aspect J, this is well articulated here:
Spring AOP vs AspectJ

A: @Component will create 2 instances, one inside the Spring container, one inside the aspectJ container.
use @Configurable to allow spring to manage dependency injection etc. for your class when instantiated by the aspectj container.
@Aspect is an aspectj style annotation that is supported by spring-aop, where runtime weaving is used to handle interception etc.
Compile-time weaving allows you to disregard the use of  as pointcuts will be present in the bytecode, this is done via the aspectj compiler (See https://www.mojohaus.org/aspectj-maven-plugin/ for mvn integration) .
Whether you use the aspectj compiler or spring-aop makes no difference, it wont create your aspect as a managed bean in the way you want unless you use factory / configurable.
Aspectj configuration is, strictly, the pointcut definitions etc that will be present inside your class.

A: @Aspect is not a spring annotation, and it is not detected by component-scan. So you have to register it somehow as a spring bean. The aspectOf solution works. You can also try
@Aspect
@Component


text:
Q: Magicline border animation - start animation from active class I am trying to use border animation (MagicLine from CSSTricks), its working fine but the only challange I am facing is, currently its starting first item and animating on all, but if I click on any item then I am adding the same class from first item and removing as well but animation begins from first items only
Here is the JS fiddle
Please help!!
NOTE: Or please suggest any CSS only solution to have this kind of animation

$(function() {
var $el, leftPos, newWidth;
        $mainNav2 = $("#example-two");
    $("#example-one").append("

");
    var $magicLine = $("#magic-line");
    $magicLine
        .width($(".current_page_item").width())
        .css("left", $(".current_page_item a").position().left)
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $magicLine.width());

    $("#example-one li").find("a").hover(function() {
        $el = $(this);
        leftPos = $el.position().left;
        newWidth = $el.parent().width();

        $magicLine.stop().animate({
            left: leftPos,
            width: newWidth
        });
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });

    $("#example-one > li").click(function () {
    alert(1);
     var _this = $(this);
      $("#example-one > li").removeClass('current_page_item');
      _this.parent().addClass('current_page_item');
    });
    });
* { margin: 0; padding: 0; }
body { font: 14px Georgia, serif; background: #2F2626; color: #eee; }

header { padding: 100px 0 0 0; display: block; }
header h1 { width: 960px; margin: 0 auto; }
a { color: #eee; }
a:hover { color: white; }

.nav-wrap {
 margin: 50px auto;
 background-color: rgba(0,0,0,0.6);
 border-top:    2px solid white;
 border-bottom: 2px solid white;
}

/* Clearfix */
.group:after { visibility: hidden; display: block; content: ""; clear: both; height: 0; }
*:first-child+html .group { zoom: 1; } /* IE7 */

/* Example One */
#example-one {
 margin: 0 auto;
 list-style: none;
 position: relative;
 width: 960px;
}
#example-one li {
 display: inline-block;
}
#example-one a {
 color: #bbb;
 font-size: 14px;
 float: left;
 padding: 6px 10px 4px 10px;
 text-decoration: none;
 text-transform: uppercase;
}
#example-one a:hover {
 color: white;
}
#magic-line {
 position: absolute;
 bottom: -2px;
 left: 0;
 width: 100px;
 height: 2px;
 background: #ff0000;
}
.current_page_item a {
 color: white !important;
}

      Home

Buy Tickets

Group Sales

Reviews

The Show

Videos

Photos

Magic Shop

A: This is because you are not setting the data attributes of the magic Line element after the click event.
Below lines where added:
$magicLine.data("origLeft", _this.position().left)
   .data("origWidth", _this.width());

See below code for solution.

$(function() {
  var $el, leftPos, newWidth;
  $mainNav2 = $("#example-two");

  /*
      EXAMPLE ONE
  */

  /* Add Magic Line markup via JavaScript, because it ain't gonna work without */
  $("#example-one").append("

");

  /* Cache it */
  var $magicLine = $("#magic-line");

  $magicLine
    .width($(".current_page_item").width())
    .css("left", $(".current_page_item a").position().left)
    .data("origLeft", $magicLine.position().left)
    .data("origWidth", $magicLine.width());

  $("#example-one li").find("a").hover(function() {
    $el = $(this);
    leftPos = $el.position().left;
    newWidth = $el.parent().width();

    $magicLine.stop().animate({
      left: leftPos,
      width: newWidth
    });
  }, function() {
    $magicLine.stop().animate({
      left: $magicLine.data("origLeft"),
      width: $magicLine.data("origWidth")
    });
  });

  $("#example-one > li").click(function() {
    var _this = $(this);
    $("#example-one > li").removeClass('current_page_item');
    _this.parent().addClass('current_page_item');
    // added lines below
    $magicLine.data("origLeft", _this.position().left)
      .data("origWidth", _this.width());
  });
});
* {
  margin: 0;
  padding: 0;
}

body {
  font: 14px Georgia, serif;
  background: #2F2626;
  color: #eee;
}

header {
  padding: 100px 0 0 0;
  display: block;
}

header h1 {
  width: 960px;
  margin: 0 auto;
}

a {
  color: #eee;
}

a:hover {
  color: white;
}

.nav-wrap {
  margin: 50px auto;
  background-color: rgba(0, 0, 0, 0.6);
  border-top: 2px solid white;
  border-bottom: 2px solid white;
}

/* Clearfix */

.group:after {
  visibility: hidden;
  display: block;
  content: "";
  clear: both;
  height: 0;
}

*:first-child+html .group {
  zoom: 1;
}

/* IE7 */

/* Example One */

#example-one {
  margin: 0 auto;
  list-style: none;
  position: relative;
  width: 960px;
}

#example-one li {
  display: inline-block;
}

#example-one a {
  color: #bbb;
  font-size: 14px;
  float: left;
  padding: 6px 10px 4px 10px;
  text-decoration: none;
  text-transform: uppercase;
}

#example-one a:hover {
  color: white;
}

#magic-line {
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100px;
  height: 2px;
  background: #ff0000;
}

.current_page_item a {
  color: white !important;
}

      Home

Buy Tickets

Group Sales

Reviews

The Show

Videos

Photos

Magic Shop


text:
Q: Colocar um balão em cima do input[type=range] Estou  gerando um form a partir de um php, ele gera um html igual a esse:

Você tem cabelos brancos?

  <input type="range" min="0" max="3" value=0 step="0.1">

    <input class="mf_option" type="hidden" name="mf[gray_hair#slider][]" id="id_0" value="Não">
    <input class="mf_option" type="hidden" name="mf[gray_hair#slider][]" id="id_1" value="Um Pouco">
    <input class="mf_option" type="hidden" name="mf[gray_hair#slider][]" id="id_2" value="Médio">
    <input class="mf_option" type="hidden" name="mf[gray_hair#slider][]" id="id_3" value="Muito">

O que quero fazer é que em cima do botão do range, apareça o value segundo os id dos input dentro div.class="mf_slider_content".
Para ajudar estou colocando esse codeopen. Se alguém souber como fazer isso.
UPDATE
Bom consegui fazer, mas o balão não aponta certinho para o botão do range ele da uma variada. Se alguém conseguir arrumar isso para mim agradeço imensamente.


text:
Q: Missing header in aastex package I'm using the aastex package (v5.2), and trying to make a header appear using the \shorttitle and \shortauthors commands (which take the place of \leftheader \rightheader), but they aren't working for me.  Here is my code:
\documentclass[12pt,preprint]{aastex}
\usepackage[left=1in,top=1in,right=1in,bottom=1in]{geometry}

\shorttitle{short title}
\shortauthors{short author}
\begin{document}
\title{Long Title}
\author{Long Author}
\bibliographystyle{plainnat}

\begin{abstract}
Test
\end{abstract}

\maketitle

\section{Introduction}
Text
\newpage
New page test
\end{document}

Anybody have any ideas?

A: hpesoj626 points out that the running headers from \shorttitle and \shortauthors don't actually appear on the document... for whatever reasons.  As per his recommendation, I'm using the fancyhdr package --- which is working nicely.

A: You can modify the plaintop page style that's used with the preprint option:
\makeatletter
\def\ps@plaintop{%
 \let\@mkboth\@gobbletwo
 \def\@oddfoot{}%
 \def\@evenfoot{}%
 \def\@oddhead{%
   \rmfamily\hfil\@rectohead\ --\ \@versohead\hfil\llap{\thepage}}%
 \let\@evenhead\@oddhead
}
\makeatother
\pagestyle{plaintop}

Modify to suit


text:
Q: Java terminate program upon user entry 'done' I am working on an array that stores a string of name and an integer of age, I want the array to be a max of 4 and print out these results, unless the user enters the word 'done', if so the program terminates and the array outputs what it has stored.
The array works fine but can't seem to get the 'done' section, that I am currently using an if statement with .equals
any suggestions?
Thanks
import java.util.Scanner;
import java.util.ArrayList;

public class NameAge {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        final int MAX_VALUE = 4;
        //boolean name = false;

        ArrayList<String> nameList = new ArrayList<String>();
        ArrayList<Integer> ageList = new ArrayList<Integer>();

        Integer[] ages = new Integer[4];

        for (int i = 0; i < MAX_VALUE; i++) {

            System.out.print("Enter a name: ");
            String currentLine = input.next();

            if (currentLine.equals("done")) {
            break;
            }

            nameList.add(currentLine);

            System.out.print("Now enter an age for " + currentLine + ": ");
            ageList.add(input.nextInt());

          }

        System.out.print("\n");
        for(int i = 0; i < MAX_VALUE; i++) {

            System.out.println("Name: " + nameList.get(i) + "   Age: " + ageList.get(i));

        }

    // display youngest and oldest member of array
    int smallest = ageList.get(0);
        int largest = ageList.get(0);

        String oldest = nameList.get(0);
        String youngest = nameList.get(0);

        for (int i = 0; i < ages.length; i++) {
            if(ageList.get(i) > largest) {
                largest = ageList.get(i);
                oldest = nameList.get(i);

            } else if(ageList.get(i) < smallest) {
                smallest = ageList.get(i);
                youngest = nameList.get(i);
            }
        }
                        System.out.println("\nThe youngest person is " + youngest + " who is " + smallest + " years old");
            System.out.println("The oldest person is " + oldest + " who is " + largest + " years old");

        }

    }

A: Ok, there are a couple of things to review in that code.
Variable name serves no purpose there, as it is only getting set to true each iteration. (You are maybe confusion = with == inside if statement?
Then, nameList is an ArrayList, so you can't compare it to a String, you need to get the value i of the ArrayList an then compare, such as:
if (nameList.get(i).equals("DONE")) {
    break;
}

A: *

*Remove the name boolean variable , it seems not useful.

*Why using two scanners. One is enough.
     Scanner input2 = new Scanner(System.in);

is not needed.

*Store first input.nextLine()  in a temporary variable and not in the final list in order to decide what do : going on or stopping :
String currentLine = input.nextLine()

*ages array is not needed. You have already a List to store age values :
ArrayList<Integer> ageList

*Scanner.nextLine() reads the whole line. It may have side effects. In your case, you need only line current input : use only next() or nextInt().
It should do the job :
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    final int MAX_VALUE = 4;

    ArrayList<String> nameList = new ArrayList<String>();
    ArrayList<Integer> ageList = new ArrayList<Integer>();

    for (int i = 0; i < MAX_VALUE; i++) {

        System.out.print("Enter a name: ");
        String currentLine = input.next();

        if (currentLine.equals("DONE")) {
        break;
        }

        nameList.add(currentLine);

        System.out.print("Now enter an age for " + currentLine + ": ");
        ageList.add(input.nextInt());

      }

    }

A: First, why do you need: if(name = true) {} You don't need that, and if you want to test if name is true you use double ==.
Second, with this line: nameList.equals("DONE") you are checking if ArrayList nameList object is equal to "DONE". You are not checking the elements of the ArrayList.
If you want to stop your program when someone enters word "DONE" then this is the code:
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);

final int MAX_VALUE = 4;
boolean name = false;
String chk = "";

ArrayList<String> nameList = new ArrayList<>();
ArrayList<Integer> ageList = new ArrayList<>();

Integer[] ages = new Integer[4];

for (int i = 0; i < MAX_VALUE; i++) {

    System.out.print("Enter a name: ");

    chk = input.nextLine();

    if (chk.equals("DONE"))
        break;

    nameList.add(chk);

    System.out.print("Now enter an age for " + nameList.get(i) + ": ");
    ageList.add(input2.nextInt());

}

If you want to enter word "DONE" to array and then check if array contains "DONE" then code is like this:
Scanner input = new Scanner(System.in);
          Scanner input2 = new Scanner(System.in);

          final int MAX_VALUE = 4;
          boolean name = false;
          String chk = "";

          ArrayList<String> nameList = new ArrayList<>();
          ArrayList<Integer> ageList = new ArrayList<>();

          Integer[] ages = new Integer[4];

          for(int i = 0; i < MAX_VALUE; i++ ) {

                  System.out.print("Enter a name: ");
                  nameList.add(input.nextLine());
                  if (nameList.contains("DONE"))    //use contains
                      break;

              System.out.print("Now enter an age for " + nameList.get(i) + ": ");
              ageList.add(input2.nextInt());

          }

A: The reason you get a index out of bounds is because you have a max value set to 4, that youre trying to loop even if the array is smaller. Since you have a person connected to an age, you can use HashMap to set name as key, and age as value and then use a lambda expression to print the hashmap when done adding new entries like this:
    Scanner input = new Scanner(System.in);
    final int MAX_VALUE = 4;
    HashMap<String, Integer> people = new HashMap<String, Integer>();

    for (int i = 0; i < MAX_VALUE; i++) {
        System.out.print("Enter a name: ");
        String name = input.next();

        if (name.equals("done")) {break;}

        System.out.print("Now enter an age for " + name + ": ");
        int age = input.nextInt();

        people.put(name, age);
    }
    input.close();
    System.out.print("\n");
    people.forEach((k,v)->System.out.println("Name : " + k + "  Age : " + v));


text:
Q: Identifying Exception in thread "main" java.lang.StackOverflowError My code is below, I am trying to recursively call my binary search function but keep getting this Exception. I am trying to identify the source of the issue. Keep in mind i've excluded my code for creating the array list for simplicity and because i know they are functional.
  import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.math.*;
public class nickclass {

public static void main(String[] args) {

for(int i = 0; i <(int)listTest.size();i++)
   {
  binarySearchHelp(listTest2,(String)listTest.get(i),0,listTest2.size());
 }

void binarySearchHelp(ArrayList list, String value, int left, int right) {

    if (left > right)
        System.exit(0);

    int middle = (int) Math.floor(list.size()/2);

    if (((String) list.get(middle)).compareTo(value) == 0)
        System.out.println(list.get(middle));

    else if (((String) list.get(middle)).compareTo(value) > 0)
         binarySearchHelp(list, value, left, middle - 1);

    else
         binarySearchHelp(list, value, middle + 1, right);

  }
}
}

A: The recursive call is never terminating (only when all memory is used) because middle is always the middle of the list, but it should be the middle between left and right:
middle = (left + right) / 2;

I would also check that the interval (left-right) is big enough to be divided or if the algorithm can stop... and System.exit is kind of brutal, you really want to stop the virtual machine without any message?


text:
Q: Change of color de my custom enter once is clicked my button im working with custon entry rendered, i need to hear  from xaml in my custom render when i clicked my button
i have this code in my xaml
<local:MyEntry   eventRefresh="true">

when i clicked my button this function is actived
private async void Execute(object sender)
        {
    var entry = ((MyEntry)view);
    entry.eventRefresh = "false";

but my EntryRendered donot hear the change
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                var element = Element as MyEntry;

A: Make your view model like this.
public class YourViewModel

  {
    public Command command
    {
        get
        {
            return new Command(() => {

               //Change here button background colors
               BackgroundColor = Color.Green;
            });
        }
    }

    private _backgroundColor = Color.White;
    public Color BackgroundColor
    {
        get { return _backgroundColor;}
        set
        {
             if (value == _backgroundColor)
                 return;

             _backgroundColor = value;
             NotifyOnPropertyChanged(nameof(BackgroundColor));
         }

}

}
Your XAML
 <local:MyEntry Text="{Binding Password}" Placeholder="Enter"  />

<Button Text="send" Command="{Binding command}" BackgroundColor="{Binding BackgroundColor}"></Button>

A: You should define the property eventRefresh as Bindable Property .
in your custom Entry
using System;

using System.ComponentModel;
using System.Runtime.CompilerServices;

using Xamarin.Forms;
namespace xxx
{
    public class MyEntry:Entry,INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public static readonly BindableProperty eventRefreshProperty = BindableProperty.Create("eventRefresh", typeof(bool), typeof(MyEntry), true,propertyChanged:(obj,oldValue,newValue)=> {

            //var entry = obj as MyEntry;

          //  entry.Text = newValue.ToString();

        });

        bool refresh;
        public bool eventRefresh
        {
            get { return refresh; }
            set {
                  if(refresh !=value)
                  {
                    refresh = value;
                    NotifyPropertyChanged("eventRefresh");
                  }

              }
        }

        public MyEntry()
        {

        }

    }
}

in xaml
<StackLayout  VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">

   <local:MyEntry eventRefresh="{Binding Refresh}" BackgroundColor="{Binding BGcolor}" WidthRequest="200" HeightRequest="50" />

   <Button Command="{Binding ClickCommand}"  />

</StackLayout>

in View Model
public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    Color color;
    public Color BGcolor
    {
        get { return color; }

        set
        {

            if (color != value)
            {
                color = value;
                NotifyPropertyChanged("BGcolor");
            }

        }
    }

    bool refresh;

    public bool Refresh
    {
        get { return refresh; }
        set
        {
            if (refresh != value)
            {
                refresh = value;
                NotifyPropertyChanged("Refresh");
            }

        }
    }

    public ICommand ClickCommand { get; set; }

    public MyViewModel()
    {
        BGcolor = Color.LightPink;

        ClickCommand = new Command(()=> {

            BGcolor = Color.Red;

        });

    }

}

in Custom Renderer

using System.ComponentModel;
using Android.Content;

using xxx;
using xxx.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly:ExportRenderer(typeof(MyEntry),typeof(NyEntryRenderer))]
namespace xxx.Droid
{
    public class NyEntryRenderer : EntryRenderer
    {
        public NyEntryRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            if(Control!=null)
            {
                Element.TextChanged += Element_TextChanged;
            }

        }

        private void Element_TextChanged(object sender, TextChangedEventArgs e)
        {
            // var content = Element.Text;
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == MyEntry.BackgroundColorProperty.PropertyName)
            {
                //  will been invoked when click button
            }

        }
    }
}


text:
Q: tsql trigger behaves abnormally I have a trigger which is as follows:
  ALTER TRIGGER [trigger_CATEGORY_VALUE_ID] ON [dbo].[tblA]
FOR UPDATE
AS
SET NOCOUNT ON
IF ( UPDATE([CATEGORY_VALUE_ID]))
BEGIN
  INSERT INTO [dbo].[htblB]
  ( ID
  , CATEGORY_VALUE_ID
  , STATUS_END_DATE
  , STATUS_END_DATE_SOURCE)
  SELECT
  t.ID
  , t.CATEGORY_VALUE_ID
  , GETDATE()
  , t.UPDATE_SOURCE
  FROM [dbo].[tblCAPITATION] t
  INNER JOIN inserted ins
  ON t.CATEGORY_VALUE_ID = ins.CATEGORY_VALUE_ID
END

What it needs to do is insert a new row in htblB when the column CATEGORY_VALUE_ID is updated. It works fine if only one row is updated. But if it has multiple row updates, then 2 to the power number of rows updated amount of new rows are inserted in htblB.
UPDATE dbo.tblCAPITATION
SET CAPITATION_STATUS_CATEGORY_VALUE_ID = '80574', UPDATE_SOURCE = 'TEST3'
WHERE CAPITATION_ID = 2 OR CAPITATION_ID = 3

This statement will insert 4 new rows to htblB instead of 2.
May you please shed some light on why this is hapening and how to prevent it?
Thanks!

A: I'm going to assume that ID is the primary key, if so then you should be joining inserted on ID not category_value_id
ALTER TRIGGER [trigger_CATEGORY_VALUE_ID] ON [dbo].[tblA]
FOR UPDATE
AS
SET NOCOUNT ON
IF ( UPDATE([CATEGORY_VALUE_ID]))
BEGIN
  INSERT INTO [dbo].[htblB]
  ( ID
  , CATEGORY_VALUE_ID
  , STATUS_END_DATE
  , STATUS_END_DATE_SOURCE)
  SELECT
  t.ID
  , t.CATEGORY_VALUE_ID
  , GETDATE()
  , t.UPDATE_SOURCE
  FROM [dbo].[tblCAPITATION] t
  INNER JOIN inserted ins
  ON t.ID = ins.ID
END


text: Q: Is it efficient to compress binary data from canonical Huffman? I am trying to learn compression algorithms using python ,so I was wondering that is it effective to use run length encoding or delta encoding on my final stream of binary data ('1011') that I get after canonical huffman? right now I am converting my binary data to bytes and storing it in a file, is there more efficient way to store my data ?


text:
Q: Create Android Library Project Only As much as I have researched, it seems that I am only able to create an Android Library within an Android Project. Is there any way in which I can create a Standalone Android Library and not have it within or alongside an App?
My scenario is to work on this Android Library and for it to create an AAR when I compile which I can then reference in a separate Android Project.
I so far have a project running but it has an App and a Library at the same level. I achieved this by creating a new project and then:
File -> New -> New Module -> Android Library.

A: *

*Create a new Android Library, we'll call it "MyAar" (File -> New -> New Module -> Android Library)

*Now there should be a folder named "MyAar" on the Android hierarchy (usually the left most window in Android Studio)

*Add all the source code you want in there under the "Java" folder, and adjust your build.gradle file accordingly (the one that says "Modele:MyAar" and begins with apply plugin: 'com.android.library').

*Highlight "MyAar" on the Android hierarchy window, then press Build -> Make Module 'MyAar' at the bar on the top (where File, Edit, View... is located)

*Go to the folder YOUR_ANDROID_APPLICATION/MyAar/build/outputs/aar, you will see a MyAar-debug.aar. That is your .aar which you can now drop into any other project.


text:
Q: Is it true NSZombies can cause a crash? I've read on here that NSZombies with ARC enabled can actually cause a crash and I've also read it can't be the cause of a crash.  People have said it can cause a crash by a bug where dealloc is not called on the object.  Is that true and is that still the case? I realize it could crash by running out of memory but is that the only time a crash could result from zombies being enabled?
The post I'm looking at is: NSZombie crashing app when enabled on the iPhone

A: It is not clear what you are asking.
By NSZombies, do you mean setting the NSZombies flag to true in your project? Yes, that will cause your program's memory to grow forever, and you will eventually run out of memory and crash. (When zombies are enabled, instead of releasing objects on dealloc, the runtime marks them as zombies and leaves their memory in use.)
If you mean can having zombies in your program (objects that get deallocated but your code tries to send messages to them) then yes, that can, and often does, cause crashes. Zombies are less common under ARC, but still possible.

A: Setting NSZombieEnabled does not cause a crash by itself.
Of course some otherwise hidden error in your app can show up as a side effect of the changes in memory usage.

People have said it can cause a crash by a bug where dealloc is not called on the object.

That is not the case. Enabling zombie detection does not prevent dealloc from being called.


text:
Q: Pandas apply function row by row Say I have this df:
sort_countries[["country", "Total"]].to_dict()
{'Total': {'Afghanistan': 1,
  'Albania': 1,
  'Algeria': 1,
  'Argentina': 6,
  'Armenia': 5,
  'Australia': 76,
  'Austria': 9,
  'Bangladesh': 1,
  'Barbados': 1,
  'Belarus': 12,
  'Belgium': 27,
  'Brazil': 34,
  'Bulgaria': 2,
  'Canada': 78,
  'Chile': 3,
  'China': 149,
  'Colombia': 4,
  'Costa Rica': 1,
  'Croatia': 4,
  'Czech Republic': 14,
  'Denmark': 6,
  'Ecuador': 1,
  'Egypt': 4,
  'El Salvador': 1,
  'Estonia': 7,
  'Finland': 18,
  'France': 125,
  'Germany': 106,
  'Greece': 18,
  'Hungary': 13,
  'India': 145,
  'Indonesia': 4,
  'Iran': 6,
  'Ireland': 10,
  'Israel': 28,
  'Italy': 31,
  'Japan': 74,
  'Kenya': 1,
  'Kyrgyzstan': 1,
  'Latvia': 2,
  'Lebanon': 1,
  'Lithuania': 7,
  'Luxembourg': 1,
  'Macedonia': 1,
  'Madagascar': 2,
  'Malaysia': 4,
  'Mauritius': 1,
  'Mexico': 3,
  'Moldova': 1,
  'Morocco': 2,
  'Mozambique': 1,
  'Nepal': 1,
  'Netherlands': 59,
  'New Zealand': 10,
  'Nigeria': 1,
  'North Korea': 1,
  'Norway': 6,
  'Pakistan': 1,
  'Panama': 1,
  'Philippines': 6,
  'Poland': 51,
  'Portugal': 15,
  'Qatar': 1,
  'Romania': 8,
  'Russian Federation': 223,
  'Senegal': 1,
  'Serbia': 3,
  'Singapore': 55,
  'Slovakia': 8,
  'Slovenia': 6,
  'South Africa': 13,
  'South Korea': 11,
  'Spain': 52,
  'Sri Lanka': 5,
  'Sweden': 20,
  'Switzerland': 24,
  'Taiwan': 27,
  'Thailand': 2,
  'Turkey': 10,
  'Ukraine': 40,
  'United Arab Emirates': 2,
  'United Kingdom': 117,
  'United States': 852,
  'Venezuela': 2,
  'Vietnam': 5},
 'country': {'Afghanistan': 'Afghanistan',
  'Albania': 'Albania',
  'Algeria': 'Algeria',
  'Argentina': 'Argentina',
  'Armenia': 'Armenia',
  'Australia': 'Australia',
  'Austria': 'Austria',
  'Bangladesh': 'Bangladesh',
  'Barbados': 'Barbados',
  'Belarus': 'Belarus',
  'Belgium': 'Belgium',
  'Brazil': 'Brazil',
  'Bulgaria': 'Bulgaria',
  'Canada': 'Canada',
  'Chile': 'Chile',
  'China': 'China',
  'Colombia': 'Colombia',
  'Costa Rica': 'Costa Rica',
  'Croatia': 'Croatia',
  'Czech Republic': 'Czech Republic',
  'Denmark': 'Denmark',
  'Ecuador': 'Ecuador',
  'Egypt': 'Egypt',
  'El Salvador': 'El Salvador',
  'Estonia': 'Estonia',
  'Finland': 'Finland',
  'France': 'France',
  'Germany': 'Germany',
  'Greece': 'Greece',
  'Hungary': 'Hungary',
  'India': 'India',
  'Indonesia': 'Indonesia',
  'Iran': 'Iran',
  'Ireland': 'Ireland',
  'Israel': 'Israel',
  'Italy': 'Italy',
  'Japan': 'Japan',
  'Kenya': 'Kenya',
  'Kyrgyzstan': 'Kyrgyzstan',
  'Latvia': 'Latvia',
  'Lebanon': 'Lebanon',
  'Lithuania': 'Lithuania',
  'Luxembourg': 'Luxembourg',
  'Macedonia': 'Macedonia',
  'Madagascar': 'Madagascar',
  'Malaysia': 'Malaysia',
  'Mauritius': 'Mauritius',
  'Mexico': 'Mexico',
  'Moldova': 'Moldova',
  'Morocco': 'Morocco',
  'Mozambique': 'Mozambique',
  'Nepal': 'Nepal',
  'Netherlands': 'Netherlands',
  'New Zealand': 'New Zealand',
  'Nigeria': 'Nigeria',
  'North Korea': 'North Korea',
  'Norway': 'Norway',
  'Pakistan': 'Pakistan',
  'Panama': 'Panama',
  'Philippines': 'Philippines',
  'Poland': 'Poland',
  'Portugal': 'Portugal',
  'Qatar': 'Qatar',
  'Romania': 'Romania',
  'Russian Federation': 'Russian Federation',
  'Senegal': 'Senegal',
  'Serbia': 'Serbia',
  'Singapore': 'Singapore',
  'Slovakia': 'Slovakia',
  'Slovenia': 'Slovenia',
  'South Africa': 'South Africa',
  'South Korea': 'South Korea',
  'Spain': 'Spain',
  'Sri Lanka': 'Sri Lanka',
  'Sweden': 'Sweden',
  'Switzerland': 'Switzerland',
  'Taiwan': 'Taiwan',
  'Thailand': 'Thailand',
  'Turkey': 'Turkey',
  'Ukraine': 'Ukraine',
  'United Arab Emirates': 'United Arab Emirates',
  'United Kingdom': 'United Kingdom',
  'United States': 'United States',
  'Venezuela': 'Venezuela',
  'Vietnam': 'Vietnam'}}

And for each column I want to register another column with the iso3 code:
def get_3_code_country(country):
    url = 'https://restcountries.eu/rest/v2/name/' + quote(country.country[0], safe='')
    r = requests.get(url)
    response = r.json()
    return response[0]['alpha3Code']

import requests
from urllib.parse import quote

data_javascript_map = sort_countries.assign(
     iso_3=lambda x: get_3_code_country(x), axis = 1
)
data_javascript_map

This obviously returns only the first country because I use country.country[0]. But I want to get all countries one by one.
Tried country.country.item() as suggested in other answers without luck. But I'm getting the whole series and not 1 by 1. Is there a way in the apply method to do it 1 by 1 and not a whole series so that I can avoid doing a for loop in my function?

A: Modify your function as such:
def get_3_code_country(c):
     url = 'https://restcountries.eu/rest/v2/name/' + quote(c, safe='')
     ...

Now, call apply on df.country:
df['iso_3'] = df.country.apply(get_3_code_country)

Beware! This is a requests operation, it's going to be slow.

I received a KeyError when trying this out. Maybe some of these countries aren't supported? Try adding a try-except brace:
try:
    return response[0]['alpha3Code']
except KeyError:
    return None


text:
Q: Autowiring issue with JUnit in a Spring Data JPA environment i have issues with @autowired in my unit tests.
here are the relevant classes and xml files:
The Service Class:
@Service(value = "statusService")
public class StatusService implements DefaultService<Status> {

  @Autowired(required = true)
  private StatusRepository statusRepository;

  public void save(Status value) {
    statusRepository.save(value);

  }
}

The Interface:
public interface DefaultService<T> {
  @Transactional
  void save(T value);

}

(i also tested a non generic interface, but the result was the same.)
The Test Class:
@ContextConfiguration(locations={"**/WEB-INF/applicationContext.xml", "**/WEB-INF/hibernate-context.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class StatusServiceTest
{
    @Autowired
    private StatusService statusService;

    @Test
    public void test()
    {
        Status s = new Status();
        s.setDescription("desc");
        s.setStatus("status");

        statusService.save(s);
    }
}

The Application Context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/data/jpa
            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
     For example @Controller and @Service. Make sure to set the correct base-package-->
    <context:component-scan base-package="at.jba.ticketbox" />
    <jpa:repositories base-package="at.jba.ticketbox.repositories" />

    <!-- Activates various annotations to be detected in bean classes -->
    <context:annotation-config />

    <!-- Configures the annotation-driven Spring MVC Controller programming model.
    Note that, with Spring 3.0, this tag works in Servlet MVC only!  -->
    <mvc:annotation-driven />

    <!-- Load Hibernate related configuration -->
    <import resource="hibernate-context.xml" />

</beans>

The Hibernate-Context
<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"

        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            ">

    <context:property-placeholder location="/WEB-INF/spring.properties" />

    <!-- Enable annotation style of managing transactions -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
    <!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
    <!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
    <!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
<!--    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
                 p:dataSource-ref="dataSource"
                 p:configLocation="${hibernate.config}"
                 p:packagesToScan="at.jba.ticketbox"/>   -->

    <!-- Declare a datasource that has pooling capabilities-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
                p:driverClassName="${jdbc.driver}"
                p:url="${jdbc.url}"
                p:username="${jdbc.username}"
                p:password="${jdbc.password}"
                />

    <!-- Declare a transaction manager-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
                p:entityManagerFactory-ref="entityManagerFactory" p:dataSource-ref="dataSource" />

      <!-- JPA Entity Manager Factory -->
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:dataSource-ref="dataSource"
          p:persistenceXmlLocation="META-INF/persistence.xml"
          p:persistenceUnitName="springJpaPersistenceUnit_TEST" />

    <!-- bean post-processor for JPA annotations -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

</beans>

and the stack trace:
INFO : org.springframework.test.context.TestContextManager - @TestExecutionListeners is not present for class [class at.jba.ticketbox.service.interfaces.DefaultServiceTest]: using defaults.
INFO : org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext@63afe611: startup date [Tue Mar 13 15:19:44 CET 2012]; root of context hierarchy
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5543bd5c: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@4ad70ab0] to prepare test instance [at.jba.ticketbox.service.interfaces.DefaultServiceTest@6bfecf32]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'at.jba.ticketbox.service.interfaces.DefaultServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private at.jba.ticketbox.service.StatusService at.jba.ticketbox.service.interfaces.DefaultServiceTest.sr; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [at.jba.ticketbox.service.StatusService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private at.jba.ticketbox.service.StatusService at.jba.ticketbox.service.interfaces.DefaultServiceTest.sr; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [at.jba.ticketbox.service.StatusService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [at.jba.ticketbox.service.StatusService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    ... 28 more
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@63afe611: startup date [Tue Mar 13 15:19:44 CET 2012]; root of context hierarchy
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5543bd5c: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy

i tried to autowire the interface (the generic one too) instead of the Service Class, cause i´ve read that there probably are issues.
i tried it with an @Resource, same stacktrace
i tried writting a non generic interface
...
i find it strange that the, application runs perfectly on an tomcat server as a web application. no problems there saving and deleting Objects. I still don´t understand why the tests aren´t working.
plz help ;) thx

A: By default, locations parameter of @ContextConfiguration annotation is assuming classpath: protocol, so you need to explicitly specify file: protocol when loading files not in the classpath, e.g. context located within WEB-INF folder:
@ContextConfiguration(locations={
    "file:**/WEB-INF/applicationContext.xml", "file:**/WEB-INF/hibernate-context.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class StatusServiceTest
  ...


text:
Q: Need help in SQL Select Query Need some help with this query, I just want to know if what I am doing is fine or do I need JOIN to get it better. Sorry if this a silly question but I am little worried as I query the same table thrice. Thanks in advance
Select *
from TableA
where (A_id in (1, 2, 3, 4)
       and flag = 'Y') or
      (A_id in
            (select A_id from TableB
             where A_id in
                        (Select A_id from TableA
                         where (A_id in (1, 2, 3, 4)
                           and flag = 'N')
             group by A_id
             having sum(qty) > 0)
    )

Relation between TableA and TableB is one-to-many
Condition or Logic:

*

*if the flag is true, the data can be selected without further checks

*if the flag is false, we have to refer TableB to see if sum of the qty column is greater than 0

A: Your approach is indeed way too complicated. Select from A where flag = Y or the sum of related B > 0. Do the latter in a subquery.
select *
from a
where a_id in (1,2,3,4)
and
(
  flag = 'Y'
  or
  (select sum(qty) from b where b.a_id = a.a_id) > 0
)

A: There's nothing badly wrong with the query you've presented, but there are improvements that can be made.  If you move the test for Flag='N' into your first select from TableA and correlate your select from TableB with your first select from TableA, then you can dispense with the second select from TableA:
Select *
from TableA A
where A_id in (1, 2, 3, 4)
  and (flag = 'Y'
   or (flag = 'N'
  and A_id in (select A_id
                from TableB B
               where b.A_id = a.A_id
               group by A_id
              having sum(qty) > 0))
    );

This will eliminate an extra lookup on TableA for information that should already be known.  Second since TableA.A_Id is now correlated with TableB.A_Id, the A_Id in (...) can be changed to an exists clause:
Select *
from TableA A
where A_id in (1, 2, 3, 4)
  and (flag = 'Y'
   or (flag = 'N'
  and exists (select A_id
                from TableB B
               where b.A_id = a.A_id
               group by A_id
              having sum(qty) > 0))
    );

This may (depending on the database type) inform the databases query optimizer that it can stop retrieving rows from TableB after the first row is found.
In an Oracle database on a small unindexed sample dataset these two changes shaved 25% off of the cost of the query, so the performance increases could be significant.

A: Would it be possible for you to split this query into a store procedure?
In Example:
DELIMITER $$

CREATE FUNCTION flaggedSelection ( my_flag varchar(1) )
RETURNS varchar(255) -- TODO: change to appropriate output

BEGIN

DECLARE return_value varchar(255); -- TODO: change to appropriate output

IF flag = 'Y'
THEN
  -- Performe select without further checks
  -- return_value = QUERY;
ELSE
  -- Refer TableB to see if sum of the qty column is greater than 0
  -- return_value = QUERY;
END IF;

RETURN return_value;

END; $$

DELIMITER;


text:
Q: Checksum function between Arduino and Java I am implementing a serial protocol for communications from Arduino to Java (one way).
Every frame I send from the Arduino looks like that:
"G FF FF FFFF FFFF FFFF FFFF T" (The spaces are not part of the frame)

*

*G signifies that a frame starts and the only possible value is G.

*The Fs are the payload encoded as HEX-values. Possible values: [0-F]

*T is a checksum. Possible values: [H-Z]
In order to calculate the checksum I have writen a function for Arduino and Java. However, using these functions I get about 50% corrupted frames when I receive them on the Java side.
I believe that the problem has something to do with the fact that Java variables cannot be unsigned. Can you spot the mistake? Or is it simply possible that a simple serial connection corrupts 50% of the frames I send? FRAME_LENGTH_WITHOUT_CRC is 21.
Java code:
char checksum(byte[] frame) {
    short sum = 0;
    for (short i = 0; i < Config.FRAME_LENGTH_WITHOUT_CRC; i++) {
        sum += (char)frame[i];
    }
    return (char) ('H' + sum % 16);
}

Arduino C code:
char checksum(const char * str)
{
  uint8_t sum = 0;
  for (uint8_t i = 0; i < FRAME_LENGTH_WITHOUT_CRC; i++) {
    sum += (uint8_t)str[i];
  }
  return 'H' + sum % 16;
}

A: I read the buffers before all the data arrives, therefore I read less data than 21 bytes which I assume that has arrived. I assumed that in an InputStream the in.read(array[], offset, size) reads all the size bytes before it returns, but apperantly it doesn't. – Dimme

A: The message is string, thus you have to convert from character to number. You're just lucky, you had correct checksum in at 50%.
int charFromHex(char x)
{
   if ((x >= '0') && (x <= '9'))
   {
     return x - '0';
   }
   else if ((x >= 'A') && (x <= 'F'))
   {
      return x - 'A' + 10;
   }
   else
   {
     return 0;
     //somehow handle error!
   }
{


text:
Q: Error configuring application listener of class [org.apache.logging.log4j.web.Log4jServletContextListener] I´m trying to execute a web app using log4j2 on tomcat 9. I added log4j api, core and web jar files to java build path, as weel to Deployment Assembly, but no matter what I do I´ve got java.lang.ClassNotFoundException: org.apache.logging.log4j.web.Log4jServletContextListener:
jun 08, 2022 10:59:32 AM org.apache.catalina.core.StandardContext listenerStart
GRAVE: Error configuring application listener of class [org.apache.logging.log4j.web.Log4jServletContextListener]
java.lang.ClassNotFoundException: org.apache.logging.log4j.web.Log4jServletContextListener
at
tomcat web.xml:
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j2.properties</param-value>
    </context-param>

    <listener>
        <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
    </listener>

    <filter>
        <filter-name>log4jServletFilter</filter-name>
        <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>log4jServletFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
        <dispatcher>ASYNC</dispatcher><!-- Servlet 3.0 w/ disabled auto-initialization only; not supported in 2.5 -->
    </filter-mapping>
</web-app>

log4j2.properties:
# Print configuration errors only
status=error

# Console appender
appender.console.type=Console
appender.console.name=LogToConsole
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

# Rotate log file
appender.rolling.type=RollingRandomAccessFile
appender.rolling.name=LogToRollingRandomAccessFile
appender.rolling.fileName=C:\\TEMP\\server.log
appender.rolling.filePattern=logs/${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz
appender.rolling.layout.type=PatternLayout
appender.rolling.layout.pattern=%d %p %C{1.} [%t] %m%n
appender.rolling.policies.type=Policies
appender.rolling.policies.time.type=TimeBasedTriggeringPolicy
appender.rolling.policies.size.type=SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=1024KB
appender.rolling.strategy.type=DefaultRolloverStrategy
appender.rolling.strategy.max=10

# Root logger
rootLogger.level=info
rootLogger.appenderRef.console.ref=LogToConsole
rootLogger.appenderRef.rolling.ref=LogToRollingRandomAccessFile


text:
Q: How to change position on scroll in tinyscrollbar on load I'm using tinyscrollbar.
There is Property contentPosition   (Number, The position of the content relative).
I cant' figure out how to change it.
My current js is:
$(document).ready(function() {
    if ( $("#contact-page__scrollbar").length > 0 ) {
        $("#contact-page__scrollbar").tinyscrollbar( {
            axis: 'x'
        })
    }
});

A: Sorry, found solution myself
$(document).ready(function() {
    if ( $("#contact-page__scrollbar").length > 0 ) {
        var $scrollbar6 = $("#contact-page__scrollbar");
        $scrollbar6.tinyscrollbar( {axis: 'x'});
        var scrollbar6 = $scrollbar6.data("plugin_tinyscrollbar");
        var anchorPosition = 92;
        scrollbar6.update(anchorPosition);
        return false;
    }
});


text:
Q: undefined reference to `SDL_Init' in an external library so i am making a class in an external library to use it in an SDL project.
when using a single file sdl is linked correctly and works fine.But when i use the external library
i get Screen.cpp:7: undefined reference to `SDL_Init' i use main.cpp, Screen.cpp and Screen.h
this is Screen.h
#ifndef TEST_CLASSSDL_SCREEN_H
#define TEST_CLASSSDL_SCREEN_H
#include "C:/dev/i686-w64-mingw32/include/SDL2/SDL.h"
    class Screen {
    public:
        void init();
    };
#endif

and this is Screen.cpp
#include "Screen.h"
void Screen::init() {
SDL_Init(SDL_INIT_VIDEO);
}

and CMakeLists.txt (used by clion and very important here)
cmake_minimum_required(VERSION 3.15)
project(test_classSDL)
set(SDL2_LIB_DIR C:/dev/i686-w64-mingw32/lib)
include_directories(C:/dev/i686-w64-mingw32/include)

add_definitions(-DSDL_MAIN_HANDLED)
add_executable(${PROJECT_NAME}  ${SDL2_LIB_DIR}/libSDL2.dll.a
        ${SDL2_LIB_DIR}/libSDL2main.a ${SDL2_LIB_DIR}/libSDL2_image.dll.a main.cpp Screen.cpp Screen.h)

and thanks a lot for helping.

A: *

*Screen.h is not needed in add_executable.

*To tell compiler which library your target (i.e. executable) should link to, use target_link_libraries.

Replace your last add_executable statement with:
add_executable(${PROJECT_NAME} main.cpp Screen.cpp)
target_link_libraries(
  ${PROJECT_NAME} ${SDL2_LIB_DIR}/libSDL2.dll.a ${SDL2_LIB_DIR}/libSDL2main.a
  ${SDL2_LIB_DIR}/libSDL2_image.dll.a)


text:
Q: Express.js do not open index.html file Issue came up, when I tried to run axpress.js solution, but it opens index.jade file from views folder and in browser I see result: "Welcome to Express" , but I would like to open my index.html file which is located in client directory -> index.html , when I run npm I am accessing to this location: http://localhost:3000/client/index.html , but this path my solution do not find.
In app.js file I set and define routes:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

routes folder: index.js file:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

Where I have to setup my routing, because now I am getting 404 .

A: Change the file name from index.html to index.jade.


text:
Q: Read data from an Android Room database in a background Service, no exceptions but no data I am attempting to read data from an Android Room database in a background Service. There are no exceptions but no data is returned.
I wrote a function to select all rows from a table in the DAO. Calling that function from a background service succeeds, but it returns no data.
My "Contact" class holds contact information (names, phone numbers, emails) and defines the database schema. The database holds rows of contacts, with names, phone numbers, an emails as columns.
The function that returns the LiveData in the DAO is:
@Query("SELECT * FROM contacts_table")
LiveData<List<Contact>> getAll();

where "contacts_table" is the database table holding contact information.
I called getAll as follows:
AppDatabase db = AppDatabase.getDatabase(messageSenderContext.getApplicationContext());
mContactDAO = db.contactDAO();
mAllContacts = mContactDAO.getAll();

where mContactDao is a ContactDAO (The Database Access Object for my Contact class), and mAllContacts is a LiveData>. These are private fields of the class calling getAll().
db.contactDAO() returns an object, as does mContactDAO.getAll(). But attempting to unpack the List from mAllContacts using mAllContacts.getValue() returns null.

A: This turned out to be a misuse of LiveData. That requires an Observer to actually get the data.

A: In your ROOM
@Database(entities={Contact.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {

    public static final String DATABASE_NAME = "AppDatabase.db";
    private static volatile AppDatabase INSTANCE;
    private static final int NUMBER_OF_THREADS = 4;
    public static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    public abstract ContactDAO contactDAO();

    public static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, DATABASE_NAME)
                            .build();
                }
            }
        }
        return INSTANCE;
    }
}

In your DAO
@Dao
public interface ContactDAO{
    @Query("SELECT * FROM contacts_table")
    LiveData<List<Contact>> getAll();
}

In your repository:
public class AppRepository {

    private ContactDAO mContactDAO;

    //constructor
    public AppRepository(Application application) {
        AppDatabase db = AppDatabase.getDatabase(application);
        mContactDAO= db.contactDAO();
    }

    public LiveData<List<Contact>> getAllContacts(){
        LiveData<List<Contact>> contactsList = null;
        Future<LiveData<List<Contact>>> futureList = AppDatabase.EXECUTOR_SERVICE.submit(new Callable(){
            @Override
            public LiveData<List<Contact>> call() {
                return contactDAO.getAll();
            }
        });

        try {
            contactsList = futureList.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return contactsList ;
    }
}

In your ViewModel
public class ContactsViewModel extends AndroidViewModel {
    private AppRepository appRepository;
    private LiveData<List<Contact>> contactsList;

    public ContactsViewModel(@NonNull Application application) {
        super(application);
        appRepository = new AppRepository(application);
    }

    public LiveData<List<Contacts>> list() {
        return appRepository.getAllContacts();
    }
}

In your activity (inside of onCreated put)
ContactsViewModel contactsViewModel = new ViewModelProvider(this).get(ContactsViewModel.class);
contactsViewModel.list().observe(getViewLifecycleOwner(), new Observer<List<Contact>>() {

            @Override
            public void onChanged(List<Contact> contactsList) {
            //the contact list will be observed and will return data if there are changes.
            //use for example to feed the adapter of a recyclerview
            //below an example just to view the contacts data
            for(Contact conctact : contactsList){
                Log.d("TestApp>>>", "Id: + contact.getId);
                Log.d("TestApp>>>", "Name: + contact.getName);
            }
        });


text:
Q: How can I "meteor run android-device" to my meteor server? If I use the command:
meteor run android-device -p 192.168.232.142:3000

I have the following error:
Can't listen on host 192.168.232.142 (EADDRNOTAVAIL from listen).

That's logic, as the 192.168.232.142 is not my local IP address, but the IP address of my remote Meteor development server.
On the other hand, the same command on my remote Meteor dev server will not be helpful as I cannot attach my Android device to it. (With USB a adb).
So, how can I, install an android web app on my locally connected Android device pointing to a remote Meteor server?
Thanks,

A: This command works just fine:
meteor run android-device --mobile-server http://remote_server.meteor.com


text:
Q: Can someone help me figure out what this code does? The following code is from our universities thesis template, which is not very well documented, and as I'm the most skilled LaTeX user, and I'm a middling user at best, we don't know what a lot of the code in it does. Could someone help us figure out what this macro does? I can tell that it has something to do with hyperref, but beyond that we don't know. It is right above a bunch of code for modifying csthesis to add a List of Programs, so it could have something to do with that?
Is there enough here to tell what it is doing?
Oh and no, I can't post up a MWE as we don't know what it does, and it was taken out of an entire Ph.D. thesis.
\makeatletter
\def\contentsline#1#2#3#4{%
  \ifx\\#4\\%
    \csname l@#1\endcsname{#2}{#3}%
  \else
    \csname l@#1\endcsname{%
      \hyper@linkstart{link}{#4}{#2}\hyper@linkend
    }{%
      % same link destination for the page:
      \hyper@linkstart{link}{#4}{#3}\hyper@linkend
      % link destination is the page itself:
      % \hyperpage{#3}%
    }%
  \fi
} \makeatother

(I'm hoping there is enough code there, this is sitting off by itself in the template so I'm hoping it is self contained. I'm also hoping this is not too localized.)

A: In older versions of hyperref either the titles or the page numbers could be made a link, not both. Therefore the definition of \contentsline in the question modifies the old definition of hyperref's \contentsline to add a link to both the title and the page number.
Since version 2008/04/13 6.77n hyperref has a new option linktoc. From
hyperref's README:

Option linktoc added
The new option linktoc allows more control which part
  of an entry in the table of contents is made into a link:

*

*linktoc=none    (no links)

*linktoc=section (default behaviour, same as linktocpage=false)

*linktoc=page    (same as linktocpage=true)

*linktoc=all     (both the section and page part are links)

With an up-to-date hyperref you can delete the definition of \contentsline and use
\usepackage[linktoc=all]{hyperref}[2008/04/13]

The option can also be set via \hypersetup.


text:
Q: How to solve problem when Java Bean mapper has different source and dest field in payload? I have  Company entity:
@Entity
@Data
public class Company {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "company_id", nullable = false, unique = true)
    private int companyId;

    @Column(name = "name", nullable = false, length = 255, unique = true)
    private String name;

    @JsonIgnore
    @OneToMany (mappedBy = "company")
    private List<Employee> employeeList;
}

And Employee entity:
@Entity
@Data
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "employee_id", nullable = false, unique = true)
    private int employeeId;

    @Column(name = "employee_name", nullable = false)
    private String name;

    @ManyToOne(optional = false)
    @JoinColumn(name = "company_id", nullable = false)
    private Company company;
}

I have trouble when I'm mapping EmployeeRequest to Employee object.
This is EmployeeRequest:
@Data
public class EmployeeRequest {
    private String name;
    private int companyId;
}

As you can see here in request I have companyId which is integer and therefore I have error.
My mapper:
@Component
public class EmployeeMapper {
    private Mapper mapper = DozerBeanMapperBuilder.buildDefault();

     public Employee transformToEmployeeEntity(EmployeeRequest employeeRequest) {
        return mapper.map(employeeRequest, Employee.class);
    }
}

I think it makes sense to have an integer as data type in EmployeeRequest. So what is proper way to solve this?


text:
Q: Bootstrap 3 typeahead.js - set form val I am using typeahead.js with Bootstrap 3 and using the code below it seems to work well to the point that I can get a dropdown with the countryName value from the json file but I now want to assign the ID to the input value attribute so I can submit the correct countryID rather than the displayed text.
My json file returns the following data  [{"ID": 1, "countryName": "United States"},{"ID": 2, "countryName": "United Kingdom"},{"ID": 3, "countryName": "United Emirettes"}]
var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
    var matches, substrRegex;
    matches = [];
    substrRegex = new RegExp(q, 'i');
    $.each(strs, function(i, str) {
        console.log(str['countryName'])
      if (substrRegex.test(str['countryName'])) {
        matches.push({ value: str['countryName'] });
      }
    });
    cb(matches);
  };
};

$.getJSON("countries2.json",function(result){
   format: "json"
})
.done(function( data ) {
    $('#the-basics .typeahead').typeahead({
      hint: true,
      highlight: true,
      minLength: 2
    },
    {
      name: 'countries',
      valueKey: 'countryName',
      displayKey: 'value',
      source: substringMatcher(data)
    });
});

A: I think if you change your subStringMatcher so that it gives also the country ID. In object add also key with value ID. Try this:
var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
    var matches, substrRegex;
    matches = [];
    substrRegex = new RegExp(q, 'i');
    $.each(strs, function(i, str) {
        console.log(str['countryName'])
      if (substrRegex.test(str['countryName'])) {
        matches.push({ key:str['ID'], value: str['countryName'] });
      }
    });
    cb(matches);
  };
};

Then change typeahead options valueKey to key.
 $('#the-basics .typeahead').typeahead({

  hint: true,
  highlight: true,
  minLength: 2
},
{
  name: 'countries',
  valueKey: 'key',
  displayKey: 'value',
  source: substringMatcher(data)
});


text:
Q: Number of neuron in CNN architecture I am using a certain CNN architecture, however, I am not sure how to calculate the exact number of neuron I have in it.
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=16,
                               kernel_size=(7, 7), padding=(1, 1),
                               stride=(2, 2))

        self.conv2 = nn.Conv2d(in_channels=16, out_channels=32,
                               kernel_size=(7, 7), padding=(1, 1),
                               stride=(2, 2))

        self.conv3 = nn.Conv2d(in_channels=32, out_channels=64,
                               kernel_size=(3, 3), padding=(2, 2),
                               stride=(2, 2))

        self.fc1 = nn.Linear(64 * 1 * 1, 8)

There is also 2D-maxpooling after each convolution layer with stride of 2.
I can get the number of parameters and Gmacs in my network, but I am not sure how to get the number of neurons?
Is there a certain way to calculate them?
Thanks.

A: One quick way to get the total count is to

*

*Fetch all parameters with nn.Module.parameters;

*Convert the generator to a flattened tensor with torch.nn.utils.parameters_to_vector;

*Find the total number of elements with torch.Tensor.numel.

Which corresponds to:
>>> p2v(model.parameters()).numel()
44936

Having imported parameters_to_vector from torch.nn.utils as p2v

If you want to count the parameters yourself:

*

*Convolutions when counting kernels and biases. Given number of input channels in_c, output channels out_c, and kernel size k:
conv = lambda in_c, out_c, k: k*k*in_c*out_c + out_c

*Fully-connected layers: just a two-dimensional matrix with biases:
fc = lambda in_c, out_c: in_c*out_c + out_c

*Max-pool layers are non-parametrized layers: 0 parameters.
All in all, this gives you:
>>> conv(1, 16, 7) + conv(16, 32, 7) + conv(32, 64, 3) + fc(64, 8)
44936

The word neurons is just an abstraction. If you consider it to be the output dimension for each given layer then:

*

*For convolution layers, it will depend on the spatial dimension of the input. So given the spatial dimension x, the kernel size k, the padding p, and the stride s:
conv = lambda x, k, p, s: math.floor((x+2*p - k)/ s + 1)

*For fully connected layers, it corresponds to the number of output features.


text:
Q: How to completely remove Xserver from OpenBSD? I just installed OpenBSD 6.9 to study how it works.
I wanted to get the most minimal config possible, because I want to use it as a server.
During instalation I chose the option to not install Xserver, but I still have the /usr/X11R6 and /etc/X11 directories with X config and commands like startx. The only difference is that now, startx doesn't work. I tried installing on VirtualBox and on bare metal and both were the same.
What do I have to do in order to completely remove X from OpenBSD? And why is it still being installed in my machine even if I explicitly write "no" when prompted during installation?
My system:

*

*OpenBSD 6.9

*Intel Pentium G5400

*Nvidia 1050 ti.

A: OpenBSD installation uses different file sets => see OpenBSD FAQ / File Sets
X11 installation is split into 4 file sets :

*

*xbase71.tgz : Base libraries and utilities for X11 (requires xshare71.tgz)

*xfont71.tgz : Fonts used by X11

*xserv71.tgz : X11's X servers

*xshare71.tgz : X11's man pages, locale settings and includes

During installation, you chose not to install xserv71.tgz (X servers) but you still have installed xbase71.tgz (startx command and others directories).
If you want to completely remove X from OpenBSD, during installation, remove every file set for X. But you should keep xbase71.tgz because some programs needs it to run correctly even if it's a non-X program.

A: I'm not a OpenBSD developer, so I cannot give a clear answer. But some specific packages which you can add with the package command from OpenBSD (pkg_add), needs some X libraries or binaries.
As example when you want to add vim for the first time, then you have eight flavors:
$ pkg_info -d vim-8.2.3456-no_x11
Information for inst:vim-8.2.3456-no_x11
[REMOVED]

Flavors:
        gtk2       - build using the Gtk+2 toolkit
        gtk3       - build using the Gtk+3 toolkit (default)
        no_x11     - build without X11 support
        lua        - build with Lua support
        perl       - build with Perl support
        python     - build with Python support
        python3    - build with Python3 support
        ruby       - build with Ruby support

It's depends on the packages what you need. Also when you want install something from the port collections.
You can try the quick and dirty way and simple remove your mentioned directories. But I could be possible that some programs from the base system no longer works, because of missing dependencies.


text:
Q: Showing that matrix $A$ and linear operator $T: M_{n\times n} \rightarrow M_{n\times n}$ ($T(B) = AB$) have the same eigenvalues $T: M_{n\times n} \rightarrow M_{n\times n} \\ T(B) = AB$
Defining $S_A$ as the set of eigenvalues of $A$ and $S_T$ as the set of eigenvalues of $T$, I have to prove $1. \ S_T \subseteq S_A$ and $2. \ S_A \subseteq S_T$.
The eigenvalues of $A$ are derived from the operation of $A$ on $n\times 1$ matrices but $T$ operates on $n\times n$ matrices and I don't think I can just assume $A$ to be the matrice form of $T$. I attempted defining an isomorphism $M_{n\times n} \rightarrow \mathbb{F}^{n^2}$ but clearly that wouldn't work because we can no longer use the same matrix multiplication anymore.

A: When $B$ has columns $b_1,b_2,\dots,b_n$ so that $B=(\ b_1\mid b_2 \mid \dots \mid b_n\ )$, then note that
$$
T(B) = AB = A(\ b_1\mid b_2 \mid \dots \mid b_n\ ) = (\ Ab_1\mid Ab_2 \mid \dots \mid Ab_n\ ).
$$
Hence $AB=\lambda B$ is equivalent to $Ab_i = \lambda b_i$ for all columns $b_i$ of $B$.
When $\lambda$ is an eigenvalue of $A$, let $b\neq 0$ an eigenvector so that $Ab=\lambda b$ and consider the matrix $B=(\ b \mid b \mid \dots \mid b\ )$. We have $B\neq 0$ and
$$
AB = (\ Ab \mid Ab \mid \dots \mid Ab\ ) = (\ \lambda b \mid \lambda b \mid \dots \mid \lambda b\ ) = \lambda B.
$$
Hence $B$ is an eigenvector of $T$ with eigenvalue $\lambda$.
When $\lambda$ is an eigenvalue of $T$, so that $AB=\lambda B$ for some non-zero matrix $B$, there is at least one non-zero column $b_i$ of $B$ and for that we have $Ab_i = \lambda b_i$. Hence $b_i$ is an eigenvector of $A$ with eigenvalue $\lambda$.
This shows that $A$ and $T$ have the same eigenvalues.


text:
Q: Why zend framework can't access to mysql database? I'm following the user guide tutorial directly from the Zend framewrok website; I create the  module ALbum and the mysql table as the guide says, but when I open the link 'localhost:8080/album' return a page error with the message below :

Connect Error: SQLSTATE[42000] [1044] Access denied for user
  ''@'localhost' to database 'zf2tutorial'

I have also configurated the global.php and local.php as the guide says, in particular I have filled in the local.php this credential :
 return array(
     'db' => array(
         'username' => 'root',
         'password' => '',
     ),
 );

because the 'zf2tutotial' database was inserted with the root user without password.
Why the framework doesn't access the database ?

A: You don't have rights to access database.
Execute
GRANT ALL PRIVILEGES ON *.* TO ''@localhost

and then
FLUSH PRIVILEGES

to get access.

A: Please check your global.php file, and match code with the following
 return array(
 'db' => array(
     'driver'         => 'Pdo',
     'dsn'            => 'mysql:dbname=zf2tutorial;host=localhost',
     'driver_options' => array(
         PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
     ),
 ),
 'service_manager' => array(
     'factories' => array(
         'Zend\Db\Adapter\Adapter'
                 => 'Zend\Db\Adapter\AdapterServiceFactory',
     ),
 ),

);
and your local.php is correct.


text:
Q: assembly retn , jmp , process register I started C++ programming recently alongside with assembly language.  I would like to clarify a few things.
From what I read, the instruction pointer gets the address where it should execute next from the retn instruction. Wont it be the same as doing a jmp because jmp also sets the instruction pointer?
If I am right, what's the difference between retn and jmp? If I'm wrong, can someone explain with C pseudo code?
What is the assembly equivalent for an infinite loop?
I read that EAX,EBX,ECX,EDX are interchangeable but do they have any difference? If so,in which scenario should I specifically use EAX/EBX/ECX/EDX.

A: You seem to be talking about subroutine calls, so here's the lowdown on that.
When you call a subroutine, it looks something like this (the addresses will be different but I didn't want to confuse you with variable-length instructions):
1234  call 8888
1235  <next instruction>

What happens is that the call first places the next instruction pointer 1235 onto the stack (a last-in-first-out data structure), then sets the instruction pointer to whatever you're calling, 8888 in this case.
Later on, a return is done at 8889:
8888  mov eax, 0
8889  ret

What the return does is simply pop the first value off the stack (ie, 1235, which was pushed by the call) and loads it into the instruction pointer. So it's not the return telling you where to go, it's the information that was pushed on the stack by the call.
If you had a jmp instruction at the end of your subroutine, it would only be able to return to one point in the code (discounting all the wonderful things you could do with other addressing modes for now):
8889  jmp 1235

By using return, you return to wherever you came from, no matter where that was.

The assembler for an infinite loop can be as simple as:
loopy:
    jmp loopy

As for the registers, eax, ebx, ecx and edx are considered the general purpose registers. This distinguishes them from the more special purpose registers like the stack pointer, base pointer, source and destination indexes and so on, which have specialised instructions depending on their use.
ax may have had some extra powers in very early iterations of the x86 architecture but I'm not sure that's still the case. If you're coding up your own stuff, you should be able to mostly use them interchangeably. If you're following an API or ABI, you'll need to follow the rules that it imposes (such as the Linux system call interface where eax holds the system call number).

A: The difference of ret and jmp in terms of a C/C++ function is similar to this:
int foo()
{
   int x = 3+4;

   if(x < 10)
      goto Quit;    <- similar to jmp

   x += 10;

 Quit:
   return x;     <- similar to ret

}
When you do return in C it's a bit more complicated what really happens on the machine level, because additional code is often executed, for example put the return value in eax and  cleaning up the stack.ö In C++ local objects will get desctructed as well, but the ultiate and of the function will be a ret instruction.

What is the assembly equivalent for an infinite loop ?

while(1);

is like
000000 jmp 000000

or more advanced
00000  inc ecx
00001  jmp 00000

General purpose registers. In some cases you can intermix the registers and use them however you want. For some instructions, they expect to be using specific registers. You must look up the instruction manual to see where this is the case.
One example is the movsw, which requires you to use (E)SI and (E)DI, so in this case you are not free to choose. If you use rep movsw additional (E)CX is also used.
Typically the assembler knows which registers are valid for an inxtruction and will give you an error message, but of course, you should look up the manual to be sure, because you might get unexpected results if the assembler can not throw an error.

A: eax and edx are implicit operands in division and int the wide-result versions of multiplication. There are also special sign-extending instructions that operate on only parts of rax (opcode 98) or that sign-extend eax into edx:eax (opcode 99). Decimal math instructions all work on parts of eax.
ecx (well cl really but close enough) is the only register that you could shift by before Haswell (which introduces sarx, shlx and shrx all of which can shift by any GPR). ecx is also used as the counter by rep-prefixes. pcmp*stri puts the length in ecx.
Many special-purpose instructions have no explicit operands but instead assign special meaning to certain GPR's, for example cpuid, rdpmc, rdtsc, wrmsr, xgetbv, xsave. Usually edx:eax, often ecx as well, and very rarely ebx. You probably won't have to deal with these a lot.