text:
Q: Do static members enter objects? This is certainly an elementary question, but I must ask to clarify an issue of mine. If a class member is made static, it may be accessed without instantiation, with a syntax like class.member. When an object is created, does it receive the static member, and can that value be changed? Since a static member does not need objects, is it the same for any object? (ie changed in one, changed in the other).
Basically, how are static members implemented in objects, and how do they change?
and can they only be manipulated with static methods?
Thank you all.

A: You can technically change a static member with an instance like this:
SomeClass c = new SomeClass();
c.someStaticMember = 5;

However, that will create a warning, which it should. The correct way would be to do this:
SomeClass.someStaticMember = 5;

Since a static member does not need objects, is it the same for any object? (ie changed in one, changed in the other).

Again, technically yes, since you can do this:
System.out.println(c.someStaticMember);

That is incorrect though and will give you a warning; the correct way is:
System.out.println(SomeClass.someStaticMember);

A:
Do static members enter objects?

No. They are held in a different place, in fact in the class itself.

When an object is created, does it receive the static member

No.

and can that value be changed?

Yes, unless it's final, but that change affects the single static variable that is seen by all the instances.

Since a static member does not need objects, is it the same for any object? (ie changed in one, changed in the other).

Yes.

Basically, how are static members implemented in objects

They aren't. They are implemented in the class.

and how do they change?

When and if you change them.

and can they only be manipulated with static methods?

No, a static variable can be manipulated by any method that has access to it.

A: Let's Look at this.
First of all, remember that static methods (and for that matter static variables) associated with the Class not with any particular instance. Static methods exists even if you don't create any instances.
To access a static method you do this:
ClassName.staticMethodName(args)

Although, Java also allows you to access static variables using instance (object), however this is discouraged as it creates confusion as to whether the method is static or not.
objectName.staticMethodName(args)

Now to your questions:

When an object is created, does it receive the static member, and can that value be changed?

Static members exists with the defining Class not with any object. If the Static member is a mutable variable, then you can certainly change it's value. Everyone (Class's own object, any other objects, any other static methods) will then see that same value.

Since a static member does not need objects, is it the same for any object? (ie changed in one, changed in the other).

Yes. Note though, at the expense of repeating myself, that static members are associated with the Class, not the object.

Basically, how are static members implemented in objects, and how do they change? and can they only be manipulated with static methods?

Oh man, this is getting tiring :) Static members are NOT implemented in object. They can be manipulated from other static and non-static method (basically from anywhere provided permissions are there). However, static members cannot see any instance variables unless they define that instance.

A:
When an object is created, does it receive the static member, and can that value be changed?

yes of course you can change the value of a static member using an object but it's better if you you change it using the class name.

Since a static member does not need objects, is it the same for any object?

yes again, a static member means that this member is the same in all instances created of this class and can be accessed through any object or through the class name.

how do they change?

there is 2 ways to change the value of a static member:
public static int x = 5;
Object.x = 10;
Class.x = 20

and both methods to change the static member value are correct, however the first method will give you a warning, the second will not.

A: In addition to @Doorknob's answer, specifically in response to:

and can they only be manipulated with static methods

You are able to access and change static members in various ways as shown below:
public class Foo {

    public static String BAR = "BAR!!";

    public static void changeBAR() {
        BAR = "BAZ!";
    }

    public void instanceMethod() {
        // some code
        BAR = "CHANGED AGAIN!";
        // some code
    }

    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(Foo.BAR);

        Foo.changeBAR();
        System.out.println(Foo.BAR);

        f.instanceMethod();
        System.out.println(Foo.BAR);

        Foo.BAR = "WHATS HAPPENING";
        System.out.println(Foo.BAR);
    }
}

Will result in:
BAR!!
BAZ!
CHANGED AGAIN!
WHATS HAPPENING


text:
Q: Libgdx making lists and scrollpanes wrap text? I was wondering, if there is anyway to make a ScrollPane and Lists that wrap text horizontally in LibGDX. I would love the scroll pane to scroll vertically but for it to wrap its text instead of scrolling horizontally.
I know I can disable the X direction of scrolling by using
scrollPane.setScrollingDisabled(false, true);

but is there anyway to make the text wrap so that there is no horizontal scrolling and it would just go to a new line?

A: You can do in this way :
public class ScrollPaneTest extends ApplicationAdapter {
    private Stage stage;
    private Table container;

    @Override
    public void create () {
        stage = new Stage();
        Skin skin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
        Gdx.input.setInputProcessor(stage);

        container = new Table();
        stage.addActor(container);
        container.setFillParent(true);

        Table table = new Table();

        final ScrollPane scroll = new ScrollPane(table, skin);
        scroll.setScrollingDisabled(true,false);

        table.pad(10).defaults().expandX().space(4);
        for (int i = 0; i < 100; i++) {
            table.row();

            Label label=new Label(i + ". Publish your games on Windows, Mac, Linux, Android, iOS, BlackBerry and HTML5, all with the same code base.", skin);
            label.setAlignment(Align.center);
            label.setWrap(true);
            table.add(label).width(Gdx.graphics.getWidth());
        }

        container.add(scroll).expand().fill();
    }

    @Override
    public void render () {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

    @Override
    public void resize (int width, int height) {
        stage.getViewport().update(width, height, true);
    }

    @Override
    public void dispose () {
        stage.dispose();
    }
}

And the output is :

A: You can wrap the text by using Labels. Then add those Labels to your scrollpane.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to parseFloat in a bulk update Mongo operation So I have a few fields that are currently strings that I am converting over to Double values in my mongo database. I was originally doing it with a find.forEach(function()).... style but that was taking way too long so I decided to try out the bulk operations Mongo has. So here is my attempt:
var bulkOp = db.transactions.initializeOrderedBulkOp();
bulkOp.find({"tran.val": {$exists: true}}).update(
    {
      $set: {"tran.val":parseFloat("$tran.val")}
    }
);
bulkOp.execute();

When I do this my tran.val which use to be "1.35" or something along those lines now becomes NaN. I also tried without the $ on tran.val but no luck. Am I missing something?


text:
Q: Streaming audio for Ruby on rails application running on LAN with front end server & Audio files on different machines? I have a ruby on rails application:
1. It use jplayer as audio player
2. Right now the audio files and the application server are on one machine.
3. I want to separate audio files and server running application on different machines .So that I can stream audio from their on LAN.
4. I have already separated the database from the server running application
5. I am using cent 0S 5.8 in all 3 machines
   one for running ROR application , 2nd for database, 3rd for audio streaming.
can any one give me an Idea
thanks

A: Ignoring streaming for now,  here is a simple example of a rails app calling another rails app :
require 'net/http'
require 'uri'
url = URI.parse("http://yourother.com/getaudio/#{@audio.id}")
req = Net::HTTP::Get.new(url.path)
resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req)}
play_your_audio(resp.body)

Note the use of GET,  so we don't have to worry about authenticating.
Here is a good article about streaming IO and Rails:
http://www.intridea.com/blog/2012/5/24/building-streaming-rest-apis-with-ruby


text:
Q: spring data neo4j 2.3.4 - ImpermamentDatabase and version of dependent jars Today I wanted to write some tests that use ImpermamentDatabase, on Neo4j page: http://docs.neo4j.org/chunked/stable/tutorials-java-unit-testing.html it says that neo4j-kernel jar must be added with <type>test-jar</type> for it to containt test classes.
Now, here is my build.sbt:
name := """scheduling-backend"""

version := "1.0"

scalaVersion := "2.10.2"

resolvers += "spray repo" at "http://repo.spray.io"

resolvers += "spray nightlies" at "http://nightlies.spray.io"

resolvers += "SpringSource Milestone Repository" at "http://repo.springsource.org/milestone"

resolvers += "Neo4j Cypher DSL Repository" at "http://m2.neo4j.org/content/repositories/releases"

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor" % "2.2.0",
  "com.typesafe.akka" %% "akka-slf4j" % "2.2.0",
  "ch.qos.logback" % "logback-classic" % "1.0.13",
  "io.spray" % "spray-can" % "1.2-20130712",
  "io.spray" % "spray-routing" % "1.2-20130712",
  "io.spray" %% "spray-json" % "1.2.3",
  "org.specs2" %% "specs2" % "1.14" % "test",
  "io.spray" % "spray-testkit" % "1.2-20130712" % "test",
  "com.typesafe.akka" %% "akka-testkit" % "2.2.0" % "test",
  "com.novocode" % "junit-interface" % "0.7" % "test->default",
  "org.springframework.scala" % "spring-scala" % "1.0.0.M2",
  "org.springframework.data" % "spring-data-neo4j" % "2.3.4.RELEASE",
  "org.springframework.data" % "spring-data-neo4j-rest" % "2.3.4.RELEASE",
  "javax.validation" % "validation-api" % "1.1.0.Final",
  "com.github.nscala-time" %% "nscala-time" % "0.8.0"
)

scalacOptions ++= Seq(
  "-unchecked",
  "-deprecation",
  "-Xlint",
  "-Ywarn-dead-code",
  "-language:_",
  "-target:jvm-1.7",
  "-encoding", "UTF-8"
)

testOptions += Tests.Argument(TestFrameworks.JUnit, "-v")

when looking in Intellij I can see that I have for example neo4j-kernel dependency in version 1.9.3, shouldn't it include jars in 2.X version?
Another question, is it safe for me to just add neo4j-kernel with type test-jar in newest version or should I add it in the 1.9.3 version (like the existing jar)

A: You have this dependency org.springframework.data:spring-data-neo4j:2.3.4.RELEASE which means it will use Neo4j 1.9.3 (including testing).
If you want the latest Neo4j release (2.0 / 2.0.1) then use org.springframework.data:spring-data-neo4j:3.0.0.RELEASE.
You must use the same testing version as the normal version. Otherwise you might get tricked into thinking that some things work on the test version (and since it's newer some bugs might be fixed), but in the normal version it will fail.


text:
Q: How to remove unwanted ad sense ads from Home Page? Some of my viewers are reporting seeing (unwanted) ads from ad sense on the top of my Home Page at wwww.shifter.pt
I've already changed the FTP access password, DB password and the passwords from all users of the website. Restarted the server and nothing changed.
The code from the ads looks like this and it's located before the header:

<iframe width="728" height="90" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&&s.handlers,h=H&&H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&&d&&(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_0" name="aswift_0" style="left:0;position:absolute;top:0;">

<iframe width="336" height="280" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&&s.handlers,h=H&&H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&&d&&(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_1" name="aswift_1" style="left:0;position:absolute;top:0;">

<iframe width="320" height="100" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&&s.handlers,h=H&&H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&&d&&(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_2" name="aswift_2" style="left:0;position:absolute;top:0;">

Thank you for your time!
EDIT
I've been able to block the code from showing on desktop version of the website but the problem remains when you access the website on the Facebook in-app browser for example.

A: You could probably do it like this:
$(document).ready(function(){
    $('.adsbygoogle').css('display','none');
});

JSFiddle Demo
But that isn't really a good fix, you should probably contact Google and see if they can fix it.

A: This is my 99.9% guess based on your report: your problem is your hosting provider, who are attempting to make money off their hosted sites by inserting ads at the top of pages.
While there are potentially some awkward hacks you could use to take them out (my guess is you can somehow use JavaScript to go through the DOM and delete the DOM nodes, assuming you even have that much control over the content), my answer, for Stack Overflow purposes, is: find a different hosting provider. You may have even signed an agreement allowing them to add the ads in this way, in which case taking them out might violate their hosting terms. In any case, allowing the hosting provider to insert ads at the top of pages is -- I am hoping -- a very uncommon way to do this, so it should be easy to find a mechanism where that won't happen.
The discussion about who to use as a host, or how to find one, is unfortunately outside the scope of Stack Overflow.


text:
Q: Query statistics on number of nodes created or edges added OpenCypher provides statistics on number of nodes created or number of edges updated as a result of query execution :
queryResult.summary?.updateStatistics?.updates()?.nodesCreated

I'm trying to find if there's a similar mechanism for Gremlin; explain/profile API return predicates but not the information on number of edges/nodes affected.
I'd appreciate any insights.
Edit:
For example, the query below:
const traversal = this.__.addV(label) .property(GREMLIN_ID, id) .property("created_timestamp", new Date().getTime()); this.logger.info("Add vertex if not exist ");
const v = await this.g .V(id) .fold() .coalesce(this.__.unfold(), traversal) .elementMap() .next();
return v.value;

This would add a new vertex only if it doesn't already exist; when it does get executed though, would like to find if there's a way to see the number of "new" nodes added as a result of the query execution.
Update:
With Kevin's solution, was able to retrieve edge counts as well:
g.inject(0).store('edgeCount').coalesce(
          V('0000x', 'facade00-0000-4000-a000-000000000000')
          .hasLabel("FINGERPRINT")
          .outE()
          .where(V().with('0000x', 'facade00-0000-4000-a000-000000000000')),
        V('0000x', 'facade00-0000-4000-a000-000000000000')
        .hasLabel("FINGERPRINT")
        .as("from")
        .V('0000x', 'facade00-0000-4000-a000-000000000000')
        .hasLabel("RDC_VISITOR_ID")
        .as("to")
        .addE("ANONYMOUS")
        .from("from")
        .to("to")
        .sideEffect(constant(1).store('edgeCount'))
      ).project('edge','count').by().by(cap('edgeCount').unfold().sum())

This gives:
{'edge': e[191][0000x-ANONYMOUS->facade00-0000-4000-a000-000000000000], 'count': 1}

And count becomes 0 with further executions. Thanks!

A: Here is a way to keep track of work done by the query using store. I was not able to get it to work the way I wanted using sack. If I figure that out, I will update the answer.
The count should be one as we are creating a new vertex.
gremlin> g.inject(0).store('x').
......1>   V('A1').
......2>   fold().
......3>   coalesce(
......4>     unfold(),
......5>     addV('test').property(id,'A1').sideEffect(constant(1).store('x'))).
......6>   project('vertex','count').
......7>     by().
......8>     by(cap('x').unfold().sum())
==>[vertex:v[A1],count:1]

It's created now, so the count should be 0.
gremlin> g.inject(0).store('x').
......1>   V('A1').
......2>   fold().
......3>   coalesce(
......4>     unfold(),
......5>     addV('test').property(id,'A1').sideEffect(constant(1).store('x'))).
......6>   project('vertex','count').
......7>     by().
......8>     by(cap('x').unfold().sum())

==>[vertex:v[A1],count:0]


text:
Q: Adding jquery event listener to a login form I added a javascript event listener to a function called validate and it worked fine. Now I'm thinking if it is possible (I bet it is) to change it to jquery event listener? I'm not really sure should I use submit or click or whatever?
HTML:
<button id ="clickButton" class="sign-in">Sign In</button>

JavaScript:
var login = document.getElementById("clickButton");
login.addEventListener('click', validate, false);

A: I think it's better to use click event listener. Here is how you can do this in jquery:
$(function(){
   $("#clickButton").click(function(){
      // Your code here.
   });
});

Working fiddle: http://jsfiddle.net/A72Jk/

A: You can use .click() to register a click event handler, to select the element using id use the id-selector
$('#clickButton').click(validate)


text:
Q: Selenium can't find elements even after timeouts I am trying to scrap a web page, but I am having problem when I try to access the element after the click action.
When the loop starts the second time I get "stale element reference: element is not attached to the page document".
I understand that Selenium can't found element - checkbox for another fare and departuretime div. I tried to put all kind of timeouts, try blocks, refresh the page. But in the end the result is the same - can't find element or get selenium.common.exceptions.TimeoutException.
Maybe somebody has ideas on what is the problem? I just run out of ideas, how to fix it:(
P.S I am using Python, Selenium and webdriver.chrome.
UPDATE:
I changed webDriver to Firefox geckodriver, deleted  "wait.until(EC.title_contains(fare.get_attribute('id')))" at the end of the loop and add  "driver.implicitly_wait(10)" in the end. Now it is kind of working. Tried to add implicity_wait to code with chrome driver but it was causing the same exceptions. So can the problem be with the chrome webdriver???
My code example:
fares =driver.find_elements_by_xpath("//td[@class='inputselect
standardlowfare']/div[1]/input[starts-
with(@id,'FlightSelectOutboundStandardLowFare') and @type='radio']")

wait = WebDriverWait(driver, 10))
    # elem = wait.until(EC.title_contains((fare.get_attribute('id'))))
    # wait.until(EC.refreshed(EC.staleness_of(fare.get_attribute('id'))))
    # driver.implicitly_wait(10)
    # wait = WebDriverWait(driver, 30)
for fare in fares:

  fare.click()
  print("clicked " )
  time.sleep(5)
    # driver.get(driver.current_url)
    # wait.until(EC.title_contains(('selectiontable')))

  departureTime = driver.find_element_by_xpath("//* [@id='ctl00_MainContent_ipcAvaDay_upnlResSelection']/div[1]/div/table/tbody/tr[4]/td")
  print ("Departure time " + departureTime.text)
  wait.until(EC.title_contains(fare.get_attribute('id')))


text:
Q: Exporting files while running .m file from command line I have the following code in a .m file which is called test.m:
Export["test.csv",0];
Exit[]
I would like to run this .m file from the command line. I found that I can do that with the command "math -initfile test.m". It seems to work, but when I check out the produced .csv file (it does get produced), I find that it's empty (so does not contain 0). When I run the .m file using the GUI it produces the .csv file with 0.
Anyone know how I can get this working from the command line?
Thanks

A: I can reproduce something similar to your issue but I cannot fully understand why.
However, if you want an alternative command, that works at least on Windows 7, here is how to do.
Add the mathematica installation folder in the system's path variable.
From the command line, move to the folder where the test.m file is saved (I have it in "C:\temp\") and run the following

math < test.m

using -initfile seems to have a different behavior because it asks to me the mathkernel file to run and then generates the empty file test.csv. Differently, using the < it works fine. Moreover, note that using < you don't need to add Exit[] in the code, the kernel automatically exits after the last computation. So, the test.m content is just

Export["test.csv", 0]

I hope this works for you too.

A: One possible workaround: It turns out that low level Open/Write i/o works from an initialization file. If the output is something simple like csv you can just roll your own.
 f=OpenWrite["test.csv"];
 WriteString[f,"1,2,3\n"];
 Close[f];

ExportString and Import also do not work by the way.


text:
Q: Jquery mobile Link clicked twice the page disappears I have the problem that when I click a navigation link it shows the page as it should. But if I click on the link again it loses all of its contents.
Is there someone who knows how I solve this?
I use jquery.mobile-1.0b2.min.js

TIL DIG

KONTAKT / BOOKMØDE

Dette er siden TIL DIG

      Jeg er nummer 3

Dette er siden KONTAKT / BOOKMØDE

Java
http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js
http://code.jquery.com/jquery-1.4.4.min.js

A: I think i know what your problem is - at least I had some very similar stuff where a listview kept dissapearing - had to do with jqm caching.

This attribute made the page reappear, hope it helps


text:
Q: Can a sequence have infinitely many subsequences that are disjoint? Can a sequence have infinitely many subsequences that are disjoint?
I wanted to prove the following,
Let $\{x_n\}$ be a sequence of a metric space with no converging subsequences. Then for each point outside the sequence $\{x_n\}$ has an open neighborhood that has no intersection with $\{x_n\}$.
Here is how I proceeded.
Let $\{ y_n \}$ be a subsequence and let $x$ be a point not in $x_n$. Since $y_n$ is not a convergent sequence it does not converge to $x$.
Therefore, for all $N>0$,  $\exists \epsilon>0$ such that $\{y_{n>N}\} \cap B(x,\epsilon) =
\emptyset$.
Since metric space is $T_0$ space, for any point $y_k \in  \{y_{n}\} $ we can find $B(x,\epsilon_k)$ not containing $y_k$. Now the set  $ U_y= \cap_{k\le N} B(x,\epsilon_k) \cap B(x,\epsilon) $ is an open set(intersection of finite number of open sets) with $U_y \cap \{y_n\} =\emptyset$.
Now consider the set $\{x_n\} - \{y_n\}$ and let $\{z_n\}$ be a subsequence of $\{x_n\} - \{y_n\}$. Then can find an open set $U_z$ such that $U_z \cap \{z_n\} =\emptyset$. Assume $\{x_n\}$ can only have a finite number of disjoint subsequences.
Then continue like that until we find finite number of points $S=\{x_n\} - \{y_n\}-\{z_n\} ...$. Again using the $T_0$ property, for each point $s \in S$, we can find an open ball around $x$, $B(x,\epsilon_s)$ that does not contain the point $s$. Therefore The set $U= \cap_{s\in S} B(x,\epsilon_s) \cap U_y \cap U_z \cap .. $ is a finite intersection of open sets that contain $x$ but does not contain $\{x_n\}$.
For the proof, I needed to use that there are only finitely many disjoint subsequences in $\{x_n\} $which I think should not be an assumption. Any comments or thoughts are really appreciated.

A: Consider the sequence
$$
1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, \ldots
$$

A: Let $Y$ be the metric space, $X = \left\{x_n; n\in \mathbb N\right\}$. Assume the inverse is true: $$\exists y \in Y,\, y\not\in X,\, \forall r > 0,\, X \cap B\left(y, r\right)\neq \emptyset$$
Let's construct by induction a subsequence $\left(x_{n_k}\right)$ of $\left(x_n\right)$ such that $d\left(x_{n_k}, y\right) \le \frac1{k+1}$. Indeed, using $r=1$, we will have our $x_{n_0}$. Now assume that we construct $x_{n_0},\ldots,x_{n_k}$. Since $y\neq x_{\ell}$ for $\ell\in\{1,\ldots,n_k\}$, let $r = \min \left\{\frac1{k+2}, \frac12\min\left\{d\left(y, x_\ell\right): \ell=1,\ldots,n_k\right\}\right\}$ and choose $x_{n_{k+1}}$ subsequently. Since $d\left(x_{n_k}, y\right)\to 0$, this contradicts the assumption you have on $x_n$.

A: All sequences with infinitely many distinct elements have infinitely many subsequences that are distinct. Simply consider a subsequence that includes "half" of the members. (I put "half" in quotes because there are different ways of defining "half" of infinity. But it doesn't matter how you define it.) Now consider a subsequence that includes half of the remainder. Etc.
But you don't really need finitely many subsequences. Your problem is that you're just blindly taking a subsequence and showing that it doesn't converge to $x$, which is known as the "denying the antecedent" fallacy. If you're trying to prove $\neg(\exists X: P(X))$, it's not very productive to go through $X$ after $X$ proving that each one doesn't have property $P$, rather than providing a proof about all $X$ at once.
But consider what happens if this sequence is not finite. Then we have an infinite sequence $S=\{x_n\}−\{y_n\}−\{z_n\}...$ If we can force this subsequence to converge to $x$, then that contradicts the hypothesis that there are no convergent subsequences. And if we can show that a converging subsequence can be constructed any time $x$ fails to have an open neighborhood disjoint from $\{x_n\}$, then this means we have proven the required proposition (if $\neg x \rightarrow y$, then $\neg y \rightarrow x$).
So how do we force the subsequence to converge to $x$? Well, converging to $x$ means that for any $\epsilon$, we have something within $\epsilon$. So take $\{z_n\}$ to have half the $\epsilon$ of $\{y_n\}$, and take the next one have half the $\epsilon$ of that, and so on. If we can do this infinitely many times without getting an empty set, then taking an element from  $\{y_n\}$, then taking an element from  $\{z_n\}$, etc., is giving a subsequence converging to $x$.


text:
Q: ffmpeg rotate 90 on Windows not working I have a video that was shot on an iPhone in portrait mode - when I run ffprobe on it, it shows the following information.
ffprobe version 3.4 Copyright (c) 2007-2017 the FFmpeg developers
  built with gcc 7.2.0 (GCC)
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libblur
ay --enable-libfreetype --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --ena
ble-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-z
lib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-cuda --enable-cuvid --enable-d3d11va --enable-nvenc --enable-dxva2 --enable-avisynth --enable-l
ibmfx
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '2017-01-14 01.19.10.mov':
  Metadata:
    major_brand     : qt
    minor_version   : 0
    compatible_brands: qt
    creation_time   : 2017-01-14T07:19:10.000000Z
    com.apple.quicktime.location.ISO6709: +29.8041-097.1844+107.044/
    com.apple.quicktime.make: Apple
    com.apple.quicktime.model: iPhone SE
    com.apple.quicktime.software: 10.2
    com.apple.quicktime.creationdate: 2017-01-14T01:19:10-0600
  Duration: 00:00:22.02, start: 0.000000, bitrate: 8342 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709), 1920x1080, 8244 kb/s, 29.98 fps, 29.97 tbr, 600 tbn, 1200 tbc (default)
    Metadata:
      rotate          : 90
      creation_time   : 2017-01-14T07:19:10.000000Z
      handler_name    : Core Media Data Handler
      encoder         : H.264
    Side data:
      displaymatrix: rotation of -90.00 degrees
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 87 kb/s (default)
    Metadata:
      creation_time   : 2017-01-14T07:19:10.000000Z
      handler_name    : Core Media Data Handler
    Stream #0:2(und): Data: none (mebx / 0x7862656D), 0 kb/s (default)
    Metadata:
      creation_time   : 2017-01-14T07:19:10.000000Z
      handler_name    : Core Media Data Handler
    Stream #0:3(und): Data: none (mebx / 0x7862656D), 0 kb/s (default)
    Metadata:
      creation_time   : 2017-01-14T07:19:10.000000Z
      handler_name    : Core Media Data Handler
Unsupported codec with id 0 for input stream 2
Unsupported codec with id 0 for input stream 3

I want to rotate it and remove the rotation flags so that it will play on media players that don't respect the rotation metadata.
When I run this command:
ffmpeg -hide_banner -i %1 -c:v libx264 -preset veryfast -crf 22 -metadata:s:v:0 rotate=0 -vf "transpose=clock" -c:a copy "%new_name%"

...instead of the video being rotated 90 degrees clockwise like I want, I get the video rotated 180 degrees. I've tried all the different transpose=x values, and I can't seem to get a command line that works.
I have other videos that were shot in landscape mode, but 'upside down' - those have a rotation flag of 180 degrees, and when I just let ffmpeg just 'auto rotate' those, it works great - I'm not sure why that doesn't work for the 90 degree case. When I try to just 'auto rotate' using this command:
ffmpeg -hide_banner -i %1 -map_metadata 0 -c:a copy "%new_name%"

I get a video file that (when played with Windows Media Player) has no video at all. VLC will play it just fine, but I'd really like it to work with Windows Media Player.
EDIT: Here is the output from ffprobe on that same file after it has been auto-rotated:
C:\>ffprobe "20170114-073811.mov"
ffprobe version 3.4 Copyright (c) 2007-2017 the FFmpeg developers
  built with gcc 7.2.0 (GCC)
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluay --enable-libfreetype --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enble-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-lib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-cuda --enable-cuvid --enable-d3d11va --enable-nvenc --enable-dxva2 --enable-avisynth --enable-ibmfx
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '20170114-073811.mov':
  Metadata:
    major_brand     : qt
    minor_version   : 512
    compatible_brands: qt
    creation_time   : 2017-01-14T07:38:11.000000Z
    encoder         : Lavf57.83.100
  Duration: 00:00:03.50, start: 0.000000, bitrate: 6189 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1080x1920, 6090 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 59.94 tbc (default)
    Metadata:
      creation_time   : 2017-01-14T07:38:11.000000Z
      handler_name    : DataHandler
      encoder         : Lavc57.107.100 libx264
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 88 kb/s (default)
    Metadata:
      creation_time   : 2017-01-14T07:38:11.000000Z
      handler_name    : DataHandler

A: If you're going to manually adjust the rotation, you should disable the auto-rotation.
ffmpeg -hide_banner -noautorotate -i %1
       -vf "transpose=cclock" -metadata:s:v:0 rotate=0
       -c:v libx264 -preset veryfast -crf 22 -c:a copy "%new_name%"


text:
Q: How to get the source of the page loaded in IWebBrowser2? From a BHO (Browser Helper Object) in Internet Explorer, how do I get the full source code of the page currently loaded in the web browser when I have its IWebBrowser2 interface?
Do I have to download it again from the url where it resides or is there a way to get the copy that internet explorer downloaded and used to render the page?
I tried getting the outerHTML of the html element of the current document, but it returns the source code already preprocessed. I need to get it in the same form you see it when you clock "View Source Code" in the Internet Explorer.
Thank you for any helpful information!!!

A: You can query the browser's Document property for IPersistStream or IPersistFile and then call its Save() method.  But when querying the browser for its HTML, you are likely to get the processed HTML, which may include DOM changes from scripts.
To get the original HTML, you should download it yourself directly from the source URL, or at least extract the file from the browser's local cache.


text:
Q: InvalidOperationException: Cannot use table 'xxxx1' for entity type 'xxxx2' since it is being used for entity type 'xxxx1' i'm trying to make a database in entity-framework code-first but im always getting a error like this:

InvalidOperationException: Cannot use table 'Device' for entity type
   'IpMac' since it is being used for entity type 'Device' and there is no relationship between the primary key {'DeviceIP'} and the primary key {'DeviceID'}."

these are my model classes:
public class IpMac
{
    [Key]
    public string DeviceIP { get; set; }
    //[ForeignKey("Device")]
    public int DeviceID { get; set; }
    public string DeviceMAC { get; set; }

    //public Device Device { get; set; }
    public ICollection<Device> Device { get; set; }
}
public class Device
{
    //[Key]
    public int DeviceID { get; set; }
    public string DeviceName { get; set; }
    public string UserName { get; set; }
    //public string DeviceMAC { get; set; }

    public IpMac IpMac { get; set; }
}

and here is my "DbContext" class:
public class DeviceContext : DbContext
{
    public DeviceContext(DbContextOptions<DeviceContext> options) : base (options)
    {
    }

    public DbSet<Device> Devices { get; set; }
    public DbSet<IpMac> IpMacs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<IpMac>().ToTable("Device");
        modelBuilder.Entity<Device>().ToTable("Device");
        Logger.Log("DeviceContext: Database & Tables SET.");
    }
}

A: Shouldnt your device context use different table names for the tables?
public class DeviceContext : DbContext
{
    public DeviceContext(DbContextOptions<DeviceContext> options) : base (options)
    {
    }

    public DbSet<Device> Devices { get; set; }
    public DbSet<IpMac> IpMacs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<IpMac>().ToTable("IpMac");
      modelBuilder.Entity<Device>().ToTable("Device");
      Logger.Log("DeviceContext: Database & Tables SET.");
    }
}


text:
Q: Determing if a RewardedVideoAd is paused? There are onVideoStart, onVideoOpen, and onVideoClosed-events.
Is there some way to get if the video is paused by the "Close video"-dialog?

A: It looks like AdMob doesn't have triggers on this event (on Video Paused). But if there isn't any super specific case I would stick with this callback void onRewarded(RewardItem reward) which is returned when a user gets through the ad and deserves the reward. Means he watched the whole video and you earned something.
Take a look here googleads-mobile-android-examples and Rewarded Video Ads. There it's perfectly explained. Good luck


text:
Q: Enabling ExpandPersistentVolumes I need to resize a bunch of PVCs. It seems the easiest way to do it is through
the ExpandPersistentVolumes feature. I am however having trouble getting the
configuration to cooperate.
The ExpandPersistentVolumes feature gate is set in kubelet on all three
masters, as shown:
(output trimmed to relevant bits for sanity)
$ parallel-ssh -h /tmp/masters -P "ps aux | grep feature"
172.20.53.249: root     15206  7.4  0.5 619888 83952 ?        Ssl  19:52   0:02 /opt/kubernetes/bin/kubelet  --feature-gates=ExpandPersistentVolumes=true,ExperimentalCriticalPodAnnotation=true
[1] 12:53:08 [SUCCESS] 172.20...
172.20.58.111: root     17798  4.5  0.5 636280 87328 ?        Ssl  19:51   0:04 /opt/kubernetes/bin/kubelet --feature-gates=ExpandPersistentVolumes=true,ExperimentalCriticalPodAnnotation=true
[2] 12:53:08 [SUCCESS] 172.20...
172.20.53.240: root      9287  4.0  0.5 645276 90528 ?        Ssl  19:50   0:06 /opt/kubernetes/bin/kubelet --feature-gates=ExpandPersistentVolumes=true,ExperimentalCriticalPodAnnotation=true
[3] 12:53:08 [SUCCESS] 172.20..

The apiserver has the PersistentVolumeClaimResize admission controller, as shown:
$ kubectl --namespace=kube-system get pod -o yaml | grep -i admission
    /usr/local/bin/kube-apiserver --admission-control=Initializers,NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,NodeRestriction,PersistentVolumeClaimResize,ResourceQuota
    /usr/local/bin/kube-apiserver --admission-control=Initializers,NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,NodeRestriction,PersistentVolumeClaimResize,ResourceQuota
    /usr/local/bin/kube-apiserver --admission-control=Initializers,NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,NodeRestriction,PersistentVolumeClaimResize,ResourceQuota

However, when I create or edit a storage class to add allowVolumeExpansion,
it is removed on save. For example:
$ cat new-sc.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  creationTimestamp: null
  labels:
    k8s-addon: storage-aws.addons.k8s.io
  name: gp2-2
  selfLink: /apis/storage.k8s.io/v1/storageclasses/gp2
parameters:
  encrypted: "true"
  kmsKeyId: arn:aws:kms:us-west-2:<omitted>
  type: gp2
  zone: us-west-2a
provisioner: kubernetes.io/aws-ebs
reclaimPolicy: Delete
allowVolumeExpansion: true

$ kubectl create -f new-sc.yaml
storageclass "gp2-2" created

$ kubectl get sc gp2-2 -o yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  creationTimestamp: 2018-05-22T20:00:17Z
  labels:
    k8s-addon: storage-aws.addons.k8s.io
  name: gp2-2
  resourceVersion: "2546166"
  selfLink: /apis/storage.k8s.io/v1/storageclasses/gp2-2
  uid: <omitted>
parameters:
  encrypted: "true"
  kmsKeyId: arn:aws:kms:us-west-2:<omitted>
  type: gp2
  zone: us-west-2a
provisioner: kubernetes.io/aws-ebs
reclaimPolicy: Delete

What am I missing? What is erasing this key from my storageclass configuration?
EDIT: Here is the command used by the kube-apiserver pods. It does not say anything about feature gates. The cluster was launched using Kops.
- /bin/sh
    - -c
    - mkfifo /tmp/pipe; (tee -a /var/log/kube-apiserver.log < /tmp/pipe & ) ; exec
      /usr/local/bin/kube-apiserver --address=127.0.0.1 --admission-control=Initializers,NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,NodeRestriction,PersistentVolumeClaimResize,ResourceQuota
      --allow-privileged=true --anonymous-auth=false --apiserver-count=3 --authorization-mode=RBAC
      --basic-auth-file=/srv/kubernetes/basic_auth.csv --client-ca-file=/srv/kubernetes/ca.crt
      --cloud-provider=aws --etcd-cafile=/srv/kubernetes/ca.crt --etcd-certfile=/srv/kubernetes/etcd-client.pem
      --etcd-keyfile=/srv/kubernetes/etcd-client-key.pem --etcd-servers-overrides=/events#https://127.0.0.1:4002
      --etcd-servers=https://127.0.0.1:4001 --insecure-port=8080 --kubelet-preferred-address-types=InternalIP,Hostname,ExternalIP
      --proxy-client-cert-file=/srv/kubernetes/apiserver-aggregator.cert --proxy-client-key-file=/srv/kubernetes/apiserver-aggregator.key
      --requestheader-allowed-names=aggregator --requestheader-client-ca-file=/srv/kubernetes/apiserver-aggregator-ca.cert
      --requestheader-extra-headers-prefix=X-Remote-Extra- --requestheader-group-headers=X-Remote-Group
      --requestheader-username-headers=X-Remote-User --secure-port=443 --service-cluster-ip-range=100.64.0.0/13
      --storage-backend=etcd3 --tls-cert-file=/srv/kubernetes/server.cert --tls-private-key-file=/srv/kubernetes/server.key
      --token-auth-file=/srv/kubernetes/known_tokens.csv --v=1 > /tmp/pipe 2>&1

A: It could happen if you did not enable alpha feature-gate for the option.
Did you set --feature-gates option for kube-apiserver?
--feature-gates mapStringBool  - A set of key=value pairs that describe feature gates for alpha/experimental features. Options are:
...
ExpandPersistentVolumes=true|false (ALPHA - default=false)
...

Update: If you don't see this option in the command line arguments, you need to add it (--feature-gates=ExpandPersistentVolumes=true).
In case you run kube-apiserver as a pod, you should edit /etc/kubernetes/manifests/kube-apiserver.yaml and add the feature-gate option to other arguments. kube-apiserver will restart automatically.
In case you run kube-apiserver as a process maintained by systemd, you should edit kube-apiserver.service or service options $KUBE_API_ARGS in a separate file, and append feature-gate option there. Restart the service with systemctl restart kube-apiserver.service command.
After enabling it, you can create a StorageClass object with allowVolumeExpansion option:
# kubectl get sc -o yaml --export
apiVersion: v1
items:
- allowVolumeExpansion: true
  apiVersion: storage.k8s.io/v1
  kind: StorageClass
  metadata:
    creationTimestamp: 2018-05-23T14:38:43Z
    labels:
      k8s-addon: storage-aws.addons.k8s.io
    name: gp2-2
    namespace: ""
    resourceVersion: "1385"
    selfLink: /apis/storage.k8s.io/v1/storageclasses/gp2-2
    uid: fe516dcf-5e96-11e8-a86d-42010a9a0002
  parameters:
    encrypted: "true"
    kmsKeyId: arn:aws:kms:us-west-2:<omitted>
    type: gp2
    zone: us-west-2a
  provisioner: kubernetes.io/aws-ebs
  reclaimPolicy: Delete
  volumeBindingMode: Immediate
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""


text:
Q: Fetching attachments from gmail via either python or php I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.
Related:

*

*How can I download all emails with attachments from Gmail?

A: I took the code above and fixed it and tested it. It works with PHP5.
<?php

$gmail_username = 'email@gmail.com';
$gmail_password = 'password';
$imap = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $gmail_username, $gmail_password) or die("can't connect: " . imap_last_error());
$savefilepath = '//Server/share/Local/Pathname/'; //absolute path to images directory
$imagefilepath = '/Local/Pathname/'; //relative path to images directory
$savethumbpath = '/Local/Pathname/'; //relative path to images directory
$headers = imap_headers($imap);
foreach ($headers as $mail) {
    $flags = substr($mail, 0, 4);
    //Check for unread msgs, get their UID, and queue them up
    if (strpos($flags, "U")) {
        preg_match('/[0-9]+/',$mail,$match);
        $new_msg[] = implode('',$match);
    }
}
if ($new_msg) {
    foreach ($new_msg as $result) {
        $structure = imap_fetchstructure($imap,$result);
        $parts = $structure->parts;
        foreach ($parts as $part) {
            if ($part->parameters[0]->attribute == "NAME") {
                //Generate a filename with format DATE_RANDOM#_ATTACHMENTNAME.EXT
                $savefilename = date("m-d-Y") . '_' . rand() . '_' . $part->parameters[0]->value;
                   save_attachment(imap_fetchbody($imap,$result,2),$savefilename,$savefilepath,$savethumbpath);
                imap_fetchbody($imap,$result,2); //This marks message as read
            }
        }
    }
}
/* grab emails */
$emails = imap_search($imap,'ALL');
/* if emails are returned, cycle through each... */
if($emails) {
  /* put the newest emails on top */
  $total = imap_num_msg($imap);
  /* for every email... */
  for( $i = $total; $i >= 1; $i--) {
        $headers = imap_header($imap, $i);
        $from = $headers->from[0]->mailbox . "@" . $headers->from[0]->host;
        echo $from . "\n";
        imap_delete($imap,$i);
        imap_mail_move($imap,"$i:$i", "[Gmail]/Trash"); // Change or remove this line if you are not connecting to gmail. The path to the Trash folder in your Gmail may be different, capitalization is relevant.
  }
}else{
        echo "no emails";
}
/* close the connection */
   imap_expunge($imap);
   imap_close($imap);

function save_attachment( $content , $filename , $localfilepath, $thumbfilepath ) {
     if (imap_base64($content) != FALSE) {
         $file = fopen($localfilepath.$filename, 'w');
         fwrite($file, imap_base64($content));
         fclose($file);
     }
}
?>

A: I found some code that works! this will download any attachments to a selected folder
<?php

$gmail_username = 'username@gmail.com';
$gmail_password = 'mypassword';

$imap = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $gmail_username, $gmail_password) or die("can't connect: " . imap_last_error());
$savefilepath = 'path/to/images_folder/'; //absolute path to images directory
$imagefilepath = 'images/'; //relative path to images directory

$headers = imap_headers($imap);
foreach ($headers as $mail) {
    $flags = substr($mail, 0, 4);
    //Check for unread msgs, get their UID, and queue them up
    if (strpos($flags, "U")) {
        preg_match('/[0-9]+/',$mail,$match);
        $new_msg[] = implode('',$match);
    }
}

if ($new_msg) {
    foreach ($new_msg as $result) {
        $structure = imap_fetchstructure($imap,$result);
        $parts = $structure->parts;
        foreach ($parts as $part) {
            if ($part->parameters[0]->attribute == "NAME") {
                //Generate a filename with format DATE_RANDOM#_ATTACHMENTNAME.EXT
                $savefilename = date("m-d-Y") . '_' . mt_rand(rand(), 6) . '_' . $part->parameters[0]->value;
                save_attachment(imap_fetchbody($imap,$result,2),$savefilename,$savefilepath,$savethumbpath);
                imap_fetchbody($imap,$result,2); //This marks message as read
            }
        }
    }
}

imap_close($imap);

function save_attachment( $content , $filename , $localfilepath, $thumbfilepath ) {
    if (imap_base64($content) != FALSE) {
        $file = fopen($localfilepath.$filename, 'w');
        fwrite($file, imap_base64($content));
        fclose($file);
    }
}
?>

A: You will have to enable IMAP access to your GMail account (Settings → Forwarding and POP/IMAP), and then use imaplib.IMAP4_SSL to access it.
Use the raw text of every message as an argument to email.message_from_string in order to process any attachments.

A: I recently worked on this topic and here is the code which works well. It also saves the details of the attachments in a word document with the following details:
-> Date
-> Time
-> From
-> Email ID
-> Subject

<?php

 /*
    *   Gmail attachment extractor.
    *
    *   Downloads attachments from Gmail and saves it to a file.
    *   Uses PHP IMAP extension, so make sure it is enabled in your php.ini,
    *   extension=php_imap.dll
    *
    */

    header('Content-type:application\msword');
    header('Content-Disposition:attachment;Filename=document_name.doc');
    set_time_limit(0);
    /* connect to gmail with your credentials */
    $hostname = '{imap.googlemail.com:993/imap/ssl}INBOX';
    $username = 'email@gmail.com';
    $password = 'password';
    /* try to connect */
    $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to
    Gmail: ' . imap_last_error());
    /* get all new emails. If set to 'ALL' instead
    * of 'NEW' retrieves all the emails, but can be
    * resource intensive, so the following variable,
    * $max_emails, puts the limit on the number of emails downloaded.
    *
    */
    $emails = imap_search($inbox,'ALL');
    /* useful only if the above search is set to 'ALL' */
    $max_emails = 110;

    /* if any emails found, iterate through each email */
    if($emails){
    $count = 1;

    /* put the newest emails on top */
    rsort($emails);
    /* for every email... */
    foreach($emails as $email_number){
    /* get information specific to this email */
    //$overview = imap_fetch_overview($inbox,$email_number,0);
    $check=imap_check($inbox);
    $result=imap_fetch_overview($inbox,"1:{$check->Nmsgs}",0);
    foreach($result as $overview){
    echo "#{$overview->msgno}({$overview->date})-From: {$overview->from}
    {$overview->subject}\n"}
    /* get mail message */
    $message = imap_fetchbody($inbox,$email_number,2);
    /* get mail structure */
    $structure =imap_fetchstructure($inbox, $email_number);
    //$functions = array('function1' => imap_fetchstructure($inbox,
    $email_number));
    //print_r(array_keys($functions));
    $attachments = array();
    //print_r(array_keys($attachments[$i]));
    if($structure->parts[$i]->ifdparameters){
    foreach($structure->parts[$i]->dparameters as $object){
    if(strtolower($object->attribute) == 'filename'){
    $attachments[$i]['is_attachment'] = true;
    $attachments[$i]['filename'] = $object->value;
        }
       }
      }
       if($structure->parts[$i]->ifparameters)
       {
         foreach($structure->parts[$i]->parameters as $object)
         {
             if(strtolower($object->attribute) == 'name')
            {
                $attachments[$i]['is_attachment'] = true;
                $attachments[$i]['name'] = $object->value;
            }
        }
     }
     if($attachments[$i]['is_attachment']){
     $attachments[$i]['attachment']imap_fetchbody($inbox,$email_number,$i+1);
     /* 4 = QUOTED-PRINTABLE encoding */
     if($structure->parts[$i]->encoding == 3){
     $attachments[$i]['attachment'] = base64_decode($attachments[$i]
           ['attachment']);
      }
      /* 3 = BASE64 encoding */
      elseif($structure->parts[$i]->encoding == 4){
      $attachments[$i]['attachment'] =

      quoted_printable_decode($attachments[$i]['attachment']);
      }

       }
      }
     }
       /* iterate through each attachment and save it */
       foreach($attachments as $attachment)
       {
       if($attachment['is_attachment'] == 1){
        $filename = $attachment['name'];
        if(empty($filename)) $filename = $attachment['filename'];
        if(empty($filename)) $filename = time() . ".dat";
       /* prefix the email number to the filename in case two emails
       * have the attachment with the same file name.
       */
       $fp = fopen($email_number . "-" . $filename, "w+");
       fwrite($fp, $attachment['attachment']);
        fclose($fp);
        }

        }

          if($count++ >= $max_emails) break;

         }

       }

        /* close the connection */

       imap_close($inbox);

  ?>

A: The php docs for imap_open explain connecting to gmail in the comments (e.g. 31-Oct-2007 07:50):
$mbox = imap_open("{imap.gmail.com:993/imap/ssl}INBOX", "username@gmail.com", "password") or die("can't connect: " . imap_last_error());
Where, obviously, you have to fill in the actual username and password as appropriate, and then to identify the attachments in the parts of the email you follow the instructions from: http://www.electrictoolbox.com/extract-attachments-email-php-imap/
Which, summarizing, says that you use:
// in a for($i=1;$i<$nummsgs;$i++) loop over all the messages in the inbox
$structure = imap_fetchstructure($mbox, $i);
to identify the attachments in the structure.  However, that is a rather elaborate process of deconstructing MIME messages (which have a lot of optional variability that must be accounted for), so the fundamentals/outline of a function for that is in that electrictoolbox page.


text:
Q: ERROR TypeError: Cannot read property 'push' of undefined in Angular 5 Getting error on when addAdd() call from html template.
this.personalForm = this.fb.group({
        user: this.fb.group({
            address: this.fb.array([this.addRows()])
            }),
addRows() {
  return this.fb.group({
    country: ['']});

addAdd() {
  const control:FormArray = this.personalForm.get[`address`] as FormArray;
  control.push(this.addRows());
}

Where i am doing wrong
ERROR TypeError: Cannot read property 'push' of undefined

html code
<button (click)="addAdd()">Add Address</button>

    Country
  <input type="text" class="form-control"   formControlName="country"
  placeholder="Country" />

A: In this case control might be null, add a check for null and length.
const control:FormArray = this.personalForm.get[`address`] as FormArray;
if(control && control.length >0){
  control.push(this.addRows());
}

A: get is a function, not an object. Also, you must specify full path to your control.
const control:FormArray = this.personalForm.get(['user', 'address']) as FormArray;

or
const control:FormArray = this.personalForm.get('user.address') as FormArray;

A: Thanks Marko ! this is working, cool !
addAdd() {
    const control:FormArray = this.personalForm.get('user.address') as FormArray;
    control.push(this.addRows());
  }


text:
Q: Having trouble loading in multiple .bmp files for textures OpenGL C++ Having some trouble trying to get to .bmp files into an array so I can use them for textures.
EDIT
Display.h
#pragma once

#include "Ball.h"
#include "Bitmap.h"

class Display
{
private :
    static Bitmap m_HeightMap;
    static unsigned int textures;
//  static float TableX, TableY, TableZ;
    static float eyeZ, eyeY, eyeX;
    static float lightX, lightY, lightZ;
    static float Position[4];
    static float translateZ, translateX;
    //static Timer m_Timer;

public:
    static void Init(int argc, char ** argv);
    static void DisplayScene();
    static void Resize(int w, int h);
    static void KeyboardInput(unsigned char pKey, int pX, int pY);
    static void Idle();
    static void DrawLight(int pLightNumber, float * pPos);
    static void Table(float zStart, float xStart, float zEnd, float xEnd);
    static void BallCollisions(float pTimestep, Vector3f New_position, Vector3f New_velocity);

};

void main(int argc, char ** argv)
{
    Display::Init(argc, argv);
}

Display.cpp
#include "Display.h"
#include "Vector3f.h"
#include "Ball.h"
#include "Glut/glut.h"
#include "GL/gl.h"
#include "GL/glu.h"
#include <math.h>
#include "Bitmap.h"

static float TableWidth = 4;  // Z axis normal = 4
float Display::eyeX = -7.5; //-7.5
float Display::eyeY = 3; //3
float Display::eyeZ = 5; //5
float Display::Position[4] = { 1.0f, 0.0f, -3.5, 1.0f };
float Display::translateZ = -3.5;
float Display::translateX = 0.0;
//Timer Display::m_Timer = Timer();
float Display::lightX = 5.0; //5 2.5
float Display::lightY = 5.0;
float Display::lightZ = 2.5;

float m_TableX = -5.0f;
float m_TableZ = -2.5f;
float m_TableWidth = 2.5f;
float m_TableLength = 5.0f;

float ballx = 0.7;
float bally = 0.1;
float ballz = -0.7;

Ball Redball;
float BALL_RED_START = 0;
float RADIUS_OF_BALL = 0.3;
float BALL_RED_END = 8;

Ball Yellowball;
float BALL_YELLOW_START = 0;

float BALL_YELLOW_END = 8;

Bitmap Display::m_HeightMap;
unsigned int Display:: textures;
GLuint textures[2];

void loadTexture(GLuint texture, const char* filename)
{
   Bitmap image;

   Bitmap image[2];

   image[0].loadBMP("myTexture.bmp");
   image[1].loadBMP("myTexture2.bmp");

   glBindTexture(GL_TEXTURE_2D, texture);

   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE , GL_MODULATE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
   gluBuild2DMipmaps(GL_TEXTURE_2D, 3, image.width, image.height, GL_RGB, GL_UNSIGNED_BYTE, image.data);
}

void Display::Init(int argc, char ** argv)
{
    glutInit(&argc, argv); // initializes glut
    // sets display mode. These parameter set RGB colour model
    // and double buffering.
    glutInitWindowSize(500,500);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutCreateWindow("Pool Version 1.0");

    // Set glut callback functions
    glutDisplayFunc(Display::DisplayScene);
    glutIdleFunc(Display::Idle);
    glutReshapeFunc(Display::Resize);
    glutKeyboardFunc(Display::KeyboardInput);
    //m_Timer.getSeconds();
    glEnable(GL_DEPTH_TEST);
    glPointSize(5);

        glEnable(GL_NORMALIZE);
        glEnable(GL_LIGHTING);
        glClearColor(0,0,0,1);
        glEnable(GL_COLOR_MATERIAL);

float white[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glLightfv(GL_LIGHT0, GL_DIFFUSE, white);

glEnable(GL_LIGHT0);
Redball.SetPos(Vector3f(0.0,0.3,0.0));

Ball Redball[8];

for(int i = BALL_RED_START; i < BALL_RED_START; i++)
{
  glColor3f(1,0,0);
  Redball[i].SetPos(Vector3f (i+128,RADIUS_OF_BALL,45));
}

Ball Yellowball[8];

for(int i = BALL_YELLOW_START; i < BALL_YELLOW_START; i++)
{
  glColor3f(2,1,0);
  Yellowball[i].SetPos(Vector3f (i+128,RADIUS_OF_BALL,45));
}

GLuint *textures = new GLuint[2];

   glGenTextures(2, textures);

 loadTexture(textures[0], "myTexture.bmp");
 loadTexture(textures[1], "myTexture2.bmp");

// Begin glut main loop
    glutMainLoop();
}

#pragma region Table Drawing Code

void drawTable()
{

glBegin(GL_QUADS); // RIGHT
glNormal3f(0,0,1);
glEnable(GL_TEXTURE_2D);
//glColor3d(0.5,0.35,0.05);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(m_TableX, 0.0f, m_TableWidth); //bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(m_TableLength, 0.0f, m_TableWidth);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(m_TableLength, 0.0f, m_TableWidth);//top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(m_TableX, 0.0f, m_TableWidth); //top left
glEnd();

glBegin(GL_QUADS); //BACK
glNormal3f(1,0,0);
glEnable(GL_TEXTURE_2D);
glColor4f(1,1,1,0);
//glColor3d(0.5,0.35,0.05);
glTexCoord2f(0.0f,0.0f);
glVertex3f(m_TableLength, 0.0f,  m_TableWidth);
glTexCoord2f(1.0f,0.0f);
glVertex3f(m_TableLength, 0.0f, m_TableZ);
glTexCoord2f(1.0f,1.0f);
glVertex3f(m_TableLength, 0.0f, m_TableZ);
glTexCoord2f(0.0f,1.0f);
glVertex3f(m_TableLength, 0.0f, m_TableWidth);
glEnd();

glBegin(GL_QUADS); //FRONT
glNormal3f(-1,0,0);
//glColor3d(0.5,0.35,0.05);
glVertex3f(m_TableX, 0.0f, m_TableZ);
glVertex3f(m_TableX, 0.0f, m_TableWidth);
glVertex3f(m_TableX, 0.0f, m_TableWidth);
glVertex3f(m_TableX, 0.0f, m_TableZ);
glEnd();

glBegin(GL_QUADS); //lEFT
glNormal3f(0,0,-1);
glColor3d(0.5,0.35,0.05);
glVertex3f(m_TableX, 0.0f, m_TableZ);
glVertex3f(m_TableLength, 0.0f, m_TableZ);
glVertex3f(m_TableX, 0.0f, m_TableZ);
glVertex3f(m_TableLength, 0.0f, m_TableZ);
glEnd();

glBegin(GL_QUADS); //BOTTOM
glNormal3f(0,-1,0);
glColor3d(0.5,0.35,0.05);
glVertex3f(m_TableX, -0.001f,  m_TableWidth);
glVertex3f(m_TableLength, -0.001f,  m_TableWidth);
glVertex3f(m_TableLength, -0.001f, m_TableZ);
glVertex3f(m_TableX, -0.001f, m_TableZ);
glEnd();

}

#pragma endregion

#pragma region Cushion Drawing Code

    // width 0.5 = dividing table width (5) by 9 to get the proportional size of 10cm
    // height 0.3 = dividing the width by 10 to find the value of 1cm = 0.05. 0.05 x 6 = 0.3
    // starting at 0.4 to leave for the pocket. (1cm x 8 = pocket size = 0.05 x 8 = 0.4)

//right cushion

void drawCushions()
{

glBegin(GL_QUADS); //BOTTOM
glNormal3f(0,-1,0);
glColor3d(0.5,0.40,0.05);
glVertex3f(-4.5, 0.01, 2);//bottom left
glVertex3f(-4.5, 0.01, 2.5);//bottom right
glVertex3f(4.5, 0.01, 2.5); //top right
glVertex3f(4.5, 0.01, 2);//top left
glEnd();

glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //TOP
glBindTexture(GL_TEXTURE_2D, textures[0]);
glNormal3f(0,1,0);
glColor4f(1,1,1,0);
//glColor3d(0.5,0.40,0.05);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-4.5, 0.3, 2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(-4.5, 0.3, 2.5);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(4.5, 0.3, 2.5);//top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(4.5, 0.3, 2);//top left
glBindTexture(GL_TEXTURE_2D, 0); // Set the GL texture to NULL, standard cleanup
glEnd();
glDisable(GL_TEXTURE_2D);

glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //RIGHT
glNormal3f(0,0,1);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-4.5, 0, 2.5);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(4.5, 0, 2.5);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(4.5, 0.3, 2.5); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(-4.5, 0.3, 2.5);//top left
glBindTexture(GL_TEXTURE_2D, 0); // Set the GL texture to NULL, standard cleanup
glEnd();
glDisable(GL_TEXTURE_2D);

glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //LEFT
glNormal3f(0,0,-1);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-4.5, 0, 2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(4.5, 0, 2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(4.5, 0.3, 2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(-4.5, 0.3, 2);//top left
glEnd();
glDisable(GL_TEXTURE_2D);

//Left Cushion

glBegin(GL_QUADS); //BOTTOM
glNormal3f(0,-1,0);
glColor3d(0.5,0.40,0.05);
glVertex3f(-4.5, 0.01, -2.5);//bottom left
glVertex3f(-4.5, 0.01, -2);//bottom right
glVertex3f(4.5, 0.01, -2); //top right
glVertex3f(4.5, 0.01, -2.5);//top left
glEnd();

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //TOP
glNormal3f(0,1,0);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-4.5, 0.3, -2.5);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(-4.5, 0.3, -2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(4.5, 0.3, -2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(4.5, 0.3, -2.5);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //RIGHT
glNormal3f(0,0,1);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-4.5, 0, -2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(4.5, 0, -2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(4.5, 0.3, -2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(-4.5, 0.3, -2);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //LEFT
glNormal3f(0,0,-1);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-4.5, 0, -2.5);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(4.5, 0, -2.5);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(4.5, 0.3, -2.5); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(-4.5, 0.3, -2.5);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);

//Bottom Cushion

glBegin(GL_QUADS); //BOTTOM
glNormal3f(0,-1,0);
glColor3d(0.5,0.40,0.05);
glVertex3f(-5, 0.01, -2);//bottom left
glVertex3f(-5, 0.01, 2);//bottom right
glVertex3f(-4.5, 0.01, 2); //top right
glVertex3f(-4.5, 0.01, -2);//top left
glEnd();

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //TOP
glNormal3f(0,1,0);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-5, 0.3, -2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(-5, 0.3, 2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(-4.5, 0.3, 2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(-4.5, 0.3, -2);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //RIGHT
glNormal3f(0,0,1);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-5, 0, -2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(-5, 0, 2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(-5, 0.3, 2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(-5, 0.3, -2);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //LEFT
glNormal3f(0,0,-1);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-5, 0.0,-2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(-5, 0.0, 2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(-5, 0.3, 2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(-5, 0.3,-2);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);

//top cushion

glBegin(GL_QUADS); //BOTTOM
glNormal3f(0,-1,0);
glColor3d(0.5,0.40,0.05);
glVertex3f(4.5, 0.01, -2);//bottom left
glVertex3f(4.5, 0.01, 2);//bottom right
glVertex3f(5, 0.01, 2); //top right
glVertex3f(5, 0.01, -2);//top left
glEnd();

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //TOP
glNormal3f(0,1,0);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(4.5,0.3,-2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(4.5,0.3, 2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(5,  0.3, 2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(5, 0.3, -2);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //RIGHT
glNormal3f(0,0,1);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(5, 0, -2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(5, 0, 2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(5, 0.3, 2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(5, 0.3, -2);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);

//glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); //LEFT
glNormal3f(0,0,-1);
glColor4f(1,1,1,0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(4.5, 0, -2);//bottom left
glTexCoord2f(1.0f,0.0f);
glVertex3f(4.5, 0, 2);//bottom right
glTexCoord2f(1.0f,1.0f);
glVertex3f(4.5, 0.3, 2); //top right
glTexCoord2f(0.0f,1.0f);
glVertex3f(4.5, 0.3, -2);//top left
glEnd();
//glDisable(GL_TEXTURE_2D);
}

void Display::DisplayScene()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the back buffer

    glPushMatrix();
    glLoadIdentity();
    glNormal3f(0,1,0);
    Vector3f Pos = Redball.GetPos();
    gluLookAt(eyeX, eyeY, eyeZ,     // eye position
            0, 0, 0,        // what I'm looking at
            0.0, 1.0, 0); // Up direction

    float Position[] = {lightX, lightY, lightZ, 1.0f};
glLightfv(GL_LIGHT0, GL_POSITION, Position);
DrawLight(0, Position);

    /* Rendering code goes here */

glPushMatrix();
Ball Redball[8];
for (int i = BALL_RED_START; i<BALL_RED_END;i++)
{

float x = 0;
glTranslatef(x+1,1,0);
glColor3f(1,0,0);
Redball[i].DrawRed();
}
glPopMatrix();

glPushMatrix();
Ball Yellowball[8];
for (int i = BALL_YELLOW_START; i<BALL_YELLOW_END;i++)
{

float x = 0;
glTranslatef(x+1,0,1);
glColor3f(2,1,0);
Yellowball[i].DrawYellow();

}
glPopMatrix();

drawTable();
drawCushions();
Table(-2,-4.5,2,4.5); // Draws the table top in trianglestrip       -4.5, 0.5, -0.5, 9.5

    glPopMatrix();
    glutSwapBuffers(); // Swap the front and back buffers
}

void Display::Resize(int w, int h)
{
    /* Resize is called when window is resized */
    glMatrixMode(GL_PROJECTION); // set matrix mode to profection
    // this dictates how the 3d scene is "squashed" onto the 2d screen
    glLoadIdentity();
    glViewport(0, 0, w, h);  // Set the part of the window to use.
    gluPerspective(45,              // field of view
                (float)w/(float)h,  // ration of window
                1,                  // front clipping plane
                1000                // back clipping plane
                );          // set the area in the 3d scene to draw

    glMatrixMode(GL_MODELVIEW); // Setthe matrix mode to model view
        // the matrix specifies how the 3d scene is viewed
    /*glLoadIdentity();
    gluLookAt(-3.5, 2, eyeZ,        // eye position
            1, 1, 0,        // what I'm looking at
            0.0, 1.0, 0); // Up direction*/
}

void Display::Idle()
{
    /* When nothing else is happening, idle is called.
     * Simulation should be done here and then
     * the display method should be called
     */

    BallMovement();

    glutPostRedisplay();

}
Bitmap.h
I also have a class for my textures
#ifndef _BITMAP_H
#define _BITMAP_H

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

const short BITMAP_MAGIC_NUMBER=19778;
const int RGB_BYTE_SIZE=3;

#pragma pack(push,bitmap_data,1)

typedef struct tagRGBQuad {
char rgbBlue;
char rgbGreen;
char rgbRed;
char rgbReserved;
} RGBQuad;

typedef struct tagBitmapFileHeader {
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
} BitmapFileHeader;

typedef struct tagBitmapInfoHeader {
unsigned int biSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
} BitmapInfoHeader;

#pragma pack(pop,bitmap_data)

class Bitmap {
public:
//variables
RGBQuad *colours;
char *data;
bool loaded;
int width,height;
unsigned short bpp;
string error;
//methods
Bitmap(void);
Bitmap(char *);
~Bitmap();
bool loadBMP(char *);
private:
//variables
BitmapFileHeader bmfh;
BitmapInfoHeader bmih;
int byteWidth; //the width in bytes of the image
int padWidth; //the width in bytes of the added image
unsigned int dataSize; //size of the data in the file
//methods
void reset(void);
bool convert24(char *);  //convert to 24bit RGB bottom up data
bool convert8(char *);   //convert to 24bit RGB bottom up data
};

#endif //_BITMAP_H

Bitmap.cpp
#include "Bitmap.h"

//basic constructor
Bitmap::Bitmap(){
reset();
}

//constructor loads the bitmap when it is created
Bitmap::Bitmap(char *file){
reset();
loadBMP(file);
}

//destructor
Bitmap::~Bitmap(){
if(colours!=0) {
delete[] colours;
}
if(data!=0) {
delete[] data;
}
}

//load a bitmap from a file and represent it correctly
//in memory
bool Bitmap::loadBMP(char *file) {
FILE *in; //file stream for reading
char *tempData; //temp storage for image data
int numColours; //total available colours

//bitmap is not loaded yet
loaded=false;
//make sure memory is not lost
if(colours!=0) {
delete[] colours;
}
if(data!=0) {
delete[] data;
}

//open the file for reading in binary mode
in=fopen(file,"rb");

//if the file does not exist return in error
if(in==NULL) {
error="File not found";
fclose(in);
return false;
}

//read in the entire BITMAPFILEHEADER
fread(&bmfh,sizeof(BitmapFileHeader),1,in);
//check for the magic number that says this is a bitmap
if(bmfh.bfType!=BITMAP_MAGIC_NUMBER) {
error="File is not in DIB format";
fclose(in);
return false;
}

//read in the entire BITMAPINFOHEADER
fread(&bmih,sizeof(BitmapInfoHeader),1,in);

//save the width, height and bits per pixel for external use
width=bmih.biWidth;
height=bmih.biHeight;
bpp=bmih.biBitCount;

//calculate the size of the image data with padding
dataSize=(width*height*(unsigned int)(bmih.biBitCount/8.0));

//calculate the number of available colours
numColours=1<<bmih.biBitCount;

//if the bitmap is not 8 bits per pixel or more
//return in error
if(bpp<8) {
error="File is not 8 or 24 bits per pixel";
fclose(in);
return false;
}

//load the palette for 8 bits per pixel
if(bpp==8) {
colours=new RGBQuad[numColours];
fread(colours,sizeof(RGBQuad),numColours,in);
}

//set up the temporary buffer for the image data
tempData=new char[dataSize];

//exit if there is not enough memory
if(tempData==NULL) {
error="Not enough memory to allocate a temporary buffer";
fclose(in);
return false;
}

//read in the entire image
fread(tempData,sizeof(char),dataSize,in);

//close the file now that we have all the info
fclose(in);

//calculate the witdh of the final image in bytes
byteWidth=padWidth=(int)((float)width*(float)bpp/8.0);

//adjust the width for padding as necessary
while(padWidth%4!=0) {
padWidth++;
}

//change format from GBR to RGB
if(bpp==8) {
loaded=convert8(tempData);
}
else if(bpp==24) {
loaded=convert24(tempData);
}

//clean up memory
delete[] tempData;

//bitmap is now loaded
error="Bitmap loaded";

//return success
return loaded;
}

//function to set the inital values
void Bitmap::reset(void) {
loaded=false;
colours=0;
data=0;
error="";
}

bool Bitmap::convert24(char* tempData) {
int offset,diff;

diff=width*height*RGB_BYTE_SIZE;
//allocate the buffer for the final image data
data=new char[diff];

//exit if there is not enough memory
if(data==NULL) {
error="Not enough memory to allocate an image buffer";
delete[] data;
return false;
}

if(height>0) {
offset=padWidth-byteWidth;
//count backwards so you start at the front of the image
for(int i=0;i<dataSize;i+=3) {
//jump over the padding at the start of a new line
if((i+1)%padWidth==0) {
i+=offset;
}
//transfer the data
*(data+i+2)=*(tempData+i);
*(data+i+1)=*(tempData+i+1);
*(data+i)=*(tempData+i+2);
}
}

//image parser for a forward image
else {
offset=padWidth-byteWidth;
int j=dataSize-3;
//count backwards so you start at the front of the image
//here you can start from the back of the file or the front,
//after the header The only problem is that some programs
//will pad not only the data, but also the file size to
//be divisible by 4 bytes.
for(int i=0;i<dataSize;i+=3) {
//jump over the padding at the start of a new line
if((i+1)%padWidth==0) {
i+=offset;
}
//transfer the data
*(data+j+2)=*(tempData+i);
*(data+j+1)=*(tempData+i+1);
*(data+j)=*(tempData+i+2);
j-=3;
}
}

return true;
}

bool Bitmap::convert8(char* tempData) {
int offset,diff;

diff=width*height*RGB_BYTE_SIZE;
//allocate the buffer for the final image data
data=new char[diff];

//exit if there is not enough memory
if(data==NULL) {
error="Not enough memory to allocate an image buffer";
delete[] data;
return false;
}

if(height>0) {
offset=padWidth-byteWidth;
int j=0;
//count backwards so you start at the front of the image
for(int i=0;i<dataSize*RGB_BYTE_SIZE;i+=3) {
//jump over the padding at the start of a new line
if((i+1)%padWidth==0) {
i+=offset;
}
//transfer the data
*(data+i)=colours[*(tempData+j)].rgbRed;
*(data+i+1)=colours[*(tempData+j)].rgbGreen;
*(data+i+2)=colours[*(tempData+j)].rgbBlue;
j++;
}
}

//image parser for a forward image
else {
offset=padWidth-byteWidth;
int j=dataSize-1;
//count backwards so you start at the front of the image
for(int i=0;i<dataSize*RGB_BYTE_SIZE;i+=3) {
//jump over the padding at the start of a new line
if((i+1)%padWidth==0) {
i+=offset;
}
//transfer the data
*(data+i)=colours[*(tempData+j)].rgbRed;
*(data+i+1)=colours[*(tempData+j)].rgbGreen;
*(data+i+2)=colours[*(tempData+j)].rgbBlue;
j--;
}
}

return true;
}

All my errors are to do with this code in Display.cpp:
 Bitmap image[2];

   image[0].loadBMP("myTexture.bmp");
   image[1].loadBMP("myTexture2.bmp");

Errors:
error C2040: image:'Bitmap [2]' differs in level of indirection of 'Bitmap'
error C2088: '[' illegal for class (twice)
error C2228: left of .BMP must have class/struct/union (twice)
no operator "[]" matches these operands (twice)

A: Bitmap image;

Bitmap image[2];

You're declaring image twice, that makes no sens. Remove the first one if you want image to be one bitmap.
If you go with the array, you'll need to refer to the actual bitmaps as bitmap[0] and bitmap[1]. And it doesn't fit with the rest of your code - you're calling loadTexture twice, so loading two bitmaps in there makes no sens. So stick with just one bitmap in there.
void loadTexture(GLuint texture, const char* filename)
{
   Bitmap image;

   image.loadBMP(filename);

   glBindTexture(GL_TEXTURE_2D, texture);

   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE , GL_MODULATE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
   gluBuild2DMipmaps(GL_TEXTURE_2D, 3, image.width, image.height, GL_RGB, GL_UNSIGNED_BYTE, image.data);
}


text:
Q: External references in JustinRainbow/JsonSchema I've been digging the way to use external references. I found that all references should be loaded to schema storage before using them in $ref.
I tried different ways to achieve that and finally there was no any exceptions:
$schemaStorage = new SchemaStorage();

$schemaStorage->addSchema('file://foo.json', json_decode(file_get_contents(realpath(__DIR__."/foo.json")));
$schemaStorage->addSchema('file://bar.json', json_decode(file_get_contents(realpath(__DIR__."/bar.json")));

$validator = return new Validator(new Factory($schemaStorage));

$validator->validate($jsonData, json_decode(file_get_contents(realpath(__DIR__."/main.json"))));

Then in my schema I tried to reference on defined schema id:
{
  "title": "foobar schema",
  "type": "object",
  "properties": {
    "foo": {
       "$ref": "file://foo.json"
    },
    "bar": {
       "$ref": "file://bar.json"
    }
  },
  "required": ["foo", "bar"]
}

But, still - all references are not validated even they are correctly preloaded. Only the main schema is used for validation. Maybe someone knows what's the correct way to do it?


text:
Q: DOS Batch file - Copy file based on filename into folder I would like to use a batch file to put them into default folder, but the account name is in the middle of the folder. Have any script I can use in dos command prompt?
888123AA.pdf
888123BB.pdf
888123CC.pdf
777456AA.pdf
777456BB.pdf
777456CC.pdf

Default folder:
999-888123-03
666-777456-01

A: @echo off
setlocal EnableDelayedExpansion

rem Process all .pdf files
for %%a in (*.pdf) do (
   rem Get just the file name, ie: "888123AA"
   set fileName=%%~Na
   rem Using the file name minus two last chars, ie: "888123"
   rem get the default folder with that name
   for /D %%b in (*-!fileName:~0,-2!-*) do (
      rem And copy the file to that folder
      copy "%%a" "%%b"
   )
)

A: I don't remember any apparent way to do it other than a UNIX shell... Maybe get MSYS and use that (outdated) bash to help?
Here is a bash script that can use after you installed bash from MSYS (or you can sort it with a Linux box - Ubuntu is no bigger than 800MB and can run as LiveCD without interfering your current Windows system, and the LiveCD can double as a system saver when needed. :-)
#!/bin/bash
for each in ./*; do
    if [ -d $each ]; then # Only folders are minded.
        # Extract the second part of the folder name.
        ACCOUNT_NAME=`echo $each | sed "s/\\-/\n/" | head -n 2 | tail -n 1`
        cp -v ./$ACCOUNT_NAME*.pdf $each
    fi
done


text:
Q: Make image height auto adjust to text height Given this HTML

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis facilisis nisi elit, vitae interdum nisi porttitor a. Maecenas porta mollis venenatis. Proin suscipit, est et malesuada ultricies, nisi elit aliquam arcu, et luctus felis dolor euismod ante. Praesent nec malesuada arcu. Nunc rutrum erat risus, id elementum leo dignissim eu. Fusce feugiat, massa vestibulum venenatis ullamcorper, nisl justo aliquam purus, nec pellentesque tellus magna non quam. Pellentesque luctus quam in justo congue tempor. Cras placerat sit amet nulla id pretium. Nulla facilisi. Phasellus dictum neque sed lacus congue, vel dapibus enim efficitur.

how can I make the image height scale automatically with the text div, according to browser width and font size of the text?

*

*https://jsfiddle.net/msuL6pvx/ In this case the image has to be scaled down to have the same height as the text

*https://jsfiddle.net/msuL6pvx/1/ In this case the image has to be enlarged to its max size (300x300) and not exceed those dimensions

A: I dont' think this is possible with pure CSS. The only think I could think of is using position: absolute for  to take it out of the flow in combination with max-height; then adjusting the margin of the text with javascript.
https://jsfiddle.net/zphb0fLd/
Hope it's useful.

A: Well as far as my knowledge, the image size can be increased with relative to text size, but its opposite case is not possible.
Here is my code. I use the flexbox to increase the height of the image as per text size. Let me know if it meets your requirements.

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis facilisis nisi elit, vitae interdum nisi porttitor a. Maecenas porta mollis venenatis. Proin suscipit, est et malesuada ultricies, nisi elit aliquam arcu, et luctus felis dolor euismod ante. Praesent nec malesuada arcu. Nunc rutrum erat risus, id elementum leo dignissim eu. Fusce feugiat, massa vestibulum venenatis ullamcorper, nisl justo aliquam purus, nec pellentesque tellus magna non quam. Pellentesque luctus quam in justo congue tempor. Cras placerat sit amet nulla id pretium. Nulla facilisi. Phasellus dictum neque sed lacus congue, vel dapibus enim efficitur.

.flex{
  display:flex;
  flex-wrap:wrap;

}
.image-container{
  flex:1;
}
.text-container{
  flex:3;
}
.text-container p{
  font-size:2em;
  padding:10px;
}
.image-container img{
  width:100%;
  height:100%;
  object-fit:cover;
}

Live example link: https://codepen.io/pranaysharma995/pen/JjdQWyQ


text:
Q: Webpack 5 devServer not loading public static files I have a file structure like this:
-node_modules
-public
--scripts
-src

And my webpack.config.js:
const path = require('path');

module.exports = () => {
    return {
        entry: './src/index.js',
        output: {
            path: path.resolve(__dirname, 'public/scripts'),
            filename: 'bundle.js'
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /nodule_modules/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                        },
                    },
                },
            ],
        },
        mode: process.env.WEBPACK_MODE || 'development',
        devServer: {
            static: {
                directory: path.join(__dirname, 'public'),
                publicPath: '/scripts'
            },

            hot: true,
            compress: true,
            port: 3000,
        },
    };
};

My problem is that the browser doesn't load any content reporting: Failed to load resource: the server responded with a status of 404 (Not Found) at 192.168.0.11/:1
When I remove the publicPath property, the HTML is getting rendered but bundle.js isn't found.

A: I hope this helps those who are looking for the answer. On webpack 5, we can set multiple paths to be public, just replacing the object with a list.
{
      ...
      devServer: {
        static: [
          path.join(__dirname, "build"),
          path.join(__dirname, "scripts"),
        ],
}


text:
Q: Java eats %100 cpu up I got this CentOS server in which a Java WebApp (Tomcat6+Hibernate+MySQL+Struts2) is being run.
Usually cpu usage is about 10% but sometimes all of a sudden it goes to 100% and the application freezes. The process causing this condition is the java command, then the server have to be rebooted to get things to normal. This happens completely irregularly, so it is kinda unlikely to be an app bug.
this is the top command under normal condition:
top - 12:50:35 up 21 min,  1 user,  load average: 0.13, 0.18, 0.21
Mem:   8300688k total,   836232k used,  7464456k free,    22168k buffers
Swap: 16779884k total,        0k used, 16779884k free,   309080k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  SWAP   TIME CODE DATA nFLT COMMAND
 3292 tomcat    18   0 1382m 415m  10m S 11.0  5.1   2:55.45 967m   2:55   36 1.3g  537 java
 3165 mysql     15   0  137m  25m 4908 S  5.3  0.3   0:26.64 111m   0:26 6496 124m   82 mysqld
 3456 root      34  19 25660   9m 2076 S  0.0  0.1   0:00.01  15m   0:00    4 8060    2 yum-updatesd
 3345 root      18   0 23040 9420 5520 S  0.0  0.1   0:00.08  13m   0:00  300 3860   20 httpd
 3421 apache    18   0 23040 4808  880 S  0.0  0.1   0:00.00  17m   0:00  300 3860    0 httpd
 3422 apache    18   0 23040 4808  880 S  0.0  0.1   0:00.00  17m   0:00  300 3860    0 httpd
 3423 apache    18   0 23040 4808  880 S  0.0  0.1   0:00.00  17m   0:00  300 3860    0 httpd
 3424 apache    18   0 23040 4808  880 S  0.0  0.1   0:00.00  17m   0:00  300 3860    0 httpd
 3425 apache    23   0 23040 4808  880 S  0.0  0.1   0:00.00  17m   0:00  300 3860    0 httpd
 3426 apache    24   0 23040 4808  880 S  0.0  0.1   0:00.00  17m   0:00  300 3860    0 httpd
 3427 apache    23   0 23040 4808  880 S  0.0  0.1   0:00.00  17m   0:00  300 3860    0 httpd
 3428 apache    23   0 23040 4808  880 S  0.0  0.1   0:00.00  17m   0:00  300 3860    0 httpd
 2951 haldaemo  19   0  5744 3944 1692 S  0.0  0.0   0:00.52 1800   0:00  268 2236    0 hald
 2669 named     19   0  109m 3684 1928 S  0.0  0.0   0:00.08 105m   0:00  364 102m    3 named

and when the hazard comes up:
top - 12:25:10 up 59 min,  3 users,  load average: 1.09, 0.97, 0.64
Tasks: 192 total,   1 running, 189 sleeping,   2 stopped,   0 zombie
Cpu(s): 12.5%us,  0.0%sy,  0.0%ni, 87.5%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   8300688k total,  2303376k used,  5997312k free,    85104k buffers
Swap: 16779884k total,        0k used, 16779884k free,   882748k cached

 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  SWAP   TIME CODE DATA nFLT COMMAND
 6609 root      18   0 1356m 1.2g  10m S 101.9 14.8   4:50.37 154m   4:50   36 1.3g    1 java
    1 root      15   0  2068  628  536 S  0.0  0.0   0:01.25 1440   0:01   32  280   20 init
    2 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 migration/0
    3 root      34  19     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 ksoftirqd/0
    4 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 watchdog/0
    5 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 migration/1
    6 root      34  19     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 ksoftirqd/1
    7 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 watchdog/1
    8 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 migration/2
    9 root      34  19     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 ksoftirqd/2
   10 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 watchdog/2
   11 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 migration/3
   12 root      34  19     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 ksoftirqd/3
   13 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00    0   0:00    0    0    0 watchdog/3

Interesting thing that the java process' user is tomcat when everything is fine, but it turns into root when problem comes up.
what could cause the issue?

A: There is obviously a thread that is hanging.
kill -3 processid

Will show a list of the running threads in the java-app. Collect these and send it back to the dev.

A: I would run VisualVM (if your running the Oracle version of Java)  , attach to the process, then take a dump of the vm (make sure its the most recent version of VisualVM/JDK that is possible).  Also, there is a "detect theadlock" button in their somewhere (or maybe it was in jconsole.exe).   Then , you can use a tool like jhat.exe (or Eclipse) to view the dump.


text:
Q: Best practices for validation depending on actions Spring MVC I am trying to perform validation using Spring validation. I am wondering what is the best practice to perform validation that depends mainly on user's action, hereafter, I have three different approaches but I don't know which one is best.
Assume, we have the following class Foo to validate and many different rules of validation depending on action performed by user.
public class Foo {
    private String name;

    private int age;

    private String description;

    private int evaluation;

    // getters, setters
}

What is the best way to perform these validations (for instance: during creation only name and age are required, during evaluate action, I only need evaluation to be validated and so on)
solution 1: one validator class per validation rule
public class CreateFooValidator implements Validator {
    //validation for action create
}
public class EvaluateFooValidator implements Validator {
    //validation for evaluate action
}

solution 2: one validator class with several methods
public class FooValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return Foo.class.equals(clazz);
    }

    //the default validate method will be used to validate during create action

    @Override
    public void validate(Object target, Errors errors) {
    //validation required
    }

    //method to validate evaluate action
    public void validateFooEvaluation(Object target, Errors errors) {
    //validation required
    }
    //other validation methods for other actions
}

solution 3: Additional property action in class Foo, one validator
public class Foo {

    private String name;

    private int age;

    private String description;

    private int evaluation;

    private String actionOnFoo;

    // getters, setters
}

public class FooValidator implements Validator {

    private final Foo foo = (Foo) target;
    @Override
    public boolean supports(Class<?> clazz) {
        return Foo.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        //test which action is performed by user
        if ("create".equals(foo.getActionOnFoo())) {
            //call for private method that performs validation for create action
        }
    }
    //all private methods
}

What is the best solution among the 3 or other solution if any?
Thanks!

A: Use JSR-303 Validation Groups, which are since Spring MVC 3.1 also supported by @Validated.
So, for each action you should have a method in your controller.
Create a validation group for each possible action that has a different set of rules, e.g.
public interface Create {
}

public interface Evaluate {
}

Annotate Foo with the validation annotations including the group, e.g.
public class Foo {

    @NotNull(groups = { Create.class, Evaluate.class })
    private String name;

    ...

    @Min(value = 1, message = "Evaluation value needs to be at least 1", groups = { Evaluate.class })
    private int evaluation;

    ...
}

Then annotate the foo argument of your controller methods with the appropriate @Validated annotation, e.g. @Validated({Evaluate.class}) for the evaluate controller method.
You can find another example here (see item 2):
http://blog.goyello.com/2011/12/16/enhancements-spring-mvc31/
Update:
Alternatively, if for some reason you can't / don't want to use @Validated, you can use an injected Validator instance and pass the groups to its validate method.  That's the way it was done before Spring 3.1 (as is the case in the article in your comment).

A: Depends that you want to do it. All solutions are good if you apply in all of your validators the same and you want to validate some business logic, not only if it's null or not (for this purpose you can use the @Valid annotation and annotation @Not null in your objects).
For me, if I have an object Foo I only want one Validator for this object, and then I have several methods for validate the data depends of I need in my controllers, for example, one for saving new Foo or other one for validating before updating, etc...


text:
Q: Check if value exists using firebase database I just want my code to check if value already exist in database when i click my button but somehow it doesn't return any value. I think i already follow tutorial on internet but not sure why it doesn't work for me.
This how my database looks like:

And this my onclick method:
@Override
public void onClick(View v) {
    try {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        Intent intent;

        switch (v.getId()) {
            case R.id.textViewLoginHere:
                intent = new Intent(ActivityRegister.this, ActivityLogin.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            case R.id.buttonRegister:
                progressBar.setVisibility(View.VISIBLE);
                checkIfUsernameExists();
                break;

        }
    }catch (Exception e){
        Toast.makeText(ActivityRegister.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
    }
}

And this is my method to check if value exists:
public void checkIfUsernameExists(){
        username = editTextUsername.getText().toString().trim();
        DatabaseReference usernameRef = FirebaseDatabase.getInstance().getReference("usernames");
        usernameRef.orderByValue().equalTo(username).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    Toast.makeText(ActivityRegister.this, "exists", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ActivityRegister.this, "not exists", Toast.LENGTH_SHORT).show();
                }
                enableButton();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

Is there anything wrong with my code and how i can fix it? Thank you in advance

A: try this ..
 public void checkIfUsernameExists(){
        username = editTextUsername.getText().toString().trim();
        DatabaseReference usernameRef = FirebaseDatabase.getInstance().getReference("usernames");
        usernameRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    String user = (String) data.getValue();

                    if (user.equals(username)) {
                        Toast.makeText(ActivityRegister.this, "exists", Toast.LENGTH_SHORT).show();
                        enableButton();
                    } else {
                        Toast.makeText(ActivityRegister.this, "not exists", Toast.LENGTH_SHORT).show();
                    }

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

in the example here you will got the "usernames" reference
 DatabaseReference usernameRef = FirebaseDatabase.getInstance().getReference("usernames");

on the response onDataChange() we will get dataSnapshot object that retrieve all the data about this reference
then we will make a loop for all the children in the dataSnapshot that we received
the children in the example is :

*

*FMt7S4ybHcf2f....oT2

*ioRdDue ...... sE22

then we get the Value in the child by  data.getValue()
and check if the value in this child equal to username

A: When you are using dataSnapshot.exists() it means that you are checking for existens a node, which is an object. You are not checking the existens of a value, which in this case is a String. So in order to see if a value does exists within an object you need to iterate through the childrens of that object.
So please use the follwing code:
public void checkIfUsernameExists(){
    username = editTextUsername.getText().toString().trim();
    DatabaseReference usernameRef = FirebaseDatabase.getInstance().getReference().child("usernames");
    usernameRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String user = ds.getValue(String.class);

                if (user.equals(username)) {
                    Toast.makeText(ActivityRegister.this, "exists", Toast.LENGTH_SHORT).show();
                    enableButton();
                } else {
                    Toast.makeText(ActivityRegister.this, "not exists", Toast.LENGTH_SHORT).show();
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}

As you can probably see, I have used getChildren() method to iterate through the DataSnapshot object to actually get all those childrens. Having those children, we can get the value to see if one of them is equals with the one we are looking for. In case of equality, we Toast exists, otherwise, not exists.

A: My mistake the root cause is because of the rules. This is a register page so the user is still not authorized. I just change it to:
{
  "rules": {
    ".read": true,
    ".write": "auth != null"
  }
}

then i manage to read the data. For more info check here. Just to add my original code works fine. after that. Very funny!
Anyway thanks for all that is trying to help. Thank you.


text:
Q: concurrent collections in python I was wondering if there was any concurrent structure like queue in python but with the ability to remove a specific element.
Example:
import queue

#with queue would be
q = queue.Queue()
#put some element
q.put(elem)

#i want to delete a specific element
#but queue does not provide this method
q.remove(elem)

What could I use?

A: Actually Python lists work like what you are looking for. As a matter of fact, the translation of your code (which requires no imports) should look like this:
#Create the list
q = [element1, element2, element3...]

#Insert element
q.insert(position, element4)

#Insert element in the end
q.append(element4)

#Remove element
del(q[position])

So that you can manage it as desired.
I hope that helps you.