text:
Q: How to listen for change within a list using flutter provider? I have a provider that is listening for changes to a playerList class:
import 'package:flutter/material.dart';
import 'package:scam_artist/constants/PlayerColors.dart';
import 'package:scam_artist/models/Player.dart';

class PlayerList with ChangeNotifier {
  List<Player> _players = [];

  List<Player> get players {
    return [..._players];
  }

  void addPlayer(Key key, String name, int index) {
    _players.add(
        new Player(key: key, color: PlayerColors.colors[index], name: name));
    notifyListeners();
  }

  void editPlayerName(String newName, int index) {
    _players[index].name = newName;
    notifyListeners();
  }

  void editPlayerColor(Color newColor, int index) {
    _players[index].color = newColor;
    notifyListeners();
  }
}

However, when I call a function to change a value to one of the Player objects (change name for example), the list doesn't update the object with new data.
Do I need another provider for the Player class? If so, how do I make the PlayerList provider listen for changes in the Player provider?
Doing a little research, I'm thinking ProxyProvider might be what I'm looking for, but I'm not sure how to implement it.
Here's my Player class if that is helpful:
import 'package:flutter/material.dart';

class Player {
  // id will be for database if implemented
  String uid;
  Key key;
  String name;

  //position is the order where the player plays
  int position;
  Color color;
  bool isTurn;
  bool isFakeArtist;
  bool isWinner;

  Player({this.key, this.name, this.color});
}

And this is where I create the ChangeNotifierProvider:
import 'package:flutter/material.dart';
import 'package:scam_artist/UserListener.dart';
import 'package:scam_artist/models/user.dart';
import 'package:scam_artist/providers/PlayerList.dart';
import 'package:scam_artist/services/AuthService.dart';
import 'package:provider/provider.dart';
import 'package:scam_artist/views/Lobby.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider<User>.value(value: AuthService().user),
        ChangeNotifierProvider(create: (context) => PlayerList())
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: UserListener(),
        routes: {Lobby.routeName: (ctx) => Lobby()},
      ),
    );
  }
}

A: There are multiple things wrong here.
1. Fix your PlayerList declaration line.
//CORRECT
class PlayerList extends ChangeNotifier {...}

//WRONG
class PlayerList with ChangeNotifier {...}

4. Fix your players getter line.
Use this:
List<Player> get players => _players;

3. You need more Conceptual Knowledge on Provider.
Basically, Provider makes your PlayerList accessible from anywhere within the Widget Tree below where you have provided it. For example, you are providing from the top of your MaterialApp. So you can access it in your HomePage or Lobby.
To access your PlayerList, you have to use a Consumer widget or Selector widget, but for your case, Consumer is enough. Selector is for advanced usage.
Here is the code for reading live values from your PlayerList.
class Lobby extends StatelessWidget {

  @override
  Widget build(BuildContext context) => Scaffold(
    body: _body(),
  );

  _body() => Container(
    child: Consumer<PlayerList>(
      builder: (BuildContext context, PlayerList bloc) =>
          ListView.builder(
            itemCount: bloc.players.length,
            itemBuilder:
               (BuildContext context, int index) => Text(bloc.players[index].name),
          ),
    ),

  );

}

A: I am having exactly the same problem.
One way I solved it (not the prettiest though) is to have a method in the ChangeNotifier to return a specific object and then watch for changes, e.g.
// in ChangeNotifier

Player getPlayer(int index) => _players[index];

and then in the widget have
context.watch<PlayerList>().getPlayer(index).updateName("newName")

A: If you are modifying from parent PlayerList then this is the way because parent is already notifying in your case
import 'package:flutter/material.dart';
class Player with ChangeNotifier {
  Player({String name, Color color}) {
    this.color = color;
    this.name = name;
  }

  String uid;
  Key key;
  String _name;

  String get name => _name;

  set name(String value) {
    _name = value;
    notifyListeners();
  }

  int position;
  Color _color;
  bool isTurn;
  bool isFakeArtist;
  bool isWinner;

  Color get color => _color;

  set color(Color value) {
    _color = value;
    notifyListeners();
  }
}

If you are modifying from within Player and want parent PlayerList to notify
import 'package:flutter/material.dart';
class Player with ChangeNotifier {
  Player({String name, Color color, this.playerList}) {
    this.color = color;
    this.name = name;
  }

  final PlayerList playerList;
  String uid;
  Key key;
  String _name;

  String get name => _name;

  set name(String value) {
    _name = value;
    notifyListeners();
    playerList.notifyListeners();
  }

  int position;
  Color _color;
  bool isTurn;
  bool isFakeArtist;
  bool isWinner;

  Color get color => _color;

  set color(Color value) {
    _color = value;
    notifyListeners();
    playerList.notifyListeners();
  }
}

A: Just change your _players accessor and you should be good.
  List<Player> get players {
    return _players;
  }


text:
Q: Why does the same process bounce around on different "CPUs"? I am doing some performance troubleshooting of some long running jobs which start processes that consume entire CPU cores, but are single-threaded. I observed these processes bouncing around to different CPUs continually. Why would the same process move around to different CPUs? It doesn't seem normal that the kernel scheduler would move running processes around that frequently, or at all. Yet, I see this behavior on many different processes. It seems like the more active the process is, the more it changes around to different CPUs.
I observe this behavior with top. I add the Last Used Cpu column. I then watch the interesting processes change to different CPUs continually even though the process ID remains the same.
It moves around so much that I believe I am seeing inconsistent performance on certain jobs, because the processes often collide with each other on the same CPU temporarily, even though they should all be balanced across different CPUs while the overlying jobs are running. The server is mostly idle except for these processes while these jobs run. So, I would expect Job 1 to start processes on one set of CPUs, and Job 2 to end up on a different set of CPUs and stay there.
Amazon Linux 2 Kernel 4.14.x on EC2

A: The Linux scheduler uses natural CPU affinity: the scheduler attempts to keep processes on the same CPU as long as practical for performance reasons. You can enforce CPU affinity in a normal Linux system with taskset.
But, as I understood it, unless you have dedicated instances, on EC2 there will be a lot of CPU sharing. You might be able to tie a process to a vCPU, but that's just windowdressing.

A: You wrote watching the phenomenon using top.
I am not sure it is the right tool for your analysis since, as man top acknowledges :

*P  --  Last used CPU (SMP) A number representing the last used processor.  In a true SMP environment this will likely change
frequently since  the  kernel  intentionally uses  weak  affinity.
Also, the  very  act of running top may break this weak affinity and
cause more processes to change CPUs more often (because of the extra
demand for cpu time).

I would personally prefer relying on the count of Rescheduling interrupts as reported in /proc/interrupts.

A:
even though they should all be balanced across different CPUs while the overlying jobs are running

No they shouldn't. You didn't say which scheduler you are using but AFAIK all current mainstream distros use the Completely Fair scheduler by default. This will assign a task to a CPU based on the available CPUs - with the CPU last used by the process being the preferred destination, a CPU in the same hyperthread group next, then a CPU on the same socket (sharing the same L2 cache IIRC?) - and then things start getting complicated when you're dealing with NUMA. Its all documented on the internet if you go looking for it.
On a happy machine, the maximum timeslot available to a process to run on a CPU will not be reached - the task will do something which means it has to wait for something to happen and hence yield its place. When the load average gets close to the number of CPUs there is contention for the CPU resource and the scheduler will start kicking tasks out of the CPU before they are ready to yeild (they are pre-empted). Typically this decreases the throughput of the system slightly.
It is possible to tweak some of the coefficients used to weight the CPU affinity algorithm. Run sysctl -A | grep "sched" | grep -v "domain" to see the parameters. But note that, to some extenet the kernel will tune CFS at run time.

The server is mostly idle except for these processes while these jobs run

Really? These processes don't do any network or storage I/O?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display a for loop output? When printing out the result I get the deck of cards for each player I want but when finding who has 2 clubs, instead of printing on the bottom of the console it prints under the players deck. I have no clue how to get this on the bottom unless I create another function. Any way of getting this to print out who has 2 clubs on the bottom of the console?
void CardClass::PrintCards(CardType *player) {
  for (int i = 0; i < 13; i++) {
    if (player[i].suit == DIAMOND)
      cout << " Diamond" << setw(11);
    if (player[i].suit == CLUB)
      cout << " Club" << setw(14);
    if (player[i].suit == SPADE)
      cout << " Spade" << setw(13);
    if (player[i].suit == HEART)
      cout << " Heart" << setw(13);
    if (player[i].value == 2)
      cout << "2" << setw(15);
    if (player[i].value == 3)
      cout << "3" << setw(15);
    if (player[i].value == 4)
      cout << "4" << setw(15);
    if (player[i].value == 5)
      cout << "5" << setw(15);
    if (player[i].value == 6)
      cout << "6" << setw(15);
    if (player[i].value == 7)
      cout << "7" << setw(15);
    if (player[i].value == 8)
      cout << "8" << setw(15);
    if (player[i].value == 9)
      cout << "9" << setw(15);
    if (player[i].value == 10)
      cout << "10" << setw(15);
    if (player[i].value == 11)
      cout << "J" << setw(15);
    if (player[i].value == 12)
      cout << "Q" << setw(15);
    if (player[i].value == 13)
      cout << "K" << setw(15);
    if (player[i].value == 14)
      cout << "A" << setw(15);
    if (player[i].points == 0)
      cout << "0" << endl;
    if (player[i].points == 5)
      cout << "5" << endl;
    if (player[i].points == 10)
      cout << "10" << endl;
    if (player[i].points == 100)
      cout << "100" << endl;
    if (player[i].points == -100)
      cout << "-100" << endl;
  }

  for(int i = 0; i < 13; i++) {
    if (player[i].suit == CLUB && player[i].value == 2)
      cout << "has the 2 clubs" << endl;
  }
}

output:
PLAYER 1

  SUIT          VALUE         POINTS
 Diamond          6              0
 Diamond          9              0
 Club             3              0
 Club             A              0
 Club             6              0
 Club             2              0
 Club             5              0
 Heart            Q             10
 Heart            4              5
 Heart            K             10
 Spade            K              0
 Spade            3              0
 Spade            9              0
has the 2 clubs
PLAYER 2

  SUIT          VALUE         POINTS
 Diamond          4              0
 Diamond          K              0
 Diamond          J           -100
 Diamond         10              0
 Diamond          Q              0
 Club            10              0
 Heart            J             10
 Heart            5              5
 Heart            2              5
 Spade            4              0
 Spade            2              0
 Spade            Q            100
 Spade            8              0
PLAYER 3

  SUIT          VALUE         POINTS
 Diamond          5              0
 Diamond          A              0
 Diamond          7              0
 Diamond          3              0
 Diamond          2              0
 Club             J              0
 Club             7              0
 Heart            9              5
 Heart            A             10
 Spade           10              0
 Spade            A              0
 Spade            J              0
 Spade            5              0
PLAYER 4

  SUIT          VALUE         POINTS
 Diamond          8              0
 Club             K              0
 Club             4              0
 Club             Q              0
 Club             9              0
 Club             8              0
 Heart            3              5
 Heart            7              5
 Heart           10             10
 Heart            6              5
 Heart            8              5
 Spade            7              0
 Spade            6              0

A: You have the information about who has 2 of clubs inside your CardClass::PrintCards function. If you print it there - you are going to see it right after that player's hand.
If you want to save it and print later - you need to return some information to a calling function. For example:
bool CardClass::PrintCards(CardType *player) {
  ...
  for (int i = 0; i < 13; i++) {
    if (player[i].suit == CLUB && player[i].value == 2)
      return true;
  }

  return false;
}


text:
Q: Hyperlink from one Angular App to another Angular App I have two different Angular Apps and one App is redirecting to the other App using a hyperlink to a specific route. However, the system is throwing a Whitelabel Error Page. The empty path has no issue.
I used the default HTML 5 location strategy for the routing.
first app: "http://www.app1.com/"
second app: "http://www.app2.com/"
the first app redirects to the second app thru:
window.location.href = "http://www.app2.com/some-path";
This is my sample route in the second app:
{
    path: 'some-path',
    component: SomeComponent,

  },
{
    path: '',
    component: SomeEmptyComponent,

  }

A: Use href for any other application

you can use relative path e.g

A: Internal link (should match your routing config):
Some path
Home

External link (should contain absolute path or relative which link other app):
Facebook


text:
Q: Combine multiple pixmaps that have transparent pixels I've been trying to combine multiple pixmaps that have transparency. The problem I'm having is that there end up with strange artifacts where they cross over.
I've created an example that should show a red circle crossing over a blue circle.
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.PixmapIO;

public class PixmapExample extends ApplicationAdapter {

    @Override
    public void create() {

        final int width = 128;
        final int height = 128;

        final Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
        pixmap.setBlending(Pixmap.Blending.SourceOver);

        pixmap.setColor(1f, 0f, 0f, 0.4f);
        pixmap.fillCircle(64, 64, 32);
        pixmap.drawPixel(45,45);

        final Pixmap otherPixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
        otherPixmap.setBlending(Pixmap.Blending.SourceOver);

        otherPixmap.setColor(0f, 0f, 1f, 0.4f);
        otherPixmap.fillCircle(84, 64, 32);

        pixmap.drawPixmap(otherPixmap, 0, 0);

        // Write the pixmap
        final FileHandle fileHandle = new FileHandle("pixmap_combine_example" + ".png");
        PixmapIO.writePNG(fileHandle, pixmap);
        pixmap.dispose();
    }
}

I've tried using Pixmap.Blending.None but this makes the second pixmap overwrite the first.
What could be causing this?


text:
Q: How to fix a depth-first Sudoku solve? I'm trying to create a sudoku puzzle solver in Python that uses a depth-first "brute-force" to solve the puzzle. However, I am coming up with the same error over and over again, after having recoded many times.
I'll try my best to explain the problem as clearly as possible - as this is my first problem related to depth-first searching, it may be that I'm missing something obvious.
Here is the cut-down code (mixed with pseudo-code in places where specifics aren't necessary):
def solvePuzzle(puzzle):
    <while the puzzle is still not solved>:
        <make a copy of the puzzle>
        <go through each unsolved box>:
            <try to find the value of the box>
            <if the current solution is impossible, return to the parent branch>
        <if the copy of the puzzle is exactly the same as the puzzle now, no changes have been made, so its time to start branching into different possibilities>:
            <pick a random box to guess the number of>
            <go through each possible value and run solvePuzzle() on that puzzle>:
                <if a solution is returned, return it>
                <else, try the next possible value>
    <return the puzzle>

That's as cut down as I could make it - sorry if its still a bit of a read/confusing.
For some reason, even after setting the program to solvePuzzle() each created copy of the puzzle, it finds that all of the copies are impossible (by impossible, I mean an error has been made in a guess). This can't be possible, as every number is being tested!
Here's the full code (only about 50 lines of code), in case that's not clear enough.
If anyone could even suggest why this wouldn't be working, I'd be greatly thankful.
Thank you!
Edit: As promised, here's the "isSolved()" method.

A: I strongly suspect that the problem is here:
# Go through each possibility in the branch until one solution is found
clone = deepcopy(puzzle)
values = clone[index / 9][index % 9]
for value in values:
    clone[index / 9][index % 9] = value
    branch = solvePuzzle(clone)
    # If a list is returned, it worked! Otherwise, try the next possibility
    if isinstance(branch, list):
        return branch

That mutates the clone copy for each candidate value, and does not restore to the semi-solved puzzle state when it finds a contradiction.  Try this:
# Go through each possibility in the branch until one solution is found
values = puzzle[index / 9][index % 9]
for value in values:
    clone = deepcopy(puzzle)
    clone[index / 9][index % 9] = value
    branch = solvePuzzle(clone)
    # If a list is returned, it worked! Otherwise, try the next possibility
    if isinstance(branch, list):
        return branch


text:
Q: Scroll event not call in Datalist using javascript Below my View Code. I am using datalist for dropdown but can not call scroll event for more data load and I want only 20 record show after scroll more data add using javascript
<input type="text" name="product" list="myselectbox"/>
<datalist id="myselectbox">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    ...
    <option>100</option>
</datalist>

//JavaScript

var mySelect = $('#myselectbox');
mySelect.scroll(function (e) {
        alert("b");
)};

A: You can be able to achieve the scroll event, only if the child height is greater than the parent's height. In such case, the child will overflow. So in your case, i believe you have given fixed height to the  myselectbox, so if the child content exceeds, it will scroll.
Now you can detect whether the scroll of myselectbox reached it's end, and then add new items to the list dynamically.
In order to detect the scroll has completed, please refer to this.


text:
Q: Entity Framework Core storing many to many relationship from multiple feeds of data How do you implement entity framework core classes properly to support a many to many relationship between two classes but the array/data of those classes and relationships is coming from 2 or more data sources.
That is to say if we had a simple relationship such as:
public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}

Our server is going to get an array of Posts, Tags, and any of their relationships from two more or data sources via a web api. So if we were simply to try to take the data directly and serialize it back into our database there would be collisions with the Id Key's given the 2 or more different sources. What is the proper way to store difference sources of the same class structure and also to not lose the relationship information? thank you

A: What you are missing a conversion layer. Let me explain.
Your post object stored in the database has to have the following structure:
Post Table
+------------+----------------+-------+----------+
| PostId     | ExternalPostId | Title | Content  |
+------------+----------------+-------+----------+

*

*PostId - This is the primary key within your own table. Auto-generated, required.

*ExternalPostId - this is the PostId as it arrives from the API.

*Title - this is the title as it arrives from the API

*Content - this is the content as it arrives from the API.

Tag table
+--------+---------------+-------------+-------------+
| TagId  | ExternalTagId | OtherField1 | OtherField2 |
+--------+---------------+-------------+-------------+

*

*TagId - This is the primary key of your own Tag table. Autogenerated, required.

*ExternalTagId - this is the TagId as it arrives from the API

*OtherField1, OtherField2 - whatever other fields arrive with the tag from the API.

Join Table
+------------+-------+
| PostId     | TagId |
+------------+-------+

*

*PostId, TagId - Composite Primary key

*PostId - foreign key, required, non-auto-numbered referencing the Post table.

*TagId - foreign key, required, non-auto-numbered referencing the Tag table.

At that point your entities will look like this:
Post Enity
[Table("Post")]
public class DbPost {

  [Key]
  [Column("PostId")]
  public int Id { get; set; }

  [Column("ExternalPostId")]
  public int ExternalId { get; set; }

  [Column("Title")]
  public string Title { get; set; }

  [Column("Content")]
  public string Content { get; set; }

  public IList<PostTag> PostTags { get; set; }
}

Tag entity:
[Table("Tag")
public class DbTag
{
    [Key]
    [Column("TagId")]
    public int Id { get; set; }

    [Column("ExternalTagId")]
    public string ExternalId { get; set; }

    public IList<PostTag> PostTags { get; set; }
}

PostTag Entity
This entity stays the same. The difference here is that PostId is mapped to the Id property of the Post entity, which is your own primary key of your own Post table. In a similar fashion the TagId is mapped to the Id property of the Tag table, which is also your own primary key, of your own table.
public class DbPostTag
{
  public int PostId { get; set; }
  public Post Post { get; set; }

  public int TagId { get; set; }
  public Tag Tag { get; set; }
}

Finally, your domain context:
public class Database : DbContext {
  public virtual DbSet<DbPost> Posts { get; set; }
  public virtual DbSet<DbTag> Tags { get; set; }
  public virtual DbSet<DbPostTag> PostTags { get; set; }
  ...
}

When you insert a post from the API you need to create a translation between the post from the API to the post entity in your database. You can do so via an extension method or a method that translates this for you:
public static class ApiObjectExtensions {

    public static DbPost ToDbPost(this Post post){
      var dbPost = new DbPost(){
        ExternalId = post.PostId,
        Title = post.Title,
        Content = post.Content,
        PostTags = new List<DbPostTags>()
      };
    }

    public static DbTag ToDbTag(this Tag tag){
      return new DbTag(){
        ExternalId = tag.Id,
        PostTags = new List<DbPostTags>()
      };

    }
  }

So when you are inserting the data in the domain context you simply have to convert the corresponding entities. This code assumes that you really have the object graph described above and your post has a bunch of post tags, and the each post tag has a bunch of tags.
foreach(var post in posts){

  var dbPost = post.ToDbPost();

  if(post.PostTags != null && post.PostTags.Any()){

    foreach(var postTag in post.PostTags){

      if(postTag.Tag != null){

         var dbTag = postTag.Tag.ToDbTag();

         var dbPostTag = new DbPostTag(){
           Post = dbPost,
           Tag = dbTag
         };

         dbPost.PostTags.Add(dbPostTag);
      }
    }
  }

  Database.DbPosts.Add(dbPost);
}

Database.SaveChanges();

If you are receiving the posts, the post tags, and the tags in separate calls than your insert operation will be a bit different:
var insertedPosts = new List<DbPost>();
var insertedTags = new List<DbTag>();

foreach(var post in posts){
  var dbPost = post.ToDbPost();
  Database.Posts.Add(dbPost);
  insertedPosts.Add(dbPost);
}

foreach(var tag in tags){
  var dbTag = tag.ToDbTag();
  Database.Tags.Add(dbTag);
  insertedTags.Add(dbTag);
}
Database.SaveChanges();

This will write all db post and db tag entities to the db and assign their primary keys.
The next step would be to link the two together.
foreach(var postTag in postTags){
  var dbPost = insertedPosts.FirstOrDefault(p => p.ExternalId = postTag.PostId);
  var dbTag = insertedTags.FirstOrDefault(t => t.ExternalId = postTag.TagId);

  if(dbPost != null && dbTag != null){
    var dbPostTag = new DbPostTag(){
      PostId = dbPost.Id,
      Tag = dbTag.Id
    };
    Database.PostTags.Add(dbPostTag);
  }
}
Database.SaveChanges();

The last piece is when you retrieve the data back and you want it in the original format.
The following query will return all posts, their linking entities, and their tags:
var dbPosts = this.Database.Posts
    .Include( p => p.PostTags )
    .ThenInclude(pt => pt.Tag )
    .ToList();

var apiPosts = dbPosts.Select(p => p.ToApiPost()).ToList();

To convert the stuff back to the original Post, PostTag, and Tag types you can simply create extension methods as follows:
public static class DbObjectExtensions {
  public static Post ToApiPost(this DbPost dbPost){
    var post = new Post(){
      PostId = dbPost.ExternalId,
      Title = dbPost.Title,
      Content = dbPost.Content,
      PostTags = new List<PostTag>()
    };

    if(dbPost.PostTags != null) {
       foreach(var dbPostTag in dbPost.PostTags){
         if(dbPostTag.Tag != null){
           var tag = dbPostTag.Tag.ToApiTag();
           var postTag = new PostTag(){
             PostId = post.PostId,
             Post = post,
             TagId = tag.TagId,
             Tag = tag
           };
           post.PostTags.Add(postTag);
           tag.PostTags.Add(postTag);
         }
       }
    }
    return post;
  }

  public static Tag ToApiTag(this DbTag dbTag){
    return new Tag(){
      TagId = dbTag.ExternalId
    };
  }
}


text:
Q: Alexa skill with Spring boot not working I am trying to connect Alexa with Spring Boot webservice but I am facing few issues. servlet is not working only in the server and it throws 404 but in local I am getting 500 and 400 with the same URL I am using for servlet.
Application file
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.amazon.speech.Sdk;
import com.amazon.speech.speechlet.servlet.SpeechletServlet;

@EnableCaching
@ServletComponentScan
@SpringBootApplication
public class VocabBrawlAlexaApplication {

    private static final Logger LOGGER = LogManager.getLogger(VocabBrawlAlexaApplication.class.getName());

    public static void main(String[] args) {
        LOGGER.info("Info Message Logged !!!");
         //setAmazonProperties();

        SpringApplication.run(VocabBrawlAlexaApplication.class, args);
        LOGGER.info("Info Message Logged asdfsa !!!");
        setAmazonProperties();
    }

    /**
     * Sets system properties which are picked up by the {@link SpeechletServlet}.
     */
    private static void setAmazonProperties() {
        // Disable signature checks for development
        LOGGER.info("Info Message Logged setAmazonProperties !!!");
        System.setProperty(Sdk.DISABLE_REQUEST_SIGNATURE_CHECK_SYSTEM_PROPERTY, "true");
        // Allow all application ids for development
        System.setProperty(Sdk.SUPPORTED_APPLICATION_IDS_SYSTEM_PROPERTY, "**********");
        // Disable timestamp verification for development
        System.setProperty(Sdk.TIMESTAMP_TOLERANCE_SYSTEM_PROPERTY, "1500");
    }

    @Bean
    public ServletRegistrationBean registerServlet() {

        LOGGER.info("Alexa configuration");

        SpeechletServlet speechletServlet = new SpeechletServlet();
        speechletServlet.setSpeechlet(new VocabBrawlSpeechlet());

        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(speechletServlet,"/hello");
        servletRegistrationBean.setLoadOnStartup(1);
        servletRegistrationBean.setName("alexa");
        servletRegistrationBean.addUrlMappings("/alexa/*");
        servletRegistrationBean.addUrlMappings("/alexa/hello/*");
        servletRegistrationBean.addUrlMappings("/hello/*");
        servletRegistrationBean.addUrlMappings("/hello");
        servletRegistrationBean.addUrlMappings("/*");
        return servletRegistrationBean;
    }
}

Servlet file
package com.vocabBrawlAlexa;

import javax.servlet.annotation.WebServlet;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.amazon.speech.json.SpeechletRequestEnvelope;
import com.amazon.speech.slu.Intent;
import com.amazon.speech.speechlet.IntentRequest;
import com.amazon.speech.speechlet.LaunchRequest;
import com.amazon.speech.speechlet.SessionEndedRequest;
import com.amazon.speech.speechlet.SessionStartedRequest;
import com.amazon.speech.speechlet.SpeechletResponse;
import com.amazon.speech.speechlet.SpeechletV2;
import com.amazon.speech.ui.OutputSpeech;
import com.amazon.speech.ui.PlainTextOutputSpeech;
import com.amazon.speech.ui.Reprompt;
import com.amazon.speech.ui.SimpleCard;
import com.vocabBrawlAlexa.service.IAlexaService;
import com.vocabBrawlAlexa.service.impl.AlexaServiceImpl;

@Service
public class VocabBrawlSpeechlet  implements SpeechletV2 {

    static final Logger log = Logger.getLogger(VocabBrawlSpeechlet.class);

    private IAlexaService alexaService= new AlexaServiceImpl();
    @Override
    public void onSessionStarted(SpeechletRequestEnvelope<SessionStartedRequest> requestEnvelope) {
        log.info("onSessionStarted " );
        log.info("Request requestId "+requestEnvelope.getRequest().getRequestId()
                +" session Id "+requestEnvelope.getSession().getSessionId()+
                " user ID "+requestEnvelope.getSession().getUser().getUserId());
        // any initialization logic goes here
    }

    @Override
    public SpeechletResponse onLaunch(SpeechletRequestEnvelope<LaunchRequest> requestEnvelope) {
        log.info("onLaunch");
        log.info("Request requestId "+requestEnvelope.getRequest().getRequestId()
                +" session Id "+requestEnvelope.getSession().getSessionId()+
                " user ID "+requestEnvelope.getSession().getUser().getUserId());
        return getWelcomeResponse();
    }

    @Override
    public SpeechletResponse onIntent(SpeechletRequestEnvelope<IntentRequest> requestEnvelope) {
        IntentRequest request = requestEnvelope.getRequest();
        log.debug("reached Intent");
        log.info("onIntent");
        log.info("Request requestId "+requestEnvelope.getRequest().getRequestId()
                +" session Id "+requestEnvelope.getSession().getSessionId()+
                " user ID "+requestEnvelope.getSession().getUser().getUserId());

        Intent intent = request.getIntent();
        String intentName = (intent != null) ? intent.getName() : null;

        if ("HelloWorldIntent".equals(intentName)) {
            log.debug("HelloWorldIntent Intent");
            log.debug(alexaService);
            //IAlexaService alexa = new AlexaServiceImpl();
            return alexaService.getHelloIntentResponse();
        } else if ("AMAZON.HelpIntent".equals(intentName)) {
            return getHelpResponse();
        } else {
            return getAskResponse("HelloWorld", "This is unsupported.  Please try something else.");
        }
    }

    @Override
    public void onSessionEnded(SpeechletRequestEnvelope<SessionEndedRequest> requestEnvelope) {
        log.info("onSessionEnded");
        log.info("Request requestId "+requestEnvelope.getRequest().getRequestId()
                +" session Id "+requestEnvelope.getSession().getSessionId()+
                " user ID "+requestEnvelope.getSession().getUser().getUserId());
        // any cleanup logic goes here
    }

    /**
     * Creates and returns a {@code SpeechletResponse} with a welcome message.
     *
     * @return SpeechletResponse spoken and visual response for the given intent
     */
    private SpeechletResponse getWelcomeResponse() {
        String speechText = "Welcome to the Alexa Skills Kit, you can say hello";
        return getAskResponse("HelloWorld", speechText);
    }

    /**
     * Creates a {@code SpeechletResponse} for the hello intent.
     *
     * @return SpeechletResponse spoken and visual response for the given intent
     */
    private SpeechletResponse getHelloResponse() {
        log.debug("reached hello world");
        String speechText = "Hello world";

        // Create the Simple card content.
        SimpleCard card = getSimpleCard("HelloWorld", speechText);

        // Create the plain text output.
        PlainTextOutputSpeech speech = getPlainTextOutputSpeech(speechText);

        return SpeechletResponse.newTellResponse(speech, card);
    }

    /**
     * Creates a {@code SpeechletResponse} for the help intent.
     *
     * @return SpeechletResponse spoken and visual response for the given intent
     */
    private SpeechletResponse getHelpResponse() {
        String speechText = "You can say hello to me!";
        return getAskResponse("HelloWorld", speechText);
    }

    /**
     * Helper method that creates a card object.
     * @param title title of the card
     * @param content body of the card
     * @return SimpleCard the display card to be sent along with the voice response.
     */
    private SimpleCard getSimpleCard(String title, String content) {
        SimpleCard card = new SimpleCard();
        card.setTitle(title);
        card.setContent(content);

        return card;
    }

    /**
     * Helper method for retrieving an OutputSpeech object when given a string of TTS.
     * @param speechText the text that should be spoken out to the user.
     * @return an instance of SpeechOutput.
     */
    private PlainTextOutputSpeech getPlainTextOutputSpeech(String speechText) {
        PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
        speech.setText(speechText);

        return speech;
    }

    /**
     * Helper method that returns a reprompt object. This is used in Ask responses where you want
     * the user to be able to respond to your speech.
     * @param outputSpeech The OutputSpeech object that will be said once and repeated if necessary.
     * @return Reprompt instance.
     */
    private Reprompt getReprompt(OutputSpeech outputSpeech) {
        Reprompt reprompt = new Reprompt();
        reprompt.setOutputSpeech(outputSpeech);

        return reprompt;
    }

    /**
     * Helper method for retrieving an Ask response with a simple card and reprompt included.
     * @param cardTitle Title of the card that you want displayed.
     * @param speechText speech text that will be spoken to the user.
     * @return the resulting card and speech text.
     */
    private SpeechletResponse getAskResponse(String cardTitle, String speechText) {
        SimpleCard card = getSimpleCard(cardTitle, speechText);
        PlainTextOutputSpeech speech = getPlainTextOutputSpeech(speechText);
        Reprompt reprompt = getReprompt(speech);

        return SpeechletResponse.newAskResponse(speech, reprompt, card);
    }

}

A: Please call setAmazonProperties() method before SpringApplication.run(VocabBrawlAlexaApplication.class, args);
 public static void main(String[] args) {
        LOGGER.info("Info Message Logged !!!");
        setAmazonProperties();
        SpringApplication.run(VocabBrawlAlexaApplication.class, args);
        LOGGER.info("Info Message Logged asdfsa !!!");
    }


text:
Q: Binding data from view to controller in AngularJS Hello I am building an angular application and I have a problem inside my stripe form. Basically I send data such as card number, expiry date and CVC code from the view to the controller's stripe callback, but I would like to add also the amount of money to pay. So I added this into my form:
<form stripe-form="handleStripe" name="myForm">

            Amount
            <input name='price' type="number" id="amount" ng-model="price">

            Card number
            <input type="text" name="number" id="cardn"  ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="myForm.number.$card.type"/>

            Expiry
            <input type="text" id="exp" ng-model="expiry" payments-validate="expiry" payments-format="expiry" />

            CVC
            <input type="text" id="cvc" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type"/>

            <button type="submit" class="btn btn-primary btn-large">Pay {{ price }}</button>

</form>

In the controller I have this variable:
▸   $scope.price = 0;

When I first load the page I can see that the price input has exactly the same amount that I put in the variable $scope.price. But when I changed it in the page and submit the form, $scope.price is always 0.
It's like the data is being passed from the controller to the view, but not the way back from the view to the controller.
How can I solve this?

A: I think your issue is with ng-if that wraps your input with price model. ng-if creates its own scope and in your case the price is connected with the scope inside ng-if and not with you controller.
You could use ng-show instead, or set the model like this: ng-model = "$parent.price" or use controllerAs syntax and you don't have to worry about this issue anymore.


text:
Q: What join do I use? Hello I have 1 database with the following 3 tables:
Classroom ///
Student ///
ClassroomToStudent

A student can have multiple classrooms
A classroom can have multiple students
Classroom:

classroomid (primary key)
classroomnumber

Student:

studentid (primary key)
studentName

ClassroomToStudent:

ctsid (primary key)
studentid
classroomid

A student called john with an id of 1, and a classroom with number 10 with an id of 1 excist. The ClassroomToStudent table has a ctsid of 1, a studentid of 1 and a classroom id of 1.
These are related.
So, now that the ClassroomToStudent table has 1 row with 3 values, I want to display the name of the student that matches the name of the classroom. So john has a classroom with the number of 10. I want to display this in a HTML table but I don't know what join to use. I hope someone can hepl me out with this.

A: SELECT s.studentName, c.classroomnumber
FROM Student AS s
LEFT JOIN ClassroomToStudent AS cs
ON s.studentid = cs.studentid
LEFT JOIN Classroom AS c
ON c.classroomid = cs.classroomid

Give that a try, then loop the query (while ($databaseClass->fetch($query)), while echoing the results as you'd like :)

A: SELECT s.studentName
FROM Classroom AS c
LEFT JOIN ClasroomToStudent AS cs
ON c.classroomid = cs.classroomid
LEFT JOIN Student AS s
ON cs.studentid = s.studentid
WHERE c.classroomnumber = x // x is a class number you're looking for

This sql gives You students names wchich are connected to class with number x


text:
Q: Reuse a group of buttons across several fragments I have a fragment defined by the following xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_example"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_example"/>

</RelativeLayout>

Now I would like to reuse the ImageButton (and other buttons I will add) in another fragment, ideally

*

*without copying its definition

*by keeping the definition in xml and not adding it programmatically

I.e. the goal is to overlay the same set of buttons in different fragments.
Is there a way to define all buttons in a separate xml file and load them programmatically on fragment creation?

A: Yes, You can.
Define all buttons in different xml say layout_buttons.xml
and add them in each fragment layout using
<include layout="@layout/layout_buttons" />


text:
Q: what's the odds of winning 3 times my money on the first try when I have a 50% chance of winning every bet? the odds of winning 2 times (W W) my money on the first try is 50%.
for 3 times in a row (W W W) it is 12.5%
but I need to include W W L W W as it also means i've won 3 times my money.
then there's W W L W L W W and so on and so forth.
as you can see I'm not very good at this, all help is greatly appreciated.
the real question is really "what's the odds of winning 20 times my money on the first try when i have a 50% change of winning every bet".
potentially irrelevant additional information:
I'm betting the same amount (my starting capital) everytime.

A: To solve the more general question: Assume you have $n$ times the betting amount, what is the probability that you reach $m$ before being broke? Let's call this probability $f(n,m)$. You are interested in $f(1,3)$ (or ultimately in $f(1,20)$).
We have the recursion
$$\tag1f(n,m)=\frac 12f(n+1,m)+\frac12f(n-1,m) $$
We obtain $m-1$ equations in the $m-1$ unknowns $f(1,m),\ldots, f(m-1,m)$ by writing down the instances of $(1)$ for $n=1,\ldots, m-1$ and observing that $f(0,m)=0$ and $f(m,m)=1$. But instead of laboriously solving this system of equations, we can in fact "guess" the right solution: According to $(1)$, in the sequence $f(0,m),f(1,m), \ldots, f(m,m)$, each term is the arithmetic mean of its neighbours, which mean sthe sequence is an arithmetic sequence. From the boundary conditions for $n=0$, $n=m$, we conclude $$f(n,m)=\frac nm. $$

If we generalize even further and say that the the winning probability of a single round is $p$ instead of $\frac12$ (but the payout on success is the bet amount), then $(1)$ becomes
$$\tag2 f(n,m)=pf(n+1,m)+(1-p)f(n-1,m) $$
We immediately "see" that this system has solutions of the form $f(n,m)=\lambda^n$ where $\lambda$ is a root of the quadratic equation $x=px^2+(1-p)$; so $\lambda=\frac{1\pm\sqrt{1-4p(1-p)}}{2p}$, which simplifies to $\lambda_1=1$, $\lambda_2=\frac{1-p}p$. The most general solution is then of the form $f(n,m)=c_1\lambda_1^n+c_2\lambda_2^n$, but we need to additionally pick $c_1,c_2$ such that $f(0,m)=0$, $f(m,m)=1$ happens, i.e., $c_1+c_2=0$, $c_1+c_2\frac{(1-p)^m}{p^m}=1$. We conclude
$$f(n,m)=\frac{p^m}{(1-p)^m-p^m}\left(\frac{(1-p)^n}{p^n}-1\right) $$

A: Start by looking for a pattern. Firstly start with the easy case - winning once. This requires an odd number of games. Writing out the first few possibilities will let us looking for a pattern:
1 game: "W"
3 games: "LWW"
5 games: "LWLWW", "LLWWW"
7 games: "LWLWLWW", "LWLLWWW", "LLWWLWW", "LLWLWWW", "LLLWWWW"
9 games: "LWLWLWLWW", "LWLWLLWWW", "LWLLWWLWW", "LWLLWLWWW", "LWLLLWWWW", "LLWWLWLWW", "LLWWLLWWW", "LLWLWWLWW", "LLWLWLWWW", "LLWLLWWWW", "LLLWWWLWW", "LLLWWLWWW", "LLLWLWWWW", "LLLLWWWWW"
etc.
We see the pattern: 1,1,2,5,14,... A quick internet search turns up that this is the Catalan Numbers.
From these you could start working out the probabilities:
Applying this approach to your three wins version gives:
3 games: "WWW"
5 games: "WWLWW", "WLWWW", "LWWWW"
7 games: "WWLWLWW", "WWLLWWW", "WLWWLWW", "WLWLWWW", "WLLWWWW", "LWWWLWW", "LWWLWWW", "LWLWWWW", "LLWWWWW"
9 games: "WWLWLWLWW", "WWLWLLWWW", "WWLLWWLWW", "WWLLWLWWW", "WWLLLWWWW", "WLWWLWLWW", "WLWWLLWWW", "WLWLWWLWW", "WLWLWLWWW", "WLWLLWWWW", "WLLWWWLWW", "WLLWWLWWW", "WLLWLWWWW", "WLLLWWWWW", "LWWWLWLWW", "LWWWLLWWW", "LWWLWWLWW", "LWWLWLWWW", "LWWLLWWWW", "LWLWWWLWW", "LWLWWLWWW", "LWLWLWWWW", "LWLLWWWWW", "LLWWWWLWW", "LLWWWLWWW", "LLWWLWWWW", "LLWLWWWWW", "LLLWWWWWW"
Which gives a pattern of: 1,3,9,28... Another quick internet search turns up that this is also linked to Catalan Numbers.
Applying this idea again to different numbers of wins (working left out as its pretty repetitive gives the following patterns:
1 win: 1,1,2,5,14,42,132,429...
2 wins: 1,2,5,14,42,132,429...
3 wins: 1,3,9,28,90,297,1001...
4 wins: 1,4,14,48,165,572...
5 wins: 1,5,20,75,275,1001...
6 wins: 1,6,27,110,429...
7 wins: 17,35,154,637...
Each of these links to the Catalan numbers.
Conclusion
This doesn't directly answer your question as the sum of Catalan numbers times powers of $\frac12$ still needs to be calculated. I have not calculated this as given an infinity amount of time you will eventually win a finite number of times for any given finite number. However along the way you may reach very large negatives which could exceed your bank account.
Update/Edit
Attempting similar enumeration with the restriction that the player cannot go into debt gives the following sequences:
1 win: 1 (only one term W)
2 wins: 1 (only one term WW)
3 wins: 1,1,1,1,1,1,etc
4 wins: 1,2,4,8,16,32,etc
5 wins: 1,3,8,21,55,144,etc (biFibonacci sequence)
6 wins: 1,4,13,40,121,etc $\left(\frac{3^n-1}{2}\right)$
7 wins: 1,5,19,66,221,728 (on OEIS but not a simple formula)
There seems much less linking these patterns than I found before.

A: If you play forever with unlimited money the chance that you ever triple your money is 1. There are two problems: One is that your probability of winning isn't 50%. Two is that if you start with k times your bet in your pocket, there is a chance that you lose all your money and have to stop.

A: The odds of winning 20 coin flips before losing 1 coin flip (relative to your original starting amount) is 1/21. (It does not matter if the betting choices are randomly or arbitrarily chosen between heads or tails every flip.)
The odds of winning 3 coin flips before losing 1 coin flip is 1/4.
For more examples:
The odds of winning 17 coin flips before losing 1 coin flip is 1/18. The odds of winning 1 coin flip before losing 1 coin flip is 1/2. The odds of winning 10 coin flips before losing 1 coin flip is 1/11.
The odds of winning n coin flips before losing 1 coin flip is 1/(n+1)
The odds of winning 5 coin flips before losing 5 coin flips is 1/2.
If you have 10 chips and your opponent has 10 chips your odds of winning are equal to your opponents odds of winning, which is 10/20 or 1/2.
If play progresses and he, your opponent, has 15 chips and you have 5 chips then now your odds of winning are only 5/20 or 1/4.
If play progresses and he has 19 chips and you have only 1 chip left then your odds of winning are 1/20. That means you must make a come back by winning 19 chips, however long it might take, to win the game.
But what if there is no "chip stack"? You just want to win 20 bets before losing 1 bet relative to your original starting amount. (That starting amount is arbitrary. It can be any reference point number you want. It is as many chips as you decide to take to the coin flip series "table" but you dont want to ever go under that amount. If you take 100 chips to the table, that means the game is considered "lost" if you keep playing and get to 99 chips before getting to 120 chips. If you get to 120 chips before getting to 99 chips, you stop, and that game is considered "won".)
If you take 1 chip to the table, then the game is lost  when you have no chips left and won when you have 21 chips. This is just like having a chip stack game where your opponent has 20 chips and you have 1 chip. That means you have to win 20 chips from him to win the game, but he has to win only 1 chip from you to win the game. The winner has 21 chips at the end of the game and the loser has no chips left.
The total amount of chips in the game are 21 and you have 1 chip. So your odds of winning are 1/21.
If you want to win Y coin flips before your friend wins F coin flips the odds are 1-Y/(Y+F).
(Or, if you prefer, it can be written as F/(Y+F).)
The relative odds of you beating an opponent at a fair coin flip "chip stack" game is simply the ratio of the two chip stacks.


text:
Q: How to locate matches in two dataframes with contains How caqn I locate a string from a dataframe field (df1), in a string from another dataframe field (df2)? Is it possible with the command contains?
Example:
df1[field1]="CEG"

df2[field2]=" CRAT Z.8.1 and Z.8.2 (INC-0022540490) M-137 --- NT[002][URB:1-CEG PET:GR.7:C2-98-S1] --- "


text:
Q: Android what is the best way to auto-connect to ble device I'm currently trying to make an Android app that will have some interaction with a BLE device. That device doesn't have the Ibeacon protocol.
What I want to do is auto connect to that device every time it is in range even (and almost 99% of the time) when the app is not in foreground. The only thing I know is that it is a BLE device, I have access to it name and address (00:1E:C0:29:BD:F8).
It is crucial tha the app connect to it every time it come in range. Even if the phone is lock it must connect no matter what (except if the phone is shut down XD). But as soon as the phone has booted and that bluetooth is activated, I must be sure that my app will be able to connect to tha device if it come in range.
I wanted to know what is the best way to do so.
The only way I can think of is to start a service as sticky, that will scan every 15 seconds (or something similar) for the device it already has registered to auto-connect.
The downfall of that method I guess is that it will surely drain the battery, I'm not sure about that but doing a scan for 3 to 4 second every 15 second must use up a lot of battery.
What do you guys think of that ?
Does anybody know a better solution I could use ?
Thank in advance for the help.


text:
Q: Should I downvote questions posted on the wrong SE site? If a question is not directly "bad", but placed on the wrong SE network (e.g., posted on stackoverflow.com when it should have been posted on superuser.com), in addition to close-voting, should I also downvote the question? Or not?

A: I generally do not downvote a question that is a good question, but merely submitted to the wrong stack. I will flag/VTC the question, and will sometimes explain why the question is inappropriate for the stack.
If the question is on a topic that belongs on a different stack, but would likely be closed on the "correct" stack for various poor-quality-related reasons, I will flag/VTC for a reason other than it being on the wrong stack, and will comment that the topic belongs on [whatever-stack], but would not be acceptable there in the present form because [reasons].


text:
Q: PHP prevent die before executing full code I have code as below where I am redirecting the user at the end but sometimes it seems that the output variable is not getting set or insert query is not getting executed . So is there any way I can wait for all the operations to be completed before the die statement is executed.
Thanks
$diff=levenshtein(strtolower($str1),strtolower($str2));
        if($diff<=2)
            {
            $output="ok";
            }
         else
            {
            $output="Not ok";
            }

$query="INSERT INTO `table` (`sn`, `output`) VALUES (NULL,'$output')";
$result=mysqli_query($con,$query);

header('Location: http://www.domain.com/');
die;

A: There may be several reasons why it doesn't work.
The first one and most obvious is that is enough to have only one simple warning on your page (variable X is not set) and this will broke your header() command. It would say that headers have been already set.
The second problem is that sometimes the server is so busy answering other request and your $con variable will be a Boolean false instead of a reliable database connector, therefore your query could fail because of this too.
I encountered both situations in real life and I solved them by ensuring that every variable is set before use it and by checking if the query was executed successfully.
You can check if a variable is set by using this code:
if (!isset($variable)) $variable = "set me here";

You can check if your query was succesfully executed by adding this:
if (!$result) {
    //do something here in case your query failed
}


text:
Q: Type 'System.Web.HttpContextWrapper' in Assembly 'System.Web' is not marked as serializable I am trying to execute some queries using Microsoft.SqlServer.Management.Smo.Server in my web application. But it throws the following exception:
Type 'System.Web.HttpContextWrapper' in assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.

Here is my code (simplified for more clearance):
string script = "INSERT INTO MyTable (Field1, Field2) VALUES (1, N'Test Value');";
using (SqlConnection sqlConnection = new SqlConnection("Data Source=.;Initial Catalog=MyDB;Integrated Security=True"))
{
    ServerConnection serverConnection = new ServerConnection(sqlConnection);
    var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
    server.ConnectionContext.ExecuteNonQuery(script);
}

And here is the stack trace:
[SerializationException: Type 'System.Web.HttpContextWrapper' in assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.]
   System.AppDomain.get_Id() +0
   <CrtImplementationDetails>.DoCallBackInDefaultDomain(IntPtr function, Void* cookie) +136
   <CrtImplementationDetails>.LanguageSupport.InitializeDefaultAppDomain(LanguageSupport* ) +36
   <CrtImplementationDetails>.LanguageSupport._Initialize(LanguageSupport* ) +359
   <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* ) +76

[ModuleLoadException: The C++ module failed to load while attempting to initialize the default appdomain.
]
   <CrtImplementationDetails>.ThrowModuleLoadException(String errorMessage, Exception innerException) +53
   <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* ) +191
   .cctor() +33

[TypeInitializationException: The type initializer for '<Module>' threw an exception.]
   Microsoft.SqlServer.Management.Common.ExecuteBatch.GetStatements(String sqlCommand) +0

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +128
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +142
   System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) +1573
   Microsoft.SqlServer.Management.Common.ServerConnection.GetStatements(String query, ExecutionTypes executionType, Int32& statementsToReverse) +472
   Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType, Boolean retry) +84
   Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand) +18
   MyApplication.Controllers.HomeController.Index() in D:\MyApplication\Controllers\HomeController.cs:62
   lambda_method(Closure , ControllerBase , Object[] ) +87
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +229
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +38
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +188
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +68
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +68
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +602
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +128

The code runs without any problem in a clean project (web application or console application). But in my real project, throws exception. I tried version 140.17283.0 and 150.18068.0-preview of the Microsoft.SqlServer.SqlManagementObjects package.


text:
Q: How to handle java.lang.OutOfMemoryError: Java heap space error on Google App Engine? I have an application deployed on Google App Engine and it throws:   java.lang.OutOfMemoryError: Java heap space  error while executing. I came across some solutions that talk about how to increase the heap size of VM by configuring eclipse.ini file, however that works only when application's running locally, so how do we configure and control the heap space size when the application is deployed on Google App Engine, is there a way to access the Java runtime on Google app engine ? Any help would be greatly appreciated.

A: As already stated you can increase your frontend instances to larger instances on the "Application Settings" (on the old GAE console) , unfortunately that might not really help you.
If you really need memory intensive operations consider moving taht portion of your app to a managed VM or a Cloud compute instance where you have more control over the environment in which your app runs.

A: In order to configure memory for an application deployed on GAE, previously there were options to select a Front end Instance Class which is shown in screenshot below :

However these options are no longer available on the GAE admin console, the screenshot below shows that GAE has fewer options now :

Now the same Front end Instance Class needs to be configured using a XML file as part of the application as decribed on this page : https://cloud.google.com/appengine/docs/java/modules/#Java_Configuration


text:
Q: Best language/method to produce a dynamic user-customisable xml-based GUI? I'm looking to start a personal project - but have no idea where to start!
Take a look at the igoogle website.
Basically it's comprised of multiple columns of different sized boxes, that can be easily moved around by the user.
I'm looking for the best/easiest way to create something like that, where the data displayed in the boxes is populated via XML.
Suggestions please?

A: JQueryUI Seems to be the best way to go about it.
The following URLs provide examples of how it's supposed to work, and code to do it.
(:// removed to stop URL's being filtered)
http jqueryui.com/demos/sortable/#portlets
http jqueryui.com/demos/sortable/
http jqueryui.com/demos/draggable/
http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/
http www.webappers.com/2008/11/19/how-to-create-igoogle-interface-with-jquery/
http geekswithblogs.net/AzamSharp/archive/2008/02/21/119882.aspx
http www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/
If you want to do it with in .NET using WPF:
http blacklight.codeplex.com/
http mightymeaty.members.winisp.net/blacklight.silverlight/


text:
Q: How do I convert 123 to 1,2,3 in pl/sql? Is it possible to convert 123 to 1,2,3 in pl/sql?
is there any easy way to convert or add a comma between two numbers in pl/sql?
thank you.

A: You don't need PL/SQL for this. A regexp_replace will do it:
rtrim(regexp_replace('123','(\d)','\1,'),',')


text:
Q: MongoDB Authentication Not Working Despite Configuring It I have MongoDB 5.0.6 installed and despite adding an admin user and database user via mongosh, as well as editing the /etc/mongod.conf to include authorization: "enabled", it still allows for anonymous users to connect without credentials. How can I force a login for any connection? Thanks

A: Did you restart the MongoDB?
Yes, you can always connect to a MongoDB even without credentials. However, apart from harmless commands like help or getMongo() you cannot execute anything.


text:
Q: Zuul not forwading if have custom security configuration in microservice I am facing issue when use zuul. Firstly I give information with my project. I use Zuul and Consul together in my project and I am trying to create own authentication and authorization system. For this I decide to use oAuth2 protocol with Spring Boot.
So in this architecture,
Zuul is receive request and control access token. If access token doesn't exist in header, route oAuth service. oAuth service authentication user and return access token to client. Client send header with access token and Zuul check access token than route suitable service.
Finally i use jwt as access token and store as jwt data store.
Let's pass issue.
Firstly that's problem, Zuul forwarding request to services that doesn't make to security configuration or make default configuration. But not forwading to services that make custom to security configuration.
Now Zuul services is resource service and have separate an authentication service in my project.
Now if i use only @EnableAutoConfiguration annotation in boot class at Authentication Service. Zuul forward request but i don't want it to be this way.
Additional Info : According to my research If @EnableAutoConfiguration and @Componentannotation use together, Spring boot scan custom configuration but only use @EnableAutoConfiguration then Spring boot not scan custom configuration. Instead of this, Spring boot use default configuration.
If I use  @EnableAutoConfiguration @ComponentScan together in Authentication Service than Zuul throw error as below.
What is the problem? I try every solution but didn't work and came here as last resort Please help me.
com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.handleException(RibbonRoutingFilter.java:190) ~[spring-cloud-netflix-zuul-2.0.0.M5.jar:2.0.0.M5]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:165) ~[spring-cloud-netflix-zuul-2.0.0.M5.jar:2.0.0.M5]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:112) ~[spring-cloud-netflix-zuul-2.0.0.M5.jar:2.0.0.M5]
    at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112) ~[zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:193) ~[zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:157) ~[zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.route(FilterProcessor.java:118) ~[zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.ZuulRunner.route(ZuulRunner.java:96) ~[zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.http.ZuulServlet.route(ZuulServlet.java:116) ~[zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.http.ZuulServlet.service(ZuulServlet.java:81) ~[zuul-core-1.3.0.jar:1.3.0]
    at org.springframework.web.servlet.mvc.ServletWrappingController.handleRequestInternal(ServletWrappingController.java:165) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.cloud.netflix.zuul.web.ZuulController.handleRequest(ZuulController.java:44) [spring-cloud-netflix-zuul-2.0.0.M5.jar:2.0.0.M5]

Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: auth-service
    at com.netflix.loadbalancer.LoadBalancerContext.getServerFromLoadBalancer(LoadBalancerContext.java:483) ~[ribbon-loadbalancer-2.2.4.jar:2.2.4]
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:184) ~[ribbon-loadbalancer-2.2.4.jar:2.2.4]
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:180) ~[ribbon-loadbalancer-2.2.4.jar:2.2.4]
    at rx.Observable.unsafeSubscribe(Observable.java:10256) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:94) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:42) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.Observable.subscribe(Observable.java:10352) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.Observable.subscribe(Observable.java:10319) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.observables.BlockingObservable.blockForSingle(BlockingObservable.java:443) ~[rxjava-1.3.4.jar:1.3.4]
    at rx.observables.BlockingObservable.single(BlockingObservable.java:340) ~[rxjava-1.3.4.jar:1.3.4]
    at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:112) ~[ribbon-loadbalancer-2.2.4.jar:2.2.4]
    at org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand.run(AbstractRibbonCommand.java:117) ~[spring-cloud-netflix-zuul-2.0.0.M5.jar:2.0.0.M5]
    at org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand.run(AbstractRibbonCommand.java:46) ~[spring-cloud-netflix-zuul-2.0.0.M5.jar:2.0.0.M5]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:302) ~[hystrix-core-1.5.12.jar:1.5.12]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:298) ~[hystrix-core-1.5.12.jar:1.5.12]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46) ~[rxjava-1.3.4.jar:1.3.4]

Spring Cloud Version :
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M7</version>
    </parent>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.M5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

If you want firsty i put Zuul Service yml properties.
server:

  port: 8080

spring:
  application:
    name: zuul-service
  cloud:
    consul:
      discovery:
        healthCheckPath: /health
        healthChechInterval: 15s
        prefer-ip-address: true
        instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
      host: 127.0.0.1
      port: 8500
      config:
        enabled: true
        watch:
          enabled: true
  sleuth:
    sampler:
      percentage: 1
zuul:
  routes:
    accounts-service:
      path: /account/**
      serviceId: accounts-service
    product-service:
      path: /product/**
      sensitiveHeaders:
      serviceId: product-service
    auth-service:
      path: /auth/**
      serviceId: auth-service

security:
  basic:
    enabled: false
  oauth2:
    sso:
      loginPath: http://localhost:8081/login
    client:
      clientId: zuulfilter
      clientSecret: secret
      accessTokenUri: http://localhost:8081/oauth/token
      userAuthorizationUri: http://localhost:8081/oauth/authorize
    resource:
      preferTokenInfo:false

And Zuul Boot Class
@EnableZuulProxy
@EnableDiscoveryClient
@EnableAutoConfiguration
@ComponentScan
@Configuration
@EnableResourceServer
public class ZuulServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZuulServiceApplication.class,args);
    }
}

And Zuul Web Security Config
@Configuration
@EnableWebSecurity
@Order(-10)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";
    private static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN";

    @Autowired
    private ResourceServerTokenServices resourceServerTokenServices;

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.authorizeRequests()
                     .antMatchers("/auth/**", "/auth/login", "/account/**","/product/**").permitAll().anyRequest().authenticated()
                     .and()
                     .csrf().requireCsrfProtectionMatcher(requestMatcher()).csrfTokenRepository(csrfTokenRepository())
                     .and()
                     .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                     .addFilterAfter(oAuth2AuthenticationProcessingFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                     .logout().logoutSuccessUrl("/").permitAll();
    }

    private OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter() {
        OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter =
                new OAuth2AuthenticationProcessingFilter();
        oAuth2AuthenticationProcessingFilter.setAuthenticationManager(authenticationManagerBean());
        oAuth2AuthenticationProcessingFilter.setStateless(false);

        return oAuth2AuthenticationProcessingFilter;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() {
        OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager();
        oAuth2AuthenticationManager.setResourceId("zuulservice");
        oAuth2AuthenticationManager.setTokenServices(resourceServerTokenServices);
        oAuth2AuthenticationManager.setClientDetailsService(null);

        return oAuth2AuthenticationManager;
    }

    private RequestMatcher requestMatcher() {
        return new RequestMatcher() {

            private final Pattern allowedMethods = Pattern.compile("^(GET|HEAD|OPTIONS|TRACE)$");

            private final AntPathRequestMatcher [] antPathRequestMatcher = { new AntPathRequestMatcher("/auth/**")};
            @Override
            public boolean matches(HttpServletRequest request) {

                if(allowedMethods.matcher(request.getMethod()).matches()) {
                    return false;
                }

                for(AntPathRequestMatcher matcher : antPathRequestMatcher) {
                    if(matcher.matches(request)) {
                        return false;
                    }
                }
                return true;
            }
        };
    }

    private static Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {

            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

                if(csrfToken != null) {
                    Cookie cookie = new Cookie(CSRF_COOKIE_NAME, csrfToken.getToken());
                    cookie.setPath("/");
                    cookie.setSecure(true);
                    response.addCookie(cookie);
                }
                filterChain.doFilter(request, response);

            }
        };
    }

    private static CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository csrfTokenRepository = new HttpSessionCsrfTokenRepository();
        csrfTokenRepository.setHeaderName(CSRF_HEADER_NAME);
        return csrfTokenRepository;
    }

}

Now secondly Authentication yml properties.
server:
  port: 8081

spring:
  application:
    name: auth-service
  cloud:
    consul:
      discovery:
        healthCheckPath: /health
        healthChechInterval: 15s
        prefer-ip-address: true
        instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
      host: 127.0.0.1
      port: 8500
      config:
        enabled: true
        watch:
          enabled: true
  sleuth:
    sampler:
      percentage: 1

security:
  basic:
    enabled : false

Authentication Server Configuration.
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("zuulfilter")
            .secret("secret")
            .authorizedGrantTypes("authorization_code", "refresh_token")
            .redirectUris("http://localhost:8081")
            .scopes("openid");

    }

    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("examplekeystore.jks"), "1234".toCharArray());
        jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("examplekeystore"));
        return jwtAccessTokenConverter;
    }

}

Authentication Web Security Configuration.
@Configuration
public class LoginConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

            httpSecurity.authorizeRequests().antMatchers("/test").permitAll().anyRequest().authenticated().and()
                    .requestMatchers()
                    .antMatchers("/login", "/oauth/authorize")
                    .and()
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated()
                    .and()
                    .formLogin()
                    .permitAll();
        httpSecurity.formLogin().loginPage("/login").permitAll().
        and().
        authorizeRequests().
        anyRequest().
        authenticated();

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {

        PasswordEncoder encoder = passwordEncoder();
        String password = encoder.encode("1234");
        authManagerBuilder.inMemoryAuthentication().passwordEncoder(encoder).
                    withUser("deneme").
                    password(password).
                    roles("USER");
    }

}

Thanks for help already.


text:
Q: Copying unmanaged memory to Managed byte array I need to read unmanaged memory into a managed byte array.
For this I have an IntPtr reference to unmanaged memory and a length which represents the size of the unmanaged memory that is of interest to me.
I use the following code to read that into a managed byte array.
            byte[] pixelDataArray = new byte[pixelDataLength];
            for (int i = 0; i < pixelDataLength; i++) {
                pixelDataArray[i] = Marshal.ReadByte(pixelData, i);
            }

However this results in very poor performance. Calling this method 1000 times with 256KB of unmanaged memory, takes more than 7 seconds. I think there must be a more efficient way of doing this.
I could not use Marshal.PtrToStructure because i would not know the size of the memory that need to read upfront.
Any ideas on how the performance of this function can be improved?

A: Instead of looping try copying the entire chunk:
Marshal.Copy(pixelData, pixelDataArray, 0, pixelDataLength);

A: Use Marshal.Copy().
byte[] pixelDataArray = new byte[pixelDataLength];
Marshal.Copy(pixelData, pixelDataArray, 0, pixelDataArray.Length);


text:
Q: android development loading Images from URL I Know this question has been asked and answered but i have a different problem. I have a app out right now that wont load images that are higher than 5mp but loads smaller ones. Im not sure if its 5mp or over 1mb, Im pretty sure its mp though, I have tested. How can I load pictures that are all sizes? My code is below, Please help, please post code not links, of must to links then links to code that can help. Thanks!
Downloading The Image
  @Override
            protected Bitmap doInBackground(Object... objects) {
              InputStream is = null;
                      BufferedInputStream bis = null;
                   Bitmap bmp = null;

                   try {
                    URL url = new URL(Pictureurl);
                       URLConnection conn = url.openConnection();
                     conn.connect();
                     is = conn.getInputStream();
                      bis = new BufferedInputStream(is);
                      bmp = BitmapFactory.decodeStream(bis);
                      return bmp;
                 } catch (MalformedURLException e) {
                  return null;
                 } catch (IOException e) {
                  return null;
                   }
    }
        @Override
        protected void onPostExecute(Object resizedBitmap) {
   MainPicture.setImageBitmap((Bitmap) resizedBitmap);
   connectionProgressDialog.dismiss();
         }

Uploading the image
public boolean SaveNewPicture(String SelectedFile, String UpdatedPhotoPath){
 HttpURLConnection conn = null;
 DataOutputStream dos = null;
 DataInputStream inStream = null;
 @SuppressWarnings("unused")

String Message = null;
     // The full path of filename which is to be uploaded to server
     String exsistingFileName = SelectedFile;
 String lineEnd = "\r\n";
 String twoHyphens = "--";
 String boundary = "*****";

 int bytesRead, bytesAvailable, bufferSize;

 byte[] buffer;

 int maxBufferSize = 1*1024*1024;

 @SuppressWarnings("unused")

String responseFromServer = "";
 //Server path to the upload.php
 String urlString = "http://www.thelinkhookup.com/upload.php";

 try
 {
 //------------------ CLIENT REQUEST

 FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );

 // open a URL connection to the Servlet

 URL url = new URL(urlString);

 // Open a HTTP connection to the URL

 conn = (HttpURLConnection) url.openConnection();

 // Allow Inputs
 conn.setDoInput(true);

 // Allow Outputs
 conn.setDoOutput(true);

 // Don't use a cached copy.
 conn.setUseCaches(false);

 // Use a post method.
 conn.setRequestMethod("POST");

 conn.setRequestProperty("Connection", "Keep-Alive");

 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

 dos = new DataOutputStream( conn.getOutputStream() );

 dos.writeBytes(twoHyphens + boundary + lineEnd);
 dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
 dos.writeBytes(lineEnd);

 System.out.println("Headers are written");

 // create a buffer of maximum size

 bytesAvailable = fileInputStream.available();
 bufferSize = Math.min(bytesAvailable, maxBufferSize);
 buffer = new byte[bufferSize];

 // read file and write it into form...

 bytesRead = fileInputStream.read(buffer, 0, bufferSize);

 while (bytesRead > 0)
 {
 dos.write(buffer, 0, bufferSize);
 bytesAvailable = fileInputStream.available();
 bufferSize = Math.min(bytesAvailable, maxBufferSize);
 bytesRead = fileInputStream.read(buffer, 0, bufferSize);
 }

 // send multipart form data necesssary after file data...

 dos.writeBytes(lineEnd);
 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

 // close streams
 System.out.println("File is written");
 fileInputStream.close();
 dos.flush();
 dos.close();

 }
 catch (MalformedURLException ex)
 {
 return false;
 }

 catch (IOException ioe)
 {
 Message = ioe.toString();
 return false;
 }

 //------------------ read the SERVER RESPONSE

 try {
 inStream = new DataInputStream ( conn.getInputStream() );
 String str;

 while (( str = inStream.readLine()) != null)
 {
 //the str contains the server response
 System.out.println("Server Response"+str);
 }
 inStream.close();
 //Message = "Should Have Worked";
 }

 catch (IOException ioex){

 return false;
 }
 try{
    HttpClient client = new DefaultHttpClient();
      HttpPost request = new HttpPost("http://thelinkhookup.com/UpdatePhotoName.php");
       List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
       postParameters.add(new BasicNameValuePair("Username", MyGlobalInfomation.getUsername()));
       postParameters.add(new BasicNameValuePair("Photopath", UpdatedPhotoPath));
       postParameters.add(new BasicNameValuePair("localphotopath",SelectedFile ));
       UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
       request.setEntity(formEntity);
       @SuppressWarnings("unused")

HttpResponse response = client.execute(request);
           if(SelectedFile != null || SelectedFile != ""){
           MyGlobalInfomation.setLocalPhotoPath(SelectedFile);
           }
      }
           catch(Exception e){
            return false;
}
     return true;
     }

A: Are you trying this against different websites or just one?
The only reason I ask is that you mentioned that > 1MB in size might be the cause. I know of some web hosting sites which provide free web space for their members but they're restricted to 1MB total per web page (or any other download). If the members want to have true download sites then they have to pay for the extra bandwidth involved.
Sorry, it probably doesn't answer your question but I thought you might want to check that it isn't the web site configuration before suspecting your code.


text:
Q: Place  items side by side I'm trying to create a sidebar div with icons and a 'top row' div with a image and texts displayed side-by-side. The sidebar is ok but my top row is displaying the image on top of both 'h1' and 'h3'. in it turn, h1 and h3 is displaying side by side.
The html's body:

algum texto

barra de progresso

and the css:
      body {
        background-color: #FCFCFC;
        font: 12px Verdana, sans-serif;
    }

    .top-row {
        position: absolute;
        top: 0;
        left: 12%;
        right: 0%;
        height: 12%;
        margin: auto;
    }

    .top-row span {
        display: inline-block;
    }

    .sidebar{
        position: absolute;
        top: 0;
        left: 0;
        float: left;
        background-color: #EAF6F6;
        width: 11%;
        height: auto;
        border-style: groove;
    }

    .botaoMenu {
        max-height: 80%;
        max-width: 80%;
        width: auto;
        height: auto;
        border: none;
    }

    .botaoMenuFundo {
        max-height: 80%;
        max-width: 80%;
        width: auto;
        height: auto;
        border: none;
        padding-top: 200%;
    }

    .fotoPerfil {
        border-radius: 100%
        max-height:10%;
        max-width:10%;
        width: auto;
        height: auto;
    }

what is wrong with it?

A: You are setting the 10% max width inside .fotoPerfil so it's calculating 10% of the span it's in.
You can set the max-width: 10% to that span that contains the image if you want the profile picture to take 10% of the top bar width.
To visualize these issues you can use Right click -> inspect element or just add background colors to each object until you find out what's taking all that space.
The reason the titles were showing up below the image is because the image (actually the span it's in) is so wide that is taking the whole first line of the top bar, pushing the other elements to a second line.
Something like this should do it:
.fotoPerfil {
    border-radius: 100%;
    max-width:100%;
}
.fotoPerfilContainer {
    max-width:10%;
}

I am not sure what you are trying to achieve without seeing it with all the images, but generally setting widths and heights as percentages of the entire screen end up with strange results that expand or contract too much in different browser sizes.


text:
Q: how to find which field an Entity maps to? I have a table with a simple foreign key relationship, with 2 fields both acting as foreign keys to the same table. It looks like this:
create table Car
(
   CarID int primary key not null identity(1,1),

   FrontSeatID int,
   BackSeatID  int,

   foreign key(FrontSeatID) references Seat(SeatID),
   foreign key(BackSeatID) references Seat(SeatID)
)

create table Seat
(
   SeatID int primary key not null identity(1,1),
   SeatName varchar(50)
)

In entity framework, I retreive an object of type 'Car'. Besides having the integer values of 'BackSeatID' and 'FrontSeatID', tt has 2 Entity objects- one is called 'Seat' and the other is called 'Seat1'.
How do I know which Entity 'Seat' and 'Seat1' point to without checking the ID values? I know obviously I could check the ID's and see that they point to BackSeat and FrontSeat respectively, but is this ordering consistent? How could I check this mapping in the code myself, and why doesn't EntityFramework give a clear distinction on which object this entity points to?
I've done a 'find' in the entire solution for the 'Seat1' and cannot find it anywhere...

A: Navigation properties are named purely by the entity that they point to (as you've seen). It doesn't take the naming of the column in the foreign key table into account, as it would be unrealistic to try to tackle all (or even most) of how someone might name that column.
How, exactly, are you trying to tell which is which? Are you asking if you can determine it programatically or are you using the designer and want to be able to tell which column is supplying the value for the navigation property?

A: If you open the ef designer and right click on the entity you want to check, then from the context menu select Table Mapping (at least I think that is what it is called as I do not have a pc in front of me right now) It will show you which table the entity maps to and which columns each property maps to (along with the data types etc)


text:
Q: crash into /usr/lib/gnome-session/gnome-session-binary in ubuntu 17.10 When I opened the ubuntu I got this crash as mentioned in the screenshot:

The output of /var/log/syslog:
Feb 15 09:14:01 OptiPlex-3020 CRON[14496]: (root) CMD (   test -x

/etc/cron.daily/popularity-contest && /etc/cron.daily/popularity-contest --crond)
Feb 15 09:14:20 OptiPlex-3020 anacron[705]: Job `cron.daily' terminated
Feb 15 09:14:20 OptiPlex-3020 anacron[705]: Normal exit (1 job run)
Feb 15 09:14:59 OptiPlex-3020 update-notifier[13312]: GtkDialog mapped without a transient parent. This is discouraged.
Feb 15 09:14:59 OptiPlex-3020 gnome-shell[4817]: value "-1.000000" of type 'gfloat' is invalid or out of range for property 'width' of type 'gfloat'
Feb 15 09:14:59 OptiPlex-3020 gnome-shell[4817]: value "-1.000000" of type 'gfloat' is invalid or out of range for property 'height' of type 'gfloat'
Feb 15 09:14:59 OptiPlex-3020 gnome-shell[4817]: value "-1.000000" of type 'gfloat' is invalid or out of range for property 'width' of type 'gfloat'
Feb 15 09:14:59 OptiPlex-3020 gnome-shell[4817]: value "-1.000000" of type 'gfloat' is invalid or out of range for property 'height' of type 'gfloat'
Feb 15 09:15:16 OptiPlex-3020 gnome-shell[4817]: Some code accessed the property 'WindowPreviewMenu' on the module 'windowPreview'. That property was defined with 'let' or 'const' inside the module. This was previously supported, but is not correct according to the ES6 standard. Any symbols to be exported from a module must be defined with 'var'. The property access will work as previously for the time being, but please fix your code anyway.
Feb 15 09:15:17 OptiPlex-3020 kernel: [  407.923705] traps: apport-gtk[14534] general protection ip:7f5f13ecb194 sp:7fffe6c15380 error:0 in libgobject-2.0.so.0.5400.1[7f5f13e9a000+52000]
Feb 15 09:15:57 OptiPlex-3020 gnome-terminal.[14576]: Couldn't register with accessibility bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.
Feb 15 09:15:57 OptiPlex-3020 dbus-daemon[2837]: Activating via systemd: service name='org.gnome.Terminal' unit='gnome-terminal-server.service'
Feb 15 09:15:57 OptiPlex-3020 systemd[2787]: Starting GNOME Terminal Server...
Feb 15 09:15:57 OptiPlex-3020 gnome-terminal-[14579]: Couldn't register with accessibility bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.
Feb 15 09:15:57 OptiPlex-3020 dbus-daemon[2837]: Successfully activated service 'org.gnome.Terminal'
Feb 15 09:15:57 OptiPlex-3020 systemd[2787]: Started GNOME Terminal Server.
Feb 15 09:16:36 OptiPlex-3020 org.gnome.Shell.desktop[4817]: Window manager warning: Buggy client sent a _NET_ACTIVE_WINDOW message with a timestamp of 0 for 0x3800084 (syslog [Re)
Feb 15 09:17:01 OptiPlex-3020 CRON[14638]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Feb 15 09:17:20 OptiPlex-3020 dbus-daemon[2837]: Activating service name='org.gnome.Nautilus'
Feb 15 09:17:20 OptiPlex-3020 dbus-daemon[2837]: Successfully activated service 'org.gnome.Nautilus'
Feb 15 09:17:20 OptiPlex-3020 nautilus[14644]: Couldn't register with accessibility bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.
Feb 15 09:17:21 OptiPlex-3020 dbus[686]: [system] Activating via systemd: service name='org.freedesktop.hostname1' unit='dbus-org.freedesktop.hostname1.service'
Feb 15 09:17:21 OptiPlex-3020 systemd[1]: Starting Hostname Service...
Feb 15 09:17:21 OptiPlex-3020 nautilus[14644]: Called "net usershare info" but it failed: Failed to execute child process "net" (No such file or directory)
Feb 15 09:17:21 OptiPlex-3020 dbus[686]: [system] Successfully activated service 'org.freedesktop.hostname1'
Feb 15 09:17:21 OptiPlex-3020 systemd[1]: Started Hostname Service.
Feb 15 09:17:27 OptiPlex-3020 dbus-daemon[2837]: Activating via systemd: service name='org.gnome.zeitgeist.Engine' unit='zeitgeist.service'
Feb 15 09:17:27 OptiPlex-3020 systemd[2787]: Starting Zeitgeist activity log service...
Feb 15 09:17:27 OptiPlex-3020 dbus-daemon[2837]: Activating via systemd: service name='org.gnome.zeitgeist.SimpleIndexer' unit='zeitgeist-fts.service'
Feb 15 09:17:27 OptiPlex-3020 dbus-daemon[2837]: Successfully activated service 'org.gnome.zeitgeist.Engine'
Feb 15 09:17:27 OptiPlex-3020 systemd[2787]: Started Zeitgeist activity log service.
Feb 15 09:17:27 OptiPlex-3020 systemd[2787]: Starting Zeitgeist full-text search indexer...
Feb 15 09:17:27 OptiPlex-3020 zeitgeist-daemon[14662]: #033[31m[08:17:27.365997 WARNING]#033[0m zeitgeist-daemon.vala:334: Failed to execute child process "zeitgeist-datahub" (No such file or directory)
Feb 15 09:17:27 OptiPlex-3020 zeitgeist-daemon[14662]: #033[31m[08:17:27.366081 WARNING]#033[0m zeitgeist-daemon.vala:127: Unable to parse version info!
Feb 15 09:17:27 OptiPlex-3020 zeitgeist-daemon[14662]: #033[31m[08:17:27.366151 WARNING]#033[0m zeitgeist-daemon.vala:127: Unable to parse version info!
Feb 15 09:17:27 OptiPlex-3020 dbus-daemon[2837]: Successfully activated service 'org.gnome.zeitgeist.SimpleIndexer'
Feb 15 09:17:27 OptiPlex-3020 systemd[2787]: Started Zeitgeist full-text search indexer.
Feb 15 09:17:33 OptiPlex-3020 gnome-terminal.[14683]: Couldn't register with accessibility bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.
Feb 15 09:17:50 OptiPlex-3020 org.gnome.Shell.desktop[4817]: Window manager warning: Buggy client sent a _NET_ACTIVE_WINDOW message with a timestamp of 0 for 0x3800084 (syslog (~/)

How can I fix this?


text:
Q: Are UUID4s distributed evenly across the md5 address space? (I will preface this question by saying I think there is virtually no way that UUID4 would be designed not to be uniformly distributed, but I lack the math skills and crypto knowledge to prove it.)
In streaming a bunch of data to kinesis, we are experiencing a problem where one shard, shard #4, is very hot and the other seven shards are underloaded. Kinesis distributes data across its shards by a partition key, which is a unicode string that it converts to an md5 hash.
Shards are sequential by default, so if you have one shard it will have all partition keys from 0 - 2^128 in it. We have eight shards, so the buckets are bounded at increments of 2^125. The end of each shard range is, in hex,
0x20000000000000000000000000000000
0x40000000000000000000000000000000
0x60000000000000000000000000000000
0x80000000000000000000000000000000
0xa0000000000000000000000000000000
0xc0000000000000000000000000000000
0xe0000000000000000000000000000000
0x100000000000000000000000000000000

We partition based on a UUID 4. We had assumed that that would be evenly distributed across the above address space, but with this "hot shard" problem I'm starting to wonder. UUID4s are 2^128 bits, but they reserve six bits for deterministic information, leaving 2^122 values that can be random. It's those six bits that give me pause.
Trivially, if I take the six most significant bits away, my largest possible value is 2^122, which will certainly fall in the first or second bucket, all the time. But back in reality those six digits aren't the most significant of the UUID4 space, so what effect do they have on the distribution? If I use a UUID4 for a sharding key, will my data be evenly distributed across the shards?