text:
Q: Asymptotic Relative Efficiency: Poisson I'm trying to find the asymptotic relative efficiency of a Poisson process:
$$\frac{\lambda^t \exp(-\lambda)}{t!} =  P(X=t).$$
When $X = t = 0$, the best unbiased estimator of $e^{-\lambda}$ is ((n-1)/n)$^y$, where y = $\Sigma{X_i}$, the complete sufficient statistic for $\lambda$.
When $X = t = 1$, the best unbiased estimator of $\lambda e^{-\lambda}$ is $\frac{y}{n}\left(\frac{n-1}{n}\right)^{y-1}$.
It is stated that the asymptotic relative efficiency for $t=0$ is:
ARE $$\left(\left( \frac{n-1}{n}\right)^{n \hat{\lambda}}, \quad\frac{y}{n}\left(\frac{n-1}{n}\right)^{y-1}\right) = \left[\frac{e^{-\lambda}}{\left(\frac{n-1}{n}\right)^{n\lambda}\log\left( \frac{n-1}{n}\right)^n}\right]^2$$
I'm not able to calculate this.

A: The asymptotic relative efficiency compares the variance of $T_1=\displaystyle\left(\frac{n-1}{n}\right)^{n\hat{\lambda}}$ to the variance of the second $T_2=\frac{y}{n}\left(\frac{n-1}{n}\right)^{y-1}$. I will find the variance of the first UMVUE $T_1$ using the Delta Method:
Since $T(X)=\sum X_i$ is the sufficient statistic for $\lambda$, and $\sum X_i\sim \mathrm{Poisson}(n\lambda)$, then $\operatorname{Var}\left(\sum X_i\right)=n\lambda (1-\lambda)$ assuming $X_i$'s are iid.
To find the variance of $T_1$, let $g(x)=\left(\frac{n-1}{n}\right)^x$ so using Delta Method, $g'(x)=\displaystyle\left(\frac{n-1}{n}\right)^{x}\log\left(\frac{n-1}{n}\right)$
$(g'(\lambda))^2=\displaystyle\left(\frac{n-1}{n}\right)^{\lambda}\log\left(\frac{n-1}{n}\right)$
$\operatorname{Var}(T_1)=(g'(\lambda))^2\operatorname{Var}(\sum X_i)=\left(\frac{n-1}{n}\right)^{2\lambda}\left(\log\frac{n-1}{n}\right)^2n\lambda (1-\lambda)$.
The variance of $T_2$ can be found similarly.


text:
Q: Setting a default value to a blank form in html.(Ruby, Sinatra, CSS) im very new to html and have a basic understanding and cant use java query or javascript yet. I am trying to give a player the option to fill in the player 2 name field to play a friend or leave it blank to play the computer in a basic game of rock, paper, scissors. I was hoping that if the field was left blank the param would pass nothing and the default value would be set in my Player Class.
Html:
<form id="name_form" action="/name" method="post">
  Enter Player Name:
  <input type="text" id="player_name" name="name" >
   Second Player Name:
  <input type="text" id="player_name" name="name2" >
  <input type="submit" value="Play!" id="play_button";>
</form>

Ruby:
class Player

  attr_reader :name

  def initialize name = "Computer"

    @name = name

  end

end

Controller:
  post '/name' do
    player = Player.new params[:name]
    player2 = Player.new params[:name2]
    @game = Game.create player, player2
    redirect '/play'
  end

I was hoping something like the above would workbut i cant it to. Am i missing something? I would rather not use javascript yet. Thanks

A: params[:name] and params[:name2] have an empty string "" as a value. So, you are actually passing an empty string to your constructor. That's is "default value" is not used. If you want to use default value, then you have to omit an argument, like so:
Player.new
# => #<Player:0x007f9c5116b698 @name="Computer">

Also, note, passing nil will still mean that you are passing an argument with the value of nil and default value will not be picked up
Player.new
# => #<Player:0x007f9c5116b698 @name=nil>

That's why you need to update your code to this:
class Player
  attr_reader :name

  def initialize name
    @name = name.empty? ? "Computer" : name
  end
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: While trying to mint NFTs from Hardhat to Polygon Mainnet using JS script getting error ProviderError: HttpProviderError I am trying to mint nfts using js script but I get this vague error ProviderError: HttpProviderError I have deployed my contract on polgonscan mainnet.
I have tested this script on the polygon test network Mumbai and works perfectly fine but on the mainnet, it gives an error. Any kind of help would be highly appreciated.
My minting script is:

require("dotenv").config();
require("@nomiclabs/hardhat-ethers");
const contract = require("../artifacts/contracts/MintNFT.sol/MintNFT.json");
const contractInterface = contract.abi;
let provider = ethers.provider;
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);
wallet.provider = provider;
const signer = wallet.connect(provider);

const id = 1; // id of the nft to be minted
const amount = 2500; // number of times nft should be minted

async function main() {
  try {
    const mintContract = new ethers.Contract(
      process.env.CONTRACT_ADDRESS,
      contractInterface,
      signer
    );
    await mintContract.functions.mint(id, amount);
  } catch (error) {
    console.log("Error:", error);
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

This is my hardhat config which I used to deploy contract on mainnet

require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config();

const { API_URL, PRIVATE_KEY } = process.env;

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.17",
  defaultNetwork: "matic",
  networks: {
    mumbai: {
      url: API_URL,
      accounts: [`0x${PRIVATE_KEY}`],
    },
    matic: {
      url: "https://polygon-mainnet.g.alchemy.com/v2/tDq9iU4BH3fEusvjSlbuOHiJhSuBHM_1",
      accounts: [`0x${PRIVATE_KEY}`],
    },
  },
};

A: Try to set gasLimit of transaction:
await mintContract.functions.mint(id, amount, { gasLimit: 40000000 });


text:
Q: GLESDebugDraw only for iOS usage? I'm using some examples from this book:
http://www.amazon.com/Cocos2d-x-Example-Beginners-Guide-Engelbert-ebook/dp/B00CITNP8A/ref=sr_1_1?ie=UTF8&qid=1393328148&sr=8-1&keywords=cocos2d-x
and in them he uses Box2D with GLESDebugDraw.  When I tried compiling for Win32 it complained that it couldn't find GLES-Render.h. I did some digging and found it in:
C:\Box2D_v2.3.0\Contributions\Platforms\iPhone\Classes
That leads me to believe that this is for iOS usage only.  Is it?
I tried including the *Render.h file from there but it then complained about more header files not found... which seemed even more iOS specific.
Thanks for any info!


text:
Q: How do I iterate over this hash selectively? {
  "menu": {
    "header": "menu",
    "items": [
      {"id": 27},
      {"id": 0, "label": "Label 0"},
      null,
      {"id": 93},
      {"id": 85},
      {"id": 54},
      null,
      {"id": 46, "label": "Label 46"}
    ]
  }
}

Above is the JSON that I am trying to iterate through.  Essentially, I would like to identify the value of key "id" if that hash also has a "label" key.
So the above would return 0 and 46 as well.
I am stuck here:
require 'json'

line = '{"menu": {"header": "menu", "items": [{"id": 27}, {"id": 0, "label": "Label 0"}, null, {"id": 93}, {"id": 85}, {"id": 54}, null, {"id": 46, "label": "Label 46"}]}}'
my_parse = JSON.parse(line)
items = my_parse['menu']['items'].compact.select { |item| item['label'] }

puts items.inject

A: Use Array#select to identify the elements that have both "id" and "label" then Array#map to pluck only the "ids".
hash = JSON.parse(your_json_string)
hash['menu']['items'].select { |h| h && h['id'] && h['label'] }.map {|h| h['id']}
# => [0, 46]

A more cleaned up version could look like this
def ids_with_label(json_str)
  hash = JSON.parse(json_str)
  items = hash['menu']['items']
  items_with_label = items.select { |h| h && h.include?('id') && h.include?('label') }
  ids = items_with_label.map { |h| h['id'] }
  ids
end

ids_with_label(your_json_string) # => [0, 46]

A: I do not know if this is what you want exactly:
items = my_parse['menu']['items'].compact.select { |item| item.has_key?('label') }.map{ |item| item['id'] }

A: There's no need to create a temporary array:
my_parse['menu']['items'].each_with_object([]) { |o,a|
  a << o['id'] if o && o.key?('id') && o.key?('label') }
  #=> [0, 46]


text:
Q: can't access global variables inside a usort function? I'm trying to do a usort in PHP, but I can't access global variables inside a usort function.
I've simplified my code down to bare bones to show what I mean:
$testglobal = 1;
function cmp($a, $b) {
    global $testglobal;
    echo 'hi' . $testglobal;
}
usort($topics, "cmp");

Assuming the usort runs twice, my expectations is this will be the output:
hi1hi1

Instead, my output is:
hihi

I've read the manual (http://us.php.net/usort) and I don't see any limitations on accessing global variables. If I assign the usort to a variable that I echo, it outputs 1, so the usort is definitely running successfully (plus, there are all those "hi's").
Am I doing something incredibly stupid here? If not, is there a workaround?

A: Can't reproduce the "error" and neither can codepad: http://codepad.org/5kwctnDP
You could also use object properties instead of global variables
<?php
class Foo {
    protected $test = 1;
    public function bar($a, $b) {
        echo 'hi' . $this->test;
        return strcmp($a, $b);
    }
}

$topics = array(1,2,3);
$foo = new Foo;
usort($topics, array($foo, 'bar'));

A: The code I put in my question was dropped inside a template on bbPress, which is the forum cousin to Wordpress. A friend told me that "Sometimes PHP will act weird if you don't global a variable before you define it, depending on how nested the code is when it's executed - bbPress does some complex includes by the time the template outputs".
So I tried that and it works:
global $hi123;
$hi123 = ' working ';

I'm answering my own question in case another idiot like me finds this in a Google search. :-)
I'm going to accept VolkerK's answer, though, because the object workaround is pretty clever.

A: Does it work if you access the variable using the super-global $GLOBALS array?
$testglobal = 1;
function cmp($a, $b) {
    echo 'hi' . $GLOBALS['testglobal'];
}
usort($topics, "cmp");

A: It is working as of php 5.2.4
$testglobal = ' WORKING ';
$topics = array('a','b','c');
function cmp($a, $b) {
    global $testglobal;
    echo 'hi' . $testglobal;
}
usort($topics, "cmp");
// hi WORKING hi WORKING


text:
Q: Error term for backward differentiation formula I am trying to derive the error term for the backward differentiation formula $f'(x) \approx \frac{3f(x)-4f(x-h)+f(x-2h)}{2h}$.
By Taylor expansion
$f(x-h)=f(x)-hf'(x)+\frac{h^2}{2}f''(x)-\frac{h^3}{6}f^3(\xi_a)$,
$f(x-h)=f(x)-2hf'(x)+2h^2f''(x)-\frac{4h^3}{3}f^3(\xi_b)$.
So in forming the linear combination I get $\frac{3f(x)-4f(x-h)+f(x-2h)}{2h}=f'(x)+\frac{h^2}{3}f^3(\xi_a)-\frac{2h^2}{3}f^3(\xi_b)\leq f'(x)+\frac{2h^2}{3}|f^3(\xi)|$, where $|f^3(x_0)|\leq|f^3(\xi)|$ for all $x_0\in(x,x-2h)$.
So $\frac{2h^2}{3}|f^3(\xi)|$ is the error bound. But the notes I am following, which uses an identical method, ends up with $\frac{16}{3}$ as the coefficient for $h^2$ in the error formula (i.e. $\frac{16h^2}{3}|f^3(\xi)|$ is the error bound). Where am I going wrong?

A: The expected error is second order, so consider and treat with the extended mean value theorem
\begin{align}
&\frac{3f(x)-4f(x-h)+f(x-2h)-2hf'(x)}{2h^3}
\\[.5em]
&=\frac{4f'(x-h_1)-2f'(x-2h_1)-2f'(x)}{6h_1^2}
\\[.5em]
&=\frac{-4f''(x-h_2)+4f''(x-2h_2)}{12h_2}
\\[.5em]
&=-\frac{f'''(x-h_3)}3
\end{align}
where $0<h_2<h_1<h$ and $h_3\in[h_2,2h_2]$, so that finally
$$
\frac{3f(x)-4f(x-h)+f(x-2h)}{2h}=f'(x)-\frac{h^2}3f'''(\xi), ~~ \xi\in[x-2h,x]
$$
This means that the error term is even smaller than the one that you derived.


text:
Q: How close Bootstrap datepicker when it is in viewMode: year? I need to close datepicker when user finally select full date. This mean that user first select year, then month and after that date, but after last action datepicker remain open. How can I make this close on last user action?
I'm not sure is any code needed here.

A: Something like this will probably work:
$('yourpickerid').on('changeDate', function(ev){
    $(this).datepicker('hide');
});

Update:
Try these 2 different options:
$('#dp2').on('changeDate', function (ev) {
   //close when viewMode='0' (days)
   if(ev.viewMode === 'days'){
      $('#dp2').datepicker('hide');
   }
})

or
$("#date").datepicker({
    autoclose: true
});


text:
Q: spring JPA java.sql.Date is accepting invalid Dates I am writing rest apis for my project to create, retrieve and modify values to my database.
The model has an sql.Date field which while doing POST request if I give date as for example 2018-01-35(yyyy-MM-dd), it is auto converting to 2018-02-04.
I want to avoid this so that it can tell me that the given date is invalid.
I searched in SO and tried this approach,
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dob;

but this did nothing, so then I tried another method
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")

but this only checks for format like if i give value as just "1993", it gives error but does not check for "1993-01-35".
I also tried,
public static boolean dateChecker(Date date){
    Calendar calendar = Calendar.getInstance();
    calendar.setLenient(false);
    calendar.setTime(date);
    try{
        calendar.getTime();
    }catch(Exception e)
    {
        System.out.println(e.getMessage());
        return false;
    }
    return true;
}

But when I debug it, this method is already getting "1993-01-35" as "1993-02-04".
The model is,
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date dob;

This is my POST method,
@RequestMapping(value = "/patient",method = RequestMethod.POST,consumes = "application/json")
public ResponseEntity<?> createPatient(@RequestBody Patient patient)
{
    if(patient.getPatientId()!=null)
    {
        Patient patient1 = patientRepository.findOne(patient.getPatientId());
        if(patient1!=null)
        {
            return new ResponseEntity("Patient for the given patient Id already exists.",HttpStatus.BAD_REQUEST);
        }
    }

    System.out.println(patient.getDob());//Here I am getting 1993-02-04 when i give date as 1993-01-35

Please help me solve this.

A: Try util.date package for date.

A: You could try doing something like this if the calendar.setLenient isn't working for you.
I just added some random number for the day for testing.
int day = 21;
    Calendar gmtCal =
            Calendar.getInstance(TimeZone.getTimeZone("GMT"));

    gmtCal.set(Calendar.MONTH, Calendar.JANUARY);

    if(day <= gmtCal.getActualMaximum(Calendar.DAY_OF_MONTH)){
        gmtCal.set(1993, Calendar.JANUARY, day );
        System.out.println(gmtCal.get(Calendar.YEAR));
        System.out.println(gmtCal.get(Calendar.MONTH));
        System.out.println(gmtCal.get(Calendar.DAY_OF_MONTH));

        System.out.println(gmtCal.getTime());
    }
    else{
        System.out.println("Out of bounds");
    }

The First thing you would have to do is to set the month for the calendar and then do a test on the day that was entered.  If it passes then then you can set the whole date and if not print out an error.
Note:  when using Calendar.get, the year and day will be printed out correctly. However, the month will start at zero.  So in this example the dot gets print out:
1993 (year)
0 (month)
21 (day).
Also the the sysout for getTime() will print out some extra information that you might not need.
I used this post as a reference, it might give you some extra help: Detect invalid date on Calendar.set()
I hope this helps you. Let me know if this needs tweeking


text:
Q: 419 Sorry, your session has expired. Please refresh and try again.This error appears when i submit the form I got this error even when I give {{ csrf_field() }} during form submission.
What could be the issue?
<form action="{{ route('e-account-post') }}" method="POST" id="e-account" enctype="multipart/form-data">
    {{ csrf_field() }}

Full Name *

            <input type="text" class="form-control" name="full_name" value="" placeholder="Full Name">

            <button class="btn credit-btn mt-30" type="submit">Send</button>

</form>

below is route
Route::post('/e-account','FrontController@e_account_action')->name('e-account-post');

below is controller
public function e_account_action(Request $request)
{
   dd($request->all());
}

Laravel 5.7 and the project is live.
There is no problem in local. I setup the project in live mode through GitLab.


text:
Q: need help, im very new. simple scan and print problem how can i make a simple program that prints a phrase whenever the user inputs a word. i cant seem to make what i wrote down to work. Im very new, thanks.
#include <stdio.h>
#include <stdlib.h>

int main ()
{
    char direction[20];

    printf ("where did he go? choose one option.\n");
    printf ("station, plaza, bathrooms\n");
    scanf ("%s", direction);

    printf ("%s", direction);

    if (direction == "plaza"){
        printf ("its going to be hard to find him now..");
    } else if (direction == "bathrooms"){
        printf ("lets go rush him right now!!!");
    } else if (direction == "car"){
        printf ("he must've escaped into the city!");
    }
    return (0);
}


text:
Q: Connection Timeout EC2 Java Web App to RDS mySQL Database I am a beginner at AWS. So far I managed to set up a mySQL database in RDS and a EC2 Java Web Application. I am using the eclipse plugin to deploy the web application. I can connect to the Java Web Application through http requests from the browser. Additionally, I can connect to the mySQL database from the command line terminal.
However, whenever I try to connect to the mySQL database from code in the java web application my request times out. I am confident my URL is correct to make the connection in code. And I am just using these lines for the connection. Something I have done numerous times successfully on localhost.
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url);

I have read a lot of information about security groups, but in my RDS management console it says:
"Your account does not support the EC2-Classic Platform in this region. DB Security Groups are only needed when the EC2-Classic Platform is supported. Instead, use VPC Security Groups to control access to your DB Instances."
Does anyone have any suggestions? Thanks in advance!

A: You have a newer AWS account that only has VPC enabled, not EC2 classic. Access to all your RDS DB instances as well as your EC2 instances will be through VPC security groups.
First check what security group your EC2 instance running the Java web app is in, and do the same for your RDS instance. Then go to the VPC console and look at those security groups. You need to ensure that the EC2 instance can access the RDS instance on port 3306. The best way is to put the EC2 instance in a group, the RDS in another group, then allow access to RDS from the entire group by group ID.


text:
Q: Migrating asp.net membership to Windows Azure I am migrating my asp.net mvc-3 project to windows azure. I have to migrate asp.net membership to windows azure. I read this article. From this artical what i understand is the following points to migrate membership :
1) Migrating membership means just changing the data store where user related information is stored. Means in my case i am using SQL server express 2008 as an on-premises data store. And i just have to chnage it to SQL azure data center.
2) I downloaded ASP.NET Universal provider through Nuget. This will automatically extend the membership support to SQL azure. Means i just have to change the connection string in the web.config file.In that connection string it requires server-name and database. For this i have to create an account in the windows azure. Where i can create the database. And from there i can get the ready made connection string which i have to just paste in my web.config file.
And i want to know the next steps after doing all this.
I Just want to know whether i am on the correct direction or not. If is there anything i am missing or i am not on the right path then please guide to the correct direction ? Thanks

A: using the ASP.NET Universal Provider is the way to go. For the migration part, I suggest you simply use the generate script functionality of SQL Server (right click your database, choose Tasks, choose Generate Scripts).
In the export wizard you can choose to export to SQL Azure and that the script should include the schema and the data. This will make it very easy for you to move your current on-premises database to SQL Azure.

A: In addition to the Sandrino's answer, I wil just add a suggestion to use  the SQL Azure Migration Wizard, as it is much better than the ingrated in SSMS functionality. Just a simple exmaple is that SQL Azure Migration Wizard will automatically create Clustered Indexes for tables which do not have such. Another thing is that the Migration wizard will give you detailed explanation for any non SQL Azure compatible definition/data/statement, while the itegrated "Generate Scripts" will just throw "it is not compatible"..

A: First off, if it works @astaykov's suggesting of SQL Azure Migration Wizard should be your first step. It will tell you what parts of your database are not compatible with SQL Azure. SSMS will generate an insert statement for each row that needs to be migrated. The Migration Wizard will use BCP which is way more efficient.
I had to migrate a Membership database for a client about a year ago. The problem that I ran into was that no automatic migration would work since the database generated by aspnet_regsql.exe contained elements that were not compatible with SQL Azure. There is a new version aspnet_regsqlazure.exe which creates tables with the same schema, but the supporting stored procedures are SQL Azure compatible. Once the matching schema is created, you can move the table contents by whatever means you like SSMS, Migration Wizard, or BCP.
Again, make sure to try astaykov's suggestion first. If the membership database generated has changed recently, it will be much easier that what I had to do.


text:
Q: #SNMP using a custom OID Is it possible to use a custom OID in the library #SNMP (http://sharpsnmplib.codeplex.com/)?
If so, how can a custom OID variable/subtree be added/registered with #SNMP so it is possible to read and write to those variables?
I would like to extend/configure the agent deamon (snmpd) so it can read custom OIDs like
iso.org.dod.internet.private.enterprise.XXX (1.3.6.1.4.1.XXX)
For testing purposes let's say a "fake" OID will be used (something like 1.3.6.1.4.1.99999.0).
What would be necessary to do in the #SNMP snmpd example agent so the program can read the values (snmpget, snmpgetnext...) of that OID?
According to the  #SNMP Documentation (Documentation->Agent Development) when a handler tries to do a typical SNMP operation, it looks into the ObjectStore object to locate the specified object.
So in order to use a custom OID does it need to be added to the ObjectStore?
Is this the example of how to add an OID https://sharpsnmplib.codeplex.com/SourceControl/latest#SharpSnmpLib/Objects?

A: If you see into snmpd sample, you can see the ObjectStore is initialized in Program.Main for simplicity,
https://github.com/lextm/sharpsnmplib/blob/master/snmpd/Program.cs
If you follow the convention to insert your custom objects, you get what you want.


text:
Q: 'vagrant ssh' not working with the vagrant-multi-putty plugin I am trying to run VirtualBox with Vagrant and the plugin vagrant-multi-putty. I am running Windows 10 and am following this guide. All the plugins and steps seem to work fine until I get to the "vagrant ssh" step. I get this error:

I did some googling and the recommended solution is usually to set the path correctly to putty.exe. You can do that like so:
set PATH=%PATH%;C:\Program Files (x86)\PuTTY

Even though the plugin seems to be installing right I can't find the putty.exe file anywhere on my system. I tried downloading the binaries from here and manually adding them to C:\Program Files (x86)\PuTTY. Then I set the path like the example above. However, I am still getting the same error when I run "vagrant ssh".

A: Made the same misstake myself at first.
According to the installation instructions for https://github.com/nickryand/vagrant-multi-putty you are supposed to use:
vagrant putty

instead of "vagrant ssh"


text:
Q: reorder linked list without creating a new one community! My problem is that I must order a linked list in such a way that a new one is not created, but the same one is returned. For example, if I have:
Head --> [8] --> [15] --> [1] should I return Head --> [1] --> [8] --> [15]
My code right now, probably my code is awful and incorrect, but I'm new and I couldn't find the answer. Thanks for your time!
LinkedList.prototype.orderList = function() {
  //temporary node to swap the element
  let current = this.head;

  if (LinkedList.value === null) return "Empty";
  if (LinkedList.next.value === null) return "Orderer list"

  while (this.head.next.value !== null) {
    for (let i; i < LinkedList.length; i++)
      if (LinkedList.head.value > LinkedList.head.next.value) {
        current = LinkedList.head;
      } else if (linkedList.LinkedList.head.next.value)
      current = linkedList.head;
  }
};

A: I did the classic simple sort (or bubble Sort). The one where i goes to n - 1 and j goes from i + 1 to n. It worked.

function Node(value) {
  this.value = value || null;
  this.next = null;
}

function print(list) {
  var head = list;
  var arr = [];
  while (head) {
    arr.push(head.value);
    head = head.next;
  }
  console.log("" + arr)
}
var list = new Node(3);
list.next = new Node(9);
list.next.next = new Node(6);
list.next.next.next = new Node(2);

function sort(list) {
  if (!list || !list.next) {
    return;
  }

  for (var i = list; i.next != null; i = i.next) {

    for (var j = i.next; j != null; j = j.next) {
      if (i.value > j.value) {
        var temp = i.value
        i.value = j.value
        j.value = temp;
      }
    }
  }
}

print(list)
sort(list)
print(list)


text:
Q: JSON object is getting corrupted I am using a JSON object on a project I am working on. I am doing many updates to this JSON file as it is my primary file to work with. I am using nodejs to handle requests and processes my file.
My JSON data looks something like this:
[
   { field1:123,
    field2:"Test",
    field3:"New",
    field4:"City",
   },
   { field1:"123",
    field2:"Test2",
    field3:"FILE to use",
    field4:"Assignment Token",
   }
]

Throughout its life cycle my files gets corrupted and a it show a similar pattern every time it gets corrupted. I tried to reduce as many number of call it is possible. The pattern it shows is as follows. Any ideas how to avoid this?
[
   { field1:123,
    field2:"Test",
    field3:"New",
    field4:"City",
   },
   { field1:"123",
    field2:"Test2",
    field3:"FILE to use",
    field4:"Assignment Token",
   }
]o use",field4:"Assignment Token",}]

The basic pattern I am using to update the file is as such:
app.post('/send-to-waitlist', function(req, res){
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    var reqData = req.body;
    console.log(reqData);
    var cpso = reqData.CPSO;
    try{
      var rawData2 = fs.readFileSync('filepath',{encoding: 'utf8'})
      var data2 = JSON.parse(rawData2);
      var eid = reqData.id;;
      for(let d of data2){
       if(d.eid==eid){
        d.SpecialType="Waiting";
        break;
      }
    }
   fs.writeFileSync('filepath', JSON.stringify(data2));

   res.json({Message: "Data moved Successfully."});
 }catch(e){
        console.log(e);
        res.json({error:e});
    }
})


text:
Q: How to get Child Variable Value in Parent JSP I am defining one variable in Parent JSP and accessing tag file from that jsp where the same variable is changing based on some conditions.
Here is my code ..
Parent JSP :
<c:set var="replaceParams" value=":${attribute.name}:${value.name}" />
<c:set var="removeURL" value="${fn:replace(queryParams, replaceParams, '')}" /> <!-- Suppose value is A -->
<%@ taglib prefix="cms2" tagdir="/WEB-INF/tags/spine/surgery"%>
<c:forEach items="${attributeDTOList}" var="attribute" varStatus="status">
   <cms2:attributeSubFeatureRemove attribute="${attribute}" />
</c:forEach>
<!-- Print removeURL showing "A". It has to show "AB" -->

attributeSubFeatureRemove.tag--
   <%@ attribute name="attribute" required="true" type="com.medtronic.b2b.core.dto.HCCB2BClassificationAttributeDTO" %>
   <%@ attribute name="removeURL" required="true" type="java.lang.String" %>
   <c:forEach items="${attribute.subFeatures}" var="subAttribute">
        <c:forEach items="${subAttribute.attributeValues}" var="subValue">
           <c:if test="${ subValue.preSelectionRequired}">
             <c:set var="replaceParams" value=":${subAttribute.name}:${subValue.name}" />
             <c:set var="removeURL" value="${fn:replace(removeURL, replaceParams, '')}" />
          </c:if>
        </c:forEach>
     </c:forEach>
     <!-- Now Suppose removeURL value changed to AB-->

In the above code Parent JSP is having variable removeURL which is of String Type. I am sending this removeURL variable inside tag file. Tag file will change the same removeURL variable to hold updated String.
Now If I will try to get removeURL in Parent JSP, it is print the same value as before in parent jsp. Updated calculation value (in tag file) is not reflecting in parent JSP.
I am confuse with scope whether it will make removeURL variable consistent or not. Please help me to get updated value in Parent JSP as well.

A: Please see my response to your other question here:  How to pass Object using jsp:include param tag into another jsp
I think that will make your life much easier and render this question no longer relevant.   If you agree that the other technique is better, I would close this question.

A: You can specify the scope of a variable by using the scope attribute
`<c:set var="removeURL" value="${fn:replace(queryParams, replaceParams, '')}" scope="request" />`

You can also use page, session or application


text:
Q: Reconstructibility of topological spaces Let $(X,\tau), (Y,\sigma)$ be topological spaces with $|X|$ infinite and suppose $\varphi:X\to Y$ is a bijection such that for all $x\in X$ we have that $(X\setminus\{x\}) \cong (Y\setminus\{\varphi(x)\})$.
Does this imply that $(X,\tau) \cong (Y,\sigma)$?

A: Edit. As pointed out by anonymous, the following argument assumes that the homeomorphisms $X\setminus\{x\}\cong Y\setminus\{\varphi(x)\}$ are all induced by $\varphi$. I will leave it for a while and maybe delete it later.
Recall that a subset $A\subset X\setminus\{x\}$ is open in the subspace topology if and only if there exists an open $V\subset X$ such that $A=V\cap(X\setminus\{x\})$. The subsets $V\subset X$ with $A=V\cap(X\setminus\{x\})$ are $A$ and $A\cup\{x\}$.
Consider $U\subset X$. If $U$ is open in $X$, then $U\setminus\{x\}$ is open in $X\setminus\{x\}$ for all $x\in X$.
On the other hand, let $U\setminus\{x\}$ be open in $X\setminus\{x\}$ for all $x\in X$. Assume that $U$ is not open in $X$, then $U\setminus\{x\}$ must be open in $X$ for all $x\in U$, and $U\cup\{y\}$ must be open in $X$ for all $y\notin U$.
Assume $X$ has at least three distinct elements. Then there are two cases.
If $U$ has at least two elements $x_1\ne x_2$ then $U\setminus\{x_i\}$ must be open in $X$, so $U=(U\setminus\{x_1\})\cup(U\setminus\{x_2\})$ is open, too.
If $X\setminus U$ has at least two elements $y_1\ne y_2$ then $U\cup\{y_1\}$ and $U\cup\{y_2\}$ must be open in $X$, so $U=(U\cup\{y_1\})\cap(U\cup\{y_2\})$ is open, too.

A: The answer is ``No''. Let $X$ be the Cantor set and let $Y = X \setminus \{p\}$, where $p$ is any element of $X$. Let $\varphi \colon X \to Y$ be any bijection. Since the Cantor set with one point removed is homeomorphic to the Cantor set with two points removed, the given condition is satisfied.  However, $X$ is compact whereas $Y$ is not.
Edit: In response to the question by Loïc Teyssier, there are many ways to see that the assertion is true.  One simple way is to note that if two points are removed from the Cantor set, the one-point compactification of the resulting space is compact, metrizable, zero-dimensional, and has no isolated points, and is, therefore, homeomorphic to the Cantor set.  Hence, when the point at infinity is removed, the resulting space is homeomorphic to the Cantor set with a single point removed, but it is also the Cantor set with two points removed.


text:
Q: Overwrite Filename of Image in Python I'm using Python and I have the following snippet of code:
>>> from PIL import Image
>>> from PIL import ImageFont
>>> from PIL import ImageDraw
>>> img = Image.open("sample_in.jpg")
>>> draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
>>> font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
>>> draw.text((0, 0),"Sample Text",(255,255,255),font=font)
>>> img.save('sample_in.jpg')

source: Add Text on Image using PIL
The problem I am having is I can't rename the file the same as the original is there a way to accomplish this?
Traceback:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1433, in save
    fp = __builtin__.open(fp, "wb")
IOError: [Errno 13] Permission denied: 'sample_in.jpg'


text:
Q: How to parse JSON string in php I'm getting below JSON response:
[{"startDate":"2012-07-12 11:21:38 +0530","totalTime":0},{"startDate":"2012-07-11 11:27:33 +0530","totalTime":0},{"startDate":"2012-07-16 18:38:37 +0530","totalTime":0},{"startDate":"2012-07-17 14:18:32 +0530","totalTime":0}]

i want make array of start date and totalTime, i have used these two lines but it wont work $obj, please suggest..
                    $obj  = json_decode($dateTimeArr);
        $dateAr = $obj->{'startDate'};

A: It is very easy:
$Arr = json_decode($JSON, true);

A: As everyone said, and you did - use json_decode.
    $dateArrays  = json_decode($dateTimeArr, true); // decode JSON to associative array
    foreach($dateArrays as $dateArr){
        echo $dateArr['startDate'];
        echo $dateArr['totalTime'];
    }

In future, if you are unsure what type or structure of data is in the variable, do var_dump($var) and it will print type of variable and its content.

A: json_decode() will give you nested PHP types you can then descend to retrieve your data.

A: use json_decode($json_response,true) to convert json to Array

A: Guess what you are looking for is json_decode()
Check out http://php.net/manual/en/function.json-decode.php for the inner workings


text:
Q: JavaScript sum all of the values in each object in an array? I have an array with 2 objects.
var sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}];
How can I sum the value in each object using just reduce/map/filter/forEach function?
The output should be [10, 14]

A: You could map the objects and the values by iterating the keys of ths object and add the value of all properties.
Methods used:

*

*Array#map for returning a result for every item

*Object.keys for getting all own properties of an object

*Array#reduce for summing up the values

var data = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 2, b: 3, c: 4, d: 5 }],
    sum = data.map(function (object) {
        return Object.keys(object).reduce(function (sum, key) {
            return sum + object[key];
        }, 0);
    });

console.log(sum);

Sum without key 'a'

var data = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 2, b: 3, c: 4, d: 5 }],
    sum = data.map(function (object) {
        return Object.keys(object).reduce(function (sum, key) {
            return sum + (key !== 'a' && object[key]);
        }, 0);
    });

console.log(sum);

A: Short solution using Array.prototype.reduce() function:

var sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}],
    result = sum.reduce(function (r, o) {
        r.push(Object.keys(o).reduce(function(r, b){ return r + o[b]; }, 0));
        return r;
    }, []);

console.log(result);

A: In the following code, o is each object in the array, t is the accumulating total sum, p is the property of the object being added.

const sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}];

const result = sum.map(o => Object.keys(o).reduce((t, p) => t + o[p], 0));

console.log(result);

A: es6 for of version:
let sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}];

let result = [], objSum;
for (let item of sum) {
    objSum = 0;
    for (let property in item) {
        if (item.hasOwnProperty(property)) {
            objSum += item[property];
        }
    }

    result.push(objSum);
}
console.log(result);//[10, 14]

A: You may do as follows in pure JS in 2017.

var sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}],
   sums = sum.map(a => Object.values(a).reduce((p,c) => p+c));
console.log(sums);

A: Or you can use a utility library like Lodash.
var _ = require('lodash');

var sum = [{a:1, b:2, c:3, d:4},{a:2, b:3, c:4, d:5}];
var result = _.map(sum, function(obj) {
      return _.reduce(_.values(obj), function(sum, n) {
          return sum + n;
      }, 0);
});
console.log(result);


text:
Q: Django post_save hook causing an error for syncdb I have a custom model with a OneToOne relationship with the User (django.contrib.auth.models.User) model;
class Profile(models.Model):
    user = models.OneToOneField(User)

And I want to create a new Profile every time a User is created. So I've added a signal;
@receiver(post_save, sender=User)
def _setup_user(sender, **kwargs):
    """
    Create a new profile instance for each user
    """
    created = kwargs.get('created', False)
    user = kwargs.get('instance', False)
    if created and user:
        profile = Profile(user=kwargs['instance'])
        profile.save()

All this is fine, however syncdb throws an error when creating the admin user because the Profile table has not been created yet (I'm using South to manage migrations).
How can I get around this?
EDIT
So, omitting creating a superuser worked;
$ ./manage.py syncdb --noinput
$ ./manage.py migrate
$ ./manage.py createsuperuser

A: Run syncdb first and decline making a superuser. Then after creating the db run manage.py createsuperuser
Here's the docs for 1.6
If you have anymore trouble let me know, but if the only issue is that the db isn't created first, then this should work.
Hope it helps
Cheers

A: You can try something like this:
from django.db import DatabaseError, transaction

@receiver(post_save, sender=User)
@transaction.commit_manually
def _setup_user(sender, **kwargs):
    """
    Create a new profile instance for each user
    """
    created = kwargs.get('created', False)
    user = kwargs.get('instance', False)
    if created and user:
        try:
            profile = Profile(user=kwargs['instance'])
            profile.save()
        except DatabaseError:
            transaction.rollback()
        else:
            transaction.commit()

Depending on your database backend you might not need the manual transaction management, but for psycopg2 it's necessary otherwise you get a "current transaction is aborted" error.
If you take this approach then you'll need to create a profile for the superuser manually after running syncdb, so in that specific case I think that TheSpurg's answer is simpler. It still worth knowing how to recover from a DataBaseError though, so I'm going to post this answer anyway.


text:
Q: Internal users can't receive email sent by application We have an application server that hosts a CRM application.  It is using SMTP on it's own server to send emails.  If I send an email using the application to me@MyPersonalDomain.com, it shows up in my inbox.  If I send an email to AnyAddress@MyCompanyDomain.com, it never shows up. It doesn't matter what address I put in for @MyCompanyDomain.com, they never get through.  Any email addresses outside our domain/firewall get through.
We're using Exchange 2007 and when I look at the message tracking logs, the missing messages don't show up there, either.
Is there something I need to configure in Exchange or the SMTP server on the application server?  I can't figure out why emails get outside the firewall but internal emails never show up.
Thanks,
Jeff

A: Sounds like a dns issue.  What is the ip address that nslookup gives you when you do an mx lookup for your domain.
My guess is the ip address that comes back is the public ip and not the private ip.  Your firewall probably isn't allowing the connection to come back in.

A: See if this is possible:

*

*Your application server is configured in the domain MyCompanyDomain.com

*When it sends an email to @MyCompanyDomain.com, it sends email to self and ultimately the email double bounces and is lost.

*This problem does not come it for other domains because the emails are delivered to outside.

If this is the case, you can just change the FQDN configured with the Application server to some other dummy domain.


text:
Q: I added a new column with spring boot jpa table. However while saving the entity i get a roll back error Initial class
@Entity
@Table
class User
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id

private Long pid

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at", nullable = false, updatable = false)
@CreationTimestamp
@JsonIgnore
private Date createdAt;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at", nullable = false, updatable = true)
@UpdateTimestamp
@JsonIgnore
private Date updatedAt;

Added: This column was added, now when I try to save the entity by setting this column it gives the following error!!!!!!
private Long aid
application.properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
This the the complete stacktrace
JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:543)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:631)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:385)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy170.save(Unknown Source)
    at com.avtaar.modules.auth.service.UserService.save(UserService.java:25)
    at com.avtaar.modules.auth.service.UserService$$FastClassBySpringCGLIB$$8c4517e0.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
    at org.springframework.cache.interceptor.CacheInterceptor.lambda$invoke$0(CacheInterceptor.java:53)
    at org.springframework.cache.interceptor.CacheAspectSupport.invokeOperation(CacheAspectSupport.java:365)
    at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:420)
    at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:345)
    at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
    at com.avtaar.modules.auth.service.UserService$$EnhancerBySpringCGLIB$$98cbd970.save(<generated>)
    at com.avtaar.modules.auth.controller.UserController.setUserAvatar(UserController.java:135)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: javax.persistence.RollbackException: Error while committing the transaction
    at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:81)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534)
    ... 84 more
Caused by: javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:177)
    at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:68)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:73)
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:127)
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:120)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:552)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:515)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:485)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:447)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:397)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:173)
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:116)
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreUpdate(BeanValidationEventListener.java:88)
    at org.hibernate.action.internal.EntityUpdateAction.preUpdate(EntityUpdateAction.java:304)
    at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:174)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
    at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1352)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:443)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3202)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
    ... 85 more
Caused by: java.lang.UnsupportedOperationException
    at java.sql/java.sql.Date.toInstant(Date.java:316)
    at org.hibernate.validator.internal.constraintvalidators.bv.time.past.PastValidatorForDate.getInstant(PastValidatorForDate.java:23)
    at org.hibernate.validator.internal.constraintvalidators.bv.time.past.PastValidatorForDate.getInstant(PastValidatorForDate.java:19)
    at org.hibernate.validator.internal.constraintvalidators.bv.time.AbstractInstantBasedTimeValidator.isValid(AbstractInstantBasedTimeValidator.java:55)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:171)
    ... 115 more


text:
Q: Replace many "else if" with something else I am using an ActionListener and have lots of else if statements in order to know which button is pressed and run some code depending on the button.
Is there a way to make the code nicer? I have nearly 10 else if statements following each other, is there something else I could use instead?
Sample of code:
class BtnListener implements ActionListener {
            @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == menu.getOpen()) {
                getFile();
            } else if (e.getSource() == btnPlay) {

            } else if (e.getSource() == btnQuit)) {
         }
}

Thanks.

A: You may use the action command of the button, and a switch-case block :
public void actionPerformed(ActionEvent e){

switch(e.getActionCommand()) {
    case "Open":
          open();
          break;
    case "Delete":
          delete();
          break;
    default :
          break;

    }
}

Of course you will have to set the action command of each button first, like :
openButton.setActionCommand("Open");

Note that switch-case with String objects only exists since JDK 7 : Strings in switch Statements

A: You can fill Map<Object, Consumer<ActionEvent>> before using of listener, for example in constructor, where key is source and value is  a consumer for action event. In action perform just get consumer by key and invoke it.
class BtnListener implements ActionListener {
    Map<Object, Consumer<ActionEvent>> eventsMap = new HashMap<>();

    public BtnListener() {
        eventsMap.put(menu.getOpen(), actionEvent -> this.getFile());
        eventsMap.put(btnPlay, actionEvent -> { //do something
        });
        eventsMap.put(btnQuit, actionEvent -> { //do something else
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Optional.of(e)
                .map(ActionEvent::getSource)
                .map(eventsMap::get)
                .ifPresent(
                        actionEventConsumer -> actionEventConsumer.accept(e)
                );
    }
}

A: You can switch statement instead lot of else if ladder.
class BtnListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == menu.getOpen()) {
            getFile();
        }

        switch( e.getSource() ){

            case btnPlay:

            break;
            case btnQuit:

            break;

            default:
        }
    }
}

A: the best way to avoid all the "overheads" is to Lambda-Expressioned the buttons. Example:
JButton b1 = new JButton("Play");
b1.addActionListener(e -> play());
...
JButton bn = new JButton("Stop");
bn.addActionListener(e -> stop());
...
private void play() {
   ....// playing codes
}
...
private void stop() {
   ...// stopping codes
}
...


text:
Q: Checking data "exists" in array? I have an small array of data which i want to check if my values im checking against exist in the array together.
This is how the data looks like from my console.log(astar);
http://i.imgur.com/PqzG7.jpg
My attempt was:
 console.log(astar); // display array info
     for (i=0; i < 50; i++){
        for (j=0; j < 50; j++){
        if( i in astar && j in astar[i] ){
               abposx = getx(i);
               abposy = gety(j);
        ctx.fillStyle = "#000";
        ctx.fillRect (abposx,abposy,10,10);
    }

The idea is the "inner arrays" which have [0][1] positions im trying to see if "any" of them have [0] == i and [1] == j if so = true.
How should i alter it to work correctly & most efficiently - so that it will draw when it is found in the arrays

A: What you are currently doing is equivalent to
for (i=0; i < astar.length; i++)
    for (j=0; j < astar[i].length; j++) {
        abposx = getx(i);
        abposy = gety(j);
        ctx.fillStyle = "#000";
        ctx.fillRect(abposx,abposy,10,10);
    }

You may want:
for (i=0; i < astar.length; i++) {
    if (astar[i][0] > 50 || astar[i][1] > 50)
        continue;
    abposx = getx(astar[i][0]);
    abposy = gety(astar[i][1]);
    ctx.fillStyle = "#000";
    ctx.fillRect(abposx,abposy,10,10);
}

Looping through all coordinates is very inefficient and would need a third loop for searching in astar. Better loop through astar and paint what you can get.
The correct three-loop code would have been:
for (i=0; i < 50; i++)
    for (j=0; j < 50; j++)
        if (astar.some(function(item) {
            return item[0] == i && item[1] == j;
        }) {
            abposx = getx(i);
            abposy = gety(j);
            ctx.fillStyle = "#000";
            ctx.fillRect(abposx,abposy,10,10);
        }

(The some() loops through the array and returns true if an item matches the condition function. It equals the extended version posted by bfavaretto). Resulting in a performance of O(n^2.5)...

A: It's not clear what you want to compare with the array values. What you have is an array containing other arrays, each one with only two items inside. You can loop it like this:
for(var i=0; i<astar.length; i++) {
    console.log("Array " + i + " contains values " + astar[i][0] + " and " + astar[i][1]);
}

UPDATE
I'm still not sure I get it, but you may be looking for this:
for (i=0; i < 50; i++){
    for (j=0; j < 50; j++){
         for(var k=0; k<astar.length; k++) {
              if(astar[k][0] == i && astar[k][1] == j) {
                    abposx = getx(i);
                    abposy = gety(j);
                    ctx.fillStyle = "#000";
                    ctx.fillRect (abposx,abposy,10,10);
                }
          }
     }
}


text:
Q: How to set a string for Toast.makeToast(...) in android In my class MainActivity I created a string:
String s = "Mystring";

And I want to do something like below:
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();

Is it possible? If yes, how can I do it?

A: The documentation of Toast.makeText():
/**
 * Make a standard toast that just contains a text view.
 *
 * @param context The context to use. Usually your Application or Activity object.
 * @param text The text to show. Can be formatted text.
 * @param duration How long to display the message. Either LENGTH_SHORT or LENGTH_LONG.
 */
public static Toast makeText (Context context, CharSequence text, int duration){ ... }

Notice the use of makeTEXT, not makeTOAST.

You mentioned you're working in an AsyncTask. It is not possible to create toasts from a non-UI thread. Make sure you're displaying your Toast either in onPreExecute, in onPostExecute, or in onProgressUpdate.

A: Ya that should work, wht is the problem you getting actually?
Try below code:
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();

A: If you are using it inside an AsyncTask then write your code in onPostexecute() as you can't access it from doInBackground() since it's Non-UI thread.
Toast.makeText(YourActivityName.this, s, Toast.LENGTH_SHORT).show()

A: String s="haha";
Context context = getApplicationContext();
CharSequence text = s;
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration).show();

//you are correct. just use charSequence equal to the string. it should work. works for me.


text:
Q: Create a recently used list in java I have a task where i have to create a recently used list in java. I'm a bit lost and I do not really know where to start. Please help! This is the code I have been given to start with:
public class RecentlyUsedList {

    // Members (a.k.a. fields)
    private String[] theItems;
    private int noOfItems;

    // Constructor
    public RecentlyUsedList(int capacity) {
        // Create the array with indicated capacity
        // Initialize numberOfItems
    }

    // Public methods
    public int getNoOfItems() {

    }

    public boolean isEmpty() {
        // Is this list empty or not?
    }

    public String getItemAt(int index) {
        // If index is out of range, return null
        // Otherwise return a reference to the indicated item
    }

    public void addItem(String item) {
        // 1. Check if the list contains this item; if so, remove it and pack
        // 2. Check if the array needs resizing
        // 3. Add the item to the list. Increment noOfItems.
    }

    public void removeItem(String item) {
        // Check if the list contains this item; if so, remove it and call pack
        // NB! use equals to compare Strings, e.g. str1.equals(str2)
    }

    public String toString() {
        // Return a string of the form
        // [1st item; 2nd item; ...]
    }

    // Private (helper) methods
    private void pack(int index) {
        // In a loop, starting at "index", copy item at position+1 to position
        // (if the items are stored in "reverse order")
        // Decrement noOfItems.
    }

    private void resize() {
        // Create a new, temporary, reference and a corresponding String-array
        // Copy all item-references to the new array
        // Let the "theList" reference the new array (i.e. theItems = temp)
    }
}

Please does anyone have directions on how to start?

A: Giving you a head start by giving code for 3 methods. Rest you can attempt on your own.
 // Public methods
  public int getNoOfItems() {
    return noOfItems;

  }

  public String getItemAt(int index) {
    if (index >= noOfItems) {
      return null;
    } else {
      return theItems[index];
    }
  }

  public String toString() {
    StringBuilder builder = new StringBuilder("[");
    for (int i = 0; i < theItems.length; i++) {
      if (theItems[i] != null) {
        builder.append(theItems[i]).append(";");
      }
      builder.append("]");
      return builder.toString();
    }


text:
Q: Solution to this beta function integral-within-an-integral (Continued) Continuing on from my earlier post, here, I have re-evaluated all the work-up to the integral and managed to re-formulate everything to be slightly different. Now, the aim is to solve
$$
I = \int_0^\infty \frac{t^{\frac{3}{\alpha}-1}}{(1+t)^8}\left(\int_0^t
\frac{t'^{\frac{2}{\alpha}-1}}{(1+t')^8}dt'\right)d t.$$
Once again, we have the condition that $2 \leq \alpha \leq 4$, where $\alpha$ is real. I'm not sure if the same problem stands that the inside integral diverges if $\alpha < 1/2$, as in my previous question or if this has managed to help somehow as the exponent is different.
Thanks!
Edit:
This once again can be written out as the integral of a hypergeometric function,
$$
I = \frac{\alpha}{2}\int_0^\infty \frac{t^{\frac{5}{\alpha}-1}}{(1+t)^8}\space_2F_1(8,\frac{2}{\alpha};\frac{\alpha+2}{\alpha};-t) \space dt.
$$

A: If $\operatorname{Re}(a) > 0$ and $- 1 < \operatorname{Re}(b) < \min (\operatorname{Re}(c)+7,\operatorname{Re}(a) + \operatorname{Re}(c) - 1)$, then
\begin{align*}
& \int_0^{ + \infty } {\frac{{t^b }}{{(1 + t)^c }}{}_2F_1 \left( {8,a;a + 1; - t} \right)dt}  = \int_0^{ + \infty } {\frac{{t^b }}{{(1 + t)^{c + 8} }}{}_2F_1 \!\left( {8,1;a + 1;\frac{t}{{t + 1}}} \right)dt}
\\ & = \frac{{\Gamma (a + 1)}}{{7!}}\sum\limits_{n = 0}^\infty  {\frac{{\Gamma (8 + n)}}{{\Gamma (a + 1 + n)}}\int_0^{ + \infty } {\frac{{t^{b + n} }}{{(1 + t)^{c + 8 + n} }}dt} }
\\ & = \frac{{\Gamma (a + 1)\Gamma (c - b + 7)}}{{7!}}\sum\limits_{n = 0}^\infty  {\frac{{\Gamma (8 + n)\Gamma (b + 1 + n)}}{{\Gamma (a + 1 + n)\Gamma (c + 8 + n)}}}
\\ & = \frac{{\Gamma (b + 1)\Gamma (c - b + 7)}}{{\Gamma (8 + c)}}{}_3F_2 (1,8,b + 1;a + 1,c + 8;1).
\end{align*}
In your case $a=\frac{2}{\alpha}$, $b=\frac{5}{\alpha}-1$, $c=8$ and $2\leq\alpha\leq 4$ fulfill the conditions.


text:
Q: JavaScript - Storing objects with unique key ? I have an JavaScript object which is being pushed to a global object.
var storedElement = {
    element: currentElement,
    parentElement: parentElement,
    elementChild: currentChild
}

storedElement is being pushed to a global array called.
pastLocations = []
I'm essentially trying to keep a history of the locations an element has been to. To do this I'm wanting to store these properties into the global array. If the same element already exists and has the same parent in the global then I dont want to push, but if the parent is different then push.
Is there a way I can put a unique key with item so I quickly and effectively get access to this element in the object. At the moment I currently have several for each loops to get the data from the object but this inst a practical approach. As Ideally I want 1 function to push to the global and to retrieve an element.
If I was to provide a unique keys for each object, how would I would know what key it is based of just knowing the element ?

A: In Javascript, an array [...] stores sequential values, preserving their order, and provides fast access if you know the index.
An object or dictionary {...} stores values along with a key, without preserving their order, and provides fast access if you know the key.
If you only need to store elements with distinct 'parent', you can use an object, using the parent as key.  If you also need to browse them in order, your best bet is to use both an array and an object:
storedElements = []
storedByParent = {}

What you store in each depends on your application requirements. You may store a copy of the object:
newEl = {element: ..., parent: parentElement, ...}
storedElements.push(newEl)
storedByParent[parentElement] = newEl

Or you may store an index into the array:
storedElements.push(newEl)
storedByParent[parentElement] = storedElements.length - 1

Or you may store a simple boolean value, to just keep track of which parents you have seen:
storedElements.push(newEl)
storedByParent[parentElement] = true

This latter use of an object is usually known as 'set', because it's similar to the mathematical object: even if you call mySet[12] = true a hundred times, the set either contains the element 12, or it does not.


text:
Q: call a javascript function from within another function I am coding a chat program but i am stuck in this part.
var Controller=function conversation() {
this.createMessageNode=function(msg,sender,time,mid){
    var newMessage;
    if(sender==sessionStorage.getItem('userid')){
        newMessage="
"+msg+""+time+"
";
    }else{
        newMessage="
"+msg+""+time+"
";
    }
    sessionStorage.setItem('lastMessage',mid);
    $('.chat-messages').append(newMessage);
}

this.getMessages=function(){
    if(sessionStorage.getItem('lastMessage')==null){
        sessionStorage.setItem('lastMessage',0);
    }
    $.ajax({url:"getmessages.php",type:"POST",data:{last:sessionStorage.getItem('lastMessage'),cid:sessionStorage.getItem('conversationid')},success:function(result) {
        var messages=JSON.parse(result);
        for (var i = 0; i < messages.length; i++) {
            createMessageNode(messages[i].message,messages[i].sender,messages[i].time,messages[i].mid);
            var cont=document.getElementById('chat-messages');
            cont.scrollTop=cont.scrollHeight;
        };
    }});
}

}
now when i do this it shows an error
Uncaught ReferenceError: createMessageNode is not defined

now in the for loop "this" variable is referring to the ajax object. how can i call the createMessageNode function?

A: Your functions are bound to the this object. If it is a global object (top most parent scope) then you can reference the functions within this by this.yourfunction
You must study SCOPE properly to understand
http://www.w3schools.com/js/js_scope.asp

A: The issue is createMessageNode() is a method of the Controller object instance, so you need to refer to the instance when calling it. Without refering to the instance, the JavaScript engine is looking for the function in the current scope, then each higher scope all the way up to the global scope.
Typically you would use the this keyword to reference the instance, but in your case, the jQuery ajax call has changed the this context, so you can't directly use this.
A possible solution is, before the ajax call, store the this context:
var that = this;

Now, in the ajax success function:
that.createMessageNode(messages[i].message,messages[i].sender,messages[i].time,messages[i].mid);
^^ refer to the instance

A: It'd probably be better to write your code following better prototypical inheritance models, like so:
function Controller() {
    this.chatMessages = $('.chat-messages');
}

Controller.prototype.createMessageNode = function (msg, sender, time, mid) {
    var newMessage;
    if (sender == sessionStorage.getItem('userid')) {
        newMessage = "
" + msg + "" + time + "
";
    } else {
        newMessage = "
" + msg + "" + time + "
";
    }
    sessionStorage.setItem('lastMessage', mid);
    this.chatMessages.append(newMessage);
};

Controller.prototype.getMessages = function () {
    var _this = this;

    if (sessionStorage.getItem('lastMessage') === null) {
        sessionStorage.setItem('lastMessage', 0);
    }

    $.ajax({
        url: "getmessages.php",
        type: "POST",
        data: {
            last: sessionStorage.getItem('lastMessage'),
            cid: sessionStorage.getItem('conversationid')
        },
        success: function (result) {
            var messages = JSON.parse(result);
            for (var i = 0; i < messages.length; i++) {
                _this.createMessageNode(messages[i].message, messages[i].sender, messages[i].time, messages[i].mid);
            }
            var cont = $('#chat-messages');
            cont.scrollTop(cont.scrollHeight);
        }
    });
};

This solves the issue of the context by creating a true class, for example:
var conversation = new Controller();
conversation.getMessages();
conversation.createMessageNode('Hello, World!', 'JimmyBoh', new Date(), 8268124);

Also, whenever you have nested functions, it can help to store the desired context in a local variable, such as _this or that, etc. Here is a more simple example:
function outer() {
    // Temporarily store your desired context.
    var _this = this;

    // Make any call that executes with a different context.
    $.ajax({
        url: "getmessages.php",
        type: "GET",
        success: function inner(result) {
            _this.doSomething(result);
        }
    });
};

Lastly, there might be a time when you want to execute a method in a different context than the current. .call() and .apply() can be used to run a method with a specified context and arguments. For example:
function printThis() {
    console.log(this.toString());
    console.dir(arguments);
}

printThis.call('Hello, World!');
printThis.call('Call array:', [2, 4, 6, 8], 10);   // Keeps arguments as-is.
printThis.apply('Apply array:', [2, 4, 6, 8], 10); // Accepts an array of the arguments.

function Sum(startingValue) {
    this.value = startingValue || 0;
}

Sum.prototype.add = function (number) {
    this.value += number;
}

var realSum = new Sum(2);
var fakeSum = {
    value: 3
};

realSum.add(1);
Sum.prototype.add.call(fakeSum, 2);

console.log(fakeSum.value); // Prints '5'
console.log(realSum.value); // Prints '3'


text:
Q: Display images in ScrollView I want to display some images in a scroll view, but I am facing some issues.
Here is what I have:
- (void)viewDidLoad
{
    [super viewDidLoad];

    myObject = [[NSMutableArray alloc] init];

    [myObject addObject:@"tut_5.jpg"];
    [myObject addObject:@"tut_2.jpg"];
    [myObject addObject:@"tut_3.jpg"];
    [myObject addObject:@"tut_4.jpg"];

    pageControlBeingUsed = NO;

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHight = screenRect.size.height;

    for (int i = 0; i < [myObject count]; i++) {
        CGRect frame;
        frame.origin.x = self.takeTourScrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = self.takeTourScrollView.frame.size;

        NSString *val = [myObject objectAtIndex:i];

        UIImage* theImage = [UIImage imageNamed:val];

        UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)];

        img.image = theImage;

        [self.takeTourScrollView addSubview:img];

    }

The first first image seems to be ok.

Then when I swipe left I am getting a blank screen

I swipe left again and then I see my second picture. And it goes like that for all the 4 images.
Any ideas what am I doing wrong ?

A: I'd advise to use UITableView/UICollectionView for such behaviour. You can set the image in each cell and they'll be reused - it will be much better in terms of memory management.
The tableView will by the way place all elements in proper places (you just need to define the height of the cell or the layout).
It will also properly resize on events (eg phone rotation).
Also, you should try to avoid hardcoding the sizes:
CGRectMake(screenWidth*i,0,185 ,284)

You will fail in case of smaller / bigger devices. It'll be a great pain to maintain the code after some time.
-- edit --
After @Duncan C posted his answer, I've noticed you're looking for a paging system. You can go with building your own solution either on UIPageViewController or on UICollectionView. However you can also use third party libraries, I really enjoy this one: https://www.cocoacontrols.com/controls/bwwalkthrough. It has a support of different animations and does a ton of stuff for you :).

A: There are system components that will give you what you want with much less work and a more refined user experience. Using a UICollectionView is one possibility, as mentioned by Vive in her answer. My suggestion would be a UIPageViewController. There is a sample app called PhotoScroller from Apple that shows how to implement a UI very much like what you describe. Do a search in the Xcode docs for "PhotoScroller" to find it.

A: you already set the x position of uiscrollview. do not need to set the x postion of  UIImageView.Because you used imageview as a subview of uiimagescrollview.
change this line to
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)];

with
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,185 ,284)];


text:
Q: How to keep variable and dictionary that contains it consistent? I have a variable
self.foo = 1

And a dictionary
self.foo_dict = {
    'foo_key' = self.foo
}

I would like to be able to change the value of self.foo and have it also change in self.foo_dict. If this was in C (and the dict was a struct), I'd just use a pointer.
Any suggestions? Is this even possible in Python?

A:
Is this even possible in Python?

Answer 1: Not in a straight forward manner, because int is immutable. However...
Answer 2: There are workarounds for achieving what you want.
Instead of using int for your variable foo, you need to have a wrapper class for foo, since int is immutable, and any wrapper class you define is not.
Your wrapper class for foo:
class Foo:
    def __init__(self, val):
        self.foo = val
    def set(self, val):
        self.foo = val
    def __repr__(self):
        return str(self.foo)

Then, the class where you are having that consistent variable-dictionary pair could be something like this:
class A:
    def __init__(self):
        self.foo = Foo(1)
        self.foo_dict = {
            'foo_key': self.foo
            }
    def set_foo(self, newval):
        self.foo.set(newval)

Test run:
>>> a = A()
>>> a.foo
1
>>> a.foo_dict['foo_key']
1
>>> a.set_foo(20)
>>> a.foo
20
>>> a.foo_dict['foo_key']
20

A: No need for wrapper classes!
Just make self.foo a property that accesses the value in your dictionary:
class Bar:
    def __init__(self, foo_):
        self.foo_dict = {}
        self.foo = foo_

    @property
    def foo(self):
        return self.foo_dict["foo_key"]

    @foo.setter
    def foo(self, value):
        self.foo_dict["foo_key"] = value

    def show(self):
        print("foo={} ; foo_dict['foo_key']={}".format(
                        self.foo, self.foo_dict["foo_key"]))

b = Bar(1)
b.show()
b.foo = 2
b.show()
b.foo_dict["foo_key"] = 3
b.show()

See this code running on ideone.com
Properties look to the outside like normal instance member fields, but they are really custom functions that could do anything. This way the two foo(...) methods are called when the foo property is accessed. The one decorated with @property is the getter and the one decorated with @PROPERTYNAME.setter is obviously the setter. You could also restrict read or write access to the property by simply omitting one of the property methods.
Here, they redirect all actions to the dictionary. That way you have exactly one instance of a simple mutable variable, but multiple ways to access it.
The example above would result in this output:
foo=1 ; foo_dict['foo_key']=1
foo=2 ; foo_dict['foo_key']=2
foo=3 ; foo_dict['foo_key']=3

So as we can see, no matter whether we change the value in the dictionary or through the property, both names always point to the same variable.

A: >>> class Test(object):
    def __init__(self,foo):
        self.foo = foo
        self.foo_dict = {'foo_key': foo}
    def set_foo(self, foo):
        self.foo = foo
        self.foo_dict['foo_key'] = foo

>>> a = Test(1)
>>> a.foo
1
>>> a.foo_dict
{'foo_key': 1}
>>> a.set_foo(2)
>>> a.foo
2
>>> a.foo_dict
{'foo_key': 2}
>>>

A: I did not fully understood your question but if your want to change the value of self.foo, you can do it directly using a dictionary. Suppose that you have some dictionary:
self.some_dict = {"valueA":1}

Considering that a dictionary functions by key to value pairs, you an change the value of valueA like this:
self.some_dict["valueA"] = some_value

Therefore, the value of the key is changed to some_value. As another possibility you can create a copy of a dictionary using dict.copy. With this you have another dictionary with the same values of the first, and then update with dict.update to add new elements or values in the keys. Something like this:
self.some_dict = {"value1":1}
self.other_dict = some_dict
self.other_dict.update("{"value2": 2}")

With this you can update the value2 to other_dict.


text:
Q: Can't match two dataframe values I am not sure why the dataframe values do not match with each other.
I have a df name fileUpload which looks like this (the cols are aligned correctly):
Destination City    Year    Adults
Amsterdam   2015    2
Amsterdam   2016    2
Amsterdam   2015    2
Amsterdam   2016    2
Amsterdam   2015    3

There is a space after each city name.
I have another dataframe that is not uploaded, like this:
cities <- read.csv(text = "
      City,Lat,Long,Pop
      Amsterdam ,4.8952,52.3702,779808
      Bali ,115.1889,-8.4095,4225000")

I need to merge the two dataframes, but I realized that the city values returns not matching (NA). I tried checking it using fileUpload %in% cities returns false
I tried removing the space after the city, also did not work.
The typeof(df$city) for both is integer.
How can I make the cities name match together?

A: As pointed out in the comments you should convert your columns to strings from factors.
mergedCities <- merge(fileUpload, cities, by.x ="Destination City", by.y = "City", all = TRUE)

Set the all parameter to specify if you want to keep all cities or just the one form x or y or only the cities present in both.


text:
Q: Count top elements in a matrix (Matlab) I have the matrix:
A=[ 4 0 0 0 0
   0 3 0 0 0
   0 0 2 0 0
   0 0 0 1 0
   0 0 0 0 1 ];

I want to get the top k elements' values in the diag, such that the sum of these elements are larger than a predefined threshold T, whilst k is as large as possible.
For example: T= 0.9

            (4+3+2)/(trace(A)) = 0.818...
            (4+3+2+1)/(trace(A)) = 0.909...

i.e. we can get the vector of top values in A as: V= [4,3,2] and thus, k = 3.
Could anyone tell me how can I do that ?

A: For the cumsum of diag(A) you want to find the last element where the comparison X./trace(A)<=T is true. Put that together into code:
find(cumsum(diag(A))./trace(A)<=T,1,'last')


text:
Q: Image batch processing crop empty alpha channel of .pngs in imagemagick or similar tools I have a bunch of PNG images of the same overall size but with different smaller 'things' in it. I want to crop these images so that all 'unused' alpha channel space is discarded and the new images are of smaller size.
An example what I want to happen. Green is the alpha channel.
Thank you!

A: You can just use -trim. So, for a single image:
magick input.png -trim +repage result.png

For lots of images, make a backup first and try on a copy:
magick mogrify -trim +repage *.png


text:
Q: pandas scatterplots: stop automatic scaling of axis I am trying to create two separate scatterplots with identical axes. As the code below shows, I am explicitly setting my axis limits. However, because the spread of the data is different between the two plots, the scaling of the x axis within these limits is changing. Compare Figures 1 & 2 below, plotted using identical code (except the different x values):
Figure 1
#set up figure
fig, ax1 = plt.subplots(1,1)

#plot first series (left y axis)
df.plot(ax=ax1, kind='line', x=bin1, y='hfall', logx=True,
        color='DarkBlue', style='.', markersize=5, legend=False)

#set up second axis as duplicate of the first
ax2 = ax1.twinx()

#plot second series (right y axis)
df.plot(ax=ax2, kind='line', x=bin1, y='vf', logx=True,
        color='Red', style='.', markersize=5, legend=False)

#set axes limits
ax1.set_xlim([0.,0.4])
ax1.set_ylim([1,1.15])
ax2.set_xlim([0.,0.4])
ax2.set_ylim([2e-06,6e-06])

#set labels and title
ax1.set_ylabel('Total horizontal flux ($kg/m^2/s$)', color='DarkBlue')
ax1.set_xlabel('horizontal flux in bin1 ($kg/m^2/s$)')
ax1.set_title('bin1', loc='center', fontsize=14)
ax2.ticklabel_format(axis='y', style='sci', scilimits=(0,0))
ax2.set_ylabel('Total vertical flux (all bins) ($kg/m^2/s$)', color='Red')

plt.show()

Figure 2
#set up figure
fig, ax1 = plt.subplots(1,1)

#plot first series (left y axis)
df.plot(ax=ax1, kind='line', x=bin2, y='hfall', logx=True,
        color='DarkBlue', style='.', markersize=5, legend=False)

#set up second axis as duplicate of the first
ax2 = ax1.twinx()

#plot second series (right y axis)
df.plot(ax=ax2, kind='line', x=bin2, y='vf', logx=True,
        color='Red', style='.', markersize=5, legend=False)

#set axes limits
ax1.set_xlim([0.,0.4])
ax1.set_ylim([1,1.15])
ax2.set_xlim([0.,0.4])
ax2.set_ylim([2e-06,6e-06])

#set labels and title
ax1.set_ylabel('Total horizontal flux ($kg/m^2/s$)', color='DarkBlue')
ax1.set_xlabel('horizontal flux in bin2 ($kg/m^2/s$)')
ax1.set_title('bin2', loc='center', fontsize=14)
ax2.ticklabel_format(axis='y', style='sci', scilimits=(0,0))
ax2.set_ylabel('Total vertical flux (all bins) ($kg/m^2/s$)', color='Red')

plt.show()

I appreciate that this is probably happening to best show me the variability within my data, but I want to compare the plots directly - the shift in space occupied on the log scale is useful to know. SO, does anybody out there know how I can stop this automatic scaling of the x axis from happening? (i.e. I want the x axis to be identical on the two plots)

A: You can't set an xlim of 0 on a logarithmic axis. Try setting it to the number on the low end of the axes you want to match. e.g.
ax1.set_xlim([2e-3,0.4])

ax2.set_xlim([2e-3,0.4])


text:
Q: how to fix Undefined variable: project in Laravel 5.2 I need add comment box to My Laravel app. this is blade file for comment box in comments folder of view file
comments/form.blade.php
 <form class="form-vertical" role="form" method="post" action="{{ route('projects.comments.create', $project->id) }}">

has('comments') ? ' has-error' : '' }}">
            <textarea name="comments" class="form-control" style="width:80%;" id="comment" rows="5" cols="5"></textarea>
            @if ($errors->has('comments'))
                {{ $errors->first('comments') }}
            @endif

            <button type="submit" class="btn btn-info">Add Comment</button>

        <input type="hidden" name="_token" value="{{ csrf_token() }}">
    </form>

and now I am going to include this file in to the show.blade.php file in tasks folder
tasks/show.blade.php
@include('comments.form')

this is My CommentController.php
public function postNewComment(Request $request, $id, Comment $comment)
    {
       $this->validate($request, [
            'comments'     => 'required|min:5',
        ]);

       $comment->comments       = $request->input('comments');
       $comment->project_id     = $id;
       $comment->user_id        = Auth::user()->id;
       $comment->save();

       return redirect()->back()->with('info', 'Comment posted successfully');
    }

and comment model
 public function user()
    {
        return $this->belongsTo(User::class);
    }

but got following error
Undefined variable: project (View: C:\Users\Lilan\Desktop\ratakaju\resources\views\comments\form.blade.php)

how to fix this problem?


text:
Q: Set inheritedByDefault to false in plugin.xml I'm having trouble while developping a maven plugin to find out how to configure the inheritedByDefault property to be set to false in the generated plugin.xml file.
Be careful, I don"t speak about the inheritedByDefault property of each mojo, but the general inheritedByDefault property at the root of the plugin  tag.
Plugin descriptor documentation isn't very loquacious about this subject and I can't find anything on Internet.


text:
Q: Wrapping libcups C library in Swift I am trying to wrap the libcups library https://github.com/apple/cups to be used in my Swift project.
I have tried some of the examples in https://www.cups.org/doc/cupspm.html and they are working fine.
However I am struggling when it comes to wrapping the C code to be used in a Swift project.
I have been searching online on how to wrap C libraries in Swift but has not been able to have much progress.
Here is the C code
#include <stdio.h>
#include <cups/cups.h>

typedef struct {
    int num_dests;
    cups_dest_t *dests;
} my_user_data_t;

int my_dest_cb(my_user_data_t *user_data, unsigned flags, cups_dest_t *dest) {
    if (flags & CUPS_DEST_FLAGS_REMOVED) {
        user_data->num_dests = cupsRemoveDest(dest->name, dest->instance, user_data->num_dests, &(user_data->dests));
    } else {
        user_data->num_dests = cupsCopyDest(dest, user_data->num_dests, &(user_data->dests));
    }
    return 1;
}

int my_get_dests(cups_ptype_t type, cups_ptype_t mask, cups_dest_t **dests) {
    my_user_data_t user_data = { 0, NULL };

    if (!cupsEnumDests(CUPS_DEST_FLAGS_NONE, 1000, NULL, type, mask, (cups_dest_cb_t)my_dest_cb, &user_data)) {
        cupsFreeDests(user_data.num_dests, user_data.dests);
        *dests = NULL;
        return 0;
    } else {
        *dests = user_data.dests;
        return user_data.num_dests;
    }
}

int main(int argc, const char * argv[]) {
    cups_dest_t *dests = NULL;
    int num_dests = my_get_dests(0, 0, &dests);
    printf("Destination found: %d\n", num_dests);

    cups_dest_t *dest;
    int i;
    const char *value;

    for (i = num_dests, dest = dests; i > 0; i--, dest++) {
        if (dest->instance == NULL) {
            value = cupsGetOption("printer-info", dest->num_options, dest->options);
            printf("%s (%s)\n", dest->name, value ? value : "No description");
        }
    }
    return 0;
}

Here is the same thing but in Swift
let destinationsCallback: cups_dest_cb_t = { user_data, flags, dest in
    // (void *user_data, unsigned flags, cups_dest_t *dest)
    var userDataPointer = user_data!.assumingMemoryBound(to: my_user_data_t.self).pointee
    var destData = dest!.pointee

    if destData.instance != nil {
        print("\(String(cString: destData.name))/\(String(cString: destData.instance))")
    } else {
        print(String(cString: destData.name))
    }

    if flags == CUPS_DEST_FLAGS_REMOVED {
        userDataPointer.num_dests = cupsRemoveDest(destData.name, destData.instance, userDataPointer.num_dests, &(userDataPointer.dests))
    } else {
        userDataPointer.num_dests = cupsCopyDest(dest, userDataPointer.num_dests, &(userDataPointer.dests))
    }
    return 1
}

func getDestinations(type: UInt32, mask: UInt32, dests: UnsafeMutablePointer<cups_dest_t>) -> Int32 {
    var userData = my_user_data_t(num_dests: 0, dests: nil)

    if cupsEnumDests(UInt32(CUPS_DEST_FLAGS_NONE), 1000, nil, type, mask, destinationsCallback, &userData) != 1 {
        return 0
    } else {
        return userData.num_dests
    }
}

I am not able to get the userData to return the correct value which I am assuming is due to the way I handle the pointers.
Greatly appreciate if I am able to get some advice.

A: IMHO the best way to work with such C libraries in Swift is to work with them in Objective-C. Nevertheless, the main issue seems to be that you are not writing back changes to userData, that's why you always get your initial value. You need to update it in your callback like this
let userDataPointer = user_data!.assumingMemoryBound(to: my_user_data_t.self)
var userData = userDataPointer.pointee
...
// make some changes to userData

userDataPointer.pointee = userData

return 1

Also there seems to be some differences between your C code and the Swift one, like checking flags with 'flags == CUPS_DEST_FLAGS_REMOVED' which, in general, is incorrect way to check flags, and comparing result of cupsEnumDests with 1 when in the original code you check that result is not 0.


text:
Q: Chrome is redirected to the api url I have a config.json file:
{
    "api": "https://**.*****.nl/",
    "debug": true,
    "signalRTransports": "auto"
}

Sometimes in Chrome when I visit http://localhost:8080 (served by webpack) I get redirected to the api url.
Currently I'm working with BackstopJS to setup a testing reference, but this doesn't work well when I get redirected. Does anyone know how to prevent the redirection?

A: It seemed the problem was that I was redirected after being logged in to the API server. Passing the cookies that come with the API call seems to fix the problem of being redirected.


text:
Q: How to disable notifications of private Telegram channel? How to disable notifications? Im tried to use entities/hash of channel/id of channel, but all of this is useless.
Exception:
a TLObject was expected but found something else

My code:
    id = client(functions.messages.ImportChatInviteRequest(hash = 'TKi_Qa66jzo3N2Uy')).chats[0].id

    ent = client.get_input_entity(id)

    client(functions.account.UpdateNotifySettingsRequest(peer=types.InputNotifyPeer(ent), settings=types.InputPeerNotifySettings(show_previews=False, mute_until=datetime(2023, 6, 25), sound='none')))


text:
Q: Error event thrown for audio object in IE, yet it plays the audio? This is my code:
<audio preload="auto" volume="1.0">
    <source type="audio/mpeg" src="path/to/file.mp3" />
</audio>

Using Javascript I get the <audio>-element as a variable, and set an error handler:
audioElement.onerror = function()
{
    alert('Error: ' + audioElement.error.code);
};

As soon as the <audio>-element is added to the DOM-tree, and after the audio is preloaded, the error gets thrown.
The alert box shows: Error: 4 which means: MEDIA_ERR_SRC_NOT_SUPPORTED.
However, when clicking the playButton:
playButton.onclick = function()
{
    audioElement.play();
};

The sound plays as it should, and does not seem to be any problem. Why is the error thrown in the first place? Should I simply ignore the error if its code is 4?
I can hardly find any documentation on specific cases in which this error is being thrown, that is why I ask this question. I hope somebody knows the answer here!


text:
Q: How do I open a file in python? I need to read the file called, "ranks.dat", however whenever I try opening the file it says there is no such file or directory even though I have downloaded the file. Below is my code:
# Reading from a file
numFile = open("ranks.dat", "r")

while True:
    text = numFile.readline()
    #rstrip removes the newline character read at the end of the line
    text = text.rstrip("\n")
    if text=="":
        break
    print (text, end = "\t")

numFile.close()

The files should always have the following fields:
Rank - Word of Size 15 or less - the Name of the Card
Power - Integer less than 100 - the Power of the Card
Number - Integer less than 100 - the Number of these cards
I need to store each of the fields into their own list. But it does not seem to work.

A: You need to specify the route, here are the lines.
import sys
import os

ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
dir = os.path.join(ROOT_DIR, "YOURFOLDERNAME")

numFile = open(dir+'/'+"ranks.dat", "r")

A: First make sure that Python is able to read the path to your file.
from os import path

if path.exists('ranks.dat'):
   # do the file processing
else:
   print('Filepath does not exist.')

If it prints out that the file path does not exist, then you can provide the full filepath to ranks.dat and it should work.
In addition, you can also use a context manager to open and close the file for you when you are done
with open('ranks.dat', 'r') as f:
    for line in f.readlines():
        print(line)


text:
Q: $\partial A = \overline{A} \cap \overline{ \mathbb{R}^d \setminus A } $ My attempt: ($A \subseteq \mathbb{R}^d$) We know by definition that $\overline{A} = \partial A \cup  A $. Hence $\overline{ \mathbb{R}^d \setminus A} = \partial [ \mathbb{R}^d \setminus A ]\cup \mathbb{R}^d \setminus A$. Obviously, have $\partial A = \partial [\mathbb{R}^d \setminus A]$. Hence:
$$  \overline{A} \cap \overline{ \mathbb{R}^d \setminus A } = [\partial A \cup A] \cap[\partial A \cup  \mathbb{R}^d \setminus A ] = \partial A \cup( A \cap \mathbb{R}^d \setminus A) = \partial A \cup \varnothing = \partial A$$
Is this a correct approach? Any feedback would be extremely appreciated. thanks

A: It depends on your definition of $\partial A$ how obvious $\partial A=∂(\Bbb R^n\setminus A)$ is. If $\partial A$ is defined as the set of points $x$ such that any neighborhood of $x$ intersects both $A$ and $X\setminus A$, then yes, it is obvious.
So your proof is correct.


text:
Q: Resize JTable/Scrollpane It's actually an question about this. How do I resize this now? I used this, I was able to resize my JPanel, but I can't find how to resize the table or scrollpane. I have 10 columns and the table just stays the same size.
Thanks in advance

A:
I was able to resize my JPanel, but I can't find how to resize the table or scrollpane.

The problem is that the JPanel uses a FlowLayout. A FlowLayout will respect the preferred size of any component added to the panel. So in the example code the table is displayed at its default preferred size.
A couple of solutions:

*

*There is no need for the panel. Just add the scrollpane directly to the frame. The table will grow/shrink as the frame size changes.

*Change the layout manager of the panel to one that will allow components added to it to grow to fill the available space. Again the table will grow/shrink as required.

*Override the getPreferredScrollableViewportSize(...) method of the JTable. This will override the default preferred size of the table. The table may grow/shrink depending of the layout manager used.