text:
Q: How is $\mathbb{F}_4$ generated? I know $\mathbb{F}_4$ is a field while $\mathbb{Z}/(4)$ is just a ring. So how is $\mathbb{F}_4$ generated?
Complement: So what are the elements like in $\mathbb{F}_4$ like? Are they $\{0,1,x,x+1\}$? Is every field $\mathbb{F}_k$ has $k$ elements no matter whether $k$ is a prime?

A: As Nishant said $\mathbb{F}_4\approx \mathbb{F}_2[X]/(X^2+X+1)$.
Since this polynomial ($p:=X^2+X+1$) has no solution in $\mathbb{F}_2$, you can show that extending $\mathbb{F}_2\to\mathbb{F}_2[\theta]\subset K$ where $\theta$ is a solution of $p$ in an algebraic closure $K$, you get that $\mathbb{F}_4$ and these two fields are isomorphic. Notice that all fields of 4 elements are isomorphic.

A: The answer of @MarceloBielsa is perfect, but I like an approach like what OP was working towards: the elements of $\mathbb F_4$ are $\{0,1,\omega,\omega+1\}$, where $\omega^2=\omega+1$, $(\omega+1)^2=\omega$, and $\omega(\omega+1)=1$. I think that that's enough for filling in the multiplication table.


text:
Q: How to output different audio channels to two different output devices So I have a bit of a dilemma. I recorded a four channel audio file with a zoom h6 and I want to output the four channels to four different speakers. I have two stereo amplifiers set up and two soundcards but I need to know if there's a program for that can simultaneously output the channels to the different sound cards. The solution could be for Windows Mac or Linux because I own computer running all three. I hope this makes sense.

A: Beginning in build 1803 of Windows 10, you can specify specific outputs per audio channel. No third-party software required.
In Settings > Sound > App Volume and Device Preferences, you are presented a selection of all currently active audio channels on the device and the ability to select the desired output of each of these:

Image courtesy of GroovyPost.com: https://www.groovypost.com/howto/new-sound-settings-windows-10-1803-april-update/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where can I find the log files for mounting disks? I understand if I boot from a live cd  I can see all the system logs under System > Administration > File Log Viewer
I have a major error with a disk not mounting and I want to trace i tback to the last time it did work and what may have corrupted the ext4 filesystem on it.
So within the File Log Viewer Where do I start examining?

A: You can find aditional information in syslog
grep 'Mounted' /var/log/syslog*

or find mounted and unmounted logs
grep 'Mounted\|Unmounted' /var/log/syslog*

A: I'd guess /var/log/dmesg
You can find all logs that mention mounting or ext4 like this:
grep -e mount -e ext4 -lR /var/log 2> /dev/null

dmesg seemed to be the most relevant to me. And there are archived versions (dmesg.*).


text:
Q: Error Uploading APK File to Google Play Console because it Keep Saying I Have the Wrong Certificate I am using Google Play Console to upload my app. Whenever I upload the APK file, this is the message that I keep getting:
You uploaded an APK that is not signed with the upload certificate. You must use the same certificate.
[ SHA1: 88:50:D6:16:J3:3B:94:47:03:10S:33:A4:0Z:S6:8F:4L:21:B3:Q3:0V ]
and the certificate used to sign the APK you uploaded have fingerprint:
[ SHA1: 22:1X:1K:22:D2:11:Z7:V0:22:1Q:B4:S3:K7::H6:NN:NN:6Y:32:W7 ]
I need help with this. It is a big set back for me. Thanks.
Note well: These are Fake Certificate Numbers that are just used for illustration purposes. :)
Looking forward for substantial help. Thanks again.

A: Did you enroll in "App Signing by Play" (you can verify this from the App Signing page of the Play Console)?
If yes, you may have been prompted to create an "upload key" at this time. That's the keystore you should be using to sign APKs uploaded to the Play Console.
If no, or if you haven't created an upload key, you need to upload an APK signed with the same keystore as the first APK you uploaded. Have you reinstalled Studio and created a new keystore by any chance?
Note that it's possible to have multiple keys stored in the same keystore as well, so make sure you enter the alias of key correctly as well. In Studio, the default is "key0".


text:
Q: java : File.getAbsoluteFile().exists() v/s File.exists() I want to check the Folder Existance before creating the new one.
For that which method I need to use :
File folder = new File(PATH);

there are two method for checking the same
1) folder.getAbsoluteFile().exists()
    OR
2) folder.exists()
Which one to use?
Thanks for looking here.

A: Under normal circumstances, there is no difference between the result of those two expressions. So, use the simpler:
folder.exists()

A: First of all read Oracle docs on exists. And getAbsoluteFile.
Answer yourself what does getAbsoluteFile do?
Then answer yourself do you need to get the absolute form of of your folder abstract pathname? Does it help you in anything?
If not, use simpliest easy to write easy to read method folder.exists().
In coding we are always trying not to do unneccesary thing, to keep our code fast, clean, readable, easy to understand and update.

A: Generally calling folder.exists() is preferred as it works on abstract pathname.
On the otherhand getAbsoluteFile() is equivalent to new File(this.getAbsolutePath()), which returns the absolute form of this abstract pathname.

A: You can use both conditions as well.
Additionally You can refer this link..
How to create a file -- including folders -- for a given path?
Hope this will help !

A: folder.exist() check if the directory exist at the abstract path, it returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.
folder.getAbsoluteFile().exists() in this case it returns the absolute form of this abstract pathname. Equivalent to new File(this.getAbsolutePath()).exist() and checks if folder exists at specified absolute path.
so you can use either of them, just the difference is abstract path and absolute path, but to my openion you should go with folder.exist() since it will avoid creating new File.


text:
Q: How to uninstall a program whose content already deleted? i'm new to Ubuntu Really need help in this problem
Now i installed old version of a program that used a port for its processes , i deleted the folder of the program by right click .. remove and didn't know that it has any files in other place !! and didn't know that may be a process using port
i installed new version of the program and every time i ran the program , old version folder created and empty !!
Now i want to delete old version folder completely in right way
i searched for PID of the old version but it gave nothing !! sure because i deleted the folder of the program , HOW can i solve this

A: first run sudo apt-get autoremove in case there are some non used packages left
then sudo rmdir /path/to/folder inorder to ReMove the dir of the folder.


text:
Q: Mostrar layout diferente wordpress PHP si hay o no hay imagen destacada Cómo puedo hacer para mostrar un artículo con un layout totalmente diferente para los artículos que tengan imagen destacada y otro layout, para los artículos que no tiene imagen destacada

A: Puedes hacer algo así dentro de tu template:
single.php
<?php

get_header();

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        if ( has_post_thumbnail() ) {
            get_template_part('views/post-with-featured-image');
        } else {
            get_template_part('views/post-without-featured-image');
        }
    }
}

get_footer();

views/post-with-featured-image.php

<?php the_title(); ?>

<?php the_post_thumbnail('full'); ?>

views/post-without-featured-image.php

<?php the_title(); ?>


text:
Q: Cannot override provider configuration error in installing DC/OS via Terraform on azure Working on setting up DC/OS on Microsoft Azure using Terraform.
I'm using the main.tf provided in the official documentation. Every time I run terraform init
I get an error:
Error: Cannot override provider configuration
│
│   on .terraform/modules/dcos/main.tf line 138, in module "dcos-infrastructure":
│  138:     azurerm = azurerm
I have authenticated via az CLI specifically via the command
az login --use-device-code
My terraform version is:
Terraform v1.1.9
on linux_amd64
How can I resolve this?
my attempts to comment out the providers still produces this error.

A: If you are using module in you main.tf file, You have to use `Provider Aliases in main file
To declare multiple configuration names for a provider within a module, add the configuration_aliases argument:
You can take reference of this aws and edit it for azure accordignly.
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 2.7.0"
      configuration_aliases = [ aws.alternate ]
    }
  }
}

Passing Providers Explicitly
main.tf
provider "aws" {
  alias  = "usw2"
  region = "us-west-2"
}

# An example child module is instantiated with the alternate configuration,
# so any AWS resources it defines will use the us-west-2 region.
module "example" {
  source    = "./example"
  providers = {
    aws.alternate = aws.usw2
  }
}

You can refer this document for information, How to use provider when using module in main.tf


text:
Q: How to set the value of UILabel in iphone? I'm doing this to set the value in UILabel:
NSMutableDictionary *responseDict = [responseString objectFromJSONString];

self.pkrLbl.text= [responseDict objectForKey:@"amount"];

and I'm getting this error:
[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x9440310

2013-05-16 15:23:34.281 EasyLoadPakistan[20341:19a03] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x9440310'
Please help me how can I set value in UIlabel

A: A UILabel expects a string (specifically NSString or one of its subclasses), and you are passing it a number (an NSNumber instance).
Convert the number to a string first, then set the label to that string:
NSNumber *n =  [responseDict objectForKey:@"amount"];
NSString *stringVersion = [n stringValue];

self.pkrLbl.text = stringVersion;

If you prefer to have it all on one line, you can omit the variables and just chain the stringValue call. The approach shown above tends to facilitate debugging, though (you can for instance set a breakpoint and have a look at your variables).


text:
Q: Check if file is JPEG, PDF or TIFF How would i check that a file is either jpeg, pdf or tiff? And I mean actually checking, not just from mime type and file extension.
I have access to the raw file data (this check is part of an uploader) and i need to verify that the files are either jpeg, pdf or tiff. I assume I would have to check for some sort of headers in the files but I have no idea what to look for and where to start.

A: Exif_imagetype is very useful for this: http://us2.php.net/manual/en/function.exif-imagetype.php
It scans the initial bytes of the file to determine the graphic type.  It supports a large number of graphic formats (and returns false if it doesn't recognize the format).

A: This can be tricky since all files must follow a certain kind of ISO standard with the "magical number" present, which basically is a "header" for the format.
I found this wiki-page about different signatures: http://en.wikipedia.org/wiki/List_of_file_signatures
So in the best case scenario you just need to validate these first bytes.

A: You need to implement byte sequence tests.
Here is a guide to checking byte sequences for the most common image formats.

A: If you have access to the raw file, you can check the file header for its magic number. This number define the type of file.

A: to check for image types you can use the exif_imagetype function.
for pdf: you have to open the file and read the first bytes and look if it starts with '%PDF'
$fp = fopen($pdf, 'r');
if(fgets($fp, 4) == '%PDF')
{
    ... is pdf
}
fclose($fp);

A: There is no sure fired way to be certain but the first few binary bits of a file are its signature/fingerprint for the file handlers to test. see https://en.wikipedia.org/wiki/List_of_file_signatures
Every file type can vary considerably and some allow for variable / shifting headers, but with a degree of uncertainty (At one time PDF did not mandate the 40 bit signature to be first) we can assume the following hex values sometimes erroneously called "Magic Numbers" as representing the start of each bit stream.
So in general to answer the requested types

*

*FF D8 (ÿØ) would be a Jpeg (EXCEPT JP2000=FF 4F or 00 00) in raw binary or /9j/4 in Base64 format

*25 50 44 46 2d (%PDF-) would be the 40 bit signature of a PDF or JVBER in Base64 format

*89 50 4E 47 (‰PNG) would be PNG in raw binary or iVBOR in Base64 format

just for good measure here is related older GIF sequence

*

*47 49 46 38 (GIF8) and that's R0lGO as Base64 also we can see the first 8 bits are 01000111 for G

Thus in ALL the above cases just the first "8 bit / byte" would be a very good indicator, no need for Magic strings, but with Zip/###X such as docX pptX cbzX xlsX they ALL have the same Magic Number

*

*50 4B (PK) base64 = UEsDB
Finally the last requested above was Tif(f) which can be two types, Intel or Motorola thus you need to test for

*

*49 49 2A 00 (II* ) base64 = SUkqA

*4D 4D 00 2A (MM *) base64 = TU0AK


text:
Q: Handling different iphone screen sizes/resolution for background images I would like to better understand the iphone resolutions etc.
I have an application that has a basic buttonView and logoView. I have output the height of the logoView which will auto fit in height depending on screen size.
For the iphone5 I have 318 to work with.
For the iphone4(<) I have 230 to work with.
My question is, how should I handle the image used for the background of this view. Would I create one three separate images for the following?
-iphone3 etc (230)
-iphone4 retina (230 size, @2)
-iphone5 retina (328 size, @2)
Or would I create only the 2x 230 images, and can I stretch the image to 318 when an iphone5 is used and more space is available?

A: It all depends on your image:

*

*If your Image can be stretched, UIImageView will do all the work.

*If only a part of you image should be stretched you should use this:

*

*imageView.image = [imageView.image resizableImageWithCapInsets:UIEdgeInsetsMake(top, left, bottom, right)];

*If your image can't be stretched you should then do different images for the phones and change them in runtime.

UPDATE
For the last point you could do something like this in your viewDidLoad method:
BOOL isIPhone = [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone;
BOOL isIPhone5 = isIPhone && ([[UIScreen mainScreen] bounds].size.height > 480.0);
if (isIPhone5) {
   imageView.image = [UIImage imageNamed:@"iphone4image.png"];
} else {
    imageView.image = [UIImage imageNamed:@"iphone5image.png"];
}

A: iOS 8 has different size classes for different screens. It's explained very well here. Every iOS Developer should go through this link:

A: If you want to make this a little more succinct you can account for longer screen sizes with a macro.
#define ASSET_BY_SCREEN_HEIGHT(regular, longScreen) (([[UIScreen mainScreen] bounds].size.height <= 480.0) ? regular : longScreen)

Example usage:
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.splashScreenImageView.image = [UIImage imageNamed:ASSET_BY_SCREEN_HEIGHT(@"Default", @"Default-568h")];
}


text:
Q: What equation can be used to solve an ideal string/membrane in a non-vacuum medium? I'm interested in the eigenmodes of the membrane for various mediums, such as vacuum, air, water, etc., which impose a damping effect on the membrane.
This cannot be done by merely changing the value for the wave propagation speed, c, because this value belongs to the string/membrane itself, and not to the medium around it.
Can the influence of medium be incorporated in the wave equation for vibrating string/membrane?


text:
Q: Expo / Android Simulator 'Error opening simulator' I just installed Android Studio, created and ran a virtual device and have run expo, which successfully established the web server.
However, when I click on 'Run on Android Device/emulator' in the browser, I simply get en error message which says 'Error opening simulator. Check metro logs for details'. There is no logged output on the screen or in the console.

After a few seconds, I get the following message from Android Studio:

If I try to launch Android in the console by pressing 'a', I get the following error:

EDIT: I found there were 2 adb processes running in the task manager. I killed both and restarted expo, which now shows a different error:

Any idea on how I can resolve this please?
Thanks

A: So I found the solution myself.

*

*I completely removed Android Studio (see here for windows: How to completely uninstall Android Studio from windows(v10)?)

*Reinstalled Android Studio

*Started the Android Device Emulator

*Ran expo start

*Entered 'Tunnel Mode' via the browser (see screenshot below)

*Clicked 'Run on Android Device'

and bingo it worked. If you have trouble, be sure you kill all adb processes before you start the process and try again.

A: I found a working solution on my system.
1- I deleted all of the emulators from android studio-

2- Then Tools --> SDK manager --> Android SDK and check the box in front of 'show package detail' and Uncheck the box for Google APIs Intel x86...

Then open your system's sdk path (Android SDK Location), (for example, my path is C:\Users\userName\AppData\Local\Android\Sdk) open the folder and delete the folders inside the system image folder.
3- Now in android studio again, Tools --> SDK manager --> Android SDK, and check the box in front of 'show package detail'. Look for Google APIs Intel x86...(check the box) under Android 12 (S), click apply to install again.
4- Tools--> Device manager --> create Device. Set up a new emulator device
connect it with Metro Bundler.
Cheers, it worked for me without uninstalling the entire android studio.


text:
Q: what to do when strong consistency is required, but entity (might) need to be shared across boundary I'm currently developing an infrastructure as a service application. I define 3 bounded context Billing, Cloud and Hosting. There's a wallet entity (or aggregate how should I define it?) which may appear in several bounded context. Billing is interested in transaction_date, invoice_id while Cloud and Hosting are interested in balance (whether a user has enough balance to buy a service).

So since each bounded context interested in difference fields here's my first design. I use upstream/downstream pattern to replicate wallet entity from Billing into Cloud and Hosting using event message (eventual consistency).  Btw there's a case where a user buys hosting and cloud at the same time. so both cloud service and hosting service check if wallet has enough balance using the replicated data. Let's say that wallet doesn't have enough balance to buy both cloud and hosting at the same time. so now race condition occurs. Domain expert says that race condition like this should never occur. So how do I properly design bounded context/context map in this case.

Edit: I'm also thinking of merge the Cloud and Hosting context together and name it Infrastructure context, but that would be hard to scale.

A: If the domain expert says a race condition like this should not occur, they are by implication saying that if the cloud/hosting contexts cannot be sure that there are funds in the wallet they should reject the sale.  The only context which can have a strongly consistent view of a wallet's balance is the billing context.
The cloud and infrastructure contexts don't really care about the balance of the wallet.  They care about the balance available to them.
This suggests that a reservation pattern is applicable:

*

*someone wants to spend X units from wallet Y in context Z

*context Z checks if the balance of wallet Y available to it is greater than X

*if it is, it deducts X from its view of the balance of wallet Y available to it and we're done (presumably something will later generate a billing event)

*if it's not, it communicates a desire to reserve enough (A) of wallet Y to the billing context; it might reject the spend attempt or just wait... at some point that someone will retry the spend attempt (presumably there's a reason they wanted to spend...)

*the billing service checks if there's enough unreserved balance in wallet Y to satisfy the reservation

*if there isn't, nothing needs to happen

*if there is, an event saying that A units of wallet Y is now reserved for context Z is published

You can elaborate on this with eventual unreservations (in which case, to prevent double-spend, you want the source of truth for unreservations in context Z to be context Z: the failure mode must always be "lose the sale").


text:
Q: How to submit form using other controller in Magento 2 I have a form in phtml file. There are 2 fields in that username and password. I want to set that username and password value from other controller and submit that form.
I tried using this below way :
$this->request->setPostValue('username','admin');
$this->request->setPostValue('password','admin@123');

But, Still I can't receive value in $this->getRequest()->getPost('username');
How can i do that?
Any help would be appreciated.
Thanks.


text:
Q: Artisan says database not found I'm working on a brand new laravel application for learning laravel.
I've done the following (I'm following this tutorial):

*

*Created new application using laravel new test_project_2

*Setup the .env file

*Created a database called laravel

*Run php artisan migrate

This is my .env file:

This is what I get:

As you can see, I can use the "laravel" database perfectly well when I'm logged into Mariadb via terminal. The website also renders absolutely fine. I did run the SQL command - SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations and table_type = 'BASE TABLE' but I got the message ERROR 1054 (42S22): Unknown column 'laravel' in 'where clause'
Note - I've worked on other dummy laravel projects last week and didn't face any problems, although admittedly I'm not sure if I ran the php artisan migrate command for those (wasn't required, but I might have run it just cause I kept seeing it).

*

*Why is this problem happening?

*How do I fix it?

A: Run the below command and try migrate command
php artisan cache:clear
php artisan config:clear

A: can you try creating your database with below and then try migration.
mysql -u root -p

create database [DB name];

use [DB name];

Then do migration:
php artisan migrate

Also make sure you have entered correct database name & credential.

A: Solved this by changing the DB_HOST values from 127.0.0.1 to localhost.
Anyone know why this works? Beats the heck out of me.


text:
Q: startdate and endDate filter based on dates in laravel I want to add a start and end date filter. I have products that have a start date and end date. Suppose I apply a filter of the start date as 1 may to end date 30 May. In that case, those products who have a start date from 1 may are coming. But, I also have products which are used from 1 April to 30 May. These products also come because these products are used in April month also. But, due to the start date, these products are not coming.
I tried this
    $products->whereBetween($productUsedDate, [$startDate, $endDate]);

but, it doesn't return anything.


text:
Q: Mongodb get specific value by using corresponding id? {
  "_id": 123,
  "username": "user123",
  "password": "pass123",
}

I want to search the database by id ("123") and get the corresponding username value ("user123") in Mongodb, but I really can't find a solution online.
Doing .find( { _id: 123 }, { } ); returns ALL of the fields, where as I am only looking for whatever string the corresponding "username" field holds

A: You can pass the fields that should be selected as below to the query
Model.find({_id: 123}, 'username -_id', (err, data) => {
  console.log(data);
})

_id will be always present in the result. Can exclude by adding -_id

A: Are you creating _id on your own? If not then do it like this:
.find({ _id: ObjectId("THE_ID") }, { username: 1 })

Usually, when you create a document, MongoDB automatically creates _id for you which is a hexadecimal string (type is ObjectId) and looks like this: "507f1f77bcf86cd799439011". The above query would work by this type of _id.
You can also assign your own _id. If your assigned id is not a type of ObjectId then a normal find query should work. But, remember, if _id is a string you have to search like a string, not as a number.


text:
Q: Show that the tangent only touches the graph in one point. Let $f: \mathbb R\to \mathbb R$ be such that $f'$ is increasing. Show that for all $x$ the tangent line through the point $(x, f(x))$ only touches the graph in that point.
So I'm kinda stuck with this problem. I know that if $f'$ is increasing then $f''>0$ and I suppose I have to use that somehow. Maybe a mean value theorem? I don't know.
Thanks

A: Hint: Let $x_0 \in \mathbb R$ So the tangent line at $x_0$ is given by
$$y = f'(x_0) (x  - x_0) + f(x_0)$$
So you need to show that for all $x$, $f(x)> f'(x_0) (x  - x_0) + f(x_0)$.


text:
Q: SQL Server connection using local application I have a simple question I believe. Because I was given a task to analyse data insertion into a SQL Server database and I'm doing it on the server (both DB and client application are installed on the same machine) if there is any chance that this client application connect to the server through the network?
This question has been raised after I repeatedly saved data from the application and at some point the normal 30-45ms time of calling the stored procedure went up to 90 seconds (same data set). I'm just wondering what may be the cause of this situation. I pointed out the network, because the server itself has had performance checks and it works properly.


text:
Q: how to solve this div overlay problem in css How to solve div overlay problem here I've one div in this div I've added two class col-sm-6. But when I am checking responsive it will going over of the div. I don't know how to solve. can anyone please help me.
I've attch the image of the output you can see :)

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Showing 1 to 6 of 6 entries

        <button class="btn btn-link previous">Previous</button>
        <button class="btn btn-info number">1</button>
        <button class="btn btn-link next">Next</button>

A: have found mobile grid class (col-xs-12) missing. Please try below snippet.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

Showing 1 to 6 of 6 entries

                    <button class="btn btn-link previous">Previous</button>
                    <button class="btn btn-info number">1</button>
                    <button class="btn btn-link next">Next</button>

A: you should set the div "col-12" for mobile size in bootstrap4."col-sm-6" don't work for size less than 557px.and make your div's "float" right.

.float-right{
  float:rigth !important;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Showing 1 to 6 of 6 entries

        <button class="btn btn-link previous">Previous</button>
        <button class="btn btn-info number">1</button>
        <button class="btn btn-link next">Next</button>


text:
Q: Best way to cause re-renders when non-state variables change I have a separate data model object that I'm passing into UI components as a prop. I need portions of the UI to re-render when certain properties in the model object change. What's the best way of achieving this?
Do I create a dummy counter state and send the setState function into the data model to increment whenever I need the UI to change? This seems clunky and difficult to modularize for mapping certain changed properties to certain portions of the UI that need to be rerendered.


text:
Q: How to Rename or Move Rails's README_FOR_APP When I run rake doc:app in my Rails application root, the API docs are generated using /doc/README_FOR_APP as the home page. I would like to add a .rdoc extention to that file so it is properly rendered on GitHub. Even better, I would like to move it to the app root (/README.rdoc). Is there a way to do this in my Rakefile by modifying the included rake/rdoctask task? Is there some place it looks for the name of the home page file that can be modified? Or do I have to write a new Rake task?
Bonus question: what is the logic behind the two separate files /README and /doc/README_FOR_APP for Rails applications? Why not just one?

A: Rails rdoc task is in <rails gem folder>/lib/tasks/documentation.rake
to do what you want, take the :app task and alter it, putting it in a .rake file in your app's /lib/tasks
#clear the doc:app task et al
Rake::Task["doc:app"].clear
Rake::Task["doc/app"].clear
Rake::Task["doc/app/index.html"].clear

namespace :doc do
  desc "Generate documentation for the application. Set custom template with TEMPLATE=/path/to/rdoc/template.rb or title with TITLE=\"Custom Title\""
  Rake::RDocTask.new("app") { |rdoc|
    rdoc.rdoc_dir = 'doc/app'
    rdoc.template = ENV['template'] if ENV['template']
    rdoc.title    = ENV['title'] || "Rails Application Documentation"
    rdoc.options << '--line-numbers' << '--inline-source'
    rdoc.options << '--charset' << 'utf-8'
    rdoc.rdoc_files.include('app/**/*.rb')
    rdoc.rdoc_files.include('lib/**/*.rb')
    rdoc.rdoc_files.include('README')
    rdoc.main = 'README'
  }
end

I'm not sure if that is exactly it, but play around with it and look at the rdoc task docs for more info.

A: To do what you want:
The README_FOR_APP file is created when creating a new Rails application. That code is in rails-#.#.#\lib\rails_generator\generators\applications\app\app_generator.rb.
To add a suffix and change the location for all of your Rails apps, you can modify the method to be:
def create_documentation_file(m)
  # was m.file "doc/README_FOR_APP", "doc/README_FOR_APP"
  m.file "doc/README_FOR_APP", "README_FOR_APP.rdoc"
end

Then, you need to modify the Rake documentation task to include this file rather than the old one, in  rails-#.#.#\lib\tasks\documentation.rake:
Rake::RDocTask.new("app") { |rdoc|
  ...
  rdoc.rdoc_files.include('README_FOR_APP.rdoc') # was 'doc/README_FOR_APP'
}

Regarding the logic of separate `README_FOR_APP` and `README` files:

*

*README_FOR_APP, as the name implies is documentation for
your specific Rails application, it concerns
the classes and methods that you will
have written.

*README is general documention for all Rails applications describing the structure
of a Rails application and some web server settings. It's at a higher-level than README_FOR_APP.

However...
As a tip, I would advise you to keep both files and not rename them (don't forget Rail's convention over configuration aspect). Any Rails developper will expect these files to be there, and renaming them might make things more complicated.
This convention might also be used by your IDE. For example, I use Netbeans, and the Rails project view is pre-configured to display certain files. If you move your README_FOR_APP file to the root directory, NetBeans will not display it in project view, you will have to use file view, or modify the project view (don't know if that's even possible).

A: If you create same task in your local app folder in, say, lib/tasks/doc.rake and define same task like this:
namespace :doc do
  task :app do
    # some code that adds rdoc extension
  end
end

then this task would be run right after rails' built-in task. Hence you wouldn't have to mess with rails sources and still accomplish your goal.


text:
Q: Sql error-int is incompatible with date create table TCS_Employee
(
Emp_name varchar(30),
Emp_id int identity(1,1)primary key,
Emp_Sal money not null,
Joining_data date,
login_date datetime,
Domain varchar not null
)

insert into TCS_Employee
(Emp_name,Emp_Sal,Joining_data,login_date,domain) values
('Varsha',50000,2015-01-05,GETDATE(),'retail')

please help in resolving the below error

error-Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with date

A: The date needs to be in quotes, otherwise it is treated as an integer.
Change 2015-01-05 to '2015-01-05'
Also, you should set to length of the domain column (like Domain varchar(50) not null or w/e length is appropriate for your needs).
Omitting the length is a bad practice and can give unexpected results as different databases default to different lengths and for some the length is mandatory (I believe it is for MySQL).

A: 2015-01-05 is actually performing the arithmetic operation of subtraction and hence, the result is an int, not a valid date format.
use : '2015-01-05'

A: I think you missed the quotes:
 INSERT INTO TCS_Employee
    (Emp_name, Emp_Sal, Joining_data, login_date, domain)
    VALUES
    ('Varsha',50000,'2015-01-05',GETDATE(),'retail');


text:
Q: Loops introduced by ORM Reduces Performance drastically I have a table as shown below. It has accounts of type Fixed and Savings. I need to update the status of all accounts of user 1. There are 10000 accounts for this user. Essentially the logic would be as shown in the following SQL Stored Procedure Script. The script takes only less than 1 second to execute (83 milli seconds).
But when I converted it to a ORM using LINQ to SQL it takes more than 3 minutes (204814 milli seconds).  It is at least 240,000% slower.
Is there a pattern in LINQ to SQL (or other ORM) that will help to overcome this performance hit?
What can force it to do a  update in one go to database?
Note: I am aware of calling stored procedures from LINQ. I don't see that as ORM and not an option for me.

Manual Stored Procedure Script
DECLARE @UserID INT
DECLARE @StatusForFixed VARCHAR(50)
DECLARE @StatusForSavings VARCHAR(50)

SET @UserID = 1
SET @StatusForFixed = 'FrozenFA11'
SET @StatusForSavings = 'FrozenSB22'

UPDATE BankAccount
SET Status =
        CASE
            WHEN BankAccount.AccountType='Fixed' THEN @StatusForFixed
            WHEN BankAccount.AccountType='Savings' THEN @StatusForSavings
        END
 WHERE  AccountOwnerID=@UserID

LINQ Generated Code Sample
Note: This type of statements happen 10000 times

UPDATE [dbo].[BankAccount]
SET [Status] = @p3
WHERE [BankAccountID] = @p0
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [3585]
-- @p3: Input NChar (Size = 10; Prec = 0; Scale = 0) [FrozenSB]

CODE after applying ORM
public class BankAccountAppService
{
    public RepositoryLayer.ILijosBankRepository AccountRepository { get; set; }

    public void FreezeAllAccountsForUser(int userId)
    {
        IEnumerable<DBML_Project.BankAccount> accounts = AccountRepository.GetAllAccountsForUser(userId);
        foreach (DBML_Project.BankAccount acc in accounts)
        {

            acc.Freeze();

        }
        AccountRepository.UpdateAccount();

    }

}

public class LijosSimpleBankRepository : ILijosBankRepository
{
    public System.Data.Linq.DataContext Context
    {
        get;
        set;
    }

    public List<DBML_Project.BankAccount> GetAllAccountsForUser(int userID)
    {
        IQueryable<DBML_Project.BankAccount> queryResultEntities = Context.GetTable<DBML_Project.BankAccount>().Where(p => p.AccountOwnerID == userID);
        return queryResultEntities.ToList();
    }

    public List<T> GetAllAccountsofType<T>() where T : DBML_Project.BankAccount
    {
        var query = from p in Context.GetTable<DBML_Project.BankAccount>().OfType<T>()
                    select p;

        List<T> typeList = query.ToList();
        return typeList;

    }

    public virtual void UpdateAccount()
    {
        Context.SubmitChanges();
    }

}

namespace DBML_Project
{

public  partial class BankAccount
{
    //Define the domain behaviors
    public virtual void Freeze()
    {
        //Do nothing
    }
}

public class FixedBankAccount : BankAccount
{

    public override void Freeze()
    {
        this.Status = "FrozenFA";
    }
}

public class SavingsBankAccount : BankAccount
{

    public override void Freeze()
    {
        this.Status = "FrozenSB";
    }
}
}

REFERENCE

*

*Pass List as XElement to be used as XML Datatype parameter

A: You are comparing two wildly different scenarios:
1: running a script locally on the SQL server, a single set-based UPDATE
2: fetching 10,000 records over the network, updating each, submitting each individually
You can improve 2 a bit by deferring the SubmitChanges() into one single batch of 10,000 rather than 10,000 batches of 1 (just: don't call SubmitChanges() until the end), but that still involves sending the details of 10,000 records in two directions, plus all the overheads (for example, SubmitChanges() might still choose to do that via 10,000 individual calls).
Basically, object-based tools are not intended for bulk updates against records. If the SP works, use the SP. Maybe call the SP via a data-context, just for convenience of it adding the method/parameters/etc.

A: You can still execute your stored procedure / custom SQL script from your application. You can even map the procedure in your Linq-to-sql model so that you don't need to open connection and create command manually.
I'm not exactly sure if Linq-to-sql always executes each modification command in separate roundtrip to database but I guess it does (at least in most cases). EF does it always. NHibernate has better support for such operations because it has command batching.
What you showed here is not batch update (single command updating a lot of records) - most ORMs will always update each record separately - that is how these tools work. If you load records and modify each of them in loop the relation to original query used to load records is lost. You now have 10.000 loaded records in your application which must be updated. The bulk update is not possible because you must move 10.000 changes from your application to the database.
If you want to do bulk update you should either use direct SQL or implement some logic which will make the update from Linq-to-sql instead of loading records and updating them in the application. Check this article or simply search for Bulk / Batch updates in Linq-to-sql.

A: This is because Linq to SQL First loads the data from server and then update each record individually which includes data query/transfer to client, update request for each record. Whereas  in SP case there is just a call to SP which executes the Update query on the server directly and it does not include data fetch and update of each record. It updates the record in bulk

A: Another approach I did is passing the object values to the stored procedure as XML datatype. But there comes a timeout exception (after some 25 seconds) when the record count is more than 1000. Is it due to huge xml file?
Note: It takes around  5 seconds for 1000 records
   public virtual void UpdateBankAccountUsingParseXML_SP(System.Xml.Linq.XElement inputXML)
    {
        string connectionstring = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=600";
        var myDataContext = new DBML_Project.MyDataClassesDataContext(connectionstring);
        myDataContext.ParseXML(inputXML);

    }

    public void FreezeAllAccountsForUser(int userId)
    {
        List<DTOLayer.BankAccountDTOForStatus> bankAccountDTOList = new List<DTOLayer.BankAccountDTOForStatus>();

        IEnumerable<DBML_Project.BankAccount> accounts = AccountRepository.GetAllAccountsForUser(userId);
        foreach (DBML_Project.BankAccount acc in accounts)
        {
            string typeResult = Convert.ToString(acc.GetType());
            string baseValue = Convert.ToString(typeof(DBML_Project.BankAccount));

            if (String.Equals(typeResult, baseValue))
            {
                throw new Exception("Not correct derived type");
            }

            acc.Freeze();

            DTOLayer.BankAccountDTOForStatus presentAccount = new DTOLayer.BankAccountDTOForStatus();
            presentAccount.BankAccountID = acc.BankAccountID;
            presentAccount.Status = acc.Status;
            bankAccountDTOList.Add(presentAccount);

        }

        IEnumerable<System.Xml.Linq.XElement> el = bankAccountDTOList.Select(x =>
                        new System.Xml.Linq.XElement("BankAccountDTOForStatus",
                          new System.Xml.Linq.XElement("BankAccountID", x.BankAccountID),
                          new System.Xml.Linq.XElement("Status", x.Status)
                        ));

        System.Xml.Linq.XElement root = new System.Xml.Linq.XElement("root", el);

        AccountRepository.UpdateBankAccountUsingParseXML_SP(root);
        //AccountRepository.Update();

    }

Stored Procedure
ALTER PROCEDURE [dbo].[ParseXML] (@InputXML xml)
AS
BEGIN

DECLARE @MyTable TABLE (RowNumber int, BankAccountID int, StatusVal varchar(max))

INSERT INTO @MyTable(RowNumber, BankAccountID,StatusVal)

SELECT ROW_NUMBER() OVER(ORDER BY c.value('BankAccountID[1]','int') ASC) AS Row,
    c.value('BankAccountID[1]','int'),
    c.value('Status[1]','varchar(32)')
FROM
    @inputXML.nodes('//BankAccountDTOForStatus') T(c);

DECLARE @Count INT
SET @Count = 0

DECLARE @NumberOfRows INT
SELECT @NumberOfRows = COUNT(*) FROM @MyTable

WHILE @Count < @NumberOfRows
BEGIN

      SET @Count = @Count + 1

     DECLARE @BankAccID INT
     DECLARE @Status VARCHAR(MAX)

     SELECT @BankAccID = BankAccountID
     FROM @MyTable
     WHERE RowNumber = @Count

     SELECT @Status = StatusVal
     FROM @MyTable
     WHERE RowNumber = @Count

     UPDATE BankAccount
     SET Status= @Status
     WHERE BankAccountID = @BankAccID

END

END

GO


text:
Q: How can I pass the Child name prop to Parent array I have a list of Child objects mapped from my Parent component in my React App.
When a Child item is clicked, I need the props.name of that item to be pushed to the selectedItems array in the Parent component via the handleClick function.
How can I achieve this?
function Parent() {
  let selectedItems = [];
  const result = Data.filter((e) => selectedItems.includes(e.id));

  return (

        {Data.map((item, i) => {
          return <Child
          key={item.id}
          name={item.name} />
        })}

  );
}
export default App

const Child = (props) => {
  const [clickCount, setClickCount] = useState(0);

  function handleClick() {
    setClickCount(prevClickCount => prevClickCount + 1);
  }

  return (

 handleClick()}
    >

{props.name}

{clickCount > 0 ?
Selected: {clickCount}
 :
Not Selected
}

  );
}

A: I would recommend using hooks for the 'selectedItems' in the parent component, as to trigger a re-render when the name changes.
You can pass functions from the parent to the child component using props.
Below I've passed the 'addToSelectedItems' function down to the child and triggered it in the handleClick method.
const Parent = () => {

  const [selectedItems, setSelectedItems] = useState([]);

  function addToSelectedItems(name){
     setSelectedItems([...selectedItems, name]);
  }

  return (

        {Data.map((item, i) => {
          return <Child
          key={item.id}
          name={item.name}
          addToSelectedItems={addToSelectedItems}
          />
        })}

  );
}
export default App

const Child = (props) => {
  const [clickCount, setClickCount] = useState(0);

  function handleClick(name) {
    setClickCount(prevClickCount => prevClickCount + 1);
    props.addToSelectedItems(name);
  }

  return (

 handleClick(props.name)}
    >

{props.name}

{clickCount > 0 ?
Selected: {clickCount}
 :
Not Selected
}

  );
}

A: I'd do something like this, but I have not tested it, it might need some fine tuning

function Parent() {
  let selectedItems = [];
  const result = Data.filter((e) => selectedItems.includes(e.id));
  const [clickCount, setClickCount] = useState(0);

  function handleClick(name) {
    setClickCount(prevClickCount => prevClickCount + 1);
    selectedItem.push(name)
  }

  return (

        {Data.map((item, i) => {
          return <Child
          key={item.id}
          name={item.name}
          clickCount={clickCount}
          handleClick={handleClick} />
        })}

  );
}
export default App;

const Child = (props) => {
  let { handleClick, name, clickCount, img } = props

  return (

 handleClick(name)}
    >

{name}

{clickCount > 0 ?
Selected: {clickCount}
 :
Not Selected
}

  );
}


text:
Q: How to change android Activity label I have created an Activity and declared in Manifest file. But I would like to re-use the same Activity for other purpose.
 <activity
            android:configChanges="orientation|keyboardHidden"
            android:label="Main Menu"
            android:name=".MainMenu"
            android:theme="@android:style/Theme.Light" >
        </activity>

I need to change the Label dynamically. Thanks in Advance

A: You need to use setTitle for this:
setTitle(R.string.your_title);
//or
setTitle("new title");

A: Use
setTitle(int titleId)

or
setTitle(CharSequence title)

A: You can define the string in res/string.xml file and then add android:label to the AndroidMenifest.xml file
string.xml code
<string name="string_name">text to display</string>

AndroidMenifest.xml code

<activity android:name=".SomeActivity"
            android:label="@string/string_name"/>

A: I have the same problem, Try this in onCreate it's work for me!
public class YourActivityName extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    setTitle("Your Title");
  }
}

A: public class YourActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
      setTitle(R.string.your_title);
      setContentView(R.layout.main);
  }
}

A: if(Condition)
{
    setTitle("Your Title");
}
else
{
    // your Default Title from Manifest
}

Try to use this line.

A: Static, not Dynamic
Go to your AndroidManifest.xml file and add the android:label attribute to the activity tag you want, like this:
<activity android:name=".name" android:label="label"/>

A: In your Manifest file
Initially, your code was like this.
    <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".NumbersActivity"  />
    <activity android:name=".FamilyMembersActivity"  />
    <activity android:name=".ColorsActivity"  />
    <activity android:name=".PhrasesActivity" />
    </activity>
</application>

But after changes to add Labels.
<activity android:name=".NumbersActivity" android:label="Numbers" />
    <activity android:name=".FamilyMembersActivity" android:label="Family Members" />
    <activity android:name=".ColorsActivity" android:label="Colors" />
    <activity android:name=".PhrasesActivity" android:label="Phrases" >
    </activity>
</application>

is the optimum way to change the Label name.
courtesy.(ryanwaite28)

A: User this
@Override
  public void onCreate(Bundle savedInstanceState) {
    setTitle("Your Title");
  }

A: android:label="any word you want"/>


text:
Q: Query works in PostgreSQL but fails with HSQL. How can I fix it? I have the following query (inherited from legacy) similar to
SELECT bla FROM table
WHERE
  some.id IN (
    SELECT id FROM (

      SELECT some FROM tag WHERE bla
      UNION
      SELECT some FROM dossierinfo WHERE bla
      ORDER BY tag LIMIT :limit OFFSET :offset

    ) AS aggregated
    WHERE dossier_type = 'auto'
  )
)

The full SQL is at the bottom. The problem is that is executes fine in PostgreSQL 8.2.x. For testing I added an embedded HSQL 1.8.x db, but then the query fails with
07 Sep 2010 13:55:11.914 [WARN] [main] [org.hibernate.util.JDBCExceptionReporter] - SQL Error: -11, SQLState: 37000
07 Sep 2010 13:55:11.914 [ERROR] [main] [org.hibernate.util.JDBCExceptionReporter] - Unexpected token ORDER, requires ) in statement [...]

So I figure out, HSQL does not like the ORDER in the inner join.

*

*Is this order not proper SQL?

*Is upgrading HSQL to 2.0 worth it? Would it support the order? I quickly tried it, but had some problems.

*Rewriting the query is not an option, I just wanted to add a test for that.

Full Query:
SELECT *, article_count as articlecount FROM tag
WHERE
  tag.id IN (
    SELECT id FROM (

      SELECT tag.tag AS tag, tag.id as id, tag.article_count as articleCount, 'auto' AS dossier_type FROM tag
           WHERE tag.tag_count >= :minimumTagCount  AND tag.article_count >= :minimumArticleCount AND
           LENGTH(tag.tag) >= :minimumTagLength  AND
           tag.tag NOT IN (SELECT dossierinfo.name FROM dossierinfo)  AND tag.is_stopword = :stopword
      UNION
      SELECT dossierinfo.name AS tag, dossierinfo.id AS id, dossierinfo.article_count as articleCount,
            'manual' AS dossier_type FROM dossierinfo
      WHERE dossierinfo.article_count >= :minimumArticleCount

      ORDER BY tag  LIMIT :limit OFFSET :offset

    ) AS aggregated

    WHERE dossier_type = 'auto'
  )
)

PS: My HSQL setup works for all other tests, so it's working and executing.

A: ORDER BY in the subquery with LIMIT and OFFSET is supported by some SQL dialects, but not all.
HSQLDB 2.0 supports this. Download the latest snapshot jars from http://hsqldb.org/support/ which have bug fixes and are more compatible with Postgres and other dialects.
Latest Hibernate 3.5.5 and 3.5.6 include a dialect which is compatible with the snapshot jars as well as HSQLDB 1.8.x.
If you have any problem with SQL queries and HSQLDB 2.0, you can report it and it will be fixed promptly.

A: My guess is that you need to be explicit about to what the ORDER BY refers:
Instead of this:
SELECT some FROM tag WHERE bla
UNION
SELECT some FROM dossierinfo WHERE bla
ORDER BY tag LIMIT :limit OFFSET :offset

Try this:
SELECT some FROM (
      SELECT some FROM tag WHERE bla
      UNION
      SELECT some FROM dossierinfo WHERE bla
) AS union_data
ORDER BY tag LIMIT :limit OFFSET :offset

I would do this anyway, even in PostgreSQL. The original looks like the ORDER BY goes with the second SELECT in the UNION.


text:
Q: Is it possible to get a Bob to move without killing him? On levels that have Bobs in them, the Bobs frequently get stuck - jammed together in narrow hallways and such, blocking them. On levels such as The Rose (Marathon 1) where your mission is to keep as many from being killed as possible, it's kind of counterproductive to kill the Bobs to get them out of the way; but if they're blocking the door to an important comm terminal then sometimes there's no choice but to kill them.
Is there any way to 'prod' a Bob to move in the other direction without hurting or killing him?

A: They will sometimes move automatically but for the most part you have to shoot them. Don't feel bad, they are just B.O.B.s


text:
Q: How to generate pojo with Lombok for complex json in Eclipse Below is the json for pojo creation. I want to create a pojo using Lombok.
I am new to rest assured. How can I create a pojo using Lombok in Eclipse. I want in for nested json, like below Jira API post body request.
{
    "fields": {
        "project": {
      "key": "RA"
    },
    "summary": "Main order flow broken",
    "description": "Creating my fist bug",
     "issuetype": {
      "name": "Bug"
    }
        }
}

I have created the below pojo manually, and I am not sure if it's correct. How can I call the generated pojo in post body?
@Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public  class createissue {
    private fieldss fields;

    @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class fieldss {
    private  Project poject;
    private  Sting summary;
    private  String description;
    private  Issuetype issuetypessuetype;
}

 @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class Project {
    private Sting key;
}
    @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class Issuetype {
  private Sting name;
  }

  }

A: The POJO is correct, It had some typos which I have corrected
public class Lombok {

public static @Data class fieldss {

    private  Project project;
    private  String summary;
    private  String description;
    private  Issuetype issuetype;

}

public static @Data class createissue {

    private fieldss fields;

}

public static @Data class Issuetype {

    private String name;

}

public static @Data class Project {
    private String key;

}
}

and the below is how you can test
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Issuetype a1 = new Issuetype();
    a1.setName("Bug");

    Project a2 = new Project();
    a2.setKey("RA");

    fieldss a3 = new fieldss();
    a3.setDescription("Creating my fist bug");
    a3.setSummary("Main order flow broken");
    a3.setIssuetype(a1);
    a3.setProject(a2);

    createissue a4 = new createissue();
    a4.setFields(a3);

    ObjectMapper mapper = new ObjectMapper();

    String abc = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(a4);

    System.out.println(abc);
}

You should be able to see the below in the console
{
    "fields": {
        "project": {
            "key": "RA"
        },
        "summary": "Main order flow broken",
        "description": "Creating my fist bug",
        "issuetype": {
            "name": "Bug"
        }
    }
}


text:
Q: Why is a constant declared with the keyword "let" in Swift? the title says it all...Why is a constant declared with the keyword "let" in Swift?
Probably there's a simple answer to this noob question,  but I couldn't find it on SO.
EDIT: OK, just to make the question clearer. I know that it needs to be initialized with SOME name, but I thought that there maybe is a deeper meaning to let, a source where it originates? Other stuff like "func" seems very logical to me, so I wonder what the deeper meaning of "let" is.

A: Actually in swift there is no concept of constant variable.
A constant is an expression that is resolved at compilation time. For example, in objective C this code:
const NSString *string = [[NSString alloc] init];

results in a compilation error, stating that Initializer element is not a compile-time constant. The reason is that NSString is instantiated at runtime, so it's not a compile time constant.
In swift the closest thing is the immutable variable. The difference may not be evident, but an immutable is not a constant, it's a variable that can be dynamically initialized once and cannot be modified thereafter. So, the compile time evaluation is not needed nor required - although it will frequently happen we use immutables as constants:
let url = "http://www.myurl.com"

let maxValue = 500

let maxIntervalInSeconds = 5 * 60 *60

But immutables can also be initialized with expressions evaluated at runtime:
let url = isDebug ? "http://localhost" : "http://www.myservice.com"

let returnCode: Int = {
    switch(errorCode) {
    case 0: return 0
    default: return 1
    }
}()

The latter example is interesting: using a closure, immediately executed, to initialize an immutable variable (differently from var, immutables don't support deferred initialization, so that's the only way to initialize using a multi line expression)


text:
Q: Filtering a query with subqueries In order to understand the question I will explain the result expected.
I have a db table where I save some data of the activity of the current day. Then I want to sum some numeric fields and the last register of the text fields, using a filter between two dates.
Example:
       •DB TABLE

  ID|CALLS|RESULT  |  DATE

  1 | 2   |FAIL    |15/09/16
  1 | 1   |ERROR   |16/09/16
  1 | 3   |OK      |17/09/16

      •SUM BETWEEN 15 and 17

 ID|TOTAL CALLS|LAST RESULT
 1 |    6      |    OK

     •SUM BETWEEN 15 and 16

 ID|TOTAL CALLS|LAST RESULT
 1 |    3      |  ERROR

-Would this be the solution?
 SELECT DISTINCT ID,
 TOTAL_CALLS=SUM(CALLS),
 LAST_RESULT= (
     SELECT RESULT FROM TABLE T2 where T2.DATE between MIN(T1.DATE) and MAX (T1.DATE) and T1.ID=T2.ID
)

FROM TABLE T1
WHERE
TIME BETWEEN 15/09/16 and 17/09/16
GROUP BY ID

Thank you very much!
Regards

A: Use the below query.
;WITH cte_1
AS
(SELECT  ID,SUM(CALLS)OVER( PARTITION BY ID) [TOTAL CALLS]
 ,Result [LAST RESULT]
 ,ROW_NUMBER()OVER( PARTITION BY ID ORDER BY [DATE] desc) RNO
from #YourTable T
WHERE [DATE] between '09/15/2016' AND '09/16/16')
SELECT ID,[TOTAL CALLS],[LAST RESULT]
FROM cte_1
WHERE Rno=1

A: You can use TOP 1 WITH TIES with ORDERING to get what you need:
DECLARE @dFrom date = '2016-09-15',
        @dTo date = '2016-09-16'

SELECT TOP 1 WITH TIES
                    ID,
                    SUM(CALLS) OVER (PARTITION BY ID) [TOTAL CALLS],
                    RESULT [LAST RESULT]
FROM YourTable
WHERE [DATE] between @dFrom and @dTo
ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY [DATE]) DESC

A: You can use max date to get result column value.
DECLARE @FromDate DATETIME= '15 SEP 2016'

DECLARE @ToDate DATETIME= '16 SEP 2016'

SELECT ID , SUM(CALLS) , ( SELECT RESULT
                           FROM #yourTable
                           WHERE [DATE] = @ToDate
                         )  RESULT
FROM **#yourTable**
WHERE [DATE] BETWEEN @FromDate AND @ToDate
GROUP BY ID


text:
Q: What does the {HTTPS} variable actually represent? I am writing a rule with the IIS Rewrite module to detect if a URL request is formed HTTP:// or HTTPS://
The documentation says "HTTPS can be used to determine if a secure connection was used".
https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference#Accessing_URL_Parts_from_a_Rewrite_Rule
But it's possible that a valid HTTPS URL may not be secure (eg because of an invalid SSL certificate).
In which case would the {HTTPS} variable be true or false?
Is there a better way?

A: Just a point of clarification: the {HTTPS} variable will evaluate to on or off, not true or false. The variable should evaluate to on if it is an https connection (even if the certificate is invalid).


text:
Q: Selectively replace specific nested delimiters (brackets) in strings, while respecting nesting I have many strings where I'm trying to selectively replace all instances of f[--whatever--] with f.__getitem__(--whatever--, x=x).
This is the last option left to me to patch some old complicated code using eval calls that I'm unfortunately stuck with.
It's easy to replace the f[, but it's hard to know whether instances of ] are associated with this pattern or some other
miscellaneous patterns like lists [--whatever--] or indexing .loc[--whatever--]. There are no isolated cases of ] that are not part of a full [] in my strings.
My latest attempt at a solution uses regex:
1) sub ([^f])[(.+?)] with \1openbracket\2closebracket to preserve [] that isn't part of f[]
2) the remaining []
3) sub back openbracket & closebracket with []
The problem is that this doesn't handle many nested cases like the example below. I'm looking for a more comprehensive solution to establish whether a given ] is associated with f[] or some other structure. Is there a way to do this with pyparsing or some other module?
Example
f[r@ndom t3xt] + [some r@ndom t3xt] + [f[more r@ndom t3xt] / f[more t3xt]] + [f[f[more t3xt] + 3]]

should become
f.__getitem__(r@ndom t3xt, x=x) + [some r@ndom t3xt] + [f.__getitem__(more r@ndom t3xt, x=x) / f.__getitem__(more t3xt, x=x)] + [f.__getitem__(f.__getitem__(more t3xt) + 3)]

A: Nested []'s make this a non-trivial problem. pyparsing has a "crutch" expression method called nestedExpr that makes it easy to match nested delimiters like ()'s and []'s. pyparsing also has the transformString method, for converting as-parsed data into a different form. We can use a parse-time callback (or "parse action") to repeatedly convert any nested f[zzz] terms until all have been transformed:
import pyparsing as pp

fname = pp.Keyword('f')
index_expr = pp.nestedExpr('[', ']')
# nestedExpr will give a nested list by default, we just want the original raw text
f_expr = fname + pp.originalTextFor(index_expr)("index_expr")

# define a parse action to convert the f[aaa] format to f._getitem__(aaa, x=x)
def convert_to_getitem(t):
    # get the contents of the index_expr, minus the leading and trailing []'s
    index_expr = t.index_expr[1:-1]

    # repeatedly call transform string to get further nested f[] expressions, until
    # transformString stops returning a modified string
    while True:
        transformed = f_expr.transformString(index_expr)
        if transformed == index_expr:
            break
        index_expr = transformed

    # reformat to use getitem
    return "f.__getitem__({}, x=x)".format(transformed)

# add the parse action to f_expr
f_expr.addParseAction(convert_to_getitem)

# use transformString to convert the input string with nested expressions
sample = "f[r@ndom t3xt] + [some r@ndom t3xt] + [f[more r@ndom t3xt] / f[more t3xt]] + [f[f[more t3xt] + 3]]"
print(f_expr.transformString(sample))

Prints:
f.__getitem__(r@ndom t3xt, x=x) + [some r@ndom t3xt] + [f.__getitem__(more r@ndom t3xt, x=x) / f.__getitem__(more t3xt, x=x)] + [f.__getitem__(f.__getitem__(more t3xt, x=x) + 3, x=x)]

This should also handle '[]'s that might occur in quoted strings.

A: Maybe,
f\[([^]]*)\]

and a re.sub with,
f.__getitem__($1, x=x)

might simply work.
Test
import re

regex = r"f\[([^]]*)\]"

string = """
f[r@ndom t3xt] + [some r@ndom t3xt] + [f[more r@ndom t3xt] / f[more t3xt]]
f[] + [] + [f[] / f[]]

"""

subst = "f.__getitem__($1, x=x)"

print(re.sub(regex, subst, string))

Output
f.__getitem__($1, x=x) + [some r@ndom t3xt] + [f.__getitem__($1, x=x) / f.__getitem__($1, x=x)]
f.__getitem__($1, x=x) + [] + [f.__getitem__($1, x=x) / f.__getitem__($1, x=x)]

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

A: A solution using Regex:
import re

string1 = "f[r@ndom t3xt] + [some r@ndom t3xt] + 3[f2[more r@ndom t3xt] / f[more t3xt]] + [f[f[more t3xt] + 3]]"
string3 = '''f[text([0,[1,2],3, x["text3"]])]'''

def get_repl(match):
    if match.groups()[-1]:
        # replace nested [ and ]  with special characters
        return match.groups()[-1].replace('[', '##1##').replace(']', '##2##')
    else:
        return '{}.__getitem__({}, x=x)'.format(*match.groups()[:-1])

def place_by_getitem(string):
    pattern = '(?<!\w)(f)\[([^\[]+?)\]|(\[[^\[]+?\])'
    while re.search(pattern, string):
        string = re.sub(pattern, get_repl, string)

    return string.replace('##1##', '[').replace('##2##', ']')

print(place_by_getitem(string1))
print(place_by_getitem(string3))

Output:
f.__getitem__(r@ndom t3xt, x=x) + [some r@ndom t3xt] + 3[f2.__getitem__(more r@ndom t3xt, x=x) / f.__getitem__(more t3xt, x=x)] + [f.__getitem__(f.__getitem__(more t3xt, x=x) + 3, x=x)]
f.__getitem__(text([0,[1,2],3, x.__getitem__("text3", x=x)]), x=x)


text:
Q: What's the word to refer to someone about whom you can never make assumptions? I want a word to describe Macavity, the Mystery Cat to denote that you could never assume anything about him. If you did, he was sure to prove you wrong. Can you help me by suggesting an appropriate word? Thanks in advance...

A: It's a pleasing challenge because the very notion of a character trait suggests you are trying to qualify or define them in a certain way.
I would say "enigma": in its everyday sense, this suggests a puzzling entity which seems unsolvable, impossible to be understood, prone to always surprise you.
PS In a theological context, an enigma is solvable, compared to the unsolvable "mystery/mysterium"

A: How about unfathomable? From M-W:

unfathomable: not capable of being fathomed; impossible to comprehend

If you can never assume anything about Macavity, Macavity is unfathomable. Hence, the Mystery Cat.


text:
Q: Is there a way to search for uncommented, unanswered and unclosed questions? I am trying to look for ignored questions and try to answer them or give them attention. I need a way to search for unclosed, unanswered, and uncommented questions. Is there a way to go about doing such a search?

A: Stack Exchange's search functionality doesn't have a comments:0 or similar filter, so that won't work. A crude way is to look for Tumbleweed badges; they are awarded to similar questions, but could be answered/commented after the badge has been earned. Because you can only earn the badge once, and the question may not have any up- and downvotes, you might miss some questions.
I've constructed a SEDE query to look for them. The view count is another measure for neglectance, so I've used it for sorting. The top hits on Chemistry.SE are these questions:

*

*https://chemistry.stackexchange.com/q/78691

*Is it possible to extract mass concentration from DLS measurement?

*Could sodium fluoride or aluminum accumulation in soils contribute to increased amounts of palmitic acid in food?
For reference, here is the complete query:
SELECT Id AS [Post Link], CreationDate, Score, ViewCount
  FROM Posts
  WHERE PostTypeId = 1 -- questions
    AND AnswerCount = 0
    AND CommentCount = 0
    AND ClosedDate IS NULL
  ORDER BY ViewCount

(thanks @ifajra for the suggestion)
Note that SEDE is updated once a week, on Sunday morning, so the questions might have answers or comments by now.

A: You can use the following snippet to select a site and then click start to list questions with no-answers. It is based on the StackAPI no-answer-questions. Using the StackAPI instead of SEDE guarantees you always look at the most recent data, not data that can be stale for up to 7 days.
It filters out questions with a comment count < 2 because for some reason comment_count is often 1 when there are no visible comments. It loads 100 questions after which you can click load next to fetch the next batch of 100 questions.

(function() {
    'use strict';

    var currentSite, currentPage = 1;

    // build api url for an endpoint and its optional parameters
    function apiBuilder(endpoint, params) {
        var url = 'https://api.stackexchange.com/2.2/',
            urlPath = url + endpoint;
        params.key ='Kdg9mxpgwALz)u5ubehUFw((';
        if (params !== undefined)  {
            var query = [];
            for(var prop in params) {
                if (params.hasOwnProperty(prop)) {
                    query.push( prop + '=' + encodeURI(params[prop]));
                }
            }
            urlPath = urlPath + '?' + query.join('&');
        }
        return urlPath;
    }

    // build url for /sites api endpoint
    function apiSitesBuilder() {
        return apiBuilder(
            'sites',
            {
                pagesize: 500,
                filter: '!*l7am7*mGv_Xmq-k..iQsWPn'
            });
    }

    // build url for /Question/Unanswered endpoint
    function apiQuestionBuilder(site, page) {
        return apiBuilder(
            'questions/no-answers',
            {
                site: site,
                order: 'desc',
                page: page,
                pagesize: 100,
                sort: 'activity',
                filter: '!*7PmgCBkOPC0W(BajiIL1.9t)Azg'
            });
    }

    // do a get on the API for the given url
    // and invoke the callback with the JSON result
    function API () {

        var backlog = [],
            getfunction;

        // simply push the params on the queue
        function cacheget(url, callback) {
            backlog.push({ url: url, callback: callback});
        }

        // this makes the actual xhr call
        function realget(url, callback) {
            var xhr = new XMLHttpRequest();

            // handles pending calls by invoking realget
            // and resetting the getfunction when
            // the backlog is cleared
            function handleBacklog() {
                var item = backlog.shift();
                if (item !== undefined) {
                    console.log('from cache');
                    // handle this single item
                    realget(item.url, item.callback);
                }
                if (backlog.length === 0) {
                    // if the backlog is empty
                    // use realget for the next call
                    getfunction = realget;
                }
            }

            xhr.addEventListener('error', function () {
                console.log(xhr.status);
            });

            xhr.addEventListener('load', function () {
                var response = JSON.parse(xhr.responseText);
                var backoff = response.backoff || 0;
                // backoff received
                if (backoff > 0) {
                    // start caching calls
                    console.log('backoff recv');
                    getfunction = cacheget;
                }
                if (response.error_id === 502) {
                    console.log(reponse.error_message);
                    getfunction = cacheget;
                    backoff = 120;
                }
                // process pending backlog
                setTimeout(handleBacklog, backoff * 1000);
                // invoke the callback
                callback(response);
            });
            xhr.open('GET', url);
            xhr.send();
        }

        // calls either xhr or the cache
        function get(url, callback)
        {
            getfunction(url, callback);
        }

        // initially we start with a realget
        getfunction = realget;

        // return the public api
        return {
            get: get
        };
    }

    var SEApi = new API(); // keep an instance

    function createQuestion(item) {
      var anchor = document.createElement('a'),
          div = document.createElement('div');
      anchor.href = item.link;
      anchor.innerHTML = item.title;
      anchor.title = 'upvotes: ' + item.up_vote_count;
      div.appendChild(anchor);
      return div;
    }

    // what we see for a question
    function handleQuestions(items) {
      var result = document.getElementById('result'), added = false;
      items.forEach(function(item) {
        if (item.comment_count &&
            item.comment_count < 2 &&
            item.locked_date === undefined) {
          result.appendChild(createQuestion(item));
          added = true;
        }
      });
      return added;
    }

    // get question with no answers
    function getUnanswered(site) {
      // call the api
      SEApi.get(apiQuestionBuilder(site, currentPage) , function(data) {
         currentPage = data.has_more === false ? -1 : (currentPage + 1);
         if (data.has_more) {
            document.getElementById('go').textContent='Load next';
         } else {
            document.getElementById('go').textContent='No more questions';
         }
         if (data && data.items) {
           // in case no question were found at all ...
           if (!handleQuestions(data.items)) {
              // .. load the next page immediately
              getUnanswered(site);
           }
         }
      });
    }

    // load next page
    function paging() {
      if (currentPage === -1 ) return;
      var site = document.getElementById('site');
      getUnanswered(site.value);
    }

    // change a site
    function change() {
       var site = document.getElementById('site'),
           img = document.getElementById('logo'),
           result;
       result = document.getElementById('result');
       while (result.firstChild) {
          result.removeChild(result.firstChild);
       }
       currentPage = 1;
       if (site.value !== '0') {
         currentSite = site.value
         site.childNodes.forEach(
           function(option) {
             if (option.value === site.value) {
               img.src = option.getAttribute('data-icon');
               img.style.display = 'inline';
             }
           }
         );
         getUnanswered(site.value);
       } else {
         img.style.display = 'none';
         document.getElementById('go').textContent='Start ...';
       }
    }

    function bindPager() {
      var pager = document.getElementById('pager'),
          select = document.getElementById('site');
      pager.addEventListener('click', paging);
      select.addEventListener('change', change);
    }

    function siteOption(site) {
       var option = document.createElement('option');
       option.value = site.api_site_parameter;
       option.setAttribute('data-icon', site.icon_url);
       option.innerHTML = site.name;
       return option;
    }

    // fill sites
    function fillSites(items) {
        var i, site, site = document.getElementById('site');
        items.forEach(function(item){
           site.appendChild(siteOption(item));
        });
        return null;
    }

    function error(msg) {
       var err = document.getElementById('error');
       err.textContent = msg;
    }

    SEApi.get(apiSitesBuilder(), function (data) {
        if (data.items && data.items.length) {
            fillSites(data.items);
            bindPager();
        } else {
           error('no sites');
        }
    });
})();
#go
{
  text-align: center;
  padding-left: 50px;
  padding-right: 50px;
  padding-top: 5px;
  padding-bottom: 5px;
  background-color:blue;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}
#pager{margin-top: 10px;}
#logo{width: 1em; height: 1em;padding-left:4px}

Site:
<select id="site">
<option value="0">Select a site</option>
</select>

Start ...

A: Getting unclosed and unanswered is easy:
https://chemistry.stackexchange.com/search?q=answers%3A0+closed%3Ano
but to look for uncommented I think you would need to write/find an SQL query for the Stack Exchange Data Explorer.


text:
Q: How to check if a channel is joined? I got channel by client.get_entity(id) using id stored locally and I need to check if I am still joined or not. I suspect it might be not Channel.left but I haven't found any docs about the field.

A: Your assumption about not channel.left is correct. The docs about the field can be found here: https://core.telegram.org/constructor/channel.


text:
Q: Why the continuity equation means constant densities of each fluid parcel? As we know, the definition of material derivative of $\varphi$ is: $\frac{D\varphi}{Dt}\equiv \frac{\partial \varphi}{\partial t} + \mathbf{u}\cdot\nabla\varphi$. And the physical meaning of material derivative is the change of $\varphi$ of a fluid parcel moving with the stream.
And it is easy to find that the continuity equation (${\displaystyle {\frac {\partial \rho }{\partial t}}+\nabla \cdot \mathbf {(\rho u)} =0}$) means the material derivative of the density is 0, which also means that every fluid parcel's density is constant along their way.
This cannot be understood intuitively easily, why the continuity equation means constant densities of each fluid parcel?
I think this SE question is relavent, but I still look forward to some answers based on my question's view.

A: Your statement is not true in general. On the one hand you have:
$$ \frac{D\rho}{dt} = \partial_t \rho + \vec u \cdot \nabla \rho, $$
On the other hand the continuity equations (which implies conservation of total mass) gives:
$$ 0 = \partial_t \rho + \nabla \cdot (\vec u \rho) = \partial_t \rho + \rho \nabla \cdot \vec u + \vec u \cdot \nabla \rho. $$
So the continuity equation implies that the material derivative is zero only for a flow whose velocity field is divergence free, and this exactly characterizes incompressible flow. (Although usually it is derived the other way around, you compare the material derivative and the continuity equation and see that for incompressibility, $\nabla \cdot \vec u$ has to vanish).
TL;DR: The continuity equation for the mass density only implies conservation of mass not conservation of density for fluid parcels. Incompressibility is characterized by $D_t \rho = 0$, and it can be shown to be equivalent to the continuity equation plus $\nabla \cdot \vec u = 0$.


text:
Q: Extracting Content after a Numbered List is there a way to extract the content after the numbered list in Python? For eg.

*

*A user interface (ui) object: The user interface (ui) object governs the layout and appearance of the app.

*A server function: The server function contains the instructions to build the app.

*A call to the shinyApp function: The shinyApp function creates Shiny app objects from an explicit UI/server pair.

I would like to extract the content after 1., 2., and 3. I've tried the following but it doesn't capture everything.
import re
content = re.search(r'[0-9]\..+', text)
text[1533:1639]

A: You could use a capture group to get the data after the digits and dot at the start.
If you also want to match for example 10. at the start, you can repeat the digit 1 or more times [0-9]+
Capture the rest after the digits and dot on the first line, and then also capture all following lines that do not start with the digits dot pattern.
^[0-9]+\. (.*(?:\n(?![0-9]+\.).*)*)

Explanation

*

*^ Start of string

*[0-9]+\.  Match 1+ digits and .

*( Capture group 1

*

*.* Match the rest of the line

*(?: Non capture group to repeat as a whole

*

*\n(?![0-9]+\.).* Match a newline and the rest of the line if it does not start with digits and .

*)* Close the non capture group and optionally repeat it

*) Close group 1

Regex demo | Python demo
Example
import re

pattern = r"^[0-9]+\. (.*(?:\n(?![0-9]+\.).*)*)"

s = ("1. A user interface (ui) object: The user interface (ui) object governs the layout and \n"
    "appearance of the app.\n"
    "2. A server function: The server function contains the instructions to build the app.\n"
    "3. A call to the shinyApp function: The shinyApp function creates Shiny app objects from \n"
    "an explicit UI/server pair.")

print(re.findall(pattern, s, re.MULTILINE))

Output
[
'A user interface (ui) object: The user interface (ui) object governs the layout and \nappearance of the app.',
'A server function: The server function contains the instructions to build the app.',
'A call to the shinyApp function: The shinyApp function creates Shiny app objects from \nan explicit UI/server pair.'
]


text:
Q: Python pandas bar graph with titles from column I have the following data frame:
   year  tradevalueus    partner
0  1989         26065    Algeria
1  1989         12345    Albania
2  1991        178144  Argentina
3  1991         44384     Bhutan
4  1990       1756844   Bulgaria
5  1990      57088556    Myanmar

I want a bar graph by year on the x-axis for each trade partner with values. By this, with the above data, I want to have 3 years on the x-axis with 2 bar-graphs for each year with the tradevalueus variable and I want to name each of these by the partner column. I have checked  df.plot.bar() and other stackoverflow posts about bar graphs but they don't give the output I desire. Any pointers would be greatly appreciated.
Thanks!

A: You can either pivot the table and plot:
df.pivot(index='year',columns='partner',values='tradevalueus').plot.bar()

Or use seaborn:
import seaborn as sns
sns.barplot(x='year', y='tradevalueus', hue='partner', data=df, dodge=True)

Output:


text:
Q: Loop through numbers from 0 to 100 and print out every third number without the modulo function using recursion I had an interview the other day that asked the question, loop through the numbers from 0 to 100 and print out every third number. This is a very easy question if you know what the modulo function is. So I came up with the solution  (Note I was using Java):
for (int i=0; i<100; i++) {
  if (i % 3 == 0) {
    System.out.println(i);
  }
}

He then asked, what if you can't use division or the modulo function. So I had to think about this for about 30 seconds, and came up with a solution, that I knew was very inefficient, and let him know it was very inefficient, but would work.
int x = 3;
for (int i=0; i<100; i++) {
  for (int j=0; j<33; j++) {
    if (x*j==i) {
      System.out.println(i);
      break;
    }
  }
}

I'm free writing this without testing, so it might not work 100%, but you get the idea of how I solved the problem. He said he understood what I was trying to do. He then said that there is another way to do it using a recursive function. He tried to briefly explain it to me, but I didn't understand how you could use a recursive function to solve this problem. Can anyone come up with a solution using recursion?
EDIT:
Thanks for all the answers! I didn't think this question would attract as much attention as it did, but I appreciate all the answers. Some of you didn't understand that you can ONLY increment by 1. So you must loop through every natural number from 0 to 100.

A: There is a cool trick to test if a number is divisible by three. If the sum of all its digits is divisible by three, then the original is divisible by three. This can be applied recursively: if I have a number a, I can add all the digits of a together to get b and see if b is divisible by 3. How do I know if b is divisible by three? Add all of its digits together to get c and see if c is divisible by three...
As with all recursion, you have to stop at some point. The base case is when you have a sum which is only one digit long- you can have a list of digits divisible by three and check against these. In code:
public boolean printDivisibleByThrees(){
    for(int i=0; i<100; i++){
        if(isDivisibleByThree(i)){
            System.out.println(i);
        }
    }
}

public boolean isDivisibleByThree(int i){
    if(i<0){
        i = -1*i; //we only care about the absolute value of i
    }
    if(Arrays.asList(0,3,6,9).contains(i)){
        return true;
    } else if(i<10){
        return false; //one digit number not divisible by three
    } else {
        int j = sumDigits(i);
        return isDivisibleByThree(j);
    }
}

public int sumDigits(int i){
    String iString = (new Integer(i)).toString();

    int sum = 0;
    for(char digit : iString.toCharArray()){
        sum += (new Integer(digit+"")).intValue();
    }

    return sum;
}

A: Use a second parameter that will keep if the number is or not the third
public class Rec
{

    public static void rec(int n, int t) {
        if(t==3) {
            System.out.println(n);
            t=0; // reset it
        }
        if(n!=100) {
            rec(++n, ++t);
        }
    }

    public static void main (String[] args)
    {
        rec(0, 3);
    }
}

A: As no answer has been picked yet I like to add my two cents here.
Since the trick is do the modulo function with recursion and without division (as I understood) here is my solution:
public static void main(String[] args) {
    for ( int i = 1; i <=100; i++ ){
        if ( mod(i, 3) ){
            System.out.println(i);
        }
    }
}

public static boolean mod(int a, int b){
    if ( a < 0 ){
        return false;
    }else if (a==b){
        return true;
    }else{
        return mod( a-b, b );
    }
}

EDIT
This version will handle division by 0 and negative numbers on the modulo function:
public static boolean mod(int a, int b){
    if ( b < 0 ){
        b=b*-1;
    }
    if ( a < 0 || b == 0){
        return false;
    }else if (a==b){
        return true;
    }else{
        return mod( a-b, b );
    }
}

A: One can define the modulus operator using recursion as follows:
// Assume a, b > 0
static int mod(a, b) {
  if (a < b) {
    return a;
  } else {
    return mod(a-b, b);
  }
}

So then you could do:
for (int i=0; i<100; i++) {
  if (mod(i, 3) == 0) {
    System.out.println(i);
  }
}

A: I want to add one more answer that is probably unusual, but works fine for each range.
The code is C++ (I'm from mobile and I've only a C++ compiler on it), but it is quite easy to understand and to rewrite in Java.
#include <iostream>

void foo(int c, int n) {
    static int i = 0;

    if(c >= n) return;

    switch(i++) {
    case 1:
    case 2:
        foo(++c, n);
        break;
    case 0:
    case 3:
        std::cout << c << std::endl;
        i = 1;
        foo(++c, n);
    }
}

int main() {
    foo(0, 100);
}

A: Another variation on the recursion (JavaScript code):
function f(m,i){
  if (i == 100){
    return;
  } else if (i == 3*m){
    console.log(i);
    f(m + 1,i + 1);
  } else {
    f(m,i + 1);
  }
}

f(0,0);

A: Why not just do:
for (int i = 0; i < 100; i += 3)
    System.out.println(i);

This way you don't have to check if it is every third number, because it goes up by 3 each time.

A: void printNth(int max, int n, int i, int sinceLastPrinted) {
    if (i>max) {
        return;
    }
    if (sinceLastPrinted == n-1) {
        System.out.println(i);
        sinceLastPrinted = -1;
    }
    printNth(max, n, i+1, sinceLastPrinted+1);
}

printNth(100, 3, 0, 0);

It's also not 100% clear whether the last number (100 in the example) should be included (if it is "a 3rd number"), depending on that you might need to modify to:
    if (i>=max) {

And also not very clear where to start the "every 3rd"? 0, 3, 6, or 2, 5, 8? The advantage of my function is that this can be easily modified by passing different value for i

A: This would work. !
public class Recursion {

 public static void main(String[] args) {
    myRecursiveMethod(0,1,100,3);
 }

 public static void myRecursiveMethod(int begin,int temp,int end,int n)
 {
    if(begin<=end)
    {
        if(temp==n)
        {
            System.out.println(begin);
            temp=0;
        }
        myRecursiveMethod(++begin,++temp,end,n);
    }

 }

}


text:
Q: Gitlab 7.5.3 not syncing SSH authorized_keys I upgraded from Gitlab 7.0 to 7.5.3 following the guidelines.
All went well but one issue remaining is that the automatic sync of sidekiq with gitlab-shell authorized_keys file is not working anymore.
Neither add nor delete.
Log files did not state anything, after e.g. adding a key I only see GitlabShellWorker executing successfully:
sidekiq.log:
2015-01-06T08:31:26Z 3292 TID-kjwek GitlabShellWorker JID-3b65f0ad00be156f30a22a62 INFO: start
2015-01-06T08:31:27Z 3292 TID-kjwek GitlabShellWorker JID-3b65f0ad00be156f30a22a62 INFO: done: 0.589 sec
2015-01-06T08:35:00Z 3292 TID-kjwek Sidekiq::Extensions::DelayedMailer JID-9c4837cd0acb34cb78cf5148 INFO: start
2015-01-06T08:35:28Z 3292 TID-kjwek Sidekiq::Extensions::DelayedMailer JID-9c4837cd0acb34cb78cf5148 INFO: done: 27.98 sec

No errors or hints in other logs.
System Information:
git@aux-git:~/gitlab> sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production SANITIZE=true
WARNING: Nokogiri was built against LibXML version 2.8.0, but has dynamically loaded 2.9.1
Checking Environment ...

Git configured for git user? ... yes

Checking Environment ... Finished

Checking GitLab Shell ...

GitLab Shell version >= 2.2.0 ? ... OK (2.2.0)
Repo base directory exists? ... yes
Repo base directory is a symlink? ... no
Repo base owned by git:git? ... yes
Repo base access is drwxrws---? ... yes
Satellites access is drwxr-x---? ... yes
hooks directories in repos are links: ...
2/30 ... ok
2/47 ... ok
5/51 ... ok
2/53 ... ok
5/55 ... ok
2/56 ... ok
5/57 ... ok
2/58 ... ok
10/60 ... ok
32/61 ... ok
6/62 ... ok
9/64 ... ok
6/65 ... ok
2/66 ... ok
2/67 ... ok
2/68 ... ok
2/69 ... ok
2/70 ... ok
41/72 ... ok
2/74 ... ok
2/76 ... ok
Running /home/git/gitlab-shell/bin/check
Check GitLab API access: OK
Check directories and files:
        /var/git/repositories: OK
        /home/git/.ssh/authorized_keys: OK
Test redis-cli executable: redis-cli 2.8.6
Send ping to redis server: PONG
gitlab-shell self-check successful

Checking GitLab Shell ... Finished

Checking Sidekiq ...

Running? ... yes
Number of Sidekiq processes ... 1

Checking Sidekiq ... Finished

Checking LDAP ...

LDAP users with access to your GitLab server (only showing the first 100 results)
Server: ldapmain
[..]
Checking LDAP ... Finished

Checking GitLab ...

Database config exists? ... yes
Database is SQLite ... no
All migrations up? ... yes
Database contains orphaned GroupMembers? ... no
GitLab config exists? ... yes
GitLab config outdated? ... no
Log directory writable? ... yes
Tmp directory writable? ... yes
Init script exists? ... yes
Init script up-to-date? ... yes
projects have namespace: ...
2/30 ... yes
2/47 ... yes
5/51 ... yes
2/53 ... yes
5/55 ... yes
2/56 ... yes
5/57 ... yes
2/58 ... yes
10/60 ... yes
32/61 ... yes
6/62 ... yes
9/64 ... yes
6/65 ... yes
2/66 ... yes
2/67 ... yes
2/68 ... yes
2/69 ... yes
2/70 ... yes
41/72 ... yes
2/74 ... yes
2/76 ... yes
Projects have satellites? ...
2/30 ... yes
2/47 ... yes
5/51 ... yes
2/53 ... yes
5/55 ... yes
2/56 ... yes
5/57 ... yes
2/58 ... yes
10/60 ... yes
32/61 ... yes
6/62 ... yes
9/64 ... yes
6/65 ... yes
2/66 ... yes
2/67 ... yes
2/68 ... yes
2/69 ... yes
2/70 ... yes
41/72 ... yes
2/74 ... yes
2/76 ... yes
Redis version >= 2.0.0? ... yes
Ruby version >= 2.0.0 ? ... yes (2.0.0)
Your git bin path is "/usr/bin/git"
Git version >= 1.7.10 ? ... yes (1.8.4)

Checking GitLab ... Finished

git@aux-git:~/gitlab> sudo -u git -H bundle exec rake gitlab:env:info RAILS_ENV=production
WARNING: Nokogiri was built against LibXML version 2.8.0, but has dynamically loaded 2.9.1

System information
System:         openSUSE project 13.1
Current User:   git
Using RVM:      no
Ruby Version:   2.0.0p247
Gem Version:    2.0.3
Bundler Version:1.6.2
Rake Version:   10.3.2
Sidekiq Version:2.17.0

GitLab information
Version:        7.5.3
Revision:       b656b85
Directory:      /home/git/gitlab
DB Adapter:     mysql2
URL:            http://aux-git
HTTP Clone URL: http://aux-git/some-project.git
SSH Clone URL:  git@aux-git:some-project.git
Using LDAP:     yes
Using Omniauth: no

GitLab Shell
Version:        2.2.0
Repositories:   /var/git/repositories/
Hooks:          /home/git/gitlab-shell/hooks/
Git:            /usr/bin/git

Any ideas? Is it a Gitlab bug? I saw some changes in shell.rb since 7.0.
Thanks
Christian

A: So, sidekiq got updated from 2.17.1 to 2.17.2, and the changelog mentions a bug fix that changes how sidekiq can be invoked.
It's likely that your GitLab installation is still invoking sidekiq using the old style, something like the following.
sidekiq -q post_receive,mailer,system_hook,project_web_hook,gitlab_shell,common,default -e production

This no longer works. If that's the case you need to fix your launch scripts to invoke sidekiq as follows, instead.
sidekiq -q post_receive -q mailer -q system_hook -q project_web_hook -q gitlab_shell -q common -q default -e production


text:
Q: Reference for a formula expressing the characteristic polynomial of a sum of endomorphisms Let $R$ be a ring, $A$ a (not necessarily commutative) $R$-algebra and $M$ a (left) A-module which is free of finite rank as an $R$-module. If $a\in A$ then multiplication with $a$ on $M$ is an $R$-linear endomorphism of $M$ and as such it has a characteristic polynomial $\chi_a$. I've learned from notes by Bart de Smit which I've accidentally found via Google (http://www.math.leidenuniv.nl/~desmit/notes/charpols.pdf) that the function $\chi_\bullet$ is determined by its values on a generating set of $A$ as an $R$-module. He proves this by deriving suitable formulas for the characteristic polynomial of a sum of two endomorphisms.
I'm looking for a reference for this fact that can be cited more easily than the informal notes above.

A: One reference is:  S. A. Amitsur, On the Characteristic Polynomial of a Sum of Matrices,
Linear and Mult. Algebra 8 (1980), 177-182.  (pp. 469-474 in Selected Papers of S. A. Amitsur,
Part 2, AMS 2001.)


text:
Q: How to upload image in JSF Hello once again i ask question on stackOverflow :D
how can i upload file with JSF using primefaces?
i have method handle Upload Image
 public void handleFileUpload(FileUploadEvent event) {
                        ExternalContext extContext = FacesContext.getCurrentInstance().
                                             getExternalContext();
                File result = new File(extContext.getRealPath
                 ("//admin//item") + "//" + event.getFile().getFileName());

            try {
                FileOutputStream fileOutputStream = new FileOutputStream(result);

                byte[] buffer = new byte[BUFFER_SIZE];

                int bulk;
                InputStream inputStream = event.getFile().getInputstream();
                while (true) {
                  bulk = inputStream.read(buffer);
                  if (bulk < 0) {
                         break;
                         }
                  fileOutputStream.write(buffer, 0, bulk);
                  fileOutputStream.flush();
                  }

                  fileOutputStream.close();
                  inputStream.close();

                  FacesMessage msg = new FacesMessage("Succesful",
                      event.getFile().getFileName() + " is uploaded.");
                  FacesContext.getCurrentInstance().addMessage(null, msg);

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

                  FacesMessage error = new FacesMessage("The files were  not uploaded!");
                  FacesContext.getCurrentInstance().addMessage(null, error);
                  }
        }

it work well but it just work when server deploy, when i upload image to server , folder //admin/item/ have image but when i re-start server i can't find image i was uploaded
and how can i display thumbnails for each item with each own image

A:
but when i re-start server i can't find image i was uploaded

That's normal in most servletcontainer configurations. When you restart the server or redeploy the webapp, any previously expanded webapp files will be deleted and the WAR will be re-expanded. You shouldn't store uploaded files in the expanded folder for the case you'd like to keep them longer than the webapp context lives.
The normal practice is to store them in a fixed path outside the webapp context, e.g. /var/webapp/upload.
File file = new File("/var/webapp/upload", event.getFile().getFileName());

Unrelated to the problem, I'd suggest to make use of File#createTempFile() to avoid that another uploaded file which has -by coincidence- the same filename will overwrite any previously uploaded one.


text:
Q: $.mobile.changePage in showing a blank page in AJAX I have login function which works but after login in it doesn't take the user to Homepage
instead shows a blank page why isthat?
Ajax with problem:
function Login(){
$.ajax({
    url: 'http://creative.coventry.ac.uk/~4078078/moviereviews/v1.0/index.php/user/adduser/'+$("#loginusername").val(),
headers: {authorization:window.btoa($("#loginusername").val()+':'+$("#loginpassword").val())},
contentType: "text",
    dataType: 'json',
    success: function(data) {
        authorisation = window.btoa($("#loginusername").val()+':'+$("#loginpassword").val()); //create a variable to pass to the cookie
        createCookie('cookie',authorisation,0); //create our authorisation cookie for the client
        alert("Login Successful!");
        $("#login").hide(); //hide the login button
        $("#logout").show(); //show the logout button
        $("#addreview").show(); //show the add a review button
        $("#adminpanel").show();//show the admin panel page
        $("#loginusername").val(''); //clear the name box
        $.mobile.changePage("#home"); //show the menu

    },
error: function (response) {
    var r = jQuery.parseJSON(response.responseText);

    alert("Error:" + r.error.text);
               }
        });

}
The login form

        Login

              <form id="check-user" class="ui-body ui-body-a ui-corner-all">
        <fieldset>

                Username:
            <input type="text" value="" name="loginusername" id="loginusername"/>

                Password:
            <input type="password" value="" name="loginpassword" id="loginpassword"/>

            <input type="checkbox" id="rememberme" name="checkbox-0" data-role="none"/> Remember me

           <input type="button" data-theme="a" onclick="Login()" name="submit" value="Log in">
              Sign up
        </fieldset>
        </form>

and the page where I am trying redirect

       ... list view here

The site can be tested here
with username demo and password demo
enter link description here
The page I am tryng to load after loginenter link description here


text:
Q: C++ mixing printf and cout
Possible Duplicate:
mixing cout and printf for faster output

I'm using Microsoft Visual Studio 6.0.
The following program,
#include "stdafx.h"
#include "iostream.h"

int main(int argc, char* argv[])
{
printf("a");
printf("b");
printf("c");
return 0;
}

produces "abc".
While the following program,
#include "stdafx.h"
#include "iostream.h"

int main(int argc, char* argv[])
{
printf("a");
cout<<"b";
printf("c");
return 0;
}

produces "acb".
What's the problem? Can't I mix cout and printf in the same program?

A: The standard says that:

When a standard iostream object str is synchronized with a standard
  stdio stream f, the effect of inserting a character c by
fputc(f, c);

is the same as the effect of
str.rdbuf()->sputc(c);

for any sequences of characters;

By default, unless you invoke sync_with_stdio(false), cout is synchronized with stdout. Therefore your second code snippet is equivalent to:
printf("a");
fputc(stdout, 'b')
printf("c");

Which must produce "abc" even on your implementation.
Bottom line: MSVC6 is not standard conforming, which is not a surprise as it is very old.


text:
Q: Data storage is about to finish and want to remove Email Tracking Statistics We are running short of data storage and I can see most od the data storage used by "Email Tracking Statistics" almost 44%. I tried to delete it but I haven't get any option to delete. We were using campaign monitor earlier and this object created by campaign monitor. I tried data loader but did not get any object related this. It a manage package so how can I remove data.
Please help if any one was running with this issue.