text:
Q: What exception to throw if an operation would bring the object into an illegal state? Consider a Product with a quantity which can be increased and decreased by a given amount. The quantity should never become negative and if it is going to happen, the operation must be prohibited and the user warned.
public class Product{

    private int quantity;

    public Product() {
        quantity = 10;
    }

    public void decreaseQuantity(int amount) {
        int decreasedQuantity = quantity - amount;
        if(decreasedQuantity < 0 )
            throw new RuntimeException(String.format("Decrease quantity (%s) exceeds avaiable quantity (%s)",
                    amount, quantity));

        quantity = decreasedQuantity;
    }
}

For example if a product has quantity 10 and I try to remove 20, I throw a RuntimeException. SonarCloud suggests to replace the RuntimeException with a Custom exception, but I was wondering if there is a standard exception suitable for this case (Effective Java: Favor The Use of Standard Exceptions).
The most suitable exception seems to be IllegalStateException. From the javadoc

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

and from Effective Java

IllegalStateException: This exception is used if, when a method is called, the state of the object is not valid for that operation. Potentially you have a filehandle and you call read before it has been opened.

However, it seems to me that there is a subtle difference between my example and what is assumed in the docs: it is not the state of the object itself that makes the operation illegal, it's the state of the object and the value of the input parameter. Reading usage examples (like What's the intended use of IllegalStateException?) the object is always in a state where the operation is rejected regardless of the input parameter.

A: There is nothing in the core java libraries that is a slam dunk. However, make your own exception is probably your best bet, it's a close race between that and using IllegalArgumentException.
RuntimeException
Ill advised for nebulous reasons. The primary reason not to use it, is because linter tools will yell at you. The reason they yell at you is twofold, and to determine whether the right move is to tell the linters to shut up, or to head their advice, is to focus on these 2 reasons:

*

*The type name of the exception is itself information. For example, throw new NullPointerException("x is null") is dumb code to write (even though its common). It's superfluous - just new NullPointerException("x") is appropriate. RuntimeException conveys almost no information at all. You are mostly avoiding this trap: Whilst RuntimeException indeed conveys nearly nothing, the message of the exception says it all, therefore, the thing the linter is trying to stop from happening (throwing an exception that doesn't properly convey the nature of the problem) isn't happening, and thus you should consider just telling the linter to stop whining... except for:

*The second reason you want a proper exception type is that you really, really don't want code that intends to catch this to have to do string analysis on an exception message. Thus, if there's any world in which you can foresee that some code wants to invoke your method and then react to the condition (of trying to subtract more than available) in any way other than blowing up all context, then you should be throwing an exception that means this specific condition and nothing else. RuntimeException is never appropriate to catch if your intent is to catch a specific condition (it's pretty much never appropriate, period - sometimes you want to run code and react to any problem regardless of its nature, but then catch (Exception e) is the appropriate catch block, or even Throwable. e.g. appservers and the like should be doing this.
IllegalArgumentException
The linters won't be yelling, but you're still not really getting the secondary benefit (that is, allow callers to catch this specific problem and not some other problem with the arguments). It's also 'mentally' slightly dubious: Your reasons for initially disregarding it are not wrong. Generally IAEs are understood to imply that the illegal argument is illegal regardless of the state of this object. But this isn't written in IAE's javadoc and isn't universally applied.
So, downsides are:

*

*It's a bit of a push to force callers to catch (IllegalArgumentException e) to deal with wanting to react to subtracting more than is there. IAE is still too 'general'.

*It could be lightly confusing.

Upside is simply:

*

*It's already there.

IllegalStateException
I think this is strictly worse than IAE. It's mostly the same story, except here the confusion is that ISE is usually used to flag that the current state of the object is such that the operation you are trying to call is simply not available. In a tweaked way that's actually true (the object's state is that there are 3 items; therefore it is not in a state that decreaseQuantity(5) is an available operation right now), but it feels more confusing than IAE: ISE feels like the Product object itself is in an invalid state. I'd be assuming that the product is a legacy product that is not now or will ever be in stock again, or is some dummy product type (a Product object representing 'unknown product' or something similarly exotic).
But, same deal with IAE: The javadoc of ISE doesn't specifically spell out that you couldn't do it. Hence, if you would prefer to throw this, you could, it's not provably incorrect, at worst it's simply bad code style. A linter tool is never going to fault you for it, or if it does, the linter tool is wrong.
write your own
Advantages:

*

*There's no chance that users of your library bring faulty assumptions (that IAE means: Argument is illegal regardless of state); that makes it less confusing.

*If code intends to call your method and write a catch clause specifically for the condition of removing more than is there, then this is definitely the nicest answer. This:

try {
  product.decreaseQuantity(5);
} catch (QuantityInsufficientException e) {
  ui.showOrderingError("Regretfully we don't have this item in stock at the quantity you want");
}

Is slightly more readable than catch (IllegalArgumentException), and more importantly, is more reliable: IAE is such an oft-used exception that you're going to one day edit the decreaseQuantity method and introduce a code path that throws IAE for some other reason and now you have a very hard to find bug.
Conclusion
I'd be writing your own. Yes, it's a bit of a drag to have to write the source file, but you can let your IDE (or Project Lombok for maximum boilerplate busting) generate the entire file and you probably never have to look at InsufficientQuantityException.java ever again.

A: java.lang.IllegalArgumentException is the right answer in this case.
This example is equivalent to the following one from Effective Java - Third Edition (page 301):

Consider the case of
an object representing a deck of cards, and suppose there were a method to deal a
hand from the deck that took as an argument the size of the hand. If the caller
passed a value larger than the number of cards remaining in the deck, it could be
construed as an IllegalArgumentException (the handSize parameter value is too
high) or an IllegalStateException (the deck contains too few cards). Under
these circumstances, the rule is to throw IllegalStateException if no argument
values would have worked, otherwise throw IllegalArgumentException.

TheIllegalStateException is not correct because the state of the object does not prevent to invoke decreaseQuantity: you can invoke it, just use an appropriate input value.


text:
Q: What are these partitons and can I delete them I currently dual boot Windows 10 an Ubuntu, and I am getting ready to delete Windows.
The Ubuntu partitions that I know what they are are sda8,sda6, and sda7.
I assume sda4 is the main Windows partition.
What are sda1, sda2, sda3, and sda9, and can I delete them?

A: Partitions with a key symbol next to them, are currently in use. These are the ones you should not delete.
You see a column "mount points" in your output. Each partition that has an entry in that column is currently connected to your running Ubuntu system. These are data partitions. The one connected to / is your system partition. So for sure, these are the ones you should not remove in order to keep your system functional.
One more partition is possibly being used by your system even if it is not mounted. That is the swap partition. Such partition can be used as overflow ram, and is never as such mounted. To check whether it is used in your system, run the swapon command. If /dev/sda7 is used, you will see it mentioned in the output. If it is not in the output, it is not used and can be removed. Latest versions of Ubuntu do not use a swap partition anymore. They instead install a swap file, which you see in the output as /swapfile.
The other partitions can be removed without breaking your system. Of course, you do not want to loose user files. Thus, you need to make sure that any personal files that might be on these partitions are backed up to an external drive before you delete the partition.

*

*sda1 is a recovery partition used for recovery if the installed Windows system has problems.

*sda2 is the EFI partition, essential for booting your system

*sda3 is a Microsoft Reserved Partition, used to store certain software components that previously used hidden sectors.

*sda9 is a very small ntfs formatted partition, apparently with no specific purpose or use.

sda3, sda4, and sda9 could be deleted. The freed contiguous space could be used for a new data partition.

A: The partitions are quite clearly described on your screenshot.
sda1 is labelled "Recovery". Recovery partition allows to reinstall Windows and restore the computer to its factory default state. If you won't need Windows in the future, you can delete it.
sda2 is the EFI partition which is needed to boot the operating systems in modern computers that use UEFI and not the legacy BIOS to boot the operating system. Don't delete it or your computer will not boot.
sda3 is the Microsoft reserved partition which is used for additional system data that may be used by Windows. If you won't need Windows in the future, you can delete it.
sda4 is probably (as you suggest) the main Windows partition. To be sure, you can just mount in in Disks application and see what's on it.
I'm not sure what is the sda9 partition - from the screenshot it looks that it is located at the very end of the disk. But because it is NTFS formatted, and flagged as msftdata (like sda4) it is probably also something used by Windows, maybe another recovery partition? Probably you can delete it.
sda8 is a bit mysterious. Looks like something you created during Ubuntu installation (as it is ext4 formatted), but why isn't it mounted? Anyway, you said you know what this partition is, so no issue here.
sda6 is a root filesystem of your Ubuntu installation. Of course you should not delete it.
sda7 is a swap partition that your Ubuntu is currently using (it has a key icon next to its name, which indicates it is in use). Don't delete it as well. You can, however, assign swap space to a different partition or to a file on main Ubuntu partition, then it won't be needed anymore.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javamail ISO-8859-1 formatting I made an E- Mail Client for my Android phone with the Javamail Api. If I try to get the sender's mail address and the recipients mail address with the following methods:
Address[] froma = m.getFrom();
        String from = InternetAddress.toString(froma);

        Address[] toa = m.getRecipients(Message.RecipientType.TO);
        String to = InternetAddress.toString(toa);

I get a String like this back:
"Georg =?ISO-8859-1?Q?SP=E4the?=
and it has to be Georg Späthe or Georg Spaethe.
I think the Problem is that this are German Mails with another encoding. Can anybody help me to solve that problem?

A: MIME headers are encoded as per RFC 2047, therefore you need to decode them first.
String decoded = MimeUtility.decodeText("Georg =?ISO-8859-1?Q?SP=E4the?=");

JDK import:
import javax.mail.internet.MimeUtility;

For Android:
import com.android.email.mail.internet;

See also Javadoc of MimeUtility

A: Each of the Address objects will be an InternetAddress, cast it to that and use the getAddress or getPersonal method depending on what you want.

A: For what it's worth: You can cast to InternetAddress and use toUnicodeString that will return the decoded mail in the form of "Georg Späthe" <georg.spaethe@example.com> if your input address was "Georg =?ISO-8859-1?Q?SP=E4the?=" <georg.spaethe@example.com>. ALso, as explained by Bill Shannon, you can call getPersonal and getAddress to get the decoded values, so there is no need to fiddle around with MimeUtility yourself.


text:
Q: Shifting Features using Arcpy I am looking to shift some geometric features using ArcPy. However, I receive the following error message each time that I run the script. What is the issue?
import arcpy
def shift_features (in_features):
...  with arcpy.da.UpdateCursor(in_features, ['SHAPE@XY','XShift',YShift']) as cursor:
...       for row in cursor:
...           cursor.updateRow([[row[0][0] + (row[1] or 0),
...                              row[0][1] + (row[2] or 0)]])
...  return
...

When then I put :
shape=r'E:\Yael\All Sorts\Testing\MovingPolygon.shp'
shift_features(shape)

(where shape contains fields name XShift, YShift)
I keep getting :

Parsing error SyntaxError: EOL while scanning string literal

A: (I assume you're basing your code off of this ArcPy Café recipe.)
When you call cursor.updateRow, you need to pass back to it a parameter: a list of values the same length as the list of row that it would be working with. So, for example...
with arcpy.da.UpdateCursor(feature, ['FIELD', 'FOO', BAR']) as cursor:
    for row in cursor:
        print row                # prints a list of 3 values -- ['a', 'b', 'c']
        row[0] = 'd'             # changes element 0 of list
        print row                # ['d', 'b', 'c']
        cursor.updateRow(row)    # passes ['d', 'b', 'c']

I only changed the value of FIELD, but also had to send back values for FOO and BAR. I could also shorten it:
with arcpy.da.UpdateCursor(feature, ['FIELD', 'FOO', BAR']) as cursor:
    for row in cursor:
        cursor.updateRow(['d', 'b', 'c'])    # will work

But passing fewer values in the list won't work:
with arcpy.da.UpdateCursor(feature, ['FIELD', 'FOO', BAR']) as cursor:
    for row in cursor:
        cursor.updateRow(['d'])    # will fail

(It will similarly break if I pass too many values -- the number of elements in the list needs to match the number of fields called by the UpdateCursor.)

So for your specific situation, you need to pass back values for SHAPE@XY, XShift, and YShift. Right now, it's only getting SHAPE@XY (which is all the original snippet recipe was working with).
Try:
with arcpy.da.UpdateCursor(in_features, ['SHAPE@XY']) as cursor:
    for row in cursor:
        cursor.updateRow([[row[0][0] + (row[1] or 0),
                           row[0][1] + (row[2] or 0)]], row[1], row[2])


text:
Q: How to remove a folder created by old version of application with files during upgrade in advanced installer Many thanks in advance, I am using advanced installer 12.1, the scenario is we have already installed application with some custom location feature and is extends the default application location, this installation creates some folders to store temporary files like "Temporary" folder, this folder is used by the application on every minute basis and hence there are some files in this folder, now issue is when i run a new build or try to install the new version of the application, i again select the another custom location, before finishing the installation the installer deleting all the folders installed with older version but not deleting the folders which contains files created by the application e.g the temporary directory above is deleted if it is empty but when it is non-empty it is not removed.
Solution i tried:
1) I used file Removal tool to remove the file, but i think it point the current location and not pointing the older application path.
2) A custom VB script, but again the same issue as #1
3) I tried uninstall cleanup wizard, result #1
Please guide me how i can delete that folder, any help would be appreciated.
Thanks


text:
Q: Using mailto on the html, how can I open the email app from Safari in iOS? I have a simple form with a button to open an email window.
On my laptop, using Chrome, everything works fine. But on my iPhone, it doesn't open the email app.
This is the HTML
<form action="mailto:myemail@hotmail.com" method="post">
    <Button type="submit" class="button">Contact Me Now</Button>
</form>

How can I fix this?

A: To fix this, I removed the form and used an anchor tag instead.

   Contact Me Now


text:
Q: How to select data based on months using mysql I'm a beginner in php and making a small online banking system in php for my College project. I wanted to generate the statement for each month. I'm recording each transaction happening in each days. I wanted to retrieve rows from the table till the end of each month beginning from the starting of the account. So If I click on the view statement link, (considering that I opened the account on 14th of Feb) I need to see two statements. 1 from 14th of Feb to 28th of Feb and another one from 1st of March to current date.
What mysql query should I used to get this?

A: You might try appending to your current query the condition for the current month, you can -1, -2, -3, etc... to the AND MONTH... condition.
AND
YEAR(`date_column`) = YEAR(NOW())
AND MONTH(`date_column`) = MONTH(NOW())

where date_column is the name of the column you are working. It might also be that you are trying to GROUP BYMONTH(date_column)` its a bit hard to tell.


text:
Q: Using Cassandra with rails app I would like to use cassandra with my rails application. There are few questions in my mind:
* How can I connection pool the cassandra clients?
* How can I store cassandra client object in a place that is shared among all my model objects during the duration of request. Of course if there is a connection pool, I need to return the object back to the pool at the end of request processing.
Thanks a lot
Behrang

A: I found the solution:
I should use Thread.current[] to ensure the cassandra client is not recreated per request.
Something like:
Thread.current[:cassandra_client] ||= Cassandra.new(keyspace, servers)


text:
Q: Convergence with Meizu Pro 5 over USB C? I'm interested in the answer to this post but nobody has answered to it:

[Meizu] says [the Meizu Pro 5] will not support video and audio over USB C. Is this a software or hardware related issue?

Will it be possible to plug a USB C to HDMI adapter in order to have Convergence?

A: apparently audio video isn't supported over USB C on Meizu Pro 5. But you can do convergence using wireless display


text:
Q: RSPEC be_valid not acting consistently Most of my test is working, but for some reason the FactoryGirl.build ... should_not be_valid isn't working at the end of this statement
describe "exceed the maximum number of subscriptions" do
  @user = FactoryGirl.create(:user)
  loop_count = GlobalVar::MAX_SUBSCRIPTIONS
  loop_count.times do
    @topic = FactoryGirl.create(:topic)
    @subscription = FactoryGirl.create(:subscription, topic: @topic, user: @user)
  end
  @topic = FactoryGirl.create(:topic)
  FactoryGirl.build(:subscription, topic: @topic, user: @user).should_not be_valid
end

In the same spec this passes successfully:
it "has a maximum length bio" do
    FactoryGirl.build(:user, bio: "a"*251).should_not be_valid
end

Here is the start of the error I'm getting:
(druby://192.168.1.118:53053) C:/Sites/mavens/spec/models/user_spec.rb:42:in `block (3 levels) in <top (required)>': undefined local variable or method `be_valid' for #<Class:0x7e49290> (NameError)
    from (druby://192.168.1.118:53053) C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rspec-core-2.11.1/lib/rspec/core/example_group.rb:238:in `module_eval'

I'm using Spork and Guard to test. I have FactoryGirl reloaded in spec_helper for each run. Have restarted spork several times and it does not work with the restart. Let me know if any of my additional code would be helpful, and as always many thanks for the help!!

A: You need to put tests inside it blocks:
describe "exceed the maximum number of subscriptions" do
  it do
    user = FactoryGirl.build(:user)
    GlobalVar::MAX_SUBSCRIPTIONS.times do
      topic = FactoryGirl.build(:topic)
      FactoryGirl.build(:subscription, topic: topic, user: user)
    end
    topic = FactoryGirl.build(:topic)
    FactoryGirl.build(:subscription, topic: topic, user: user).should_not be_valid
  end
end

This is due to how RSpec handles the context of the DSL.


text:
Q: Apache/Passenger rufus cron job not working I have a Rails app running on Apache/Passenger.  I have a rufus cron job that runs in the background and sends out notifications via email.  When I am running the app in development on the WEBrick server, the emails are sent like they are supposed to be sent.  When I start up the app in production on Apache/Passenger, then the emails dont get sent.  The class doing the work is in config/initializers/task_scheduler.rb
require 'rubygems'
require 'rufus/scheduler'

Rails.logger.info "Starting the scheduler"

## to start scheduler
scheduler = Rufus::Scheduler.start_new

## Every day at 6 AM, send email for projects that haven't been updated in 14 days
Rails.logger.info "Adding the Stale Email job to the scheduler"
scheduler.cron("* * * * *") do
  Rails.logger.info "Running every minute"
  projects = Project.stale
  projects.each do |project|
    Rails.logger.info "Inside the loop"
    days = (Time.now - project.updated_at).to_i / 1.day
    ProjectMailer.stale(Jetway::Application.config.stale_email, project, days).deliver
    Rails.logger.info "Sent stale email for project #{project.name}; it's #{days} days stale."
  end
end

Right now it is running every minute, so I can debug.  Here is my log file output.
Started GET "/assets/availity_spinner.gif" for 99.44.242.76 at 2012-06-23 21:46:28 -0400
Served asset /availity_spinner.gif - 304 Not Modified (0ms)
Starting the scheduler
Adding the Stale Email job to the scheduler

You can see the log statement and how far we get into the code.  I have read in blogs that Passenger kills threads, specifically around cron jobs.  I am stuck and trying to get a direction to figure out this issue.  Please point me in the right direction.

A: Add the below lines to your apache2 config and restart your apache2 server
RailsAppSpawnerIdleTime 0
PassengerMinInstances 1


text:
Q: finding sum of a series I need some hint to find the sum of the series.
$$\displaystyle \sum_{n=1}^{\infty}\frac{1}{n3^n}$$
I calculated using mathematica. it gives the sum as $\log(3/2)$

A: Use the expansion
$$-\log{(1-x)} = \sum_{n=1}^{\infty} \frac{x^n}{n} $$
Then you should get
$$-\log{\frac{2}{3}} = \log{3}-\log{2} = \sum_{n=1}^{\infty} \frac1{n 3^n}$$


text:
Q: How does one definition of "countably compact" lead to another? The fundamental definition of countably compact as given in my textbook ("Foundations of General Topology by Pervin)  is: $X$ is countably compact if every infinite subset $E$ of $X$ has a limit point within $E$.
How does this definition lead to the modern definition of countably compact: every countable cover of a subset has a finite subcover?
Motivation:
Let subset $E$ consist of an infinite countable number of points $\{x_{i}\}, i\in\Bbb{N}$. Let $\{x_{1},x_{2}\}$ be one open set, and each $\{x_{i}\},i\geq2$ be a distinct open set. Let every open set containing $x_{1}$ contain at least one of $x_{i},i\geq 2$. This shows that $x_{1}$ is a limit point of $E$, and also a part of $E$.
Clearly, if we take $\{x_{1},x_{2}\},\{x_{2}\},\{x_{3}\},\dots$ to cover $E$, we don't get a finite subcover of $E$.
EDIT: In another portion, the book says "a countably compact subset $E$ must have atleast one limit point within $E$".

A: Pervin's definition is of the Bolzano-Weierstrass property, and it can be stated more succinctly as follows:

$X$ has the Bolzano-Weierstrass property if it does not contain an infinite closed discrete subset.

Every countably compact space has the Bolzano-Weierstrass property. To see this, suppose that $X$ does not have the Bolzano-Weierstrass property. Then $X$ has an infinite closed discrete subset $D$. Let $D_0$ be a countably infinite subset of $D$; then $D_0$ is discrete and closed. For each $x\in D$ let $V_x$ be an open nbhd of $x$ such that $V_x\cap D_0=\{x\}$, and let $\mathscr{U}=\{X\setminus D_0\}\cup\{V_x:x\in D_0\}$; then $\mathscr{U}$ is a countable open cover of $X$ with no finite subcover, since for each $x\in D_0$, $V_x$ is the only member of $\mathscr{U}$ that contains $x$, and $X$ is not countably compact.
The converse is false in general. For each $n\in\Bbb N$ let $V_n=\{k\in\Bbb N:k<n\}$, and let $$\tau=\{\Bbb N\}\cup\{V_n:n\in\Bbb N\}\;;$$ then $\tau$ is a $T_0$ topology on $\Bbb N$. Suppose that $A\subseteq\Bbb N$ is a non-empty closed set; then $$A=\Bbb N\setminus V_n=\{k\in\Bbb N:k\ge n\}$$ for some $n\in\Bbb N$, and $A$ is not discrete: every open nbhd of $n+1$ contains $n$. Thus, the only closed discrete set in $\langle\Bbb N,\tau\rangle$ is the empty set, and therefore $\langle\Bbb N,\tau\rangle$ has the Bolzano-Weierstrass property. However, it's easy to check that $\{V_n:n\in\Bbb N\}$ is an open cover of $X$ with no finite subcover, so $\langle\Bbb N,\tau\rangle$ is not countably compact.
The converse does hold in $T_1$-spaces, however: every $T_1$-space with the Bolzano-Weierstrass property is countably compact. To see this, suppose that $X$ is $T_1$ and that $\mathscr{U}=\{U_n:n\in\Bbb N\}$ is a countable open cover of $X$ with no finite subcover. For $n\in\Bbb N$ let $V_n=\bigcup_{k\le n}U_k$, and let $\mathscr{V}=\{V_n:n\in\Bbb N\}$. Then $\mathscr{V}$ is also a countable open cover of $X$ with no finite subcover, and $V_n\subseteq V_{n+1}$ for each $n\in\Bbb N$. Let $M=\{n\in\Bbb N:V_n\subsetneqq V_{n+1}\}$; if $M$ were finite, we'd have $V_{\max M}=X$, and $\mathscr{V}$ would have a finite subcover, so $M$ is infinite. For each $n\in M$ let $x_n\in V_{n+1}\setminus V_n$, and let $D=\{x_n:n\in M\}$; clearly $D$ is infinite, and I claim that it is closed and discrete as well.
To see this, let $x\in X$ be arbitrary; there is an $n\in M$ such that $x\in V_n$. By construction $V_n\cap D=\{x_k:k<n\}$; let $F_x=\{x\}\cup(V_n\cap D)$. $F_x$ is finite, and $X$ is $T_1$, so $F_x$ is closed, and therefore $V_n\setminus F_x$ is an open nbhd of $x$. Finally,
$$D\cap(V_n\setminus F_x)=\begin{cases}
\varnothing,&\text{if }x\notin D\\
\{x\},&\text{if }x\in D\;,
\end{cases}$$
so $D$ is indeed closed and discrete.

A: That equivalence (if you take a limit point of a set to be the point each neighbourhood of which contains infinitely many points from that set), as julien has stated, indeed holds in case of $T_1$ spaces and you can prove it in this case as follows.
So first assume a $T_1$ space $X$ to be countably compact in the sense of coverings, and assume that there's an infinite subset $E$ eithout limit points. You can take $E$ to be countable. Now since $X$ is $T_1$ and $E$ has no limit points, it follows that $E$ is closed, i.e. $X\backslash E$ is open (indeed, take any point $x\in X\backslash E$, by our assumption, it is not a limit point for $E$, hence $\exists U\subset X\backslash E$ - an open neighbourhood of $x$ which contains at most finitely many of points from $E$ - say, $x_1,...,x_n$. By $T_1$-property, you can choose an open neighbourhood $V$ of $x$ which does not contain any of $x_1,...x_n$. Then $U\cap V$ will be the neighbourhood of $x$ which does not intersect $E$. Hence, $X\backslash E$ is indeed open).
Also, for any $x_i\in E$ you can choose an open set $V_i$ with the property $V_i\cap E = \{x_i\}$ (again due to our assumption and $T_1$-property). Consider the family $\{X\backslash E, V_i|i\in \mathbb{N}\}$. It is a countable open cover (recall that we assumed $E$ to be countable) of $X$. Choose a finite subcover to obtain a contradiction ($E$ is infinite!).
The proof of the other part is as follows. You assume that there's a countable open cover ${\cal U} = \{U_1,...,U_n\}$ of $X$ that has no finite subcover. Hence you can assume without loss of generality that for every $k>1$ the set $U_{k+1}$ is not contained in the union of $U_1,...,U_k$ (since if it was contained, you would simply delete it from your cover, and considered the respective subcover. After doing all of the required deletions, you would obtain still an infinite subcover according to our assumption).
So now for any $k\in \mathbb{N}$ choose $x_k\in U_{k+1}\backslash \cup_{i=1}^k U_i$. Denote $E = \{x_1,...,x_n,...\}$. $E$ must have a limit point, say, $x_0\in X$. This point must be contained in $U_i$ for some $i\in \mathbb{N}$. But $U_i$ contains only finitely many points from $E$, namely, $x_1,...,x_{i-1}$, a contradiction with $x_0$ being a limit point of $E$.
I hope this helps...


text:
Q: Can you convert any "bad" classifier to a good one? Consider an ML Model that is trained to classify between two classes of elements.
This particular classifier has consistently (must be consistent for the following conversion to take place) poor performance, say 30%.
Does flipping the output of this classifier result in a 70% accuracy classifier?

A: Accuracy is (TP + TN)/(P + N), where TP are true positives, TN are true negatives, P are positive cases, and N are negative cases. This means that the numerator is calculated by counting cases such that predicted == actual. The condition is the same as looking at !predicted != actual, because it's a double negation. So if you reverse the labels, it's the same calculating predicted != actual, while
the denominator wouldn't change. So yes, reversing the labels would reverse accuracy.


text:
Q: how do i "View in browser" a mvc 2 app? This is probably a pretty simple question, but I don't see how to view in browser like I would for a traditional asp.net application.

A: If you're using Visual Studio, Ctrl + F5 to run without debugging and Cassini will take care of the rest (or do you mean from inside visual studio like you can with webforms)?

A: Sadly, it seems that Microsoft has acknowledged this as a bug.
There are a couple workarounds you can try -- though none of them are exactly what you are looking for. None of them let you start your web page from any arbitrary page simply by right-clicking.
One inexact workaround that is good enough for me is:
If you open up your project properties and go to the Web tab you will see the "Start Action" setting. Change this to "Don't open a page. Wait for a request..."
Now when you start debugging, nothing will happen! (oh no, it's worse!)
Now you can right-click on the Cassini system-tray icon and choose to open the browser from there. You only have to do this on your first session of the day. Once you do this, you can navigate to where you want in your site, and keep that browser window open all day. Letting you start and stop debugging from that point whenever you want.
Again, it isn't exactly the same, but it isn't terrible either.

A: Just run the Visual Studio Project and it should open the application's Index view of home controller by default!
If you are talking about IIS file viewing, in IIS go to your application -> switch to content view -> go to default.aspx -> right click -> choose browse


text:
Q: Using bind to utilize another Javascript class's method I have an old-style class in Javascript that I want to utilize another old-style class's behavior without a full subclassing. Something like this:
function Foo(x) {
  this.x = x;
}
Foo.prototype.add1 = function() {
  return this.x + 1
}
function Bar(n) {
  this.x = 2*n;
}
Bar.prototype.add1 = function() {
  // steal behavior from Foo.add1
  return Foo.prototype.add1.call(this);
}

This works fine in a browser console:
> b = new Bar(3)
Bar {x: 6}
> b.add1()
7

Is there a way to use bind instead? Something like
function Bar(n) {
  this.x = 2*n;
}
Bar.prototype.add1 = Foo.prototype.add1.bind(xyz);

except that there's no "this" object to use for xyz before the object actually exists.
The following code works, but seems wrong....
function Bar(n) {
  this.x = 2*n;
  this.add1 = Foo.prototype.add1.bind(this);
}

Is there a way to use bind in this way when setting up an old-style class's prototype?

A: You didn't need to use bind, just assign Bar.prototype.add1 = Foo.prototype.add1. bind method is useful for instances not for classes.


text:
Q: Orchard cms, how to make a list of content items on admin menu Can somebody help me finding any sort of doc, how to make a list of content item on the admin menu.
Regards
George

A: Any content item can be promoted to the admin menu if there is the Admin Menu Part on its content type. Projections have this part by default.
That doesn't necessitate any coding, but if you want to see how to add a custom list of contents from code to the admin menu, there are examples of that in Vandelay.Industries.

A: You just have to make a query to the ContentManager with the criterions you want:
var query = _contentManager.Query( //your query);

This method has a ton of overloads and extension overloads, so you should find one that suits your needs.
For an exemple of use, try looking at the source from the Contents AdminController (see source), it does exactly that.


text:
Q: Bcrypt in node.js http request error 500 I want to make create users with hash password, and when i am sending http request i have code error 500 Internal Server Error. Can someone tell me what is wrong??
router.post('/create', function (req, res, next) {

  var newUser = {
    login: req.body.login,
    password: req.body.password,
  }

  bcrypt.hash(password, saltRounds, function (err, hash) {
    if (err) {
      console.log(err)
    } else {
      newUser.password = hash;
      var user = new User(newUser);
      user.save()
        .then(function (User) {
          res.send(User);
        })
        .catch((err) => {
          console.log(err)
        })
    }

  });
});


text:
Q: where are the windows users names stored in xp...? I am writing an application that searches for a particular file in the C:\Documents and Settings\user accounts\Application Data folder. Now i am trying to make this application generic. I can make this application search in a particular users application data folder. But what i am tryin to do is take the user name from a certain file or place where windows xp stores it. Then make it search for that user. Is there a particular way to do it.
Need ideas and suggestions.

A: User Names are Stored in Windows Registry or Use Can get FolderNames as C:\Documents and Settings contains Every Folder with a UserName

A: The problem here is that Microsoft has not provided an API method of doing this directly.  Perhaps it was an oversight.  That being said, any solution you find is going to be some kind of workaround and is going to present some kind of limitations.
Using the registry to get this information is not officially supported by Microsoft and thus, may not work going forward.
Iterating through user profile folders is unreliable because the folder is not always named after its user and because you can change its location.
And so on.
All of that being said, I use a combination of WMI and the registry to accomplish this.  Here's what it looks like in VBScript, you should be able to adapt it to your needs.
  ' Create some arrays to hold the data.

arrUsers = Array()
arrSIDs = Array()
arrAppDataFolders = Array()

 ' Get a list of all the non-system users with their SID
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2"
Set colUsers = objWMIService.ExecQuery _
    ("Select * from Win32_UserAccount Where Status = 'OK'")

i = 0
For Each objUser in colUsers
    ReDim Preserve arrUsers(i)
    ReDim Preserve arrSIDs(i)
    arrUsers(i) = objUser.Name
    arrSIDs(i) = objUser.SID
    i = i + 1
Next

Set colUsers = Nothing
Set objWMIService = Nothing

  ' Now go to the registry and get the Document folder location using the SID
Const HKEY_USERS = &H80000003

Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
    & strComputer & "\root\default:StdRegProv")

ReDim arrAppDataFolders(UBound(arrSIDs))
For i = 0 to UBound(arrSIDs)
    strKeyPath = arrSIDs(i) & "\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
    strValueName = "AppData"      ' or "Local AppData"
    intReturn = objRegistry.GetExpandedStringValue HKEY_USERS, strKeyPath, strValueName, strValue
    If (intReturn = 0) And (Err.Number = 0) Then
        arrAppDataFolders(i) = strValue
    Else
        arrAppDataFolders(i) = vbNull
    End If
Next

Set objRegistry = Nothing

A: net user

from a command prompt will return a list of all users... probably more than what you're asking for. Your best bet is to do what you had already planned on doing with your Documents and Settings.


text:
Q: Adding scrollview that is compatable with my layout I am trying to make my main layout file scrollable, but whenever I try to change it to a scrollview, I get error messages.  I tried to put a linear view for my widgets and the srollview on the outside but it does not work.  I am wondering if there is a better way to add a scrollview, and one that is compatable with my xml file.
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context="com.example.jesse.myapp2.MainActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textMultiLine"
        android:id="@+id/editText"
        android:cursorVisible="false"
        android:textSize="20sp"
        android:textStyle="normal|bold"
        android:background="@android:color/transparent"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="250dp"
        android:id="@+id/imageView2"
        android:layout_marginTop="1dp"
        tools:textSize="12sp"
        android:onClick="click"
        android:layout_gravity="left"
        app:srcCompat="@android:drawable/ic_menu_camera"
       />

    <View
        android:layout_width="fill_parent"
        android:layout_marginTop="5dp"
        android:layout_height="1dp"
        android:background="@color/black" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dp"
        android:layout_marginTop="1dp"
        android:inputType="textPersonName"
        android:ems="10"
        android:cursorVisible="false"
        android:textSize="10sp"
        android:background="@android:color/transparent"
        tools:textAlignment="gravity"
        android:id="@+id/editText4" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="@color/black" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:weightSum="2">

    <EditText
        android:layout_width="0dp"
        android:layout_weight="1"
        android:inputType="textMultiLine"
        android:ems="10"
        android:id="@+id/editText2"
        android:layout_height="wrap_content"
        android:textAlignment="inherit"
        tools:textAlignment="gravity"
        android:cursorVisible="false"
        android:autoText="true"
        android:gravity="left"
         android:textSize="12sp"
        android:background="@android:color/transparent"
        android:layout_marginRight="5dp"
        />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:ems="10"
            android:id="@+id/editText3"
            android:inputType="textMultiLine"
            android:textSize="12sp"
            tools:textAlignment="inherit"
            android:textAlignment="gravity"
            android:cursorVisible="false"
            android:gravity="left"
            android:maxLines="18"
            tools:backgroundTint="@android:color/transparent"
            android:background="@android:color/transparent"
            />

    </LinearLayout>

</LinearLayout>

A: Wrap LinearLayout with ScrollView like below.
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        ...

    </LinearLayout>

</ScrollView>

A: <ScrollView android:layout_width="match_parent" android:layout_height="match_parent">

android:layout_width="match_parent"
 android:layout_height="match_parent">
...


text:
Q: How can I return a list of strings from a LINQ to Entities many-many relationship? I have a view model that needs to encapsulate a couple of many-to-many relationships.
I have my LINQ to Entites query that returns the appropriate list, but can't figure out how to return a list of objects.
I have a Foo table, and a Bar table.  Bar has a FK to Foo.ID, and a Description string.  I want to create a FooViewModel that has Foo.ID, as well as list of all the Bar.Descriptions.
  public class FooViewModel {
    public int ID {get; set; }
    public IEnumerable Descriptions { get; set; }
  }

  var all = from f in ctx.Foo.Include("Bar")
            select new FooViewModel
            {
              ID = f.ID,
              Descriptions = <insert magic here>
            };

What am I missing?

A: In Linq to Sql, Foo objects would have a property "Bar" (or "Bars" if it's one-to-many), so it would be just:
var all = from f in ctx.Foo
            select new FooViewModel
            {
              ID = f.ID,
              Descriptions = f.Bars;
            };

I'm told it works the same way in Linq-to-Entity, with the proviso that while that property is automatically create in L2S, there's some explicit task you must do manually to have L2e create it.


text:
Q: wildfly-swarm project-stabes-yml configre jms-bridge I'm trying to configure a jms-bridge for Wildfy Swarm in the project-stages.yml file, but without success.
Someone would be kind to tell me how I have to proceed?
Thanks a lot.


text:
Q: Why does "echo EHC1 > /proc/acpi/wakeup" change Enabled to Disabled I have a very basic question.  I understand what echo does, and how it directs a string to the file /proc/acpi/wakeup.
My question is what is actually happening when I direct the word EHC1 to /proc/acpi/wakeup.  Why does it change the line under Status from *enabled to *disabled or vice versa?
Thank you!  Why doesn't it just append the word EHC1 to the end?

A: Like the other files at /proc/ the file /proc/acpi/wakeup is not a real file but an interface to some kernel functions.
If you write something into it, the value you wrote isn't stored in a file but a kernel functions is called and does something with the value.
If you read from it another kernel function is called that creates some output that appears as the content of that file.


text:
Q: Permission denied (public key) for ubuntu user but not for root on AWS EC2 instance Yesterday I was able to use my key pair to log into my EC2 instance, but this morning it tells me "Permission denied (public key)".
I am on an ubuntu AMI, I checked that I was trying the correct user name. However what is interesting is that when I try to ssh in using 'root', it connects and authenticates successfully, but tells me to use 'ubuntu' instead and terminates the connection.
How can the public key work for root, but not for the 'ubuntu' user?
Is there perhaps something wrong with the permissions for user 'ubuntu' on the EC2 instance?

A: Public key/private key pair added in .ssh directory of every user. Check where you hace added this key. in ssh directory of root user or ssh directory of ubuntu user. ssh directory is different for all users.
You can find this directory as /home/ubuntu/.ssh

A: Turns out I had changed the permissions on the ubuntu user's home directory.


text: Q: How to set previous selected dates in times square calendar picker view from today? I want to set previous dates on the calendar and I am using times square library calendarPickerView.....Dates are coming from server, and I want to highlight with red colour on the calendar.


text:
Q: Dice Battle Game I need help with a dice battle game for Visual Basic.
A player and a computer are supposed to battle each other. When you click on the Roll button, it generates 6 random images - 3 for the PC and 3 for the PLAYER.
I got everything down, but I can't seem to add the 3 images. The first image shows, but the second and third aren't showing up, nor the three for the PC.
Here is my code
//=============================================================================
Public Class Form1

Dim randomObject As New Random() 'Create Random object
Dim BestOfGamesCounter As Integer

Private Sub RollDice_Click(sender As Object, e As EventArgs) Handles RollDice.Click
    If GameTextBox.Text <= "0" Then
        MsgBox("Number of Games > 0", MsgBoxStyle.Critical)
        Application.Restart()
    End If

    If GameTextBox.Text > "0" Then
        BestOfGamesCounter = Convert.ToInt32(GameTextBox.Text)
    End If

    DisplayDie(d1PictureBox)
    DisplayDie(d2PictureBox)
    DisplayDie(d3PictureBox)

    DisplayDie(UserDice1)
    DisplayDie(UserDice2)
    DisplayDie(UserDice3)
End Sub

Sub DisplayDie(diePictureBox As PictureBox)
    'generate random integer in range 1 to 6
    Dim face As Integer = randomObject.Next(1, 7)

    'retrieve specific die image from resources
    Dim pictureResource = My.Resources.ResourceManager.GetObject(String.Format("die{0}", face))

    'Convert pictureResource to type Image and display in ImageBox
    diePictureBox.Image = CType(pictureResource, Image)
End Sub ' DisplaDie

Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
    Dim response As MsgBoxResult
    response = MsgBox("Do you want to exit?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question)
    If response = MsgBoxResult.Yes Then
        Me.Dispose()
    End If
End Sub

Private Sub GameTextBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles GameTextBox.Validating
    If GameTextBox.Text > "0" Then
        Do
            MsgBox(GameTextBox.Text + " round(s) will be played GOOD LUCK")
        Loop While GameTextBox.Text = "STOP"
    End If
    GameTextBox.Enabled = False
End Sub

End Class


text:
Q: Initialize vector to zero Initially the vector "perm" is null. I want to set it to zero based on the index of the loop. But i have encounter error "vector subscript out of range" while doing the below code.
I placed "perm(charLength, 0)" in the "Start()" method outside of any loop so that it will not be reset, it's used for accumulating values.
DecodeEngine.h
class DecodeEngine
{

public:

    vector<int> temp;
    vector<int> perm;

    //Default constructor
    DecodeEngine();

    //Declare a virtual destructor:
    virtual ~DecodeEngine();

    //Methods
    string GetFilePath();
    Mat Start();
    void FrameTo8by8();
};

DecodeEngine.cpp
Mat DecodeEngine::Start()
{
  charLength = 160;

  //Initialize perm to zero
  perm(charLength, 0);

  //Loop 1st 100 frame of header
  while(true)
  {
     if(frame_count <= 100)
     {
        FrameTo8by8();                  //Proccess and algorithm

        namedWindow("dctBlockImage");
        imshow("dctBlockImage", dctImage);      //display watermarked image

        if(waitKey(30) == 27) //wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
        {
            cout << "esc key is pressed by user" << endl;
            break;
        }

        frame_count++;
     }

     else
     {
        cout << endl;
        cout << "End of video" << endl;
        cout << endl;

        destroyWindow("Original Video");
        destroyWindow("dctBlockImage");
        break;
     }
}

void DecodeEngine::FrameTo8by8()
{
  for(int i = 0; i < height-16; i += 16)
  {
    for(int j = 0 ; j < width-16; j += 16)
    {
       if(j > 112)
       {
           if(((sum4 / 4) - avg) > 0)
           {
              value = 0;
              temp.push_back(value);
           }

           else
           {
              value = 1;
              temp.push_back(value);
           }
       }

       if(temp.size() == charLength)
       {
          for(int a = 0; a <= temp.size(); a ++)
          {
             //Initialize perm to zero
             perm[a] = 0;

             if(temp[a] == 1)
             {
                perm[a]++;
             }

             //Reset temp for next frame to use
             temp[a] = 0;
          }
       }

    }
  }
}

A: This line:
perm(charLength, 0);

Does not call the constructor std::vector(size_t, const T&) and initialize the vector with 160 elements of value 10. In fact, I don't see how that compiled at all since the vector class doesn't have an operator().
std::vector contains a member function assign() that you can instead:
perm.assign(charLength, 0);

A: In the following piece of code, you go out of range:
   ...
   if(temp.size() == charLength)   // ok!  temp.size() is same as perm.size()
   {
      for(int a = 0; a <= temp.size(); a ++)   // !!! loop will execute with a=temp.size() and stop afterwards
      {
         //Initialize perm to zero
         perm[a] = 0;                    // !!! but subscripts start with 0 and go to temp.size()-1


text:
Q: Reconhecimento facial em Tempo real no Android Bom dia!
Estou criando um aplicativo de reconhecimento facial em tempo real. O aplicativo deve comparar a imagem em vídeo com uma imagem gravada.
Em praticamente todas as pesquisas que fiz o mais indicado a ser utilizado foi o OpenCV.
Implementei com este tutorial, a biblioteca contendo a versão 3.1.0 do OpenCV.
Estou lendo todas as informações da API. Porém, não estou encontrando um método para reconhecimento facial, onde eu possa usar o onDraw e desenhar um quadrado no rosto e muito menos como utilizar o reconhecimento facial e comparar com outro rosto.
Alguém já utilizou esta API? Recomenda o uso desta ou de outra ferramenta?
Abaixo o fonte:
ShowCameraActivity
public class ShowCameraActivity  extends AppCompatActivity implements CvCameraViewListener2 {

private static final String TAG = "OCVSample::Activity";
private CameraBridgeViewBase mOpenCvCameraView;
private boolean              mIsJavaCamera = true;
private MenuItem             mItemSwitchCamera = null;
Mat mRgba;
Mat mRgbaF;
Mat mRgbaT;

public ShowCameraActivity() {
    Log.i(TAG, "Instantiated new " + this.getClass());
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "called onCreate");
    super.onCreate(savedInstanceState);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.show_camera);
    mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);
    mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    mOpenCvCameraView.setCvCameraViewListener(this);
}

@Override
public void onCameraViewStarted(int width, int height) {

    mRgba = new Mat(height, width, CvType.CV_8UC4);
    mRgbaF = new Mat(height, width, CvType.CV_8UC4);
    mRgbaT = new Mat(width, width, CvType.CV_8UC4);
}

@Override
public void onCameraViewStopped() {
    mRgba.release();
}

@Override
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    mRgba = inputFrame.rgba();
    Core.transpose(mRgba, mRgbaT);
    Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
    return mRgba;
}

private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
    @Override
    public void onManagerConnected(int status) {
        switch (status) {
            case LoaderCallbackInterface.SUCCESS:
            {
                Log.i(TAG, "OpenCV loaded successfully");
                mOpenCvCameraView.enableView();
            } break;
            default:
            {
                super.onManagerConnected(status);
            } break;
        }
    }
};

@Override
public void onPause()
{
    super.onPause();
    if (mOpenCvCameraView != null)
        mOpenCvCameraView.disableView();
}

@Override
public void onResume()
{
    super.onResume();
    if (!OpenCVLoader.initDebug()) {
        Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, mLoaderCallback);
    } else {
        Log.d(TAG, "OpenCV library found inside package. Using it!");
        mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
    }
}

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

<org.opencv.android.JavaCameraView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"
    android:id="@+id/show_camera_activity_java_surface_view"
    opencv:show_fps="false"
    opencv:camera_id="back" />

Inserido no Manifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<supports-screens android:resizeable="true"
    android:smallScreens="true"
    android:normalScreens="true"
    android:largeScreens="true"
    android:anyDensity="true" />

<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>

PS: A dúvida Reconhecimento Facial de 2014 indicava como resposta o uso do tutorial onde o link está down. Também lí sobre o FaceDetection muito bom, por sinal. Mas a maioria dos métodos estão descontinuados e mesmo implementando a atualização dos métodos, não estou conseguindo validar a imagem com alguma foto.
Muito obrigado!


text:
Q: what does "have someone identified by" mean in this context? I think the sentence basically means that we need to consider the man's history to judge if something is good or ill fortune to him.
I also think the relevant part of it can be shortened as "good or ill fortune has a person identified by...". If I'm right, then what does "have someone identified by" mean in this context?

It therefore seems to me worth exploring the position that most good and ill fortune has as its subject a person identified by his history and his possibilities, rather than merely by his categorical state of the moment  -- and that while this subject can be exactly located in a sequence of places and times, the same is not necessarily true of the goods and ills that befall him.
-- From Nagel, Thomas. "Death." In Mortal Questions. New York: Cambridge University Press, 1979. pp. 1-10

A:
I think the sentence basically means that we need to consider the man's history to judge if something is good or ill fortune to him.

I agree with you on this. This seems to be the meaning of the sentence, especially considering the example given in the paragraph that follows your quote.

I also think the relevant part of it can be shortened as "good or ill fortune has a person identified by...". If I'm right, then what does "have someone identified by" mean in this context?

I disagree. It would break the meaning of the sentence. The broken sentence could be read two ways.
In English, the construction "to have something/someone + past participle + by" is often used in sentences such as this:

John has his car cleaned by professionals.   (okay)
  Ill fortune has a person identified by his history. (what? O_o)

This would be hard to apply to your example sentence. Ill fortune cannot command a man's history to identify this man. "History? It's ill fortune calling. I need you to identify one person for me."
The second way to read it would be similar to reading this sentence:

A poet has a cat (which is) identified by its black tail. (okay)
  Ill fortune has a person (who is) identified by his history. (what? O_o)

See, "good or ill fortune" cannot have a person in this way.
The real meaning of

It therefore seems to me worth exploring the position that most good and ill fortune has as its subject a person (who is) identified by his history and his possibilities

is that the subject experiencing some event is a person whose characteristics include all the circumstances of his life up until this moment. This person is "the subject of ill or good fortune". This person is idendified ("described") by his history and his possibilities.


text:
Q: Insert variable to array using .push() based on outcome of conditional statement I have a script that includes a for-loop that generates the numbers 0-9. The script also includes a function that checks if the numbers generated by the for-loop are divisible by 3 or 5. If they are divisible (e.g. 9 is divisible by 3), the if/else-statement returns true, and if they are not divisible, the conditional-statement returns false.
What I want to achieve is that, when the conditional statement returns true, the number should be added to an empty array.
The desired result would in this case be:
var myArray = [0, 3, 5, 6, 9];

This is my current code:
var isDivisibleArray = [];

for(var i = 0; i < 10; i++) {
    isMultiple(i);
}

function isMultiple() {

    var isMultipleOf3 = i % 3;
    var isMultipleOf5 = i % 5;

    if(isMultipleOf3 === 0 || isMultipleOf5 === 0) {
        return true;
    }

    else {
        return false;
    }

}

isMultiple();

I am using the modulus operator to find out if a number is divisible with 3 or 5, since if x % 3 = 0, x is divisible with 3, as an example.
I have done some experimenting as well. If I do this is the for-loop, I can manage to print the outcome using an alert:
for(var i = 0; i < 10; i++) {
    alert(isMultiple(i));
}

The outcome is T, F, F, T, F, T, T, F, F, T.
I have also tried this approach within the conditional statement:
if(isMultipleOf3 === 0 || isMultipleOf5 === 0) {
    isDivisibleArray.push(i);
}

This has not succeeded. All help would be much appreciated!

A: This should work:
var isDivisibleArray = [];

for(var i = 0; i < 10; i++) {
    if(isMultiple(i)) {
      isDivisibleArray.push(i);
    }
}

function isMultiple(i) {
    return i % 5 === 0 || i % 3 === 0
}

A: There is no need for a separate function.  Furthermore the following:
if(isMultipleOf3 === 0 || isMultipleOf5 === 0) {
    return true;
}

else {
    return false;
}

Can simply be written:
return isMultipleOf3 === 0 || isMultipleOf5 === 0;

The entire solution is as simple as follows:
var isDivisibleArray = [];

for(var i = 0; i < 10; i++) {
    if (i%3 === 0 || i%5 === 0) isDivisibleArray.push(i);
}

console.log(isDivisibleArray); //[ 0, 3, 5, 6, 9 ]

A: The error is that you aren't actually pushing to the array, only calling the function to check - but then you ignore the result.
You could make this code shorter and reusable by putting it inside a function that you can call with different parameters

function createArray(min = 0, max = 9, divisibleBy = [3, 5]) {
  return [...Array(max + 1).keys()]
    .filter(e => e >= min && divisibleBy.some(i => e % i === 0))
}

console.log(createArray());
// same as createArray(0, 9, [3, 5])

A:     let isDivisibleArray = [];

for(var i = 0; i < 10; i++) {
  if(isMultiple(i)=== true){
  isDivisibleArray.push(i)
}
}

function isMultiple(i) {

    var isMultipleOf3 = i % 3;
    var isMultipleOf5 = i % 5;

    if(isMultipleOf3 === 0 || isMultipleOf5 === 0) {

      return true;
    }

    else {
        return false;
    }

}

try this


text:
Q: apache server is confusing with HTTPService responses This is a very weird problem.
I have an apache server on solaris with php.
I wrote two php scripts that return values.
Sometimes, when I run the php scripts urls on the same time, the apache server returns the result of one php script to the other php page.
I tried to minimize the problem by write two php script:

*

*hello.php - print hello

*world.php - print world

sometimes when i run them on the same time by url, the hello.php return world.
when i'm using html pages it's working just fine so i think the problem is in the php installed on the server.
I'm a flex developer and I thought that the problem is in my flex client application but after I just run the php scripts directly, I see that the problem is in the server itself.
somebody know this problem?
thank you very much.

A: I am perhaps not answering your question but what if you instead of making your scripts return hello in one and world in the other instead output something a bit less static like the date and time.
script1.php
echo "Script1:".date("Y-m-d H:i:s")."
";

script2.php
echo "Script2:".date("Y-m-d H:i:s")."
";

That way you will know if this is caused by some caching.


text:
Q: Finding the nth business day of the month in Groovy Does anyone know the best way to calculate the nth business day of the month in Groovy?
i.e. the 7th business day in April (4), in 2011, would be 11th April.

A: I wrote a quick DSL for working with days (the linked example shows working out the UK holidays)
Using that, to find (for example) the 5th weekday in September this year (2011), you can do:
// 5th weekday in September
println new DateDSL().with {
  every.weekday.in.september( 2011 )
}[ 4 ]

Which prints
Wed Sep 07 00:00:00 UTC 2011

Using your example, you would do:
// 7th Weekday in April
println new DateDSL().with {
  every.weekday.in.april( 2011 )
}[ 6 ]

which prints (as you wanted)
Mon Apr 11 00:00:00 UTC 2011

As you probably don't have the month by name but by an integer, you could wrap the call in a function:
// n and month starts from 1 (for first day/month)
Date nthWeekdayInMonth( int n, int month, int year ) {
  new DateDSL().with {
    every.weekday.in."${months[month-1]}"( year )
  }[ n - 1 ]
}

println nthWeekdayInMonth( 7, 4, 2011 )

If you don't want t use that (and it is probably over-comlpex for this specific issue), you're back to using a java Calendar and rolling the date (as it does inside the workings of the dsl)

Edit
A less convoluted method might be to create a class which iterates over weekdays like so:
class WeekdayIterator {
  private static GOOD_DAYS = [Calendar.MONDAY..Calendar.FRIDAY].flatten()
  private Calendar c = Calendar.instance
  private Date nxt
  private int month, year

  WeekdayIterator( int month, int year ) {
    c.set( year, month, 1 )
    this.month = month
    nxt = nextWeekday()
  }
  private Date nextWeekday() {
    while( c.get( Calendar.MONTH ) == month ) {
      if( c.get( Calendar.DAY_OF_WEEK ) in GOOD_DAYS ) {
        Date ret = c.time.clearTime()
        c.add( Calendar.DATE, 1 )
        return ret
      }
      c.add( Calendar.DATE, 1 )
    }
    null
  }
  Iterator iterator() {
    [ hasNext:{ nxt != null }, next:{ Date ret = nxt ; nxt = delegate.nextWeekday() ; ret } ] as Iterator
  }
}

This can then be called like this to get the 7th business day by either:
def weekdays = new WeekdayIterator( Calendar.APRIL, 2011 )
println weekdays.collect { it }[ 6 ]

or
def weekdays = new WeekdayIterator( Calendar.APRIL, 2011 )
println weekdays.iterator()[ 6 ]


text:
Q: RxPy - Why are emissions interleaved with merging operators? So I'm learning RxPy after doing RxJava and RxKotlin for two years. One thing I'm noticing is that certain operators cause crazy interleaving that does not happen in RxJava.
For example, flat_map() will cause emissions to interleave out of order for a simple Observable source.
items = Observable.from_( ("Alpha","Beta","Gamma","Delta","Epsilon"))

items.flat_map(lambda s: Observable.from_(list(s))).subscribe(print)

OUTPUT:
A
l
B
p
e
G
h
t
a
D
a
a
m
e
E
m
l
p
a
t
s
a
i
l
o
n

However, with RxJava or RxKotlin, everything stays sequential and in order.
fun main(args: Array<String>) {
    Observable.just("Alpha","Beta","Gamma","Delta","Epsilon")
        .flatMap {
            Observable.from(it.toCharArray().asIterable())
        }.subscribe(::println)
}

OUTPUT:
A
l
p
h
a
B
e
t
a
G
a
m
m
a
D
e
l
t
a
E
p
s
i
l
o
n

I confirmed that everything is running on the MainThread and there is no weird asynchronous scheduling going on (I think).
Why does RxPy behave this way? I notice that this happens almost with any operator that deals with multiple Observable sources merging together. What exactly is the default Scheduler doing?
Also, why is there no concat_map() in RxPy? I'm getting the impression this is somehow not possible with how the scheduling works...

A: As has already been noted,  flatMap does not guarantee order. RxPy doesn't implement concat_map as a distinct operator but you can get the same effect using the map and concat_all operators
Observable.from_( ("Alpha","Beta","Gamma","Delta","Epsilon"))\
          .map(lambda s: Observable.from_(list(s)))\
          .concat_all()\
          .subscribe(print)


text:
Q: where can I find SSL certificates on Mac OSX I need an access to .k12 or .pem files for all https websites I am visiting on Mac OSx machine. Can anyone help me know the path where these files can be found.
Also, need to know a way to decrypt some packets using the key.

A: There are a couple of ways to get a certificate file in OSX.  One way is to export the certificates from Keychain Access.  Select Certificates in the Category (lower left) panel, choose Select All from the Edit menu (or hit ⌘A), and then choose Export Items... from the File menu (or hit ⇧⌘E).  You can export your certificates as a .p12 file or a .cer file.  The problem with this approach is you have to perform these steps periodically to keep your file in sync with the latest updates from Apple.
Another way is to install OpenSSL and use the cert.pem file that comes with it.  Similarly, you'll have to keep OpenSSL up to date.

A: You would simply access the tool named "Keychain Access" in the Utilities folder of your Applications directory.
Once there, you can filter each keychain to only show certificates.
As for decrypting packets using a given key, there are plenty functions doing that within the Security framework, but this question would require clarification (Language requirement etc).

A: I was looking for this too. I couldn't find the files anywhere so I thought how about exporting them.
From the Keychain Access:
On left pane, click on the KEYS. On right pane, CTRL-Click on the desired certificate.
The Public key should be exported as a PEM file.
The Private Key should be exported as a P12 file.
The Certificate should be exported as a CRT file.
The Private key export option will as for a passphrase and then the user's keychain password. Upon import you will be asked for this passphrase.
NOTE: The private key, contains the public key.

A: If you were to run openssl x509 -req -days 365 -in my-csr.pem -signkey my-key.pem -out my-cert.pem, it saves my-key.pem and my-cert.pem in the same directory where you ran the command. In my case, I ran the command at the root so it was saved there. Hope this helps someone. I spent a lot of time searching, when it was right in front of my face.


text:
Q: How to add variables to a template I am using a query argument detail to check if a custom template should be loaded. This works fine, but I also need to add some variables that can be accessed from within the template. Here I am using add_action('template_include' array($this, 'templateInclude'):
public function templateInclude($template)
{
    if (get_query_var('detail', false) !== false) {
        // Check theme directory first.
        $newTemplate = locate_template(array('detail.php'));
        if ($newTemplate != '')
            return $newTemplate;

        // Check plugin directory next.
        $newTemplate = plugin_dir_path(__FILE__) . 'templates/detail.php';
        if (file_exists($newTemplate)) {
            return $newTemplate;
        }
    }

    // Return default template.
    return $template;
}

The above works, but of course I am not able to actually set any variables for the template.
I tried using set_query_var() to set a variable that could be accessed using get_query_var(), but this does not really seem to be the best solution.
I also tried using add_action('template_redirect' array($this, 'templateRedirect'), which works but this neither seems to be a really good solution:
public function templateRedirect() {
    if (get_query_var('detail')) {
        $detailId = get_query_var('detail', null);
        // Set a variable 'data' that can be used inside the template
        $data = get_detail($detailId);
        include plugin_dir_path(__FILE__) . 'templates/detail.php';
        exit;
    }
}

Would be really great if someone has some nice way of adding custom variables for a specific template.


text:
Q: Discord.js V13 | Sticky Message I want to create a sticky message for my server to keep everything at the bottom. I have tried a lot of different things but none of them worked.
client.on("messageCreate", async message => {
    if(message.channel === "") { // If someone sends a message in this channel, it gets triggered
    let botcmd = new Discord.MessageEmbed()
        .setTitle("Bot Commands")
        .setDescription("Description stuff ")

    // I want the bot to delete the previous message before sending the embed to avoid it deleting the new embed

    message.channel.send( {embeds: [botcmd] }) } })
})

How I want it to work:
Me : sends message
Bot : sends embed
Me: : sends another message
Bot : deletes old embed and sends new embed

A: This not an entirely clean solution, but I have tested this and it should put you on the right direction. I used message.channel.messages.fetch() method to fetch all the messages and used .find() to filter the messages based on author and channel id.
You can even set up a whitelist in an array to hold all the channels that have sticky messages enabled.
Example of how I did it:
const stickyChannels = ["1031928905516470322"];
bot.on("messageCreate", async (message) => {
    if(message.author.bot) return;
    if(stickyChannels.includes(message.channel.id)) {
        const fetchedMessages = await message.channel.messages.fetch();
        const stickyMessage = fetchedMessages.find(m => m.author.id === bot.user.id && stickyChannels.includes(m.channel.id));

        if(stickyMessage) {
            stickyMessage.delete().then(() => {
                message.channel.send("__ Sticky message__");

            }).catch(() => {});
        } else {
            // Force send a new message.
            message.channel.send("__ Sticky message__");
        }
    }
});

This is a general idea of how you can start using sticky messages in your Discord server. Note that you have to adjust this snippet to work in your own environment.


text:
Q: Keyframing in 3DS MAX 2014 SDK c++ I want to ask you guys to help me with creating keyframes in Max SDK C++.
What I've done:

*

*Created a Controller Plugin

*Inside the getValue function I've done my translations via code.

*I also wrote the setValue function.

Which I think manages keyframes and stores the controllers position in a given time in a given keyframe. In this way I achieved to be able to set keys manually, but I really would like, to work with the Auto Key turned on in Max.
On the other hand, I can't see the freshly added keys values. So please help me, how could I add keyframes?
Many Thanks:
Banderas
void maxProject3::GetValue(TimeValue t, void *ptr, Interval &valid, GetSetMethod method)
{

Point3 p3OurAbsValue(0, 0, 0);
tomb[0]=0;

//These positions stores my data they are globals
XPosition += (accX);
YPosition += (accY);
ZPosition += (accZ);

p3OurAbsValue.x = XPosition;
p3OurAbsValue.y = YPosition;
p3OurAbsValue.z = ZPosition;

   valid.Set(t,t+1); //This answer is only valid at the calling time.

   MatrixCtrl->GetValue(t, &p3OurAbsValue.y, valid, CTRL_RELATIVE);

   if (method == CTRL_ABSOLUTE)
   {

          Point3* p3InVal = (Point3*)ptr;
          *p3InVal = p3OurAbsValue;

   }
   else // CTRL_RELATIVE
   {
          //We do our translations on a Matrix
          Matrix3* m3InVal = (Matrix3*)ptr;
          //m3InVal->PreTranslate(p3OurAbsValue);
          m3InVal->PreRotateX(rotX);
          m3InVal->PreRotateY(rotY);
          m3InVal->PreRotateZ(rotZ);
   }
}

int maxProject3::NumSubs() {
return 1;
}

Animatable* maxProject3::SubAnim(int n) {
return MatrixCtrl;
}

void maxProject3::SetValue(TimeValue t, void *ptr, int commit, GetSetMethod method)
{
    Matrix3* m3InVal = (Matrix3*)ptr;
    MatrixCtrl->AddNewKey(t, ADDKEY_SELECT);
    MatrixCtrl->SetValue(t, &m3InVal, commit, CTRL_RELATIVE);
}

A: To turn on the Auto key mode try using AnimateOn() before your transformation. Also add AnimateOff() to turn off the auto key mode in the end.
I did it in one of my project to create material id animation using auto key mode.
/** Auto key on*/
AnimateOn();

/** Creating material id animation */
for(int mtl_id = 1; mtl_id <= num_sub_mtl; ++mtl_id, time += time_step)
{
    mtl_modifier->GetParamBlock()->SetValue(MATMOD_MATID,time,mtl_id);
}

/** Auto key off*/
AnimateOff();

Also as a suggestion, use the max script listener to know whats happening when the animation is created using 3ds Max GUI. This will help you to recreate the animation using Max SDK.


text:
Q: Add remote to master repo and use the remote in all future clones My problem is, I've added a remote of live to a current repo.
$ git remote add live ssh://user@myserver:port/directory

I've then pushed this repo to bitbucket and then cloned on another machine, however when clone the repo it doesn't have the remote settings that I put in the initial repository.
I have to add it every time, is there a way to add it so that it works across the board - or works within each repo that I add it to? Or am I doing something wrong when I add the live remote?
Thanks

A: No you are not doing anything wrong.
The ideal way to run a sequence of steps after a particular type of action would be to use a git-hook for that action. However, that won't be possible here - there is no git-clone hook in git which could do that for you -- i.e.,automatically add a remote whenever a new clone is made for you.
Check out answers on git-clone and post-checkout hook and is there a clone hook.
Basically, If you were cloning the same repo on the same machine again and again, then you could have used --template flag for the hook; However, since you are checking out the repo on different machines everytime, you will need to copy the template hook on each new machine, which is bad.
It is better that you run the command git remote add live ssh://user@myserver:port/directory everytime you clone the repository, from within the cloned repository.
You can then run git remote -v to check all the remotes available in the repository.


text:
Q: can´t understand fetchRequest.predicate I´ve a quite "simple" predicate for a NSFetchRequest:
guard let kategorie = self.fetchedResultsController.objectAtIndexPath(indexPath) as? Kategorien else {
            return
}
let fetchRequest = NSFetchRequest(entityName: "Details")
fetchRequest.predicate = NSPredicate(format: "kategorie == %i", kategorie.katid!)
do {
    let results = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [Details]
...

The content of the sqllite-"table" is

the content of the variables are

So from
fetchRequest.predicate = NSPredicate(format: "kategorie == %i", kategorie.katid!)

i get the Predicate

kategorie == 18

while

kategorie.katid is 1

I can´t understand it :-(
Any help???

A: That's really strange, but you can just do:
NSPredicate(format: "kategorie = \(kategorie.katid!)")

And then you don't need to worry about whether you need a %i, or a %ld, or a %@, etc...

A: katid is an (optional) NSNumber, and what happens in your case
is that the (lower 32-bit of the) address of the object is taken as an integer.
The correct format
specifier is %@ (for instances of NSObject subclasses):
 NSPredicate(format: "kategorie == %@", kategorie.katid!)

Alternatively, convert the object to an integer:
NSPredicate(format: "kategorie == %d", kategorie.katid!.intValue)

Of course, forced unwrapping should be avoided, e.g.
NSPredicate(format: "kategorie == %d", kategorie.katid?.intValue ?? 0)

Using string interpolation in the format string (as suggested by
@Gargoyle) is another solution in this special case of numbers,
but not generally: If you interpolate a string then any percent
character will be interpreted as a format specifier and that leads
to unexpected output or crashes. Also single or double quotes will
lead to problems because these have a special meaning in predicate
format strings.


text:
Q: Count number of times two elements in array are less than or equal to a sum value - Javascript I have this JS function that finds the number of times two elements equal to a sum value. I am trying to modify this so that the condition isn't only when the two elements are equal to sum, but when it's less than the sum value as well.
var array = [-10, -8, -1, 0, 1, 6, 10];
var sum = 16;

function findLessThanOrEqualSum(array, sum){
  var count = 0;
  var map = {};
  for(var i = 0; i<array.length; i++){
    var temp = sum - array[i]; //This right here only accounts for when two elements = sum

    if(temp >= 0 && map[temp]){
      console.log(sum + " " + array[i] + " " + temp);
      count++;
    }
    map[array[i]] = true;
  }
  console.log(count);
}

findLessThanOrEqualSum(array, sum);

How would I change this condition var temp = sum - array[i]; so that it accounts for the instances temp is <= sum - array[i];?
I've tried assigned a second temp variable that will hold all the values for when temp <= sum - array[i]; but I was not successful. Any help would be appreciated.

A: You're doing it in a very convoluted way. Just use nested loops that add two array elements, and test if they're less than the sum.

var array = [-10, -8, -1, 0, 1, 6, 10, 11, 8, 9];
var sum = 16;

function findLessThanOrEqualSum(array, sum) {
  var count = 0;
  for (var i = 0; i < array.length - 1; i++) {
    for (var j = i + 1; j < array.length; j++) {
      if (array[i] + array[j] < sum) {
        console.log(sum + " " + array[i] + " " + array[j]);
        count++;
      }
    }
  }
  console.log(count);
}

findLessThanOrEqualSum(array, sum);

The way you're doing it works for the equal condition because you can look for a specific key in map. But there's no specific thing to look for when you have an comparison condition.


text:
Q: Передача флагов форматирования в функцию Как передать в функцию флаг форматирования std::left, std::right или std::internal?

A: Вообще-то можно передавать их и как целые числа (точнее, перечисление) - просто нужно передавать не std::left, а ios_base::left, и использовать не в конструкции <<, а как параметр setf(). Обычно почему-то этот метод оказывается незаслуженно забыт.
Подробнее - см. тут.

A: Например, таким образом
#include <iostream>
#include <iomanip>
#include <string>

void f( const std::string &s, std::ios_base & flag(std::ios_base & ) )
{
    std::cout << std::setw( 20 ) << flag << s << std::endl;
}

int main()
{
    f( "Hello", std::left );
    f( "Hello", std::right );

    return 0;
}

Вывод программы на консоль:
Hello
               Hello

Аналогичным образом можно использовать std::internal
Все эти флаги, то есть функции-манипуляторы потоком, имеют одинаковое объявление
std::ios_base & flag(std::ios_base & ):

A: Если уж задаться целью передавать именно манипуляторы (вместо более гибкого и разумного варианта с флагами, предложенного @Harry), то вместо того, чтобы заниматься филигранным выписыванием конкретного типа этих манипуляторов лучше тем или иным образом полностью от него абстрагироваться
static_assert(
  std::is_same<decltype(std::left), decltype(std::right)>::value &&
  std::is_same<decltype(std::left), decltype(std::internal)>::value, "");

void foo(const std::string &str, decltype(std::left) alignment)
{
  std::cout << std::setw(42) << alignment << str << std::endl;
}


text:
Q: What is the reason behind this Eclipse behavior due to changing an Environment Variable? I have two versions of Eclipse that I use (Indigo for C++ and Helios for Java). I've used both for years without problems. Last week I needed to view Java Bytecode, so in my Environment Variables I added "C:\Program Files\Java\jdk1.6.0_26\bin;" to the Path variable (this let me use javap 'class' -c to view bytecode in a command prompt).
I continued to use Helios just fine. Today I tried booting up Indigo to work on some C++ code, but I got the "Failed to load JNI shared library etc." error for it, causing it to force close. Eventually I tried removing that path I placed in environment variables, and Indigo boots up correctly again.
Any idea why this happened? I don't fully understand paths, but I don't see why adding the path I did would cause my other Eclipse to break. I don't really need javap anymore so I removed the path, but I'm still curious as to why this happened.
Thanks for any insight!

A: With the change to the path Eclipse was probably trying to load 32 bit Eclipse with a 64 bit Java (or the other way round), they both have to be 32 bit or 64 bit.


text:
Q: Outputting raw bytes from a file, first byte is corrupted So I have written a small program that reads the contents of a file into a char array(because fstream seems to only support char pointers). What I want to do is send the raw bytes to the console. AFAIK char is an 8 bit data type so it should not be too hard.
However if I just print members of the array, I get the characters corresponding to the ASCII values, so I am using a static cast. This works fine, except the first byte does not seem to get cast properly.
I am using a PNG file as the test.bin file. PNG files always begin with the byte sequence of 137,80,78,71,13,10,26,10. However the fist byte is printed incorrectly. I have a feeling it has to do something with the value being over 127. However, I cannot change the read buffer data type to anything else (like unsigned char, or unsigned short int), because foo.read() from fstream only supports char destination buffers.
How do I get fstream to read the raw bytes into a usable unsigned type?
My code:
#include <iostream>
#include <fstream>
#include <sys/stat.h>

#define filename "test.bin"

void pause(){
    std::string dummy;
    std::cout << "Press enter to continue...";
    std::getline(std::cin, dummy);
}

int main(int argc, char** argv) {
    using std::cout;
    using std::endl;
    using std::cin;
    // opening file
    std::ifstream fin(filename, std::ios::in | std::ios::binary);
    if (!fin.is_open()) {
       cout << "error: open file for input failed!" << endl;
       pause();
       abort();
    }
    //getting the size of the file
    struct stat statresults;
    if (stat(filename, &statresults) == 0){
        cout<<"File size:"<<statresults.st_size<<endl;
    }
    else{
        cout<<"Error determining file size."<<endl;
        pause();
        abort();
    }
    //setting up read buffer and reading the entire file into the buffer
    char* rBuffer = new char[statresults.st_size];
    fin.read(rBuffer, statresults.st_size);

    //print the first 8 bytes
    int i=0;
    for(i;i<8;i++) {
        cout<<static_cast<unsigned short>(rBuffer[i])<<";";
    }

    pause();
    fin.clear();
    fin.close();
    delete [] rBuffer;
    pause();
    return 0;
}

A: -119 signed is 137 unsigned (both are 1000 1001 in binary).
This gets sign-extended into the short 1111 1111 1000 1001, which is 65,417 unsigned.
I assume this is the value you're seeing.
To read into an unsigned buffer:
unsigned char* rBuffer = new unsigned char[statresults.st_size];
fin.read(reinterpret_cast<char*>(rBuffer), statresults.st_size);

A: How about trying something other than fin.read()?
Instead of:
char* rBuffer = new char[statresults.st_size];
fin.read(rBuffer, statresults.st_size);

You could use:
unsigned char* rBuffer = new unsigned char[statresults.st_size];
for(int i = 0; i < statresults.st_size; i++)
{
    fin.get(rBuffer[i]);
}

A: You likely want to be using unsigned char as your "byte". You could try something like this:
using byte = unsigned char;

...

byte* buffer = new byte[statresults.st_size];
fin.read( reinterpret_cast<char*>( buffer ), statresults.st_size );

...

delete[] buffer;


text:
Q: perl: input multiple files as array I have 5 files in different directory. I am extracting the data's from all files and make it as new file.
Note: input each file as an array and extract the data by using for loop for each n every files. I want to make it as single for loop to take the files and process the rest
For file1 am using
foreach (@file)
{
    my @temp = split(/\t/, trim($_));
    push(@output, $temp[0] . "\t" . $temp[1] . "\n");
}

foreach(uniq(@output))
{
    print $OUTPUTFILE $_;
}

I am doing this for five times to process five file. Can anyone help me on how to make it simple

A: Just wrap it in an outer loop, iterating over all five files:
for my $file ( @five_files ) {

    open my $fh, '<', $file or die "Unable to open $file: $!";
    my @file = <$fh>;

    foreach (@file) {
        my @temp = split(/\t/, trim($_));
        push(@output, $temp[0] . "\t" . $temp[1] . "\n");
    }

    foreach(uniq(@output)) {
        print $OUTPUTFILE $_;
    }
}

Since you're interested in just the first two elements of @temp, the foreach @file loop can be simplified:
my @temp = split /\t/, trim($_), 2;
push @output, @temp, "\n" ;

A: What if you simplify things by flattening out your @file array with join.
Then you can just split it up and deal with the list.
Eg:
!/usr/bin/perl

my @file = ("file1\tfile3 ","file1\tfile3\tfile3 ","file2");  # Some test data.

my $in = join "\t", @file;  # Make one string.
my @temp = split(" ", $in); # Split it on whitespace.

# Did it work?
foreach(@temp)
{
    print  "($_)\n";  # use () to see if we have any white spaces.
}

Might be a problem if you have spaces in your filenames though!


text:
Q: Resident Memory increases with Lucene Mmap Currently i'm Mmap 1.5 GB of lucene index, i noticed virtual memory size gone up from 14GB to 23GB(that's fine this size includes the size of swapout pages in hard-drive). But i'm witnessing increase in RSS(resident-size) size from 8GB to 12GB if we use MMAP. Any suggestion to reduce RSS usage without compensating performance.
Regards,
Raghavan

A: Mmap allows Lucene to work directly on page cache ( by loading the Lucene index on page cache and avoiding copying the page cache to bytes on heap so this should not lead to increase in resident memory. For an excellent and must read check here) .You might want to  take a heap dump to ascertain if the increase in resident size is not due to any heap objects.


text:
Q: why $ \mu \left( \bigcap_{n=N}^{\infty} (G_n \setminus C_n) \right)= \sum_{n =N}^{\infty} {\mu(G_n \setminus C_n)}?$ In theorem $2.17$ Rudin say that  If $E\in\frak M$, there are sets $A$ and $B$ such that $A$ is an $F_\sigma, B$ is a $G_\delta$, $A\subset E\subset B$, and $\mu(B-A)=0.$
I found  the  proof here
My confusion:In proof it is written
\begin{align*} \mu(V  \setminus U) &\leq \limsup_{N \to \infty} \mu \left( \bigcap_{n=N}^{\infty} (G_n \setminus C_n) \right)\\ &\leq \limsup_{N \to \infty} \sum_{n =N}^{\infty} \underbrace{\mu(G_n \setminus C_n)}_{\leq 2^{-n}} = 0. \end{align*}
why $\limsup_{N \to \infty} \mu \left( \bigcap_{n=N}^{\infty} (G_n \setminus C_n) \right)= \limsup_{N \to \infty} \sum_{n =N}^{\infty} {\mu(G_n \setminus C_n)}?$
I think if we replace union instead of intersection then
$\limsup_{N \to \infty} \mu \left( \bigcup_{n=N}^{\infty} (G_n \setminus C_n) \right)= \limsup_{N \to \infty} \sum_{n =N}^{\infty} {\mu(G_n \setminus C_n)}$

A: No, it is
$$ \mu \left( \bigcap_{n=N}^{\infty} (G_n \setminus C_n) \right) \leq \sum_{n =N}^{\infty} {\mu(G_n \setminus C_n)} $$
It is "less than", not "equal to".
In fact, the sum is not even needed. The fact that
$$ \mu \left( \bigcap_{n=N}^{\infty} (G_n \setminus C_n) \right) \leq \mu(G_N \setminus C_N) \leq \frac{1}{2^N} $$
is enough to conclude the result.


text:
Q: How to detect whether the two graphs are topologically equivalent From this link I construct a regular graph .How to construct a k-regular graph?
10-4 regular graph:
here is one m choose
def get_2mth_v(self,v:Vertex,m:int) -> List[Vertex]:
    """ m neibor on eachside"""
    answer = []

    if m == 0 :
        return answer

    v_index = self.vindex[v]
    vnum = len(self.vindex)

    for i in range(1,m+1) :
        answer.append(self.indexv[ (v_index-i) % vnum ])
        answer.append(self.indexv[ (v_index+i) % vnum ])

    return answer

graph1

the other one is
   def get_2mth_v(self,v:Vertex,m:int) -> List[Vertex]:
        """ m neibor on eachside"""
        answer = []

        if m == 0 :
            return answer

        v_index = self.vindex[v]
        vnum = len(self.vindex)

        for i in range(1,m+1) :
            answer.append(self.indexv[ (v_index-i*2) % vnum ])
            answer.append(self.indexv[ (v_index+i*2) % vnum ])

graph2

So are these two graphs the same in some way? If they are the same, why?

update
as yes or not connectivity is clear to detect wheather it is equal
may be this method need see more .
def get_2mth_v_stepii(self,v:Vertex,m:int) -> List[Vertex]:
    """ m neibor on eachside"""
    answer = []

    if m == 0 :
        return answer

    v_index = self.vindex[v]
    vnum = len(self.vindex)

    for i in range(1,m+1) :
        answer.append(self.indexv[ (v_index-i*i) % vnum ])
        answer.append(self.indexv[ (v_index+i*i) % vnum ])

    return answer

graph3

So graph1 and graph3 both is connected .

A: The second graph is not connected (the first is) so is not topologically equivalent to the first graph in most senses of 'topologically equivalent'. They're not isomorphic as graphs, homeomorphic, homotopy equivalent, shape equivalent, etc.

A: Two graphs $G_1, G_2$ are "the same" (more formally, isomorphic) when there's a bijection $\phi$ between their vertex sets such that $\phi(x)\phi(v)$ is an edge in $G_2$ if and only if $xy$ is an edge in $G_1$.
Do you need help applying this criterion to your example graphs or can you take it from there? (As Daniel Rust points out, one graph is not connected, and the other is, so there can't be such a bijection, but if you can't immediately see that I can try to help.)


text:
Q: What are the steps to instantiate the chrome browser in Selenium Webdriver? I want the detailed steps. Like from scratch and in serial order.
I know that we want to install the chromeDriver then:
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Downloads\\chromedriver_win32\\chromedriver.exe");

WebDriver driver = new ChromeDriver();

A: @Indrajit
that all for it any way refer the following
Step1: Click Here to download chromedriver.exe
Step2: add the following code to your java file
System.setProperty("webdriver.chrome.driver","D:/your/path/to/Driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");

Beside this if you are looking for any other query, please be specific on it.

A: The two code lines you mentioned, are the basic steps are required to instantiate the chrome driver. If you have any specific query then you should mention that.


text:
Q: How to display an organized category using groupby in an array angular 7? I want to show tiles organised by their category.
in the categories I want to show Category_title and Category_intro at the top
and show the the title and description below.
App.component.html:

This is my html

{{tool[0]}}

{{val.title}}

{{val.desc}}

This is my ts component
App.component.ts
import { Component } from '@angular/core';
@Component({
     selector: 'my-app',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
 })
export class AppComponent {
  tools = [
  {
     id: 0,
     title: 'Title 0',
     desc: 'Description',
     categories: [
       {
          "Category_title": "My Category Title 1",
          "Category_intro": "My Category intro 1",
       },
       {
          "Category_title": "My Category Title 2",
          "Category_intro": "My Category intro 2",
       }
         ],
  },
  {
     id: 1,
     title: 'Title 1',
     desc:'Description',
     categories: [
       {
          "Category_title": "My Category Title",
          "Category_intro": "My Category intro
       },
       {
          "Category_title": "My Category Title 2",
          "Category_intro": "My Category intro 2",
       }
         ],
   },
   {
      id: 2,title: 'Title 2',
      desc: 'Description',
      cat: 'Category 2',
      categories: [
        {
           "Category_title": "My Category Title",
           "Category_intro": "My Category intro 1",
        },
        {
           "Category_title": "My Category Title 2",
           "Category_intro": "My Category intro 2",
        }
          ],
    },
    {
       id: 3,title: 'Title 3',
       desc: 'Description',
       categories: [
         {
            "Category_title": "My Category Title",
            "Category_intro": "My Category intro 1",
         },
         {
             "Category_title": "My Category Title 2",
             "Category_intro": "My Category intro 2",
         }
           ],
      },
      {
         id: 4,
         title: 'Title 4',
         desc: 'Description',
         categories: [
           {
              "Category_title": "My Category Title",
              "Category_intro": "My Category intro 1",
           },
           {
              "Category_title": "My Category Title 2",
              "Category_intro": "My Category intro 2",
           }
   ],
 }]

}
this is the view:
This is the error view
I want this to display: