Errors about Kali Linux repository when I run apt-get update

Question: root@BlackRishi98:~# apt-get update
Get:1 http://old.kali.org/kali sana InRelease [20.3 kB]
Err:1 http://old.kali.org/kali sana InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY ED444FF07D8D0BF6
Get:2 http://ftp.yzu.edu.tw/Linux/kali kali-rolling InRelease [30.5 kB]
Err:2 http://ftp.yzu.edu.tw/Linux/kali kali-rolling InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY ED444FF07D8D0BF6
Reading package lists... Done
W: GPG error: http://old.kali.org/kali sana InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY ED444FF07D8D0BF6
E: The repository 'http://old.kali.org/kali sana InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: http://ftp.yzu.edu.tw/Linux/kali kali-rolling InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY ED444FF07D8D0BF6
E: The repository 'http://http.kali.org/kali kali-rolling InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

A few days back, I tried to install TheFatRat, a Kali Linux application. Thereafter I started getting these errors. I cannot even install any new packages.
Any help is appreciated.
Comment: **Kali is not Ubuntu...**
Answer: It would appear that you added the Kali Linux Repository to your list of repositories to install that package, yet you did not add the repository's public key to your local keyring. Thus, Ubuntu cannot verify the authenticity of the repository.
The following commands should fix this problem:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys ED444FF07D8D0BF6
sudo apt update


Why is my code generating different results

Question: I am learning automation through Selenium (using Java programming language), and I am working on a test case. The last step in my case involves checking for the presence of a button an a page, by using findElement.By.xpath, and I have two versions of the step. With either version, my entire test case passes. However, the two versions each generate a different result by themselves. If I use the first version, with the int, I get "Write review button' does not exist" result. If I use the second version with the Boolean, I get "Write review button' exists!"
Since the test case passes, and with the second version generating the 'button exists' result, the problem cannot be with the xpath, so the issue with the second version getting the wrong result must be in the logic, yet I cannot tell what it is.
I tried rerunning the case multiple times to see if the problem is a glitch, but same result. I tried finding similar problems online, but cannot find anything that shows exactly how my problem is wrong.
int i = driver.findElements(By.xpath("//ul[@class='comments_advices']")).size();
if (i > 0)  { System.out.println("'Write review button' exists!"); }
else        { System.out.println("'Write review button' does not exist :( ");

}
boolean reviewButtonPresent = driver.findElements(By.xpath("//ul[@class='comments_advices']")).size() > 0;
if (reviewButtonPresent = true) { System.out.println("'Write review button' exists!"); }
else { System.out.println("'Write review button' does not exist :( "); }

Comment: **reviewButtonPresent = true** you meant **==** right? And note, when checking for booleans, just go `if (someCondition)` and avoid that == true or == false stuff.
Answer: The two instances of code you have are essentially the same and I see no reason for them to perform differently. My guess is that it's a timing issue. To make it behave more consistently, I would add a wait for the review button to appear. Since the button may not be there at times, it will throw a timeout exception so you will need to catch that to have a clean pass/fail for each run. To do this, I would use the function below that returns a boolean based on whether the element exists or not after waiting.
public static boolean elementExists(By locator, int timeout)
{
    try
    {
        new WebDriverWait(driver, timeout).until(ExpectedConditions.presenceOfElementLocated(locator));

        return true;
    } catch (Exception e)
    {
        return false;
    }
}

The above method tests for the "presence" of the element which means, does it exist in the DOM? If you want to make sure that it's actually visible (and not just present), you will want to change .presenceOfElementLocated() to .visibilityOfElementLocated().
Since you are new to Selenium, I would also recommend that you use a common library to do your validations like JUnit or TestNG. This will keep you from having to write your own custom code for validations and go through the process of finding bugs in your own custom code. Using JUnit, you would use
Assert.assertTrue("Verify the review button exists", elementExists(By.xpath("//ul[@class='comments_advices']"), 10));

See the JUnit docs.
Comment: thank you for the analysis. Since you say the two instances are essentially the same, do you see any errors in the code?
Comment: No, I don't see any errors... places for improvement, but no errors.
Answer: There are some differences between the two blocks of code.

Apparently your first code block is logically correct which is as follows:

Code:
int i = driver.findElements(By.xpath("//ul[@class='comments_advices']")).size();
if (i > 0)
    System.out.println("'Write review button' exists!");
else
    System.out.println("'Write review button' does not exist :( ");

Output:
Write review button' does not exist

But it's not perfect, which I will explain later in this discussion.

Your second code block is a bit deceptive as it contains two logical operators in the same line and you have left it to the compiler to decide the Operator Precedence which is a clear deviation from the best practices. Possibly you were lucky as > had more precedence then = as in:
boolean reviewButtonPresent = driver.findElements(By.xpath("//ul[@class='comments_advices']")).size() > 0;

Solution
Ideally you need to:

Induce WebDriverWait for the visibilityOfAllElementsLocatedBy().
Evalute the size() through a if()
Sample Code:
if (new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[@class='comments_advices']"))).size()>0)
    System.out.println("'Write review button' exists!");
else
    System.out.println("'Write review button' does not exist :( ");

Outro
Operator Precedence:

The operators in the following table are listed according to their precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
Comment: Your code doesn't do anything different than OP's except you put the first line inside the `if`. You added a wait, which I already covered, but the OP is asking about presence not visibility. Then you posted a ton of stuff about operator precedence which has nothing to do with this question. So what does your answer add?


Parse git log by modified files

Question: I have been told to make git messages for each modified file all one line so I can use grep to find all changes to that file.  For instance:
$git commit -a
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......

$git log | grep path/to/file.cpp/.h
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......

That's great, but then the actual line is harder to read because it either runs off the screen or wraps and wraps and wraps.
If I want to make messages like this:
$git commit -a
     modified: path/to/file.cpp/.h
               1) change1
               2) change2
               etc......

is there a good way to then use grep or cut or some other tool to get a readout like
$git log | grep path/to/file.cpp/.h
     modified: path/to/file.cpp/.h
               1) change1
               2) change2
               etc......
     modified: path/to/file.cpp/.h
               1) change1
               2) change2
               etc......
     modified: path/to/file.cpp/.h
               1) change1
               2) change2
               etc......

Comment: just post the output of `git log` in your question and also the desired output.
Answer: If the output of grep command shows like this,
$ git log | grep path/to/file.cpp/.h
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......

Then you can pipe it to the below awk command to produce the desired output,
git log | grep path/to/file.cpp/.h | awk -v RS='[-,]' '{print}'

Example:
$ cat aa
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......
     modified: path/to/file.cpp/.h - 1) change1 , 2) change2, etc......

$ awk -v RS='[-,]' '{print}' aa
     modified: path/to/file.cpp/.h
 1) change1
 2) change2
 etc......
     modified: path/to/file.cpp/.h
 1) change1
 2) change2
 etc......
     modified: path/to/file.cpp/.h
 1) change1
 2) change2
 etc......

Comment: Thanks Avinash Raj.  I guess it makes sense to just deal with initially writing the commit message for a file all on one line, then processing it after.

Parse git log by modified files


If statement inside variable

Question: Im trying to put the following inside a php variable.
I dont know what im doing wrong here :
$cartlink='' + if ( $count > 0 ) {"'.$count.'"} + '';

Comment: @Andrew no he's not
Comment: are you experienced in php :|
Comment: Possible duplicate of [PHP, Shorthand, If..Else using Ternary Operators](http://stackoverflow.com/questions/29814065/php-shorthand-if-else-using-ternary-operators)
Answer: Your string concat is a bit off, and PHP uses dots . to concat variables together, not + like JavaScript.
There are a couple of ways you could achieve this, via a ternary operator
$cartlink = ''.($count > 0 ? '"'.$count.'"' : "").'';

Or string concatination via a normal if
$cartlink = '';
if ($count > 0)
    $cartlink .= '"'.$count.'"';
$cartlink .= '';

Answer: You can't use if statement like that. Instead use inline version: (condition ? true_case : false_case)
You can write variables directly into quotes
echo "Value: $variable";
$cartlink="" . ( $count > 0 ? "$count" : "" ) . '';

edit: in php whole ternary operator have to be surrounded by brackets to work properly

If statement inside variable


Windows phone 8 web browser task

Question: WebBrowserTask webbrowsertask = new WebBrowserTask();
            webbrowsertask.Uri = new Uri("http://johndoe/index.php?dsa=51",UriKind.Absolute);
            webbrowsertask.Show();
            NavigationService.Navigate(new Uri("Mainpage.xaml",UriKind.RelativeOrAbsolute));

webbrowsertask.Show(); is executing this code and opens browser
I dont want to open browser , I just want to execute this code(got to this url , because i want this parameters to be sent in my site/database)
are there any other ways ?
Comment: use WebClient then. and remove WebBrowserTask
Comment: Can you give me an example based on this code with WebClient?
Answer: using System.IO;
using System.Net;

String URI = "http://somesite.com/somepage.html";

WebClient webClient = new WebClient();
Stream stream = webClient.OpenRead(URI);
String request = reader.ReadToEnd();

from here : http://www.codeproject.com/Articles/33798/HTTP-GET-with-NET-WebClient
It's raw idea but you can adapt it to whatever you like.
MSDN info: http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx
P.S. and you definitely need  a POST call, rather then GET, for storing data in your service/db/whatever, as you mentioned in question.
More info: How to post data to specific URL using WebClient in C#

Windows phone 8 web browser task


Segmentation fault while using FAISS `index.search()` in FastAPI

Question: I am trying to do an index search given a vector within a FAISS index that is saved on disk and is read into memory. This happens within a function that is called within an endpoint using FastAPI.
The endpoint and the function it is calling are the following:
# Endpoint
@app.get('/neighbours', response_model=Neighbours)
async def get_neighbours(case: str, ids: str, request: Request):
    """
       Retrieves a set of neighbors for a single id
    """
       id_list = ids.split(';')
       return Neighbours(result=get_neighbours_from_id(case, [int(id) for id in id_list]))

# Functions and objects
class Neighbour(BaseModel):
    id: int
    neighbours: List[int]

class Neighbours(BaseModel):
    result: List[Neighbour]

def get_neighbours_from_id(case, ids):

    case_path = validate_case_path(case)

    index = read_index(case_path.as_posix())
    # The above works well, the index is loaded properly.

    vec = index.reconstruct_n(0, 1)
    # This also works, I can see the vector being reconstructed.

    faulthandler.enable()
    faulthandler.dump_traceback()
    # Enabling faulthandler for the traceback

    d, i = index.search(vec, 1)
    # This is where the code crashes.

The code crashes when I am trying to do a search on the loaded index given a reconstructed vector, with the following traceback:
Current thread 0x000000010781adc0 (most recent call first):
  File "/../api/app/vectors.py", line 37 in get_neighbours_from_id
  File ".../api/service.py", line 87 in get_neighbours
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/fastapi/routing.py", line 160 in run_endpoint_function
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/fastapi/routing.py", line 227 in app
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/starlette/routing.py", line 61 in app
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/starlette/routing.py", line 259 in handle
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/starlette/routing.py", line 656 in __call__
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/fastapi/middleware/asyncexitstack.py", line 18 in __call__
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/starlette/exceptions.py", line 71 in __call__
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/starlette/middleware/cors.py", line 84 in __call__
  File ".../pypoetry/virtualenvs/env1-py3.8/lib/python3.8/site-packages/starlette/middleware/base.py", line 34 in coro
  File ".../anaconda3/lib/python3.8/asyncio/events.py", line 81 in _run
  File ".../anaconda3/lib/python3.8/asyncio/base_events.py", line 1859 in _run_once
  File ".../anaconda3/lib/python3.8/asyncio/base_events.py", line 570 in run_forever
  File ".../anaconda3/lib/python3.8/asyncio/base_events.py", line 603 in run_until_complete
  File ".../anaconda3/lib/python3.8/asyncio/runners.py", line 43 in run
  File ".../run_service.py", line 19 in <module>
Fatal Python error: Segmentation faultFatal Python error: Fatal Python error:

Segmentation faultFatal Python error:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

The traceback makes me think that it is something related to asyncio or multithreading within FastAPI?
Important to note that the exact same code (index loading, vector reconstruction and search) all work without any problems in the following minimal example within the same environment:
import faiss

index = faiss.read_index("my_index.index")

vec = index.reconstruct_n(0, 1)

d, i = index.search(vec, 1)

print(i)
# Works properly.

I have looked at this issue but it would seem like it is fixed in the newer versions of FAISS, and that is what I am using.
Thank you very much for the help!
Comment: Downgrading to 1.7.0 seemed to fix the issue for me... however the problem/question remains for the version 1.7.2. I'll submit a GitHub issue.
Answer: Segmentation faults are usually due to hardware/memory issues. I'm using a Macbook pro, so it was a mac issue for me. I could go with one of the following two options to make it work:

I switched from Mac to AWS EC2 / Linux
If I didn't want to switch to EC2 / Linux, I built a Ubuntu docker image and ran it in there


How can I tell what Pokemon I will get from an Egg?

Question: I am gonna try to hatch a Shiny Pokemon via the Masuda method, and I would like to know if there is a way to tell what the Pokemon will be before the egg hatches.
For example I'm gonna try to breed Feraligatr with Greninja to get a shiny Froakie with timid (Greninja has it).
But how do I know the egg won't hatch a Totodile?
Answer: Hatched Pokemon will always be of the mother's Pokemon type...
...except when breeding with a Ditto.

If Greninja is female and Feraligatr is male, then you will always hatch Froakies
Greninja is male and Feraligatr is female, then you will get Totodiles
If they are both the same gender (both male or both female) then they will be unable to breed.

If you are breeding a Pokemon with Ditto, then the gender does not matter - even some Genderless Pokemon (like Magnemite) can be bred with Ditto.
Another thing to keep in mind is that Pokemon are grouped into compatible breeding pools, known as 'Egg groups'. Luckily, both Greninja and Feraligatr are in the Water 1 Egg Group, which means they are compatible.
Comment: My Feraligatr is female so I would get Totodile then. So if I breed Greninja with Ditto instead, I will get Froakie
Comment: @Zayden - Yep that sounds correct. If your Greninja is male, you'll have to breed it with ditto to get Froakies


Automatically create links symbolic links between directories, creating one uber directory

Question: I have one directory, folder1, that I have shared via samba.  I have another directory, folder2, that is not shared, but contains a lot of subfolders that I do want to share.  When a user connects to my shared folder1 I would like them to also see the subdirectories from folder2.
Currently the way I accomplish this is to open up folder2 in gnome, right-click on the directories there, and select Make Links.  Then I take the symbolic links and manually cut and paste them into folder1.
I would like to have it so that when I create a new directory in folder2, a symbolic link to it is created inside folder1.  How should I go about this?  I'm using Ubuntu 14.04
Answer: There may be automagical ways to do this, but just writing a few shell scripts is probably the easiest way to address this.
First, instead of just creating a new subdirectory in folder2, do it with a script that also creates the symbolic link at the same time. The following untested script will do that once you fill in the real paths to your directories. The core script is really simple, but I added some error processing so it would have a chance in the real world.
#!/bin/bash
## create subdirectory and symbolic link
## Usage: script-name <name of new subdirectory to create and link>

PRIVATE="path to private directory" ## Put real path here
SHARED="path to shared directory" ## Put real path here
cd "${PRIVATE}"
if [ -z "${1}" ]
then
  echo "Aborting - no new directory name specified"
  exit 1
fi

if [ -e "${1}" ]
then
  echo "Aborting - file or directory with that name already exists"
  exit 1
fi

mkdir "${1}"
RC=$?
if ((RC))
then
  echo "Aborting - Failed to create new private subdirectory named [${1}] in [${PRIVATE}] with error code [${RC}]"
  exit ${RC}
fi

cd "${SHARED}"
ln -s "${PRIVATE}/${1}" .
RC=$?
if ((RC))
then
  echo "Aborting - Failed to create new symlink named [${1}] in [${SHARED}] with error code [${RC}]"
  exit ${RC}
fi

exit 0

Other concerns:
If you need to access this from a gui instead of the command line, just add a little code that calls yad to create a dialog box to ask for the name of the directory to create and then create an entry for your script in your menu system and, optionally, on your desktop or panel. Doing this is simple, but beyond the scope of this question.
Similarly, if something else creates the new subdirectories in folder1, you can write a script which scans for new subdirectories in folder1 and then symlinks them to folder2.
You could run this manually, or run it inside of a loop where it does its work, sleeps for awhile, and then runs again.
This "daemon" script could either be started manually or run from your .login script so it will start every time you login. It could also be started from cron if you make sure that any subdirectories and links it creates have the desired owner, group, and permissions. (You probably don't want them owned by root which is the user cron runs under.)
It all depends on what your exact requirements are.
If either folder1 or folder2 require elevated privileges for writing, then your script will need to either be run with those permissions or have a sudo or two to handle that, and possibly, an entry in sudoers so it doesn't have to ask for your password every time. Then, the script itself would have to have a secure owner and restricted permissions and be kept in a directory which also requires elevated privileges for writing - for security reasons.
You may also need to consider the case when subdirectories are deleted from folder1. Then, you will probably want to delete the broken symlinks from folder2. The approach/code would be very similar to the above.


python - py-expression-eval - Passing a numpy ndarray

Question: I am using py-expression-eval library for evaluating an expression.
import numpy as np
from py_expression_eval import Parser
parser=Parser()
a = np.array([1,2,3])
parser.parse('x*5').evaluate({'x':a})
#Works and outputs
array([  5.,  10.,  15.])

However:
parser.parse('sin(x)').evaluate({'x':a})

throws an error:
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
parser.parse('sin(x)').evaluate({'x':a})
File "C:\Python27\lib\site-packages\py_expression_eval\__init__.py", line 133, in evaluate
nstack.append(f(n1))
TypeError: only length-1 arrays can be converted to Python scalars

But if I pass values of array one by one it works:
parser.parse('sin(x)').evaluate({'x':a[0]})
0.8414709848078965

Answer: Looks like sin is hardwired to math.sin. Replacing it with np.sin works:
parser.ops1['sin'] = np.sin
parser.parse('sin(x)').evaluate({'x':a})

array([ 0.84147098,  0.90929743,  0.14112001])

Operators are in ops2:
parser.ops2['^'] = np.power
parser.parse('x^2').evaluate({'x':a})

array([1, 2, 3])

Comment: Thanks..Works with cos, tan, asin, acos, atan, log ,ceil ,floor, round, exp functions also. Now only problem is '^', which is implemented using math.pow function. Replacing with np.power doesnot work.
Comment: Added a solution for `^`.
Comment: whoa....Thanks....I was certain that I used ops2...It didn't work yesterday....But now it is working...:)


jdbc template failsafe IN statement

Question: Is there a way to get multiple rows using Spring's jdbc template that is fail safe?
Something like in this post:
https://stackoverflow.com/a/1327222/1321514
Set<Integer> ids = ...;

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);

List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
     getRowMapper(), parameters);

But being able to return all the ids regardless the DB's limit for the number of parameters. So if the DB can only accept 2000 parameters within the IN clause and I'm passing 2001 I get the 2001 records.
Answer: You can do this with the help of temporary tables wherein first you need to create it n then dump all values IN values on it. Later you need to use that table in a join or sub-query to associate with main table where you wanted your IN caluse initially. Complete JDBCTemplate code can be found here http://forum.spring.io/forum/spring-projects/data/63634-spring-jdbc-and-sybase-temp-tables
Comment: Thanks, I wanted to avoid using temporary tables, but I guess the only other option is to do it in batches, selecting 500 ids or so each time and merging them together.
Comment: That's correct either temporary table or in batches.
Answer: You can do it by breaking up the parameters list into smaller batches of around 100 or maybe more. I remember that I had written a similar code where I was creating a dynamic select query based on the batch count and passing a subset of the total parameters. For example, In case of 2001 records my function would have created 21 queries such as SELECT * FROM
 WHERE <column> IN (?,..<batchSize>..,?).
Answer: I am (quite radical) user of parameters (in query), but series of int's in clause "in" I concatenate as string (in Java using StringBuilder of-course), so final query string is:
"SELECT * FROM foo WHERE a IN (215, 567, 957, 1298)"

To be clear: IN based on enumeration, not relation to slave table, this is different story
Limit of query string length is quite big (different in databases? probably yes)

jdbc template failsafe IN statement


502 Bad Gateway - Nginx - Unicorn suddenly stopped working, Nginx logs empty

Question: BIG EDIT WITH THE ANSWER
If your Nginx application throws you a "502 Bad Gateway", check inside your Nginx conf files /etc/nginx/conf.d/*, probably you might have the same domain declared twice in different .conf files. Nginx error logs WON'T show you anything.
=====
I have a few Rails Applications running on same Centos VPS. Those apps are running with Nginx and Unicorn. Today I noticed that one app throws a "502 Bad Gateway" error. Other Rails Application are fine.
Therefore, I'm not sure what might have caused this error, but yesterday I did some changes to VPS, I changed my ssh port and then executed shutdown. Other Apps are fine, only that one isn't. However, I'm not sure if that is the cause.
I've been trying restarting both Unicorn and Nginx, but website still doesn't respond.
What is really frustrating is that /var/log/nginx error logs is empty, Rails production log is also empty. Only Unicorn stderr log has some kind of info:

myweb/current/log/unicorn.stderr.log

INFO -- : worker=1 ready
INFO -- : reaped #<Process::Status: pid 595 exit 0> worker=0
INFO -- : reaped #<Process::Status: pid 598 exit 0> worker=1
INFO -- : master complete
INFO -- : Refreshing Gem list
INFO -- : unlinking existing socket=/var/sockets/unicorn.myweb_production.sock
INFO -- : listening on addr=/var/sockets/unicorn.myweb_production.sock fd=11
INFO -- : worker=0 ready
INFO -- : master process ready
INFO -- : worker=1 ready

I don't think there is a problem with my Nginx.conf file, It's template-generated and it works with all webs. Here it goes:

/etc/nginx/conf.d/miweb.conf

upstream unicorn_myweb_production {
  server unix:/var/sockets/unicorn.myweb_production.sock fail_timeout=0;
}
server {
  listen 80;
  client_max_body_size 4G;
  keepalive_timeout 10;

  error_page 500 502 504 /500.html;
  error_page 503 @503;

  server_name myweb.com www.myweb.com;
  root /var/www/myweb/current/public;
  try_files $uri/index.html $uri @unicorn_myweb_production;

  location @unicorn_myweb_production {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://unicorn_myweb_production;
    # limit_req zone=one;
    access_log /var/log/nginx/myweb_production.access.log;
    error_log /var/log/nginx/myweb_production.error.log;
  }

  location = /50x.html {
    root html;
  }

  location = /404.html {
    root html;
  }

  location @503 {
    error_page 405 = /system/maintenance.html;
    if (-f $document_root/system/maintenance.html) {
      rewrite ^(.*)$ /system/maintenance.html break;
    }
    rewrite ^(.*)$ /503.html break;
  }

  if ($request_method !~ ^(GET|HEAD|PUT|POST|DELETE|OPTIONS)$ ){
    return 405;
  }

  if (-f $document_root/system/maintenance.html) {
    return 503;
  }

  location ~ \.(php|html)$ {
    return 405;
  }
}

Unicorn file:

myweb/shared/config/unicorn.rb

working_directory "/var/www/myweb/current"
pid "/var/www/myweb/shared/tmp/pids/unicorn.pid"
stdout_path "/var/www/myweb/shared/log/unicorn.stdout.log"
stderr_path "/var/www/myweb/shared/log/unicorn.stderr.log"

listen "/var/sockets/unicorn.myweb_production.sock"

worker_processes 2
timeout 30

preload_app true

before_exec do |server|
  ENV["BUNDLE_GEMFILE"] = "/var/www/myweb/current/Gemfile"
end

before_fork do |server, worker|
  # Disconnect since the database connection will not carry over
  if defined? ActiveRecord::Base
    ActiveRecord::Base.connection.disconnect!
  end

  # Quit the old unicorn process
  old_pid = "#{server.config[:pid]}.oldbin"
  if File.exists?(old_pid) && server.pid != old_pid
    begin
      Process.kill("QUIT", File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
      # someone else did our job for us
    end
  end

  if defined?(Resque)
    Resque.redis.quit
  end

  sleep 1
end

after_fork do |server, worker|
  # Start up the database connection again in the worker
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
  end

  if defined?(Resque)
    Resque.redis = 'localhost:6379'
  end
end

Comment: Your rails app and unicorn are definitely working, must be problem from the Ngnix side. What kind off error you getting in the browser?
Also try putting some dummy index.html in /var/www/myweb/current/public and try to restart Nginx, then open browser, just of purpose of pinpoiting the problem, if index.html is not shown then problem is in webserver and not in rail.
Comment: The error is 502 Bad Gateway. I have tried adding index.html inside /public and restarting nginx, but it's the same. Other websites witn Nginx in same VPS work fine.
Comment: Just for testing, inside deploy/production.rb I added two new domains as nginx_server_name, with those the application works. But it doesn't with the former domain. Any hint?
Answer: After many hours, I found that the source of my problem was that (by mistake) I had two different /etc/nginx/conf.d/ files using the same server_name. That was the source of my 502 Bad Gateway.


radio click not showing

Question: How do i check to see if a radio button is clicked?
$(document).ready(function() {
$("#rad").click(function() {
        var radio = $("#rad input:checked");
        if(radio == 0)
        {
            alert($(this).data('id'));
        }
    });
});

[html]
<input type="radio" data-id='1' name="default" class="rad" value="1">
<input type="radio" data-id='2' name="default" class="rad" value="1">
<input type="radio" data-id='3' name="default" class="rad" value="1">
<input type="radio" data-id='4' name="default" class="rad" value="1">
<input type="radio" data-id='5' name="default" class="rad" value="1">

Comment: Did the below answers helped you ?
Answer: In the code rad is class not id so use the class selector instead of id selector to bind event.
Live Demo
Change
$("#rad")

To
$(".rad")

When ever you click a radio button it is check so you do not need to verify it again, and $(this) represents source of event you can use it directly, your code would be
$(".rad").click(function () {
    alert($(this).data('id'));
});

Answer: you could get your radio buttons by name and then check to see which one is clicked. like this,
    $(function() {
    $('input[name="default"]').click(function() {
     var getID = $(this).attr('data-id');
      alert(getID);
     });
    });

Answer: You should be selecting element via class selector instead of id selector first, then you check for the checked status if you need but since you click it its always gonna be checked.
after that use .attr() method to get the data-id attributes data
$(document).ready(function(){
      $(".rad").click(function() {
        if($(".rad").is(":checked")) { // not necessarily needed
            alert($(this).attr('data-id')); // use data-id inside .attr()
        }
    });
});

Answer: Check here for Demo
JQuery
$(document).on('click', '.rad', function () {
    alert($(this).attr('data-id'));
});

Make sure that you have 1.7+ Jquery

Alternative - 1
$(document).ready(function () {
    $('.rad').bind('click', function () {
        alert($(this).attr('data-id'));
    });
});

Alternative - 2
$(document).ready(function () {
    $('.rad').click(function () {
        alert($(this).attr('data-id'));
    });
});

radio click not showing


MobX, React Router v4, Route using render function not observing and re-rendering when store changes

Question: Using a route that needs props passed in to the components, I'm passing in a boolean that is observable from my store. When this value changes, components rendered by the route are not updated.
<Switch>
    <Route exact path="/" render={()=><MyComponent isLoading={this.props.MyMobxStore.ShowMyComponentLoader} />} />
</Switch>

This component is Observable and injected with MyMobxStore. If I change that observable, the component "MyComponent" is not re-rendered or notified about the change.
If I call any arbitrary "setState" on my top level component, it works. or if I add a dummy element such as

that makes the current component re-render such that "MyComponent" that depends on this observable behaves as expected.
Is there an obvious solution that I'm missing? I can add one of these hacks to make it work. I could wrap my "MyComponent" in another observable and pass it down that way, But that isn't conducive with my design. Though It doesn't matter that much. This is purely academic at this point. I'd like to know why it doesn't work.
Update
was asked to include more code.

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import {inject, observer } from 'mobx-react';
import {MyComponent, CoolChildComponent} from '.coomComponents';

@inject('LoaderStore')
@observer
class App extends Component {

    componentWillMount() {
        this.props.LoaderStore.setShowLocalLoader(true);
        setTimeout(() => {
            this.props.LoaderStore.setShowLocalLoader(false);
        }, 5000);
    }

    render() {
        return(

            {/* note router container and "with router" wrapper one level up. */}
              <Switch>
                  <Route render={()=>{return <MyComponent isLoading={this.props.LoaderStore.showLocalLoader}><CoolChildComponent/></MyComponent>}} />
              </Switch>

        );
    }
}

export default App;

note, I know ways to get around this. What I don't understand is why MobX doesn't realize that render is using LoaderStore.showLocalLoader
Answer: try the following:
render() {
    const showLocalLoader = this.props.LoaderStore.showLocalLoader
    return(

        {/* note router container and "with router" wrapper one level up. */}
          <Switch>
              <Route render={()=>{return <MyComponent isLoading={showLocalLoader}><CoolChildComponent/></MyComponent>}} />
          </Switch>

    );
}

this will cause the correct value to be sent as prop to the Route,
there is an issue that sometimes the change in value doesn't trigger re-rendering when the observable is nested inside the return value of render.
let me know if it worked
Comment: bingo. That makes a lot of sense. I'm not sure why I didn't think of that one.
Answer: sounds like you are missing an observer wrapper for MyComponent
you can use @observer if you have support for decorators else you should enable decorators as shown here,
hopes that helps, if that's the issue here is a little explanation:
when you set an observable in a mobx store you can react to a change of this observable in a few ways (i'm just listing 2 for more options see the mobx docs):

using autorun - more info
using @observable - more info

both this methods work on the same principles, just that in the option of observable what happens is that the render function works like autorun works
it's pretty straight forward if you have an observable inside the function it will trigger it every time the observable in the function scope changes
good luck!
Comment: MyComponent is marked Observable. But that's not the issue, If I use the observable value directly from the store in MyComponent it works as expected, but if I pass the observable value down as a prop it doesn't. I can get around the issue in 3 ways. I just don't understand if the current component is watching the use of the value, and I pass that value to a child component as a prop inside the render function. Why doesn't react/mobx trigger the update. it's clear that mobx x doesn't see that it's being used. I just don't understand why.
Comment: if you can add the code or just the way you're propagating the observable down, I could be much more helpful, and just to make sure, when you say the component is observable you mean observer?
Comment: I added more code. It is the way I'm passing it down. I just don't understand why this way doesn't work. I've fixed the issue already by using a wrapper component around  But I want to know why fundamentally this doesn't work.


Repairing a broken screw hole on a plastic junction ceiling box?

Question: One of the screw holes on a junction box on my ceiling has fallen apart, leaving a hole that is too big to fix a screw into (see top of picture). As a result, I cannot hang my smoke detector from the junction box, since the detector hangs from the heads of the screws.
I was trying to see if there was something I could fill the hole with to then make a new hole for the screw. This would save me the cost and hassle of having the box replaced, which I assume would require cutting into the ceiling (the box seems to be affixed to a brace above the ceiling that runs between two joists, since all I see is the head of a bolt at the top of the box and no nail heads anywhere). Any thoughts on what I could do here?
Thanks
Comment: it looks kind of like plastic to me
Comment: It is probably possible to remove the box and replace it without cutting into the ceiling. Also fixing hole in the ceiling is not rocket science. Attempting to fix the box is not advisable.
Comment: you see that the box is attached with a screw and you are asking what to do next?
Comment: that screw is for the cover.
Answer: That box is a type of plastic called Bakelite. It's tough, but brittle. If you're careful, you can break the box apart without damaging the ceiling. If you have a hole saw, you can probably drill out around the rivet heads you see in the back of the box and it will come right out.
Then you can replace it with a new "old work" box.
Answer: Yep, you can fill it by tightly stuffing it with even just damp toilet paper, paper towel or napkin(s), then let fully dry and harden...a liberal coating of Krazy Glue on the first wad would help.
Otherwise, a wood putty or auto body (car) dent filler (Bondo) would likely be a more permanent solution for future smoke detectors. If you can drill small holes through the sides, then the insert of a nail or brad for the filler to stuff around will really help durability.
Answer: I'd just use a toggle bolt. No need to patch or replace the box if the outer shell is intact.


Is there any preferable time to play through the season pass missions?

Question: I'm just past the end of Act One, and my phone is offering the various DLC missions as well as the next story mission.  Is there any advantage in holding off on completing them vs rushing to do them as fast as possible? For example, are the DLC missions' rewards likely to make story missions easier, or vice versa? Or maybe the difficulty varies?
Answer: I think that if you complete the DLC missions first, they make the game easier, and if you complete the game first, that makes the DLCs easier. But, it would be better to complete the DLCs first, they give you a lot of money, respect and new guns that can make the game easier.
Answer: Completing the DLC missions, like Lucca Dornelles said, will make the main game story missions easier. Since you can't replay the main game story missions after you finish them (unless you're playing on the PC and have installed a mission replay mod), and you can replay the DLC missions after you finish them, completing the DLC missions as soon as possible may be preferable.
Also, completing the DLC missions are the only ways to add additional 'Brute' homies (aside from Oleg in the main game). So if you want to have 3 brutes with you as homies, completing the DLC missions as soon as possible is preferable.
Screenshot of the DLC-added 'Brute' homies (possible spoilers):


How to make a new profile?

Question: My mum dad and brother all use my computer, so I thought of making accounts but I am not sure how to make an account.
I want to make an account that has few privileges like a normal account, not administrator.
I am using trusty tahr 14.04
Thanks!
Comment: [Add a new user account - Ubuntu Help](https://help.ubuntu.com/stable/ubuntu-help/user-add.html)
Answer: Load up a terminal or console window and use the following command:
<code>sudo useradd <username>
</code>
That will create a basic user inside of ubuntu for you.  When a user needs to use administrator rights it will prompt them.

How to make a new profile?


Counting singularities

Question: It is well known that a smooth vector field on a 2-sphere must vanish twice.
What is the general technique for counting singularities of a smooth map between manifolds? For example, how many singularities must a smooth, surjective map $\phi: V \rightarrow SU(n)$ possess? Here $V$ is a finite dim vector space over $\mathbb{R}$. Can this be established via any analogous method to the vector field on the sphere.
Comment: The first sentence isn't a special case of the second sentence. Anyway, for maps to $\mathbb{R}$ what you want is called Morse theory, and for vector fields what you want is called the Poincare-Hopf theorem. I don't know what the general situation is.
Comment: I realize that it's not exactly a special case. I just wondered if there was something in the same spirit using the Euler characteristic.
Comment: It also depends on what you mean by "singularities." In the case of maps to $\mathbb{R}$ I mean points at which the derivative vanishes, but in the case of vector fields I mean points at which the vector field vanishes. I don't know what you mean for a map to $SU(n)$.
Comment: Points where the Jacobian has rank less than the largest possible rank.
Comment: The first sentence is false. Wikipedia kindly provides a counterexample: http://upload.wikimedia.org/wikipedia/commons/1/14/Hairy_ball_one_pole.jpg
Comment: It is true if you include the multiplicity of the zero
Answer: Concerning your first case. Section 9 of Heinz Hopf's lecture notes on differential geometry is called: "the role of the euler characteristic in the theory vector fields" which generalizes your first statements to surfaces:
Theorem: Summing up the singularity of any vector field on a surface, gives the Euler characteristic.
Answer: Well here's maybe a somewhat enlightening example. Any smooth map $f:M\rightarrow \Bbb R^n$ where $M$ is an $m$-dimensional closed compact manifold has infinitely many singularities (for $n\geq 2$ and $m\geq n$). If $f$ only had finitely many singularities, then $f(M)\subset \Bbb R^n$ would be compact with non-empty interior and hence have infinite topological boundary (for $n\geq 2$). By the inverse function theorem, a topological boundary point must be a critical value.
In fact using a little covering space theory, we can conclude from this that any map from $S^2$ to a closed orientable surface of genus $\geq 1$ also has infinitely many singularities.
Generically, I do not think one should expect there to even exist maps where singularities are isolated, so the case where the target is $\Bbb R$ (as in Morse theory) is quite special.
Edit: Here's a further generalization of the above that should be easy for anyone interested to fill in the details. Let $M$, $N$ be smooth compact manifolds (without boundary) with $\operatorname{dim}M \geq \operatorname{dim}N$. If we have $p(\pi_1(M))$ has infinite index in $\pi_1(N)$ for any homomorphism $p: \pi_1(M) \rightarrow \pi_1(N)$, then any map $f:M \rightarrow N$ has infinitely many singularities.
Comment: I tried to up vote this, but it won't let me! Sorry +1

Counting singularities


Html onmousedown vs href Precedence

Question: I use the following code in one of my html pages.
When user clicks "Search Engines" links it opens yahoo.com on a new page and Google on current page.
I've tested this and it works (opens both urls), but is there any chance that the page will complete the window.location (redirect to a different page) without completing the href command?
Is there a rule for Precedence between the two command?
**Note: I know I can solve the problem in different ways, but I'm curious about this specific situation.

    <title></title>

Search Engines

Answer: The mousedown event will happen first, but as you can see from the fact your code is currently working, that's not the whole story.
The question is: Once the mousedown has happened and you've set window.location, does the page get whisked away immediately (and therefore processing of the default action of the click on the a element doesn't happen), or does that default action get completed before the page is destroyed and replaced with the new page?
The answer is: I don't think that's guaranteed behavior at all (either way), and I wouldn't rely on it cross-browser. For one thing, what if the user holds down the mouse button? Since the default action of an a element isn't triggered until a click, which requires a mouseup.
Instead, I'd probably hedge my bets, in two ways:
First, I'd use click, not mousedown, for this. Users don't expect pages to swap out when they just hold the mouse down.
Second, I'd change your function:
function clickRedirect() {
    setTimeout(function() {
        window.location = "http://www.google.com";
    }, 0);
}

Now you're specifically giving the browser a chance to complete the default action of the click before you go off to another page.
You might find more information on this buried deep in the DOM events specifications:

DOM2 Events
DOM3 Events

...in that they might say something about what should happen when an event is in progress and the page is being destroyed. I didn't immediately see anything.
Comment: Thank you for the detailed information , this is just what i was afraid of - the order isn't set in stone and can go either way. i also considered using a timeout (i guess you didn't mean to use timeout with zero).
Comment: @sharru: No, the `0` is intentional, it's quite a standard technique when you need something to be asynchronous, but almost instantaneous: Using `0` sets the *minimum* timeout that the browser supports (typically between 5 and 10 ms). Short enough to be imperceptible to humans (we don't tend to notice things until 50-100ms), but using any timeout at all allows the browser to finish the event processing. (Again, I'd use `click`, not `mousedown`, so you know that the processing has begun at that point.)

Html onmousedown vs href Precedence


Cannot use Steam after upgrade Trusty 14.04.1 to the 14.04.2 HWE

Question: sudo apt-get install libgl1-mesa-glx:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
gnome-control-center : Depends: libcheese-gtk23 (>= 3.4.0) but it is not going to be installed
                    Depends: libcheese7 (>= 3.0.1) but it is not going to be installed
libgl1-mesa-glx:i386 : Depends: libglapi-mesa:i386 (= 10.1.3-0ubuntu0.3)
                    Recommends: libgl1-mesa-dri:i386 (>= 7.2)
unity-control-center : Depends: libcheese-gtk23 (>= 3.4.0) but it is not going to be installed
                    Depends: libcheese7 (>= 3.0.1) but it is not going to be installed
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages

Answer: It`s a bug already reported in launchpad https://bugs.launchpad.net/ubuntu/+source/mesa/+bug/1424263
Some people are having luck with these packages:
sudo apt-get install libc6:i386 libgl1-mesa-dri-lts-utopic:i386 libgl1-mesa-glx-lts-utopic:i386

Answer: If you're now using the HWE mesa stack then you are trying to install the wrong package.
With trusty -proposed still enabled -
sudo apt-get -s install libgl1-mesa-glx-lts-utopic:i386
If the simulation looks good then rerun the command but remove the -s
Comment: Nope
The following packages have unmet dependencies:
 libgl1-mesa-glx-lts-utopic:i386 : Depends: libglapi-mesa-lts-utopic:i386 (= 10.3.2-0ubuntu1~trusty2) but it is not going to be installed
Answer: When installing the HWE if you combine the apt-get command from the official Ubuntu HWE site with the fix from  Launchpad Bug #1424263 you can install the HWE safely (i.e without risking it de-installing Skype, Steam, WINE or any other 32-bit apps). The combined command is:
sudo apt-get install --install-recommends xserver-xorg-lts-utopic libgl1-mesa-glx-lts-utopic libegl1-mesa-drivers-lts-utopic libc6:i386 libgl1-mesa-dri-lts-utopic:i386 libgl1-mesa-glx-lts-utopic:i386

Note that Steam will still pop-up a little terminal window on launch and try to install some 32-bit mesa packages (since Steam isn't clever enough to know to look for the Utopic mesa packages you've installed with the above command). But this is a minor annoyance since all you need to do is ctrl+c or close the terminal window and Steam loads and runs fine.


Changing 3 way switch to a half 3-way switch half outlet, missing a neutral

Question: I'm attempting to swap out a 3-way switch for a half 3-way switch / half outlet single gang receptacle.
I've got the three way switch working (I believe it was incorrectly wired to begin with), but the outlet does not work and there is no neutral. Is there anything I can do?
Here is a photo while I was in the middle of wiring it up (ground not connected).
Comment: Short answer: If you can't run another cable to that j-box, there's nothing you can do to add an outlet and retain three-way switching.
Comment: You have no full time neutral. No neutral. No workie.
Comment: Can you post photos of the insides of the rest of the boes involved?
Comment: That's what I was afraid of. There's not really anymore to see. There are those 3 wires + ground. That's it.
Comment: From other comments, that look improbable, but... Are you certain the swich and outlet share the neutral? What if you move the white wire to that other neutral, below, beside the ground?
Comment: Also, if you really have no neutral and this wire is unused, where does that cable go? Most likely, there's a neutral wire there, at the appliance controlled by that switch.
Comment: @Jeffrey That white wire is not a neutral actually. It was miswired from the beginning and that is a common I believe (which is hot?).
Comment: yeah, had totally missed the "three-way" part
Answer: Most three-way switch circuits from homes of the 20th century will not have a neutral at the switch box.
The white wire should be reidentified as blue or another color. It is either the hot feed to the 3-way circuit or the switched leg to the lights.
The only way to have a receptacle at this location is to add another 2 wire cable from a source having an actual neutral.
Good luck!
Answer: This is the "switch-loop" end of a 3-way switch loop circuit.  You cannot fit a receptacle because they need hot and neutral, which are not present here.
Use a smart switch
This circuit can be rewired using smart switches to provide hot and neutral here.
In that case, white and black would be re-assigned to be hot and neutral.  The red wire would become a communication wire, if your smart switch type requires it.   Typically "smart" 3-ways are made as a master and remote; the remote would be here.
That would provide the hot and neutral which the receptacle also requires.
Wire colors
It's really hard to understand 3-way circuits because all wires are black, white and red.  They seem to do all different things.   Those colors are only used because that's how the cable is manufactured.  You can make things a lot clearer by marking electrical wires by function.  A 5-pack of electrical tape makes this easy. Mind you, if neutral is present, it must be on the white wire.  Otherwise, tape away, but mark each wire the same on both ends.  I like

black for always-hot, as to a receptacle
red for switched-hot to a lamp
yellow for both travelers. There isn't really any need to tell them apart.

Now it looks like this. Now it's clear what those wires are doing, none are hot or neutral, and that's why your receptacle can't work.

Lastly, there's a way to do this with "old fashioned relays".  It's what Tesla would do in 1910, but smart switches are easier so I'm excluding the details. If you want them, ask.


FragmentTransaction animation: onAnimationEnd is called before it really ended

Question: My question is very similar to this question, except that I need it to work with fragments instead of Views.
As explained in that thread, there seems to be a bug(?) in Android when an AnimationListener is attached to an Animation, which results in the onAnimationEnd() callback getting called before the animation has really completely ended.
I'm using fullscreen fragments which are animated in the FragmentTransaction (v4 support library) to have a horizontal "roll-in" effect. This works smoothly everywhere except in the fragment where I start a camera preview. Therefore I want to only start the camera preview once the animation is finished.
I tried using this method in my Fragment:
<code>@Override
public Animation onCreateAnimation(final int transit,final boolean enter,final int nextAnim)
{
  Animation anim=super.onCreateAnimation(transit, enter, nextAnim);

  if (anim==null && nextAnim!=0)
    anim=AnimationUtils.loadAnimation(getActivity(), nextAnim);

  if(anim!=null)
  {
    anim.setAnimationListener(new AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation)
    {
    }

    @Override
    public void onAnimationRepeat(Animation animation)
    {
    }

    @Override
    public void onAnimationEnd(Animation animation)
    {
      scannerView.startCameraInHandlerThread();
    }
  });
}
</code>
Unfortunately starting the camera is quite an expensive operation and so my animation lags every time right before the animation is over. It looks ugly and my client is complaining about it.
I also thought about a cheap solution like waiting/sleeping on the camera thread, but the main thread actually needs to wait for the camera starting thread for synchronization otherwise it can deadlock in some cases, so sleeping actually makes the issue worse (the lag becomes longer).
Does anyone know how to solve this?

edit: someone asked for more code...
<code>public void startCameraInHandlerThread()
{
  if (mThread == null)
    mThread = new CameraHandlerThread();

  synchronized (mThread) {
    mThread.openCamera();
  }
}

private class CameraHandlerThread extends HandlerThread
{
  Handler mHandler = null;

  CameraHandlerThread()
  {
    super("CameraHandlerThread");
    start();
    mHandler = new Handler(getLooper());
  }

  synchronized void notifyCameraActionCompleted() {
    notify();
  }

  void openCamera()
  {
    mHandler.post(new Runnable() {
      @Override
      public void run() {
        startCamera();
        notifyCameraActionCompleted();
      }
    });

    try
    {
      wait();
    }
    catch (InterruptedException e)
    {
      Thread.currentThread().interrupt();
      LOG.warn("Waiting for camera opening was interrupted");
    }
  }
}
</code>
Comment: Post your code of startCameraInHandlerThread
Comment: I don't think that code is so relevant, but there you go. It starts a new thread which will then create a SurfaceView for camera preview and then open the camera.
Comment: I think its a possible duplicate of http://stackoverflow.com/questions/4750939/android-animation-is-not-finished-in-onanimationend, hope it helps.
Comment: I actually referenced that thread in my first sentence, you must have missed it.
Comment: did you find a different solution for that meanwhile? i am having the same issue
Comment: sorry that was years ago, don't remember...but I seem to have posted a solution below
Answer: I was able to come up with a workaround: Just delay the start of my method for a very short time to give the animation time to run to completion. On the devices that my client is going to use this works fine but I don't feel that it's a general enough solution, therefore I'm not going to mark this as the accepted answer.
<code>@Override
public void onAnimationEnd(Animation animation)
{
  new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
      scannerView.startCameraInHandlerThread();
    }
  }, 10); // will start after 10ms
}
</code>
Comment: in onCreateAnimation return a test Animation that does nothing (class A extends Animation) but overrides applyTransformation and Log.d interpolatedTime parameter,  see if it is called after onAnimationEnd callback was called


scrollbar moves rough when activating fastscrollenable in android listview

Question: scrollbar moves roughly while scrolling. how to make scrollbar move smoothly when enable fastcrollenable="true"?
I've been looking for it for a month. both in android documentation, stackoverflow, and other web ,but i can't find it.
in my listview , im just add....
android:fastScrollEnabled="true"

Answer: setSmoothScrollbarEnabled(boolean enabled)
When smooth scrollbar is enabled, the position and size of the scrollbar thumb is
computed based on the number of visible pixels in the visible items.

note that sometimes your answer would be easily found in java


Model "Behaviors" in Django

Question: I'm new to Django, moved from PHP with Propel ORM engine.
So here is what I am currently doing in Django. My website has several models like

Book,
Publisher,
Comment,
Article and so on (it's not the point)

Each of them can can be
liked or disliked by a user (only once) changing the model's rating by +1 or -1.
In terms of PHP i would create a behavior, for ex. "Rateable" which would add some fields and methods to the original model and query class (like get_rating(), order_by_rating(), etc) and create a separate table for each model, for ex. book_rating_history which would hold all of the ratings for each object, to determine if the user can or can't change the rating (or show all object's ratings, if necessary). So all I would need to do is to specify the "Rateable" behavior in the model declaration, and that's all. Everything else is done automatically.
The question is - how to solve this in Django? How to model correctly? Which techniques do you use in similar cases?
Answer: You'll want to store ratings and books separately, something like this (untested).
from django.contrib.auth.models import User
from django.db import models
from django.db.models import Sum

class BookRating(models.Model):
  user = models.ForeignKey(User)
  book = models.ForeignKey('Book')

  # you'll want to enforce that this is only ever +1 or -1
  rating = models.IntegerField()

  class Meta:
    unique_together = (('user', 'book'),)

class Book(models.Model):
  title = models.CharField(max_length = 50)

  def rating(self):
    return BookRating.objects.filter(book = self).aggregate(Sum('rating'))

unique_together enforces that each user can only rate a given book once.
You can then use this something like:
book = Book.objects.get(pk = 1)
rating = book.rating()

Add a comment if you have problems with this - I've not tested it, but hopefully this is enough to get you started.
You can probably avoid each object (books, publishers, comments, articles) having a separate rating object using content types, if you want.
Alternatively, you might consider looking at existing reusable apps that handle liking, like django-likes or phileo.
Comment: Bonus feature: the user can change their rating at a later time.
Answer: You can define special methods (for example vote, get_rating, etc.) only onсe in abstract model and then create your "Rateable" models using this one.
class Rateable(models.Model):

    class Meta:
        abstract = True

    def vote(self, *args, **kwargs):
        ...

    def rating(self, *args, **kwargs):
        ...

class Book(Rateable):
    ...

Also it is better to use single model for storing rating data witch content types as noticed Dominic Rodger
Comment: Thanks guys, I've read the documentation for the content types framework and decided to use it for ratings, tags and similar stuff.

Model "Behaviors" in Django


Are there any nonlinear Lie groups in 1D?

Question: The classical example of a nonlinear Lie group is $\mathrm{SL}(2,\mathbb{R})$ (the group of 2-by-2 real matrices with determinant one).
But, are there any one-dimensional nonlinear Lie groups?
For example, consider $a,b\in\mathbb{C}$, equipped with an operation defined $$a*b\equiv\sqrt{a^2+b^2}.$$  It would seem that $\mathbb{C}$ forms a Lie group under $*$, with identity $e=0$.  And it would seem to be nonlinear.  But I suppose, because it acts on the complex plane, it's two-, not one-dimensional.
Comment: Your proposed multiplication makes no sense. If $a$ and $b$ are complex numbers, then $a^2+b^2$ is complex, and there's no continuous way to define the square root.
Comment: What's your definition of a nonlinear Lie group?
Comment: Why is the special linear group not linear?
Comment: I suppose a nonlinear Lie group is one which is not a subgroup of $\mathrm{GL}(n)$ (see https://mathoverflow.net/questions/91789/non-linear-lie-group?rq=1 - I should have said the "universal cover" of $\mathrm{SL}(2)$).  Please ignore my example if it is flawed.
Comment: Every connected 1-dimensional real Lie group is linear, since it is either isomorphic to $S^1$  or to ${\mathbb R}$. Same for connected 1-dimensional complex Lie groups: There are three of them up to an isomorphism; the compact one is real-linear but not complex-linear.
Comment: Thanks Moishe, can you post this as an answer, as well as giving a name/link for this 1D nonlinear complex Lie group?
Answer: Here is how one can classify all connected 1-dimensional Lie groups $G$ over a field $F$ which is either ${\mathbb R}$ or ${\mathbb C}$.
The Lie algebra ${\mathfrak g}$ of $G$ is 1-dimensional, hence, commutative, hence, isomorphic to $F$ (with trivial Lie bracket structure). Let $\tilde{G}$ be the universal cover of $G$; it is a simply connected Lie group over $F$. It is a nice exercise to see that the exponential map is an isomorphism from ${\mathfrak g}\cong F$ (regarded as an abelian Lie group) to $G$. Hence, there is a unique simply-connected Lie group over $F$.
Now, $G$ itself is isomorphic to the quotient of $\tilde{G}$ by a discrete subgroup $L\subset \tilde{G}$. It is again a nice exercise to identify discrete subgroups of $(F, +)$:
In the real case, you only have $\{0\}$ and ${\mathbb Z}$. The quotient groups $G$ are isomorphic to (respectively) ${\mathbb R}$ and $S^1\cong U(1)$. Both are real-linear.
In the complex case, you have discrete subgroups isomorphic to $\{0\}, {\mathbb Z}$ and ${\mathbb Z}^2$.
Their quotient groups ${\mathbb C}/L$ are isomorphic, respectively, to ${\mathbb C}$, ${\mathbb C}^\times$ (both are complex-linear) and, as a real Lie group, to $S^1\times S^1$. the latter group is real-linear. However, it cannot be complex-linear, i.e. cannot be isomorphic to a complex Lie subgroup of $GL(n, {\mathbb C})$. The reason is the Liouville's theorem: Every holomorphic function on the compact connected complex manifold, such as a real torus $T^2$, is constant. Since the matrix coefficients are holomorphic functions, we obtain that the only compact connected complex Lie subgroups of $GL(n, {\mathbb C})$ is the trivial subgroup.
Comment: I can't say I know enough group theory to follow your reasoning, but I am grateful for your thorough response.


.net core web api 500 error and can't hit breakpoints

Question: I have a manager class:
 public class UserManager : IUserManager
{
    private readonly IGraphApiClient _client;
    private readonly IUserDataProvider _userDataProvider;
    private readonly IMapper _mapper;

    public UserManager(IGraphApiClient client, IMapper mapper, IUserDataProvider _userDataProvider)
    {
        _mapper = mapper;
        _client = client;
        _userDataProvider = userDataProvider;
    }
    public IEnumerable<Customer> GetAssociatedCustomersByUserEmail(string email)
    {
        var customers = _userDataProvider.GetAssociatedCustomersByUserEmail(email);
        return customers;
    }

And when I remove the IUserDataProvider _userDataProvider in the UserManager constructor signature and the _userDataProvider = userDataProvider; my web api will "work" in the sense that I can get a breakpoint to hit and I can call an endpoint. An exception is obviously thrown inside the GetAssociatedCustomerByUserEmail() because I did not inject the IUserDataProvider.
And when I keep these lines of code in, all my web API will return is 500 error status and I cannot hit any breakpoints.
At first I realized I forgot to register the IUserDataProvider, but even after doing so in my startup.cs I still get the same problem.
        services.AddScoped<IUserDataProvider, UserDataProvider>();
        services.AddScoped<IUserManager, UserManager>();

Everything else... all my controllers, managers, dataproviders, etc work except for this specific one. I cannot figure it out. I've checked all my accessor (public vs private) everywhere and they are seem legit. I've run out of things to investigate at this point.
Answer: Install Install-package Microsoft.AspNetCore.Diagnostics from nuget
Change your Configure method in startup.cs to below, then you will see the error message
pay attention that it should be before any other lines
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        env.EnvironmentName = EnvironmentName.Development;
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/error");
        }

        app.UseStatusCodePages();

More info https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling
Comment: Thank You!! That led me to what I needed to know. I didn't register something a little deeper down ;)  will accept as answer in a couple min
Answer: I was bit by this issue today. Using Dependency injection and did not register a class in my startup that my controller was using.


Small leak in bathtub valve stem (hot)

Question: I replaced the valve stems in my bathtub yesterday. When screwing in both the cold and diverter stems, they slowly got tighter and tighter as I went (as expected). However, with the hot stem there wasn't much resistance until I basically hit the end of the threads. I wasn't too worried except that when I turned the water back on, there was a small leak on the hot side at the seat. We're talking 1 drop every 30 seconds. I tightened it up more (didn't want to turn that much) and that seemed to fix it but I'm a little concerned it might come back.
Obviously, I'm not a pro, but why is did the hot side stem screw in differently than the cold side? Because it was hot and the metal had expanded? And does that have anything to do with the leak? And most of all, should I do something about this like put some teflon tape on the hot side threads?
Here is a photo of where the water was dripping:

It's the very back part of the valve stem where you screw it over the valve body inside the wall. Here is the same point on the old stem:
Comment: OK, there is a small gasket required there, actually it's a *friction ring* and may be made of either plastic or fiber. Sometimes people forget to use one, or accidentally use **two** because it is hard to see if the old one is stuck on the valve body. Check that. P.S. no teflon is normally used there, and no leak is acceptable there.
Comment: Do you mean a leak at the seat or a leak at the stem packing ?
Comment: Good question, at the seat.
Comment: "At the seat" as in there is a drip from the tub spout? Or are we talking about a drip/leak in the wall where the valve screws into the valve body?
Comment: @JimmyFix-it Yes, I believe so. I uploaded a photo. Hopefully that clarifies.
Comment: @JimmyFix-it Great, thanks for the info. I'll have a look and check back in.
Comment: @JimmyFix-it You nailed it. I had left the friction ring off the hot stem. Thanks for the help! If you want to leave a formal answer I'll gladly mark it as correct.
Answer: That type of stem requires a friction ring (generally either plastic or fiber) at the valve-body thread shoulder. Ensure there is one present and that it is in good condition. Also make sure that you have not inadvertantly installed two rings, as it is sometimes difficult to notice that an old one is stuck to the valve housing in the wall.

Small leak in bathtub valve stem (hot)


Inequality that I believe can be conquered with Cauchy Schwarz I.E

Question: There are ten real numbers $x_0, . . . , x_9$ with $x_0 = 0, x_9 = 9$. What is the smallest possible value of the expression
$$(x_1 − x_0)^2/1 +(x_2 − x_1)^2/2+(x_3 − x_2)^2/3+ · · · +(x_9 − x_8)^2/9$$?
I thought this problem had cauchy schwartz I.E written all over it , I was able to get the $x_i$'s to telescope down to $9^2$ or $ 81$ but then Im getting confused what will be the bi in the sum. will it be the sum of $1+1/2+1/3...+1/9$ or just $1+2+3...+9$ ? please help :(
Comment: well the expression is just $1+(1-1/2)x_1+(1/2-1/3)x_2+\cdots+(1/8-1/9)x_8$ so you can make it as small as you like, as there are no constraints on $x_1,\cdots,x_8$
Comment: @Randin: With $(x_0, \ldots, x_9) = (0, a, \ldots, a, 9)$ the expression becomes $\frac 89 a$, that can be arbitrary large or small.
Comment: maybe $x_i$'s are ordered?
Comment: Please clarify how $x_i$ are selected among 0,1,...,9
Comment: thats exactly how contest author worded it .. xi are real
Comment: @Randin Maybe we are assuming  $0=x_0\le x_1\le \ldots \le x_8\le x_9=9$?
Comment: lets assume that yes gimusi. and why was my question down voted twice??
Answer: cauchy schwartz inequality with writing the denominators as a sequence of radicals ]1
Answer: [![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/fXUVO.jpg by cauchy schwarz the (xi+1 -x i ) telescope leaving 9^2=81 but then we have the denominators which are the sum of integers from 1 to 9 , this gives a total of 9/5


Signature of the Redshift internal "identity" function

Question: While working on a legacy Redshift database I discovered unfamiliar pattern for default identity values for an autoincrement column. E.g.:
create table sometable (row_id bigint default "identity"(24078855, 0, '1,1'::text), ...

And surprisingly I wasn't able to find any docs about that identity function. The only thing I was able to dig up is the following:
select * from pg_proc proc
join pg_language lang on proc.prolang = lang.oid
where proc.proname = 'identity';

So I've found out that function to be internal, and it's prosrc column is just ff_identity_int64 (not googleable, unfortunately).
Could someone please provide me with some info about its first and second arguments? I mean 24078855 and 0 from that example "identity"(24078855, 0, '1,1'::text). ('1,1'::text -- here first 1 is the start value and second 1 is the step of increment). But 24078855 and 0 are still mysterious for me.
Comment: something tells me it's max value and min value (seed), what else could it be?
Comment: @AlexYes I did some experiments using `"identity"(5, 0, '1,2'::text)`. I wasn't able to make it take 5 in account while adding rows to the table, deleting them, and adding again. Looks like it takes in account only  '1,2'::text, consistently increasing that autoincrement.
Answer: "identity"(24078855, 0, '1,1'::text)

table OID
0-based column index
text representation of parameters provided with IDENTITY clause

For reference look at pg_attrdef table
Answer: I've found that the first argument is the oid of the table. So, in your example (without the schema specified)
select oid from pg_class where relname = 'sometable'

Answer: The IDENTITY clause is documented in the CREATE TABLE docs here: http://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html#identity-clause

IDENTITY(seed, step)
Clause that specifies that the column is an IDENTITY column. An IDENTITY column contains unique auto-generated values. The data type for an IDENTITY column must be either INT or BIGINT. When you add rows using an INSERT statement, these values start with the value specified as seed and increment by the number specified as step. When you load the table using a COPY statement, an IDENTITY column might not be useful. With a COPY operation, the data is loaded in parallel and distributed to the node slices. To be sure that the identity values are unique, Amazon Redshift skips a number of values when creating the identity values. As a result, identity values are unique and sequential, but not consecutive, and the order might not match the order in the source files.
Comment: Unfortunately, this not addresses my question.


Trying to show AM-GM mean inequality

Question: I want to show that
$$ ( \prod_i^n x_i )^{\frac{1}{n}} \leq \frac{1}{n} \sum_i^n x_i $$.
I know there exists plenty of solutions to this problem. However, I know this result follows this directly by the following:
Suppose $x_1,... x_n \in \mathbb{R}^{\geq 0} $ and $\alpha_1 + ... + \alpha_n = 1 $, $\alpha_i \in \mathbb{R}^{\geq 0 }$ then
$$ x_1^{\alpha_1}...x_n^{\alpha_n} \leq \alpha_1x_1 + ... + \alpha_n x_n $$
Is this result true?
Comment: It is. It's generally called the weighted AM-GM inequality.
Answer: Taking logs, you want to show
$$\sum \alpha_i \log x_i \le \log \left( \sum \alpha_i x_i\right) $$
Hint: Jensen
Answer: It is suffice to show for two variables, and you can how it by convex function inequality. In more detail, t
$$
e^{\lambda x + (1-\lambda)y} \leq \lambda e^{x} + (1-\lambda)e^{y}
$$
and set $\alpha_{1} = \lambda$, $\alpha_{2} = (1-\lambda)$, $x = \log x_{1}$, $y = \log x_{2}$

Trying to show AM-GM mean inequality


How to simplify $\sum_{k=0}^{n} \frac{e^{\sum_{i=0}^kx_{i}}}{\sum_{i=0}^k x_{i}}$

Question: Is it possible to simplify
$$
S(\mathbf{x})=\sum_{k=0}^{n}  \frac{e^{\sum_{i=0}^kx_{i}}}{\sum_{i=0}^k x_{i}}
$$
A few observations:

$\sum_{k=0}^{n}\sum_{i=0}^k x_{i}=\sum_{k=0}^{n}(n+1-k)x_k$
$ e^{\sum_{i=0}^kx_{i}}=\prod_{i=0}^k e^{x_i}$
$S(\mathbf{x})=\sum_{k=0}^{n}e^{\sum_{i=0}^kx_{i}-\log\left( \sum_{i=0}^k x_{i}\right)}$

Perhaps one could approximate $S(\mathbf{x})$ by defining $y\equiv \sum_{i=0}^k x_{i}$ and finding an approximation to $y-\log(y)$. Any ideas?
Edit: If $y_k=\sum_{i=0}^k x_i$ is a bounded sequence, can we hope to find an approximation of
$$
\lim_{n\to\infty}\sum_{k=0}^n \frac{e^{y_k}}{y_k}
$$
for $x_i>0$?
Comment: Even when $(x_i)$ is a constant sequence with value $a\neq 0$, the resulting sum $$\frac{e^a}{a}+\frac{e^{2a}}{2a}+\cdots+\frac{e^{na}}{na}+\frac{e^{(n+1)a}}{(n+1)a}$$does not simply further.
Comment: @SangchulLee what if $y_k=\sum_{i=0}^k x_i$ is a bounded sequence, can we hope to find an approximation of $\lim_{n\to\infty}\sum_{k=0}^n \frac{e^{y_k}}{y_k}$? Added this to the original post.
Answer: Too long for a comment
As noted by @SangchulLee : If $(x_i)$ is a constant sequence with value $a≠0$ , then the sum is
$$
S(a,n) = \frac{e^a}{a}+\frac{e^{2a}}{2a}+\cdots+\frac{e^{na}}{na}+\frac{e^{(n+1)a}}{(n+1)a} \tag{1}
$$
Suppose $a >0$, then
$$
S(a,n)
= \sum_{k = 1}^{n+1} \int_{-\infty}^1   e^{y k a} dy\\
= \int_{-\infty}^1 \sum_{k = 1}^{n+1}  ( e^{y a})^k dy\\
= \frac{1}{a} \int_{-\infty}^a \sum_{k = 1}^{n+1}  ( e^{z})^k dz\\
= \frac{1}{a} \int_{-\infty}^a  \frac{e^{z} (e^{z (n + 1)} - 1)}{e^{z} - 1} dz\\
$$
Analytic solutions for this integral for fixed $n$ bring back the sum as in (1). However, the integral may be useful for finding approximations. To do so, let us factor out an even term:
$$
S(a,n)
= \frac{1}{a}\int_{-\infty}^a  \frac{e^{z} (e^{z (n + 1)} - 1)}{e^{z} - 1} dz\\
= \frac{1}{a}\int_{-\infty}^a  \frac{e^{z (n+2)/2} \sinh (z (n+1)/2) }{\sinh (z/2)} dz\\
= \frac{2}{a} \int_{-\infty}^{a/2}  \frac{e^{w (n+2)} \sinh (w (n+1)) }{\sinh (w)} dw
$$
Note that $\frac{\sinh (w (n+1)) }{\sinh (w)} $ is an even function of $w$ which may be used for further approximations.


How can I extract more heat from my enclosed wood stove?

Question: I recently moved into a house that has a working wood burner/multi fuel. It's the first time I've had a wood burner/stove/multi fuel and I'm unsure how to use it efficiently.
It's unlike conventional stoves that I see (it's all metal with no glass doors).
The heat output has so far been uninspiring and I was hoping it would be better.
So far we've been burning coal and some wood.
I'm looking for some pointers on how to maximise the heat output; should I run it with the doors open or shut? I have 2 vents on the bottom of the doors and something on the flue that turns (which I imagine shuts off the flue/chimney), do I run the top flue/vent wide open?
Any advice will be much appreciated.
Thanks :-)
Comment: Stoves don't have the greatest heat efficiency, they leak a lot though the chimney (which you need to vent to the outside if you want to keep breathing).
Comment: Have a reputable chimney sweep check out the whole thing from top to bottom before using; the flue could be plugged with critter nests, or worse, creosote.
Answer: You should definitely run it with the flue open, all that smoke/CO needs to go outside, not in the house. You mentioned two vents on the bottom. Those are likely there to allow you to close the front and allow the fire to still get air. As SqlACID mentioned, spending $100 or so on a reputable chimney sweep to come take a look at it in person would be a good idea; they would be able to help you use it to its best advantage.
I would experiment with closing the front and see what effect it has on the burning rate as well as the heat produced. It is also a good idea to try to move the warmth produced by the stove into the rest of the house, so running a fan to pull that warm air away might also be something to try.
What make/model of stove do you have? I might try googling the make/model to see what comes up on how to best use it.
Answer: I have had a coal/wood stove for years.  It will take you a while to master.  You do not want the flue all the way open, you will lose all of the heat out of the chimney and your fuel will burn fast.  You will need to mess around with the dampers to figure out your optimal settings.  These will change some with outside temperature.
Answer: Damping the flue can retain heat in the firebox, but the real key to heat extraction is airflow outside the fireplace. The best stoves and fireplaces have integrated fans that route air though the interior of the structure, but keep it isolated from the combustion chamber. I'd be looking to emulate that somehow.
Either investigate add-on kits, or simply place a small fan behind the stove, at a safe distance, and direct it at the fireplace. You'll probably be amazed at how much heat is available at even low fan speeds.
To really make it work well, connect the fan to a thermostatic plug, and place that under the fireplace to automatically shut off the fan when heat diminishes.
Answer: I only have a woodburner to provide heat in the house.  First year I did similar and had the flue open, the heat just went up the chimney, burnt a lot of fuel and was mildy warm.
I would recommend running it with the doors shut and balance the draw going up the chimney, almost completely level but only move it down after a few minutes of it being a light so the flue is warm, otherwise you'll fill the room with smoke!  You should have sliders in the bottom of the doors which you want open.  This will circulate air into the stove and it will burn hotter.  Coal burns longer than wood and gives longevity, wood is quick burning but gives a higher heat output.  So burn a coal bed and add wood on top.  When adding fuel you probably want to move the flue fully open first, otherwise you'll fill the room with smoke, close doors again and then move the flue back to almost closed.
Because the stove is in the chimney breast rather than set out from it means the air circulating around it is reduced which gives you the heat, rather than the fuel (fuel is heating the stove which is heating the air) but you should still get a good level of heat from it.
Also get a carbon monoxide monitor if you are worried and make sure the flue is swept yearly.
Good luck
Answer: Congratulations - you appear to have a knock-off of a Ben Franklin stove. Yep, that Ben Franklin, design nearing 250 years old, though most extant examples were produced in the wild and wooly 1970's when "the oil crisis" hit and there were no regulations to speak of applying to wood stoves. If yours happens to be a lot older it might be worth some serious money as an antique, but it probably isn't.
The best way to get good heat from one of those is: sell it (as an antique, or as scrap, preferably not as a wood-burning appliance), and buy something remotely modern, efficient, and clean burning. None of which that is - I know, I have replaced one myself. Be sure to save the lovely brass parts, (or scrap them separately) they are probably worth more than the entire rest of the stove.
Answer: First of all, safety should be your top priority. Unlike a regular furnace, a wood stove represents a serious safety hazard. Before using it, at a minimum you should:

have the chimney / flue inspected and cleaned if necessary.
make sure you have a smoke alarm and carbon monoxide alarm installed nearby. Note that alarms have a limited lifespan (5-10 years), so check the bottom for an expiration date. (This would be a good time to verify the whole house's alarms, for that matter: one smoke alarm in every bedroom, one outside each sleeping area, minimum one per floor. For CO alarms you only need one per floor.)
make sure your homeowner's insurance knows that you have a wood stove. They may have questions about the type, installation, last service, etc. Make sure you are 100% legit since if the house burns down and they find out you lied about it, they will deny your coverage.

Having said all that, you generally want to keep the doors closed while using it to prevent all your warm air from being sucked up the chimney. Adjust the vents on the bottom to let fresh air in. If the stove is properly designed the vents should provide sufficient airflow. On some stoves you might have to leave the door ajar while the kindling lights; if you can find a model number you should be able to look up a manual online.


JclMapi mapi general failure

Question: I have the code:
procedure TfrmMain.btnSendClick(Sender: TObject);
var
  aMail: TJclEMail;
begin
  aMail := TJclEMail.Create;
  Screen.Cursor := crHourGlass;
  try
    aMail.Recipients.Add('email@example.com');
    aMail.Subject := '[IMPORTANT] blablba';

    aMail.Body := 'text text text text';
    aMail.Send(True);
  finally
    Screen.Cursor := crDefault;
    aMail.Free;
  end;
end;

This throws: MAPI Error: (2) "General MAPI failure"
Any idea?
ps:
OS Windows 7
Outlook 2010
Delphi 2007
Answer: I have the same as you, just wrapped inside a class and it is working.
I use to check if MAPI is OK at the first time I execute Send():
function TMAPIPrerequisites.IsClientAvailable: Boolean;
var
  SimpleMAPI: TJclSimpleMapi;
begin
  SimpleMAPI := TJclSimpleMapi.Create;
  try
    Result := SimpleMAPI.AnyClientInstalled;
  finally
    SimpleMAPI.Free;
  end;
end;

function TMAPIPrerequisites.IsMapiAvailable: Boolean;
var
  SimpleMAPI: TJclSimpleMapi;
begin
  SimpleMAPI := TJclSimpleMapi.Create;
  try
    Result := SimpleMAPI.SimpleMapiInstalled;
  finally
    SimpleMAPI.Free;
  end;
end;

Comment: I Create a wrapper, called TEmailWrapper and the send method use your function "IsMapiAvailable" before execute, function returns true but send continues throwing MAPI Error: (2) "General MAPI failure"
Answer: My problem was that my Jedi library wasnt up to date. I search into jedi repository and JclMapi has change in Tue Dec 27 (Mantis 5748: JclMapi incompatibilities with 64-bit.)
Download this changes, re-compile pkg and now works perfectly!
Thank you anyway!!
Answer: The above code works fine IF email client is not already running.
After struggling with same problem i found that the MAPI client has to run in same user context as the MAPI server (e-mail client - Thunderbird in my case).
However, if calling from an app started with administrator privileges (for example an app running in the debugger) then the MAPI calls would fail with error code 2. If both caller and email client are running as admin then everything works (but who's crazy enough to run e-mail client as admin these days?).

JclMapi mapi general failure


How to trigger ir.ui.view action to a Menu in Odoo

Question: This is my first Module I'm creating, I have learnt in the documentation that after creating the action (record tag) I have to mention this action in the (Menu tag) to act on it, as the following
<record model="ir.actions.act_window" id="action_list_ideas">
    <field name="name">Ideas</field>
    <field name="res_model">idea.idea</field>
    <field name="view_mode">tree,form</field> </record>
<menuitem id="menu_ideas" parent="menu_root" name="Ideas" sequence="10"
          action="action_list_ideas"/>

My question is
I want to create another action type
record model="ir.ui.view"
how to make the relation between the action and the menu ?
This is what I wrote, 4 actions for 2 menu

<record id="globalhaatahmedviewa" model="ir.ui.view">
    <field name="name">haatglobal_ahmed</field>
    <field name="model">haatglobal_ahmed.haatglobal_ahmed</field>
    <field name="priority" eval="16"/>
    <field name="arch" type="xml">

<form create="false" edit="false">
    HTML Text to
</form>
    </field>
</record>

<record id="globalhaatahmedviews" model="ir.ui.view">
    <field name="name">haatglobal_ahmed</field>
    <field name="model">haatglobal_ahmed.haatglobal_ahmed</field>
    <field name="priority" eval="16"/>
    <field name="arch" type="xml">

<form create="false" edit="false">
    HTML Text to
</form>    </field>
</record>

<record id="haatglobal_ahmed_about_a" model="ir.actions.act_window">
            <field name="name">HAAT_Global</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">haatglobal_ahmed.haatglobal_ahmed</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="globalhaatahmedviewa"/>
            <field name="help" type="html">

 about company window

            </field>
        </record>

<record id="haatglobal_ahmed_about_s" model="ir.actions.act_window">
            <field name="name">HAAT_Global</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">haatglobal_ahmed.haatglobal_ahmed</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="globalhaatahmedviews"/>
            <field name="help" type="html">

                    Support window

            </field>
        </record>

<menuitem name="HAAT Global" id="haatglobal_ahmed.menu_root"/>
<menuitem name="About Company" id="haatglobal_ahmed.menu_a" parent="haatglobal_ahmed.menu_root" action="haatglobal_ahmed_about_about"/>
<menuitem name="Support" id="haatglobal_ahmed.menu_s" parent="haatglobal_ahmed.menu_root"
 action="haatglobal_ahmed_about_about" />

was that right?
My target is to create (main menu) and (two sub menu) if I click on the (sub menu) it will show just text in the page.
Thanks for help in advance
I'm odoo 15
Comment: You can specify the view in the window action using the [view_id](https://www.odoo.com/documentation/master/developer/reference/backend/actions.html#window-actions-ir-actions-act-window) field
Answer: you need to add this line to your action record:
<field name="view_id" ref="you_action_id"/>

your action record will be like:
<record model="ir.actions.act_window" id="action_list_ideas">
    <field name="name">Ideas</field>
    <field name="res_model">idea.idea</field>
    <field name="view_mode">tree,form</field>
    <field name="view_id" ref="globalhaatahmedview"/>
</record>

Comment: Thanks for your answer, I updated the post and I wrote the whole code which I have wrote..... was that right ? because I'm still facing error
Answer: The XML file does not fit the required schema!
Arch fields and the first help field will raise the following errors:
text not allowed here
element "field" incomplete

Odoo will expect a view type inside the arch field: form, tree, ...
You can wrap the text inside a form tag, for example:
<form create="false" edit="false">
    HTML Text to
</form>

Form views are composed of regular HTML, this is why the above example should work but they are used to display the data from a single record.
The same thing to the window action, try to wrap the text inside a p tag
Odoo will use the import_xml RNG file and the corresponding views validation schemes in the base module to validate the structure and content of an XML document (data files). Check the views documentation for more details on what you can define inside a view arch.
Note that it's possible to define a new view type and display custom content using a qweb template
Comment: Thanks for your trying to help, I edited the post to include your suggestion, I run out that, the result was as error
`odoo.tools.convert.ParseError: while parsing /odoo54/custom/addons/haatglobal_ahmed/views/views.xml:96, somewhere inside
`
Comment: Actually what i need is Main menu with html text only.
Comment: Your actions are `haatglobal_ahmed_about_s` and `haatglobal_ahmed_about_s` but you used `haatglobal_ahmed_about_about` in menu items. Make sure to define that action first.