text:
Q: How to find the PID of a C code during compilation time? How to find the PID of a C code which is being executed So that I can find its stack and heap memory usage? And also can anyone ellaborate me about the sections in the map file?

A: PID exists only for running process. That means your c code should be running. In your c code can use getpid(); to get current process ID. This should be call from your c code which you need pid. You can print the pid and can look in to /proc entries of that pid. Or you can read /proc entries from your program after gettign PID. (OR) When yoou run your c code, Use ps -ef command to print details of all running processes. In that you'll find a field called pid. you can identify your executable pid from its name.

A: Why not the getpid() method defined in unistd.h?
#include <unistd.h>
int main(){
    int pid = getpid();
    int parentsPID = getppid();
    return 0;
}

A: A C code is only a bunch of textual source files.
It can be built, i.e. compiled then linked (and perhaps installed), as an executable program (often in ELF on Linux).
That executable may be executed by the execve(2) syscall from inside some fork-ed process. Each process has its pid (a unique positive number of type pid_t). On Linux, you may have several different processes running the same executable (in particular, you usually have several running /bin/bash shells, e.g. one for each terminal).
From inside a process, use the getpid(2) syscall to get its pid. Read also more about proc(5) and fork(2). Use also the top(1) and ps(1) commands (in particular, try ps auxw)
The /proc/$PID/maps (which, from inside the application, you can access as /proc/self/maps) gives the address space in virtual memory of the process. That space has been set-up by execve and changed by various syscalls (mostly mmap(2) and related syscalls, which also get called by the dynamic loader ld-linux(8), by malloc(3), etc... etc...). Be aware of ASLR...
Your question shows that you probably should take several hours to read Advanced Linux Programming to understand more the relevant concepts and the terminology.
Stack and heap don't exist inside the C code, they makes sense only inside a process! If you want to measure them from inside your application, use various files from /proc/self/ notably read sequentially /proc/self/maps, /proc/self/status, /proc/self/stat, /proc/self/statm etc... From outside the application, use /proc/$PID/ (e.g. /proc/1234/ for the process of pid 1234), and also use the pmap(1) command (which queries /proc/). See also this.
BTW, one cannot in general get the lowest upper and highest lower bound[s] of stack and heap usage by static examination and analysis of the C source code (this is an intractable or an undecidable problem). See Rice's theorem...

PS. The ps, top, pmap (etc ....) commands should be run (and the /proc filesystem should be accessed) on the Linux system running your executable built from your C code. If you are using Linux/x86-64 to cross-compile for an Android/ARM or a embedded Linux/ARM board, you should have /proc/ mounted on that embedded board, and you should run (remotely, using ssh or telnet etc....) the commands on that board.


text:
Q: How to get color of a particular stack on click of a stacked bar chart in kendo UI using angularJS I want to retrieve the color of clicked portion of stack in stacked bar chart using angularjs in kendoUI.

A: Use the seriesClick event:
seriesClick: function(e) {
    alert(e.series.color);
}

DEMO
Here is a demo using Angular:
Angular DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: Postgres DB is taking up a lot of space because of pg_largeobject I have my node on Corda 3.0 configured to connect Postgres DB 9.6 on Azure. When I uploaded ~5000 LinearStates (no attachment), it seems that the DB is taking up to ~5GB.
And upon investigation, it seems there's a table pg_largeobject that gets populated for every transaction performed. And this table is linked to

*

*node_attachments

*node_checkpoints

*node_identities

*node_message_retry

*node_our_key_pairs

*node_info_party_cert
Why is the table taking such a large space? Is it normal for this behavior? Even when I switched to H2, the behavior remains? What can contribute to this large data?

A: This is a Corda bug which will be fixed with
https://github.com/corda/corda/pull/3577/commits/9efa7ac63a38b0d888da29c79cef032d84708184

A: Package your contract- and state-code in a separate jarfile conform this structure:
The contract- and state-code is used for tx-verification and therefore stored in the DB so it should be packaged in a small jar-file.


text:
Q: Android SDK DownLoad Failed I'm trying to install a platform but when I open Android Manager then I click Available Software then select the https://dl-ssl.google.com/android/repository/repository.xml repository
I get this error:
Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml
I have also tried downloading by clicking on force "http:" for all "https:" downloads on settings panel but it still doesn't help.
I'm working on Windows 7(x64).

A: Please deactivate any firewall, and any virus protection software. I tried every thing, but this is the final solution. When doing that every thing goes fine, I was able to finish my android sdk downloads.

A: Instead of using this

https://dl-ssl.google.com/android/repository/repository.xml

Use this

http://dl-ssl.google.com/android/repository/repository.xml

Also check if you are using any proxy.


text:
Q: Rails authenticity from Android API with HttpPost I'm working on an Android client API for my organization's new website. The new website is written in Rails, and authentication is done as follows: I make a POST request to the site's login URL with the credentials, and I'm returned a CSRF token and a cookie to Android's cookie manager. I then pass the CSRF token to authenticated functions.
My problem is with an UploadCSV function that I'm trying to implement. I've mimicked the request that the website's UI generates when you click the Upload CSV button, but the site is refusing my request and telling me it can't verify my CSRF token. This same token will work for other authenticated functions, and I can't for the life of me figure out why.
Here's my function that creates the request:
URI url = new URI(baseURL+"/projects/"+projectId+"/CSVUpload");
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName(HTTP.UTF_8));
entity.addPart("authenticity_token", new StringBody(authToken));
entity.addPart("csv", new FileBody(csvToUpload));
entity.addPart("utf8", new StringBody("\u2713", "text/plain", Charset.forName("UTF-8")));
httpPost.setEntity(entity);
client.execute(httpPost);

and here is the server log message:
Started POST "/projects/7/CSVUpload" for ***.**.***.** at 2013-08-13 08:38:13 -0400
Processing by DataSetsController#uploadCSV as HTML
  Parameters: {"authenticity_token"=>"OvJanht9/GZu90rcRrR3YH94M8Ukamr5OLp/qiOEZAY=", "csv"=>#<ActionDispatch::Http::UploadedFile:0x007fd6ae12a7a0 @original_filename="weird.csv", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"csv\"; filename=\"weird.csv\"\r\nContent-Type: application/octet-stream\r\n", @tempfile=#<File:/var/folders/9q/v5l53m3141d4cbrd8w07g0sm0000gn/T/RackMultipart20130813-55943-5v1kp8>>, "utf8"=>"✓", "id"=>"7"}
WARNING: Can't verify CSRF token authenticity
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
Redirected to http://***.**.**.**:3000/
Filter chain halted as :authorize rendered or redirected
Completed 302 Found in 12ms (ActiveRecord: 0.3ms)

Other functions in my API use the HTTPUrlConnection method to send their POST requests, and these authenticate fine. I want to use HttpPost to send the MultipartEntity.

A: Have you tried sending the token in the header X-CSRF-Token? I am guessing the reason some of your requests don't complain is because they use GET, which skips the verification.
If you want to bypass this for a POST as well, you can add a skip_before_filter :verify_authenticity_token, though I mention this with the caveat that it is not recommended.

A: Apparently the answer is not to use HttpPost. I changed my request to use an HttpURLConnection and it succeeded.
URL url = new URL(baseURL+"/projects/"+projectId+"/CSVUpload?authenticity_token="+URLEncoder.encode(authToken, "UTF-8"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");

MultipartEntity entity = new MultipartEntity();
entity.addPart("utf8", new StringBody("\u2713", "text/plain", Charset.forName("UTF-8")));
entity.addPart("csv", new FileBody(csvToUpload, "text/csv"));

connection.setRequestProperty("Content-Type", entity.getContentType().getValue());
OutputStream out = connection.getOutputStream();
try {
    entity.writeTo(out);
} finally {
    out.close();
}
connection.getResponseCode();

It's a little less concise, but it works.


text:
Q: How can I know the application state of an Android App to display or not a notification? I am developping an instant messaging application that uses Google Cloud Messaging. I send a notification when a user receive a message from a contact. Everything works properly. I set up the GCMBroadcastReceiver and the GCMMessageHandler. The problem is : the notification is always displaying even if the user is currently chatting with his contact. How can I know the application state in the GCMMessageHandler to not display the notification ?
Here is the GCMBroadcastReceiver :
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    // Explicitly specify that GcmMessageHandler will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(),
            GcmMessageHandler.class.getName());

    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}

}
Here is the GCMMessageHandler :
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    mes = extras.getString("message");

    if(IM_NOT_IN_THE_CHAT_ACTIVITY)
    {
        showNotification(mes);
    }

What I'm struggling to get is that flag : IM_NOT_IN_THE_CHAT_ACTIVITY.
How can I know this in the IntentService ?

A: Doing this would do the trick I guess :
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
    String activity_name = taskInfo.get(0).topActivity.getClassName();

    if(activity_name != ACTIVITY_NAME)
        showNotification(mes);


text:
Q: Batch removing leading dash in file names in Bash $ ls -l
-rw-r--r--@ 1 ywang  Users  6156 Aug 16 14:38 -STEST.20140728.151116.pgp
-rw-r--r--@ 1 ywang  Users  2756 Aug 16 14:38 -STEST.20140728.152042.pgp
-rw-r--r--@ 1 ywang  Users  3424 Aug 16 14:38 -STEST.20140729.141735.pgp
-rw-r--r--@ 1 ywang  Users  2439 Aug 16 14:38 -STEST.20140729.142515.pgp
-rw-r--r--@ 1 ywang  Users  2672 Aug 16 14:38 -STEST.20140730.125115.pgp
-rw-r--r--@ 1 ywang  Users  2391 Aug 16 14:38 -STEST.20140730.125556.pgp

Hi, I've tried multiple ways, e.g. looping through the file and do mv one by one. However, I wasn't successful as the caveat was that mv interprets the leading dash as a parameter to itself and backslash escaping doesn't seem to work when combining with the wildcard *.
Any ideas how it can be done in a oneliner in Bash? Thanks!

A: You can use:
for i in ./-*; do mv "$i" "${i#*-}"; done

It is important to use ./-* for globbing so that shell doesn't interpret - as command option.


text:
Q: MIT app inventor 2 on exporting aia file I am new in MIT app inventor. Recently I faced a problem when I exported my .aia file to QR code.
The errors given by the system:

My code:

This is a homework problem.

A: If you're connecting via wireless to a mobile device, it is highly likely that your aia is too big for your device to handle. To test this, create a very small app with one simple command (like playing a sound) and try to connect. If it connects, chances are your aia is too big.
Also, as far as getting answers goes, unfortunately you just have to play the waiting game/learn to exercise patience.


text:
Q: Azure App Configuration LabelFilters in .Net 4.8 Not working Correctly I have several App Configuration Keys that are working correctly.  Now one of them I need to have based on Environment so I am trying to use labels.  So I have 2 labels "Production" and "ProductionIntranet".
labelFiler=""

This brings back all the keys without labels.
According to the documentation this should bring back all null and ProductionIntranet
labelFilter="%00,ProductionIntranet"

This does not get any of the keys (Not the ones with labels or the null ones)
labelFilter="%00"

Neither does this.
I am sure this is a simple syntax issue but I am racking my head and I cannot figure it out. Any help would be greatly appreciated.

A: I got it to work.  I am not sure it is the best solution but it works.  I created 2 buulder stores and had the first with no labelFilter (AppSettingsStore) which gave me all the keys without any labels and then I created a second that had ProductionIntranet as a filter(AppSettingsStoreIntraNet).
Then I updated appsettings like this
<appSettings configBuilders="Environment,AppSettingsStore,AppSettingsStoreIntraNet">

This might be making two calls to App Configuration.  If someone knows how to do this in one ConfigBuilder please let me know.


text:
Q: Работа с изображениями на смартфонах В связи с тем, что разрешения экранов у всех разное. Как сделать так, чтоб на каждом устройстве изображение было на всю ширину экрана (отступы 10-20px)?
Создавать для каждого разрешения отдельное изображение?
A: Как минимум 4 основных изображения нужно будет создать. Но если учесть то, что экраны не пропорциональные, то возможно Вам придется создать больше. Либо изучить 9-patch - все сильно зависит от типа изображений.
A: В зависимости от ситуации возможны разные решения. Но если вы делаете собственный компонент, то не в ваших интересах держать зашитыми в компоненте множества изображений с различными разрешениями, единственным правильным решением является самостоятельное вычисление размера изображения. Весь процесс занимает несколько этапов:
1 - Определяем пропорции эталонного изображения (от качества этой картинки зависит всё). К примеру картинка размером 800*600, будет иметь следующие пропорции 1/0,75 (за главную сторону берём ширину).
2 - Определяем площадь которая доступна компоненту (например 600*550).
3 - Вычисляем новые размеры эталонного изображения для компонента- ширина - 600*1 = 600, высота - 600*0,75 = 450.
А затем меняем размер. Если это простая BitMap то - Bitmap btmp = Bitmap.createScaledBitmap(_temp_down_shd, 600, 450, false);

A: На самом деле есть способ, как обойтись 2умя:
Разделим устройства на две группы:

*

*Смартфоны и планшеты 7.* (соотношение экрана ~2.3/1)

*Планшеты 10.1 (соотношение экрана ~1.2/1)

Заводим для каждой группы отдельные рисунки. Остается лишь растягивать изображения при необходимости. Искажение не сильное, я проверял.
Если же нужна супер графика, то тут вам придётся заводить целый парк копий картинок


text:
Q: Declare type for imported module that allows undefined I'm using a module that has a TS def like:
// index.d.ts

interface SomeContext {
  // ... other props

  thing?: Record<string, any>;
}

When we use this module, we guard on someContext.thing being defined so it's never undefined when we start using it. We want to give it our own type in our code since we'll know what the shape will be but have had to do the following to get it to pass the TS build:
const { thing: ourThing } = <{ thing: any }>someContext.thing;

This feels like the wrong way to go about it as we lose the safety and DX that TS usually gives us.
Is there a better way to go about this?

A: When you are positive that thing is defined you can use the exclamation mark operator (non-null assertion operator) to tell the compiler that you know the value will not be null/undefined.
const thing = someContext.thing!;


text:
Q: How can I avoid TypeError: '>' not supported between instances of 'tuple' and 'int'? I am creating a program that will simulate an Nba player's statline. I am a beginner and unfortunately I have run into the following error:
TypeError: '>' not supported between instances of 'tuple' and 'int'

This error occurs at while numbers > 0:
Here is my code so far:
import random

Malcolm_Brogdon_tendencies = { "Under_Basket_Rate" : 396,
"Close_Left_Rate" : 32, "Close_Mid_Rate" : 50, "Close_Right_Rate" : 38, "Mid_Left_Rate" : 6, "Mid_Mleft_Rate" : 36, "Mid_Mleft" : 375, "Mid_Mid_Rate" : 47,
"Mid_Mright_Rate" : 83, "Mid_Right_Rate" : 15, "Three_Left_Rate" : 8, "Three_Mleft_Rate" : 91, "Three_Mid_Rate" : 70, "Three_Mright_Rate" : 109, "Three_right_Rate" : 18}

Malcolm_Brogdon_Percentages = {"Under_Basket" : 487, "Close_Left" : 571, "Close_Mid" : 515, "Close_Right" : 480, "Mid_Left" : 500, "Mid_Mleft" : 375,
 "Mid_Mid" : 452, "Mid_Mright" : 564, "Mid_Right" : 400, "Three_Left" : 0, "Three_Mleft" : 350, "Three_Mid" : 261, "Three_Mright" : 319, "Three_Right" : 417}

Malcolm_Brogdon_Person = {"Shot_Attempts" : random.randint(10,16)}

do_not_include = [0]
total_shots = 0

while total_shots< Malcolm_Brogdon_Person["Shot_Attempts"]:
    for tendencies, numbers in Malcolm_Brogdon_tendencies.items():
        for numbers in Malcolm_Brogdon_tendencies.items():
            while numbers > 0:
                shot_distribution = random.randint(1,1001)
                if shot_distribution not in do_not_include:
                    do_not_include.append(shot_distribution)
                    total_shots = total_shots + 1
                    numbers = numbers - 1

print (do_not_include)

I also understand that it would be easier to import the data from the internet, however, I wanted to start slow. The numbers represent how many times out a 1000 each one would occur. Then for each one in Malcolm_Brogdon_Tendencies it would generate that many numbers out of 1000 and assign them a value so that Close_Left_Rate, for example would occur 32/1000 times. There is probably a much simpler way to do this, however, I am new to programming and do not know that much.
I know that the variable, numbers, is the value in Malcolm_Brogdon_Tendencies and cannot be compared to an int. Is there a way to parse the number before so it acts as an int?
Thank you to anyone who helps because I realize that I gave a horrible description and that my code could probably be simplified a ton.

A: May be you are trying to access the number part of the (key,value) pair in items so try replacing
while numbers > 0:

with
while numbers[1] > 0:

A: Try replacing
while numbers > 0:

with
while int(numbers[0]) > 0:

This is way it will only compare the integer from the tuple.


text:
Q: Three on node.js with ColladaLoarder I know now how use JsonLoader in three.js for node.js.
But I have see, in the folder examples (three\examples\js\loaders) of node module an other loader whose is ColladaLoader.
I have try to execute this loader, but he isn't in the core folder of module.
I obtain an error: "ColladaLoader is not a function"
I have try to make a require to this file, but I obtain an error even I make a require to three module : "Three is not defined"
How can I use this ColladaLoader in node.js?
Thank You

A: var fs = require('fs');
var THREE = require("three");

eval(fs.readFileSync("bower_components/three.js/examples/js/loaders/ColladaLoader.js")+"");

First you load three.js, ensure you set it to a var with the uppercase name "THREE". Then you load the ColladaLoader - feels quite dirty.
A more beautiful solution would encapsule ColladaLoader.js to a node module.

A: If "ColladaLoader is not a function", then you did not reference to the ColladaLoader.js file.
Make sure to add <script src="js/loaders/ColladaLoader.js"></script> (or where ever your src is located) in your <head> or <body> somewhere before calling the ColladaLoader() function.


text:
Q: Linq2Sql Buildtime takes ages I am using Linq2Sql to access my database which is fairly large. (67 tables)
It's quite a pain in the butt to work with currently because it takes ages for the "MSLinqToSQLGenerator" to generate it's classes and finally finish compiling.
Are there any ways to speed up that process?
Like, is it possible to cache its generated output as I'm rarely touching the databasestructure?
Thank you for reading.

A: Moving your model to a separate assembly.
When your model is included directly in your application's project and you generate views through a pre-build event or a T4 template, view generation and validation will take place whenever the project is rebuilt, even if the model wasn't changed.
If you move the model to a separate assembly and reference it from your application's project, you can make other changes to your application without needing to rebuild the project containing the model.
Note:  when moving your model to separate assemblies remember to copy the connection strings for the model into the application configuration file of the client project.
For more Information Check Performance Considerations for Entity Framework


text:
Q: TypeError: not enough arguments for format string in print() I am trying to code a program to write a file:
print("Team %s, %s\t\t\t\tWon %s\t\t\tLost %s\t\t\tPercentage $%.3f"%(team,won,lost,perc))

but when I run it it keeps saying:
TypeError: not enough arguments for format string

Is there a way to fix this?

A: You have given it five variables to format, or five places you used % in your string, but you only pass it four variables to populate it with (team,won,lost,perc). You either need to remove a %s from your string or pass it another variable.
print("Team %s, %s\t\t\t\tWon %s\t\t\tLost, %s\t\t\tPercentage $%.3f"%(team,won,lost,lost,perc))

This may have been what you intended.

A: print("Team %s, %s\t\t\t\tWon %s\t\t\tLost %s\t\t\tPercentage $%.3f"%(team,won,lost,perc))

Here You are using 5 times % format specifier in print function and You're providing only 4 argument(team,won,lost,perc)  that's why
TypeError: not enough arguments for format string
Either you have to provide 5 arguments
print("Team %s, %s\t\t\t\tWon %s\t\t\tLost %s\t\t\tPercentage $%.3f"%(team,won,argument,lost,perc))

Or you may have putted 2nd %s mistakenly . So the correct format can be
print("Team %s, \t\t\t\tWon %s\t\t\tLost %s\t\t\tPercentage $%.3f"%(team,won,argument,lost,perc))

Hope it would help You :-)


text:
Q: How to find the 5th perfect number (which is 33550336)? The problem is taking forever to run I am trying to write a Java method that checks whether a number is a perfect number or not.
A perfect number is a number that is equal to the sum of all its divisor (excluding itself).
For example, 6 is a perfect number because 1+2+3=6. Then, I have to write a Java program to use the method to display the first 5 perfect numbers.
I have no problem with this EXCEPT that it is taking forever to get the 5th perfect number which is 33550336.
I am aware that this is because of the for loop in my isPerfectNumber() method. However, I am very new to coding and I do not know how to come up with a better code.
public class Labreport2q1 {

  public static void main(String[] args) {
    //Display the 5 first perfect numbers
    int counter = 0,
    i = 0;

    while (counter != 5) {
      i++;
      isPerfectNumber(i);
      if (isPerfectNumber(i)) {
        counter++;
        System.out.println(i + " ");
      }
    }

  }

  public static boolean isPerfectNumber(int a) {
    int divisor = 0;
    int sum = 0;
    for (int i = 1; i < a; i++) {
      if (a % i == 0) {
        divisor = i;
        sum += divisor;
      }
    }

    return sum == a;

  }

}

This is the output that is missing the 5th perfect number

A: Let's check the properties of a perfect number. This Math Overflow question tells us two very interesting things:

*

*A perfect number is never a perfect square.

*A perfect number is of the form (2k-1)×(2k-1).

The 2nd point is very interesting because it reduces our search field to barely nothing. An int in Java is 32 bits. And here we see a direct correlation between powers and bit positions. Thanks to this, instead of making millions and millions of calls to isPerfectNumber, we will be making less than 32 to find the 5th perfect number.
So we can already change the search field, that's your main loop.
    int count = 0;
    for (int k = 1; count < 5; k++) {

      // Compute candidates based on the formula.
      int candidate = (1L << (k - 1)) * ((1L << k) - 1);

      // Only test candidates, not all the numbers.
      if (isPerfectNumber(candidate)) {
        count++;
        System.out.println(candidate);
      }
    }

This here is our big win. No other optimization will beat this: why test for 33 million numbers, when you can test less than 100?
But even though we have a tremendous improvement, your application as a whole can still be improved, namely your method isPerfectNumber(int).
Currently, you are still testing way too many numbers. A perfect number is the sum of all proper divisors. So if d divides n, n/d also divides n. And you can add both divisors at once. But the beauty is that you can stop at sqrt(n), because sqrt(n)*sqrt(n) = n, mathematically speaking. So instead of testing n divisors, you will only test sqrt(n) divisors.
Also, this means that you have to start thinking about corner cases. The corner cases are 1 and sqrt(n):

*

*1 is a corner case because you if you divide n by 1, you get n but you don't add n to check if n is a perfect number. You only add 1. So we'll probably start our sum with 1 just to avoid too many ifs.

*sqrt(n) is a corner case because we'd have to check whether sqrt(n) is an integer or not and it's tedious. BUT the Math Overflow question I referenced says that no perfect number is a perfect square, so that eases our loop condition.

Then, if at some point sum becomes greater than n, we can stop. The sum of proper divisors being greater than n indicates that n is abundant, and therefore not perfect. It's a small improvement, but a lot of candidates are actually abundant. So you'll probably save a few cycles if you keep it.
Finally, we have to take care of a slight issue: the number 1 as candidate. 1 is the first candidate, and will pass all our tests, so we have to make a special case for it. We'll add that test at the start of the method.
We can now write the method as follow:
  static boolean isPerfectNumber(int n) {
    // 1 would pass the rest because it has everything of a perfect number
    // except that its only divisor is itself, and we need at least 2 divisors.
    if (n < 2) return false;

    // divisor 1 is such a corner case that it's very easy to handle:
    // just start the sum with it already.
    int sum = 1;

    // We can stop the divisors at sqrt(n), but this is floored.
    int sqrt = (int)Math.sqrt(n);

    // A perfect number is never a square.
    // It's useful to make this test here if we take the function
    // without the context of the sparse candidates, because we
    // might get some weird results if this method is simply
    // copy-pasted and tested on all numbers.
    // This condition can be removed in the final program because we
    // know that no numbers of the form indicated above is a square.
    if (sqrt * sqrt == n) {
      return false;
    }

    // Since sqrt is floored, some values can still be interesting.
    // For instance if you take n = 6, floor(sqrt(n)) = 2, and
    // 2 is a proper divisor of 6, so we must keep it, we do it by
    // using the <= operator.
    // Also, sqrt * sqrt != n, so we can safely loop to sqrt
    for (int div = 2; div <= sqrt; div++) {
      if (n % div == 0) {
        // Add both the divisor and n / divisor.
        sum += div + n / div;
        // Early fail if the number is abundant.
        if (sum > n) return false;
      }
    }
    return n == sum;
  }

These are such optimizations that you can even find the 7th perfect number under a second, on the condition that you adapt the code for longs instead of ints. And you could still find the 8th within 30 seconds.
So here's that program (test it online). I removed the comments as the explanations are here above.
public class Main {
  public static void main(String[] args) {
    int count = 0;
    for (int k = 1; count < 8; k++) {
      long candidate = (1L << (k - 1)) * ((1L << k) - 1);
      if (isPerfectNumber(candidate)) {
        count++;
        System.out.println(candidate);
      }
    }
  }

  static boolean isPerfectNumber(long n) {
    if (n < 2) return false;
    long sum = 1;
    long sqrt = (long)Math.sqrt(n);
    for (long div = 2; div <= sqrt; div++) {
      if (n % div == 0) {
        sum += div + n / div;
        if (sum > n) return false;
      }
    }
    return n == sum;
  }
}

The result of the above program is the list of the first 8 perfect numbers:
6
28
496
8128
33550336
8589869056
137438691328
2305843008139952128

You can find further optimization, notably in the search if you check whether 2k-1 is prime or not as Eran says in their answer, but given that we have less than 100 candidates for longs, I don't find it useful to potentially gain a few milliseconds because computing primes can also be expensive in this program. If you want to check for bigger perfect primes, it makes sense, but here? No: it adds complexity and I tried to keep these optimization rather simple and straight to the point.

A: There are some heuristics to break early from the loops, but finding the 5th perfect number still took me several minutes (I tried similar heuristics to those suggested in the other answers).
However, you can rely on Euler's proof that all even perfect numbers (and it is still unknown if there are any odd perfect numbers) are of the form:
2i-1(2i-1)
where both i and 2i-1 must be prime.
Therefore, you can write the following loop to find the first 5 perfect numbers very quickly:
int counter = 0,
i = 0;

while (counter != 5) {
    i++;
    if (isPrime (i)) {
        if (isPrime ((int) (Math.pow (2, i) - 1))) {
            System.out.println ((int) (Math.pow (2, i -1) * (Math.pow (2, i) - 1)));
            counter++;
        }
    }
}

Output:
6
28
496
8128
33550336

You can read more about it here.
If you switch from int to long, you can use this loop to find the first 7 perfect numbers very quickly:
6
28
496
8128
33550336
8589869056
137438691328

The isPrime method I'm using is:
public static boolean isPrime (int a)
{
  if (a == 1)
    return false;
  else if (a < 3)
    return true;
  else {
    for (int i = 2; i * i <= a; i++) {
      if (a % i == 0)
        return false;
    }
  }
  return true;
}


text:
Q: Create Component does not work! MetaUml: Using MetaPost in LuaLaTeX I am trying to create a component diagram using MetaUml embedded in TeX using LuaLaTeX. Every example form the manual I tried, worked well except from components.
\documentclass{article}
\usepackage{luamplib}
\title{Algo}
\author{Paul}
\begin{document}
\maketitle
\newpage
\tableofcontents
\newpage
\section{Reengineering Algo Architecture}
\subsection{Current System Structure}
\subsection{Restructured System}
\subsection{Extended  Restructured System}
    \subsubsection{System Component Structure}
        \begin{mplibcode}
            input metauml;
            beginfig(1);
            Component.C("Business Logic")();
            drawObject(C);
            endfig;
            end
        \end{mplibcode}
    \subsubsection{Inner Component Structure}
    \subsubsection{Usecasses}
\end{document}

This does not work for me, but it should, see page 14.
Error Message is:

Cannot figure it out. Sorry.
Edit: Automatic installation was not correct:
But it is still not working.


text:
Q: table *** has no column named *** Hello Guys ive got a DB and created a new Edit Text field to save a new column im my database called COLUMN_AUSWIRKUNGEN ...if i go to my app on my device, enter a text and click on confirm button ,the error log give me this :
07-31 16:19:23.368: E/SQLiteLog(10039): (1) table todo has no column named auswirkungen
07-31 16:19:23.378: E/SQLiteDatabase(10039): Error inserting summary=texthere category=Sehr Wichtig (Folgenschwer bei Versagen) description=text here too auswirkungen=here is the column that dont work
07-31 16:19:23.378: E/SQLiteDatabase(10039): android.database.sqlite.SQLiteException: table todo has no column named auswirkungen (code 1): , while compiling: INSERT INTO todo(summary,category,description,auswirkungen) VALUES (?,?,?,?)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:923)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:534)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1523)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1395)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at de.vogella.android.todos.contentprovider.MyTodoContentProvider.insert(MyTodoContentProvider.java:86)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.content.ContentProvider$Transport.insert(ContentProvider.java:232)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.content.ContentResolver.insert(ContentResolver.java:1213)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at de.vogella.android.todos.TodoDetailActivity.saveState(TodoDetailActivity.java:115)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at de.vogella.android.todos.TodoDetailActivity.onPause(TodoDetailActivity.java:95)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.app.Activity.performPause(Activity.java:5442)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1356)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3601)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3570)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3547)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.app.ActivityThread.access$1000(ActivityThread.java:156)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1372)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.os.Handler.dispatchMessage(Handler.java:102)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.os.Looper.loop(Looper.java:157)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at android.app.ActivityThread.main(ActivityThread.java:5872)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at java.lang.reflect.Method.invokeNative(Native Method)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at java.lang.reflect.Method.invoke(Method.java:515)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
07-31 16:19:23.378: E/SQLiteDatabase(10039):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)

    07-31 16:19:23.378: E/SQLiteDatabase(10039):    at dalvik.system.NativeStart.main(Native Method)
here is my db
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class TodoTable {

    // Database table
    public static final String TABLE_TODO = "todo";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_CATEGORY = "category";
    public static final String COLUMN_SUMMARY = "summary";
    public static final String COLUMN_DESCRIPTION = "description";
    public static final String COLUMN_AUSWIRKUNGEN = "auswirkungen";
    // Database creation SQL statement
    private static final String DATABASE_CREATE = "create table " + TABLE_TODO
            + "(" + COLUMN_ID + " integer primary key autoincrement, " + ""
            + COLUMN_CATEGORY + " text not null, " + COLUMN_SUMMARY
            + " text not null," + COLUMN_DESCRIPTION + " text not null"
            + COLUMN_AUSWIRKUNGEN+ " text not null"
            +
            ");";

    public static void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    public static void onUpgrade(SQLiteDatabase database, int oldVersion,
            int newVersion) {
        Log.w(TodoTable.class.getName(), "Upgrading database from version "
                + oldVersion + " to " + newVersion
                + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
        onCreate(database);
    }
}

the content provider
import java.util.Arrays;
import java.util.HashSet;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import de.vogella.android.todos.database.TodoDatabaseHelper;
import de.vogella.android.todos.database.TodoTable;

public class MyTodoContentProvider extends ContentProvider {
    // database
    private TodoDatabaseHelper database;
    // Used for the UriMacher
    private static final int TODOS = 10;
    private static final int TODO_ID = 20;
    private static final String AUTHORITY = "de.vogella.android.todos.contentprovider";
    private static final String BASE_PATH = "todos";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
            + "/" + BASE_PATH);
    public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
            + "/todos";
    public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
            + "/todo";
    private static final UriMatcher sURIMatcher = new UriMatcher(
            UriMatcher.NO_MATCH);
    static {
        sURIMatcher.addURI(AUTHORITY, BASE_PATH, TODOS);
        sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", TODO_ID);
    }

    @Override
    public boolean onCreate() {
        database = new TodoDatabaseHelper(getContext());
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        // Uisng SQLiteQueryBuilder instead of query() method
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
        // Check if the caller has requested a column which does not exists
        checkColumns(projection);
        // Set the table
        queryBuilder.setTables(TodoTable.TABLE_TODO);
        int uriType = sURIMatcher.match(uri);
        switch (uriType) {
        case TODOS:
            break;
        case TODO_ID:
            // Adding the ID to the original query
            queryBuilder.appendWhere(TodoTable.COLUMN_ID + "="
                    + uri.getLastPathSegment());
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        SQLiteDatabase db = database.getWritableDatabase();
        Cursor cursor = queryBuilder.query(db, projection, selection,
                selectionArgs, null, null, sortOrder);
        // Make sure that potential listeners are getting notified
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsDeleted = 0;
        long id = 0;
        switch (uriType) {
        case TODOS:
            id = sqlDB.insert(TodoTable.TABLE_TODO, null, values);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return Uri.parse(BASE_PATH + "/" + id);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsDeleted = 0;
        switch (uriType) {
        case TODOS:
            rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO, selection,
                    selectionArgs);
            break;
        case TODO_ID:
            String id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO,
                        TodoTable.COLUMN_ID + "=" + id, null);
            } else {
                rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO,
                        TodoTable.COLUMN_ID + "=" + id + " and " + selection,
                        selectionArgs);
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsUpdated = 0;
        switch (uriType) {
        case TODOS:
            rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO, values, selection,
                    selectionArgs);
            break;
        case TODO_ID:
            String id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO, values,
                        TodoTable.COLUMN_ID + "=" + id, null);
            } else {
                rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO, values,
                        TodoTable.COLUMN_ID + "=" + id + " and " + selection,
                        selectionArgs);
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

    private void checkColumns(String[] projection) {
        String[] available = { TodoTable.COLUMN_CATEGORY,
                TodoTable.COLUMN_SUMMARY, TodoTable.COLUMN_DESCRIPTION,
                TodoTable.COLUMN_ID ,TodoTable.COLUMN_AUSWIRKUNGEN};
        if (projection != null) {
            HashSet<String> requestedColumns = new HashSet<String>(
                    Arrays.asList(projection));
            HashSet<String> availableColumns = new HashSet<String>(
                    Arrays.asList(available));
            // Check if all columns which are requested are available
            if (!availableColumns.containsAll(requestedColumns)) {
                throw new IllegalArgumentException(
                        "Unknown columns in projection");
            }
        }
    }
}

**After reinstalling app on my phone i get this error **
07-31 20:23:29.257: W/asset(2255): Copying FileAsset 0x780f87a8 (zip:/data/app/de.vogella.android.todos-2.apk:/resources.arsc) to buffer size 3392 to make it aligned.
07-31 20:23:29.337: E/SQLiteLog(2255): (1) near "nullauswirkungen": syntax error
07-31 20:23:29.337: W/dalvikvm(2255): threadid=11: thread exiting with uncaught exception (group=0x41b2ee18)
07-31 20:23:29.347: E/AndroidRuntime(2255): FATAL EXCEPTION: AsyncTask #1
07-31 20:23:29.347: E/AndroidRuntime(2255): Process: de.vogella.android.todos, PID: 2255
07-31 20:23:29.347: E/AndroidRuntime(2255): java.lang.RuntimeException: An error occured while executing doInBackground()
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at java.lang.Thread.run(Thread.java:864)
07-31 20:23:29.347: E/AndroidRuntime(2255): Caused by: android.database.sqlite.SQLiteException: near "nullauswirkungen": syntax error (code 1): , while compiling: create table todo(_id integer primary key autoincrement, category text not null, summary text not null,description text not nullauswirkungen text not null);
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:923)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:534)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1728)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1659)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at de.vogella.android.todos.database.TodoTable.onCreate(TodoTable.java:23)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at de.vogella.android.todos.database.TodoDatabaseHelper.onCreate(TodoDatabaseHelper.java:18)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at de.vogella.android.todos.contentprovider.MyTodoContentProvider.query(MyTodoContentProvider.java:65)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.content.ContentProvider.query(ContentProvider.java:869)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.content.ContentProvider$Transport.query(ContentProvider.java:212)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.content.ContentResolver.query(ContentResolver.java:476)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.content.CursorLoader.loadInBackground(CursorLoader.java:65)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.content.CursorLoader.loadInBackground(CursorLoader.java:43)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:57)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-31 20:23:29.347: E/AndroidRuntime(2255):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-31 20:23:29.347: E/AndroidRuntime(2255):     ... 3 more
07-31 20:23:29.367: I/Adreno-EGL(2255): <qeglDrvAPI_eglInitialize:385>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066_msm8974_refs/tags/AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066__release_AU ()
07-31 20:23:29.367: I/Adreno-EGL(2255): OpenGL ES Shader Compiler Version: E031.24.00.06
07-31 20:23:29.367: I/Adreno-EGL(2255): Build Date: 02/06/14 Thu
07-31 20:23:29.367: I/Adreno-EGL(2255): Local Branch:
07-31 20:23:29.367: I/Adreno-EGL(2255): Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066
07-31 20:23:29.367: I/Adreno-EGL(2255): Local Patches: NONE
07-31 20:23:29.367: I/Adreno-EGL(2255): Reconstruct Branch: NOTHING

A: This is wrong:
" text not null"
        + COLUMN_AUSWIRKUNGEN+

You can see that you miss a comma after null. It should be:
" text not null, "
        + COLUMN_AUSWIRKUNGEN+

Otherwise the table won't be created.
By the way, this + "" is completely useless and introduces some extra work (one more string concatenation)


text:
Q: ImportError: cannot import name 'Settings' from 'settings' This is the content of Alien_invasion.py:
import pygame
import sys

#here im importing the class from the settings class
from settings import Settings

def run_game():

    ai_settings = Settings()

    pygame.init()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    bg_color = (230, 230, 230)

    while True:
        ...

run_game()

This is within the settings.py:
class Settings():

    def __init__(self):
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (230, 230, 230)

When trying to run Alien_invasion.py, the following error occurs:
ImportError: cannot import name 'Settings' from 'settings'

A: You can try import settings and ai_settings = settings.Settings(). Also, make sure the two files are in the same folder.


text:
Q: Calculate the total price of items in an invoice here is what I have:-
accountid    |    productname     |   qty    |   price       |    companyexported   |
8            |    name            |    5     |    50         |         company1     |
8            |    name2           |    5     |    60         |         company1     |
8            |    name3           |    10    |    10         |         company2     |

this is the basket table and I'm sorting each item by companyexported (Bill)
so I want to calculate the total cost for the bill ( the sum(price) of the all the same value (companyexported) row that contain the same company name and of course order by accountid
what I have tried:-
Code:-
$price = $PDOCon->prepare("SELECT SUM(price) AS totalprice FROM basket WHERE accountid ='$accountid' order by companyexported");
$price->execute();

$row = $price->fetch(PDO::FETCH_ASSOC);
echo $row['totalprice'];

A: To get the sum per company, you need to GROUP BY companyexported, not ORDER BY. Note that as long as you are preparing a statement, you should use placeholders for parameters:
$price = $PDOCon->prepare("SELECT SUM(price) AS totalprice
                           FROM basket
                           WHERE accountid = :accountid
                           GROUP BY companyexported");
$price->bindParam(':accountid', $accountid);
$price->execute();

Also since you will get multiple results (one for each company), your fetch should be in a loop:
while ($row = $price->fetch(PDO::FETCH_ASSOC)) {
    echo $row['totalprice'];
}


text:
Q: fire .net event from jquery I have an image on my page than can be changed from a fileupload asp.net control on the page, i want to provide and alternative to clicking the button by allowing the user to click their image. i gave the fileupload a class 'jqueryPhotoUploadTrigger' and it renders like this:
<input type="file" name="ctl00$ctl00$ctl00$ContentPlaceHolderDefault$C2kMasterPlaceholder$ucEditDetails_20$photoupload" id="ctl00_ctl00_ctl00_ContentPlaceHolderDefault_C2kMasterPlaceholder_ucEditDetails_20_photoupload" class="jqueryPhotoUploadTrigger" />

i then have jquery script at the bottom:
 $(document).ready(function() {
        $("#clickMyColl").click(function () {

            alert("image has been clicked");
            $('.jqueryPhotoUploadTrigger').click();
        });
 });

the alert does show so i know the script is firing when i click the image. i was just hoping the .click would fire the event on the button but it didnt. can i do it this way or must i find an alternative?

A: you could do a submit or use the Ajax way, there are functions like __doPostback(), look in the ASP.NET documentation.

A: You could either to an ajax call of have an ImageButton on the page with a transparent image (so its hidden)
then in your jquery you could use
 $("#yourhiddenbutton").click();

this would then fire the server side click event

A: Maybe you've to set the focus on the input (if I've understood your question):
$('.jqueryPhotoUploadTrigger').focus();

A: You are using the ID of your image as "#clickMyColl", but instead use the ID as it is rendered (jQuery does not know the asp ID): "ctl00_ctl00_ctl00_ContentPlaceHolderDefault_C2kMasterPlaceholder_ucEditDetails_20_photoupload"
Alternatively, you could use the class to select:
$(".jqueryPhotoUploadTrigger").click(function ...


text:
Q: Can't verify CSRF token authenticity when using custom subdomain url in localhost I'm using devise gem for authentication. earlier it was working fine when I ran rails in localhost:3000. but when I edited my /etc/hosts and added
127.0.0.1       tenant1.lv.me to my hosts file
I'm not able to login getting "Can't verify CSRF token authenticity"
any idea !!


text:
Q: change the title of web page opened through target= "_blank" I want to change the title of web page tab when it is opened through <h:commandLink target='_blank'>. How can i set this?

A: this is one method:
url = www.domain.com?title=popupwindowtitle

window.open(url)

-popup windows code-
<html>
<title><?php echo $_GET['title'']?></title>
</html>

not sure if there's a way to directly set the title, hope this helps.


text:
Q: Seeking Advice re. IPFS Clustering - Overhead, Performance, Design Guidance I'm about to rebuild a server cluster - currently set up for high reliability & availability - RAID, disk mirroring, automatic failover, all that good stuff.
I've been thinking about replacing the storage "plumbing" with a distributed filesystem - that extends beyond the cluster to another location, and to various laptops & desktops - one big file system for an organization & its community.
From 50,000 feet, just turning all the machines into one big IPFS cluster would seem to make sense - but one wonders about all the processing & data transfer overhead. Also, the latency - how fast will systems sync if they're on neighboring machines. And then there's the matter of checkpointing & reliable failover.
Can anybody point at some analysis of the processing & network overhead associated with IPFS & IPFS-cluster? Any experience and/or suggestions for using IPFS as a generic, distributed, high-availability storage network? Case studies? Places to start looking? (Note: Didn't get a single response on discuss.ipfs.tech - doesn't seem to be very active as a support community.)
Thanks Very Much,
Miles Fidelman


text:
Q: Under what circumstances are general relativistic coordinate transformations physically meaningful? Although the field equations of GR are covariant under arbitrary coordinate transformations, such as the transformation given by Dirac (in Princeton Landmarks pp 34) that eliminate the singularities in the Schwartzschild metric, is it necessarily the case that the new coordinate system, with its singularity free metric, is physically meaningful?
    This question comes up because there are transformations that are clearly meaningless. For example, if an observer makes a transformation from his coordinate system to that of his virtual image seen in a mirror, general covariance is preserved, but there is no actual space that can be entered by an observer.
     Is there a criterion for deciding when the transformation is strictly virtual in the sense above?
     Does the world inside a black hole as described, by say Kruskal coordinates, have the operational meaning of consisting of a world that can be entered and explored by an observer, or is it a strictly virtual construct like the mirror image coordinates?

A: The coordinate transformation is never physically meaningful. Certain coordinate systems have some specific meaning.
The coordinates are just sets of arbitrary numbers with some convenient mathematical properties (a smooth and invertible map) but they are otherwise arbitrary. Coordinate transformations are just bookkeeping required to go from one set of such arbitrary numbers to another.
Because the numbering is largely arbitrary, a physicist may arbitrarily choose to assign them based on some physically meaningful quantity, but they are not required to do so. Any physical meaning (or lack thereof) comes from that choice.
Edit: regarding the question about the meaningfulness of the coordinate transforms on the interior of the event horizon in Schwarzschild coordinates. Again, the coordinates are not in themselves physically meaningful; instead physical meaning comes from the invariants. All of the curvature invariants are well behaved and finite at the event horizon, so there is no GR-based reason to think that it is any kind of a barrier. Geodesics crossing the horizon are well behaved and so forth. All invariants are reasonable, so absent unknown quantum effects and direct experimental evidence, the assumption is that the interior is physically meaningful based on invariants, not on coordinates.

A: As an example of a possible virtual coordinate transformation consider the Schwarzschild metric for r less that the Schwarzschild radius. Then make the space-time switching transformation indicated to get the inside metric:
$$ds^2=\Big(1-\frac{r_s}{r}\Big)\ c^2dt^2-\Big(1-\frac{r_s}{r}\Big)^{-1}dr^2$$$$d\rho = cdt$$ $$dr =cd\tau$$
$$ds^2=\Big(\frac{r_s}{c\tau}-1\Big)^{-1}\ c^2d\tau^2-\Big(\frac{r_s}{c\tau}-1\Big)d\rho^2$$.
$$(dr/dt)(d\rho/d\tau) = c^2$$
Notice that the speed of the same particle in both coordinate systems is related by an inversion transformation using a sphere of radius c.
This means that if the speed of a particle in the r,t coordinates must be less than c, then in violation of relativity, it must be greater than c w/rspt to the $\rho, \tau$ coordinates
Conversly, if $d\rho/d\tau$ is less than c, then $dr/dt$ must be greater.
This seems to imply that the transformation must be virtual because it inevitably leads to a contradiction of relativity. A similar problem can be shown to exist using Kruskal coordinates


text:
Q: Hibernate native query that returns an object with nested properties for GraphQL Is it possible for a native Hibernate/Spring database query to return an object structure that contains nested properties? Ultimately I want to return the data to a GraphQL query. I'm using Spring for GraphQL and want the following request satisfied:
query Query {
    someField {
        prop1
        prop2
        complexProp {
            prop3
            prop4
        }
    }
}

What does work is to return a flattened version of the graph as you see below. I'm okay with working with the flattened version, but I would prefer a graph with nested fields for complex objects. Here is what does work:
query Query {
    someField {
        prop1
        prop2
        prop3
        prop4
    }
}

I'm able to generate the above flattened graph by using Transformers.aliasToBean (aka, ResultTransformer), like so:
var query = """
        select p.prop1      as prop1,
               p.prop2      as prop2,
               c.some_prop1 as prop3,
               c.some_prop2 as prop4
        from parent p
                 inner join child c on c.parent_id = p.id
        """;

var results = (List<ParentWithChildFlattenedDto>) entityManager.createNativeQuery(query)
        .setMaxResults(100)
        .unwrap(NativeQuery.class)
        .setResultTransformer(Transformers.aliasToBean(ParentWithChildFlattenedDto.class))
        .getResultList();

If I were using managed entities instead of a native query, I know the nested graphql structure could be built by doing one of two things:

*

*The "new" operator in JPQL

*Interface projections

thx


text:
Q: Geowebcache does not displaying map tiles in EPSG:900913 from a remote WMS server I connect  Geowebcache to a remote WMS service  through their Getcapability request by adding the url in geowebcache-servlet.xml document. Geowebcache demo page  displays the list of wms layers from the remote wms server.  When I click on the png link for the EPSG:900913 format ,  to display the map,  only displays the image place holders instead of map tiles. This displays map for the png link for EPSG:4326 formaT.  When I issue a Getmap request to the remote wms service directly from my browser, for EPSG:4326   works well but for EPSG:900913 it shows error "SRS Code 'EPSG:900913' is not supported (not found in SRS xml settings)". When I check their Getcapability document   I could not find EPSG:900913 in the SRS list, but EPSG:4326 is available.  Since I want display the map in google map api v2 , think i need EPSG900913 format to get this work.  I think geowebcache generate an automatic re-projection in EPSG:900913 format for googlemap api. This link  is not working for me, I think that could be the reason this is not displying in google map api.
could someone tell me a solution for this ? why the reprojection not working ?
Here is the link for  EPSG:4326 format , this will start disply at a scale 1:272K range 10th zoom
This is the  link for  EPSG:900913 format which is not working for me.
This is the link for the Geowebcache demo page
I think there is a way to define independent layers and projections in geowebcache.xml document. Not sure how to do this to suit for my situation ?

A: GWC doesn't do reprojection, so you need to
download GeoServer 2.1 and set up your remote WMS as a cascading WMS, GeoServer will then reproject your remote WMS from 4326 to what ever projection you need. Then use the built in GWC to serve out tiles from the cascaded layer.
This blog post http://geo-solutions.blogspot.com/2010/10/wms-cascading-in-latest-geoserver.html describes how to set up your remote WMS. After that it behaves exactly as if you have a local layer.


text:
Q: UIScrollView - paging UIImage larger than the screens width Am currently developing an iPad app which uses a UIScrollView. The UIScrollView is populated with UIImage(s) and all the images are larger than the iPads width, twice the width, 1536px. What I would like it to do is when swiped/flicked it will scroll to the second image, i.e. 1536 and the third image to 3072 and so on. Its just to see a quick image when sliding across. I've had a look at scrollViewDidEndDragging but it gets really nasty and jumpy at times.
Is there a way of setting the animation to scroll by 1536 each time apart from the last UIImage in the UIScrollView? I know you can use setContentOffset but if I use this in the above method it doesn't work as its using the current transition still and therefore making it very jumpy.
Edit
for (i = 1; i <= kNumImages; i++)
{
    NSString *imageName = [NSString stringWithFormat:@"cocktail_%d.png", i];
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    CGRect rect = imageView.frame;
    rect.size.width = kMainImageWidth;
    rect.size.height = kMainImageHeight;
    rect.origin = CGPointMake(xpos, 0);
    imageView.frame = rect;

    [mainImgScrollView addSubview:imageView];
    [imageView release];
    xpos += kMainImageWidth;
 }

Edit
All I needed to do was make the UIScrollView 1536px wide and it worked. The app will have 6 images to start with and more in the future. Hopefully there won't be a memory issue to start with?
Thank you for your help.

A: The page size is the UIScrollView size. It is perfectly acceptable to make the UIScrollView itself larger than the width of the iPad screen. If you make the UIScrollView 1536px wide, then each page will be 1536px wide.
To allow the user to scroll around and see each picture, what you want is a scrollview containing a row of scrollviews. The outer scrollview is the one in the window, it is 1536px wide, and it is just for paging. The inner scrollviews are the width of the screen and they have their contentSize set to the image size so that the user can scroll around in each one and see the image.
(However, you're going to want to rethink your architecture, since an app into which you have predrawn multiple images 1536px wide will not run (because it will exceed the available memory for the device). The WWDC2010 videos include an excellent talk on this very topic, i.e. how to design a paging scroll view that lets you page from image to image.)

A: I think you want to turn on paging on your UIScroll view.  This will make it "snap" to the width of the scroll view.  It will behave like the home screen on the iPad/iPhone does.  You may need to make your scrollView's frame wider than the screen also to get the paging effect correct.  You may encounter some lag no matter what due to the size of your images.


text:
Q: When tracking clicks AMPscript tag breaks our landing page Newer user, so please ELI5 if you are able. I'm having a bit of a weird issue. When I have click tracking turned off my link my website works just fine. However, when I turn click tracking on the additional AMPscript code is added to the URL and the landing page won't fully load. My developers have said that having the %% characters is what's breaking the page. %25%25 is seems to work fine as well but the two characters next to each is what's causing the error. The tracking link that SFMC wraps it in breaks the link and the page doesn't load. The website is hosted off of Microsoft Azure too if that could cause anything.

A: Without seeing your ampscript code, I can bet that you're having a similar problem that I had.
Check out this topic:
RedirectTo, AmpScript and website-generated parameters
You need to use the RedirectTo function and find out whether or not SFMC is adding on extra parameters that are breaking your links when tracking.


text:
Q: Kohana 3 -> Checking if page with (URI) exists With Kohana 3, I would like to get to know if a page with a by the user entered URI exists.
So basically the user enters an URI, and I will say if it will give a (404) error or not.
I already tried this, but it didn't work:
<?php
 public function action_test_uri()
 {
    $r = Request::factory('this/uri/is/not/leading/to/a/valid/page');
    $test = $r->status;
    $test = ($test == 404) ? 'THIS PAGE DOESN\'T EXISTS' : 'THIS PAGE EXISTS';
    die($test);
 }
?>

Unfortunately this outputs 'THIS PAGE EXISTS'.
Is there anyone who does know the solution?
Thanks

A: Retrieve all routes and test if any of them matches the URI. However, this does not tell you how the controller handles the URI. The controller might as well generate a 404, so the only sure way is to actually retrieve the page referred to by the URI.


text:
Q: How can ping know if my host is down When I ping a server there are two kinds of result I might get:

*

*Timeout

*Host is down message

How does the ping command know if a host is down? In both cases, the host does not send any response to the ping packet, so how can ping tell the difference?

A: Host is down message:
This indicates that you don't know a route to the desired destination, or a remote router reports that it has no route to the destination.
Timeout:
Indicates the absense of Echo Reply messages. No package were received within the default time.

A: Differences between responses are not actually determined by ICMP itself but rather indirectly.
ICMP can distingush between the following:
  0 = net unreachable;

  1 = host unreachable;

  2 = protocol unreachable;

  3 = port unreachable;

  4 = fragmentation needed and DF set;

  5 = source route failed.

But it does so with other network resources. Codes 0, 1, 4, and 5 may be received from a gateway. Codes 2 and 3 may be received from a host.
If, according to the information in the gateway's routing tables, destination network is unreachable, (e.g., the distance to the network is infinity), the gateway may send a destination unreachable message to the internet source host of the datagram.  In addition, in some networks, the gateway may be able to determine if the internet destination host is unreachable. It is the Gateways in these networks that can send destination unreachable messages to the source host when the       destination host is unreachable, so it's not actually ICMP doing the determinations.
In the case that in the destination host, the IP module cannot deliver the      datagram  because the indicated protocol module or process port is not active, then the destination host may send a 'destination unreachable' message to the source host.
Finally, if a datagram must be fragmented to be forwarded by a gateway yet the 'Do not Fragment' flag is on, the gateway will discard the datagram and will return a 'destination unreachable' message.
Now to difference between the 2 separate cases: Request Timed Out means that no Echo Reply messages were received within the set time. This can be due to many different causes: ARP request failure, network congestion, packet filtering, routing error, or a even silent discard.
When you get a Reply From [IP address]: 'Destination Host Unreachable,' then the problem occurred at/after a remote router, whose address is indicated by the [IP address]. So it's a router telling you that there is a problem between it and the destination address.

A: You cant ping if the computer isnt connected to the internet because by pinging you actually request the ip of the host .


text:
Q: Change WordPress "Blog" Directory Name and Structure My company changed WordPress themes and reorganized the site structure of our website and I would like to know if it is possible to change the directory used for the Posts page?"
On our old site the directory structure was "site.com/blog/"
The new site has the directory structure of "site.com/home-2/blog/"
Is there any way to change the directory structure back to "/blog" instead of "home-2/blog"?
To be clear, I am not trying to move the WordPress installation.
Here is the URL structure of the site currently:

*

*Home – sitename.com

*About – sitename/about-us/

*Portfolio – sitename/portfolio/

*Contact – sitename/contact/

*Blog – sitename/home-2/blog/
Notice that "/blog/" is in the subdirectory "/home-2/blog/", this is the directory I am trying to change.
I have attempted to change Permalink settings to a Custom Structure (sitename.com/blog/%postname%/), use Yoast SEO to strip the category base from the category URL, and tried the "Remove Category URL" plug-in - all without success.
Thank you for your time.


text:
Q: Bell character as Fields separator in Python print output I am fairly new to Python and need a little help here.
I have a Python script running on Python 2.6 that parses some JSON.
Example Code:
if "prid" in data[p]["prdts"][n]:
    print data[p]["products"][n]["prid"],

    if "metrics" in data[p]["prdts"][n]:
        lenmet = len(data[p]["prdts"][n]["metrics"])
        i = 0
        while (i < lenmet):
            if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
                print data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"]
                break

Now, this prints values in 2 columns:
prid price
123 20
234 40

As you see the fields separator above is ' '. How can I put a field separator like BEL character in the output?
Sample expected output:
prid price
123^G20
234^G40

A: FWIW, your while loop doesn't increment i, so it will loop forever, but I assume that was just a copy & paste error, and I'll ignore it in the rest of my answer.

If you want to use two separate print statements to print your data on one line you can't avoid getting that space produced by the first print statement. Instead, simply save the prid data until you can print it with the price in one go using string concatenation. Eg,
if "prid" in data[p]["prdts"][n]:
    prid = [data[p]["products"][n]["prid"]]

    if "metrics" in data[p]["prdts"][n]:
        lenmet = len(data[p]["prdts"][n]["metrics"])
        i = 0
        while (i < lenmet):
            if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
                price = data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"]
                print str(prid) + '\a' + str(price)
                break

Note that I'm explicitly converting the prid and price to string. Obviously, if either of those items is already a string then you don't need to wrap it in str(). Normally, we can let print convert objects to string for us, but we can't do
print prid, '\a', price

here because that will give us an unwanted space between each item.

Another approach is to make use of the new print() function, which we can import using a __future__ import at the top of the script, before other imports:
from __future__ import print_function

# ...

if "prid" in data[p]["prdts"][n]:
    print(data[p]["products"][n]["prid"], end='\a')

    if "metrics" in data[p]["prdts"][n]:
        lenmet = len(data[p]["prdts"][n]["metrics"])
        i = 0
        while (i < lenmet):
            if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
                print(data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"])
                break

I don't understand why you want to use BEL as a separator rather than something more conventional, eg TAB. The BEL char may print as ^G in your terminal, but it's invisible in mine, and if you save this output to a text file it may not display correctly in a text viewer / editor.

BTW, It would have been better if you posted a Minimal, Complete, Verifiable Example that focuses on your actual printing problem, rather than all that crazy JSON parsing stuff, which just makes your question look more complicated than it really is, and makes it impossible to test your code or their modifications to it.


text:
Q: Offset CSS grid items on explicitly placed rows I'm trying to achieve the following with CSS Grid Layout:
A                    A
B  B  B  B  B  B  B  B
C  C     E  E  E  E  E
         D  D  D
         F  F  F

I can add classes in the HTML but I cannot re-order the elements or add wrapping elements.
I have almost achieved this by using explicit grid-row values. Is it possible to position the last two rows starting at the fourth column without explicitly specifying the grid-column property individually for each element? (For brevity I've kept it to 6 here but there's more in the actual layout)
Here's what I have so far. As you can see, the two rows for E and F start on column 1.
I can add grid-column: 4 to .c13 but the subsequent elements in the row flow back to column 1.

.grid {
  display: grid;
  grid-template-rows: repeat(5, 2em);
  grid-gap: 0.5em;
  text-align: center;
}

.c2 {
  grid-column: 8;
}

.c16 {
  grid-column: 4;
}

.extra1 {
  grid-row: 4;
}

.extra2 {
  grid-row: 5;
}

.global1 { background-color: #ccc; }
.intra1 { background-color: lightblue; }
.intra2 { background-color: yellow; }
.intra3 { background-color: purple; color: white; }
.extra1 { background-color: orange; }
.extra2 { background-color: #f66; }

You need a browser that supports CSS Grid Layout for this.

A

A

B

B

B

B

B

B

B

B

C

C

D

D

D

E

E

E

E

E

F

F

F

A: You can add pseudo-elements to the .grid to block out the bits you don't want to use. CSS Grid will treat the pseudo-element as a grid-item and use up the space specified.
In your case these rules should work:
.grid:before{
  content:'';
  grid-column: 1 / 4;
  grid-row: 4 / -1;
}
.grid:after{
  content:'';
  grid-column: 7 / 10;
  grid-row: 4 / -1;
}

Here's an example of it for you to play with: https://codepen.io/chrisboon27/pen/Lddpqa
I added in the text and background-color to make it easier to see what is going on, but you would just remove those.


text:
Q: Exponential vs Polynomial growth May somebody give me a prove why $n^{r} < c^{n}$  when $r \in R_{>0}$, $ c \in R_{>1}$ and $ n    \in N$ (for all $n$ at some point).

A: what is, given real $\beta > 0,$
$$ \lim_{x \rightarrow + \infty} \frac{e^{\beta x}}{x} ?$$
It is not necessary to use L'Hospital, it is enough to see that the first derivative is
$$  \frac{\left( \beta x - 1 \right) e^{\beta x}}{x^2} $$ and the second is
$$  \frac{\left( \beta^2 x^2 - 2 \beta x +2 \right) e^{\beta x}}{x^3}. $$
That is, for $x > 0,$ the second derivative is strictly positive. The original function begins with a vertical asymptote at $x=0,$ descends to a minimum at $x = 1 / \beta,$ but then increases without bound as $x \rightarrow + \infty$
With $\beta = \frac{1}{3},$ here is a nice graph for $x > 0.$


text:
Q: IEnumerable not null, but throwing a NullReferenceException on iteration I have an IEnumerable that I run a foreach on. It's throwing a null reference exception in certain cases on the foreach line, it says

ienumerable threw an exception of type 'System.NullReferenceException

if (ienumerable != null)
{
    foreach (var item in ienumerable)
    {
        ......
    }
}

I put in a null check before the foreach loop, and the iEnumerable passes the null check, but then when I run the foreach loop on it it throws the null reference exception.

A: Iterators can do just about anything when iterated, including throw exceptions. So basically, you need to know what the source is. For example, this is a non-null iterator that throw in the same way:
var customers = new [] {
    new Customer { Name = "abc" },
    new Customer { },
    new Customer { Name = "def" }
};
IEnumerable<int> lengths = customers.Select(x => x.Name.Length);

this won't fail until the second time through the loop. So: look at where the iterator came from, and how the iterator is implemented.
Purely for fun, here's another that will fail identically:
IEnumerable<int> GetLengths() {
    yield return 3;
    throw new NullReferenceException();
}

A: the items in your ienumerable are sometimes null,
try this:
    if (ienumerable != null)
    {
        foreach (var item in ienumerable)
        {
            if(item != null)
            {
               // do stuff
            }

        }
    }

here is an example to try for you guys.
        string[] testStr = new string[] { null, "", "test" };
        foreach (var item in testStr)
        {
            if (item != null)
            {
                Console.WriteLine(item);
            }
            else
            {
                Console.WriteLine("item was null");
            }
        }

        Console.ReadKey();


text:
Q: phpcassa Schema create column family PwdUrl with
    default_validation_class=UTF8Type and key_validation_class=UTF8Type and
    comparator =UTF8Type and
    column_metadata = [ {
        column_name:createdAt,
        validation_class:UTF8Type,
        index_type: KEYS
    },{
        column_name:expireAt,
        validation_class:UTF8Type,
        index_type: KEYS}
    ]

This is the schema I need to set up. Is it possible to do this using phpcassa? If not, what other options are there?

A: Yes, you can do this with just phpcassa.  You'll use the SystemManager class.  Here's an example:
<?php
require_once('phpcassa/sysmanager.php');

$sys = SystemManager("localhost:9160");
$my_keyspace = "Keyspace1";
$cfattrs = array("column_type" => "Standard",
                 "comparator_type" => "UTF8Type",
                 "default_validation_class" => "UTF8Type",
                 "key_validation_class" => "UTF8Type");
$sys->create_column_family($my_keyspace, "PwdUrl", $cfattrs);
$sys->create_index($my_keyspace, "PwdUrl", "createdAt", "UTF8Type");
$sys->create_index($my_keyspace, "PwdUrl", "expireAt", "UTF8Type");
$sys->close();
?>


text:
Q: Where to store the id of a VertexHandle in OpenMesh? I am building index and vertex buffers from OpenMesh structures which I will feed into my rendering engine. Here I iterate my elements (not shown) and create VertexHandles for each of my points and then add the face.
std::vector<Mesh::VertexHandle> vhandles;

for (... 3 triangle points) {
    vhandles.push_back(mesh.add_vertex(Mesh::Point(
        point->px, point->py, point->pz)));
}

mesh.add_face(face_vhandles);

The vertex buffer for a Point appears below and I copy the vhandles data into this struct, then build an array of these to feed to the graphics engine.
struct Point
{
        float px, py, pz;   // positions
        float nx, ny, nz;   // normals
        float cx, cy, cz;   // diffuse
}

When I build the vhandles vector above, I did not add an index/id to the VertexHandle.
I need to somewheres store and have access to the id of the point with the VertexHandle iteself. Where would I store that? I've not yet found a field for this purpose within the source of a VertexHandle, but seems like something that would be needed.

A: Although I'm still just getting familiar with OpenMesh, it seems to me like a bad practice to access any element by their index because these are internal indices that will be rearranged upon garbage collection. OpenMesh provides iterators and circulators to iterate over its elements. If you need random access, you can always store the handles associated to whatever index you want in a container. Also, there are the vertex_handle(), face_handle(), edge_handle() functions which give you mesh elements by their internal indices.


text:
Q: Use Multi Model in View Please help me to use Two Model in MVC View.
I have used the bottom lines, But it still doesn't Work:
@using HelpDesk.Models;

@model Tuple<IEnumerable<Ticket>, IEnumerable<Order_List>>

And This is my Error In Red Page:

The model item passed into the dictionary is of type
  'System.Collections.Generic.List1[HelpDesk.Models.Login]', but this
  dictionary requires a model item of type
  'System.Tuple2[System.Collections.Generic.IEnumerable1[HelpDesk.Models.Ticket],System.Collections.Generic.IEnumerable1[HelpDesk.Models.Order_List]]'.

Thanks.

A: Instead of using a Tuple you can create a new ViewModel that contains both the objects, like a container.
Like This:
public class BothViewModel
{
    public IEnumerable<Order_List> Orders { get; set; }
    public IEnumerable<Ticket> Tickets { get; set; }
}

Then, in your View, you can use the new ViewModel(BothViewModel)
@model BothViewModel

Hope this helps.


text:
Q: Rails - Facebook Omniauth - undefined local variable or method `"omniauth' for # I just installed the facebook omniauth to be used with the devise and followed the setting up process but encountered with the undefined local variable or method `"omniauth' when trying to signin with facebook account (this happens after authorizing the app on facebook)
The config of the omniauth was already placed on the devise.rb
Started GET "/users/auth/facebook" for ::1 at 2021-02-07 18:26:19 +0700
I, [2021-02-07T18:26:19.757906 #344142]  INFO -- omniauth: (facebook) Request phase initiated.
Started GET "/users/auth/facebook" for ::1 at 2021-02-07 18:26:20 +0700
I, [2021-02-07T18:26:20.451094 #344142]  INFO -- omniauth: (facebook) Request phase initiated.
Started GET "/users/auth/facebook/callback?code=xxxx" for ::1 at 2021-02-07 18:26:21 +0700
I, [2021-02-07T18:26:21.060527 #344142]  INFO -- omniauth: (facebook) Callback phase initiated.
Processing by Users::OmniauthCallbacksController#facebook as HTML
  Parameters: {"code"=>"xxxx", "state"=>"xxxx"}
Completed 500 Internal Server Error in 25ms (Allocations: 4188)

NameError (undefined local variable or method `"omniauth' for #<Users::OmniauthCallbacksController:0x000000000226f0>):

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, event: :authentication
      set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def failure
    redirect_to root_path
  end
end

Appreaciate your help

A: I don't know if this code was written in an editor that wasn't meant for code, but somehow your quotes aren't the standard "programming" quotes. Replace all occurrences of " and " with ".
In "omniauth.auth" ruby thinks you're accessing the auth" property of an "omniauth object that doesn't exist.


text:
Q: Cannot read Json value by key in JenkinsFile I am defining my environment variables in Jenkins-File.
I am using Pipeline Utility Steps Plugin to read a json file in the directory that has configuration.
When I echo out the read json file, the output is correct, it reads and prints the json file correctly.
When I try to access the value associated with a key in that json object, I am getting error: "No such property: internalCentralConsoleUrl for class: java.lang.String"
The json format config file looks life following:
{
    "activeVersion": "19.01.303",
    "internalCentralConsoleUrl": "https://11.111.111:8083/api/v1",
    "dataType": "APPLICATION_JSON"
}

I am reading that file using readJSON in the pipeline.
And in the following lines, trying to access the value inside the json object using the key.
Which gives the error I mentioned above.
pipeline {
agent any
environment {
        config = readJSON file: 'config.json'
        baseUrl = "${config.internalCentralConsoleUrl}"
        baseUrl2 = config['internalCentralConsoleUrl']
        }
stages {}
}

Both the ways I tried above to read the json value are documented in the jenkins page linked here
I cannot wrap my head around what is causing an issue in this straight forward task.
Edit1: Just corrected a formatting mistake in pipeline.

A: I copied your example and added a stage to print the variable:
pipeline {
    agent any
    environment {
        def config = readJSON file: 'config.json'
        baseUrl = "${config.internalCentralConsoleUrl}"
    }
    stages {
        stage('Test') {
            steps {
                echo baseUrl
            }
        }
    }
}

And it prints the variable correctly without any exception:
[Pipeline] {
[Pipeline] readJSON
[Pipeline] readJSON
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] echo
https://11.111.111:8083/api/v1
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline

A: After RNoB's comment above that it works fine in his Jenkins; I came to the conclusion that it has nothing to do with the pipeline and it might be:
a. Jenkins Plugin issue.
b. Jenkins itself.
c. Host where Jenkins is running.
So, I took the following approach:
a. I upgraded the plugins, and reinstalled them. This did not fix the problem.
b. I uninstalled Jenkins and removed all Jenkins related files and reinstalled it, and installed all the plugins again. This fixed the problem.
I still don't know what exactly was wrong, it just might be some file that was corrupt. I am not Jenkins expert but this solved the issue for me. Hope this will be helpful for somebody who is having similar issue.


text:
Q: Dialog is unintended vertically flipped I'm using WebGL and Chrome.
The application I created consist of several webpages.
Upon switching to a next page a dialog is popping up to indicate that a new page is being loaded.
Sometimes this dialog is vertically flipped (due to race condition?)
This (and other) dialog stay vertically flipped) when I move back and forward through the webpages.
I can solve it by zooming in the browser.
Is anyone familiar with this problem


text:
Q: Input type date is not working with some values angular 6 I have a date input of html5,where I am using date picker,but my value contains some extra characters like "2019-01-01T23-00-11" which is not appearing first time with text box,Here is the code below
app.component.html

  <input  type="date" [(ngModel)]="name" value="name">

Value: {{ name }}

app.component.ts
import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name: string = '2019-01-01T23-00-11';
  //name: string = '2019-01-01';
  ngOnInit() {

  }

}

A: If you change the date input to datetime-local, and then change your string to have colon separated time instead of hyphen separated time, you will work. This will work in Chrome. Haven't tested all other browsers.
// In the html
<input  type="datetime-local" [(ngModel)]="name" value="name">

// In app.component.ts
name = `2019-01-01T23:00:11`

If you do this, the date and time will appear in the browser.

A: You can format the value before you get it
getDate(){

   let d = new Date(this.name)

     return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`

   }

HTML
<input  type="date" [(ngModel)]="getDate()" value="name">


text:
Q: Discontigious Selection is not supported error in google chrome and chromium I am working on a bookmark app where i have to store the user's selected keywords or words or content. I am using the createRange() and addRange() javascript methods to create the range and then find out the selected elements/contents by the user. The code i written for this is as follow.

    Select some content on this page and use the buttons below.

    <button onclick="StoreSelection ();">Store the selection</button>
    <button onclick="ClearStoredSelections ();">Clear stored selections
</button>
    <button onclick="ShowStoredSelections ();">Show stored selections</button>

This code is working perfectly on Firefox. I am able to select multiple things one by one and able to show the selected content again but on chrome and chromium i am getting Discontiguous selection is not supported. error when i store more than one elements in range array and click on show stored selections button.
Help will be appreciated. And please suggest me if there is some other alternatives do accomplish this bookmarking task.

A: Write
window.getSelection().removeAllRanges();

immediately before creating range.
https://bugs.chromium.org/p/chromium/issues/detail?id=399791

A: Here's the only possible way of doing this that I was able to come up with:
Wrap the selection in ....
But note:

*

*Obviously, you have to remove those spans again as soon as anything else is selected, but that shouldn't be too difficult. However, you should use window.onmousedown for that rather than window.onclick, because onclick is fired after any button is pressed, so when pressing your "Show stored selections" button, a new selection will be created, thus destroying the one that was supposed to be captured.

*Removing or replacing any elements in which a stored selection starts or ends will invalidate that selection, so when clicking "Show stored selections", nothing will show up.

*If the selection spans over multiple elements, it needs to split up into one selection for each element, otherwise inserting the span will either fail or cut other elements (like buttons) in half.

The following code (fiddle) is the best I was able to do:

var storedSelections = [];
var simulatedSelections = [];

window.onmousedown = clearSimulatedSelections;

function storeSelection()
{
    if(window.getSelection)
    {
        var currSelection = window.getSelection();
        for(var i = 0; i < currSelection.rangeCount; i++)
        {
            storeRecursive(currSelection.getRangeAt(i));
        }
        currSelection.removeAllRanges();
    }
    else
    {
        alert("Your browser does not support this example!");
    }
}

function storeRecursive(selection, node, started)
{
    node = node || document.body;
    started = started || false;
    var nodes = node.childNodes;
    for(var i = 0; i < nodes.length; i++)
    {
        if(nodes[i].nodeType == 3)
        {
            var first = nodes[i] == selection.startContainer;
            var last = nodes[i] == selection.endContainer;
            if(first)
            {
                started = true;
            }
            if(started)
            {
                var sel = selection.cloneRange();
                if(!first)
                {
                    sel.setStartBefore(nodes[i]);
                }
                if(!last)
                {
                    sel.setEndAfter(nodes[i]);
                }
                storedSelections.push(sel);
                if(last)
                {
                    return false;
                }
            }
        }
        else
        {
            started = storeRecursive(selection, nodes[i], started);
        }
    }
    return started;
}

function clearStoredSelections()
{
    storedSelections = [];
}

function showStoredSelections()
{
    if(window.getSelection)
    {
        var currSelection = window.getSelection();
        currSelection.removeAllRanges();
        for(var i = 0; i < storedSelections.length; i++)
        {
            var node = document.createElement("span");
            node.className = "highlight";
            storedSelections[i].surroundContents(node);
            simulatedSelections.push(node);
        }
    }
    else
    {
        alert("Your browser does not support this example!");
    }
}

function clearSimulatedSelections()
{
    for(var i = 0; i < simulatedSelections.length; i++)
    {
        var sec = simulatedSelections[i];
        var pn = sec.parentNode;
        while(sec.firstChild)
        {
            pn.insertBefore(sec.firstChild, sec);
        }
        pn.removeChild(sec);
    }
    simulatedSelections = [];
}
.highlight
{
    background: Highlight;
}
Select some content on this page and use the buttons below.

<button onclick="storeSelection();">Store the selection</button>
<button onclick="clearStoredSelections();">Clear stored selections</button>
<button onclick="showStoredSelections();">Show stored selections</button>

It works in Firefox, Safari and Chrome, but has the following shortcomings:

*

*Selections over multiple lines don't select the blank area between the end of the line and the border of the parent element, like actual selections do.

*Sometimes when starting a selection at a point before the start of a stored selection, displaying them will merge the ranges, so the text in between is selected too. Sorting the array of stored selections doesn't seem to help.

*In Safari, the tab crashed multiple times with a segmentation fault when selecting multiple lines and ending/starting a selection in the middle of a button's text.

However, I doubt that anything better is possible in browsers other than Firefox, but even Firefox has a ticket to drop discontiguous selections.

A: FYI I was getting a similar error when rolling my own "copy to clipboard" feature. I'm not going to address OP's provided code, but I'll tell you how I fixed it in my own code.
Reproduce:

*

*Copy some other text on the page to the clipboard, e.g. "foo".

*Paste the text somewhere. It outputs "foo".

*Click your "copy to clipboard" button, which copies e.g. "bar".

*Paste the text somewhere.

Expected:
"bar" is outputted.
Actual:
"Discontiguous selection is not supported"
Fix:
Call window.getSelection().removeAllRanges() at the start of your "copy to clipboard" event handler. "Discontiguous" means "not connected". So my guess is that the browser copies the first range (the node containing "foo"), and then gets angry when you try to select another range that is not next to the first node.