text:
Q: Downloading all my questions with the answerer names I am writing several papers in which I use answers which I received in various StackExchange websites. Naturally I would like to acknowlege and thank the SE members that gave the useful answers. But there are many such answers, and each answer is relevant to a different paper.
So, I would like to download all the questions that I asked in the various SE websites, including the answerer names, to an Excel worksheet in which I can organize the questions by subject.
Is this possible?

A: You already got a per site query from Patrick and that leaves the cross-site-query for me.
This query outputs all your questions network-wide with the answers given, listing score, creationdate and the user (linked).
The query requires an accountid and that one can be found by visiting your network account on StackExchange.com and then take the id from the url. Yours is 439169, mine is 281857.
---- accountid: Account on stackexchange.com! "In the url on stackexchange.com"

-- start create url from dbname
IF OBJECT_ID ( '#siteurl', 'P' ) IS NOT NULL
    DROP PROCEDURE #siteurl;
GO
create procedure #siteurl
   @dbname nvarchar(250),
   @res nvarchar(250) OUT
   as
   begin
      -- we have three sites that have borked DNS entries
      set @dbname = (case @dbname
      when 'StackExchange.Audio' then 'StackExchange.Avp'
      when 'StackExchange.Audio.Meta' then 'StackExchange.Avp.Meta'
      when 'StackExchange.Mathoverflow.Meta' then 'net.Mathoverflow.meta'
      else @dbname
      end)
      -- and one of those doesn't want to end with .com
      if @dbname <> 'net.Mathoverflow.meta'
         set @dbname = 'com.' + @dbname
      exec #recursesiteurl @dbname,  @res OUTPUT
   end
GO
-- create url from dbname
IF OBJECT_ID ( '#recursesiteurl', 'P' ) IS NOT NULL
    DROP PROCEDURE #recursesiteurl;
GO
create procedure #recursesiteurl
   @dbname nvarchar(250),
   @res nvarchar(250) OUT
   as
   begin
      declare @pos integer
      declare @rec nvarchar(250)

      set @res = @dbname
      set @pos = CHARINDEX('.', @dbname)
      if (@pos > 0 )
      begin
         set @rec = substring(@dbname, @pos+1, len(@dbname))
         exec #recursesiteurl @rec,  @rec output
         set @res = @rec
                  + '.'
                  + substring(@dbname, 0, @pos)
      end
   end;
GO

declare @accountid int = ##accountid:int##  -- 93484

-- all databases
declare  db_c cursor for select [name]
                         from sys.databases
                         where database_id > 5 -- skip master, temp, model, msdb, Data.SE

declare @db_c_name sysname   -- holds name of db after fetch
declare @sql nvarchar(max) -- holds build up sql string

-- result table
create table #all_posts ( site nvarchar(250)
                            , id int
                            , title nvarchar(200)
                            , aid int
                            , creationdate datetime
                            , score int
                            , bodyexcerpt nvarchar(100)
                            , owneruserid int
                            , displayname nvarchar(200));

open db_c
fetch next from db_c into @db_c_name
while(@@FETCH_STATUS = 0)
begin
    set @sql = N'use '+ QUOTENAME(@db_c_name) +';
               declare @url nvarchar(250)
               exec #siteurl ''' + @db_c_name  + ''', @url output
               insert into #all_posts
               select @url
               , q.id
               , q.title
               , p.id
               , p.creationdate
               , p.score
               , left(p.body,100)
               , p.owneruserid
               , pu.displayname
               from posts p
               inner join posts q on p.parentid = q.id
               inner join users pu on pu.id = p.owneruserid
               inner join users qu on qu.id = q.owneruserid
               where qu.accountid = '+ cast(@accountid as nvarchar) + ';'
    exec (@sql)
   fetch next from db_c into @db_c_name
end;
close db_c;
deallocate db_c;

select replace(
       replace(
       replace(site,
         '.StackExchange.com',''),
         '.com',''),
         '.net','') as [site]
     , 'http://'
     + site
     + '/q/'
     + cast(id as nvarchar)
     + '|'
     + title as question
     , 'http://'
     + site
     + '/a/'
     + cast(aid as nvarchar)
     + '|answer' as AnswerLink
     , score
     , creationdate
     --, bodyexcerpt
     , 'http://'
     + site
     + '/users/'
     + cast(owneruserid as nvarchar)
     + '|'
     + displayname as [user]
from #all_posts

drop table #all_posts

drop procedure #recursesiteurl
drop procedure #siteurl

I start with creating a procedure (functions are not allowed) to translate a databasename to a site url. The db's are named StackExchange.Photography.meta and the url for that site is meta.photography.stackexchange.com
A temporary table is going to hold all our data.
Then I open a cursor to iterate over all databases (except the system db's). In that loop I create a sql statement to switch to the correct database, create an insert/select to insert your posts with the answers in the temp table. When that is done the sql statement is executed.
After the loop is done the final select statement produces the result where I buildup the final url to the answers, question and user. The links work because SEDE interprets column values that contain http://site/url/tosomething|title as link and the front end renders a nice title for us.

A: Yes, you can using SEDE.
Here is the query you want:
select q.Id [Question Id]
,      q.Id [Post Link]
,      a.Id [Answer Id]
,      a.Id [Post Link]
,      a.OwnerUserId
,      a.OwnerUserId [User Link]
from   posts q
join   posts a
on     q.Id = a.ParentId
join   users u
on     a.OwnerUserId = u.Id
where  q.PostTypeId = 1
and    q.OwnerUserId = ##userid##

You can download the results as CSV, which you can import into Excel. I am not sure how to make this query cross-site, maybe someone else can enlighten me on that, but you can run it one-by-one for your sites.


text:
Q: "Sum equals integral" identities similar to $\int_0^1 \frac{dx}{x^x} = \sum_{n = 1}^{\infty} \frac{1}{n^n}$ It is quite a well known fact that:
$$\int_0^{+\infty} \frac{\sin x}{x} \, dx = \frac{\pi}{2}$$
also the value of related series is very similiar:
$$\sum_{n = 1}^{+\infty} \frac{\sin n}{n} = \frac{\pi - 1}{2}$$
Combining these two identities and using ${\rm sinc}$ function we get:
$$\int_{-\infty}^{+\infty} {\rm sinc}\, x \, dx = \sum_{n = -\infty}^{+\infty} {\rm sinc}\, n = \pi$$
What is more interesting is the fact that the equality:
$$\int_{-\infty}^{+\infty} {\rm sinc}^k\, x \, dx = \sum_{n = -\infty}^{+\infty} {\rm sinc}^k\, n$$
holds for $k = 1,2,\ldots, 6$. There are some other nice identities with ${\rm sinc}$ where sum equals integral but moving on to other functions we have e.g.:
$$\sum_{n = -\infty}^{+\infty} \binom{\alpha}{n} e^{int} = \int_{-\infty}^{+\infty} \binom{\alpha}{n} e^{itx} \, dx = (1+e^{it})^\alpha, \; \alpha  >-1$$which is due to Pollard & Shisha.
And finally the identity which is related to the famous Sophomore's Dream:
$$\int_0^1 \frac{dx}{x^x} = \sum_{n = 1}^{+\infty} \frac{1}{n^n}$$
Unfortunately in this case the summation range is not even close to the interval of integration.
Do you know any other interesting identities which show that "sum = integral"?

A: Several papers are dedicated to the subject of integrals of functions that equal the sum of the same function, primarily for estimation purposes.
Boas and Pollard (1973) has some interesting sum-integral equalities:
$$\pi/\alpha=\sum_{n=-\infty}^\infty \frac{\sin^2 (c+n)\alpha}{(c+n)^2}=\int_{-\infty}^\infty \frac{\sin^2 (c+n)\alpha}{(c+n)^2}\, \text{d}n$$
$$\pi\operatorname{sgn} a=\sum_{n=-\infty}^\infty \frac{\sin (n+c)\alpha}{n+c}=\int_{-\infty}^\infty \frac{\sin (n+c)\alpha}{n+c}\, \text{d}n$$
It also gives several general formulae for functions that suffice:
$$\sum_{n=-\infty}^\infty f(n)=\int_{-\infty}^\infty f(n) \, \text{d}n$$
mainly with Fourier analysis.

This paper gives an equality with the Bessel J function:
$$\int_{-\infty}^\infty \frac{J_y (at) J_y(bt)}{t}\, \text{d}t=\sum_{t=-\infty}^\infty \frac{J_y (at) J_y(bt)}{t}$$
and some more references:

There have been a number of studies of this kind of sum-integral
equality by various groups, for example, Krishnan & Bhatia in the
1940s (Bhatia & Krishnan 1948; Krishnan 1948a,b; Simon 2002) and Boas,
Pollard & Shisha in the 1970s (Boas & Stutz 1971; Pollard & Shisha
1972; Boas & Pollard 1973).

See also Surprising Sinc Sums and Integrals which has some other equalities.  This paper also states that (paraphrasing)
If $G$ is of bounded variation on $[−\delta, \delta]$, vanishes outside $(−α, α)$, is Lebesgue integrable over $(−α, α)$ with $0 < α < 2\pi$ and has a Fourier transform of $g$, then
$$\sum_{n=-\infty}^\infty g(n)=\int_{-\infty}^\infty g(x)\, \text{d}x+\sqrt{\frac{\pi}{2}}(G(0-)+G(0+))$$

Ramanujan's second lost notebook contains some sums of functions that equal the integral of their functions (Chapter 14, entries 5(i), 5(ii), 16(i), 16(ii)).

If you want, even more references with examples are in the papers I have mentioned.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Preserve Case sensitive filename in Dropbox API when updating a file I am using code like this:
Metadata e = ...;
dbxClient.files().uploadBuilder(e.getPathLower()).withMode(WriteMode.OVERWRITE).uploadAndFinish(...)

which results in losing the case of the filename (e.g. MyFile.txt becomes myfile.txt). This seems obvious as getPathLower is returning the lower-case filename.
Metadata has another method getDisplayName() returning the cased path:
 /**
     * The cased path to be used for display purposes only. In rare instances
     * the casing will not correctly match the user's filesystem, but this
     * behavior will match the path provided in the Core API v1, and at least
     * the last path component will have the correct casing. Changes to only the
     * casing of paths won't be returned by {@link
     * DbxUserFilesRequests#listFolderContinue(String)}. This field will be null
     * if the file or folder is not mounted.
     *
     * @return value for this field, or {@code null} if not present.
     */
    public String getPathDisplay() {
        return pathDisplay;
    }

I did not want to use this as it says it's for display purposes only.
So, how can I avoid losing the case of the filename correctly?

A: To update an existing file for which you have the Metadata, you can use the file ID. You can get the file ID using FileMetadata.getId, and then pass that value to the path parameter of uploadBuilder (instead of e.getPathLower()).


text:
Q: How to set size of the image? I have splash.png and want that this image take all place on the screen like fitXY for ImageView. splash.png has sizes 480x767.
What does I must to change in my code?
public class BitmapConfigView extends LinearLayout {
private Bitmap mImage;
private Paint mPaint = new Paint();

public BitmapConfigView(Context context) {
    super(context);

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
    opts.inScaled = false;
    mImage = BitmapFactory.decodeResource( getResources(), R.drawable.splash, opts);

    mPaint.setDither(true);
    setWillNotDraw(false);
    setOrientation(VERTICAL);
    setGravity(Gravity.BOTTOM);
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(mImage, 0.0f, 0.0f, mPaint);
}
}

A: Scale the bitmap. This is what you're looking for:
android.graphics.Bitmap.createScaledBitmap

A: This is how i usually do mine with a scale method.
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

int width = bm.getWidth();

int height = bm.getHeight();

float scaleWidth = ((float) newWidth) / width;

float scaleHeight = ((float) newHeight) / height;

// create a matrix for the manipulation

Matrix matrix = new Matrix();

// resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap

Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

return resizedBitmap;

}

A: As a result, I used WebView:
public class TestwebViewimageActivity extends Activity {
private WebView wv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    wv = (WebView) findViewById(R.id.webview);
    wv.setWebViewClient(new HelloWebViewClient());
    wv.setBackgroundColor(0x00000000);
    wv.getSettings().setBuiltInZoomControls(false);
    wv.setVerticalScrollBarEnabled(false);
    wv.setHorizontalScrollBarEnabled(false);
    wv.loadUrl("file:///android_asset/6.html");

}

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

   <WebView
   android:id="@+id/webview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"/>
</LinearLayout>

6.html


text:
Q: Creating a numerical data type exceeding its normal size There is a calculator program that I have came across on Windows long ago. I couldn't recall its name, but one impressive thing about it is that it can calculate numbers up to 512 bytes size. Requesting a pi value, for instance, it can give out numbers with hundreds of digits. (but of course it takes a few seconds to output) Normally, an int would be 4 bytes, double 8 bytes, etc.
Now, how can we do that? How can we allocate a variable for numbers that can exceed the normal range? (as in, int is 4 bytes, long is 8 bytes) And how to prevent overflow and underflow in this case? Assume that this is C++.

A: Google around for the terms arbitrary-precision arithmetic and multiple-precision arithmetic.  The number of libraries plus the number of applications which implement such arithmetic probably exceeds 2^32.

A: You can do this using the GNU MP library, or one of its competitors.
You can also roll your own, if you're good at maths.


text:
Q: How to getText on one page and then use it for assertEquals on another one? I have a table with some data like:
|_name_|___email_____|
|website|website@test.com|
After clicking on the name Website, a settings page of the Website is displayed. On the top, there is a header with the "Website" name.
I need a solution for JUnit to verify that after click on the "Website" name in the table user is redirected to the "Website" settings page.
I tried the way below but didn't help:
String firstNameInTheTable = driver.findElement(By.xpath(TestPage.FIRST_NAME_IN_THE_TABLE)).getText();
driver.findElement(By.xpath(TestPage.FIRST_NAME_IN_THE_TABLE)).click();
assertEquals(firstNameInTheTable, WebsitePage.WEBSITE_TITLE_TEXT);

Actually it would be better to verify that text from the first column ("name" in our case) is the same as on the settings page. So it may happen that we do not have a Website text but another Name. Still the test should pass.

A: 1.Select and get the name of the website.
WebElement element = driver.findElement(By.xpath("//xpath"))
String name = element.getText();
element.click();

2.Wait the load, select the title and assertEquals.
sleep(3);
String title = driver.findElement(By.xpath("//xpath")).getText();
Assert.assertTrue(name.equals(title));

/!\ If the 2nd step is to open a new window, take a look at the tutorial here (to put between the sleep(3); and String title ...).
Other :
sleep method
protected void sleep(int i) {
    driver.manage().timeouts().implicitlyWait(i, TimeUnit.SECONDS);
}

A: This is example, you can refer it and create your TCs accordingly
    WebDriver driver = new FirefoxDriver();
    driver.get("https://www.google.co.in/");

    String linkTitle = driver.findElement(By.xpath("//a[@href='/intl/en/about.html']")).getText();
    driver.findElement(By.xpath("//a[@href='/intl/en/about.html']")).click();
    System.out.println(driver.findElement(By.xpath("//div[@id='corp-crumb']/ol/li")).getText());
    Assert.assertTrue(linkTitle.equals(driver.findElement(By.xpath("//div[@id='corp-crumb']/ol/li")).getText()));


text:
Q: Convert keras model from pb file to tflite file I am trying to convert a trained Keras model from .pb file to .tflite file:
tflite_model = tf.contrib.lite.toco_convert(frozen_graph_def, input_tensors, output_tensors)

However, when I run this code, there is an error that says:

AttributeError: module 'tensorflow.contrib.lite' has no attribute
  'toco_convert'

How to solve this problem?

A: If you are on windows it won't work since toco library does not support windows. So it's better to switch over Linux and try again.

A: Are you using the last version of tensorflow? this can also be solved when installing tf-nightly. Or compiling tensorflow from the source with bazel.
You can also use instead: tf.contrib.lite.TocoConverter.from_frozen_graph(final_model_path, input_arrays, output_arrays)

A: Please provide the tensorflow graph you are trying to convert to reproduce the exact error. It would help to also file an issue on GitHub https://github.com/tensorflow/tensorflow/issues


text:
Q: Evaluating $\lim\limits_{n\rightarrow +\infty }\left ( 2\sqrt[n]{x}-1 \right )^n$ for $x \ge 1$ Given a real number $x\geq 1$. Find the limit
$$\lim_{n\rightarrow +\infty }\left ( 2\sqrt[n]{x}-1 \right )^n$$

A: The Taylor expansion of $x^{n}$ at $n=0$ is $\displaystyle 1+ n \ln x  + \mathcal{O}(n^{2})$.
So the Laurent expansion of $x^{\frac{1}{n}}$ at $n= \infty$ is $ \displaystyle 1 + \frac{\ln x}{n} + \mathcal{O}\left( \frac{1}{n^{2}}\right)$.
Then $ \displaystyle \lim_{n\to \infty }\left( 2\sqrt[n]{x}-1 \right )^{n} = \lim_{n \to \infty} \left(2 + \frac{2 \log x}{n}  + \mathcal{O} (n^{-2} )-1 \right)^{n}  $
$\displaystyle = \lim_{n \to \infty} \left( 1 + \frac{\log x^{2}}{n} + \mathcal{O}(n^{-2}) \right)^{n} = e^{\log x^{2}} = x^{2}$

A: $$\lim_{n\to\infty}(2\cdot\sqrt[n]x-1)^n=\lim_{n\to\infty}\exp\,\left[n\cdot\ln\left(2\cdot\sqrt[n]x-1\right)\right]=\lim_{n\to\infty}\exp\left[\frac{\ln(2\cdot x^\frac1n-1)}{\frac1n}\right]=$$ $$=\lim_{n\to\infty}\exp\Bigg[\frac{2\cdot x^\frac1n\cdot\ln x\left(-\frac1{n^2}\right)\bigg/\left(2\cdot\sqrt[n]x-1\right)}{-\frac1{n^2}}\Bigg]=\lim_{n\to\infty}\exp\left[\frac{2\cdot\sqrt[n]x\cdot\ln x}{2\cdot\sqrt[n]x-1}\right]=$$ $$=\exp\left[\frac{2\cdot1\cdot\ln x}{2\cdot1-1}\right]=\exp\left[2\cdot\ln x\right]=x^2$$


text:
Q: Determine "average min and max" of a list of values I've got a large dataset of about 1,000 values which represent the flex of a finger (higher s more flexed). The data is collected within 10 seconds. During that time the finger will be repeatedly flexed and made straight.
I need to find the "average range" meaning that I don't need the global minimum and global maximum but the "average minimum and maximum".
I want to use this "average minimum and maximum" to calculate a normalised finger flex which works independently from the absolute flex value.
How can I do that?

A: It is not possible to give an optimal answer to your question without
definitions of terminology 'normalized finger flex' and 'absolute finger flex'. (These are not terms immediately clear to a statistician, and I am curious about the 'independence' you mention.) What do these two terms mean in terms of finger flexing
and why are they important to you?
Also, it would be helpful to see what the data look like: are
neighboring values in the sequence of 1000 near to each other (for
instance, suggesting a sinusoidal curve), and about how many
finger flexes are there in a 10-second period.
Lacking this information I have to guess, and the results of
guessing may not be useful to you. It is a little like asking
a physician to diagnose a disorder if you say on the phone, "Sometimes the
twitch in my left eye is very disturbing."
If the data move fairly regularly up and down about 10 times
in 10 seconds, then you might look for several highest local
maxima (about 10) and average, and to look for several lowest local minima
and average them. Do individual flexes result in widely different
max and min values? Do you want to average over all individual flexes, or only get averages for the several most extreme. (By any definition, there would be ways to automate this search pretty
well, so after deciding an a strategy by by looking at a couple of
data streams of 1000, you could have a computer search
additional such streams.)
Another approach (simpler, more general, possibly less
satisfactory) would be just to average the top 50 values (about) to get
the 'average global maximum' and similarly for the bottom 50
to get the 'average global minimum'. (Of course, "50" is a
mildly educated guess without seeing the data.)
The reason I'd like to know what you mean by 'absolute flex value'
and how you derive that from data, is that your word 'independent'
indicates you want the 'normalized finger flex' to carry
fundamentally different information than the 'absolute flex value'
and I cannot be sure that is true without knowing what
'absolute flex' means.
If this answer sets you on the right track, then please so indicate.
If not, please leave a Comment with more information, and maybe I (or someone else) can do better.


text:
Q: (Java) SQL Query not returning anything at all I've got a problem with my SQLite Database. To bring it to the point: Everything is working (executes / create table / ...) except the queries.
Important: autoCommit = False (But it isn't required for the query function i use)
Here's the code:
---=> Database.class <=---
package me.Syloh.Core;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import me.Syloh.Core.Customized.LOG;

public class Database {

    public static Connection connection;
    public static String path = "plugins/Core.db";

    public static void setup() throws SQLException, ClassNotFoundException {

        Class.forName("org.sqlite.JDBC");
        connection = DriverManager.getConnection("jdbc:sqlite:" + path);
        connection.setAutoCommit(false);

        DatabaseMetaData metadata = connection.getMetaData();
        ResultSet resultset = metadata.getTables(null, null, "%", null);

        List<String> tables = new ArrayList<String>();
        while(resultset.next()) {
            tables.add(resultset.getString(3));
            LOG.info("Table '" + resultset.getString(3) + "' has been found.");
        }

        if(!tables.contains("Bans")) {
            execute("CREATE TABLE Bans (player TEXT, date TEXT, sender TEXT, reason TEXT, ip TEXT, time DOUBLE)");
            LOG.info("Table 'Bans' has been created.");
        }

    }

    public static void execute(String execute) {
        try {

            Statement statement = connection.createStatement();
            statement.execute(execute);
            statement.close();

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

    public static void execute(List<String> execute) {
        try {

            Statement statement = connection.createStatement();
            for(String e : execute) { statement.execute(e); }
            statement.close();

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

    public static ResultSet query(String query) {
        try {

            Statement statement = connection.createStatement();
            ResultSet resultset = statement.executeQuery(query);
            statement.close();
            return resultset;

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

        return null;
    }

    public static void commit() {
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

---=> Main.class <=---

package me.Syloh.Core;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin implements Listener {

    Plugin Core = this;

    @Override
    public void onDisable() {
        Database.commit();
    }

    @Override
    public void onEnable() {

        Bukkit.getServer().getPluginManager().registerEvents(this, this);
        try {
            Database.setup();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Core, new Runnable() {
            public void run() {
                Database.commit();
           }
        }, 60L, 4L);

        Database.execute("INSERT INTO Bans VALUES ('hI', 'a', 'b', 'c', 'd', 1)");
        ResultSet rs = Database.query("SELECT * FROM Bans WHERE player = 'hi'");
        try {
            while(rs.next()) {
                System.out.println(rs.getString("player"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

I've checked out my Database using a SQL Database editor and all inserts were made. But when iam trying to display them, nothing gets displayed at all.
Please help me! Thanks in advance.
Sincerely,
Max

A: The problem is, you are closing the statement, which will automatically close the associated ResultSet:
Statement statement = connection.createStatement();
ResultSet resultset = statement.executeQuery(query);
statement.close();  // This is the problem
return resultset;

From Statement#close() javadoc:

When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

Having said that, you should never pass around your ResultSet object around your methods. This way it would be very difficult to manage resources, as you would have to keep your Statement and ResultSet objects opened accross methods.
You should rather build some data structure in the same method you are getting the ResultSet in, and return that data structure instead.
Also, you should close the resources like, ResultSet, Statement, and Connection in a finally block, so as to ensure they are always closed, even in case of exception.


text:
Q: Error:Cause: com.android.sdklib.repository.FullRevision I wanted to try instant-run from AS 2.0 - for this to work I had to update to build-plugin to 2.0.0-alpha1 - but when doing this I cannot gradle-sync the project anymore as I am getting:
Gradle 'SCR' project refresh failed
  Error:Cause: com.android.sdklib.repository.FullRevision

Anyone knows the reason/workaround for this?

A: In case you want to keep the SDK Manager plugin, you can get the fixed committed version with :
repositories {
    maven { url 'https://jitpack.io' }
}

classpath 'com.github.JakeWharton:sdk-manager-plugin:220bf7a88a7072df3ed16dc8466fb144f2817070'

Not ideal though!

A: Quick answer for anyone in the same situation:
It's Jake Wharton's SDK Manager plugin.
Already fixed: https://github.com/JakeWharton/sdk-manager-plugin/pull/100.
As some of you pointed out, it's been a while since the latest release, so you might want to use the jitpack.io workaround provided in the answer below
(https://stackoverflow.com/a/33889117/1673540)


text:
Q: A witch, a vampire and a pixie meet in a bar and talk about tomatoes eradicating humanity I remember reading a series of books that took place in the Unites States in our time, but some  50 years ago or so there was a problem with genetically modified tomatoes eradicating most of humanity - except the supernatural entities in our world decided that this is their time to shine and help the humans, so they revealed that all those fairy tales we know have always been true.
The story is about a witch who was working for an agency that was trying to fight criminal supernatural creatures. One day she has a job together with a female vampire and a male pixie who were also working for this agency. Somehow they rescue a creature that can help them with a little head-start for their own business and they decide to quit their job at the agency. They talk about this plan in a bar.
Which turns out not to be the greatest idea because this agency doesn't like people quitting.
There were multiple books in this series. What I described was the start of the first one. I've read all of them in German and the word "Blut" (meaning blood) was in the title of every book of the series.
Random stuff I remember from the series:

*

*humans had a deep fear for tomatoes

*supernaturals were immune to the disease of the tomatoes leaving tomatoes something of a delicacy for them

*there were a lot of different creatures throughout the series:

*

*witches

*werewolves

*pixies

*fairies

*demons

*...

*the witch was obsessed with shoes - especially her boots

*after some time the three protagonists moved into a church

*there were some romantic scenes between the witch and the vampire in later books, though they never really got together

I can't remember the name of the series and I haven't finished the series. Can you help me identify what books I am remembering so that I may continue reading the series? I would prefer information about the first book. I think there were about 10 books and I have read maybe 6 or 7 of them, but I am not sure. I've read them a few years back and the newer ones were just getting printed in Germany.

A: The Hollows Series by Kim Harrison
The Tomato-part checks out on this, as well as the titles.
Relevant part from the above wiki:

The alternate history is built upon two premises: the recent open existence of magical and supernatural species, primarily witches, vampires, and werewolves, with the human population; and the historical investment of Cold War military spending in genetic engineering as opposed to the Space Race, which resulted in the accidental release of a genetically modified tomato in the 1960s that killed a significant portion of the human population. The series is set approximately forty years after this plague, referred to as 'The Turn' within the series.

There are 13 books in the series with 12 novellas.
The list of books in publication order are as follows (for the reading order, the author's official website has more information:

*

*Dead Witch Walking

*The Good, The Bad, and The Undead
2.1  Undead in the Garden of Good and Evil (Ivy novella in the Dates From Hell anthology, also in Into the Woods compilation)

*Every Which Way But Dead

*A Fistful of Charms
4.1  Dirty Magic (Mia short story in the Hotter Than Hell anthology, also in Into the Woods compilation)

*For A Few Demons More
5.1  The Bridges of Eden Park (Kisten/Rachel short story in For a Few Demons More(US mass market edition), also in Into the Woods compilation)
5.2  Two Ghosts For Sister Rachel (Robbie/Rachel/Pierce novella in the Holidays Are Hell anthology, also in Into the Woods compilation)

*The Outlaw Demon Wails (retitled Where Demons Dare in the UK)
6.1  The Bespelled (Ceri/Al short story in The Outlaw Demon Wails (US mass market edition), also in the Demons anthology and the Into the Woods compilation)

*White Witch, Black Curse
7.1  Ley Line Drifter (Bis/Jenks novella in Unbound anthology, also in Into the Woods compilation)

*Black Magic Sanction

*Pale Demon
9.1  Blood Work (Graphic novel of Rachel's internship under Ivy at the Inderlander Security)
9.2  The Hollows Insider (The Hollows world book - an overarching new story, character profiles, maps, spell guides, charm recipes, secret correspondence, ... )

*A Perfect Blood
10.1 Million-Dollar Baby (Trent novella an Into the Woods original)
10.2 Blood Crime (Graphic Novel of Rachel's continued interning under Ivy at the IS)
10.3 Trouble on Reserve

*Ever After

*The Undead Pool

*The Witch With No Name
13.1  Sudden Backtrack


text:
Q: Shopware: Store custom field for customer I added this custom field to my customer and to the register form in storefront/component/account/register.html.twig:
<input type="checkbox" class="custom-control-input" id="alumni" name="custom_kw_dau" value="1">

The field is type checkbox. It works fine in the backend but it is not filled during customer registration.

A: You have to manually store it. Subscribe to event and add the field to customFields in the output like this:
public static function getSubscribedEvents(): array
{
    return [
        CustomerEvents::MAPPING_REGISTER_CUSTOMER => 'addCustomField'
    ];
}

public function addCustomField(DataMappingEvent $event): bool
{
    $inputData = $event->getInput();
    $outputData = $event->getOutput();

    $custom_field = (bool)$inputData->get('custom_kw_dau', false);
    $outputData['customFields'] = array('custom_kw_dau' => $custom_field);

    $event->setOutput($outputData);

    return true;
}

A: Yeah you need to subscribe to the event - but I have done it like this instead of the above event, and it works fine as well.

    public static function getSubscribedEvents(): array
    {
        return [
            CustomerRegisterEvent::class => 'onRegister',
            GuestCustomerRegisterEvent::class => 'onRegister'
        ];
    }

    public function onRegister(CustomerRegisterEvent $event): void
    {
        $request = $this->requestStack->getCurrentRequest();
        if ($request) {
            $params = $request->request->all();
            $customer = $event->getCustomer();
            $data = [
                'id' => $customer->getId(),
                'customFields' => [
                    'your_field' => $params['your_field']
                ]
            ];

            $this->customerRepository->update([$data], $event->getContext());
        }
    }

But I think the answer above might be more suitable as it does not require any additional services.


text:
Q: how to get proper labels in a scatter plot multiindex dataframe I have a dataset that looks like this:
dataset = pd.read_csv("dataset.xls", sep='\t',index_col=0)

Nr  TID PID x [pixel]   y [pixel]
1   1   1   266.659 243.028
2   1   2   266.659 243.028
3   1   3   266.659 242.372
4   1   4   266.659 242.372
5   1   5   266.659 242.372
6   1   6   267.972 238.433
7   1   7   267.972 238.433
8   1   8   267.972 237.777
9   2   1   267.315 235.808
10  2   2   267.315 234.495
11  2   3   267.315 234.495
12  2   4   267.972 232.526
13  2   5   267.972 232.526
14  2   6   267.972 231.213
15  2   7   267.972 231.213
16  3   1   267.315 230.556
17  3   2   267.315 230.556
18  3   3   267.972 227.931
19  3   4   267.972 227.931
20  3   5   267.972 227.931
21  3   6   267.972 227.931
22  3   7   267.972 225.962

Using pandas, I converted to a multiindex datrame where the index are TID and PID:
df = dataset.set_index(["TID", "PID"])

TID PID x [pixel]   y [pixel]
1   1   266.659 243.028
1   2   266.659 243.028
1   3   266.659 242.372
1   4   266.659 242.372
1   5   266.659 242.372
1   6   267.972 238.433
1   7   267.972 238.433
1   8   267.972 237.777
2   1   267.315 235.808
2   2   267.315 234.495
2   3   267.315 234.495
2   4   267.972 232.526
2   5   267.972 232.526
2   6   267.972 231.213
2   7   267.972 231.213
3   1   267.315 230.556
3   2   267.315 230.556
3   3   267.972 227.931
3   4   267.972 227.931
3   5   267.972 227.931
3   6   267.972 227.931
3   7   267.972 225.962

If I make a scatter plot, I get this:
plt.scatter(df["x [pixel]"],df["y [pixel]"])

I can extract the TID_index in a list with:
TID_index = df.index.get_level_values("TID").unique()

But when I try to use those indexes as labels, I get a unique label in the plot with the first element of the TID_index:
plt.scatter(df["x [pixel]"],df["y [pixel]"])
plt.legend(TID_index)

My goal is to have every value in TID_index as labels. If you could point me in the right direction, I would really appreciate it.
Thanks in advance.

A: You could use scatterplot from seaborn. The hue argument of the function is used to indicate a grouping variable that will produce points with different color:
import seaborn as sns
sns.scatterplot(df["x [pixel]"], df["y [pixel]"],
                hue=df.index.get_level_values("TID"), legend='full')


text:
Q: Not able to set serializability to false in redux-toolkit I am just trying to call my asyncthunk funtion and signup the user but i am getting this error
I just need to set the serializability to false if there is any other option where where i do  not need to set it to off please recommend.
Error Image

Here is my store.js
    import {
  configureStore,
  createSerializableStateInvariantMiddleware,
  getDefaultMiddleware,
} from "@reduxjs/toolkit";
// import { Iterable } from "immutable";
import authReducers from "./reducers/authReducers";
export default configureStore({
  reducer: {
    auth: authReducers,
    middleware: [
      ...getDefaultMiddleware({
        serializableCheck: false,
      }),
    ],
  },
});

my reducer
import { createSlice } from "@reduxjs/toolkit";
import { createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
export const authSlice = createSlice({
  name: "Auth",
  initialState: {
    name: "",
    email: "",
  },
  reducers: {},
});

export default authSlice.reducer;
// export const { increment } = authSlice.actions;
export const signupUser = createAsyncThunk(
  "auth/signupUser",
  async (payload) => {
    const data = await axios({
      url: "http://fathomless-meadow-37873.herokuapp.com/auth/signup",
      method: "POST",
      data: payload,
    });
    return data;
  }
);

and my signup component
import { Flex, Input } from "@chakra-ui/react";
import React from "react";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { increment } from "../../reducers/authReducers";
import { signupUser } from "../../reducers/authReducers";
import { unwrapResult } from "@reduxjs/toolkit";
import {
  FormControl,
  FormLabel,
  FormErrorMessage,
  FormHelperText,
  InputGroup,
  InputRightElement,
  Button,
  Divider,
  Text,
  useToast,
} from "@chakra-ui/react";
export default function SignUp() {
  const dispatch = useDispatch();
  const toast = useToast();
  const [show, setShow] = useState(false);
  const handleClick = () => setShow(!show);
  const data = useSelector((state) => state.auth.count);
  const [formData, setFomData] = useState({
    username: "",
    email: "",
    password: "",
  });
  //function to set the data entered by the user
  const handleFormData = (event) => {
    setFomData({
      ...formData,

      [event.target.name]: event.target.value,
    });
  };
  const signup = async () => {
    dispatch(signupUser(formData))
      .then(unwrapResult)
      .then((res) => {
        console.log(res);
        toast({
          title: "Account created.",
          description: "We've created your account for you.",
          status: "success",
          duration: 3000,
          isClosable: true,
        });
      })
      .catch((err) => {
        toast({
          title: "Account cannot be created.",
          description: "User already exists",
          status: "error",
          duration: 3000,
          isClosable: true,
        });
      });
  };
  return (
    <Flex>
      <FormControl>
        <Divider mb={4}></Divider>
        <FormLabel>Full Name</FormLabel>
        <Input name="username" onChange={handleFormData} type="text" />
        <FormHelperText>Eg : Jane Doe</FormHelperText>
        <FormLabel mt={3}>Email address</FormLabel>
        <Input name="email" onChange={handleFormData} type="email" />
        <FormHelperText>We'll never share your email.</FormHelperText>
        <InputGroup mt={4} size="md">
          <Input
            pr="4.5rem"
            type={show ? "text" : "password"}
            name="password"
            onChange={handleFormData}
            placeholder="Enter password"
          />
          <InputRightElement width="4.5rem">
            <Button h="1.75rem" size="sm" onClick={handleClick}>
              {show ? "Hide" : "Show"}
            </Button>
          </InputRightElement>
        </InputGroup>

        <Button onClick={signup} colorScheme="purple" w="100%" mt={5}>
          Submit
        </Button>
      </FormControl>
    </Flex>
  );
}

Any help would be appreciated


text:
Q: BigQuery - format_date and year for iso 8601's week According to the bigquery documentation for supported elements for format_date and format_datetime, I didn't find a way to represent the year + week in iso 8601 format; for instance "2017W01". The reason is that there are no operators for getting the year matching the %V week.
For instance the following query will return "2008W01" instead of "2009W01"
SELECT FORMAT_DATE('%YW%V',  DATE '2008-12-29')

With MySQL I would use '%xW%v' format that apparently has no equivalent with bigquery?

A: You need to use %G as per the docs: "%G is the ISO 8601 year with century as a decimal number."
SELECT FORMAT_DATE('%GW%V', DATE '2008-12-29')
Produces: 2009W01


text:
Q: How to Fix AttributeError: module 'botocore.vendored.requests' has no attribute 'Post' Traceback I'm trying to get my LexBot to communicate with Lambda so I followed the process for creating the request, signature and everything needed to do so.
But I am not sure if I need to import certain things from Python. It fails when I'm about to post the message. The signature is created as well as the auth header.
Please advise guys, Any help will be appreciated!
I've used these articles as guidelines:
https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html
https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
print ('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
print ('Request URL = ' + endpoint)
print('\n' + authorization_header)
print('\nX-Amz-content-Sha256 header is' + payload_hash)

r = requests.Post ('myendpoint'+ canonical_uri, data=payload,
headers=headers)
data = r.json()
lex_message = data['message']
print ('' + lex_message)

So I assume my problem is coming from this piece of code, N.b I removed my endpoint.
Also not sure what goes into data in request.

A: I had the same error but for GET using python3.8. Support for GET/POST has already been removed from botocore.vendored.requests in python3.8.
As a workaround, you can use python3.7 for your lambda and it will still work for a while. However you will be getting a warring that support for this will be removed on 2020/03/31 as well:
DeprecationWarning: You are using the put() function from 'botocore.vendored.requests'.  This dependency was removed from Botocore and will be removed from Lambda after 2020/03/31. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.put() function instead.

So there is not much choice as to use pip to get requests package, or use layer as shown in the link below.
More information can be found in Upcoming changes to the Python SDK in AWS Lambda

A: In this pull request they recommend not to use the vendored version of requests
https://github.com/aws-quickstart/taskcat/pull/343 anymore. unfortunately many AWS code examples still use it.
You can use the official 'requests' library (https://requests.readthedocs.io/en/master/) instead by substituting:
from botocore.vendored import requests

with
import requests

A: Here is an example from AWS that shows how to use urllib3 library to achieve the same https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html
Putting the relevant parts here, in case the link goes stale:

import urllib3
...

http = urllib3.PoolManager()

responseBody = { 'foo': 'bar' }

json_responseBody = json.dumps(responseBody)

headers = { ... }

try:
    response = http.request('PUT', responseUrl, headers=headers, body=json_responseBody)

    print("Status code:", response.status)

except Exception as e:

    handle error

P.S. I've tested, the code works out of the box with Python 3.9 Lambda Runtime, with no need to install extra packages


text:
Q: How do i print the else if none of the if's is True? I am trying to print things that you can be eligible for, and if you are not eligible for any of them, I'm trying to print that you are not eligible for any of them. But with this code, it always prints the else along with the if's
PS: I started programming 1 month ago.
print('Task 2')
print()
name = str(input('Navn: '))
age = int(input('Age: '))
gender = str(input('Gender (f for female, m for male): '))
children = int(input('How many children: '))
repute = int(input('repute, on a scale from 1(bad) to 9(immaculate): '))
record = str(input('record (done time/convicted/suspect/clean): '))
seniority = int(input('seniority (years): '))
print()
member = gender == 'f' and age >= 20 and repute <= 7
solder = gender == 'f' and age >= 20 and age <= 30 and repute <= 7 and children == 0
sargent = gender == 'f' and age >= 20 and age <= 30 and repute <= 7 and children == 0 and seniority >= 4 and record != 'clean'
captain = gender == 'f' and age >= 20 and age <= 40 and repute <= 7 and seniority >= 6 and record == ('done time' or 'convicted')
commander = gender == 'f' and age >= 20 and age <= 40 and repute <= 3 and seniority >= 6 and record == ('done time' or 'convicted')
president = gender == 'f' and age >= 20 and age <= 40 and repute <= 2 and seniority >= 8 and record == ('done time' or 'convicted') and name != 'kim'
print('You are eligible to become:')
if member == True:
    print('Member')
if solder == True:
    print('Solder')
if sargent == True:
    print('Sargent')
if captain == True:
    print('Captain')
if commander == True:
    print('Commander')
if president == True:
    print('President')
else:
    print('You are not eligible to be a member')

A: Use a final if condition to check if none of the conditions matched instead of an else:
if member == True:
    print('Member')
if solder == True:
    print('Solder')
if sargent == True:
    print('Sargent')
if captain == True:
    print('Captain')
if commander == True:
    print('Commander')
if president == True:
    print('President')
if not (member or solder or sargent or captain or commander or president):
    print('You are not eligible to be a member')

EDIT: Modified to print all eligible positions.

A: you could replace
else:
    print('You are not eligible to be a member')

with
if all([not cond for cond in [member, soldier, sargent, captain, commander, president]]):
    print('You are not eligible to be a member')

or even with this as comment suggested, using a generator expression, for theoretical better performance
if all(not cond for cond in [member, soldier, sargent, captain, commander, president]):
    print('You are not eligible to be a member')

A: Just one more option, So, if you have to add more possibilities, you just insert them in the middle and not have to change any other statement.
msg = []
if member:
  msg.append('Member')
if solder:
  msg.append('Soldier')
..
..
if new_possibility:
   msg.append('blah')

if msg:
   print print '\n'.join(msg)
else:
   print 'Not elligible'

A: Another options is to use a mapping to determine and print. Allows for modulation.
positions = {"Member":member, "Soldier":soldier, "Sargent":sargent, "Captain":captain, "Commander":commander, "President":president}

for i in positions:
    avail_positions = 0 # a counter to determine if we are eligible for anything
    if positions[i]:
        avail_positions += 1
        print('You are eligible to become: {}'.format(i))

if avail_positions == 0:
    print('You are not eligible to be a member')


text:
Q: how to open a listview item on a new page How to display an item on a new page by clicking on the item

A: You have to register ItemSelected event handler for you ListView.
ListView listViewJson = new ListView();
listViewJson.HasUnevenRows = true;
listViewJson.ItemSelected += listViewJson_ItemSelected;

In Event Handler, you can get selected item.
private void listViewJson_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
    var item = e.SelectedItem;

    // Navigate to new page
    Navigation.PushAsync(new YOUR_PAGE(item));
}

And you can develop UI as you want in you new page for displaying a joke.
UPDATE
You detail page should be like this. I prepared this very roughly. Please make necessary changes.
namespace JokesListView
 {
    public class JokeDetail : ContentPage
    {

        private Joke jk;

       public JokeDetail(Joke j)
       {
          jk = j;

          Display();
       }

       public void Display()
       {
          try
          {
            Label lblJoke = new Label();
            lblJoke.LineBreakMode = LineBreakMode.WordWrap;

             lblJoke.Text = jk.joke;

             Content = lblJoke;
         }
         catch (Exception e)
         {
            throw e;
         }
     }

 }


text:
Q: which include file has contain "wxEVT_WEBVIEW_LOADED" macro? erlang 24.3.3 is used.
From the 24.3.3 document, the wx version is 2.1.3.
I have find 2.1.3's wx.hrl and it doesn't contain the wxEVT_WEBVIEW_LOADED and wxEVT_WEBVIEW_ERROR.
But in the doc, it says

Many of the methods in wxWebView are asynchronous, i.e. they return
immediately and perform their work in the background. This includes
functions such as loadURL/2 and reload/2. To receive notification of
the progress and completion of these functions you need to handle the
events that are provided. Specifically wxEVT_WEBVIEW_LOADED notifies
when the page or a sub-frame has finished loading and
wxEVT_WEBVIEW_ERROR notifies that an error has occurred.

My code is as follows:
Ad = wxWebView:new(Frame,?wxID_ANY,[{size,{1000,1000}}]),
lager:debug("_ad_1082:\t~p",[Ad]),
ok = wxWebView:loadURL(Ad,"http://www.baidu.com"),
wxFrame:connect(Ad, ?wxEVT_WEBVIEW_LOADED,[{callback,fun chair_launch_frame:update_webview/2},
                               {userData,{?CONST_FRAME_MAIN_AD_PRODUCER,Frame}}]),
wxFrame:connect(Ad, ?wxEVT_WEBVIEW_ERROR,[{callback,fun chair_launch_frame:update_webview/2},
                                {userData,{?CONST_FRAME_MAIN_AD_PRODUCER,Frame}}]),

The compiler give error messsage undefined macro 'wxEVT_WEBVIEW_LOADED'


text:
Q: Error while upgrading to MarkLogic 9.0-3 After uninstalling version 7, I am trying to run the command -
yum install /path/to/MarkLogic-rpm-file

but receiving following error -
Error: Package: MarkLogic-9.0-3.1.x86_64 (/MarkLogic-9.0-3.1.x86_64)
           Requires: libc.so.6(GLIBC_2.14)(64bit)
Error: Package: MarkLogic-9.0-3.1.x86_64 (/MarkLogic-9.0-3.1.x86_64)
           Requires: libc.so.6(GLIBC_2.14)
Error: Package: MarkLogic-9.0-3.1.x86_64 (/MarkLogic-9.0-3.1.x86_64)
           Requires: libstdc++.so.6(GLIBCXX_3.4.15)(64bit)

I have already run yum install update and yum -y update glibc. I'm running centos 64 bit virtual box. The one that is provided my MarkLogic University for grooming.

A: You do not give much information about OS - all helpful information...
But lets start with a basic sanity check: you are running this on a 64 bit machine, right? I ask this because glibc errors are predictable because of requirements, but I would expect an error on the 32 bit version.
If we have passed that step, then see below:
Please refer to this page:
https://docs.marklogic.com/guide/installation/intro
You will see a table of notes per OS. You do not clarify CentOs or RHEL in your description, but they are both noted.
Among one of the requirements, you will see that the 32 bit version of glibc is required. For CentOS, for example, this is simple because they make  both 64 and 32 bit versions available. I suggest you try: yum install glibc.i686
If that does not get you over the hump, then please add a bit more details to your post related to OS, etc..

A: I typically run this yum command as part of my mlvagrant scripts that automate MarkLogic deployment:
yum -y install glibc.i686 gdb.x86_64 redhat-lsb.x86_64 cyrus-sasl cyrus-sasl-lib cyrus-sasl-md5

Next to the link shared by David, you can also review OS requirements from here:
http://developer.marklogic.com/products/marklogic-server/requirements-9.0
HTH!


text:
Q: I am not gettin how to get rid of error here #include <iostream>

using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node()
    {
        data = NULL;
        left = right = NULL;
    }
};

Node* insertBST(Node* root, int value)
{
    if (root == NULL) {
        root->data = value;
        root->left = root->right = NULL;
    }
    if ((root->data) > value)
        insertBST(root->left, value);
    if ((root->data) < value)
        insertBST(root->right, value);
}

Node* printBST(Node* root)
{
    if (root != NULL) {
        printBST(root->left);
        cout << "\n" << root->data;
        printBST(root->right);
    }
}

int main()
{
    Node* root = new Node;
    insertBST(root, 30);
    insertBST(root, 20);
    insertBST(root, 40);
    insertBST(root, 70);
    insertBST(root, 60);
    insertBST(root, 80);
    printBST(root);
}

Above is the code which I wrote to implement Binary Search Tree. When I execute it, the program stops responding and closes. I tried getting help from pythontutor.com but I am not able to tackle it.What should I do to make it run without error?
here is where it stops : Click to see
Any help is appreciated,I am new to writing program.

A: In insertBST in the case of root == NULL you do not create a new node and attempt to modify the contents of root, as this is null it should result in an access violation or segmentation fault.
I think the reason your program is hanging instead of crashing is that you are using an online compiler that ignores invalid writes and instead allows the program to continue. This then possibly ends up with infinite recursion through the insertBST function.
To fix this you need to allocate a new node, one way would be as follows:
void insertBST(Node*& root, int value)
{
    if (root == NULL) {
        root = new Node();
        root->data = value;
        root->left = root->right = NULL;
    }
    if ((root->data) > value)
        insertBST(root->left, value);
    if ((root->data) < value)
        insertBST(root->right, value);
}

Note that your program leaks all the nodes that it allocates. You should write a destructor in Node which deletes all child nodes and call delete root at the end of your program. Alternatively don't use raw pointers at all and use std::shared_ptr or std::unique_ptr instead.


text:
Q: Using BufferedReader.readLine() with sockets and stuck in an infinite loop I'm working on a basic TCP server and I've come to the point that I need to handle all incoming lines from the client (the browser) and I've made this loop to detect wether it is GET or HEAD or if-modified-since or whatever I'd want to add to detect.
while ((acumulador = sEntrada.readLine()) != null) {
            if (acumulador.startsWith("GET") || acumulador.startsWith("HEAD")) {
                recibido = acumulador;
                System.out.println("SERVIDOR: Recibido " + acumulador);
                //Troceamos la entrada en tres
                StringTokenizer tokens = new StringTokenizer(acumulador);
                while (tokens.hasMoreTokens()) {
                    aux.add(tokens.nextToken());
                }
                tipo = aux.get(0);
                archivo = aux.get(1);
                version = aux.get(2);
            } else if (acumulador.toLowerCase().startsWith("if-modified-since")) {
                StringTokenizer tokens = new StringTokenizer(acumulador);
                while (tokens.hasMoreTokens()) {
                    aux2.add(tokens.nextToken());
                }

            } else {
                System.out.println("SERVIDOR: Recibido " + acumulador);
            }

        }

The problem is that this is the output:
SERVIDOR: Conexion establecida con /127.0.0.1 al puerto 5000
SERVIDOR: Recibido GET / HTTP/1.1
SERVIDOR: Recibido Host: 127.0.0.1:5000
SERVIDOR: Recibido Connection: keep-alive
SERVIDOR: Recibido Cache-Control: max-age=0
SERVIDOR: Recibido Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
SERVIDOR: Recibido User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22
SERVIDOR: Recibido Accept-Encoding: gzip,deflate,sdch
SERVIDOR: Recibido Accept-Language: es,en-US;q=0.8,en;q=0.6
SERVIDOR: Recibido Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
SERVIDOR: Recibido Cookie: __utma=1.1831406279.1361823043.1361997547.1362010032.7; __utmc=1; __utmz=1.1361823043.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
SERVIDOR: Recibido

It looks good, right? It reads everything like I want it to read but the problem is that it does not stop reading, the client never receives anything back from my server because the server never gets out of that loop, like .ReadLine() never got back 'null' and stopped.
What am I doing wrong?

A: If the server never got null, the client never closed the connection.


text:
Q: swift - using replaceRange() to change certain occurrences in a string Say I have a string, and I want to change the first "a" in that string to an "e" in order to get the correct spelling.
let animal = "elaphant"

Using stringByReplacingOccurrencesOfString() will change every "a" in that string to an "e", returning:
elephent

I am trying to get the index of the first "a" and then replacing it using replaceRange(), like so:
let index = animal.characters.indexOf("a")
let nextIndex = animal.startIndex.distanceTo(index!)
animal = animal.replaceRange(animal.startIndex.advancedBy(nextIndex)..<animal.startIndex.advancedBy(1), with: "e")

However, this code gives me the following error:
Cannot assign value of type '()' to type 'String'

I have been trying to find a way to convert nextIndex into an Int, but I feel like I've got this whole method wrong. Help?

A: This is is what you want to do:
var animal = "elaphant"
if let range = animal.rangeOfString("a") {
  animal.replaceRange(range, with: "e")
}

rangeOfString will search for the first occurrence of the provided substring and if that substring can be found it will return a optional range otherwise it will return nil.
we need to unwrap the optional and the safest way is with an if let statement so we assign our range to the constant range.
The replaceRange will do as it suggests, in this case we need animal to be a var.

A: update:
Swift 4.2 or later
var animal = "elaphant"
if let index = animal.firstIndex(of: "a") {
    animal.replaceSubrange(index...index, with: ["e"])
}

We can extend RangeReplaceableCollection Protocol and create our own replaceFirstOccurrence(of: Element) method:
extension RangeReplaceableCollection where Element: Equatable {
    mutating func replaceFirstOccurrence(of element: Element, with replacement: Element) {
        guard let index = firstIndex(of: element) else { return }
        replaceSubrange(index...index, with: CollectionOfOne(replacement))
    }
    func replacingFirstOccurrence(of element: Element, with replacement: Element) -> Self {
        var elements = self
        elements.replaceFirstOccurrence(of: element, with: replacement)
        return elements
    }
}

var animal = "elaphant"

// non mutating method
print(animal.replacingFirstOccurrence(of: "a", with: "e"))  // elephant
print(animal)     // still "elaphant"

// mutating method
animal.replaceFirstOccurrence(of: "a", with: "e")
print(animal)    // mutated to "elephant"

A: Tested in Playground:
var animal = "elaphant"
if let range = animal.rangeOfString("a") {
animal.replaceRange(range, with: "e")
}

print (animal)

A: Swift4
var animal = "elaphant"

if let index = animal.index(of: "a") {
    animal.replaceSubrange(index...index, with: "e")
}

print (animal) // elephant


text:
Q: Restore-DfsrPreservedFiles on a remote machine I'm trying to restore preexisting files on a DFS share on Server2012r2. No matter what I do, I get this response. This occurs even if I use -RestoreToPath or if I try to run it with the local admin account.
PS E:\> Restore-DfsrPreservedFiles -Path "E:\share\DfsrPrivate\PreExistingManifest.xml" -RestoreToOrigin -Force

Restore-DfsrPreservedFiles : Access to path E:\share\DfsrPrivate\PreExisting\username\Data aplikací\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar was denied.

The issue seems to be the fact, that the administrator doesn't have the permissions to access some AppData stuff. However the DFS service moved it to PreservedFiles without an issue, so there has got to be some way of doing this.
I need for Restore-DfsrPreservedFiles to work in a sudo rsync -a kind of way.
Or at least make it move anything it can access while ignoring errors.

A: After finding out the original files were in SHARE\DfsrPrivate\PreExisting\ and only the direct contents had malformed names in a "nice" way, I decided to just move it in file explorer and rename the folders with a regex in powershell. Seems to have worked.


text:
Q: PDO does not recognize column with special character I'm trying to create an application with SimpleMVC (PHP Framework) and in the database there is a column with the name "contraseña".
When trying to make any query in this column, the PDO returns this error:
SQLSTATE [HY093]: Invalid parameter number: parameter was not defined

There is how to make the PDO recognize special characters?
Controller:
$servidor = array(
 'cuenta' => $usuario,
 'contraseña' => $senha,
 'ipRegistro' => $ip,
 'apodo' => $apelido
);
$this->_model->insert_server($servidor);

Model:
public function insert_server($data) {
 $this->_db->insert("cuentas",$data);
}

Link to the SimpleMVC Framework: PHP Framework - SimpleMVC

A: Wrap the column bame in backticks, like so:
$servidor = array(
 'cuenta' => $usuario,
 '`contraseña`' => $senha,
 'ipRegistro' => $ip,
 'apodo' => $apelido
);

Might be something worth mentioning to the SimpleMVC developers.


text:
Q: PointlnPolygon function not processing multiple objects from JSON Array var polyLat = new Array();
polyLat[0]=10.194027;
polyLat[1]=10.200000;
polyLat[2]=10.200000;
polyLat[3]=10.226975;
polyLat[4]=10.243501;
polyLat[5]=10.254458;
polyLat[6]=10.304448;
polyLat[7]=10.269654;
polyLat[8]=10.161533;
polyLat[9]=10.059987;
polyLat[10]=10.002248;
polyLat[11]=9.920747;
polyLat[12]=9.885241;
polyLat[13]=9.854925;
polyLat[14]=9.853784;
polyLat[15]=9.835443;
polyLat[16]=9.899107;
polyLat[17]=9.948692;
polyLat[18]=9.993088;
polyLat[19]=10.029430;
polyLat[20]=10.046396;
polyLat[21]=10.063923;
polyLat[22]=10.081425;
polyLat[23]=10.072854;
polyLat[24]=9.992266;
polyLat[25]=9.972824;
polyLat[26]=10.010875;
polyLat[27]=10.141595;
polyLat[28]=10.194027;//First point repeated to close polygon
var polySides = (polyLat.length)-1;//number of points in polygon
//vertical Longitude coordinates of polygon
var polyLng =  new Array();
polyLng[0] =76.201205;
polyLng[1] =76.266667;
polyLng[2] =76.316667;
polyLng[3] =76.375022;
polyLng[4] =76.394118;
polyLng[5] =76.401347;
polyLng[6] =76.626291;
polyLng[7] =76.687660;
polyLng[8] =76.767483;
polyLng[9] =76.775730;
polyLng[10] =76.778940;
polyLng[11] =76.681244;
polyLng[12] =76.631163;
polyLng[13] =76.584336;
polyLng[14] =76.493901;
polyLng[15] =76.411473;
polyLng[16] =76.368070;
polyLng[17] =76.379645;
polyLng[18] =76.397007;
polyLng[19] =76.385622;
polyLng[20] =76.365176;
polyLng[21] =76.362383;
polyLng[22] =76.317492;
polyLng[23] =76.281544;
polyLng[24] =76.267905;
polyLng[25] =76.244195;
polyLng[26] =76.215773;
polyLng[27] =76.178283;
polyLng[28] =76.201205;//First point repeated to close polygon
//Coordinates for bounding box
var maxLat = Math.max.apply(null,polyLat);
var minLat = Math.min.apply(null,polyLat);
var maxLng = Math.max.apply(null,polyLng);
var minLng = Math.min.apply(null,polyLng);

setInterval(function(){ob();},10000);

function ob()

{

$.post('outboundupd.jsp',
        {
    mx_lat:maxLat,
    mn_lat:minLat,
    mx_lng:maxLng,
    mn_lng:minLng,
    ply_sds:polySides
        },
        function(response,status,xhr)
        {

            plotdata(response);

});

}
    function plotdata(response)
    {
        var k;
        var x;
        var y;
        var mob;
        var jsonArray=JSON.parse(response.trim());
        var oblen= jsonArray.length;
        var obj;
        for(k=0;k<oblen;k++)
        {
            obj=jsonArray[k];
            pcode= obj.Pcode;
            nplate= obj.N_plate;
            driver= obj.Driver;
            mob= obj.MobileNu;
            x= obj.Latitude;
            y= obj.Longitude;
            time= obj.Time;
            console.log(obj);
        }

        var j = polySides-1 ;
          oddNodes = 0;
          for (i=0; i<polySides; i++) {
            if (polyLng[i]<y && polyLng[j]>=y  ||  polyLng[j]<y && polyLng[i]>=y) {
                if (polyLat[i]+(y-polyLng[i])/(polyLng[j]-polyLng[i])*(polyLat[j]-polyLat[i])<x)  {
                    oddNodes=!oddNodes;
                }
            }
           j=i; }

            if(oddNodes!=true)
            {

                $.post('obsouth.jsp',
                        {

                    pcd:pcode,
                    npt:nplate,
                    drv:driver,
                    mobl:mob,
                    lat:x,
                    lon:y,
                    tm:time

                        },
                        function(response,status,xhr)
                        {
                            response.trim();

                });

            }

          return oddNodes;

    }

in the above code, am getting multiple values from the JSON array in the function plotdata(response) and able to retrieve it using for loop but on passing it to the pointpolygon math equation defined on following line, am able to get only single set of data.
how to get all the values obtained in loop process the pointpolygon function?

A: You require the pointInPolygon()in the for() loop. As it is it only checks the last value of JSON array.
for(k=0;k<oblen;k++)
    {
        obj=jsonArray[k];
        pcode= obj.Pcode;
        nplate= obj.N_plate;
        driver= obj.Driver;
        mob= obj.MobileNu;
        x= obj.Latitude;
        y= obj.Longitude;
        time= obj.Time;
        console.log(obj);
        //pointInPolygon  HERE
    }


text:
Q: I'm writing a calendar program in java, but besides oct 2015 the months dont match, i need help please So basicaly, everything works like it should. But the main thing that should be correct, which is the date, is wrong, so far for october 2015 it is correct but for some reason i cannot detect, the other months i have tried so far are incorrect when compared to the calendar in my computer.
Here is my program, maybe you have some valid input to help me with these issues.
    public static boolean isLeapYear(int year) {
        int month = 0;
        int s = getDaysIn(month, year);
        return year % 4 == 0 && (year % 100 != 0) || (year % 400 == 0);
    }

    public static int getDaysIn(int month, int year) {
        switch (month) {
            case 1:
                return 31;
            case 2:
                if (isLeapYear(month)) {
                    return 29;
                } else {
                    return 28;
                }
            case 3:
                return 31;
            case 4:
                return 30;
            case 5:
                return 31;
            case 6:
                return 30;
            case 7:
                return 31;
            case 8:
                return 31;
            case 9:
                return 30;
            case 10:
                return 31;
            case 11:
                return 30;
            case 12:
                return 31;
            default:
                return -1;
        }
    }

    public static String getMonthName(int month) {
        switch (month) {
            case 1:
                return "January";
            case 2:
                return "February";
            case 3:
                return "March";
            case 4:
                return "April";
            case 5:
                return "May";
            case 6:
                return "June";
            case 7:
                return "July";
            case 8:
                return "August";
            case 9:
                return "September";
            case 10:
                return "October";
            case 11:
                return "November";
            case 12:
                return "December";
            default:
                return "Invalid month.";
            }
        }

    public static int getStartDay(int month, int year) {
        int days = 0;

        for (int i = 1900; i < year; i++) {
            days = days + 365;
            if (isLeapYear(i)) {
                days = days + 1;
            }
        }
        for (int i = 1; i < month; i++) {
            days = days + getDaysIn(month, year);
        }
        int startday = (days + 1) % 7 + 2;
        return startday;
    }

    public static void displayCalendar(int month, int year) {
        String monthName = getMonthName(month);
        int startDay = getStartDay(month, year);
        int monthDays = getDaysIn(month, year);

        System.out.println("   Sun   Mon   Tue   Wed   Thu   Fri       Sat");
        int weekDay = startDay - 1;
        for (int i = 1; i < startDay; i = i + 1) {
            System.out.print("      ");
        }
        for (int x = 1; x <= monthDays; x++) {
            weekDay = weekDay + 1;
            if (weekDay > 7) {
                System.out.println();
                weekDay = 1;
            }
            System.out.format("   %3d", x);
        }
        if (weekDay > 7) {
            System.out.println();
        }
    }

A: Your getStartDay is actually where your error lays :
    for (int i = 1; i < month; i++) {
        days = days + getDaysIn(month, year);
    }
    int startday = (days + 1) % 7 + 2;
    return startday;

Should be replaced with :
    for (int i = 1; i < month; i++) {
        days = days + getDaysIn(i, year);
    }
    int startday = (days % 7) + 2;
    return startday;

There is a minor problem with your loop as you see.
You should have had used your incrementor i in your getDaysIn calls to count the days from the begin of the year until the month you want to display.

Second error is here :
    int startday = (days + 1) % 7 + 2;

The logic behind this expression is still a mystery for me.
Let's break this off with a concrete example :
Let's say we want to display FEB 1900. Easy to do because we start at the begin of JAN 1900 so we can count the days easily (31 days in january so days = 31)
Which result will the first expression return?
= (31 + 1) % 7 + 2
= 32 % 7 + 2
= 4 + 2
= 6

Because day 1 in your logic is SUNDAY, day 6 is FRIDAY.
Let's check it out :

Not really the expected result right?
I see one more problem with this method.
Let's imagine days = 33 (this will never happens but we need this example here).
= (33 + 1) % 7 + 2
= 34 % 7 + 2
= 6 + 2
= 8

What would the 8th day of the week be?

The explanation of the correct answer is the following :
(days % 7) + 2

days % 7 gives us the value of the last day of the following month when weeks begin with MONDAY.
To this value, we add 2 :

*

*1 to have the beginning day of the wanted month.

*1 because our calendar begins with sunday and we'll have to slide our days on the calendar view.

Here is the full code (that I also modified a bit to make it more compact) :
    public class Calendar{

    public static void main(String[] args) {
        // INSERT YOUR TESTS HERE
    }

    public static boolean isLeapYear(int year) {
        return year % 4 == 0 && (year % 100 != 0) || (year % 400 == 0);
    }

    public static int getDaysIn(int month, int year) {
        switch (month) {
            case 1 : case 3 : case 5 : case 7 : case 8 : case 10 : case 12 :
                return 31;
            case 4 : case 6 : case 9 : case 11 :
                return 30;
            case 2:
                return isLeapYear(year) ? 29 : 28;
            default:
                return -1;
        }
    }

    public static String getMonthName(int month) {
        String[] months = {"January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"};

        return month <= 12 && month > 0 ? months[month - 1] : "Invalid month";
    }

    public static int getStartDay(int month, int year) {
        int days = 0;

        for (int i = 1900; i < year; i++) {
            days += 365;
            if (isLeapYear(i)) {
                days = days + 1;
            }
        }

        for (int i = 1; i < month; i++) {
            days = days + getDaysIn(i, year);
        }
        int startday = (days % 7) + 2;
        return startday;
    }

    public static void displayCalendar(int month, int year) {
        String monthName = getMonthName(month);
        int startDay = getStartDay(month, year);
        int monthDays = getDaysIn(month, year);

        System.out.println("   Sun   Mon   Tue   Wed   Thu   Fri   Sat");
        int weekDay = startDay - 1;
        for (int i = 1; i < startDay; i = i + 1) {
            System.out.print("      ");
        }
        for (int x = 1; x <= monthDays; x++) {
            weekDay = weekDay + 1;
            if (weekDay > 7) {
                System.out.println();
                weekDay = 1;
            }
            System.out.format("   %3d", x);
        }
        if (weekDay > 7) {
            System.out.println();
        }
    }

}

EDIT
You should try to write something in your main method if nothing displays.
public static void main(String[] args) {
    for (int i = 0 ; i < 5 ; i++){
        System.out.println(getMonthName(i+1) + " " + (2010 + i));
        displayCalendar(i+1, 2010 + i);
        System.out.println();
    }
}

Gives the following output :
    January 2010
   Sun   Mon   Tue   Wed   Thu   Fri   Sat
                                   1     2
     3     4     5     6     7     8     9
    10    11    12    13    14    15    16
    17    18    19    20    21    22    23
    24    25    26    27    28    29    30
    31
February 2011
   Sun   Mon   Tue   Wed   Thu   Fri   Sat
                 1     2     3     4     5
     6     7     8     9    10    11    12
    13    14    15    16    17    18    19
    20    21    22    23    24    25    26
    27    28
March 2012
   Sun   Mon   Tue   Wed   Thu   Fri   Sat
                             1     2     3
     4     5     6     7     8     9    10
    11    12    13    14    15    16    17
    18    19    20    21    22    23    24
    25    26    27    28    29    30    31
April 2013
   Sun   Mon   Tue   Wed   Thu   Fri   Sat
           1     2     3     4     5     6
     7     8     9    10    11    12    13
    14    15    16    17    18    19    20
    21    22    23    24    25    26    27
    28    29    30
May 2014
   Sun   Mon   Tue   Wed   Thu   Fri   Sat
                             1     2     3
     4     5     6     7     8     9    10
    11    12    13    14    15    16    17
    18    19    20    21    22    23    24
    25    26    27    28    29    30    31


text:
Q: JavaFX: Cannot dunamically update GridPane OK here is a tough one that has been driving me nuts for a couple of days now...
I have two stages:
A users administration stage (Controller: UsersAdminController.java)

with the following element hierarchy:

and a User addition stage: (Controller: AddUserController.java)

As a child to the scroll pane of the upper anchor pane of the users admin stage (see elements hierarchy) I add during initialization of the UsersAdminController a GridPane intended to list the users of the system as described here
When I add a user through the user addition screen, I try to update the GridPane of the Users Administration stage by getting a reference to the UsersAdminController and then calling a method that updates its contents.
However, the GridPane CANNOT BE UPDATED. (I seem unable to perform any gui-related action to the scroll pane neither the gridpane although I manage to get a reference to the relevant controller.
Code:
Here is how the gridpane is (correctly) initialized through the initialize method of the UsersAdminController:
public void initialize(URL location, ResourceBundle resources) {
    gridPaneNonSudoUsers = new GridPane();
    gridPaneNonSudoUsers.setId("gridPaneNonSudoUsers");
    // setting column widths for the grid pane
    gridPaneNonSudoUsers.getColumnConstraints().add(new ColumnConstraints(145));
    gridPaneNonSudoUsers.getColumnConstraints().add(new ColumnConstraints(85));
    gridPaneNonSudoUsers.getColumnConstraints().add(new ColumnConstraints(210));
    gridPaneNonSudoUsers.getColumnConstraints().add(new ColumnConstraints(150));

    srcPaneUsers.setContent(gridPaneNonSudoUsers);
    gridPaneNonSudoUsers.setAlignment(Pos.CENTER);

    displayNonSudoUsers(getSystemNonSudoUsers());
}

Here is the displayNonSudoUsers that populates the GridPane
public void displayNonSudoUsers(ArrayList nonSudoUsers) {
    // adding some space between lines
    gridPaneNonSudoUsers.setVgap(15);

    Label lblHeaderUsername = new Label("Username");
    lblHeaderUsername.setPadding(new Insets(0, 0, 0, 20));
    lblHeaderUsername.setId("lblHeaderUsername");
    Label lblHeaderIsProtected = new Label("Προστασία");
    lblHeaderIsProtected.setId("lblHeaderIsProtected");
    GridPane.setHalignment(lblHeaderUsername, HPos.LEFT);
    GridPane.setHalignment(lblHeaderIsProtected, HPos.CENTER);

    // adding header elements to GridPane
    GridPane.setColumnIndex(lblHeaderUsername, 0);
    GridPane.setRowIndex(lblHeaderUsername, 0);
    GridPane.setColumnIndex(lblHeaderIsProtected, 1);
    GridPane.setRowIndex(lblHeaderIsProtected, 0);
    gridPaneNonSudoUsers.getChildren().addAll(lblHeaderUsername,
            lblHeaderIsProtected);

    // adding users
    int i = 1; // starting from 2nd row given that 1st row belongs to
                // headers
    for (NonSudoUser nsuser : nonSudoUsers) {

        /**** Label ****/
        String username = nsuser.getUsername();
        Label lblUsername = new Label(username);
        lblUsername.setPadding(new Insets(5, 0, 5, 20));
        lblUsername.setId("lbl" + username);
        GridPane.setHalignment(lblUsername, HPos.LEFT);

        /**** Image ****/
        boolean isProtected = nsuser.isProtected();
        ImageView imgIsProtected = new ImageView(
                isProtected ? "/resources/media/notOK.png"
                        : "/resources/media/ok.png");
        imgIsProtected.setFitHeight(20);
        imgIsProtected.setFitWidth(20);
        imgIsProtected.setId("img" + username);
        GridPane.setHalignment(imgIsProtected, HPos.CENTER);

        /**** Button for protection ****/
        Button btnSetProtected = new Button("Ενεργοποίηση Προστασίας");
        btnSetProtected.setId("btnProt" + username);
        btnSetProtected.setDisable(!isProtected);
        GridPane.setHalignment(btnSetProtected, HPos.CENTER);

        /**** Button for deletion ****/
        Button btnDeleteUser = new Button("Διαγραφή Χρήστη");
        btnDeleteUser.setId("btnDel" + username);
        GridPane.setHalignment(btnDeleteUser, HPos.CENTER);
        // delete user in a seperate thread
        btnDeleteUser.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                Action response = Dialogs
                        .create()
                        .owner(root)
                        .title("ΔΙΑΓΡΑΦΗ ΧΡΗΣΤΗ")
                        .masthead(
                                "ΠΡΟΣΟΧΗ! ΠΡΟΚΕΙΤΑΙ ΝΑ ΔΙΑΓΡΑΨΕΤΕ ΤΟ ΧΡΗΣΤΗ: "
                                        + username)
                        .message("ΕΙΣΑΣΤΕ ΣΙΓΟΥΡΟΙ?")
                        .actions(Dialog.ACTION_OK, Dialog.ACTION_CANCEL)
                        .showConfirm();
                if (response == Dialog.ACTION_CANCEL)
                    return;
                Task<Void> task = new Task<Void>() {
                    @Override
                    public Void call() throws Exception {
                        String username = ((Button) event.getSource())
                                .getId();
                        LinuxCommand lc = new LinuxCommand("userdel", "-r",
                                username);
                        lc.execute();
                        return null;
                    }
                };
                task.setOnFailed(new EventHandler<WorkerStateEvent>() {
                    public void handle(WorkerStateEvent t) {
                        System.out.println("FAILURE deleting  " + username);
                    }
                });
                task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                    public void handle(WorkerStateEvent t) {
                        Platform.runLater(new Task<Void>() {
                            @Override
                            public Void call() throws Exception {
                                ArrayList<Node> toErase = new ArrayList<Node>();
                                for (Node nodeToErase : gridPaneNonSudoUsers
                                        .getChildren()) {
                                    if (nodeToErase.getId().endsWith(
                                            username))
                                        toErase.add(nodeToErase);
                                }
                                gridPaneNonSudoUsers.getChildren()
                                        .removeAll(toErase);
                                // rearrangeGridPane(); - TBD
                                return null;
                            }
                        });
                    }
                });
                executorUserDeletion.submit(task);
            }
        });

        // adding user-related gui items
        GridPane.setColumnIndex(lblUsername, 0);
        GridPane.setRowIndex(lblUsername, i);

        GridPane.setColumnIndex(imgIsProtected, 1);
        GridPane.setRowIndex(imgIsProtected, i);

        GridPane.setColumnIndex(btnSetProtected, 2);
        GridPane.setRowIndex(btnSetProtected, i);

        GridPane.setColumnIndex(btnDeleteUser, 3);
        GridPane.setRowIndex(btnDeleteUser, i);

        gridPaneNonSudoUsers.getChildren().addAll(lblUsername,
                imgIsProtected, btnSetProtected, btnDeleteUser);
        i++;
    }
}

And here is the method that is called on action of the ADD USER BUTTON of the User Addition Stage
    public void createUser() throws UserCreationException {

        String username, password1, password2;
        username = txtUsername.getText();
        password1 = txtPassword1.getText();
        password2 = txtPassword2.getText();
        LinuxCommand lc = new LinuxCommand(System.getProperty("user.dir")+"/adduser.sh", username, password2);
    Task<Void> task = new Task<Void>() {
        @Override
        public Void call() throws Exception {
            lc.execute();
            return null;
        }
    };
    task.setOnFailed(new EventHandler<WorkerStateEvent>() {
        public void handle(WorkerStateEvent t) {
            System.out.println("FAILURE creating  " + username);
            System.out.println("exit code: " + lc.getExitCode());
        }
    });
    task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent t) {
            if (lc.getExitCode() != 0)
                // show dialog
                return;
            System.out.println("Successfully created new user:  " + username + " With exit code: " + lc.getExitCode());
            Platform.runLater(new Task<Void>() {
                @Override
                public Void call() throws Exception {
                    uac.addUser();
                    return null;

                }
            });
        }
    });

    executorUserCreation.submit(task);

where uac is a reference to the UserAdministrationController.java and the adduser the method that tries to update the GridPane by CALLING AGAIN the displayNonSudoUsers().
I have also experimented by trying to do various stuff on the scroll pane / gridpane of the Users Admin Stage (e.g. deleting a label etc) but NADA!
Thanks.
EDIT: And this is the way I get the reference to the user admin controller (which is probably right because e.g. I manage to sysout some of its elements's ids etc.) in the initialize method of the AddUserController.java
public void initialize(URL location, ResourceBundle resources) {
    // need to access UsersAdminController to update users list
    // when adding user
    URL loc = getClass().getResource("/resources/fxml/UsersAdminPane.fxml"); // the UsersAdmin fxml
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(loc);
    fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
    try {
        Parent root = (Parent) fxmlLoader.load(loc.openStream());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    uac = (UsersAdminController)fxmlLoader.getController();
}

A: In this code:
public void initialize(URL location, ResourceBundle resources) {
    // need to access UsersAdminController to update users list
    // when adding user
    URL loc = getClass().getResource("/resources/fxml/UsersAdminPane.fxml"); // the UsersAdmin fxml
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(loc);
    fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
    try {
        Parent root = (Parent) fxmlLoader.load(loc.openStream());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    uac = (UsersAdminController)fxmlLoader.getController();
}

you load a new copy of UsersAdminPane.fxml, get the reference to its controller... and then discard the view (root) and never do anything with it. Since that view is never displayed, calling methods on the controller is never going to produce any update you will see.
You need to get a reference to the controller associated with the existing view, and call methods on that, instead of creating a new controller. Assuming you load the AddUser fxml file from the UsersAdminController, you can get the AddUserController from the FXMLLoader and pass a reference to the UsersAdminController by defining a setUsersAdminController(...) method in the AddUserController.


text:
Q: How to convert a continuous probability density function into discrete samples? What are the different methods that can be used to convert a probability density function of a continuous random variable into a discrete random variable? I have studied the uniform width method but are there other methods that give better approximations?

A: The question is somewhat broad.  It is is a continuous distribution whose support is the whole of $\mathbb R$, then its cumulative probability distribution function $F$ is continuous and strictly increasing.  In that case, if $U_1,\ldots,U_n$ is an i.i.d. sample from the uniform distribution on $(0,1)$, then $F^{-1}(U_1),\ldots,F^{-1}(U_n)$ is an i.i.d. sample from the distribution whose c.d.f. is $F$.
But there is a lot more to say about it. Enter the term "stochastic simulation" on amazon(dot)com and in a library catalog and you should see lots of stuff.


text:
Q: passing struct pointers to functions c++ Should be a simple question, I have a struct
struct Foo{
    float *bar;
    Foo(){
        bar = 0;
    }
};

and a load function:
bool loadFoo(Foo *data){
    float nums[4] = {0,1,2,3};
    data->bar = nums;
    return true;
};

And I run it like this:
void main(){
    char data;
    Foo myFoo;
    loadFoo(&myFoo);
    std::cerr << sizeof(myFoo.bar) << "\n";
    std::cerr << myFoo.bar[0] << "\n";
    std::cerr << myFoo.bar[1] << "\n";
    std::cerr << myFoo.bar[2] << "\n";
    std::cerr << myFoo.bar[3];
    std::cin >> data;
};

and the output is 4 bytes for the sizeof(myFoo->bar) I thought by passing the struct to the method I could modify data->bar and since bar is, float *bar; I could make it an array since I cant specify that bar is an array because its an 'unknown size' when loaded. (when implemented the program will read in values from a file) This works fine with non pointer variables but its the pointer that I can't seem to understand.
How do I make it so that when I pass the struct I can modify the variable pointer?
any help would be greatly appreciated!

A: You haven't specified the problem but let me guess - it crashes and/or doesn't yield the result you expect. The reason for that is assigning a pointer to a local variable in the line data->bar = nums; Here you link your data->bar to a nums array which is allocated on stack and is freed when you exit loadFoo. The result is a dangling pointer inside your Foo object.
You can solve this in different ways. The most straightforward would be to use a constructor with size parameter - this will solve your unkonwn size issue. You'll need to explicitly allocate memory for the data->bar and copy the data into the allocated space (of course, it will require to free it when not in use anymore). Same effect can be achieved by using your loadFoo func but using internal language features (constructor/destructor) is much cleaner.

A: You can do something like you've specified, but the exact implementation you've given will encounter undefined behavior.
bool loadFoo(Foo *data){
    // Create an array of 4 floats ON THE STACK.
    float nums[4] = {0,1,2,3};
    // point data->bar at the above slice of stack.
    data->bar = nums;
    return true;
    // abandon the piece of stack we're pointing at.
}

You might want to look into std::vector as a growable way of storing runtime sizes arrays, or you will need to allocate backing store for the destination floats, e.g.
data->bar = new float[4];

and free it when you are done with it
delete data->bar;

That said; it would seem more elegant to do these operations as members of Foo.
#include <vector>
// #include <algorithm>   // (for the std::copy option)

class Foo
{
    std::vector<float>  m_floats;

public:
    Foo() : m_floats() {}
    void loadFloats()
    {
        m_floats = { 0, 1, 2, 3 };
    }
    // or load them from someplace else
    void loadFloats(float* srcFloats, size_t numFloats)
    {
        m_floats.clear();
        m_floats.reserve(numFloats);

        // copy by hand:
        for (size_t i = 0; i < numFloats; ++i) {
            m_floats.push_back(srcFloats[i]);
        }

        // or just:
        // std::copy(srcFloats, srcFloats + numFloats, m_floats);
    }
};

A: Instead of loadFoo you can have constructor
struct Foo{
    float *bar;
    Foo( int size){
        bar = new float[size];  //allocate memory
        //... Initialize bar
    }
    ~Foo() { delete bar;}
};

OR using initializer_list
#include <initializer_list>

struct Foo{
    float *bar;
    Foo( std::initializer_list<float> l){
        bar = new float[l.size()];  //allocate memory
        std::initializer_list<float> ::iterator it = l.begin();
        size_t i=0;
        for(;it!=l.end();++it,++i)
          bar[i] = *it;
    }
    ~Foo() { delete bar;}
};

Also, make sure you follow rule of three


text:
Q: log trick on message passing in factor graphs I'm reading Barbers book on Bayesian reasoning and Machine learning  http://web4.cs.ucl.ac.uk/staff/D.Barber/textbook/200620.pdf page 90
To give context this is a proof of using the log trick for the Factor graph messages.

I have two questions
1.
Is the derivation incorrect?
Using the definition that $e^{\lambda_{f \rightarrow x}(x)} = \mu_{f \rightarrow x}(x)$. Substituting into the top equation we get
$$e^{\lambda_{f \rightarrow x}(x)} = \sum_{\mathcal{X_f} \setminus x} \phi_{f}(\mathcal{X}_f) \prod_{y \in ne(f) \setminus x} e^{\lambda_{y \rightarrow f}(y)}$$
Now let $n = |ne(f) \setminus x|$
We can write the above as
$$e^{\lambda_{f \rightarrow x}(x)} = \sum_{\mathcal{X_f} \setminus x} \phi_{f}(\mathcal{X}_f) e^{\sum_{y \in ne(f) \setminus x} \lambda_{y \rightarrow f}(y)}$$
Which is equivalent to
$$ e^{\lambda_{f \rightarrow x}(x)} = \sum_{\mathcal{X_f} \setminus x} \phi_{f}(\mathcal{X}_f) e^{n \lambda^{*}_{y \rightarrow f}} e^{\sum_{y \in ne(f) \setminus x} \lambda_{y \rightarrow f}(y) - \lambda^{*}_{y \rightarrow f}} $$
which is equivalent to
$$ e^{\lambda_{f \rightarrow x}(x)} = e^{n \lambda^{*}_{y \rightarrow f}}\sum_{\mathcal{X_f} \setminus x} \phi_{f}(\mathcal{X}_f)  e^{\sum_{y \in ne(f) \setminus x} \lambda_{y \rightarrow f}(y) - \lambda^{*}_{y \rightarrow f}} $$
Finally taking logs we get
$$\lambda_{f \rightarrow x}(x) = n \lambda^{*}_{y \rightarrow f} + \mathrm{log}\left(\sum_{\mathcal{X_f} \setminus x} \phi_{f}(\mathcal{X}_f)  e^{\sum_{y \in ne(f) \setminus x} \lambda_{y \rightarrow f}(y) - \lambda^{*}_{y \rightarrow f}}\right)$$
So mine differes by a factor of n in the first term. Am i correct or have i made a mistake?
2.
How would we calculate $\lambda^{*}_{y \rightarrow f} = \mathrm{max}_{y \in \mathrm{ne}(f) \setminus x } \lambda_{y \rightarrow f} $ given that technically $\lambda_{y \rightarrow f}$ is a vector? I was thinking perhaps you pick the vector with the largest element but since we do difference elementwise that wouldn't necessarily ensure differences are negative.


text:
Q: Sending HTTP Header Info with Java UrlConnection Alright, so I have this bit of code, and when I make the request, I would like to include some HTTP Header info.  How would I go about doing that?
public boolean call(String apiCall) {
    if (this.apiCalls.containsKey(apiCall)) {
        try{
            URL url = this.apiCalls.get(apiCall);
            url = new URL(url.toString() + "?memberid=76710");

            URLConnection urlConn = url.openConnection();

            InputStream is = urlConn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while((current = bis.read()) != -1){
                baf.append((byte)current);
            }

            this.responseResultText = new String(baf.toByteArray());
            return true;
        } catch(Exception e){
            this.responseResultText = e.getMessage();
            return false;
        }
    }
    this.responseResultText = "API call " + apiCall + " doesn't exist.";
    return false;
}

Thanks!

A: Use URLConnection#setRequestProperty().
connection.setRequestProperty("Content-Type", "text/plain");

See also:

*

*How to use URLConnection?


text:
Q: Copy folders only with numeric names Lets assume we have a directory /dir/ which contains lots of folders. Some of the folder names are numeric like 1, 2, 64346, 2353, 3 etc. Some contain classical names some_name, some_other_name, another_name etc. How can I copy from remote to local host only directory that have only numbers in their name?
I'm looking for something like scp -r username@host:/dir/[all_numerical_names] .
Any ideas appreciated

A: I know of no way to match remote file/directory names against a criterion such as being entirely numeric. However, since you're using scp it seems reasonable to assume ssh is also available. On that basis here's how I would consider solving the problem:
rhost="user@remoteHost"    # Fix as appropriate
rpath="/dir"               # Likewise

ssh -qn "$rhost" "find '$rpath' -maxdepth 1 -type d -print0" |
    while IFS= read -r -d '' item
        do
            if [[ "$item" =~ ^(.*/)?[0-9]+$ ]]
            then
                # Numeric directory
                echo "Copying $item" >&2            # Optional
                scp -r "$rhost":"$rpath/$item" .    # Maybe -a instead of -r
            fi
        done

Caveats

*

*Requires GNU find on the remote system (for -print0)

*Requires bash on the local system (for read and the RE comparison)

*Certificate based authentication is strongly recommended (so that a password is not repeatedly required)

*$rpath must not contain either double or single quotes

If you don't have GNU find on the remote system you can replace -print0 with -print and then adjust the read -r -d '' item to become simply read -r item. However, it may then perform unexpectedly with "strange" directory names such as $'123\ntext\n456' that should be excluded.


text:
Q: Find the fallacy in the following treatment Claim:

any two positive integers  are equal

Proof:
Let $A(n)$ be statement:

if $a$ and $b$ are any two positive integers such that $\max(a,b)=n$ then $a=b$

Suppose $A(r)$ is true. Let $a$ and $b$ be any two positive integers such that $\max(a,b)=r+1$. Consider the two integers $p=a-1$ and $q=b-1$: then $\max(p,q)=r$. Hence $p=q$, for we are assuming $A(r)$ to be true. It follows that $a=b$; hence $A(r+1)$ is true. $A(1)$ is obviously true, for $max(a,b)=1$ implies $a=b=1$. Therefore by mathematical induction, $A(n)$ is true for every $n$.
Now if $a$ and $b$ are any two positive integers whatsoever, denote $\max(a,b)$ by $r$. Since $A(n)$ has been shown to be true for every $n$, in particular $A(r)$ is true. Hence $a=b$.

A: Presumably your induction assumption is that the result is true for any  positive integers whose maximum is $r$. You are then trying to prove the result for maximum equal to $r+1$.  Note that $a-1$ or $b-1$ need not be positive, so the induction assumption is not sufficient.


text:
Q: ios - keep track of views with dismiss(modal)View I am trying to have a number (UILabel) to be send to another UIViewController.
Now I am able to go one way, but I also need to bring the result back to the initial Controller when I return to that.
On top of that I am trying to do this with 4 UILabel's so I need to distinguish between them.
Now to get to the 2nd ViewController I want to use a segue like this:
    if ([segue.identifier isEqualToString:@"ChangeNumberSegue"])
{
    NSLog(@"Changing the Number on NumberPadViewController");

    NumberPadViewController *numberPad = segue.destinationViewController;

    if(_BtnNumber01)
    {
        numberPad.numberLine.text = _LblNumber01.text;
    }
    if(_BtnNumber02)
    {
        numberPad.numberLine.text = _LblNumber02.text;
    }
    if(_BtnNumber03)
    {
        numberPad.numberLine.text = _LblNumber03.text;
    }
    if(_BtnNumber04)
    {
        numberPad.numberLine.text = _LblNumber04.text;
    }
}

The question is: What is the correct way to dismiss the 2nd view once I am done with it.
Once I am in the second view it will only change the number of the selected label.
Cheers.

A: Assuming this is a modal segue...
In lieu of an actual return value, just create a property in the first view controller that you want set, such as:
@property (nonatomic, assign) NSInteger theValue;

Inside the second view controller, you can get a handle to the first such as:
FirstViewController *vc = (FirstViewController *) [self presentingViewController];
vc.theValue = 5;

As far as returning back to the original view controller, you can add this inside your second view controller:
[self dismissViewControllerAnimated:YES completion:nil]; // iOS 6
// or
[self dismissModalViewControllerAnimated:YES]; // iOS 5 or earlier