text:
Q: Java : Object Initialization How to interpret the statements below:
Notes bean = null;
bean = new Notes();

Small explanation would be very helpful.

A: Are you sure the sequence of the instruction is not the opposite?
Notes bean = null;
bean = new Notes()

It seems a mistake :-)
Maybe could be:
Notes bean = new Notes();
bean = null;

In this case it can be used to signal to the garbage Collector that it has to trash the object referenced by Bean.
Otherwise I guess it a mistake. Could you post more code?

A: one step back:
    Notes bean;

this is a field or a local variable declaration without explicit initialization.
A field will be initialized with a default initial value: null for objects, 0 for primitive numbers and char, and false for boolean.
A local variable will stay uninitialized. It's an error to access such variable until a value is assigned to it.

    bean = new Notes();

is assigning a value to the field or variable. In this case a new instance of Notes is created and assigned*  to bean. Similar to:
    bean = null;          // kind of assigning 'nothing' or 'empty'
    bean = someMethod();  // assigning the value returned by the method

* actually it is the reference to the instance that is assigned to bean

    Notes bean = null;

is the combination of both: declaring a field or variable, and assigning a value to it (initializing it). In this case the value is null, which means the same as no instance.
These is almost equivalent to writing
    Notes bean;
    bean = null;

The variable could also be initialized with an new instance of Notes:
    Notes bean = new Notes();

A: new creates a new instance of the object, which allows you to use it as expected (such as accessing its methods)
null essentially means it references nothing (and thus you can't use any of its methods)

A: bean = new Notes();

This statement assumes you've already delcared a variable named bean of type Notes (or any of its parent classes. If you just run this line by itself, it will blow up because it can't find the variable 'bean'.
Notes bean = null;

This here will initialize a variable 'bean' and have it point to nothing. A variable is just a pointer to a spot in memory where your object will reside.
You should switch the order of these 2 statements, or combine then like:
Notes bean = new Notes();

A: First statement creates an initialize fields on the bean object (a Notes object),
Notes bean = null, is the declaration of a bean reference that doesn't reference to an actual object (that's the meaning of null), referencing to null means that you can't use bean and its methods.
If the statementes are within the same block of code (enclosed by the same pair of {}), the program won't compile, because you're declaring the same reference twice.

A: bean = new Notes();

This assumes that you have a variable named "bean" that has already been declared.  The type of bean must be Notes or one of its parent classes or an interface implemented by Notes.  The "new" keyword along with the parameter-less constructor call signify the creation of a new object of type Notes and the variable bean references that new instance.
Notes bean = null;

This declares a variable named "bean" of type Notes.  It also initializes the variable to null.  Variables that are fields are initialized to null by default (unless they are primitives), but local variables are not initialized to anything by default.  Thus this line explicitly initializes bean to null.


text:
Q: Is there a way to set a DLL to always follow CultureInfo.InvariantCulture by default, if not specified? I have a lot of code in a class library that does not specify CultureInfo.InvariantCulture. For example in toString operations, toBool, toInt, etc.
Is there a way I can get set a property for the class library to always execute using CultureInfo.InvariantCulture, even if it is not explicitly specified everywhere in the code?
Sort of like a global switch?
It is not only messy to have to explicitly type it everytime, it makes my code less readable, and is a royal pain for example:
if (Convert.ToInt16(task.RetryCount, CultureInfo.InvariantCulture) <
            Convert.ToInt16(ConfigurationManager.AppSettings["TasksMaxRetry"], CultureInfo.InvariantCulture))

A: While I agree that Mark's answer is the correct answer to the question posed; I don't think that switching the thread culture is a good design. It could introduce subtle bugs if other parts of the application, most likely the UI, depends on the threads current culture. Also,  I would argue that explicitly stating the culture in Convert calls is a good design, that tells the reader of the code that the original programmer has made an active decision about which format to allow; and that the code is not just "working by coincidence".
You will most likely want to have many of your parse operations grouped together in the same class; perhaps one that deals with reading configuration. In that class, you could define a field to contain the culture you would like to use for parsing:
private static readonly IFormatProvider parseFormat = CultureInfo.InvariantCulture;

Then use that field in any calls to Convert methods or similar. Declaring the field as an IFormatProvider, together with a well chosen name, tells the reader of the code very explicitly, that this is a field used to define the parsing format. IMHO, it makes the intent of the code clearer.
Another way to do this would be to make your own Parse / Convert class, that wraps the Convert.ToXxx methods and calls them with the format you intend to use. Then you will have the desired benefit of not having to explicitly state the format in each call.

A: I don't think so, but it is possible to set the CultureInfo on a per-thread basis:
Console.WriteLine(double.Parse("1.000"));
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine(double.Parse("1.000"));

Output on my machine (your output may vary depending on your current culture):
1000
1

Is this what you want?

redpajama_set_name: RedPajamaStackExchange


text:
Q: onreceive() not working with Android O I am testing on Android O phone. I have a Broadcast receiver registred to receive the Bluetooth status change event. I have added this inside my code as
context.registerReceiver(receiver , BluetoothAdapter.ACTION_STATE_CHANGED)

When i test, the callback do not come to onreceive(). I have read that Android O do not support implicit broadcast. I am not sure why onreceive() is not fired. Is Bluetooth Action state change intent having issues with Android O ?

A: ACTION_STATE_CHANGED is not in the list of Implicit Broadcast Exceptions.
Changing to the ACTION_CONNECTION_STATE_CHANGED, ACTION_CONNECTION_STATE_CHANGED, ACTION_ACL_CONNECTED and/or  ACTION_ACL_DISCONNECTED, that are in the list of whitelisted actions, might solve your issue.


text:
Q: What's API call method of statistics? I want to provide LinkedIn statistics, but i can not see stats URI.
So, what is Socialbakers LinkedIn Statistics API using?
Thanks.

A: They aren't using a public (that's if they are even using anything from LinkedIn) LinkedIn API.
They also have statistics for Twitter and twitter doesn't offer those statistics in their API. I don't know where they get their stats from, but its not from the API everyone has access to.
Edit : I used public because they might be using a private API that LinkedIn offers them


text:
Q: Calling a functor in with declaration I wanted to implement sets of pairs of elements. For that, I copied the Make functor of MSetWeakList. It is originally defined like this:
Module Make (X: DecidableType) <: WSets with Module E := X.

So I tried to do the same, but with two DecidableType.
Require Import MSets.

Module DecidablePair (DT1:DecidableType) (DT2:DecidableType) <: DecidableType.
  Definition t : Type := DT1.t * DT2.t.
  Definition eq x y := DT1.eq (fst x) (fst y) /\ DT2.eq (snd x) (snd y).
  Lemma eq_equiv : Equivalence eq.
  Proof.
    split.
    - split; reflexivity.
    - split; symmetry; apply H.
    - split.
      + transitivity (fst y). apply H. apply H0.
      + transitivity (snd y). apply H. apply H0.
  Qed.
  Lemma eq_dec : forall x y, {eq x y} + {~ eq x y}.
  Proof.
    intros.
    destruct (DT1.eq_dec (fst x) (fst y)).
    - destruct (DT2.eq_dec (snd x) (snd y)).
      + left. split; assumption.
      + right. intros contra. apply n. apply contra.
    - right. intros contra. apply n. apply contra.
  Qed.
End DecidablePair.

Module MakePair (DT1: DecidableType) (DT2:DecidableType) <: WSets
  with Module E := DecidablePair DT1 DT2.

But Coq does not accept the call of functors in with declarations. How can I then write the module type returned by MakePair ?


text:
Q: SelectSingleNode with XPath not working - works in online test tool I have the following XML (only part of it, can't share it all as its confidential):
<?xml version="1.0" encoding="utf-8"?>
<Report xsi:schemaLocation="Aircraft_SpecSheetDetails" Name="Aircraft_SpecSheetDetails" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="Aircraft_SpecSheetDetails">
    <Aircraft_SpecSheet_SUB_SpecificData>
        <Report Name="Aircraft_SpecSheet_SUB_SpecificData">
            <table8 Textbox29="No">
                <Detail_Collection>
                    <Detail OperWeightType_Description="Maximum Landing Weight" AcrftOperWeight_Current_KG="43000" AcrftOperWeight_Current_LBS="94799" />
                    <Detail OperWeightType_Description="Maximum Take Off Weight" AcrftOperWeight_Current_KG="50300" AcrftOperWeight_Current_LBS="110893" />
                    <Detail OperWeightType_Description="Maximum Zero Fuel Weight" AcrftOperWeight_Current_KG="40800" AcrftOperWeight_Current_LBS="89949" />
                    <Detail OperWeightType_Description="Basic Empty Weight" AcrftOperWeight_Current_KG="27841" AcrftOperWeight_Current_LBS="61379" />
                </Detail_Collection>
            </table8>
        </Report>
    </Aircraft_SpecSheet_SUB_SpecificData>
</Report>

I want to grab the Detail element with a specific value in the OperWeightType_Description attribute.
My XPath looks like this: //Detail[@OperWeightType_Description='Maximum Landing Weight']
It works using this tool: https://www.freeformatter.com/xpath-tester.html
But in C#, the code below doesn't work - the weightNode remains NULL.
private int? ImportWeightValue(XmlNode report, string weightDescription)
{
    XmlNode weightNode = report.SelectSingleNode($"//Detail[@OperWeightType_Description='{weightDescription}']");

    if (weightNode != null)
    {
        return weightNode.ReadInt("AcrftOperWeight_Current_KG");
    }

    return null;
}

The report XmlNode in the parameter is the DocumentElement -- the <Report> element of the XML.


text:
Q: Windows 8 freezes/creashes when playing video My computer crashes sometimes watching movies or playing flash videos on the internet browser (I use Chrome).
What happens is while watching a movie I'm starting to hear a buzz and screen disappears, or sometimes audio keeps on playing for several moments before screen disappears. Then I either continue hearing that noise until I restart, either the computer restarts by itself.
I tried looking at the event viewer but I didn't manage to track the actual problem down.
I just see warnings like:

*

*(12:07:39) The system has rebooted without cleanly shutting down first. This error could be caused if the system stopped responding, crashed, or lost power unexpectedly.

*(12:08:02) The previous system shutdown at 11:49:21 PM on 4/24/2013 was unexpected.

*(12:10:22) The NVIDIA Update Service Daemon service failed to start due to the following error:
The service did not start due to a logon failure.

*(12:10:22) The nvUpdatusService service was unable to log on as .\UpdatusUser with the currently configured password due to the following error:
The password for this account has expired.
To ensure that the service is configured properly, use the Services snap-in in Microsoft Management Console (MMC).

*(12:08:09) Custom dynamic link libraries are being loaded for every application. The system administrator should review the list of libraries to ensure they are related to trusted applications. Please visit http://support.microsoft.com/kb/197571 for more information.

*(12:07:43) The driver \Driver\WudfRd failed to load for the device ROOT\WPD\0000.

The truth is that I'm not an event viewer expert, and I'm hoping one of you experts will guide me on tracking down the problem source and solve it.
I tried updating the graphic card drivers with the latest version but the issue still persists.
The real issue is that I'm unable to reproduce the issue as it occurs randomly.

A: A failing graphics card could cause these symptoms. You can troubleshoot this possibility by temporarily swapping graphics cards if you have another one.

A: Check power supply, is it the correct rating for the card?  Disable hardware acceleration in the meantime in programs such as VLC and M Player classic.

A: In my scenario it was due to a bug in the new update to graphics driver. When I rolled back to the previous driver version the problem was gone.


text:
Q: Floating point exception error in simple c++ code #include <iostream>
using namespace std;

int main() {
    // your code goes here
    int t,x,y,z,set,i,check=0;
    cin>>t;
    while(t--)
    {
        cin>>x>>y>>z;

        check=z-(x+y);

      for(i=0;i<10;i++){
            if(check%i==0)
            {
                set=i;
            }
           // i++;
        }
        cout<<set<<endl;
    }

    return 0;
}

While I run this code then I get run time error like

FLoating point exception

and from next input it gives error like:

dash: 2: 4:not found

A: There is a floating point exception because I divided i by 0 so I need to start loop from 1.


text:
Q: What is the best way to model year covariates when predicting BLUPs in CRAN sommer package? I have a biparental population of plants with high-density SNP/SSR marker data for all individuals and phenotypic data taken over three independent years.  I've modeled each year separately for each trait of interest to calculate breeding values for each individual.  I've also tried modeling the year as a random effect covariate, with a covariance matrix equal to the identity matrix (assuming no covariance between years), to see if modeling for a year covariate and combining phenotypic values across all three years can increase the heritability of my traits.
However, I've noticed that when I model using the CRAN sommer package's mmer() function, I will have heritability values that seem inflated more than they should.  In some cases, I'll have no heritability for a trait when considered within a year, but when I model across all three years, with year as a random effect covariate and an identity covariance matrix, I get large increase in heritability values.
What is the best way to estimate BLUPs in this case, when I want to combine/consider all three years of data together?  In particular, what way should I do this if I don't really have a good idea of how to specify a year-by-year covariance matrix?

A: In the vignettes of the package multiple covariance structures are explained but in general you could model the GxE in different ways. If you assume that there's no GxE you could assume a diagonal structure (DIAG):
data(DT_example)
head(DT)
## Diagonal (DIAG) model
ans0 <- mmer(Yield~Env,
             random= ~vs(ds(Env),Name),
             rcov= ~ vs(ds(Env),units),
             data=DT)

which is the same that fitting the models by separate. On the other hand, if you assume GxE exist, the most typical model is the compound symmetry model, which assumes same GxE variance in all environments:
## Compound simmetry (CS) model
ans1 <- mmer(Yield~Env,
             random= ~ Name + Env:Name,
             rcov= ~ units,
             data=DT)

you can also assume that each environment has a different GxE variance:
## Compound simmetry (CS) + Diagonal (DIAG) model
ans2 <- mmer(Yield~Env,
             random= ~Name + vs(ds(Env),Name),
             rcov= ~ vs(ds(Env),units),
             data=DT)

and the most complex model estimates all genetic variance and covariance components:
## Unstructured (US) model
ans3 <- mmer(Yield~Env,
             random=~ vs(us(Env),Name),
             rcov=~vs(us(Env),units),
             data=DT)

By modeling better the GxE you can increase the heritability by propagating the genetic signal among environments.
I hope this helps. Cheers


text:
Q: Send params to Joomla module I write custom module, for example, when module called with parametr 1, module return 1, when called with 2, return 2 e.t.c.
But I cant find any documentation, how to send parametrs from page to module. Its how I call module now:
jimport( 'joomla.application.module.helper' );
$modules = JModuleHelper::getModules('NAME_OF_CUSTOM_POSITION');
$count_array = count($modules);
if ($count_array >0)
    {
    $attribs['style'] = 'xhtml';
    echo JModuleHelper::renderModule( $modules[0], $attribs );
    }
?>

But I don't know how to send params nor how to recieve them in my module.

A: I have used below code in one of my custom component.And it worked for me.
$document   = JFactory::getDocument();
$renderer   = $document->loadRenderer('module');
$params   = array('style'=>'xhtml');
$contents   = '';
foreach (JModuleHelper::getModules('NAME_OF_CUSTOM_POSITION') as $mod)  {
    $registry   = new JRegistry();
    $registry->loadString($mod->params);
    $registry->set('paramname','paramvalue');
    $mod->params = (string)$registry;
    $contents .= $renderer->render($mod, $params);
}
echo $contents;


text:
Q: Plotting multi-dimensional true and predicted arrays in a regression task In a regression task of predicting 1 hour power load in the future using LSTM (univariate LSTM), the results can be plotted easily something like this:
plt.plot(y_ts, label='True Future', color='blue')
plt.plot(y_pred, label='Forecast', color='red')
plt.show()

This is because both y_ts and y_pred are 1D. Now, assuming that the task has changed to predict 6 hours power load in the future using LSTM. This means y_ts and y_pred are going to be now in 2D, for instance y_ts= (3454, 6) and y_pred= (3454, 6) How do I plot this case of high dimensional array?

A: Fundamentally there is only one dimension in your data i.e. time; what you have are 6 time slices - it would make sense to append them to each other, plot on the same axes and mark each hour separately.
Let me explain this with the help of some fabricated data:
import numpy as np
from matplotlib import pyplot as plt

np.random.seed(42)

n, h = 3454, 6
y_ts, y_pred = np.random.randn(n, h).cumsum(), np.random.randn(n, h).cumsum()
y_ts = y_ts - np.min(y_ts)
y_pred = y_ts - (y_pred - np.min(y_pred)) / np.max(y_pred) * 0.05 * np.mean(y_ts)
y_ts = y_ts.reshape((n, h), order="F")
y_pred = y_pred.reshape((n, h), order="F")

Plotting y_ts individually (and similarly for y_pred):
for i in range(h):
    plt.plot(y_ts[:, i], label=f'y_ts_h{i+1}')

plt.legend()
plt.show()

Now, you can straighten your data and plot it as a 1-D series as shown below:
y_ts = y_ts.reshape((n*h), order="F")
y_pred = y_pred.reshape((n*h), order="F")
plt.plot(y_ts, label=f'y_ts')
plt.plot(y_pred, label=f'y_pred')

for i in range(h):
    plt.axvline(x=(n*(i+1)), c='m')

plt.xticks([(i+1)*n for i in range(h)], [f'hr_{i+1}' for i in range(h)])
plt.legend()
plt.show()


text:
Q: Geocode with an address database that didn't have XY or lat/long info I was asked

How would you geocode with an address database that didn't have XY or lat/long info?

as part of a pre-interview questionnaire for an analyst position. I've only geocoded using address locators off of tables that already had addresses or lat/long info but this question has me stumped. I did think of maybe doing something like a feature to point operation on something like a parcel layer that may contain address data but don't know if this would be the proper alternative.

A: Geocoding is the process of converting an address or location description into a set of geographic coordinates (latitude and longitude). If your address database doesn't have XY or lat/long information, there are several methods that you can use to obtain this information:

*

*Third-party APIs: There are several geocoding APIs available that
can be used to convert addresses into geographic coordinates.
Examples include Google Maps API, Bing Maps API, and MapQuest API.

*Batch Geocoding Tools: Batch geocoding tools can be used to process
large datasets of addresses and convert them into geographic
coordinates. Examples of these tools include ArcGIS Online Batch
Geocoding and QGIS MMQGIS Plugin.

*Geocoding software: Some GIS software packages have built-in
geocoding functionality that can be used to convert addresses into
geographic coordinates. Examples include ArcGIS Desktop and QGIS.

*Manually: As a last resort, you can manually geocode addresses by
using a web-based mapping tool, such as Google Maps, to find the
latitude and longitude of each address and then enter it into your
database.

Regardless of which method you choose, it's important to note that the accuracy of the resulting geographic coordinates will depend on the quality and completeness of the address data in your database. You may need to perform additional data cleaning and validation to ensure that the addresses are in a standard format that can be accurately geocoded.


text:
Q: Game Engine to use with Eclipse for API 14 Can anyone give a Game Engine that can be:

*

*Used with Eclipse

*Used for Android 4.0 or API level 14

I downloaded AndEngine But it is for API 15...Changed 8 to 15 in <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15"/> of AndEngine. Still it is saying android-15 cannot be found.
What can i do?

A: I guess API lvl 15 is missing in your Android SDK. Try to update your SDK version and install API Level 15 SDK by using Android SDK Manager.


text:
Q: What does key "M" mean in Emacs? I am totally new to Emacs and am reading this tutorial, and it mentions:
M-f    Forward one word

Which key is M?
As such pressing M followed by f types Mf and pressing them together also types some combination of M and f.

A: M- is meta, which is an old X11 extended shift key designation.  In modern systems it's usually the Alt key.  You can also press Esc followed by the other keys in the sequence (here, Esc f).
You mostly won't see them on modern machines, but there are other extended shifts such as S- (super; you may see this if you press the Windows key) and H- (hyper).


text:
Q: Blinking of Pin upon Updating Position in Azure Map on Xamarin [Android] Blinking of Pin while running on android device. Take a look at the gif attached.
I followed this sample & used Xamarin Forms WebView for displaying map.
It works fine while running on browser.

A: If it's what I think it is, this is likely caused by the transition of the labels fading in and do collision detection. There isn't an option exposed to modify this fade in timing currently, but the following workaround appears to work for me.
After the map has loaded (in the ready event callback), add the following line of code:
map.map._fadeDuration = 0;

This overrides an internal, undocumented setting that the map uses when labels fade in. Using the above removes that delay.


text:
Q: what replaces indexPathForSelectedRow in Swift 3? In projects prior to Swift 3 - If I was looking to segue an indexPath from a tableController, I'd have a line of code like
      let indexPath = self.tableView.indexPathForSelectedRow!

However, in Swift 3, I am unable to write this. I can't seem to find any documentation on Apple's site or other SO questions to find a workable piece of code.
In response to Frankie's comment, I went back to my code (here is all of the current segue Swift 3 code) and have tried to copy and paste above code snippet... but to no avail. Xcode does not auto complete if I enter "self.tableView". It does not recognize indexPathForSelectedRow! either.  I'm missing something.
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "dineSegue"
    {
        if let destinationViewController = segue.destination as? RestaurantController
        {
            let indexPath = DineController.indexPathForSelectedRow!
            destinationViewController.restaurantIndex = index
        }
    }
}

A: I googled 'indexPathForSelectedRow Apple documentation` and was able to find the property reference for you as it was conveniently the first result.
https://developer.apple.com/reference/uikit/uitableview/1615000-indexpathforselectedrow
That being said, it's exactly what you posted in Swift 3.
self.tableView.indexPathForSelectedRow

A: Are you sure the "DineController" reference is to the actual UITableView
When I had this issue, my initial reference was to the generic class, not the actual table I had coded.


text:
Q: Program Tikz in Beamer The attached .Rnw-code produces two similar slides, but with different texts and different arrow positions. I wrote both slides manually, but because I need to produce hundreds of similar slides, I would prefer to write only one type-slide, and use variable-names that relate to the R-table to draw the slides. One slide per row in the R-table.
How can this be done?
Update: Tom Bombadil gave a much better example (I replaced my original with it). It is correct, with the addition that the source of the numbers and arrow positions come from an R-script. Here is the modified version.
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{shapes}

\begin{document}

% Here are the numbers and coordinates that should be different on each slide (one row per slide).
<<input, echo=FALSE>>=
#input.data <- rbind(c(1, 1234, 1965, 3, 4),
#c(2, 5678, 1974, 7, 4))
#colnames(input.data) <- c("SlideNr", "LeftNr", "RightNr", "ArrowPos1", "ArrowPos2")
@

\begin{frame}
    \begin{tikzpicture}
        \draw (0,0) rectangle (10,4);
        \node[above right] at (0,0) {1234};
        \node[above left] at (10,0) {1965};
        \node[single arrow,shape border rotate=90,fill=white,below,draw] at (3,4) {1.};
    \end{tikzpicture}
\end{frame}

\begin{frame}
    \begin{tikzpicture}
        \draw (0,0) rectangle (10,4);
        \node[above right] at (0,0) {5678};
        \node[above left] at (10,0) {1974};
        \node[single arrow,shape border rotate=90,fill=white,below,draw] at (7,4) {2.};
    \end{tikzpicture}
\end{frame}

\end{document}

How can one "link" a field in a table from R with a text or number in the Tikz?
Update 2. Thanks to Tom's response and comments I realized I can do the formatting in R instead. If I create this file (intext1.tex) in R (paste("\def\x{",variable,"}",sep="")):
\def\x{1234}
\def\z{3}

and intext2.tex
\def\x{4321}
\def\z{7}

...then I can do this in LaTex:
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{shapes}

\begin{document}

\foreach \n in {1,...,2} {
\input{intext\n.tex}
\begin{frame}
    \begin{tikzpicture}
        \draw (0,0) rectangle (10,4);
        \node[above right] at (0,0) {\x};
        \node[above left] at (10,0) {1965};
        \node[single arrow,shape border rotate=90,fill=white,below,draw] at (\z,4) {1.};
    \end{tikzpicture}
\end{frame}
}
\end{document}

A: Are you looking for something like this?
Code
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{shapes}

\begin{document}

\begin{frame}
    \begin{tikzpicture}
        \draw (0,0) rectangle (10,4);
        \node[above right] at (0,0) {\only<1>{1234}\only<2>{5678}};
        \node[above left] at (10,0) {\only<1>{1965}\only<2>{1974}};
        \only<1>{\node[single arrow,shape border rotate=90,fill=white,below,draw] at (3,4) {1.};
            }
        \only<2>{\node[single arrow,shape border rotate=90,fill=white,below,draw] at (7,4) {2.};
            }
    \end{tikzpicture}
\end{frame}

\end{document}

Output


text:
Q: what is the kotlin nested loop syntax issue? I am getting error for this syntax
  for (i in 0 until 8) {
      for (j in 0 until 8) {

      } println()
  }

error is

For is not an expression, and only expressions are allowed here.

but this is valid
  for (i in 0 until 8) {
      for (j in 0 until 8) {

      }
      println()
  }

only thing I changed was where println() is called, I have worked with java so I thought that placement should not matter. What is the issue here ?

A: I did some testing in Kotlin Playground. Kotlin compiler indeed cannot parse statements that are placed on the same line and not divided by ;.
For example 10 println("")
will produce an error: "Unresolved reference: println".
Note that 10 actually is an expression, since expressions are code blocks that produce single value.
The guessing is below:
The real question is, why Kotlin compiler shows the specific error, which is
For is not an expression, and only expressions are allowed here

I believe that has something to do with the Kotlin compiler's code parse algorithm. That seems like compiler tries to parse multiple statements on the same line as a single expression. for keyword makes it fail right away. However, if you replace for loop with a real expression, compiler will highlight the println call as something wrong, since it is something excess for an expression.


text:
Q: can you tell me what those 2 methods which reads bytes from an Input stream do? I am trying to understand an implementation of a b+ Tree. I don't understand what this overloaded method exactly do. Why in the first method having Inputsteam is as an argument declare 4 variables which are i1,i2,i3 and i4. In the second method using ObjectInput in as an argument, i understand that it returns a byte from 0 to 255, why is result=251? It will be helpful to explain each line and what it do.
First method:
    public final static int readLuposInt(final InputStream is) throws IOException {
        final int i1 = is.read();
        if (i1 < 0) {
            return i1;
        }
        final int i2 = is.read();
        if (i2 < 0) {
            return i2;
        }
        final int i3 = is.read();
        if (i3 < 0) {
            return i3;
        }
        final int i4 = is.read();
        if (i4 < 0) {
            return i4;
        }
        return (0xFF & i1) | ((0xFF & i2) | ((0xFF & i3) | (0xFF & i4) << 8) << 8) << 8;

}

overloaded method:
public final static int readLuposInt(final ObjectInput in) throws IOException {
        final int i0 = in.read();
        if (i0 <= 251){
            return i0;
        }
        int result = 251;
        int offset = 1;
        for (int i = 1; i <= i0 - 251; i++) {
            result += in.read() * offset;
            offset <<= 8;
        }
        return result;
    }

A: You could have used a debugger to find the following result.
The first method reads an 4 byte integer from an input stream. It seems to be stored as little-endian value.

*

*the bytes are read in sequentially

*ff any of the bytes is missing, -1 is returned.

*to return the complete integer, a computation is made by shifting the more significant bytes to the left.

Example:

*

*The number 2293742 represents the hex number 22 FF EE, which will be stored in reverse order: 0xEE 0xFF 0x22 0x00

*now the data gets read

*

*i1 = 0xEE

*i2 = 0xFF

*i3 = 0x22

*i4 = 0x00

*now the return value is computed:

*

*(0xFF & i4) << 8 = (0xFF & 0x00) << 8 = 0x0000

*((0xFF & i3) | (0xFF & i4) << 8) << 8) = ((0x22 | 0x0000) << 8) = (0x0022 << 8)  = 0x002200

*((0xFF & i2) | ((0xFF & i3) | (0xFF & i4) << 8) << 8) << 8 = (0xFF | 0x002200) << 8 = 0x0022FF00

*(0xFF & i1) | ((0xFF & i2) | ((0xFF & i3) | (0xFF & i4) << 8) << 8) << 8 = 0xEE | 0x0022FF00 = 0x0022FFEE
The second method reads unicode characters from the stream, encoded in an  UTF-8 encoding. Much can be said about unicode and their character encodings, see Wikipedia how that is working.


text:
Q: Extjs combo not working in IE7 Ext js combo is not working in IE7. I need this combo act like  textbox with virtual combo (like google search). It is working in IE9 and FF but not in IE7
This is my code:
SearchIncidentForm=new Ext.FormPanel ({

         border:false,
        renderTo:'searchIncidentDiv',
        id: 'searchIncidentForm',
        items : [{
            xtype:'panel',
            id :'panelsearchIncident',
            layout:'column',
            defaults:{
                    columnWidth:0.50,
                 labelAlign : 'top',
                 layout:'form',
                 border:false,
                 bodyStyle:'margin-top:5px; '
            },
            border:false,
            items : [{
                defaults:{anchor:'100%'},
                    items:[{
                        id : "incidentId",
                        fieldLabel : 'Incident Id',
                        labelStyle: 'color: #6C6C6C;width:85px;padding-top:7px;height: 22px;',
                        xtype : 'combo',
                        store:incidentStores,
                        //style: 'width:85px;height: 18px;',
                        width:100,
                        allowBlank : false,
                        labelAlign: 'top',
                        displayField : 'incidentId',
                        valueField : 'incidentId',
                        selectOnFocus : true,
                        typeAhead : false,
                        mode : 'remote',
                        triggerAction : 'all',
                        editable: true,
                        msgTarget:'qtip',
                        listAlign : 'tl-bl?',
                        //anchor : '80%',
                        minChars : 1,
                        hideTrigger:true,
                        hiddenName: 'incidentId',
                        listWidth:100,
                        listHeight:50,

                        submittValue:true,
                        listeners : {
                            specialkey : function(field, e){
                                var key=e.getKey();
                                if (key==e.ENTER) {
                                    incidentSearchButtonHandler();
                                }
                            },

                            beforequery : function(){
                            var val=Ext.getCmp('incidentId').getValue();
                                if(isNaN(this.getEl().dom.value)){
                                    Ext.Msg.alert("","Please type numeric value");
                                }
                                else{
                                    Ext.getCmp('incidentId').getStore().proxy.setUrl('getIncidentId.html?&query='+this.getEl().dom.value);

                                }
                            }
                        }

                    }]
                },{

                    items:[{
                        xtype : 'button',
                        text : 'Search',
                        style: 'margin-top:19px;margin-left:20px;width:50px;',
                        width: 35,
                        height:15,
                        handler : incidentSearchButtonHandler
                    }]
                }]
        }]
    });
}

but it's not working in IE. When I press Search button, an alert is shown that please type Id. That means it doesn't take the value that has been typed. Please help.

A: I've been bitten by this before with IE: you have an extra comma after the last element of your array:
items:[{

    submittValue:true,
    listeners : {
        specialkey : function(field, e){
            var key=e.getKey();
        if (key==e.ENTER) {
            incidentSearchButtonHandler();
        }
    },  // <------ Extra comma.  Delete it.
]}


text:
Q: Setting Coordinates in VLC media player I want to open multiple instances of VLC Media player side by side.
How can I set the co-ordinates on Windows? I couldn't find anything in the VLC Command Line, is there a way I can launch these, and pass some positions using Windows parameters.

A: Go to Tools > Preferences or press [CTRL + P].
Under the currently selected Interface preference, find the heading that says Playlist and Instances.
Make sure that Allow only one instance checkbox is not checked.

To open a second player window, we just have to click on any shortcut which is used to access the software. Search for and click on the VLC menu item from the start menu and it will open a new one. Similarly, you can also simply right-click on the current VLC icon in the task bar and click on VLC Media Player to open a new one.
Get more instructions here: http://filejunkie.org/download/vlc_media_player.html

A: You cannot do it via the user interface. Just write a batch/shell script that contains:
vlc.exe --no-one-instance --no-embedded-video --video-x=50 --video-y=50 videofile.mp4

If you want to disable the window borders just add:
--no-video-deco

And to set the window size use:
--width=640 --height=480

Hope it helps.


text:
Q: Not printing files content in socket programming I am naive to this socket programming. I am trying to print the content of the file present in the directory in the server's console but the server is not able to locate the file.
Here is my code:
myClient.java

import java.net.*;
import java.io.*;

public class myClient {
    public static void main(String args[]){
        Socket socket = null;
        String hostName,command,fileName;
        int port;

        if(args.length == 0){
            System.out.println("Error: command line arguments (hostname,port,command,"
                    + "filename) not found.\nTry again...!!!");
            System.exit(1);
        }
        hostName = args[0];
        port = Integer.parseInt(args[1]);
        command = args[2];
        fileName = args[3];

        try{
            socket = new Socket(hostName,port);
            System.out.println("Client Socket Created..!!");

            // creating input and output streams to read from and write to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            if(command.equals("GET")){

                System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
                bw.write(fileName);

                String line = br.readLine();
                while(line != null){
                    System.out.println("Server: "+line);
                    line = br.readLine();
                }
            }
            if(command.equals("PUT")){
                System.out.println("Client: "+fileName+" sent to server");
                bw.write(fileName);
                // pass the file contents
                bw.flush();

                System.out.println("Server: "+br.readLine());
            }
        }
        catch(UnknownHostException uhe){
            System.out.println("Unknown Host...!!!");
            System.exit(1);
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally
        {
            //Closing the socket
            try{
                socket.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

myServer.java

import java.net.*;
import java.io.*;

public class myServer {
    static Socket socket;
    public static void main(String args[]){
        try {
            int port = Integer.parseInt(args[0]);
            //String fileName = "";
            ServerSocket server = new ServerSocket(port);

            while(true)
            {
                System.out.println("Server started and listening on port "+port);
                socket = server.accept();
                System.out.println("received a connection :"+socket);

                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);

                bw.write("Echo server 1.1\n");
                bw.flush();

                String line = br.readLine();
                while(line != null){
                    bw.write("Echo: "+line);
                    bw.flush();
                    line = br.readLine();
                }
            }
        } catch (IOException e) {
            System.out.println("No conncetion established");
            System.exit(0);
            //e.printStackTrace();
        }
        finally
        {
            //Closing the socket
            try{
                socket.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

Kindly help me out finding a solution to this. I have tried many examples browsing different websites but not get to the solutions.

A: System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);

You aren't writing a correct HTTP command to the server. You're only sending the filename, not a complete command such as the GET command you're printing to the console.
The line terminator in HTTP is specified as \r\n, not \n.
You're also making no attempt to implement other aspects of HTTP 1.1 correctly, such as content-length. If you're going to implement HTTP you need a good knowledge of RFC 2616.
If possible you should throw this away and use HttpURLConnection.


text:
Q: How to connect Java with MongoDB in Windows Azure's worker role? I have a Spring RESTFul web service project that use "Spring Data MongoDB" library to connect with MongoDB database.
After successfully testing with my local machine, I am ready to deploy on cloud server (Windows Azure's worker role).
I have followed step-by-step from official website (here) with additional worker role called TomcatWorkerRole (since I want to run mongodb for internal use only, I have to deploy my web application in the same cloud service).
Everything works fine in deployment but in setting the database connection of my application is not like that.
The problem is because the replica-set is look like this ..
rs:PRIMARY> rs.conf()
{
   "_id" : "rs",
   "version" : 1,
   "members" : [
         {
             "_id" : 0,
             "host" : "rs_0:27017"
         },
         {
             "_id" : 1,
             "host" : "rs_1:27017"
         },
         {
             "_id" : 2,
             "host" : "rs_2:27017"
         }
   ]
}

Due to the description ..

To account for possible changes in the IPs of the instances running
  MongoDB, the worker role uses the hosts file to alias each of the
  instances. Hence the client application instance needs the same
  instances. Additionally the client application must also have the name
  of the replica set.

The problem is how can I know "rs_X" stand to which host ?
Because I have to specify the host in order to create the client connection.
Could anyone help me, please ? Do I have to change my mind to use VM's role for MongoDB instead of worker role ?
Thank you.
PS. Sorry for my english.


text:
Q: CLIPS Printout Number Of Times Rule Fired I have the following CLIPS construct below and I'm interested in tallying up how many times a particular rule fired so the output will be a series of the rules fired followed by their count (see picture for example).
So it would be all those rules followed by:
temperature: (times fired) seconds
pressure: (times fired) seconds
(deftemplate oil-measure
  (slot utc-time (type STRING))
  (slot temperature (type INTEGER))
  (slot pressure (type INTEGER)))

(defrule oil-is-hot
  (oil-measure (temperature ?temp) (utc-time ?time))
  (test (> ?temp 32))
  =>
  (printout t ?time tab "temperature:" tab ?temp crlf))

(defrule pressure-is-high
  (oil-measure (pressure ?press&:(> ?press 0)) (utc-time ?time))
  =>
  (printout t ?time tab "pressure:" tab ?press crlf))

A: You can store counters in global variables and increase them accordingly.
(defglobal ?*hot-oil-times* = 0)

(defrule oil-is-hot
  (oil-measure (temperature ?temp) (utc-time ?time))
  (test (> ?temp 32))
  =>
  (bind ?*hot-oil-times* (+ ?*hot-oil-times* 1))
  (printout t ?time tab "temperature:" tab ?*hot-oil-times* tab ?temp crlf))

A: Code incorporating noxdafox's solution:
(defglobal ?*hot-oil-times* = 0)
(defglobal ?*high-pressure-times* = 0)

(deftemplate oil-measure
  (slot utc-time (type STRING))
  (slot temperature (type INTEGER))
  (slot pressure (type INTEGER)))

(defrule oil-is-hot
  (oil-measure (temperature ?temp) (utc-time ?time))
  (test (> ?temp 32))
  =>
  (bind ?*hot-oil-times* (+ ?*hot-oil-times* 1))
  (printout t ?time tab "temperature:" tab ?*hot-oil-times* tab ?temp crlf))

(defrule pressure-is-high
  (oil-measure (pressure ?press&:(> ?press 0)) (utc-time ?time))
  =>
  (bind ?*high-pressure-times* (+ ?*high-pressure-times* 1))
  (printout t ?time tab "pressure:" tab ?*high-pressure-times* tab ?press crlf))


text:
Q: How to rewrite .htaccess rule to URL minus one character? A Newsletter was send with a token generated login URL inside. Accidentally a closing square bracket ] was placed as the URL's last character and the login links now doesn't work. How to redirect any URL with a closing square bracket to the same URL without the square bracket?

A: You can either use mod_alias and the RedirectMatch directive or mod_rewrite and the RewriteRule directive. If you already are using mod_rewrite elsewhere, it may be more prudent to stick with mod_rewrite, otherwise it doesn't matter:
RedirectMatch 301 ^/(.*)\]$ /$1

or
RewriteEngine On
RewriteRule ^(.*)\]$ /$1 [L,R=301]

A: You can use this rule:
RewriteEngine On

RewriteRule ^(.+?)]$ /$1 [R=301,L,NE]


text:
Q: how do you use a string in a while loop and then number the string? in my intro to programming class. I am supposed to make a program that asks the user to enter his/her name and then use a while loop to print the name in the following manner:
(user entered Caroline)

*

*C

*a

*r

*o

*l

*i

*n

*e

Caroline, there are 8 letters in your first name.
--I've tried a bunch of things but still can't figure it out.--This is what I have so far

A: Assuming you are correctly getting the user entered string from the STDIN.
You may look to do something like this in your language of choice:

*

*Find the length of your string

*Use the while loop, with the condition relating to the length of your string, to move through the string character by character

*Print out to a newline each individual character in your string

Feel free to ask questions and I would be happy to elaborate. Adding some examples of your code so far and the problems your facing would be useful.

A: In C++, this would be:
#include<iostream>
#include<string>
using namespace std;
int main()
{
  int i=0;
  string s;
  cin>>s;
  while(i<s.length())
  { cout<<i+1<<"."<<cout<<s[i]<<endl;
    i++;
  }
cout<<s<<", "<<"There are "<<s.length()<<" letters in your first name.";
return 0;
}

This is also very similar in Java, you should be able to derive it looking at this if you expected it in a programming language of your choice.

A: inside your main method try this:
    //Asks user name.
    System.out.println("What's your name?");

    //Instantiates scanner
    Scanner sc = new Scanner(System.in);

    //With the scanner it reads user input and save it in the variable name
    String name = sc.nextLine();

    //It is a good programming practice to close the scanner
    sc.close();

    /*The loop that for each letter of the name also prints the position
    number plus 1*/
    int i = 0;
    while (i < name.length()) {

        System.out.println(i+1 + ". " + name.charAt(i));
        i++;
    }

A: As per snap shot shared by OP:

Here, you need to modify this lines:
System.out.println(name.charAt(i));

to
System.out.printf("%d. %c%n",(1+i),name.charAt(i));

Also, change this line:
  i++;
}}}

to
  i++;
}
System.out.printf("%s, there are %d letters in your first name%n",name,i));
}}


text:
Q: Why do I get this error message when I press my button? I have defined a button in my layout xml file:
<Button
   android:id="@+id/my_btn"
   android:layout_width="30dip"
   android:layout_height="20dip"
   android:text="@string/click_me"
   android:textSize="10dip"
/>

In my activity class I handle the click event with the following code:
 Button myBtn = (Button) findViewById(R.id.my_btn);
 myBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                 showToast();
            }
          });

public void showToast() {
        Context context = getApplicationContext();
        CharSequence text = "button clicked";
        int duration = Toast.LENGTH_SHORT;

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

I run my application, when I press the button, I got the following error message from Eclipse LogCat console:

I do not understand what does this error message mean? What does it complain about? Where am I wrong?
(Please mouse right click on the following image, and view image)
If you got problem of viewing the above image , I write the error message here below:
ActivityThread | enter process activity msg=120

ActivityThread | exit process activity msg=120

WindowManager  | waitForLastKey: mFinished=true, mLastWin=null

ViewRoot enter | Dispatching touchevent to com.android.internal.policy.impl.PhoneWindow$DecorView@2fde0c80 touchevent action is 0 X=219.54167 Y=505.3675
...
...

P.S. I got this error after I change the button size and background drawable, sounds odd...I feel very strange too.
-----UPDATE--------
layout file:
<RelativeLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dip">

            ...
        <TextView
        android:id="@+id/upper_text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="10sp"
        android:textStyle="bold"/>

    <Button
        android:id="@+id/my_btn"
        android:layout_toRightOf="@id/upper_text1"
        android:layout_alignTop="@id/upper_text2"
        android:layout_width="80dip"
        android:layout_height="20dip"
        android:background="@drawable/btn_bg"
        android:text="@string/click_me"
                        />
...
...

A: Toast.makeText(ClassName.this, "button clicked", Toast.LENGTH_SHORT).show();

please try it

A: Your error is in this line....
android:textSize="10dip"
The textSize must be specified in sp instead of dip.replace your code with->
android:textSize="10sp" and you are done!

A: Try this ::
 Button my_btn;
 my_btn = (Button) findViewById(R.id.my_btn);

 my_btn.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {

Toast.makeText(getApplicationContext(), "button clicked", Toast.LENGTH_SHORT). show();
}


text:
Q: What is the purpose of  within association definition in a content model? I noticed this within the person model (Didn't pick up on it the first time):
 <associations>
    <association name="cm:avatar">
       <source>
          <role>cm:avatarOf</role> <!-- What is the purpose of this?? -->
          <mandatory>false</mandatory>
          <many>false</many>
       </source>
       <target>
          <class>cm:content</class>
          <role>cm:hasAvatar</role>
          <mandatory>false</mandatory>
          <many>false</many>
       </target>
    </association>
 </associations>

I am duplicating this association for my own model and would like to know it's significance of this element within associations.

A: The info is informational only, the value can even be retrieved via the JavaScript API.
Information can be found here: https://issues.alfresco.com/jira/browse/MNT-7403


text:
Q: The toggling methods of jQuery I have browsed several tutorial sites to get more information about this, but I have not found any which focuses on this topic.
Apart from jQuery hide/show, jQuery fade and jQuery slide are there any other toggling methods in jQuery?

A: Yes of course there are few more methods like-

*

*slideDown()

*slideUp()

*addClass()

*removeClass()

*toggleCLass()

please refer the official website .
https://api.jquery.com


text:
Q: Android Studio build file R broken I am working on an android app which has worked and been tested many times. Today, however, in attempting to run the application for further testing, I have encountered the following error message:
C:\Users\1000\AndroidStudioProjects\WarofSol\app\build\generated\source\r\debug\com\blacktentdigital\warofsol\R.java
Error:(1251, 32) error: identifier expected
Error:(1251, 34) error: illegal start of type
Error:(1251, 35) error: identifier expected
Error:Execution failed for task ':app:compileDebugJava'.
Compilation failed; see the compiler error output for details.

>Information:BUILD FAILED

The problem is in the R.java file (as listed above). It is a generated file, so I've never touched it.
The offending line is this:
public static final class drawable {
    public static final int 3=0x7f020000;

Hover over the offending line gives the following warning: "Identifier expected | Unexpected token"
Comparisons to other R files reveal that the "3" is not supposed to be a 3, and is evidently corrupted.
Attempts to replace the line or file with older backed-up versions have failed to produce any result because (evidently) the file is regenerating the wrong way each time I attempt the build, and I have no idea what might cause this. As I say, the problem sprang up suddenly without any provocation of which I am aware.
I've also attempted closing the program and restarting the computer to no avail.
Any ideas as to what might cause this and how it might be fixed?

A: I did get the Same error when i have defined a String in xml file like this.
<string name="3">Settings</string>

Error:
Error:(1426, 32) error: <identifier> expected
Error:(1426, 34) error: illegal start of type
Error:(1426, 35) error: <identifier> expected
Error:Execution failed for task ':app:compileDebugJava'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED

Solution: Resource name must begin with character.
 So i have just change String like <string name="S3">Settings</string> and it worked.
So just check if you have any resource name 3 in all your resource file(string.xml, style.xml, attrs.xml) and folder(drawable, layout).

A: This is a quote from java documentation:

A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_".

And you named drawable with digit, that caused the problem.


text:
Q: Swift % not computing correctly I have code that examines if a variable elapsedTime (double) is a multiple of 0.4. i.e. 0.4, .0.8, 1.2, 1.6 etc code checks like so:
    let roundedInterval = Double(round(timeInterval*10)/10) //(this is 0.4)
    let roundedActualElapsedTime = Double(round(actualElapsedTime*10)/10)

        if roundedActualElapsedTime%roundedInterval == 0 {

             print("is a multiple of 0.4")
    }

However from my results output 0.4, 0.8, 1.6, 3.2 are being reported as multiples, so it is missing values. Any ideas what I might be doing wrong here?
NOTE: roundedTimeInterval remains constant at 0.4 and roundedActualElapsedTime increments in 0.1s i.e. 0.1, 0.2, 0.3, 0.4... etc

A: The % operator for Float and Double is probably going to be removed in Swift 3.0, so you should not rely on it. See this swift-evolution thread for the discussion.
Furthermore, you need to learn more about floating point numbers. Floating point numbers (as implemented on all of Apple's platforms) can only represent numbers of the form m * 2e, where m and e are integers (and may be negative). Only integer multiples of a power of two (including negative powers like 1/2, 1/4, 1/8, etc.) can be represented exactly, and numbers like 0.1, 0.2, and 0.3 are not integer multiples of any power of two. (Note that 0.5 is an integer multiple of a power of two: it's 2-1.)
Thus when you take round(timeInterval * 10) and divide it by 10, you generally get an inexact result, and in general you shouldn't expect the remainder of two inexact results to be exactly zero.
What you probably want to do is work with deciseconds (tenths of seconds) as integers, since then you're dealing with exact numbers:
let roundedTenths = Int(round(timeInterval*10))
let roundedElapsedTenths = Int(round(actualElapsedTime * 10))
if roundedElapsedTenths % roundedTenths == 0 {
    print("is a multiple of 0.4")
}


text:
Q: Ajax Php Image Upload and Save I want to upload an image and save it in the uploads folder without refreshing the page. Furthermore, I also want to display the uploaded image on the screen in a div. However, when I run the code, when I try to upload an image, the text continues to say "Image Uploading..." and never finishes to actually upload. Therefore, the image never gets displayed on the page. Additionally, I am having trouble saving my image in the uploads folder, so can someone point me in the right direction? Thank you!
UPDATE: The Ajax POST gets an error each time I try to to upload an image. In fact, the POST request might not even reach my upload.php file. I trie d to alert myself when the request actually reaches upload.php but nothing ever prints out. What may be the potential causes of this?
UPDATE #2: I have included a picture of my file layout. I have the HTML and Javascript in privatecreate.blade.php and the Javascript in upload.php. I want to save the images in uploads folder.

Update #3: I printed out the ajax error and it is "No Input File Specified"
Please bear with my everyone. This is my absolute first time working with php and sql and I am trying my hardest to learn.
HTML:

                                        Select Image
                                        <input type="file" name="file" id="file" />

Javascript:
 $(document).ready(function(){
    $(document).on('change', '#file', function(){
        var name = document.getElementById("file").files[0].name;
        var form_data = new FormData();
        var ext = name.split('.').pop().toLowerCase();

        if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
        {
            alert("Invalid Image File");
        }
        else{
            var oFReader = new FileReader();
            oFReader.readAsDataURL(document.getElementById("file").files[0]);
            var f = document.getElementById("file").files[0];
            var fsize = f.size||f.fileSize;
            if(fsize > 2000000)
            {
                alert("Image File Size is very big");
            }
            else
            {
                form_data.append("file", document.getElementById('file').files[0]);
                $.ajax({
                    url:"upload.php",
                    method:"POST",
                    data: form_data,
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend:function(){
                        $('#uploaded_image').html("Image Uploading...");
                    },
                    success:function(data)
                    {
                        $('#uploaded_image').html(data);
                    }
                    ,error: function(ts)
                    {
                        alert("error:" + ts.responseText);
                    }
                });
            }
        }
    });
});

PHP (upload.php):
<?php
//upload.php
$message = "Running Upload.php";
echo "";
if($_FILES["file"]["name"] != '')
{
    $test = explode('.', $_FILES["file"]["name"]);
    $ext = end($test);
    $name = rand(100, 999) . '.' . $ext;
    $location = 'uploads/' . $name;
    move_uploaded_file($_FILES["file"]["tmp_name"], $location);
    echo '';
}
?>

A: <?php
//Change your location path
if($_FILES["file"]["name"] != '')
{
    $test = explode('.', $_FILES["file"]["name"]);
    $ext = end($test);
    $name = rand(100, 999) . '.' . $ext;
    $location = 'upload/' . $name; // change here & enjoy
    move_uploaded_file($_FILES["file"]["tmp_name"], $location);
    echo '';
}
?>


text:
Q: BufferedWriter overwriting itself I want to read in a file and create a duplicate of the file but my code only write the last line in the file. How do I make so that whenever I call write(), it writes to a new line. I want to create a new file for the duplicate so I can't add true to FileWriter constructor.
This is my code:
    //Create file reader
    BufferedReader iReader = new BufferedReader(new FileReader(args[1]));

    //Create file writer
    BufferedWriter oWriter = new BufferedWriter(new FileWriter(args[2], true));

    String strLine;
    //reading file
    int iterate = 0;
    while((strLine = iReader.readLine()) != null)  {
        instructions[iterate] = strLine;
    }

    //creating duplicate
    for(int i = 0; i < instructions.length; i++) {
        if(instructions[i] != null) {
            oWriter.write(instructions[i]);
            oWriter.newLine();
        }  else {
            break;
        }
    }

    try {
        iReader.close();
        oWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

A: You are not incrementing iterate
 int iterate = 0;
 while((strLine = iReader.readLine()) != null)
{
    instructions[iterate] = strLine;
    iterate++;
}

A: You're not updating the index of the instructions array.
In addition, it's not immediately clear why you're copying the file this way anyway; why bother doing it line-by-line? Or just use a utility class, like from Apache Commons.


text:
Q: How Rest Controller handle multiple request at same time for a single instance application?
*

*If multiple request are hit to a single RestController at the same time in a application, how it is handle for different scenarios (Multiple request to a single endpoints (only GET), or Multiple requests for multiple endpoints(GET, POST, PUT...))

*Is multi-threading concept utilized? If yes is it possible to handle the requests in FIFO pattern?

*What is the maximum request a RestController can take ?

*Does RestController scope affect handling of requests (behavior of request scope with default scope-singleton) ?

*Also how it is handle by Application context (example with flow will be helpful)

Considering building Micro-services with Spring Boot 2.

A: From the point of view of Spring (Application Context) rest controller is a singleton if not specified otherwise.
So the code of controller must be ready to be invoked by multiple threads simultaneously.
When a new request reaches the server, in a tradition thread-per-request model the web server (like tomcat) is responsible to allocate a thread from the predefined pool of threads to the request. Then the request gets processed by controller in the context of this thread.
The actual thread pool implementation can in general vary from server to server, but in general, its something that can be configured (number of threads per loop, queue size to store requests for future processing if the pool is full, etc.)
Now regarding the Scope of RestController. If the controller is stateless (and it should be for many cases, just keep it singleton). If you need the new Instance of controller to be created per request, than change the scope. Obviously each thread will have to use the same (in case of singleton scope) instance of rest controller or spring mvc will create a new instance of controller if you specify another scope.
All the answer above applies to a "traditional" thread-per-request model.
Note that since spring 5 / spring boot 2 spring also supports "Reactive" model with a webflux. It works on top of netty and doesn't utilize a thread-per-request model. Please specify in the question if you're interested in this model rather than a tradition model that I've tried to briefly describe.


text:
Q: Estimation with MLE and returning the score/gradient (QMLE) I am estimating a simple AR(1) process by the ML approach. I also wish to compute the Quasi MLE standard errors, which is given by the sandwich form of the Hessian and the Score (see for example the last slide here)
So, I start by just specifying the (conditional) log likelihood for the (gaussian) AR(1) process. Then I optimise this with R's optim, which returns the Hessian to me, evaluated at the MLE-estimates, which I use as my information matrix estimate, to get the standard errors of my parameters.
So far so good (I get the same results as with the stats toolbox in Matlab).
But, how do I proceed to estimate the QMLE standard errors? For that I need the  estimate of the outer product of the score function (i.e. the outer product of the gradient evaluated at the MLE estimates).
I have not found any way to get an estimate (numerically) for the gradient in any of R's optimization /ML commands. Am I missing something?. Thank you
data = read.table("Data/AR.txt", header=FALSE)
y = as.vector(data$V1) # A simple vector of observations: n1, n2, ... , nT

#Conditional LH
loglik = function(theta, y) {
  T = length(y)
  L = sum (dnorm(y[2:T],
       mean = theta[1] + theta[2]*y[1:T-1],
       sd = theta[3], log = TRUE))
  return (-L)
}

start=c(2.5, 0.6, 3)
b = optim(start, loglik, y=y, hessian=TRUE)
I = solve(b$hessian)
se = sqrt(diag(I)) # All good. The same MLE estimates and SE's as in Matlab.

EDIT:
I could perhaps try and use the numDeriv package to get the gradient of the likelihood function (evaluated at every observation). But I am stuck on exactly how to accomplish my goal, as I don't know how to rewrite my likelihood function for that purpose...
EDIT2: NA
EDIT3: Sorry for my stupidity, the sum of outer products is of course not the same as the outer product of the sums. It seems consistent now:
sum = numeric(3)
for (t in 2:length(y)) {
  g = grad(LLi, x=b$par, y=y, t=t)
  sum = sum + outer(g,g)
}

I2 = solve(sum)
se2 = sqrt(diag(I2))

Where LLi is the Likelihood function for each observation:
LLi = function(theta, y, t) {
  L = dnorm(y[t],
                 mean = theta[1] + theta[2]*y[t-1],
                 sd = theta[3], log = TRUE)
  return (L)
}

Which gives me standard errors:
> se2
[1] 0.41208510 0.04256279 0.10242072

Which is reasonably identical(?) to those obtained by the Hessian:
> se
[1] 0.40621637 0.04179929 0.09874189

Any suggestions for improvements? Programming wise my approach doesnt seem that elegant. Thanks again.

A: The numDeriv package can indeed be used to compute the gradient
and the hessian (if needed). In both cases the argument y of the log-likelihood
is passed through the dots mechanism, using an argument with the suitable name. For a vector-valued function, the jacobian function of the same package can be used
similarly.
You could also consider computing analytical derivatives rather than
numerical ones.
library(numDeriv)
H <- hessian(func = loglik, x = b$par, y = y)
g <- grad(func = loglik, x = b$par, y = y)

We can compute as well the Jacobian of a function returning a vector of length $T-1$.
mlogDens <- function(theta, y) {
  T <- length(y)
  -dnorm(y[2:T], mean = theta[1] + theta[2] * y[1:(T-1)],
                 sd = theta[3], log = TRUE)
}
## a matrix with dim (T-1, 3)
G <- jacobian(func = mlogDens, x = b$par, y = y)
## a matrix with dim (9, T-1)
GG <- apply(G, MARGIN = 1, FUN = tcrossprod)
## a vector with length 9 representing a symmetric mat.
GGsum0 <- apply(GG, MARGIN = 1, FUN = sum)
## a symmetric mat.
GGsum <- matrix(GGsum0, nrow = 3, ncol = 3)


text:
Q: C# XNA Space Invaders. Tank bullet not showing The bullets in my code seem to be shooting the invaders, since the invaders disappear. However there is no bullet coming out of the tank and hitting the invaders. I don't know where the bullet went.
Initialize Code for bullet:
recBullet = new Rectangle();
isRight = true;
isShotFired = false;
isBulletOut = false;
isBulletAlive = true;

Update Code:
 KeyboardState keys = Keyboard.GetState();
 if ((keys.IsKeyDown(Keys.Space) == true || oldState.IsKeyUp(Keys.Space) == false))
        {
            recBullet.X = recTank.X + recTank.Width / 2;
            recBullet.Y = screenHeight;
            isShotFired = true;
            isBulletAlive = true;
        }if (isShotFired)
        {
            recBullet.Y -= 10;
        }
        if (recBullet.Y <= 0)
        {
            isShotFired = false;
        }
        for (int x = 0; x < numberOfXInvaders; x++)
        {
            for (int y = 0; y < numberofYInvaders; y++)
            {
                if (isBulletAlive)
                {
                    if (recBullet.Intersects(recInvader[x, y]))
                    {
                        if (!isInvaderDead[x, y])
                        {
                            isInvaderDead[x, y] = true;
                            isBulletAlive = false;
                        }

                    }
                }
            }
        }
oldState = keys;

Draw Code:
if (isBulletAlive)
        {
            spriteBatch.Draw(texBullet, recBullet, Color.Green);
        }

I appreciate any help I can get for this! Thanks.

A: Do the following steps:

*

*First check if your bullet image is being loaded properly

*Try to draw it on top of all your images. Put it on the last part of your Draw method.

*If it is still not there, try to comment out all your spriteBatch.Draw and leave the draw for your bullet. If it's there, try to check your logic on your draw. Some images might be overlapping.

*If steps 2 and 3 fails, repeat step 1


text:
Q: Android runOnUiThread - how to pass the Activity I'm writing a XMPP Client using SMACK.
So when I want to update my contactList - the ListAdapter.notifyDataSetChanged requires to be run in the UI thread, but obviously the SMACK Library uses Multithreading on the RosterListener (which in fact is a good thing). But here is the problem: to run s.th. in the UI thread, I need a valid context.
But how do I get it? Passing the Context of the Activity down to the register function of the RosterListener was the first that came to mind - but I have some functions in different classes there before I even get to the register function, and I don't really like it to pass the context over and over again until it finally reaches its destination, where it will be used.
I guess, I'm not the only one, who has encountered this problem, so how would you solve it?
Maybe a Singleton, just to save this one Context (in my opinion an even less favourable idea...)
Or is maybe my whole design flawed?
Is there a possibility to get the UI thread from anywhere?
Bottom line: I don't really have a clue how to handle it, at the moment I'm passing the context as argument through multiple functions, but is there a better way to do it.
Thanks for any help.

A: Put XMPP code into Service and then send broadcasts. Interested Activities can simply register for those broadcasts. That way you'll never again worry about UI thread and availability of Activity context.

A: I found a neater and more modular way of doing it. For this you need to have defined an Application Context. Once you have that, you can call RunOnUIThread from any class library without the mess of having a reference to the Activity.
From anywhere within your class library call:
Handler handler = new Handler(Application.Context.MainLooper);
handler.Post(() => doStuff());

Please bear in mind that this is written in C# as I use MonoDroid, but I believe it is very similar to Java.
For how to create an ApplicationContext look at this thread

A: I do not get what exactly you try to do but if you are in some thread and you want to shitch back to UIThread than
Looper is your solution
http://developer.android.com/reference/android/os/Looper.html

A: Reading you, I get a feeling like you are working with callbacks. Smack or whatever that is is calling you back from a worker thread, and you want to post to the main UI thread when that happens.
In my experience, callbacks can always be associated to a custom piece of data, which you pass when registering the callback, and receive when you are actually called back.
In your context there are two approaches which I consider to be poor design:

*

*using any kind of global thingy, call it a singleton if you like

*let your Model expect and return the (Android-and-UI-specific) Context

Instead, I would create a small interface which is implemented by the Activity, have the Model accept an instance of this interface, and yes pass it over the different layers until registration.
The methods exposed by this interface will be called asynchronously, which you could document appropriately, to indicate that runOnUiThread() or similar must be used.
This way, you're not exactly passing the Context (which is a platform and UI detail) all over the place and into the Model. Plus, you avoid global/static data, which leads to various problems, conflicts and other memory leaks.


text:
Q: How to get the current video frame while playing video by libvlcsharp? How to get the current video frame while playing video by libvlcsharp?
I can play video with libvlcsharp by the codes below:
public void OnAppearing()
        {

            LibVLC = new LibVLC();
            var media = new LibVLCSharp.Shared.Media(LibVLC, new Uri("http://live.cgtn.com/1000/prog_index.m3u8"));

            MediaPlayer = new MediaPlayer(LibVLC)
            {
                Media = media
            };

            media.Dispose();

            Play();
        }
private void Play()
        {

            if (m_url != string.Empty)
            {
                MediaPlayer.Play(new LibVLCSharp.Shared.Media(LibVLC, new Uri(m_url)));
            }

        }

A: You could use the TakeSnapshot method. However please note:

*

*The snapshot will be written to the disk, there's no way to get the frame in memory in VLC 3 (A new API for that will likely come in VLC4)

*This is not meant to grab every frame, use it only for a snapshot.

If you need more frames, have a look at the Thumbnailer samples. They're not meant to grab all frames either.


text:
Q: python re regular expression freezes processing on random text I have troubles with using re.
There are 2 re:
re.findall(r'\w+@\w+.\w+', text)
re.findall(r'[\+0-9\-\(\)]{8,20}', text)

I have ~10000 texts. And this regular expressions freezes python on random text while processing!
It could be 4000 or 4299 or another one.
Texts processes sequently. So I have no ideas why it could be...
Help me, please)

A: Not enough reputation to comment, so I'll response as an answer.
What is your purpose with the regex?
Is the first for email address and the second for phone number?
The second regex matches something like +9-()+8-()...
Try your regex here: https://regex101.com/
Or you can print out evey 10th or 20th line of text to find out which text failed.


text:
Q: Ruby Mysql - Failed to allocate memory error I have a large MySQL table of about 4 million rows, which I want to process with a ruby script.  At the moment, when I run the script I get a "failed to allocate memory (NoMemoryError)".  The query runs but the error pops up once I try to loop through the resultset.  Can I allocate more memory to the ruby heap space?
Currently, I am thinking of saving the resultset to a large file and the processing that file in chunks.
Any suggestion on an alternative course of action?
Thanks all,
s


text:
Q: DELETE C# SqlCommand: Subquery returned more than 1 value I have an error doing either a DELETE or INSERT using a C# SqlCommand; database is SQL server.
The SQL statement is
DELETE FROM [table_name]
WHERE id = 'some_id';

which is pretty simple.
id is a column name with datatype varchar(15) that can be NULL; some_id has 15 characters.
First, to verify that only 1 row with that ID exists, this SELECT query was made that returns no errors
SELECT *
FROM [table_name]
WHERE id = 'some_id';

returns 1 row
The error on the DELETE is

System.Data.SqlClient.SqlException (0x80131904): Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

This error can happen when more than 1 row satisfy the criteria of the query; clearly not the case here
What is puzzling is that doing the same DELETE query using the C ODBC API there is no error; so it seems the problem is in the C# code
C# code that calls DELETE:
public int execute(string sql)
{
    SqlConnection conn = new SqlConnection(conn_str);

    try
    {
        conn.Open();

        SqlCommand command = new SqlCommand(sql, conn);
        command.ExecuteNonQuery();
        conn.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return -1;
    }

    return 0;
}

C# code that calls SELECT:
public List<List<string>> select(string sql)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();

    List<List<string>> rows = null;
    SqlConnection conn = new SqlConnection(conn_str);

    try
    {
        conn.Open();

        SqlDataReader reader = null;
        SqlCommand command = new SqlCommand(sql, conn);
        reader = command.ExecuteReader();

        int nbr_cols = reader.FieldCount;
        int nbr_rows = 0;

        rows = new List<List<string>>();

        while (reader.Read())
        {
            nbr_rows++;
            List<string> col = new List<string>();

            for (int idx_col = 0; idx_col < nbr_cols; idx_col++)
            {
                 string str = reader[idx_col].ToString();
                 col.Add(str);
            }

            rows.Add(col);
        }

        reader.Close();
        conn.Close();

        sw.Stop();

        Console.WriteLine("Time to get {0} rows: {1} msec", nbr_rows, sw.ElapsedMilliseconds);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }

    return rows;
}

C++ DELETE code with no error
std::string sql = "DELETE FROM [some_table] WHERE ID='some_id';";
  if (query.exec_direct(sql) < 0)
  {
    std::cout << sql;
  }

where the function exec_direct is here
https://github.com/pedro-vicente/lib_odbc/blob/master/odbc.cc
thanks
EDIT
adding link to DELETE documentation
https://learn.microsoft.com/en-us/sql/t-sql/statements/delete-transact-sql?view=sql-server-2017


text:
Q: Is there any options in yocto bitbake to make the command autocomplete? Is there any options in yocto bitbake to make the command autocomplete?
For example
bitbake busybox -c <tab> should display the available tasks for that particular receipe

A: Please take use this repo - https://github.com/lukaszgard/bitbake-completion, which store bash completion scripts that allows to complete recipes and all subcommands for bitbake and other tools (like devtool and bitbake-layer). I am author of this repository so in case of any problem please let me know.


text:
Q: Convert fraction to an infinite series with alternating sign $$
f(m)=\sum_{n=0}^\infty{\Bigl(\frac{-1}{m}\Bigr)^n}\\
$$
converges at $\frac{m}{m+1}$ where $1 < m < \infty$. In other words, where $m$ approaches $1$ it converges at $0.5$ and where m approaches $\infty$ it converges at $1$.
Does that mean that I can multiply any real number $m$ with $2(f(m)-0.5)$ to converge at that number? It makes sense algebraically, although I might as well just multiply $m$ by $1$, but with an infinite series, $m$ should surely be factored into every term?
Is there maybe another way to convert a fraction into a variation of a geometric series?

A: The following series will converge at m:
$$\sum_{n=0}^\infty{\frac{1.5m}{-2^n}}$$


text:
Q: Self-Hosting WCF for AJAX Client I'm trying to self-host a WCF web service and provide a HTTP endpoint with ajax support. Pretty much everything I've found about WCF and AJAX are talking about IIS, which I don't want to use.
I've build a simple Console App to host the service. My service only have a single method:
[ServiceContract]
interface IMyService
{
    [OperationContract]
    string TestConnection();
}

And here's the app.config code:

<services>
  <service name="Service.MyService" behaviorConfiguration="MyServiceBehavior" >
    <endpoint address="" binding="webHttpBinding" behaviorConfiguration="WebBehavior" contract="Service.IMyService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>
</services>

<behaviors>
  <endpointBehaviors>
    <behavior name="WebBehavior">
      <enableWebScript/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="MyServiceBehavior" >
      <serviceMetadata httpGetEnabled="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>

I can access the service metadata endpoint and see the WSDL, but I'm unable to use it from my ajax client. So my question are :
1. Is it possible to do this?
2. What is the needed configuration that I'm obviously missing?
NOTE I'm not using a .svc file
Thanks!

A: What is your client? With enableWebScript, you're getting ASP.NET AJAX support (eg, decorated members, types, and all the othe goo that implies). If you want "raw" JSON, use the webHttp behavior instead of enableWebScript, and tag your interface operations with WebInvokeAttribute or WebGetAttribute (setting the request/response types to JSON or XML as you wish). It also looks like you haven't attributed your interface with ServiceContractAttribute, which is required.


text:
Q: populate vuetify select from an array of json Am a Newbie to VUEJS, am having trouble populating a vuetify select element with a names ofcountries from a local JSON file containing an array of a json objects.
Instead of populating the options it creates single select objects for each country.
Here is my Form....
<form>
  <v-select v-validate="'required'" v-bind="countryData"
  v-for="item in countryData" :key="item.name" :items="item.name"
  v-model="select" :error-messages="errors.collect('country')"
  label="Country" data-vv-name="country" prepend-icon="mdi-flag"
  required></v-select>
 </form>

This is my script.....
<script>
import Vue from "vue";
import VeeValidate from "vee-validate";
import countryData from '@/components/countryData.json';
Vue.use(VeeValidate);
export default {
  name: "signup",
  $_veeValidate: {
    validator: "new"
  },
  data: () => ({
    countryData: countryData,
    country: ''
    })
</script>

Here JSON file Structure...
[
    {
        "id": 1,
        "name": "Afghanistan",
        "iso3": "AFG",
        "iso2": "AF",
        "country_code": "4",
        "phone_code": "93",
        "capital": "Kabul",
        "currency": "AFN",
        "states": ["Badakhshan","Badgis"...]
    },
    {
        ...
    }
]

Output of my codes

A: You shouldn't use v-for to add data to the v-select component, you need only to pass contryData as value of items property :
 <v-select v-validate="'required'"
    :items="countryData"
    item-text='name'
    item-value='id'
    v-model="country"
    :error-messages="errors.collect('country')"
  label="Country" data-vv-name="country" prepend-icon="mdi-flag"
 required></v-select>

Note 'item-name' will control which field in your item object will be displayed, while 'item-value' will be the field that controls the selected option value.  I chose 'id' for that but depending on your use case you might pick 'country_code' or something else.


text:
Q: Search Box not visible when i come from save edit page When i edit the page and add a custom list web part in SharePoint 2013 and edit the web part go under Miscellaneous section and select 'Display search box' option. i am able to see the search box in the edit mode of the page. Once i save the page or publish the page. The search box is getting disappeared. WHY ???

A: We had the same issue and it is a bug that is fixed in Service Pack 1.


text:
Q: IndexError: list index out of range peek opeartion for stack in python class stack():
    def __init__(self):
        self.s=[]
    def push(self,x):
        self.s.append(x)
    def pop(self):
        if self.s==[]:
            return -1
        else:
            return self.s.pop()
    def peek(self):
        return self.s[-1]
    def isempty(s):
        return len(s)
    def size(self):
        return len(self.s)
def printNGE(arr):
    v=[]
    n=len(arr)
    s=stack()
    for i in range(n):
        if s.size()==0:
            v.append(-1)
        elif s.size()>0 and s.peek()>arr[i]:
            v.append(s.peek())
        elif s.size()>0 and s.peek()<=arr[i]:
            while(s.size()>0 and s.peek()<=arr[i]):
                s.pop()
            if s.size==0:
                v.append(-1)
            else:
                v.append(s.peek())
        s.push(arr[i])
        print('s z',s.peek(),s.size())
    return v
arr=[1,3,2,4]
x=printNGE(arr)
print(x)

I am trying to implement greatest integer to the left in python using stack, I am getting an eror , the code worked fine for greatest int to the left if you change the loop for(n-1,-1,-1)
File "c:\Users\Amit\Desktop\greatrightstak.py", line 42, in <module>
    x=printNGE(arr)
 File "c:\Users\Amit\Desktop\greatrightstak.py", line 35, in printNGE
    v.append(s.peek())
 File "c:\Users\Amit\Desktop\greatrightstak.py", line 13, in peek
    return self.s[-1]
IndexError: list index out of range

A: You just have a small error with missing brackets:
if s.size==0:

should be
if s.size()==0:


text:
Q: CSV Matrix into Mysql I'm trying to get this code working as it's exactly what i'm after:
http://www.reloadedpc.com/php/php-convert-csv-price-matrix-mysql-table/
Although I get this error:

Warning: array_merge() [function.array-merge]: Argument #1 is not an
  array in C:\xampp\htdocs\matrix\Csv.php on line 580
Warning: array_merge() [function.array-merge]: Argument #1 is not an
  array in C:\xampp\htdocs\matrix\Csv.php on line 580
Warning: array_merge() [function.array-merge]: Argument #1 is not an
  array in C:\xampp\htdocs\matrix\Csv.php on line 580
Fatal error: Cannot access protected property Csv::$field_names in
  C:\xampp\htdocs\matrix\index.php on line 24

Line 580 is the following of Csv.php is:
$this->contents[$line_nr][(int) $position] = array_merge( $this->contents[$line_nr][(int) $position] );

and Line 24 (and 23) of index.php is:
//get the row of width increments
$stack = $csv->field_names;

The Csv.php file can be viewed here:
http://hg.mijnpraktijk.com/csv-library/src/e4397b31002d/Csv.php
Any suggestions?
Thanks Guys.
-EDIT-
The whole code block is:
 foreach ( $this->contents as $line_nr => $line )
                {

                        if ( array_key_exists( (int) $position, $this->contents[$line_nr] ) )
                        {
                             $return[$line_nr] = $this->contents[$line_nr][(int) $position];
                                unset( $this->contents[$line_nr][(int) $position] );
                                // reindex after removal
                                $this->contents[$line_nr][(int) $position] = array_merge($this->contents[$line_nr][(int) $position] );
                        }
                }

It seems to unset it. $this->contents[$line_nr][(int) $position] is header of the matrix.

A: If you look at the last line of the error, it says:

Fatal error: Cannot access protected property Csv::$field_names in C:\xampp\htdocs\matrix\index.php on line 24

now go to the Csv.php link you posted and look in the code and you'll see that indeed field_names is defined as: protected $field_names = array();, this means you cannot access it directly unless you extend the Csv class.
If you don't want to extend this class just use the public method:
$csv->get_field_names();