Mysql Query that requires subtraction of fields that cannot be referenced

Question: Our db stores customer orders in two tables: customerorders and customerorderlines.
Amongst other fields, there is a customerorders.type field which determines (being = 1 or = 2)
if that customerorder is an invoice or a creditnote.
We currently have a report that lists amount of units sold, profits etc but with its current query, only displays total units sold over the period, ie, it doesnt subtract the number of credits, if any. Here is its sql and an example of the results it generates:
(apologies for the massive query that follows :))
SELECT l.name AS locationname
, sr.name AS salesrepname
, ct.name AS customertypename
, c.name AS customername
, c.id AS customer_id
, c.code
, s.name AS suppliername
, p.description AS productname
, p.id AS product_id
, p.unitofmeasure
, SUM(col.vatableprice) AS totalsales
, SUM(col.vatprice) AS vat
, SUM(col.quantity) AS totalitems
, SUM(col.quantity * col.costprice) AS totalsalecost
, SUM(col.vatableprice) - SUM(col.quantity * col.costprice) AS totalprofit
,(
     SELECT SUM(col2.vatableprice) AS totalsales
     FROM customerorders AS co2
     LEFT JOIN customerorderlines AS col2 ON col2.customerorder_id = co2.id
     LEFT JOIN customers AS c2 ON c2.id = co2.customer_id
     LEFT JOIN locations AS l2 ON l2.id = c2.location_id
     LEFT JOIN customertypes AS ct2 ON ct2.id = c2.customertype_id
     LEFT JOIN salesreps AS sr2 ON sr2.id = c2.salesrep_id
     LEFT JOIN products AS p2 ON p2.id = col2.product_id
     LEFT JOIN suppliers AS s2 ON s2.id = p2.supplier_id
     WHERE c.salesrep_id = c2.salesrep_id
     AND co2.type = 2 AND p2.supplier_id = 179
     AND co2.orderdate >= '2010-01-01 00:00:00'
     AND co2.orderdate <= '2010-02-01 23:59:59'
) AS credits
,(
    SELECT SUM(col2.vatprice) AS totalvat FROM customerorders AS co2
    LEFT JOIN customerorderlines AS col2 ON col2.customerorder_id = co2.id
    LEFT JOIN customers AS c2 ON c2.id = co2.customer_id
    LEFT JOIN locations AS l2 ON l2.id = c2.location_id
    LEFT JOIN customertypes AS ct2 ON ct2.id = c2.customertype_id
    LEFT JOIN salesreps AS sr2 ON sr2.id = c2.salesrep_id
    LEFT JOIN products AS p2 ON p2.id = col2.product_id
    LEFT JOIN suppliers AS s2 ON s2.id = p2.supplier_id
    WHERE c.salesrep_id = c2.salesrep_id
    AND co2.type = 2
    AND p2.supplier_id = 179
    AND co2.orderdate >= '2010-01-01 00:00:00'
    AND co2.orderdate <= '2010-02-01 23:59:59'
) AS creditsvat

FROM customerorders AS co
LEFT JOIN customerorderlines AS col ON col.customerorder_id = co.id
LEFT JOIN customers AS c ON c.id = co.customer_id
LEFT JOIN locations AS l ON l.id = c.location_id
LEFT JOIN customertypes AS ct ON ct.id = c.customertype_id
LEFT JOIN salesreps AS sr ON sr.id = c.salesrep_id
LEFT JOIN products AS p ON p.id = col.product_id
LEFT JOIN suppliers AS s ON s.id = p.supplier_id
WHERE co.status_v = 5
AND co.type = 1
AND p.supplier_id = 179
AND co.orderdate >= '2010-01-01 00:00:00' AND co.orderdate <= '2010-02-01 23:59:59'
GROUP BY c.salesrep_id

Which, in this case (grouping etc is determined by application code) generates a 'per sales rep' report:
Rep | TotalItems | SalesValue| CostOfSales | Profit   | VAT      | Credits | Credits(VAT)
Rep1| 937        | £5796.49  | £3606.49    | £2190.00 | £1013.73 | £220.12 | £38.57
Rep2| 1905       | £11695.09 | £7314.95    | £4380.14 | £2045.32 | £268.85 | £47.00
Rep3| 1074       | £6346.61  | £3950.53    | £2396.08 | £1109.76 | £54.89  | £9.57
Rep4| 2687       | £16129.42 | £10171.65   | £5957.77 | £2820.46 | £839.15 | £146.78

So, the problem lies in that TotalItems is the absolute number of items sold (all customerorders of type = 1). The credits field shows total cost of items in the period of type = 2, ie returned. TotalItems should have the qty of credits deducted from it so at a glance it can be seen what has actually been sold and of course all the other fields need their Credits counterpart deducting from each other too so that they reflect the correct amounts for items sold.
At first I thought this would be as simple modification to the existing query, but then noticed that i could not reference subquery aliases in the select so I rewrote the whole query using JOIN (SELECT ....) AS sales / JOIN (SELECT .....) AS credits so I could then reference sales.qty and credits.qty from the SELECT at the top of the query but then that didnt scale at all unless you were doing little queries.
This is how far I got:
(Yes, Im querying for different things here... this would be essentially the simplest form of the query: sales / credits for a single product)
SELECT sr.name AS salesrepsname
,l.name AS locationname
,sup.name AS suppliername
,p.description AS productname
,sales.qty AS sold
,credits.qty AS credits
,sales.qty - credits.qty AS actualsold
FROM
customerorders co
LEFT JOIN customerorderlines col ON col.customerorder_id = co.id
LEFT JOIN customers c ON c.id = co.customer_id
LEFT JOIN products p ON p.id = col.product_id
LEFT JOIN salesreps sr ON sr.id = c.salesrep_id
LEFT JOIN locations l ON l.id = c.location_id
LEFT JOIN suppliers sup ON sup.id = p.supplier_id
JOIN (SELECT SUM(col.quantity) AS qty,
SUM(col.vatableprice) AS total FROM customerorderlines col
LEFT JOIN customerorders co ON co.id = col.customerorder_id
WHERE col.product_id = 27642 AND co.type = 1)
AS sales
JOIN (SELECT SUM(col2.quantity) AS qty FROM customerorderlines col2
LEFT JOIN customerorders co2 ON co2.id = col2.customerorder_id
WHERE col2.product_id = 27642 AND co2.type = 2) AS credits
WHERE col.product_id = 27642
GROUP BY c.salesrep_id

So I have to admit Im a bit stuck, not being very knowledgable with mysql at all.
Any suggestions are very welcome and please feel free to point me towards any literature on advanced subquerying and joins that I should be reading.
Cheers!
Answer: I think the trick you may be looking for is along these lines. In any given query/subquery you want to fix, use some SQL like this, selecting all the rows, regardless of whether it's an invoice or a creditnote, and summing a value that's either positive or negative depending on which way the order/money is going:
SELECT
  SUM(CASE WHEN co.type = 1 THEN col.quantity ELSE -col.quantity END)
FROM
  ...

Get it? You grab all your order lines back, but when you do the sum, you're adding up positive credits and negative debits, to get the real total in one operation.
Comment: Thanks. Never considered using a CASE statement, but you might be onto something. Im testing some queries out as we speak. I will report back :-)
Comment: @prevailrob Good luck! This technique is especially useful if you want to report on different measurements in the same result row from the same query, e.g. you can calculate total credits (`SUM(CASE WHEN co.type = 1 THEN col.quantity ELSE 0 END)`), total debits, total net amount, all using the one base query.
Comment: Just thought I'd keep you up to date: im editing the query with these case statements and so far so good. I've managed to do away with the two subqueries but currently running into some issues with one of the sums (its timingout). Will post my new query here for scrutiny after a bit more tinking. Cheers!
Comment: @matt-gibson Query now seems to work beautifully, thanks muchly. I would like to post it here, see if you or anyone else can see if it seems coherant and can or cannot be optimized. Hows the best way of me sticking it on here? answering my own question or can it actually be pasted into comments without looking atrocious?
Comment: @prevailrob Well, stackoverflow works best when there's one specific question per post. Effectively, you want to ask a different question, I think, so you should probably accept this answer, and post a brand new question for your next bit of work, linking back to this one for background. (Also, if it's specifically a code review you're after, you might try http://codereview.stackexchange.com/ but I don't know how much MySQL is being posted over there...)
Comment: Ok, thanks for the advice. And overall, thank you very much for your help & answer. Up till now I had been stuck on this now seemingly easy problem for two whole days :). I may post a new question to iron out the two bits im unsure about on the new query.


Passing request Parameters from Managed Bean to A jsf page

Question: I am new to JSF 2.0. I am stuck at the following problem. I have a page from which a
managed bean action method is called. In that i do some custom processing and the it
navigates to another xhtml page. Now the problem is that, before moving to next xhtml
page, i need to pass some parameters along with it as well. I have used the following
approaches
1- Put that variable in requestMap and tried to access in the page this way
<h:outputText value="#{param['userid']}"/>

it doesn't work. Then someone told me there is no standard way in JSF 2.0 to pass
request parameters along with a URL, so try to pass it as a servlet request. I ammened
the code as follows
 ServletRequest request = (ServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    ServletResponse response = (ServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
             //("user",user);
    //ServletRequest request = (ServletRequest)context.getRequest();
    request.setAttribute("userid", "prithvi");
    System.out.println("Came here");
    RequestDispatcher rd = request.getRequestDispatcher("testf.xhtml");
    try {
        rd.forward(request, response);
    } catch (ServletException ex) {
        Logger.getLogger(TestFlashScope.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(TestFlashScope.class.getName()).log(Level.SEVERE, null, ex);
    }

I tried to access same way but no luck. no value is displayed. Can someone help me how
to achieve this solution.
BR,
Prithvi
Answer: Just set the result as bean property.
page1.xhtml
<h:commandButton value="Submit" action="#{bean.submit}" />

Bean:
public String submit() {
    this.result = "blah";
    return "page2"
}

page2.xhtml
<h:outputText value="#{bean.result}" />

(assuming that you aren't using <redirect/> in <navigation-case> if any)
Comment: thanks very much. I still have one confusion that when we press an action button and it navigates it to a new page. Previous request object is lost, it's a new request, so how does the bean still remain in scope means whatever we set in this bean? Additionally, what if we just want to pass a few parameters not the bean, is there something to jsp and servlets we can do in jsf also?
Comment: It's just the same request. JSF is just doing a `RequestDispatcher#forward()`.
Answer: you should use Flash Scope. For more information you can look at this blog post.
Comment: This is only useful when the new page is opened by a **redirect** instead of a forward (which JSF by default uses for naviation).


book one level more concise/practical/easier than Courant

Question: I am a software engineer moving into machine learning, which has also meant "moving back into academia" because my boss has me reading research papers. I am glad for the opportunity, but I realized quickly I lack the background in probability and calculus to understand them. I got a 5 in BC Calculus, but that was 14 years ago and I haven't done much since.
I found a great book on probability (Introduction to Probability by Blitzstein and Hwang) which doesn't skimp on theory, which I like, but also gets to the point without extreme detour, which I also like.
This weekend I tried to find a similar book on calculus. Based on strong online recommendations I started Courant's Introduction to Calculus and Analysis, but while I could mostly understand it (with help from Math StackExchange), I'm overwhelmed by the time and energy it will take just to get to "what is an integral." I'm already planning to study ML+Probability+Calculus nonstop for months, but I was hoping to resurface with new practical knowledge every few days, not only after months of study.
So I'm looking for something more practical and concise, and (while I hate to say it) a bit easier. I found recommendations for Stewart but it looks ridiculous. I know I'm being petty, but in the table of contents every chapter has an incongruous image next to it, and one chapter's image is a photo of Shrek. This is not the book I am looking for, because I want a book that takes itself and its readers seriously.
So, what book is a step away from Courant toward practicality/conciseness, a bit easier, but also completely serious and respectful to itself and its readers? Or maybe what I'm asking for is: What is a calculus book for aspiring computer scientists, as opposed to one for aspiring mathematicians?
EDIT: To be clear, I'm not totally averse to "cookbooks." I don't see that as incompatible with theory, I see that as evidence of good editing. Also some may suggest Spivak or Apostol. Since they are usually recommended in the same breath as Courant I am hesitant. I guess this is where I admit to myself that I am looking for something easier.
Comment: In machine learning you need probabilistic reasoning in the first place such as in Bayesian networks. The mathematics there is really simple.
Answer: Good question.
I'm not up on current textbooks, but you might want to try Apostol.
http://www.matematica.net/portal/e-books/Apostol%20-%20CALCULUS%20-%20VOLUME%201%20-%20One-Variable%20Calculus,%20with%20an%20Introduction%20to%20Linear%20Algebra.pdf
For machine learning you'll need linear algebra too. Apostol has some.
I suspect that calculus for computer science books are likely to be too cookbook for you.
Comment: See my edit at the bottom. I'm not necessarily opposed to "cookbook", I think that may actually be evidence of good editing. I skimmed Apostol but I think its level of difficulty is higher than would be practical for me right now.
Comment: @Stephen Fair enough. Good luck.


Deserializing JSON Response to C# object error

Question: What I'm doing is an API call to and turn the response into a C# object.
I'm trying to refactor my working code https://codereview.stackexchange.com/questions/253949/api-response-json-to-c-object/. Into code that was suggested on codereview now I get the following error:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Candlestick' because the type requires a JSON object (e.g. {"name":"
value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be
 deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Json Response from API:
[
    [
        1609065000000,
        "22739.71000000",
        "22795.73000000",
        "22700.39000000",
        "22779.08000000",
        "38.81782800",
        1609065899999,
        "883167.94526884",
        2261,
        "18.58965200",
        "423036.58181400",
        "0"
    ]
]

    [System.Text.Json.Serialization.JsonConverter(typeof(CandlestickConverter))]
    public class Candlestick
    {
        public long OpenTime { get; set; }
        public double Open { get; set; }
        public double High { get; set; }
        public double Low { get; set; }
        public double Close { get; set; }
        public double Volume { get; set; }
        public long CloseTime { get; set; }
        public double QuoteAssetVolume { get; set; }
        public long NumberOfTrades { get; set; }
        public double TakerBuyBaseAssetVolume { get; set; }
        public double TakerBuyQuoteAssetVolume { get; set; }
    }

   public class CandlestickConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var candle = (Candlestick) value;
            serializer.Serialize(writer ,
                new[]
                {
                    candle.OpenTime,
                    candle.Open,
                    candle.High,
                    candle.Low,
                    candle.Close,
                    candle.Volume,
                    candle.CloseTime,
                    candle.QuoteAssetVolume,
                    candle.NumberOfTrades,
                    candle.TakerBuyBaseAssetVolume,
                    candle.TakerBuyQuoteAssetVolume
                });
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            var candle = existingValue as Candlestick ?? new Candlestick();

            var array = JArray.Load(reader);

            candle.OpenTime = array.ElementAtOrDefault(0)?.ToObject<long>(serializer) ?? 0;
            candle.Open = array.ElementAtOrDefault(1)?.ToObject<double>(serializer) ?? 0;
            candle.High = array.ElementAtOrDefault(2)?.ToObject<double>(serializer) ?? 0;
            candle.Low = array.ElementAtOrDefault(3)?.ToObject<double>(serializer) ?? 0;
            candle.Close = array.ElementAtOrDefault(4)?.ToObject<double>(serializer) ?? 0;
            candle.Volume = array.ElementAtOrDefault(5)?.ToObject<double>(serializer) ?? 0;
            candle.CloseTime = array.ElementAtOrDefault(6)?.ToObject<long>(serializer) ?? 0;
            candle.QuoteAssetVolume = array.ElementAtOrDefault(7)?.ToObject<double>(serializer) ?? 0;
            candle.NumberOfTrades = array.ElementAtOrDefault(8)?.ToObject<long>(serializer) ?? 0;
            candle.TakerBuyBaseAssetVolume = array.ElementAtOrDefault(9)?.ToObject<double>(serializer) ?? 0;
            candle.TakerBuyQuoteAssetVolume = array.ElementAtOrDefault(10)?.ToObject<double>(serializer) ?? 0;

            return candle;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Candlestick);
        }
    }

Implementation of convertion:
    var jsonObjectResponse = await response.Content.ReadAsStringAsync();
    var candles = JsonConvert.DeserializeObject<List<Candlestick>>(jsonObjectResponse);

I also tried  var candles = JsonConvert.DeserializeObject<List<Candlestick>>($"{{{jsonObjectResponse}}}");
This gave next errror: Newtonsoft.Json.JsonReaderException: Invalid property identifier character: [. Path '', line 1, position 1.
The json response object is something I haven't worked with before. I got it working but I would like some cleaner code and I'm trying to make it work as suggested as in the link I provided. Anyone got any idea what a solve would be or where I can find some more information?
Comment: Have you registered the custom converter?
Comment: @TomekSzpakowicz well you resolved my problem.. Thanks
Answer: @TomekSzpakowicz gave me the answer in his comment. I had to register the custom converter so I added the following code in my start up file.
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Converters = new List<JsonConverter>
                {
                    new CandlestickConverter(),
                }
            };


ansible logrotate issues with postrorate script

Question: Below is my ansible role > defaults/main.yaml
    $cat roles/logrotate/defaults/main.yml

      logrotate_conf_dir: "/etc/logrotate.d/"
      logrotate_scripts:
        - name: test
          log_dir: '/var/log/test'
          log_extension: 'log'
          options:
            - rotate 7
            - weekly
            - size 10M
            - missingok
            - compress
            - create 0644 test test
          scripts:
            postrotate: "echo test >> /var/log/test.log"

and my task/main.yaml has
    $ cat roles/logrotate/tasks/main.yaml
    # tasks file for nginx

    - name: Setup logrotate scripts
      template:
        src: logrotate.d.j2
        dest: "{{ logrotate_conf_dir }}{{ item.name }}"
      with_items: "{{ logrotate_scripts }}"
      when: logrotate_scripts is defined

Getting the below error while running this simple playbook:

TASK [logrotate : Setup logrotate scripts] *******************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ansible.errors.AnsibleUndefinedVariable: 'dict object' has no attribute 'iteritems'
failed: [10.20.5.72] (item={'name': 'test', 'log_dir': '/var/log/test', 'log_extension': 'log', 'options': ['rotate 7', 'weekly', 'size 10M', 'missingok', 'compress', 'create 0644 test test'], 'scripts': {'postrotate': 'echo test >> /var/log/test.log'}}) => {"ansible_loop_var": "item", "changed": false, "item": {"log_dir": "/var/log/test", "log_extension": "log", "name": "test", "options": ["rotate 7", "weekly", "size 10M", "missingok", "compress", "create 0644 test test"], "scripts": {"postrotate": "echo test >> /var/log/test.log"}}, "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'iteritems'"}
Comment: Post the template `logrotate.d.j2`
Answer: In the template, fix the iteration. For example,
{% for k,v in item.scripts.items() %}

Example of a complete playbook for testing
shell> cat pb.yml
- hosts: localhost

  vars:

    logrotate_conf_dir: "/etc/logrotate.d/"
    logrotate_scripts:
      - name: test
        log_dir: '/var/log/test'
        log_extension: 'log'
        options:
          - rotate 7
          - weekly
          - size 10M
          - missingok
          - compress
          - create 0644 test test
        scripts:
          postrotate: "echo test >> /var/log/test.log"

  tasks:

    - name: Setup logrotate scripts
      template:
        src: logrotate.d.j2
        dest: "{{ logrotate_conf_dir }}{{ item.name }}"
      loop: "{{ logrotate_scripts|d([]) }}"

shell> cat logrotate.d.j2
{{ item.log_dir }}/{{ item.name }}.{{ item.log_extension }}
{
{% for option in item.options %}
        {{ option }}
{% endfor %}
{% for k,v in item.scripts.items() %}
        {{ k }}
                {{ v }}
        endscript
{% endfor %}
}

gives (--check --diff)
+/var/log/test/test.log
+{
+        rotate 7
+        weekly
+        size 10M
+        missingok
+        compress
+        create 0644 test test
+        postrotate
+                echo test >> /var/log/test.log
+        endscript
+}

Comment: Thanks a lot, the solution worked for me!!!
Comment: You're welcome. You should [edit] the question and post the template. It should be clear where does the error come from.


Como alterar objetos do URL via JavaScript?

Question: Tenho um sistema de busca no meu site usando o Google Custom Search, e para definir a pesquisa por imagens, é acrescentado no URL: #gsc.tab=1. Como eu crio um sistema em JS que pode ser executado via link que adiciona isso no URL?
Answer: Não tenho certeza se é isso que você está buscando, mas esse fragmento que começa com # é chamado de hash e pode ser obtido e alterado assim:
// pega o valor atual
var hashAtual = window.location.hash;

// troca o valor
window.location.hash = 'foo';

// monitora trocas de valor
window.onhashchange = function() {
    console.log('hash trocado para ' + window.location.hash);
}

Comment: No onclick do seu link, simplesmente altere o hash usando a segunda linha do meu exemplo.
Comment: Mas como eu linko essa função?
Answer: Para ler a hash que está no URL pode usar:
window.location.hash

A partir daí tem de retirar os valores que pretende com uma funcão como esta em baixo:
function getHASH() {
    var hash = window.location.hash.slice(1);
    var pares = hash.split('&');
    var chaves = pares.map(function (par) {
        var chave_valor = par.split('=');
        return {
            chave: chave_valor[0],
            valor: chave_valor[1]
        };
    });
    return chaves;
}

Fica um exemplo que funciona apesar do jsFiddle não mostrar a HASH no url: http://jsfiddle.net/hym346sw/
O resultado do exemplo é:
"[
    {
        "chave": "teste",
        "valor": "10"
    },
    {
        "chave": "outro.Teste",
        "valor": "20"
    }
]"

Answer: Você não pode simplesmente colocar esse código no próprio atributo href do link?
Pesquisar por imagens


Authentication page before loading the main website

Question: I am using Drupal 7. I need any user(who has not logged in) to just see the login screen only for authentication before he can traverse the actual website.
How this can be done?I tried to do it using Panels but without success.
Answer: You can use this module

The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

Allow users to login using either their username OR their e-mail address.
Allow users to login immediately.
Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
Customize the registration form with two e-mail fields to ensure accuracy.
Optionally redirect the user to a specific page when using the 'immediate login' feature.
Optionally redirect the user to a specific page upon validation of their e-mail address.
Optionally display a user message indicating a successful login.
Optionally combine both the login and registration form on one page.
Optionally have unvalidated users purged from the system at a pre-defined interval.
Integrates with the Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example).

Or you can add this code as well:
<code>    global $user
    if ($user->uid  == 0  && $_GET['q'] == 'node') {
      drupal_set_message("Access Denied: Please Login");
      drupal_goto('user/login', drupal_get_destination());
    }
</code>
Comment: Thanks for this but my requirement is little different.I would want user to first see the login form only
Comment: About the module:
provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in".

And about the code:
You can change it for fit your needs, that was just an example


CustomAdapter is not displaying ArrayList Item: ImageView

Question: In my CheckOutMemo.class I can set any title and content as shown in picture.

MainActivity.class then retrieves this title and content without any problems and displays a custom row. Like in this picture:
Title = Header
Content = bodyText

But the problem is: When I take a picture - I can't display it on my custom row. (That little dog in my MainActivity is there by default).
I don't know what the problem is.
I can preview my captured image as an Bitmap in my CheckOutMemo.class's contentView. I can successfully save it to my External Storage. But I can't display it on my MainActivity.
MAINACTIVITY.CLASS
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {

public ImageView view;
private String[] mPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private static final int REQUEST_CODE_PERMISSION = 5;
CustomAdapter customAdapter;
ListView listView;
Intent intent;
final Context context = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    customAdapter = new CustomAdapter();
    listView = (ListView) findViewById(R.id.myListView);
    listView.setAdapter(customAdapter);
    listView.setOnItemLongClickListener(this);
    listView.setOnItemClickListener(this);
    view = (ImageView) this.findViewById(R.id.imageIcon);

    if (ActivityCompat.checkSelfPermission(MainActivity.this, mPermission[0])
            != MockPackageManager.PERMISSION_GRANTED ||
            ActivityCompat.checkSelfPermission(MainActivity.this, mPermission[1])
                    != MockPackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(MainActivity.this,
                mPermission, REQUEST_CODE_PERMISSION);
    }
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Memo memo = customAdapter.getItem(position);
    intent = new Intent(getApplicationContext(), CheckOutMemo.class);
    intent.putExtra("header", memo.header);
    intent.putExtra("bodyText", memo.bodyText);
    intent.putExtra("position", position);

    // launches edit request and saving existing item.
    startActivityForResult(intent, CheckOutMemo.EDIT_REQUEST_CODE);
}

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    alertDialogBuilder.setTitle("Confirm Delete");
    alertDialogBuilder.setMessage("Delete memo?");
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            customAdapter.delete(position);
            customAdapter.notifyDataSetChanged();
        }
    });
    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
    });
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();

    return true;
}

public void addNewNote(View view) {
    Intent intent = new Intent(getApplicationContext(), CheckOutMemo.class);
    //Adding new listItem to the ArrayList.
    startActivityForResult(intent, CheckOutMemo.ADD_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) {
        return;
    }
    if (requestCode == CheckOutMemo.ADD_REQUEST_CODE) {
        String header = data.getStringExtra("header");
        String bodyText = data.getStringExtra("bodyText");
        if (getIntent().hasExtra("byteArray")) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(
                    getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
            view.setImageBitmap(bitmap);
        }
        Memo memo = new Memo(header, bodyText, view);
        customAdapter.add(memo);
        customAdapter.notifyDataSetChanged();
    }

    if (requestCode == CheckOutMemo.EDIT_REQUEST_CODE) {

        int position = data.getIntExtra("position", 0);
        Memo memo = customAdapter.getItem(position);
        memo.header = data.getStringExtra("header");
        memo.bodyText = data.getStringExtra("bodyText");
        customAdapter.notifyDataSetChanged();
    }
  }
}

CHECKOUTMEMO.CLASS
public class CheckOutMemo extends AppCompatActivity {
public static final int ADD_REQUEST_CODE = 1;
public static final int EDIT_REQUEST_CODE = 2;
public static final int REQUEST_IMAGE_CAPTURE = 1337;
public String fileName;
public Bitmap bitmap;
private int position;
EditText editableTitle;
EditText editableContent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    Intent intent = getIntent();
    editableTitle = (EditText) findViewById(R.id.editHeader);
    editableContent = (EditText) findViewById(R.id.editBodyText);
    editableTitle.setText(intent.getStringExtra("header"));
    editableContent.setText(intent.getStringExtra("bodyText"));
    checkIfUserChangedOrWroteAnyText();
    //Declaring keyword and default position.
    position = intent.getIntExtra("position", 0);
}

public void capturePhoto(View view) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

        try {
            loadImageFromFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public void loadImageFromFile() throws IOException {

    ImageView view = (ImageView)this.findViewById(R.id.primeImage);
    view.setVisibility(View.VISIBLE);
    int targetW = view.getWidth();
    int targetH = view.getHeight();

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(fileName, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bitmap = BitmapFactory.decodeFile(fileName, bmOptions);
    view.setImageBitmap(bitmap);

}

public void createImageFromBitmap(){
    if(bitmap!=null) {
        Intent i = new Intent(this, MainActivity.class);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bs);
        i.putExtra("byteArray", bs.toByteArray());
        startActivity(i);
    } else {
        Toast.makeText(CheckOutMemo.this, "Bitmap is null", Toast.LENGTH_SHORT).show();
    }
}

public void onSaveClick(View view){
    String editableContentString = editableContent.getText().toString();
    String editableTitleString = editableTitle.getText().toString();
    if(TextUtils.isEmpty(editableContentString) && TextUtils.isEmpty(editableTitleString)) {
        finish();
        Toast.makeText(CheckOutMemo.this, "No content to save, note discarded", Toast.LENGTH_SHORT).show();
    }
    else {
        if ((TextUtils.isEmpty(editableTitleString))) {
            editableTitleString.equals(editableContentString);
            Intent intent = new Intent();
            createImageFromBitmap();
            intent.putExtra("header", editableContent.getText().toString());
            intent.putExtra("position", position);

            //Sending userInput back to MainActivity.
            setResult(Activity.RESULT_OK, intent);
            finish();

        } else {
            Intent intent = new Intent();
            createImageFromBitmap();
            intent.putExtra("header", editableTitle.getText().toString());
            intent.putExtra("bodyText", editableContent.getText().toString());
            intent.putExtra("position", position);
            //Sending userInput back to MainActivity.
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    }
}

public void cancelButtonClickedAfterEdit() {
    Button button = (Button) findViewById(R.id.bigCancelButton);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            openDialogFragment(v);
        }
    });
}

public File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        String folder_main = "DNote";
        String path = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES).toString() + File.separator + folder_main;
        File storageDir = new File(path);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        fileName =  image.getAbsolutePath();
        MediaScannerConnection.scanFile(getApplicationContext(), new String[]{image.getPath()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
//                        Log.i(TAG, "Scanned " + path);
                    }
                });
        return image;
    }

@Override
public void onBackPressed() {
    openDialogFragment(null);
}
public void onCancelClick(View view){
    finish();

}
}

CUSTOMADAPTER.CLASS
public class CustomAdapter extends BaseAdapter {

ArrayList<Memo> memos = new ArrayList<>();

public void add(Memo memo) {
    this.memos.add(memo);
}

public void delete(int position) {
    memos.remove(position);
}

@Override
public Memo getItem(int position) {
    return memos.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getCount() {
    return memos.size();
}

class MyViewHolder {
    public TextView header, bodyText;
    public ImageView imageView;

    public MyViewHolder(View view) {
        header = (TextView) view.findViewById(R.id.header);
        bodyText = (TextView) view.findViewById(R.id.bodyText);
        imageView = (ImageView) view.findViewById(R.id.primeImage);

    }
}

@Override
public View getView(final int position, View convertView, ViewGroup parent){

    MyViewHolder viewHolder;
    if(null == convertView){
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        convertView = inflater.inflate(R.layout.custom_row, parent, false);
        viewHolder = new MyViewHolder(convertView);
        viewHolder.header.setTag(position);

        convertView.setTag(viewHolder);

    }
    else{
        viewHolder = (MyViewHolder) convertView.getTag();
    }

    Memo memo = getItem(position);
    viewHolder.header.setText(memo.header);
    viewHolder.bodyText.setText(memo.bodyText);
    CheckOutMemo checkOutMemo = new CheckOutMemo();;
    if(checkOutMemo.bitmap!=null) {
        viewHolder.imageView.setImageBitmap(checkOutMemo.bitmap);
    }

    return convertView;
}

}

MEMO.CLASS
public class Memo {

    public String header, bodyText;
    public ImageView imageView;

    public Memo(String header, String bodyText, ImageView imageView){
        this.header = header;
        this.bodyText =  bodyText;
        this.imageView = imageView;
    }
}

I've been working on this for over 2 months every day. Any help would be appreciated!!
Comment: I gotcha here man, working on a solution for you. Mainly stems from the fact that you aren't passing some sort of a reference to your image out to your Main Activity.

For example when you instantiate a new CheckoutMemo in your adapter's get view method, it has no bitmap.
Comment: you have not set Data to your customAdapter. you haven't call customAdapter.add(memo) method any where.
Answer: Ok here is the minimal viable solution to get what you want. I just fixed it enough so an image is returned to your main activity. The rest of your issues are for you to fix. The only class I haven't touched is your Memo class. But that being said I highly recommend you update it to store a String with the path to the image instead of an ImageView.
But if for you what you want to do here are your files edited to work:
First custom adapter:
I've changed the lines where you get the image from memo, to check it's image view for a bitmap drawable and transfer that bitmap to the row's image view. There was no need to instantiate that CheckoutMemo activity here.
public class CustomAdapter extends BaseAdapter {

    ArrayList<Memo> memos = new ArrayList<>();

    public void add(Memo memo) {
        this.memos.add(memo);
    }

    public void delete(int position) {
        memos.remove(position);
    }

    @Override
    public Memo getItem(int position) {
        return memos.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getCount() {
        return memos.size();
    }

    class MyViewHolder {
        public TextView header, bodyText;
        public ImageView imageView;

        public MyViewHolder(View view) {
            header = (TextView) view.findViewById(R.id.header);
            bodyText = (TextView) view.findViewById(R.id.bodyText);
            imageView = (ImageView) view.findViewById(R.id.primeImage);

        }
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent){

        MyViewHolder viewHolder;
        if(null == convertView){
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            convertView = inflater.inflate(R.layout.custom_row, parent, false);
            viewHolder = new MyViewHolder(convertView);
            viewHolder.header.setTag(position);

            convertView.setTag(viewHolder);

        }
        else{
            viewHolder = (MyViewHolder) convertView.getTag();
        }

        Memo memo = getItem(position);
        viewHolder.header.setText(memo.header);
        viewHolder.bodyText.setText(memo.bodyText);
        if (memo.imageView.getDrawable() instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) memo.imageView.getDrawable();
            viewHolder.imageView.setImageBitmap(bitmapDrawable.getBitmap());
        }

        return convertView;
    }

}

Next your CheckoutMemo:
I've changed how your setResult methods work. I've also deleted the method createImageFromBitmap. It was problematic, and also caused confusion. That one was a doozy. The createImageFromBitmap method was creating another MainActivity... confused me for a bit why onActivityResult wasn't being called. It wasn't being called because you were creating another activity =/
Anyways in your intent you create with your results, you'll notice I am also adding the file path string to the image created. So that main activity can use it to get the image!
public class CheckOutMemo extends AppCompatActivity {
    public static final int ADD_REQUEST_CODE = 1;
    public static final int EDIT_REQUEST_CODE = 2;
    public static final int REQUEST_IMAGE_CAPTURE = 1337;
    public String fileName;
    public Bitmap bitmap;
    private int position;
    EditText editableTitle;
    EditText editableContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        Intent intent = getIntent();
        editableTitle = (EditText) findViewById(R.id.editHeader);
        editableContent = (EditText) findViewById(R.id.editBodyText);
        editableTitle.setText(intent.getStringExtra("header"));
        editableContent.setText(intent.getStringExtra("bodyText"));
        //checkIfUserChangedOrWroteAnyText();
        //Declaring keyword and default position.
        position = intent.getIntExtra("position", 0);
    }

    public void capturePhoto(View view) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File

            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

            try {
                loadImageFromFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void loadImageFromFile() throws IOException {

        ImageView view = (ImageView)this.findViewById(R.id.primeImage);
        view.setVisibility(View.VISIBLE);
        int targetW = view.getWidth();
        int targetH = view.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(fileName, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bitmap = BitmapFactory.decodeFile(fileName, bmOptions);
        view.setImageBitmap(bitmap);

    }

    public void onSaveClick(View view){
        String editableContentString = editableContent.getText().toString();
        String editableTitleString = editableTitle.getText().toString();
        if(TextUtils.isEmpty(editableContentString) && TextUtils.isEmpty(editableTitleString)) {
            finish();
            Toast.makeText(CheckOutMemo.this, "No content to save, note discarded", Toast.LENGTH_SHORT).show();
        }
        else {
            if ((TextUtils.isEmpty(editableTitleString))) {
                editableTitleString.equals(editableContentString);
                Intent intent = new Intent();
                //createImageFromBitmap();
                intent.putExtra("header", editableContent.getText().toString());
                intent.putExtra("position", position);
                intent.putExtra("photo", fileName);

                //Sending userInput back to MainActivity.
                setResult(AppCompatActivity.RESULT_OK, intent);
                finish();

            } else {
                Intent intent = new Intent();
                //createImageFromBitmap();
                intent.putExtra("header", editableTitle.getText().toString());
                intent.putExtra("bodyText", editableContent.getText().toString());
                intent.putExtra("photo", fileName);
                intent.putExtra("position", position);
                //Sending userInput back to MainActivity.
                setResult(AppCompatActivity.RESULT_OK, intent);
                finish();
            }
        }
    }

    public void cancelButtonClickedAfterEdit() {
        Button button = (Button) findViewById(R.id.bigCancelButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                //openDialogFragment(v);
            }
        });
    }

    public File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        String folder_main = "DNote";
        String path = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES).toString() + File.separator + folder_main;
        File storageDir = new File(path);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        fileName =  image.getAbsolutePath();
        MediaScannerConnection.scanFile(getApplicationContext(), new String[]{image.getPath()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
//                        Log.i(TAG, "Scanned " + path);
                    }
                });
        return image;
    }

    @Override
    public void onBackPressed() {
        //openDialogFragment(null);
    }
    public void onCancelClick(View view){
        finish();

    }
}

Finally your MainActivity:
In on activity result if the photo path exists. Then I am adding it to the memo object's image view to later be retrieved by the adapters ImageView. This can be upgraded a bit hence my comments above to be a little less convoluted by just passing the file path ;)
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener,
        AdapterView.OnItemClickListener {

    public ImageView view;
    private String[] mPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    private static final int REQUEST_CODE_PERMISSION = 5;
    CustomAdapter customAdapter;
    ListView listView;
    Intent intent;
    final Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        customAdapter = new CustomAdapter();
        listView = (ListView) findViewById(R.id.myListView);
        listView.setAdapter(customAdapter);
        listView.setOnItemLongClickListener(this);
        listView.setOnItemClickListener(this);
        //view = (ImageView) this.findViewById(R.id.imageIcon);

        if (ActivityCompat.checkSelfPermission(MainActivity.this, mPermission[0])
                != MockPackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(MainActivity.this, mPermission[1])
                        != MockPackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(MainActivity.this,
                    mPermission, REQUEST_CODE_PERMISSION);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Memo memo = customAdapter.getItem(position);
        intent = new Intent(getApplicationContext(), CheckOutMemo.class);
        intent.putExtra("header", memo.header);
        intent.putExtra("bodyText", memo.bodyText);
        intent.putExtra("position", position);

        // launches edit request and saving existing item.
        startActivityForResult(intent, CheckOutMemo.EDIT_REQUEST_CODE);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle("Confirm Delete");
        alertDialogBuilder.setMessage("Delete memo?");
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                customAdapter.delete(position);
                customAdapter.notifyDataSetChanged();
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

        return true;
    }

    public void addNewNote(View view) {
        Intent intent = new Intent(getApplicationContext(), CheckOutMemo.class);
        //Adding new listItem to the ArrayList.
        startActivityForResult(intent, CheckOutMemo.ADD_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == CheckOutMemo.ADD_REQUEST_CODE) {
            String header = data.getStringExtra("header");
            String bodyText = data.getStringExtra("bodyText");
            File photo = new File(data.getStringExtra("photo"));
            ImageView view = new ImageView(this);

            if (photo.exists()) {
                Bitmap myBitmap = BitmapFactory.decodeFile(photo.getAbsolutePath());
                view.setImageBitmap(myBitmap);
            }

            Memo memo = new Memo(header, bodyText, view);
            customAdapter.add(memo);
            customAdapter.notifyDataSetChanged();
        }

        if (requestCode == CheckOutMemo.EDIT_REQUEST_CODE) {

            int position = data.getIntExtra("position", 0);
            Memo memo = customAdapter.getItem(position);
            memo.header = data.getStringExtra("header");
            memo.bodyText = data.getStringExtra("bodyText");
            File photo = new File(data.getStringExtra("photo"));

            if (photo.exists()) {
                Bitmap myBitmap = BitmapFactory.decodeFile(photo.getAbsolutePath());
                memo.imageView.setImageBitmap(myBitmap);
            }
            customAdapter.notifyDataSetChanged();
        }
    }
}

All in all, running this I can now see images in the notes created!
Keep at your project here. Two months is a good commitment. You are doing great, keep up the good work. There are more things you can improve in there! Just keep massaging it, and never give up.
You rock =)
I can get you the working project I've created to test this if needed.
Comment: I can't thank you enough for helping me out! I've literary got teary-eyes when I saw your answer! Yes I would really want to get your working project if it's not too much to ask, since there somehow seems to be differences in our XML_Layouts. The program throws nullPointerException-–telling me my ImageView is attempting to invoke on a null object reference in my CustomAdapter.class.
This is normally caused if I haven't referenced my ImageView to the correct id, but since you wrote this code for me, I feel a little clueless on what could be the issue. Seriously Dave you're the hero of the day!
Comment: Hi again Dave! I found the problem was in my XML_layout and I managed to fix it so everything works now! :)
Thank you so much for your help!
Comment: Great, that is awesome.  Good job figuring out the differences.  Glad you got it yourself, you will always learn more when you do.  All the best to you!
Comment: Uploaded my solution here for extra reference: https://github.com/davethomas11/stackoverflow_Q_39401723  Just in case


I cannot get the id in jquery

Question: The problem is i want to get the id of the li and alert it, but it i cannot get the value of the id it just alerts an empty string. I'm stuck with this for almost 3 hours.
here is my code:
HTML:

        My Project

JQUERY:
 $(document).on("click",".projectlink",function(){
    var idx = event.target.id;
    alert(idx);
 });

Any idea what's the problem with this code?
UPDATE
Thanks to vsync! and i'm able to solve the problem. Just edited this code here and it really worked:
$(document).on("click",".projectlink",function(){
  var idx = this.id;
  alert(idx);
});

Comment: I actually tried different values for the id but it doesn't seem to work also.
Comment: @vsync Thanks! that worked. I just wonder how?
Comment: Because `this` refers to the the object which the delegation matched, which was the specific '.projectlink` element which was clicked. This is how jQuery event delegation works. People want to be scored so badly they write answers to such simple questions. I prefer to just comment on the simple things.
Answer: You need to define event as callback parameter

$(document).on("click", ".projectlink", function(event) {
  var idx = event.target.id;
  alert(idx);
});

d
  dd

 d
        dd
        My Project

The target property can be the element that registered for the event or a descendant of it. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

Taken from https://api.jquery.com/event.target/
Update :
So you need to use this.id because event.target property can be the element that registered for the event or a descendant of it which doesn't have any id . this or event.currentTarget refers the element that registered for the event

$(document).on("click", ".projectlink", function() {
  var idx = this.id;
  alert(idx);
});

      My Project

Comment: You don't _need_ to use `this.id`, you could just use `event.currentTarget.id`...
Comment: @PranavCBalan No problem. Also `this` can be a tricky thing in JavaScript, so that's why I tend to stay away from it if possible. ([See note here](https://api.jquery.com/event.currentTarget/))
Answer: There are a few things wrong with your javascript:

Be sure to specify the event parameter in the click handler.
Use event.currentTarget or this instead of event.target.
Recommendation - Make id's more complex, not just numbers.

 $(document).on("click", ".projectlink", function (event) {
     var idx = event.currentTarget.id;
     alert(idx);
 });

        My Project

The reason you need to use event.currentTarget instead of event.target has to deal with the event chain. When a click event gets fired the deepest element fires the initial trigger, and then the event is passed up to each parent element for them to handle.
In this example a span is getting clicked on (at least in my browser) and that event bubbles up to the div.row.ellipsis and then up to the li#item3 and then up to body and so on. In other words, once all the click handlers for that element have been executed then the event gets passed up to that element's parent and the cycle continues.
In jQuery when a click event occurs it assigns 'event.targetto the initial element and the current element that has aclickhandler toevent.currentTarget`.
While you can use this to refer to the event.currentTarget, I don't recommend that for a few reasons. Mostly it is due to the danger of context in JavaScript. It is not hard to modify the context that a method runs in, just use Function.prototype.bind(), jQuery.proxy(), or (underscore/lodash's) _.bind(), etc. Since this can be changed, it's best to stick to the dedicated property on event that we can always trust. Likewise using event.currentTarget is much more descriptive that this, which makes it far more maintainable.
Comment: Wow! It seems like there are many alternatives. This code also worked. Thanks :)
Answer: In your script, event.target.id is giving an error for "event is not defined". Modify your script to either include event in the call or not use event and work with this pointer as below:
jQuery(document).on("click",".projectlink",function(){
var idx = this.id;
alert(idx);
});

I cannot get the id in jquery


$\phi: K \to K$ be an $F$-embedding with ${tr.}\;{deg}(K/F)$ finite then $\phi$ is surjective.

Question: Let $K$ be an algebraically closed field and $F$ be a subfield of $K$ with ${tr.}\;{deg}(K/F)$ finite. If $\phi: K \to K$ be an $F$-embedding show that $\phi$ is surjective.
I know the result when ${tr.}\;{deg}(K/F)=0.$ I need some help to prove it in the more general case. Thanks
Answer: Consider the sequence of extensions $K/\phi(K)/F$. Since $\newcommand\trdeg{\operatorname{tr.deg}}\trdeg K/F=n<\infty$, we have that $\trdeg\phi(K)/F=n$ as well, so $\trdeg K/\phi(K) =0$. However $\phi(K)\cong K$ is algebraically closed, so since $K$ is an algebraic extension of $\phi(K)$, it must be trivial. I.e., we have $K=\phi(K)$.


Search for multiple values in IN clause located in where clause

Question: I'm extending search functionality and I need to add search for multiple values in IN clause. So I have textbox and write some number in it. This is dynamic functionality which could add query syntaxis to the WHERE clause of the sql and should be added only when you search.
Let's say we put 1056 in our textbox to search for it.
SELECT
   *
FROM
    QueryTable
WHERE
   (Select ID from SearchTable Where Number='1056') IN
         (SELECT value FROM OPENJSON(JsonField,'$.Data.ArrayOfIds'))

This is working properly because searching for ID in SearchTable returns one row, but I want to make it work when returns multiple rows, something like this:
(Select ID from SearchTable Where Number like '%105%')

This obvious gives an error, because returns multiple records. What is the approach to search multiple values(or array of values) in IN clause.
Answer: Use an EXISTS. I think this is what you need (no sample data to test with to confirm):
FROM QueryTable QT
WHERE EXISTS (SELECT 1
              FROM SearchTable ST
                   JOIN OPENJSON(QT.JsonField,'$.Data.ArrayOfIds') J ON ST.ID = J.[value]
              WHERE ST.Number LIKE '%105%')

Note: I've added aliases to everything, but I've guessed the alias for JsonField. Quantifying your columns is really important to avoid unexpected behaviour and make your code easier to read for both yourself and others.
Comment: That statement doesn't make any sense @mybirthname, as you state that your initial query works. If the `OPENJSON` query returns further JSON, then your query would not work either. So your comment above means that your statement *"This is working properly because searching for ID in SearchTable returns one row"* is untrue. Which is it?
Comment: This is smart, but OPENJSON(QT.JsonField,'$.Data.ArrayOfIds') returns array of number/Guids, so there is not J.[value] in it.It is something like [1,2,3,4]
Comment: Oh I'm stupid I didn't change ID to [value], it is working, my mistake to not change the value. I will accept after 3 minutes, thanks a lot !


After Python 3.6.2 Installation Error

Question: Below is the python shell error shows when it launched, Please let me know if this causes an issue or how to solve this?
I have installed most recent version of Python 3.6.2 and installed Django later.
3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)]
Traceback (most recent call last):
  Python Shell, prompt 0, line 21
  File "<string>", line 1, in <module>
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\conf\__init__.py", line 56, in __getattr__
    self._setup(name)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\conf\__init__.py", line 43, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\conf\__init__.py", line 106, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\importlib\_bootstrap.py", line 994, in _gcd_import
    return _find_and_load(name, _gcd_import)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\importlib\_bootstrap.py", line 971, in _find_and_load
    return _find_and_load_unlocked(name, import_)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\importlib\_bootstrap.py", line 941, in _find_and_load_unlocked
    _call_with_frames_removed(import_, parent)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\importlib\_bootstrap.py", line 219, in _call_with_frames_removed
    return f(*args, **kwds)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\importlib\_bootstrap.py", line 994, in _gcd_import
    return _find_and_load(name, _gcd_import)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\importlib\_bootstrap.py", line 971, in _find_and_load
    return _find_and_load_unlocked(name, import_)
  File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\Lib\importlib\_bootstrap.py", line 953, in _find_and_load_unlocked
    raise ModuleNotFoundError(_ERR_MSG.format(name), name=name)
builtins.ModuleNotFoundError: No module named 'simplesocial'

Comment: This appears to be a django package... see @Cyzanfar's answer.
Comment: Install the package `simplesocial` (see last line of the error traceback).
Comment: do I need to install with pip install simplesocial command?
Comment: That's usually the best way!
Comment: I tried to answer but ended in error as below
C:\Windows\System32>pip install simplesocial
Collecting simplesocial
  Could not find a version that satisfies the requirement simplesocial (from versions: )
No matching distribution found for simplesocial
Answer: From the last error message in the stack trace, You're missing the simplesocial module which is a Django package. Install using pip:
pip install django-simple-social

Answer: As far as I can see, you don't have the module simplesocial installed.

After Python 3.6.2 Installation Error


Do these two definitions of *enough projectives* coincide?

Question: Let $\mathcal{C}$ be a $k$-linear abelian category. Are the following two definitions of enough projectives equivalent?

(i) For every object $A$ there exists a projective object $P$ s.t. $P\twoheadrightarrow A$
(ii) Every simple object $U_i$ has a projective cover $p_i: P_i\twoheadrightarrow U_i$

The first one is taken from wikipedia, the second from the book Tensor Categories by Etingof et al.
I think this cannot be the same, for the superficial reason that nothing in (ii) makes a reference to arbitrary (generally indecomposable) objects of $\mathcal{C}$. However, I might be very wrong since I cannot seem to prove it.
Any pointers?
Comment: What's your definition of simple object?
Comment: One whose only subobjects are $0$ and itself.
Answer: They do not, in general. I bet Etingof is assuming we're in a semisimple category, as is usually the case, if not always, in that book. If every object is a sum of simples, then it should be clear that these conditions are equivalent, since a sum of projectives is projective and a sum of epis is epi. The conditions are not equivalent in general, since abelian categories need not have any simple objects. See Jeremy Rickard's example  here.
Comment: To be fair, I lied a bit (by omission). We are actually assuming *local finiteness* (Hom-finite and every object has finite length) and finitely many iso classes of simple objects. As you might have noticed, this is precisely the definition of a finite abelian cat over $k$, which is generally not semisimple.
Comment: If the category is semsimple, then the statement is trivial: all objects are projective in this case!
Answer: Taking into account the local finiteness assumption in your comment to Kevin Arlin's answer (which should rather be in the question itself), here is the receipe to treat a general object, assuming (ii): consider its head (quotient by the radical, which is semisimple), and take the direct sum of the projective covers of the simples involved.


Combining p-values for averaging technical protein quantification replicates in python

Question: I have some data about protein expression levels in a cell. For each identified protein, there is an expression level and an associated p-value indicating the confidence that the protein was identified correctly. Two of the samples were technical replicates (i.e. a single sample was split into two parts and analysed separately). I now need to average the expression levels of the two technical replicates, and their corresponding p-values. I thought to use Fisher's method to combine them, which seems to me like the right thing to do. The problem is that I need to convert the result from a $\chi^2$ value into a p-value. Excel has a CHIDIST function which seems to do the trick, but, since I'm likely to be doing this sort of thing a lot in the near future, I thought to write a script to do it to plug into our analysis pipeline. I'm using python to write it, but can't find an equivalent function to CHIDIST. I realize that the process is basically finding the probability of getting the given $\chi^2$ score, so I'd like to check my thinking.

Am I doing the right thing combining the p-values?
Is Fisher's Method the appropriate process for combining the p-values?
How many degrees of freedom? I'm thinking 2, as per the Wikipedia page.
The final p-value is one minus the integral from negative infinity to the $\chi^2$ score over the $\chi^2$ probability density function with one degree of freedom -- is this correct?
Comment: With respect to Python and finding the analog to Excel's CHIDIST function, Scipy has what you need in the scipy.stats.chi2 class. For example,  1 - chi2.cdf(5, 3) = CHIDIST(5, 3) = 0.171797
Comment: (1) Where does the one degree of freedom in (4) come from?  (2) The complementary CDF for $\chi^2(2)$ is simply $x\to \exp(-x/2)$.
Comment: @whuber, sorry the 1 was a typo, and the replacement (2) was a misreading of the formula for fisher's method. DF should be 2k where k is the number of tests combined (in my case 2), so it should be 4
Comment: @JoshHemann, thanks, this is what I'm looking for.
Comment: With four df, Fisher's Method gives $p_1 p_2 (1 - \log(p_1 p_2))$.  In general, for other (even) degrees of freedom, the result does not require calculating chi-squared distributions; it is a polynomial in the product of the $p_i$ and its logarithm.  For $n$ tests, instead of 2, the formula is $x\sum_{k=0}^{n-1}(-\log(x))^k/k! $ for $x=p_1p_2\ldots p_n$.
Comment: Someone, like @JoshHemann or whuber should probably write it as an answer so it can be accepted.
Comment: @whuber , do you know where I can find a reference for this formula? I opened a new question with that topic: http://stats.stackexchange.com/q/199581/36056
Answer: To combine p-values means to find formulas $g(p_1,p_2, \ldots, p_n)$ (one for each $n\ge 2$) for which

$g$ is symmetric in its arguments;
$g$ is strictly increasing separately in each variable; and
$P=g(P_1,\ldots, P_n)$ has a uniform distribution when the $P_i$ are independently uniformly distributed.

Symmetry means no one of the $n$ tests is favored over any other.  Strict increase means that each test genuinely influences the combined result in the expected way: when all other tests remain the same but a given p-value gets larger (less significant), then the combined result should get less significant, too.  The uniform distribution is a basic property of p-values: it assures that the chance of a combined p-value being smaller than any level $0 \lt \alpha \lt 1$ is exactly $\alpha$.
For many situations these properties imply that when the $p_i$ are p-values for independent tests of hypotheses, $g(p_1,\ldots,p_n)$ is a p-value for the null hypothesis that all $n$ of the separate hypotheses are true.
Fisher's method is
$$g(p_1,\ldots, p_n) = 1 - \frac{1}{(n-1)!}\int_0^{-\log(p_1p_2\cdots p_n)} t^{n-1}e^{-t}dt.$$
Properties (1) and (2) are obvious, while the third property (uniform distribution) follows from standard relationships among uniform and Gamma random variables.
I claim the integral can be eliminated, leaving a relatively simple algebraic function of the $p_i$ and their logarithms.  To see this, define $$F_n(x) = C_n\int_0^x t^{n-1}e^{-t}dt$$ where $$C_n =\frac{1}{(n-1)!} = \frac{1}{n-1}C_{n-1}$$
(provided, in the latter case, that $n \ge 2$).  When $n=1$ this has the simple expression
$$F_1(x) = \int_0^x e^{-t}dt = 1 - e^{-t}.$$
When $n\ge 2$, integrate by parts to find
$$\eqalign{
F_n(x) &=\left. - C_n t^{n-1} e^{-t}\right|_0^x + (n-1)C_n \int_0^x t^{n-2}e^{-t}dt \\
&= -\frac{x^{n-1} e^{-x}}{(n-1)!} + F_{n-1}(x).
}$$
Apply this $n-1$ times to the right hand side until the subscript of $F$ reduces to $1$, for which we have the simple formula shown above.  Upon indexing the steps by $i=1, 2, \ldots, n-1$ and then setting $j=n-i$, the result is
$$F_n(x) = 1 - e^{-x} - \sum_{i=1}^{n-1} \frac{x^{n-i} e^{-x}}{(n-i)!} = 1 - e^{-x}  \sum_{j=0}^{n-1} \frac{x^j}{j!}.$$
Write $p=p_1p_2\cdots p_n$ for the product of the p-values.  Setting $$x=\log(p) = \log(p_1)+\cdots+\log(p_n)$$ yields
$$\eqalign{
g(p_1,\ldots, p_n) &= 1 - F_n(-x) = p \sum_{j=0}^{n-1} \frac{(-x)^j}{j!} \\
&=p_1p_2\cdots p_n \sum_{j=0}^{n-1} (-1)^j \frac{\left(\log(p_1)+\cdots+\log(p_n)\right)^j}{j!}.
}$$

This is most useful for its insight into combining p-values, but for small $n$ isn't too shabby a method of calculation in its own right, provided you avoid operations that lose floating point precision or create underflow.  (One method is illustrated in the R code below, which computes the logarithms of each term in $g$ rather than computing the terms themselves.)  Here are the formulas for $n=2$ and $n=3$, for instance:
$$\eqalign{
g(p_1,p_2) &= p_1p_2\left(1 - \log(p_1p_2)\right) \\
g(p_1,p_2,p_3) &= p_1p_2p_3\left(1 - \log(p_1p_2p_3) + \frac{1}{2} \left(\log(p_1p_2p_3)\right)^2\right).
}$$
The terms in parentheses are factors (always greater than $1$) that correct the naive estimate that the combined p-value should be the product of the individual p-values.

Fisher.algebraic <- function(p) {
  if (length(p)==1) return(p)
  x <- sum(log(p))
  return(sum(exp(x + cumsum(c(0, log(-x / 1:(length(p)-1)))))))
  #
  # Straightforward (but numerically limited) method:
  #
  n <- length(p)
  j <- 0:(n-1)
  x <- sum(log(p))
  return(prod(p) * sum((-x)^j / factorial(j)))
}
Fisher <- function(p) {
  pgamma(-sum(log(p)), length(p), lower.tail=FALSE)
}
#
# Compare the two calculations with one example.
#
n <- 10 # Try `n <- 1e6`; then try it with the straightforward method.
p <- runif(n)
c(Fisher=Fisher(p), Algebraic=Fisher.algebraic(p))
#
# Compare the timing.
# For n < 10, approximately, the timing is about the same.  After that,
# the integral method `Fisher` becomes superior (as one might expect,
# because of the two sums involved in the algebraic method).
#
N <- ceiling(log(n) * 5e5/n) # Limits the timing to about 1 second
system.time(replicate(N, Fisher(p)))
system.time(replicate(N, Fisher.algebraic(p)))
#
# Show that uniform p-values produce a uniform combined p-value.
#
p <- replicate(N, Fisher.algebraic(runif(n)))
hist(p)


Exercise help: Asteroid impacts on the Earth modelled with a Poisson distribution

Question: Suppose that asteroid impacts on the earth are modelled with a Poisson distribution. Suppose large asteroids are estimated to impact the Earth once every 50000 years.  Poisson distribution predicts the probability of $k$ events when the event frequency is $\lambda$ to be $\frac{\lambda^k}{k!}e^{-\lambda}$
How many years are required for the probability of at least one1km diameter impact to exceed 10%?
How would I solve this question?
Answer: You have a mean of 1 impact every 500 000 years.

Let's study the number of impacts $X$ in the next 500 000 years: $X\sim\text{Pois}(\lambda)$ with $\lambda = 1$. $$P(X>1) = 1-P(X=1)-P(X=0)$$ Now replace $P(X=k)$ with the expression given by the poisson distribution.

Let's study the number of impacts $X$ in the next 100 000 years: $X\sim\text{Pois}(\lambda)$ with $\lambda = \frac{1}{5}$. Give $P(X=0)$

Let's study the number of impact $X$ in the next $y$ years: $X\sim\text{Pois}(\lambda)$ with $\lambda = \frac{y}{500000}$.
$$P(X>0)>0.5$$
$$P(X=0) < 0.5$$
$$e^{-\lambda} < 0.5$$
Express with $y$


Correct way for a db_query for nodes between two timestamps

Question: I have a very simple db_query.  I want to look for any node created between two timestamps.
This query works fine in MySQL shell
<code>SELECT nid as id,created as start,title FROM node WHERE created BETWEEN '1403564400' AND '1403650800';
</code>
This works fine in Drupal
<code>$data = db_query("SELECT nid as id,created as start,title FROM node")->fetchAll();
echo json_encode($data);
</code>
As soon as I add in the BETWEEN conditions below I get an Internal Server Error.
<code>$data = db_query("SELECT nid as id,created as start,title FROM node WHERE created BETWEEN '1403564400' AND '1403650800'")->fetchAll();
</code>
I am unsure what I am doing wrong here, perhaps someone can point me in the right direction please!
Answer: You can try using db_select instead wich is a better way to create query with Drupal (assuming you are using Drupal 7).
<code>$start_time = '1403564400';
$end_time = '1403650800';
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'created', 'title'))
  ->condition('created', array($start_time, $end_time), 'BETWEEN');
$result = $query->execute();
$record = $result->fetchAll();
</code>
Comment: Thank you - I have been told that db_select is slower and for critical performance related tasks, db_query is the better option.  I also only wnated to use DRUPAL_BOOTSTRAP_DATABASE for this task as I need to retrieve this data quickly and did not want to do a full Drupal boostrap call.
Comment: My mistake, db_query was working, I just had some wrong code elsewhere.
Comment: Ok, but beware when using db_query to escape your vars. Glad your problem was solved :-D
Comment: Use placeholders instead of escaping your variables.  These work in `db_query()`.  Also, if you are querying against the `{node}` table you should just about always use a `db_select()` with `->addTag('node_access')` to make sure you don't have a permission bypass problem.


Proving that a quasi-Dirac delta function is a pulse of magnitude one at positive integers

Question: Consider the function,
$$\delta(n)=\lim_{z\rightarrow\infty}\left(\sum_{n=1}^{\infty} e^{-z\left(x-n\right)^2}\right).$$
I am trying to prove that
\begin{equation}
\delta(n)=\begin{cases}1 & \text{if }n\in\mathbb{N}+1\\ 0 & \text{if $n\notin\mathbb{N}+1$}\end{cases}.
\end{equation}
Theory of distributions might help, since the function is a quasi-Dirac delta function (but with impulse of magnitude one instead of infinity). The following property seems to be true, although I'm not sure of its rigour:
\begin{equation}
\int_{-\infty}^{\infty} \phi(x)\delta\left(x-a\right)\equiv0.
\end{equation}
Any help would be much appreciated.
Comment: I think you meant $\delta(x)$ in you first equation. I can't edit it myself however.
Comment: What does $\mathbb{N}+1$ mean?  Do you mean $\mathbb{N}_{>0}$?
Comment: @MarkViola $\mathbb N+1 = \{n+1| n\in\mathbb N\}$.
Comment: That is not a conventional way to write that set.  $\mathbb{N}_{>0}$ or $\mathbb{N}_+$ are common.
Comment: $\mathbb N^*$ too. $\mathbb N_+$ is misleading in many countries, as $\mathbb R_+ = \{x\in\mathbb R, x \geq 0\}$ to me.
Comment: Sorry for not clarifying. I was using Tao's notation, whereby $\mathbb{N}+1=\{1,2,3,...\}$ denotes the positive integers (i.e. $\mathbb{N}$ starts from $0$).
Answer: The Theory of distributions is of little help here, as the function we're studying is not continuous, and zero almost everywhere. The easiest way to prove your result is still to prove it pointwise. Let $x\in\mathbb R$.
If $x\in\mathbb N +1$, then for $z>0$,
\begin{split}
\sum_{n=1}^\infty e^{-z(x-n)^2} &= 1+\sum_{n=1}^{x-1} e^{-z(x-n)^2}+\sum_{n=x+1}^\infty e^{-z(x-n)^2} \\
 &= 1+\sum_{n=1}^{x-1} e^{-z(x-n)^2}+\sum_{n=1}^\infty e^{-zn^2}
\end{split}
The first sum in the right-hand side converges to zero as $z\to\infty$, and so does the second one by uniform convergence. Therefore $\delta(x)=1$.
If $x\neq\mathbb N +1$, then each of the exponents is non-zero so uniform convergence works as well to get $\delta(x)=0$.
Comment: Note that monotone convergence works as well.


SQL query for words (not the sentence)

Question: I would like to query a single column (varchar):
sample datarows:
1) The fox jumps like a foo on my bar
2) Jumpers are not cool
3) Apple introduced iJump

When I enter a search criteria like... jump
I expect to get a resultset of: jumps, Jumpers, iJump
(So I dont want the complete row)
Currently I'm using MySQL (I'm open to suggestions as long it's open source)
Comment: What happens where there are more than one `jump`'s in the row?
Comment: What Type of SQL?  SQL Server, MySQL, Oracle, etc...?
Comment: I suggest reading up on [full text search](http://en.wikipedia.org/wiki/Full_text_search). Depending on database, you may already have support for it.
Comment: I've never ever heard of a SQL-Statement doing this. I suggest looping the resultset with a regex for filtering. EDIT: Whoops! Google proofs me wrong. There may be support for it depending on your DB-System. But maybe the suggested solution is of some value anyway?
Comment: first occurrence returned is good, if more could be returned it's even better
Comment: extended with info, it's MySQL
Answer: Since you're using MySQL, I might suggest looking into LIB_MYSQLUDF_PREG.
This open source library will provide you with additional regex functionality, including the PREG_CAPTURE function, which extracts a regex match from a string.
Using this function, you could easily build a regex to return the match you're looking for... Something like:
\b\w*jump\w*\b

Answer: Getting any row with your search criteria is easy:
SELECT sentence
FROM sentences
WHERE sentence LIKE '%jump%'

I'd probably do the rest in application logic, since doing it in the database doesn't help you at all.
Also, any method of splitting a string and handling it will probably be database-specific, so you would need to say which one you're using.
Comment: And "LIKE '%jump'"  to find jumps, Jumpers.          And "LIKE 'jump%'" to find iJump          And simple "LIKE 'jump'" to find jumps, Jumpers, iJump  :3   But i recomend use sphinx or lucene

SQL query for words (not the sentence)


Logic inside Django serializer

Question: I have a Django serializer implementation that has a field which contains a list as part of a JWT authentication process. For example:
class MySerializer(serializers.ModelSerializer):
    class Meta:
        field = ['a', 'b', 'c']

I then have some logic in my user model
class MyUser(PermissionMixin, AbstractBaseUser):
   permissions = ['OK', 'NOT_OK']

I can access my users from the following logic inside my serializer
self.context['request'].user.permissions

I would now like to only share parts a and b of field if the user is not permitted to access c. In other words I want to do something roughly equivalent to
class MySerializer(serializers.ModelSerializer):
    class Meta:
        if 'OK' in self.context['request'].user.permissions:
           field = ['a', 'b', 'c']
        else:
           field = ['a', 'b']

However, the Meta class does not have self attached. What is the best design pattern to achieve what I want? Is the serializer the best place to house this logic?
Comment: You may create two serializers, one with fields (a ,b and c), and the other with fields (a and b) only. and choose which to use in the view.
Answer: If you need to alter the serialization or deserialization behavior of a serializer class, you can do so by overriding the .to_representation() or .to_internal_value() methods.
Some reasons this might be useful include...

Adding new behavior for new serializer base classes.
Modifying the behavior slightly for an existing class.
Improving serialization performance for a frequently accessed API endpoint that returns lots of data.

The signatures for these methods are as follows:
.to_representation(self, instance)
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
May be overridden in order to modify the representation style. For example:
def to_representation(self, instance):
    ret = super().to_representation(instance)
    ret['username'] = ret['username'].lower()
    return ret

ref: https://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior

Logic inside Django serializer


How to use an NT auth connection in PHP?

Question: I am attempting to connect to a Microsoft SQL server db using PHP (in IIS). The user/pass provided in the code is an AD account that can access the database via ODBC in Access just fine.
$serverName = "servername";
$connectionInfo = array( "Database"=>"dbname", "UID"=>"myuser", "PWD"=>"mypass");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.
";
}else{
     echo "Connection could not be established.

";
     die( print_r( sqlsrv_errors(), true));
}

The username and password are valid, as are the server name and database name. But this is returning the error:

[Microsoft][SQL Server Native Client 10.0][SQL Server]Login failed for user 'myuser'.

For the username (which is a valid user in AD, and I can connect/link to this database using Access) I've also tried:

DOMAIN.ORG\myuser
DOMAIN.ORG\\myuser
email@example.com

My domain user (myuser) has admin privileges to that server via AD. But that returns the same Login failed error. Is there something I'm missing? I can connect to this same db using Access without a problem (under the same user).
The way I connect in Access is an ODBC Data Source for the local user. The Data Source is set to authenticate "With Windows NT authentication using the network login ID". How can I do that in PHP?
Is this impersonation configuration the possible cause?
PHP is running under the user nt authority\iusr
If it was trying to login using iusr wouldn't the error message say so?
I've tried creating a Data Source on this machine called "TestDS" and using the code:
$conn = odbc_connect("TestDS", "", "");

But that gives me:

The specified DSN contains an architecture mismatch between the Driver and Application, SQL state IM014 in SQLConnect

Machine1 is a client trying to access a webpage (where the PHP code is on Machine2) and the code on Machine2 is making the SQL connection to Machine3 (servername).
Answer: "Windows Security" in SQL Server connections is enabled by specifying "Trusted Connection=SSPI" in the connection string. No username or password is stored in the connection string (that's only for "SQL Server Security"). The process running PHP (presumably php_cgi.exe itself) must run under a Windows (either local or AD) that has a Windows login registered on the SQL Server.
Under IIS php_cgi.exe runs under the user identity of the application pool. If you have a heterogenous security environment I suggest creating an IIS application pool just for this single website.
Comment: I made an edit to my question. So I should be adding a local user `iusr` to the SQL server?
Comment: Yes, but then use the "Trusted Connection" option in your connection string instead of Username/Password. Note that if your SQL Server is located on a different physical machine (and you don't have an Active Directory trust relationship between the machines) then you will have to use SQL Server Authentication instead of Windows auth.
Comment: I went with SQL authentication.


DateTime.ParseExact to UTC value

Question: I retrieve a date and time from my web api and set it as so :
tmp = DateTime.ParseExact(dateAndTimeFromApi, "dd/MM/yyyy HH:mm:ss", null);

I need to convert this DateTime to a UTC DateTime. When I add .ToUniversalTime() it does not convert from local to UTC. My current timezone is UTC + 2.
So I want to get from 11am to 9am after the conversion.
How can I do this if I want to keep the "dd/MM/yyyy HH:mm:ss" format ?
Answer: You should add a couple of DateTimeStyles (in the System.Globalization namespace) flags as the 4th parameter.
By default the resulting DateTime will have an Unsepcified DateTimeKind therefore adjustments between local and UTC will fail. - DateTimeStyles.AssumeLocal will  make sure that DateTimeKind.Local is set.
The DateTimeStyles.AdjustToUniversal flag will also perform the conversion between DateTimeKind.Local and DateTimeKind.UTC
var tmp = DateTime.ParseExact("28/07/2022 10:51:25", "dd/MM/yyyy HH:mm:ss", null,
    DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal);

Comment: Ok, i have to check what's going on.
Thank you for your time and awnsers !
Comment: `ParseExact` is surprisingly powerful. Nice!
Comment: Thank you for your reply, I understand better now why the conversion was not working, my DateTime is not set as Local Time so it can't convert to UTC , but the conversion is still not taking place after adding the "DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal" as 4th parameter.
I aslo tried just the ""DateTimeStyles.AssumeLocal" and then do a ".ToUniversalTime()" but it doesn't seem to work either.
Comment: Can you be more specific about _"is still not taking place"_ and _"it doesn't seem to work either"_
Comment: Yes, the date is still the same : "DateTime.ParseExact("28/07/2022 10:51:25", "dd/MM/yyyy HH:mm:ss", null)" returns the same value as "DateTime.ParseExact("28/07/2022 10:51:25", "dd/MM/yyyy HH:mm:ss", null, DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal)" They both return 28/07/2022 10:51:25
Comment: Weird, it works fine here at UTC+1. How are you testing/running the code? Does that machine think it's in a UTC+2 timezone?
Comment: Yes the machine executing my code is in UTC+2 timezone. But my goal is to come back to UTC.
My goal :
(UTC+2) 28/07/2022 10:51:25  =>  (UTC) 28/07/2022 08:51:25
Comment: If I run this at UTC+1 I get `28/07/2022 09:51:25` and it adjusts correctly, must be something else going on!
Comment: What do you get with `TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now)`?
Comment: I get TimeZone = 00:00:00
Comment: Then, for whatever reason, your code thinks the local timezone is currently equivalent to UTC. That is why you're not seeing a change. Time to check a few assumptions.

DateTime.ParseExact to UTC value


gzip not working on nginx for JSON responses

Question: I'm trying to figure out why my JSON responses are not being gzip'ed. In my main ngninx.conf, I have:
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types    text/plain application/javascript application/x-javascript text/javascript text/xml text/css text/html application/json  application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;

Then in my script I a printing out the content type as:
print $IN->header( 'application/json' );

which converts to:
Content-Type: application/json \n\n

I see the correct content-type there, it's its not compressed:
curl -H "Accept-Encoding: gzip" -I 'https://www.example.com/cgi-bin/links/spots_load_new.cgi?catid=9&linkid=0&t=luna'
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 07 Dec 2017 10:18:58 GMT
Content-Type: application/json
Connection: keep-alive
Keep-Alive: timeout=60
Access-Control-Allow-Origin: *

If I test it on a JS file, it works fine:
curl -H "Accept-Encoding: gzip" -I http://www.example.com/new_design/categories25.min.js
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 07 Dec 2017 10:23:54 GMT
Content-Type: application/javascript
Last-Modified: Wed, 27 Sep 2017 14:21:09 GMT
Connection: keep-alive
Keep-Alive: timeout=60
Vary: Accept-Encoding
ETag: W/"59cbb3d5-323e"
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Content-Encoding: gzip

What am I missing? (I have rebooted nginx, FWIW :))
UPDATE: Just to make it as simple as possible - I have created a test.json file (valid contents), and it still comes back as non-gzipped:
curl -H "Accept-Encoding: gzip" -I https://www.example.com/new_design/test.json
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 07 Dec 2017 17:58:25 GMT
Content-Type: application/json
Content-Length: 245
Last-Modified: Thu, 07 Dec 2017 17:55:58 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "5a2980ae-f5"
Accept-Ranges: bytes

Comment: Where did that extra whitespace come from?
Comment: @MichaelHampton what extra space? I also just figured it out. The file size in question was smaller than what I had set as `gzip_min_length` ... duh!
Comment: There are a couple of places where `application/json ` has an extra whitespace after it.
Answer: Ah man - I can't believe how dumb this is!!!
The data in question was 245 bytes:
Content-Length: 245

...and I had this set:
gzip_min_length 256k set. I've changed it to:
gzip_min_length 128;

and it works fine now. ARGH!


Why are two identical lines in this context here non-parallel?

Question: I came across this question on Linear Algebra: concepts and techniques on euclidean spaces (second edition)

This is the answer given for the question:

I do not understand why did they mention x + y - z =1 twice and state that they are two non-parallel line? With my understanding, shouldn't two identical line be parallel to each other?
Comment: Maybe it is a misprint for "$x+y-z=1$ and $x-2y+z=0$ are two non-parallel planes..."
Comment: Looks like a typo and that they mean to refer to the two components of B. There evidently isn't a lot of care put into the answer key, as $x+y-z=1$ doesn't describe a line in the first place, it describes a plane.
Answer: It's just a copy-paste misprint. It should read:

Since $x+y-z=1$ and $x-2y+z=0$ are two non-parallel planes, $\ldots$
Comment: It should read two non-parallel *planes* - neither of those equations represent a line.
Comment: Thank you @NuclearHoagie. Corrected.


Iterating ListView in parent Activity returns null

Question: I have a list view and the list contains 2 items, a TextView and a Button/EditText based on some logic as as 2 columns in a table row.
Now in the layout, where I have listview, I also have some button say Save. When I click Save, I should retrieve the values of Button/EditText in the Activity where Listview is residing and need to store them in db.
I am not able to figure out this situation. There could be many list rows, say if there are 5 list rows, then need to retrieve each of the values from the positions 0-4.
Please see the screenshot below to know how the list view looks.
Hope you can see the fields on the right side there. Next to COmments is the Edit text and next to Ship Date is a button.
Can anybody please help me or suggest me something?

Update:
I am now iterating the list view as below,
<code>    View vr;
    EditText ee;
    for (int i=0;i<=list.getLastVisiblePosition()-list.getFirstVisiblePosition();i++) {
        //vr = list.getChildAt(i);
        vr = list.getAdapter().getView(i, null, null);
        ee = (EditText) vr.findViewById(i);
        System.out.println(ee.getText().toString());
    }
</code>
Edittext ee is always null in this case. I have tried uncommenting vr = list.getChildAt(i); But still it returns null.
Here there can be either Edittext ee or some other button in the same i position based on some requirement. But I'm not understanding why ee is null.
Referred the answer here Iterate through ListView and get EditText-Field values.
Any thoughts where I am going wrong?
Answer: You can do this by storing  the button/edittext text in your custom list adapter as a list. A OnFocusChangeListener or a TextWatcher can be added on the EditText view to update the list in the adapter. The link below will get you started.
EditText in Listview
Answer: What I understand from your requirement is, you want to store the values from the TexViews on your List rows to db. And you want to do that on the tap of the button 'Save' which is on the main Activity which has the ListView.
Well you may define an ArrayList on your main activity
<code>List<Integer> listOfDataFromTVsOnList = new ArrayList<Integer>();
</code>
And then on Change/Focus listener of your TextView which is a part of the List row, you may assign the value of TextBox in question to the ArrayList we defined on the Main activity as:
<code>((YourMainActivityClass) contextPassedToTheListAdapdter).listOfDataFromTVsOnList.add("Data on the TextView of the Row");
</code>
This way when all the rows are finished editing (this actually depends on your business logic) the ArrayList would have the entire data set from the TextViews from all the rows of your List. Now on the tap of the save button you can iterate over listOfDataFromTVsOnList and save the data as individual records in the db.
Comment: yes what you understood about my requirements is perfect!! But here I cannot assume that there will be only TextView. It can be either a Button/EditText
Comment: so you mean to say, When I tap on Save all the data will be available in listOfDataFromTVsOnList? I will try this
Comment: Yes, it can be any type of control as long as your are using the proper event to get the data from it, in fact I had EditText in mind when I answered your the question but referred to TextView (focus listeners won't help there) wrongly.
Comment: I'm confused where to perform this? ((YourMainActivityClass) contextPassedToTheListAdapdter).listOfDataFromTVsOnList.add("Data on the TextView of the Row"); in List Adapter or Activity? I guess it should be in adapter
Comment: Obviously on the adapter, use the focus listener of the EditView and store the value from it to the ListArray.
Comment: Ok, I guess list listOfDataFromTVsOnList should be of String, right?
Comment: Yes, List listOfDataFromTVsOnList = new ArrayList();

I quickly used one example from my code base!
Comment: No, problem. I wanted to confirm, datz it :)
Comment: I have one problem here, the list need not contain data in the same order as the items are placed in the list right? I want them to be in the sequential order as they are sorted in the listview.
Comment: This is tricky for edittext field. Because unless normal button/other field. I cannot get values of edittext and set it to the List using setonclicklistener. Each time you click a edittext, it will be an empty string. SO if i add this, list has only empty strings at the end