text:
Q: Todo List App in React Error: no-unused-expressions So I am trying to make a To-Do-List App in ReactJS but I got an error:

/src/todoList.js   Line 40:21:  Expected an assignment or function
call and instead saw an expression  no-unused-expressions.

I am storing all the tasks in the state of Todolist and using a .map() which returns another component called TodoItem. I am pretty new to the react environment and have been not able to figure out the error myself.
import React from 'react';
import TodoItem from './components/todoItem';

class TodoList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            todos: [
                {
                    id: 1,
                    title: 'Take out the trash',
                    completed: false
                },
                {
                    id: 2,
                    title: 'Clean the room',
                    completed: false
                },
                {
                    id: 3,
                    title: 'Wash the dishes',
                    completed: false
                },
            ]
        }
    }

    render() {
       const todos = this.state.todos;

            return (

                   todos.map((todo) => {
                    //console.log(todo);
                    <TodoItem todo = {todo} />
                    })

            )

    }
}

export default TodoList;

The TodoItem Component.
It is a separate component for each item of the Todo list.
import React from 'react';

class TodoItem extends React.Component {

    render() {
        console.log(this.props);
        return (
            <h3>{this.props.todo.title}</h3>
        )
    }
}

export default TodoItem;

A: The problem is here:
return (

                   todos.map((todo) => {
                    //console.log(todo);
                    <TodoItem todo = {todo} />
                    })

Should be:
return (<>{todos.map((todo) => <TodoItem todo = {todo} />)}</>)

A: *

*you do well just a tiny mistake happened in the map method you didn't return any thing so it gave you a warning that there is nothing to render so the solution is this:

import React from 'react';
import TodoItem from './components/todoItem';

class TodoList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            todos: [
                {
                    id: 1,
                    title: 'Take out the trash',
                    completed: false
                },
                {
                    id: 2,
                    title: 'Clean the room',
                    completed: false
                },
                {
                    id: 3,
                    title: 'Wash the dishes',
                    completed: false
                },
            ]
        }
    }

    render() {
       const todos = this.state.todos;

            return (

                   todos.map((todo) => {
                    //console.log(todo);
                    return <TodoItem todo = {todo} />
                    })

            )

    }
}

export default TodoList;

A: You should use () instead of {} in the map function like this:
 return (
      todos.map((todo) => (
          <TodoItem todo = {todo} />
      ))

  )

Or add return statement if you want to use curly brackets like this:
return (
      todos.map((todo) => {
          return <TodoItem todo = {todo} />
      })

  )


text:
Q: Can you use operators to define the size of an array in C? Right now I'm trying to write a program, and one part of the it involves expanding an existing array by copying values from a previous array into an array with a larger size.
The way I'm doing this by using an int variable which is defined in a previous point int the program by user input.
int[x] array;

int[x + 1] array2;

Will this work, or do I have to initialize a separate int variable with value of x + 1?

A: The correct syntax is:
int array[x];
int array2[x+1];

C 1999 and later supports this (with the value of x determined at run time), although it is optional in C 2011. Some compilers (of questionable quality) do not support it.
The space available for objects of this sort is typically limited to one to eight mebibytes or so, and that space must also serve for other program needs, so it should be used only for small arrays.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pyodbc Error "A TVP's rows must be Sequence objects.", 'HY000' I am calling an API and moving the data from json to sql. When I try to post to sql I get this error:
Pyodbc Error "A TVP's rows must be Sequence objects.", 'HY000'
Here is my SQL Statement in python:
conn =  pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};Server=' + server+ ';Database=' +
database + ';Trusted_Connection=yes')
cursor = conn.cursor()

for row in range(4):
    cursor.execute('''

          INSERT INTO [dbo].[IndustryCode] (id,name,billingAddress,frontOfficeId,link,isArchived,representativeUsers,statusId,status,industry,
                createdDate,lastUpdatedDate,lastActivityDate,latestActivityName,openJobs,street1,street2,city,stateOrProvince,postalCode,country,
                    county,geoCode,schoolDistrictCode,source)
            VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ''',
            (
            field1,     #id
            field2,     #name
            field3,     #billingAddress
            field4,     #frontOfficeId
            field5,     #link
            field6,     #isArchived
            field7,     #representativeUsers
            field8,     #statusId
            field9,     #status
            field10,    #industry
            field11,    #createdDate
            field12,    #lastUpdatedDate
            field13,    #lastActivityDate
            field14,    #latestActivityName
            field15,    #openJobs
            field16,    #street1
            field17,    #street2
            field18,    #city
            field19,    #stateOrProvince
            field20,    #postalCode
            field21,    #country
            field22,    #county
            field23,    #geoCode
            field24,    #schoolDistrictCode
            'PL1'     #source
            )
        )

    cursor.commit()

I am converting my data from json to a dataframe and from there, I am inputting it into sql.
Here is a sample of my input from my dataframe:
            field1  = df_t['id'].values[0]
            field2  = df_t['name'].values[0]
            field3  = df_t['billingAddress'].values[0]
            field4  = df_t['frontOfficeId'].values[0]
            field5  = df_t['link'].values[0]
            field6  = df_t['isArchived'].values[0]
            field7  = df_t['representativeUsers'].values[0]
            field8  = df_t['statusId'].values[0]
            field9  = df_t['status'].values[0]
            field10 = df_t['industry'].values[0]
            field11 = df_t['createdDate'].values[0]
            field12 = df_t['lastUpdatedDate'].values[0]
            field13 = df_t['latestActivityDate'].values[0]
            field14 = df_t['latestActivityName'].values[0]
            field15 = df_t['openJobs'].values[0]
            field16 = df_t['street1'].values[0]
            field17 = df_t['street2'].values[0]
            field18 = df_t['city'].values[0]
            field19 = df_t['state_Province'].values[0]
            field20 = df_t['postalCode'].values[0]
            field21 = df_t['country'].values[0]
            field22 = df_t['county'].values[0]
            field23 = df_t['geoCode'].values[0]
            field24 = df_t['schoolDistrictCode'].values[0]

Field25 is a constant, this is why it is in my sql statement.
Sample of my json:
{'id': 4177713, 'name': '', 'mainAddress': {'street1': None, 'street2': None, 'city': None, 'state_Province': 'AR', 'postalCode': None, 'country': 'US', 'county': None, 'geoCode': None, 'schoolDistrictCode': None}, 'billingAddress': None, 'frontOfficeId': 11259, 'link': 'https://apisite.comPyodbc Error "A TVP's rows must be Sequence objects.", 'HY000'/app/#/company/4177713', 'isArchived': True, 'representativeUsers': [151209], 'statusId': 6492, 'status': 'Delete', 'industry': None, 'createdDate': '2008-04-15T15:28:00', 'lastUpdatedDate': None, 'latestActivityDate': None, 'latestActivityName': None, 'openJobs': 0}

A: Because df_t['representativeUsers'].values[0] has a string with '[]', adding
df_t['representativeUsers'].values[0][0] resolves my issue.


text:
Q: Why can't I use bash freely after using the "At" utility? (Can't insert stdin until ctrl+c) I ran the following code block (an at timeout to uninstall PHPmyadmin). It should be scheduled to run 2 horus ahead, but I ran it in a timeout of 2 minutes, just to test it:
bash /dev/fd/50 50<< PMA_UNINSTALL | at 'now + 2 minutes'

apt-get purge phpmyadmin -y
PMA_UNINSTALL

The at utility seems to prevent me from using Bash freely, unless I do CTRL+C. At also prompts the following warning, which is normal, and hardcoded in the Utility's source code. When I do CTRL+C the warning vanish and I can use Bash regularly again.

commands will be executed using /bin/sh

I don't say that it's the warning that prevents me from using Bash regularly as long it appears. I know the warning is just stdout and something else might prevent me from creating stdin.
What prevents me from creating stdin piping the above code block with at and how could I reach a state when I could execute commands piped with at, but use Bash freely right afterwards without interrupting at to work ?

A: It took me some time to see your real problem - you want to directly send a command to at instead of providing command(s) afterwards as i assumed.
There is no need for a complicated scheme, just type
echo 'apt-get purge phpmyadmin -y' | at 'now + 2 minutes'

When you do it this way at does not expect any input afterwards and you get back to the command line immediately.

(keeping my original answer here)
Issuing at gives you the possibility to list commands to execute. You have to tell at that you are done:
Press CTRL + D (This is also known as End Of Transmisssion)

A: TL;DR: Those commands don't seem to do what you probably intend.
If you're trying to make at execute apt-get purge phpmyadmin -y from bash in 2 minutes, then your code will not do what you want it to do.
The command on the left of the pipe (|) has your here document as its standard input. That command does not even run until the shell has read your complete here document.
From 3.6.6 Here Documents in the Bash Reference Manual:

This type of redirection instructs the shell to read input from the
  current source until a line containing only word (with no trailing
  blanks) is seen. All of the lines read up to that point are then used
  as the standard input (or file descriptor n if n is specified) for
  a command.

A command with a here document is, in effect, just a single command that must be fully read by the shell before it is executed. In your code, the shell reads input until PMA_UNINSTALL appears on a line by itself. Once that has happened, the shell then uses the content of the here document as file descriptor 50 for the command bash /dev/fd/50.
That command does not even start a new instance of bash until the here document has been fully read. When bash does run, it runs this command:
apt-get purge phpmyadmin -y

Since the whole left side of the pipe including the here document has its standard output piped to at, the input at gets is the output of bash, which is the output of apt-get purge phpmyadmin -y. at then attempts to interpret that output--not your apt-get command,  but its output--as a list of commands to execute in /bin/sh.
So this is almost certainly not what you mean to do.
I'm not sure why you don't get a shell prompt back right after entering that code. When I run it on a test machine, I get a shell prompt back in a couple of seconds. If you want to debug this, you can try running apt-get purge phpmyadmin -y interactively in bash. The way your code is written, that command runs completely before at returns to the shell (and before at can schedule anything). It would probably not be useful to debug this particular code further, though.


text:
Q: Javascript: Trouble getting JS to run onclick instead of on pageload I built a dev site for a project I'm working on. The problem is that it seems that the JS is running on pageload instead of onclick. It runs correctly after an address is entered and the submit button is clicked but the previous error still remains. How do I get the JS to only run after submit has been clicked? Here is the code:

/**
 * Build and execute request to look up voter info for provided address.
 * @param {string} address Address for which to fetch voter info.
 * @param {function(Object)} callback Function which takes the
 *     response object as a parameter.
 */
var userSubmitJS = document.querySelector('#userSubmit');
var userInputJS = document.querySelector('#userInput');
var address;
userSubmitJS.addEventListener('click', function(event) {
  event.preventDefault();
  address = userInputJS.value;
  lookup(address, renderResults);
});

function lookup(address, callback) {
  /**
   * Election ID for which to fetch voter info.
   * @type {number}
   */
  var electionId;
  /**
   * Request object for given parameters.
   * @type {gapi.client.HttpRequest}
   */
  var req = gapi.client.request({
    'path': '/civicinfo/v2/voterinfo',
    'params': {
      'electionId': electionId,
      'address': address
    }
  });
  req.execute(callback);
}

/**
 * Render results in the DOM.
 * @param {Object} response Response object returned by the API.
 * @param {Object} rawResponse Raw response from the API.
 **/
function renderResults(response, rawResponse) {
  var getResults = document.getElementById('results');
  var para = document.createElement("p");
  var bold = document.createElement('strong');
  if (!response || response.error) {
    getResults.appendChild(document.createTextNode(
      'Error while trying to fetch polling location.'));
    return;
  }
  var normalizedAddress = response.normalizedInput.line1 + ' ' +
    response.normalizedInput.city + ', ' +
    response.normalizedInput.state + ' ' +
    response.normalizedInput.zip;
  if (response.pollingLocations.length > 0) {
    var pollingLocation = response.pollingLocations[0].address;
    var pollingLocationName = pollingLocation.locationName;
    var pollingAddress = pollingLocation.line1 + ' ' +
      pollingLocation.city + ', ' +
      pollingLocation.state + ' ' +
      pollingLocation.zip;
    getResults.appendChild(document.createTextNode("The closest polling location near you is: "));
    bold.appendChild(document.createTextNode(pollingLocationName + ' '));
    getResults.appendChild(bold);
    getResults.appendChild(document.createTextNode(pollingAddress));
    var getDirections = "Get Directions";
    var getDLink = getDirections.link("https://www.google.com/maps/search/" + pollingAddress);
    document.getElementById("directions").innerHTML = getDLink;
  } else {
    getResults.appendChild(document.createTextNode(
      'Could not find polling location near ' + normalizedAddress + '. Please try again.'));
  }
}

function load() {
  gapi.client.setApiKey('XXX');
  lookup('', renderResults);
}
<!DOCTYPE html>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

Places to Vote

Find a polling location near you.

        <form>

              <input id="userInput" type="text" class="form-control form-control-lg" placeholder="100 Example Ave Austin Texas">

              <button id="userSubmit" type="submit" class="btn btn-block btn-lg btn-primary">Submit</button>

        </form>


text:
Q: mysql database many to many relation confusion I have 4 tables
hubs | countries | categories | news
here hubs and countries have many to many relation
country_hub
id
hub_id
country_id

and then this pivot table country_hub has many to many relation with categories so I did like
category_country_hub
id
country_hub_id
category_id

and again this table has many to many relation with news table
category_country_hub_news
category_country_hub_id
news_id

this is giving me a complicate relation to query
so I am thinking of modifying the relation like
country_hub
country_id
hub_id

category_country_hub
country_id
hub_id
category_id

category_country_hub_news
hub_id
country_id
category_id
news_id

which is one to many relation with hubs/countries/ categories
is there any better way to handle these kind of relation please help or any tutorials links

A: Ok, clear now.  Expanded comments below, here is the summary:
tl;dr:
1) your revised approach makes more sense to me.
2) your naming conventions could use some polish, will improve readability for humans (specifically the 'tokens' in table names matching order of columns in table, fwiw the database itself won't care).
3) book: I will recommend "SQL for Smarties" (Celko), which goes into some of the modeling issues you're dealing with.
http://www.amazon.com/Joe-Celkos-Smarties-Fourth-Edition/dp/0123820227
Let's dig into the table definitions... I can't reason well from a text summary, my brain works better if I can see examples.
Let me know if the examples are (more or less) suitable.
raw data tables
Seems ok to call these fact tables.
|-----------------|---------------|---------------|--------------------|
| select * from   | select * from | select * from | select * from      |
| COUNTRIES       | HUBS          | CATEGORIES    | NEWS               |
|-----------------|---------------|---------------|--------------------|
|  id :   name    |   id : name   |  id : name    |    id :   title    |
| --- : --------- |  --- : -----  | --- : ------- |  ---- : -----------|
| 101 : China     |  201 : X      | 301 : Red     |   401 : 'aa aaaa a'|
| 102 : Nepal     |  202 : Y      | 302 : Blue    |   402 : 'bbbb b bb'|
| 103 : Australia |  203 : Z      | 303 : Green   |   403 : 'cc ccc cc'|
| 104 : NewZealand|  ...etc...    | 304 : Orange  |   404 : 'ddddd d'  |
|   ...etc...     |               | ...etc...     |   405 : 'ee eeee'  |
|-----------------|---------------|---------------|--------------------|

original relation tables
Observation: These are not really dimension tables, I don't see an obvious hierarchy here.
Let's carry this out a little further.
  |-----------------------|---------------------------|--------------------------|
  | select * from         | select * from             | select * from            |
  | COUNTRY_HUB           | CATEGORY_COUNTRY_HUB      | CATEGORY_COUNTRY_HUB_NEWS|
  |-----------------------|---------------------------|--------------------------|
  |     :        : country|    : country  :  category |        cat_cnt  : news   |
  |  id : hub_id : _id    | id :  _hub_id :  _id      |  id  : _hub_id  : _id    |
  |---- : ------ : -------|----: -------- : ----------| ---- : -------- : ------ |
  |  11 :    101 :  201   | 21 :     11   :   301     |  31  :    21    :   401  |
  |  12 :    101 :  202   | 22 :     11   :   303     |  32  :    21    :   403  |
  |  13 :    101 :  203   | 23 :     12   :   302     |  33  :    21    :   404  |
  |  14 :    102 :  200   | 24 :     12   :   304     |  34  :    22    :   405  |
  | ...etc...             | ...etc...                 |  ...etc...               |
  |-----------------------|---------------------------|--------------------------|

Yes, this is starting to look complicated. :-)
observation: If you were going to stay with the approach, I think  it could be a little easier if you
follow a naming convention embedding the Raw Data tables last:
 Original tbl names         |    Notes
----------------------------|------------------------------------------------------
COUNTRY_HUB                 | Two raw-data id#'s (hub_id & country_id)s
----------------------------|------------------------------------------------------
CATEGORY_COUNTRY_HUB        | One raw data id#, last column (category_id), but CATEGORY_... first
                            | token in the table name.
                            | I will suggest COUNTRY_HUB_CATEGORY would be easier to read
                            | for human readers, since both right-most column and right-most token
                            | in the table name tie back to the same concept (the CATEGORY raw data table).
----------------------------|------------------------------------------------------
CATEGORY_COUNTRY_HUB_NEWS   | One raw data id#, last column (news_id), also _NEWS  is last token
                            | in the table name, easier for human readers to parse & follow.
----------------------------|------------------------------------------------------

modified relationship tables
This looks better.
  |-----------------------|-------------------------------|-------------------------------------------|
  | select * from         | select * from                 | select * from                             |
  | COUNTRY_HUB           | CATEGORY_COUNTRY_HUB          | CATEGORY_COUNTRY_HUB_NEWS                 |
  |-----------------------|-------------------------------|-------------------------------------------|
  |     : country: hub    |    : country : hub  : category|      : hub   : country : category : news  |
  |  id : _id    : _id    | id : _id     : _id  :  _id    |  id  : _id   : _id     : _id      : _id   |
  |---- : ------ : -------|----: --------: ---- : --------| ---- : ----- : ------- : -------- : ----- |
  |  11 :    201 :  101   | 21 : 201     :  101 :  301    |  31  :  101  :    201  :  301     : 401   |
  |  12 :    202 :  101   | 22 : 201     :  101 :  302    |  32  :  101  :    201  :  301     : 401   |
  |  13 :    203 :  102   | 23 : 201     :  101 :  303    |  33  :  102  :    201  :  301     : 401   |
  |  14 :    204 :  102   | 24 : 201     :  102 :  301    |  34  :  102  :    201  :  301     : 402   |
  | ...etc...             | ...etc...                     |  ...etc...                                |
  |-----------------------|-------------------------------|-------------------------------------------|

About Naming Conventions
The table-name "tokens" still don't follow the column order.
As a favor to yourself and future maintainers, consider changing that:
COUNTRY_HUB is fine.
CATEGORY_COUNTRY_HUB still seems flipped, use COUNTRY_HUB_CATEGORY
CATEGORY_COUNTRY_HUB_NEWS doesn't follow from previous, I would use COUNTRY_HUB_CATEGORY_NEWS and adjust the columns accordingly (though I
don't know enough about your data relationships to comment on what is
the best order).

The thing that you have implicit in your naming is a rough "category"
overly simplistic:
   Each COUNTRY has 0..many HUBS.
   Each HUB has 0..many CATEGORIES.
   Each CATEGORY  has 0..many NEWS items.

I'll suggest you work on making your table-name "tokens" match the "column order".
You seem to have (in order of few to many):
COUNTRY  : COUNTRIES (relatively few)
HUB      : HUBS (# of HUBS greater than # of COUNTRIES)
CATEGORY : Assigned CATEGORIES (# of COUNTRY+HUB+CATEGORY combinations exceeds # of previous)
NEWS     : Assigned NEWS items (# of COUNTRY+HUB+CATEGORY+ combinations exceeds # of previous)

Let's do a little data modeling and describe the relationships...
COUNTRY <*----*> HUB
   Each COUNTRY has 0..many HUBS.
   A given HUB may be associated w/multiple COUNTRIES.

HUB ----*> CATEGORY
or..?
COUNTRY + HUB <*----*> CATEGORY
   Your tables suggest CATEGORIES do not simply associate directly with a given HUB.
   Consider HUB.id=101 name='X'
      X.China.categories = ( Blue, Yellow );
      X.Nepal.categories = ( Orange, Green );
      X.Australlia.categories = ( ); e.g. none.

   Instead of all countries associated with that HUB sharing the same "HUB CATEGORIES",
   it sounds like the CATEGORIES are like "tags" and that the various countries involved
   with a given HUB can have their collection of 0..many CATEGORIES.
   It seems weird, but I don't know your data.
   In the interests of simplifying I would try to make CATEGORIES be HUB-specific, not
   HUB+COUNTRY specific... but that may be unavoidable for you.

COUNTY + HUB + CATEGORY <*----*> NEWS
   This suggests that a given NEWS item can be associated with 2+ (COUNTRY+HUB+CATEGORY) triples.
   If that is what you need, then it can't be avoided.

You're going to have a challenge keeping all of the relationships up to date.
You will want to study up on foreign key constraints and cascading deletes.
I did greatly enjoy this book: SQL for Smarties (Celko), which goes into some of the modeling issues you're dealing with.
Splitting them out the way you are has the advantage of avoiding some anomalies (one of the examples Celko uses involved class scheduling at a school: teachers, classes, rooms, students and the relationships between them).  I will recommend the book, I think it reads well.


text:
Q: Overwrite if newer : SCP folder transfer WinSCP has a great feature that only copies newer versions of files when you transfer between hosts.  For whatever reason, I'm not able to connect to my remote host via WinSCP so I must use SSH.  I don't want to overwrite ever file in the target folder, only the new ones. Does this happen automatically?
Additionally, for the protocol: scp -r [/path/filename][login@ipaddress]:. what is the home directory of the filename path? Is it simply C drive? I know I can write the full path but I'm just curious.

A: If your priority is to overwrite with newer copies, I recommend rsync.
cwRsync is a version you can use with Windows: http://www.rsync.net/resources/howto/windows_rsync.html

A: I think you have a lot of misguided thoughts here.
First... Winscp uses native ssh to copy files.  It does nothing different than the linux command scp.  There is no way scp will work... when winscp does not.  winscp is a windows interface that uses a basic scp client to connect to a ssh server to copy files.
Second... In Linux-based OSes, there is no concept of a "C drive".  You have the root (/) and directories under root.  A block device is mounted to root, and various other block devices can be mounted to directories that fall under root.
The syntax for "scp" is as follows:
scp from_where to_where

Both the from and to can be local directories like /some/local/directory or a remote directory like user@some.server:/some/remote/directory
the -r just means to "recurse" directories. (copy everything from that directory and everything beneath it.)
in a windows environment with a "C drive"  typically you'd use putty's pscp command and do something like this:
pscp -r c:\some\directory username@some.server:/some/path/to/where/you/want/it


text:
Q: unable to load Grid-Gain cache configuration file I am trying to start grid-gain by bin\ignite.bat examples\config\example-cache.xml
Also I have set JAV_HOME and GRIDGAIN_HOME PATH
To start gridgain I am using below code
Grid g = GridGain.start("/C:/Grid-Gain/ignite-fabric-1.0.0-RC1/ignite-fabric-1.0.0-RC1/examples/config/example-cache.xml");

I also tried with partial path
Grid g = GridGain.start("examples/config/example-cache.xml");

but all the time it is throwing exception

Exception in thread "main" class org.gridgain.grid.GridException: Failed to find grid configuration in: file:/C:/Grid-Gain/ignite-fabric-1.0.0-RC1/ignite-fabric-1.0.0-RC1/examples/config/example-cache.xml

All the time it shows this error.

A: You are using GridGain and Ignite interchangeably, while you probably want to use Apache Ignite only. GridGain is an enterprise product sitting on top of the Apache Ignite.
Please take a look at Apache Ignite Getting Started guide and the rest of the documentation. There is also a community forum there where you can ask questions.


text:
Q: Replacing Nginx with Traefik caused Django to use admin files via HTTP instead of HTTPS, breaking functionality I had a perfectly fine Django CMS 3.4.1 setup running behind Nginx as an edge-server with SSL termination. The complete chain was:
nginx (SSL) → nginx (django server) → gunicorn → django
All I did was to replace the first nginx reverse proxy with traefik, for a better integration of other services. Everything is run with docker (compose)
The issue is, that Django now wants to redirect HTTPS calls to admin files (and ajax calls) to HTTP, breaking functionality because those files are blocked by the browser.
I did not change anything with the django installation. In fact, it even is the same docker image as before.
Because it did work with the old setup, I don't think that it is an issue with the Django CMS code using hardcoded http://. SSL was terminated before the django reverse proxy, as well.
Does anyone see something I am missing?
Here are some configuration files, from top to bottom:
traefic.yml:
global:
  sendAnonymousUsage: false

api:
  dashboard: true
  insecure: true

providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    watch: true
    exposedByDefault: false

log:
  level: INFO
  format: common

entryPoints:
  http:
    address: ":80"
    http:
      redirections:
        entryPoint:
          to: https
          scheme: https
  https:
    address: ":443"

certificatesResolvers:
  letsencrypt:
    acme:
      email: ***
      storage: /etc/acme/acme.json
      httpChallenge:
        entryPoint: http

relevant parts of django-server docker-compose file:
# ...
services:

  cms-nginx:
    build: "./nginx"
    depends_on:
      - postgres
    networks:
      - proxy
      - cms
    volumes:
      - cms_static:/usr/src/app/static
      - cms_media:/usr/src/app/media
    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=proxy"
      - "traefik.http.routers.cms.rule=Host(`***`)"
      - "traefik.http.routers.cms.tls=true"
      - "traefik.http.routers.cms.tls.certresolver=letsencrypt"

  cms:
    restart: always
    build: ./cms
    links:
      - postgres:postgres
      - static:static
    expose:
      - "8000"
    volumes:
      - ./cms:/usr/src/app
      - static_out:/usr/src/app/data/generated
      - cms_static:/usr/src/app/data/static
      - cms_media:/usr/src/app/data/media
    depends_on:
      - static
    env_file:
      - .env
      - ./cms/.env
    command: /bin/sh -c "./docker-init.sh"
    networks:
      - cms

django server nginx conf:
server {

    listen 80;
    server_name *** default_server;
    charset utf-8;

    client_max_body_size 75M;

    location ^~ /static/ {
        alias /usr/src/app/static/;
    }

    location ^~ /media/ {
        alias /usr/src/app/media/;
    }

    location / {
        proxy_pass http://cms:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Protocol $scheme;
    }

    error_log /var/log/nginx/deckel_error.log;
}

gunicorn start command:
/usr/local/bin/gunicorn cms.wsgi:application -w 2 -b :8000

django settings part:
SESSION_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True


text:
Q: Spacing issue with literate in listings I answered this question and OP showed me a problem with the answer. The code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\lstset{
  % keepspaces, % Apparently this works...
  literate=
    {à}{{\`a}}1
}

\begin{document}

\begin{lstlisting}[mathescape=true]
  Adicionar v à lista.
  Adicionar $v$ à lista.
  Adicionar $v$ onde?
  R: à lista.
  Yoda style: à lista, $v$ adicionar.
  Adicionar $v$ à lista e à outra lista.
\end{lstlisting}

\end{document}

prints:

and the space after the à is eaten.
From the four examples above, I concluded that the problem is isolated at the first literated character in lines after mathescaped text.

*

*The second and sixth lines show the issue.

*The fourth line shows that the effect from the third line stops after the line break.

*The fifth line shows that the effect starts only after the mathescaped text

*The sixth line shows that the problem does not propagate to the following literated characters.

Using the keepspaces option apparently solves the problem.
From the look of it I think it's a bug. How to fix this?

I also concluded that v was definitely added to the list :)

A: (August 12, 2018—it's Sunday and I don't have the nerve for delving deeply into the source code of the listings package.)
But when skimming over that source code, I got the impression that

*

*the macro underlying the replacement-process for the things provided via the literate key is called \lst@Literate.

*there is a switch \lst@ifwhitespace which indicates whether the last processed thingie has been a space which has been printed as a whitespace.

*the code of \lst@Escape—\lst@Escape seems to underlie all those thingies for escaping to LaTeX—does set that switch to false in case of being used due to mathescape being true. So with mathescape=true the switch is false after $...$. This leads to processing the space following $...$ as whitespace which is not to be discarded but to be printed. This processing of the next space in turn leads to setting the switch to true again. Now the literate-thingie is processed. The underlying macro \lst@Literate does not set the switch to false. Thus due to the space before the literate-thingie being processesd as printed whitespace, the "machinery" after processing the literate-thingie still "thinks" that it has just processed and printed a whitespace and thus should discard following spaces.
This "thinking" of the machinery seems wrong in cases where the literate-thingie did as last item of output produce something other than whitespace .
What can be done about this?
Perhaps \lst@Literate should be redefined to set that switch to false.
Could look like this:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\lstset{
  literate=
    {à}{{\`a}}1
}

\makeatletter
\def\lst@Literate#1#2#3{%
    \ifx\relax#2\@empty\else
        \lst@CArgX #1\relax\lst@CDef
            {}
            {\let\lst@next\@empty
             \lst@ifxliterate
                \lst@ifmode \let\lst@next\lst@CArgEmpty \fi
             \fi
             \ifx\lst@next\@empty
                 \ifx\lst@OutputBox\@gobble\else
                   \lst@XPrintToken \let\lst@scanmode\lst@scan@m
                   \lst@token{#2}\lst@length#3\relax
                   \lst@XPrintToken
                   \lst@whitespacefalse %!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                 \fi
                 \let\lst@next\lst@CArgEmptyGobble
             \fi
             \lst@next}%
            \@empty
        \expandafter\lst@Literate
    \fi}
\makeatother

\begin{document}

\begin{lstlisting}[mathescape=true]
  Adicionar v à lista.
  Adicionar $v$ à lista.
  Adicionar $v$ onde?
  R: à lista.
  Yoda style: à lista, $v$ adicionar.
  Adicionar $v$ à lista e à outra lista.
\end{lstlisting}

\end{document}

(Addition in August 18, 2018—it's Saturday and I still don't have the nerve for delving deeply into the source code of the listings package. ;-)  )
But when doing so, we loose the possibility of having the literate-mechanism produce material whereafter a following space-token does not lead to producing more whitespace.
Thus perhaps it is better to just set the \lst@whitespace-switch to false within the literate-directive whenever that directive is used for having LaTeX typeset non-whitespace.
Could look like this:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\makeatletter
\lstset{
  literate=
    {à}{{\`a\lst@whitespacefalse}}1
}
\makeatother

\begin{document}

\begin{lstlisting}[mathescape=true]
  Adicionar v à lista.
  Adicionar $v$ à lista.
  Adicionar $v$ onde?
  R: à lista.
  Yoda style: à lista, $v$ adicionar.
  Adicionar $v$ à lista e à outra lista.
\end{lstlisting}

\end{document}

I can absolutely not guarantee that my analysis of the situation is correct.
Maybe it is a starting point.
Seems that things work out correctly when

*

*either adding \lst@whitespacefalse to the definition of \lst@Literate

*or applying \lst@whitespacefalse inside the literate-directive.
Again: I can absolutely not guarantee that my analysis of the situation is correct.
Maybe it is a starting point.
In case setting \lst@whitespacefalse inside the literate-directive is to be considered good practice, both this should be mentioned somewhere in the manual, and for the end-user there should be a possibility of setting that switch without using \makeatletter..\makeatother beforehand.
In case you come to the same conclusion, feel free to hand in a bug report.  ;-)


text:
Q: Angularjs1.x Directive Prelink/Postlink/link function difference? I was trying to understand the angularjs directive prelink/postlink function in many tutorial, but not able to identify whether the normal link function , is it equivalent to a pre link or a post link function.
(1)

link : function(scope element, attrs) {

}

(2)

pre : function(scope element, attrs) {

}

(3)

post : function(scope element, attrs) {

}

"Is (1) equal to (2) || (1) equal to (3)" ??

A: After going through so many blogs and tutorials , finally got my answer here
For AngularJs, the link function is a post-link function. So in general we can write the post-link function in two ways:
(1) using object literal notation which has a post method link:
  link:{ post:function(scope,elem,attr)
    {
      // .....
    }
   }

(2) Simply set the link method.
link: function(scope,elem,attr){
       // ...
      }


text:
Q: How to open a BottomNavigationView menu item in an activity I have an activity, it has a button that I need to take the user to the main activity in the specific menu item
Activity

when you click cancel it needs to go here in the item "cobrar"

MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }
}

Click event
btnCancelar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getBaseContext(), MainActivity.class));
            }
        });

A: I solved this problem by simply adding finish();
btnCancelar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               finish();
                //startActivity(new Intent(getBaseContext(), MainActivity.class));
            }
        });

He automatically went back to where he was, which for now solves my problem


text:
Q: Conexão Python com SQL Anywhere 16 falha Olá!
Estou tentando conectar o Python com um banco de dados do Sybase mas todas as formas que eu tento, acaba dando esse erro.

Traceback (most recent call last):   File
  "C:\Users\yuri.mendonca\AppData\Local\Programs\Python\Python35\Scripts\dominio_connection.py",
  line 2, in
      conn = pyodbc.connect('Driver={SQL Anywhere 16};' pyodbc.OperationalError: ('08001', '[08001] [Sybase][ODBC Driver][SQL
  Anywhere]Database server not found (-100) (SQLDriverConnect)')

Meu código está como:
import pyodbc  conn = pyodbc.connect('Driver={SQL Anywhere 16};'
                      'Server=***.**.**.***;'
                      'Database=*********;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor() cursor.execute('select...')

for row in cursor:
    print(row)

Já utilizei o mesmo código pra conectar em um banco de dados do SQL Server e consegui sem problemas, pra conectar com um banco de dados SQL Anywhere não está indo.
Alguma sugestão?


text:
Q: error with basic java code This is some basic java code:
package javaapplication32;

import java.io.*;

public class JavaApplication32 {
    public static void main(String[] args)throws Exception {
        try{
            out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("dec.dat")));
            in = new DataInputStream(new BufferedInputStream(new FileInputStream("enc.dat")));

            String enc=in.readUTF();
            System.out.println(enc);
        }catch(EOFException e){
        }
    }
}

I am getting the error that it cannot find the symbol 'in' or 'out'

A: You should declare them first.
public static void main(String[] args)throws Exception {
    DataOutputStream out = null;
    DataInputStream in = null;
    try{
        out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("dec.dat")));
        in = new DataInputStream(new BufferedInputStream(new FileInputStream("enc.dat")));

        String enc=in.readUTF();
        System.out.println(enc);
    }catch(EOFException e){
    }
}

A: In order to define variables you must give them types, e.g.:
OutpustStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("dec.dat")));
InputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("enc.dat")));

A: You have not actually declared anything as in or out.
DataInputStream in =
DataOutputStream out =

A: This should work.
package javaapplication32;
import java.io.*;

public class JavaApplication32 {
    public static void main(String[] args)throws Exception {
        try {
            DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("dec.dat")));
            DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("enc.dat")));

            String enc=in.readUTF();
            System.out.println(enc);
        } catch(EOFException e) {
        }
    }
}

A: You need to declare in and out as something first!
DataInputStream in =
DataOutputStream out =
E.g.
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("dec.dat")));
    in = new DataInputStream(new BufferedInputStream(new FileInputStream("enc.dat")));

A: In Java, Pre Initialisation of strings is mandatory. Only then you can use them inside a program. Easiest way to do this is:
String in="";
String out="";

You should be fine...


text:
Q: Blade server backplane wiring Are there any blade server enclosures which have hard wired network lines on the backplane? I want be able to have separate female ethernet connectors for the NIC on every blade server in the enclosure. Because of security reasons they have to be hard wired, so there is no possibility to attack data streams from other blade servers.

A: Blade servers are used in a variety of industries ranging from hyper-secure environments to large scale financial applications. Is there something unique about your requirements that extends beyond what's needed for other critical computing environments?
But let's use the example of an HP C7000 enclosure... The server downlinks are hardwired.

See: Probability of Blade Chassis Failure
I think you're asking whether there's an option for passthrough Ethernet modules to an external network switch on the blade uplink connections. If that's what you're asking, then yes, use a passthrough ethernet module and you'll be able to control the network interconnects on your own. This is available from most blade vendors.


text:
Q: Transport equation problem with boundary condition: $a(x,y)u_x + b(x,y)u_y = -u \ \ \mbox{in} \ \ \overline{\Omega}$. Let $\Omega \subset \mathbb{R}^2$ be the unit disk and $u \in C^1(\overline{\Omega})$ solution of
$$a(x,y)u_x + b(x,y)u_y = -u \ \ \mbox{in} \ \ \overline{\Omega}.$$
If $a(x,y)x + b(x,y)y > 0$, for all $x,y \in \partial \Omega$, show that $u \equiv 0$.
Hint: Show that $\displaystyle\max_{\Omega} u \leq 0$ and $\displaystyle\min_{\Omega} u \geq 0$.


text:
Q: Why does react reconciliation preserve the constant sibilings when order is changed I'm checking react reconciliation. It says that when traversing the children, React will iterate over both lists of children at the same time and generate a mutation whenever there's a difference.
I made a simple example:
class ComponentA extends React.Component {

    state = {
        first: true
    }

    clickHandler = () => {
        this.setState({
            first: !this.state.first
        })
    }

    render() {
        return (

                {this.state.first ? xyz : undefined}

abc

efg

                <button onClick={this.clickHandler}>click me</button>

)
    }
}

On click, the first child (span element) will get in and out of the list of children. From React's point of view, iterating one by one, it should look like all elements have changed. Therefore React should re-render the DOM for all of these 4 children (including button).
But checking the DOM inspector in Firefox and Chrome I see highlight only on the span element, not on all four, meaning the DOM is preserved for the three unchanged elements. Why?

(highlight is not seen on this picture but the span element gets highlighted on button click)

A: React compares element attributes in this case. From the React docs:

DOM Elements Of The Same Type
When comparing two React DOM elements of
the same type, React looks at the attributes of both, keeps the same
underlying DOM node, and only updates the changed attributes. For
example:

This is also the reason why you need to supply a key when you create a list of elements dynamically. If that key is not supplied and the list changes because of prop or state changes, all list items need to be removed and appended.
You may want to read the following article, where this phenomenon is explained more thoroughly. https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
From the article:

Let me explain, a key is the only thing React uses to identify DOM
elements. What happens if you push an item to the list or remove
something in the middle? If the key is same as before React assumes
that the DOM element represents the same component as before. But that
is no longer true.

A: What happens in my example is that the first child (the span) is never really removed from the children array but only toggles between span and undefined. So there are always 4 children and the reorder (index shifting) never happens.
That's why react knows to match the elements and update only span DOM element and leave the other 3 as they are.


text:
Q: rbind.pages with missing pages "Error: all(vapply(pages, is.data.frame, logical(1)))" is not TRUE I am trying to rbind.pages with jsonlite from web where some of the data files are missing(for example values for aa are missing).
temp<- c("6702","1","67")
library(jsonlite)
baseurl <- "https://api.angel.co/1/startups/"
pages <- list()
for(i in 1:3){
  mydata<- fromJSON(paste0(baseurl,temp[[i]]),flatten= TRUE)
 pages[[i+1]] <- mydata
}
out<- rbind.pages(pages[sapply(pages, length)>2])

I am getting the following errors. Any suggestions on how to address this? Thanks.
Error: Error in open.connection(con, "rb") : HTTP error 404.
Error: all(vapply(pages, is.data.frame, logical(1))) is not TRUE

A: rbind.pages doesn't appear to like "empty" lists. You should filter your list to exclude them
out<- rbind.pages(pages[sapply(pages, length)>0])


text:
Q: Limit superior and inferior when one part diverges How can I find the limit superior and inferior of given sequence:
$x_n = (1 + \frac{1}{2n})\cos{\frac{n\pi }{3}}$
as $ n \in \mathbb N $
I did the following: since $\lim_{n\to\infty}(1 + \frac{1}{2n}) = 1$ and the second term' limit oscillates between -1 and 1, I decided that the supremum should be $1$ and infimum should be $-1$.
But this is an incorrect answer.
What I do wrong? Thank you.
UPD:
It is a task from the online-courses site and there is an automatic answer checking system. So, as I said in my question, answer $-1$ and $1$ not passed and there is no explanation why.
I believe there should be used Bolzano–Weierstrass theorem to find all possible convergent subsequences, and then find limits for each of them...

A: We have $\lim_{n\to\infty}(1+\frac{1}{2n}) = 1$ and $0 \le |\cos(x)| \le 1$ for all $x \in \Bbb R$, so
$$\limsup_n \,(1+\frac{1}{2n}) = 1 \text{ and }
\limsup_n \, \left|\cos{\frac{n\pi }{3}} \right| \le 1.$$
Using $\limsup ( a_n b_n ) \leqslant \limsup a_n \limsup b_n$ (with $a_n = 1 + \frac{1}{2n}$ and $b_n = |\cos\frac{n\pi}{3}|$), we have
$$\limsup_n \, (1 + \frac{1}{2n}) \left|\cos{\frac{n\pi }{3}} \right| \le 1,$$
so
$$-1 \le -\limsup_n \, (1 + \frac{1}{2n}) \left|\cos{\frac{n\pi }{3}} \right| \le \liminf_n\, (1 + \frac{1}{2n}) \cos{\frac{n\pi }{3}}.$$
(Recall that $\liminf_n a_n$ can be equivalently defined as the minimum possible limit of subsequence $(a_{n_k})_k$, which is bounded below by $(-|a_{n_k}|)_k$.)

*

*$n = 6k + 3$: $x_n = (1 + \frac{1}{12k + 6})(-1) \to -1$ as $k \to \infty$.

*$n = 6k$: $x_n = (1 + \frac{1}{12k})(1) \to 1$ as $k \to \infty$.

This shows that $\limsup_n x_n = 1$ and $\liminf_n x_n = -1$.

(Edit in response to OP's update)
OP has appealed to his online system that we have no access to to conclude that my answer is wrong.
Here, I'm going to prove that why
$$\limsup_n \,x_n < 1+\epsilon \quad \forall \epsilon > 0.$$
In other words, wny number $1 + \epsilon$ strictly greater than $1$ can't be a limit of any subsequence of $(x_n)_n$.  With the example subsequence $n = 6k$ in the last part of my original answer, this would show that $\limsup_n x_n = 1$.
The idea is simple: $\require{cancel}$
$$x_n = \underbrace{\left( \color{red}{1+\frac{1}{2n}} \right)}_{\to 1} \; \xcancel{\color{blue}{\cos{\frac{n\pi }{3}}}}.$$

Source: Wikipedia's page on $\limsup$ in French
To make it rigorous, for any $\epsilon > 0$, take $N = \left\lceil \dfrac{1}{\epsilon} \right\rceil$.  For all $n \ge N$,
$$\left( 1 + \dfrac{1}{2n} \right) \cos{\frac{n\pi }{3}} \le \left( 1 + \dfrac{1}{2n} \right) \, (1) \le 1 + \dfrac12\:\epsilon < 1 + \epsilon,$$
which violates the later part of (1) in the proposition in an older question: the above inequality shows that $x_n \le 1 + \dfrac\epsilon2$ eventually, instead of $x_n > (1 + \epsilon) - \dfrac\epsilon2$ frequently.

A shorter alternative solution: use the following computation rule (Proposition 2.4 from this note).

Let $(a_n)_n$ and $(b_n)_n$ be two bounded real sequences such that $b_n$ converges to $b \ge 0$.  Then
  \begin{align}
\limsup_n\, a_nb_n &= b \limsup_n\, a_n \text{ and } \\
\liminf_n\, a_nb_n &= b \liminf_n\, a_n.
\end{align}

Apply this rule with $a_n = \cos\dfrac{n\pi}{3}$ and $b_n = 1 + \dfrac{1}{2n}$ to get the same conclusion.


text:
Q: Query slow in neo4j comparing relationships I have a small changetracking application I am building. I wanted to learn graph databases in the process. I have made a model where I have a changetracker with multiple runs checking items. In run A I found 1,2,3,4,5 and in the next run I might find 1,2,4,5,6.
So I made a simple model
(:ChangeTracker)-[:Has_Run]->(:Run)
(:Run)-[:NEXT]->(:Run)
(:Run)-[:HAS_Found]->(:Item)

the following query end up being quite slow when benchmarking (50.000 Items results in query times of > 10 seconds)
    PROFILE
MATCH
    (t:WebsiteTracker {Id : 'fde6fd1f-a899-5295-b73b-63fa75d131f4'})-[:HAS_SiteMapRun]->(lastRun)<-[:NEXT*0..2]-(run)
WHERE NOT (lastRun)-[:NEXT]->()
with t,run

MATCH
  (run)-[:NEXT]->(runNext),
  (runNext)-[:HAS_Found]->(itm)
WHERE
  NOT(run)-[:HAS_Found]->(itm)
RETURN
  t.Id, t.Name, run, itm
ORDER BY
  runNext.Start

I guess the part NOT(runPrev)-[:HAS_Found]->(itm) is the culprit, but how could I make my query better?
As expected the part NOT(runPrev)-[:HAS_Found]->(itm) is hitting every item node, the results look ok though.

A: If you have APOC Procedures, you can use apoc.coll.pairsMin() to get the adjacent pairs of each run, and use apoc.coll.subtract() on the collections of items to find the new elements that weren't present in the previous run.
This requires Neo4j 3.1, as we're using pattern comprehension to obtain the list of items for each run.
Something like this:
MATCH
  (t:ChangeTracker)-[:HAS_Run]->(run)
WHERE
  t.Id = 'fde6fd1f-a899-5295-b73b-63fa75d131f4'
  AND NOT (run)-[:NEXT]->()
MATCH
  (runPrev)-[:NEXT*0..7]->(run)
WITH t, runPrev
ORDER BY runPrev.Start
WITH t, COLLECT({run:runPrev,
  items:[(runPrev)-[:HAS_FOUND]->(itm) | itm]}) as runs
WITH t, apoc.coll.pairsMin(runs) as runPairs
UNWIND runPairs as runPair
WITH HEAD(runPair) as runPrev, LAST(runPair) as runNext
WITH t, runPrev, runNext,
  apoc.coll.subtract(runNext.items, runPrev.items) as newItems
RETURN t.Id, t.Name, runNext.run as run, newItems
ORDER BY
  run.Start


text:
Q: Will supercold flow extract heat from an ice cube? Suppose you have an ice cube in a nonflowing liquid bath of m, where m is an element with a freezing temperature far below water (and whose temperature for this thought experiment is far below water's freezing point).
Will the ice cube get colder if it is placed in a flowing bath of m? That is, will the direction of heat transfer occur from the ice cube to the infinitely flowing thermal sink?

A: You have not given the ice or liquid's temperatures. however heat always flows from a warmer to a colder environment. So if the ice cube is not as cold as the liquid, it will lose heat energy to the liquid, until they reach equilibrium.


text:
Q: Tikz: Calculate position based on node using fit option I want the nodes c and d be inside q and the position of q to be determined by p.
A second problem is, that the distance between p and q isn't correct even with on grid=false (I guess the width of p isn't available because of using fit?).
\documentclass[tikz]{standalone}
\usetikzlibrary{positioning,fit}

\begin{document}

\begin{tikzpicture}
\node (a) [draw=black] {a};
\node (b) [draw=black,on grid,below=of a] {long text};
\node (p) [draw=black,fit={(a) (b)}] {};

\node (c) [draw=red] {c};
\node (d) [draw=red,below=of c] {d};
\node (q) [right=of p,draw=red,fit={(c) (d)}] {};
\end{tikzpicture}
\end{document}

A: marmot proposes to use a matrix, but I think two matrices are better:
\documentclass[tikz]{standalone}
\usetikzlibrary{positioning,matrix}

\begin{document}

\begin{tikzpicture}
\matrix[draw, matrix of nodes, nodes=draw, row sep=3mm] (a) {
a\\
long text\\
};

\matrix[draw=red, matrix of nodes, nodes={draw=red},
          right=3mm of a, row sep=3mm] (b) {
c\\
d\vphantom{g}\\
};
\end{tikzpicture}
\end{document}

A: How about using a matrix?
\documentclass[tikz]{standalone}
\usetikzlibrary{fit,matrix}

\begin{document}

\begin{tikzpicture}
\matrix[column sep=8mm,row sep=3mm] {
\node (a) [draw=black] {a};
&
\node (c) [draw=red] {c};
\\
\node (b) [draw=black] {long text};
&
\node (d) [draw=red] {d};
\\
};
\node (p) [draw=black,fit={(a) (b)}] {};
\node (q) [draw=red,fit={(c) (d)}] {};
\end{tikzpicture}
\end{document}

The advantage of using one matrix (instead of two) is that it also looks good if the vertical dimensions of the nodes vary.
\documentclass[tikz]{standalone}
\usetikzlibrary{fit,matrix}

\begin{document}

\begin{tikzpicture}
\matrix[column sep=8mm,row sep=3mm,anchor=center] (mat) {
\node (a) [draw=black] {a};
&
\node (c) [draw=red] {c};
\\
\node (b) [draw=black,align=center] {long\\ text};
&
\node (d) [draw=red] {d};
\\
};
\node (p) [draw=black,fit={(a) (b) (b|-mat.south)}] {};
\node (q) [draw=red,fit={(c) (d) (d|-mat.south)}] {};
\end{tikzpicture}
\end{document}

As in any TikZ matrix, every line, including the last one, has to be terminated by \\.

A: \documentclass[tikz,margin=3mm]{standalone}
\usetikzlibrary{fit, positioning}

\begin{document}

\begin{tikzpicture}[
node distance = 8mm and 4 mm,
every node/.style = {inner sep=1mm, minimum height=1.5em}
                    ]
\node (a) [draw=black] {a};
\node (b) [draw=black,below=of a] {long text};
\node (p) [draw=black,fit={(a) (b)}] {};

\node (c) [draw=red,right=of b.east |- a] {c};
\node (d) [draw=red,below=of c] {d};
\node (q) [draw=red,fit={(c) (d)}] {};%right=of p,
\end{tikzpicture}
\end{document}


text:
Q: Como dar um select e trazer o top 1 de cada grupo? Tenho uma table de processos. Ou seja, cada vez que um processo é executado, ele gera uma linha nova. Quero dar um select trazendo a última execução de cada processo. Segue table exemplo:
Id|ProcessoNome|Situação|DataInicio
1 |RPA_001     |sucesso |03/10/2018
2 |RPA_002     |sucesso |04/10/2018
3 |RPA_003     |erro    |04/10/2018
4 |RPA_003     |sucesso |04/10/2018
5 |RPA_001     |sucesso |04/10/2018

A: Olá,
Você precisa da última execução de cada processo, certo? Segue abaixo uma query que resolve esse cenário.
select distinct nome_processo,
  (select max(data)
     from processos p2
    where p1.nome_processo = p2.nome_processo) as ULTIMA_EXECUCAO
  from processos p1;

Exemplo de dados:
+----+---------------+-----------------+------------+
| id | nome_processo | status_processo | data       |
+----+---------------+-----------------+------------+
|  1 | RPA_001       | sucesso         | 2018-10-03 |
|  2 | RPA_002       | sucesso         | 2018-10-04 |
|  3 | RPA_003       | erro            | 2018-10-05 |
|  4 | RPA_003       | sucesso         | 2018-10-04 |
|  5 | RPA_001       | sucesso         | 2018-10-04 |
|  6 | RPA_002       | sucesso         | 2018-10-06 |
+----+---------------+-----------------+------------+

Retorno da query :
+---------------+------------+---+
| nome_processo | ULTIMA_EXECUCAO|
+---------------+----------------+
| RPA_001       | 2018-10-04     |
| RPA_002       | 2018-10-06     |
| RPA_003       | 2018-10-05     |
+---------------+----------------+

Qualquer dúvida estamos aí, boa sorte!

A: Minha sugestão é você ordenar a data de execução no select.
SELECT *FROM tb_processos
ORDER BY data_inicio DESC;

O restante é ideal tratar diretamente no código.


text:
Q: Geofence doesn't work when the app is killed I know that the question is already asked, but I tried so many suggested solutions but it doesn't work.
My code for geofence works when app is running, but once the app is killed the notification doesn't appear anymore even when BroadcastReceiver
You can find here the code associated to the activity, btn_reservation is the button that starts adding the geofence.
public class DetailsActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        ResultCallback<Status> {

public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = 12 * 60 * 60 * 1000;
public static final float GEOFENCE_RADIUS_IN_METERS = 500
private List<Geofence> mGeofenceList;
private GoogleApiClient mGoogleApiClient;
private Button btn_reservation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_details);

    btn_reservation = (Button) findViewById(R.id.reserver);

    mGeofenceList = new ArrayList<Geofence>();

    mGeofenceList.add(new Geofence.Builder()

            .setRequestId("1")

            .setCircularRegion(
                    MapsActivity.getLatitude(),
                    MapsActivity.getLongitude(),
                    GEOFENCE_RADIUS_IN_METERS
            )
            .setExpirationDuration(GEOFENCE_EXPIRATION_IN_MILLISECONDS)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
            .build());

    // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    btn_reservation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                if (!mGoogleApiClient.isConnected()) {
                    Toast.makeText(getApplicationContext(), "Google API Client not connected!", Toast.LENGTH_SHORT).show();
                    return;
                }

                try {
                    LocationServices.GeofencingApi.addGeofences(
                            mGoogleApiClient,
                            getGeofencingRequest(),
                            getGeofencePendingIntent()
                    ).setResultCallback(DetailsActivity.this); // Result processed in onResult().
                } catch (SecurityException securityException) {
                    // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
                    Toast.makeText(getApplicationContext(), "ACCESS_FINE_LOCATION permission unused ", Toast.LENGTH_SHORT).show();
                }
            }
    });

}

private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

private PendingIntent getGeofencePendingIntent() {

    Intent intent = new Intent("ACTION_RECEIVE_GEOFENCE");

    return PendingIntent.getBroadcast(
            getApplicationContext(),
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
}

@Override
protected void onStart() {
    super.onStart();
    if (!mGoogleApiClient.isConnecting() || !mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

@Override
public void onConnected(Bundle bundle) {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        System.out.println("My lat " +String.valueOf(mLastLocation.getLatitude()));
        System.out.println("My lon " +String.valueOf(mLastLocation.getLongitude()));
    }
}

@Override
public void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();
}

@Override
public void onResult(Status status) {
    if (status.isSuccess()) {
        System.out.println("Geofences Added");
    } else {
        System.out.println(status.getStatusCode());
    }
}

And this is my GeofenceReceiver.java
public class GeofenceReceiver extends BroadcastReceiver {
Context context;

Intent broadcastIntent = new Intent();

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;

    broadcastIntent.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES);

    GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    if (event.hasError()) {
        handleError(intent);
    } else {
        handleEnterExit(intent);
    }

}

private void handleError(Intent intent){
    GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    // Get the error code
    int errorCode = event.getErrorCode();

    // Get the error message
    String errorMessage = LocationServiceErrorMessages.getErrorString(
            context, errorCode);

    // Log the error
    Log.e(GeofenceUtils.APPTAG,
           "geofence_transition_error_detail"+
                    errorMessage);

    // Set the action and error message for the broadcast intent
    broadcastIntent
            .setAction(GeofenceUtils.ACTION_GEOFENCE_ERROR)
            .putExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS, errorMessage);

    // Broadcast the error *locally* to other components in this app
    LocalBroadcastManager.getInstance(context).sendBroadcast(
            broadcastIntent);
}

private void handleEnterExit(Intent intent) {

    GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    int transition = event.getGeofenceTransition();

    // Test that a valid transition was reported
    if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER)
            || (transition == Geofence.GEOFENCE_TRANSITION_EXIT)) {

        // Post a notification
        List<Geofence> geofences = event
                .getTriggeringGeofences();
        String[] geofenceIds = new String[geofences.size()];
        String ids = TextUtils.join(GeofenceUtils.GEOFENCE_ID_DELIMITER,
                geofenceIds);
        int tran = Geofence.GEOFENCE_TRANSITION_ENTER;
        String transitionType = String.valueOf(tran);

        // Create an Intent to broadcast to the app
        broadcastIntent
                .setAction(GeofenceUtils.ACTION_GEOFENCE_TRANSITION)
                .addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES);

        LocalBroadcastManager.getInstance(context)
                .sendBroadcast(broadcastIntent);

        // Log the transition type and a message
        Log.d(GeofenceUtils.APPTAG, transitionType + ": " + ids);
        Log.d(GeofenceUtils.APPTAG,
                context.getString(R.string.geofence_transition_notification_text));

        // In debug mode, log the result
        Log.d(GeofenceUtils.APPTAG, "transition");

        // An invalid transition was reported
    } else {
        // Always log as an error
        Log.e(GeofenceUtils.APPTAG,
                "geofence_transition_invalid_type"
                       + transition);
    }

    sendNotification(String.valueOf(Geofence.GEOFENCE_TRANSITION_ENTER), "here");
}

private void sendNotification(String transitionType, String locationName) {

    // Create an explicit content Intent that starts the main Activity
    Intent notificationIntent = new Intent(context, TicketActivity.class);

    // Construct a task stack
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    // Adds the main Activity to the task stack as the parent
    stackBuilder.addParentStack(TicketActivity.class);

    // Push the content Intent onto the stack
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack
    PendingIntent notificationPendingIntent = stackBuilder
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions
    // >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            context);

    // Set the notification contents
    builder.setSmallIcon(R.drawable.cast_ic_notification_0)
            .setContentTitle(transitionType + ": " + locationName)
            .setContentText(
                    context.getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());

    System.out.println("in radius");
  }
}

And this is my receiver in the manifest
 <receiver android:name="tn.odc.noq.receiver.GeofenceReceiver" android:exported="false">
    <intent-filter >
      <action android:name="tn.odc.noq.receiver.ACTION_RECEIVE_GEOFENCE"/>
      <category android:name="tn.odc.noq.receiver" />
    </intent-filter>
  </receiver>

A: Work with geofences from scratch it's really hard, I've been tried for along time do this, but I didn't getting a good stub. So i've adopted to use some libs
Here some awesome libs:
Smart-location-lib
Ex:
GeofenceModel mestalla = new GeofenceModel.Builder("id_mestalla")
    .setTransition(Geofence.GEOFENCE_TRANSITION_ENTER)
    .setLatitude(39.47453120000001)
    .setLongitude(-0.358065799999963)
    .setRadius(500)
    .build();

Android-rxgeofence
 RxGeoFence.with(this) //context
        .dbUrl(GEO_FIRE_DB) //String
        .geoFenceSource(...) // rx.Observable<List<Place>>
        .locationSource(...) // rx.Observable<LatLng>
        .build()
        .subscribe(geoFenceEvent -> {
         // do what you wanna do with the event
     });

Android-ReactiveLocation
 Geofence geofence = new Geofence.Builder()
                    .setRequestId("GEOFENCE")
                    .setCircularRegion(latitude, longitude, radius)
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();

I actually indicate use libs as there are a large number of developers working to solve all the problems, and negotiations exception.


text:
Q: Django - Testing a view name retrieved from a url parameter ie. ref=home Simply put, I am trying to test a view name, captured from a URL parameter, within one of my view functions to see if it is valid. If not, to redirect to another page.
For example, take this url...
www.site.com/users/?ref=view_name
Then in my view
    ref = request.GET.get('ref', None)
    return redirect(ref) if ref else redirect('users')

The problem is, of course, that if a user alters the ref parameter, it will kick back a 404. I was hoping to be able to test if ref=home is a valid view and return it, if not then redirect to another view.
I have been messing with Django's resolve and reverse but I am not getting the results I was looking for.
I also tried to use a try/finally in all sorts of ways mixed in with resolve and reverse. Yeah, dumb...I know.
try:
     if ref:
          return redirect(resolve(ref))
finally:
     return redirect('user')

I have searched for almost two hours to try to fund a succinct way to do this.
Any help would be appreciated!

A: The problem is that you are passing a view name to resolve() which requires a URL path. To protect against 404, you need to first reverse() the view name to get a path. Then you can use that path with resolve() to check if the path exists.

A: Working Solution
This was actually very simple after guidance from @Code-Apprentice
A couple Imports first off
from django.urls.resolvers import NoReverseMatch
from django.urls import reverse

Then to get the ref parameter and validate is as a legit view name I did the following
# get ref parameter
ref = request.GET.get('ref', None)

if ref:
    try:
        # redirect to ref view name if valid
        return redirect(reverse(ref))
    except NoReverseMatch as e:
        print('No reverse match found')

# redirect to specific view if ref is invalid
return redirect('users')


text:
Q: How can I make a function for summoning an object in pygame? I'm trying to create a kind of simple 2D "game" in python, using pygame, to test my skills. I was thinking of adding a command-system to the game, so I can test things without having to change the code, but I wasn't able to create a function for summoning an object, I hope I've been clear enough, because I'm pretty new to all the python stuff and it's like my second time using pygame.
I've tried this so far:
import pygame, random

#Start main window
pygame.init()
size = (800, 600)
win = pygame.display.set_mode(size)
icon_image = pygame.image.load("logo.png")
pygame.display.set_caption("\t\r\a\t\b\fa\v")
pygame.display.set_icon(icon_image)

#Set images
player_image = pygame.image.load("player.png")
background_image = pygame.image.load("bg.png").convert()
raw_rock_image = pygame.image.load("rock.png")
rock_image = pygame.transform.scale(raw_rock_image, (55, 55)).convert()
raw_tree_image = pygame.image.load("tree.png")
tree_image = pygame.transform.scale(raw_tree_image, (75, 75))

#Spawn trees
trees = []
for tree in range(3):
    x = random.randint(0, 740)
    y = random.randint(0, 540)
    trees.append([x, y])

#Spawn rocks
rocks = []
for rock in range(10):
    x = random.randint(0, 740)
    y = random.randint(0, 540)
    rocks.append([x, y])

#Create a class for the player
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = 0.065

    def move(self, dx, dy):
        self.x += dx * self.speed
        self.y += dy * self.speed

    def draw(self):
        win.blit(player_image, (self.x, self.y))

#Set player's coordinates
player = Player(400, 300)

#Define command "setcoors" to set the player's coordinates to a specific value
def setcoors(x, y):
    player.x = int(x)
    player.y = int(y)

#Define command "showcoors" to show player's coordinates
def showcoors():
    print(f"Your player's coordinates are: {int(player.x)}, {int(player.y)}")

def help_command():
    print("""
Available commands:

        setcoors (setcoors int:x int:y): Sets the player's coordinates to a specific number.
        showcoors (showcoors): Shows player's coordinates.
        exit (exit): Exits the command line.
        help (help): Shows this message.
        """)
    cmd(input("Insert a command (use help to help): "))

def summon(object, count, xcor, ycor):
    int(xcor)
    int(ycor)
    int(count)
    if object.lower() == "tree":
        for tree in range(count):
            trees.append([xcor, ycor])
    elif object.lower() == "rock":
        for rock in range(count):
            rocks.append([xcor, ycor])
    else:
        print("Please choose one of the available objects to summon.")

#Create the command-system
def cmd(user_input):
    words = user_input.split()
    command = words[0]
    parameters = words[1:]
    if command.lower() == "exit":
        return "exit = True"
    elif command.lower() == "help":
        help_command()
    elif command.lower() == "quit":
        print("Quitting game... (Note: You can also use Q for that).")
        event.type = pygame.QUIT
    elif command.lower() == 'setcoors':
        try:
            setcoors(*parameters)
        except ValueError:
            print("Please insert an valid integer number between 0 and 800 for X and 0 and 600 for Y.")
        except TypeError:
            print("Please insert an valid integer number between 0 and 800 for X and 0 and 600 for Y.")
        except IndexError:
            print("Please insert an valid integer number between 0 and 800 for X and 0 and 600 for Y.")
        else:
            pass
    elif command.lower() == "showcoors":
        showcoors()
    elif command.lower() == "summon":
        summon(*parameters)
    else:
        print("Please insert a valid command. Use help to show help.")

#Main game loop
running = True
while running:

    #Close window
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
       running = False

    #Keybinds
    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        player.move(-3, 0)
    if keys[pygame.K_d]:
        player.move(3, 0)
    if keys[pygame.K_w]:
        player.move(0, -3)
    if keys[pygame.K_s]:
        player.move(0, 3)
    if keys[pygame.K_q]:
        event.type = pygame.QUIT
    if keys[pygame.K_e]:
        cmd(input("Insert a command (use help to show help): "))

    #Screen borders
    if player.x >= 740:
        player.x = 740
    if player.x <= 0:
        player.x = 0
    if player.y >= 540:
        player.y = 540
    if player.y <= 0:
        player.y = 0

    #Set the background
    win.blit(background_image, (0, 0))

    #Set objects and the player
    for tree in trees:
        win.blit((tree_image), (tree[0], tree[1]))

    for rock in rocks:
        win.blit((rock_image), (rock[0], rock[1]))
    player.draw()

    #Update window
    pygame.display.update()

#Quit game
pygame.quit()


text:
Q: Array of pointers and file I/O in C #include <stdio.h>
#include <stdlib.h>

int main()
{
    char *strs[6], array[100];
    int i;
    FILE *file  = fopen("random.txt", "r");

    for (i=0 ; i<6; i++)
    {
        fscanf(file ,"%s", array);
        strs[i]= array;

        printf("%s ", strs[i]);
    }

    printf("%s", strs[3]);

    return 0;
}

Inside the random.txt:
one two three four five six
Output is:
one two three four five six six
My question is why the last one 'six', I cannot access third element that is 'four'. Why doesn not record them in char array of pointers?

A: The problem is that all element in your array of pointers, i.e. strs, points to array. In other words - strs[0] points to array, strs[1] points to array, strs[2] points to array and so on.
So when you change array all elements in strs points to the new value.
It can be fixed in several ways but the easiest way is:
//char *strs[6], array[100];
char strs[6][100];

and
// fscanf(file ,"%s", array);
// strs[i]= array;
fscanf(file ,"%s", strs[i]);

However, notice that your code has no check for buffer overflow (which is bad). I'll recommend that you read about fgets

A: You shall use strcpy from string.h library
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char strs[6][100] , array[100];
    int i;
    FILE *file  = fopen("random.txt", "r");

    for (i=0 ; i<6; i++)
    {
        fscanf(file ,"%s", array);
        strcpy(strs[i], array) ;

        printf("%s ", strs[i]);
    }

    printf("%s", strs[3]);

    return 0;
}


text:
Q: How to mask subdomain as domain Is it possible to to access web with url example.com but variables inside php (like SERVER_NAME) would act like sub.example.com?
We made wrong decision during development and now we are actually stuck with two separate versions of software. One for example.com and other for automatically generated subdomains. We could reserver one subdomain to act as our main domain, but we don't want that sub. example.com part.

A: You should add some checks, for example:
function hasSubdomain($url) {
    $parsed = parse_url($url);
    $exploded = explode('.', $parsed["host"]);
    if(count($exploded) > 2){
       return true;
    }else{
       return false;
    }
}

if(!hasSubdomain($_SERVER['SERVER_NAME'])){
   $_SERVER['SERVER_NAME']="sub.example.com";
}


text:
Q: Not able to open Nvidia X Server settings Laptop: Asus Zenbook UX430UN-GV020T
OS: Ubuntu 18.04
$ ubuntu-drivers devices
== /sys/devices/pci0000:00/0000:00:1c.0/0000:01:00.0 ==
modalias : pci:v000010DEd00001D10sv00001043sd00001C20bc03sc02i00
vendor   : NVIDIA Corporation
model    : GP108M [GeForce MX150]
driver   : nvidia-driver-390 - third-party free
driver   : nvidia-driver-396 - third-party free recommended
driver   : xserver-xorg-video-nouveau - distro free builtin

$ sudo ubuntu-drivers autoinstall
$ <reboot>

$ echo $XDG_SESSION_TYPE
x11

$ sudo apt show nvidia-390
Package: nvidia-390
Version: 390.67-0ubuntu0~gpu18.04.1
Priority: optional
Section: libs
Source: nvidia-graphics-drivers-390
Maintainer: Ubuntu Core Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Installed-Size: 20.5 kB
Depends: nvidia-driver-390
Download-Size: 8,044 B
APT-Sources: http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic/main amd64 Packages
Description: Transitional package for nvidia-driver-390
This is a transitional package for nvidia-driver-390, and can be
safely removed after the installation is complete.

$ sudo apt show nvidia-396
N: Unable to locate package nvidia-396
N: Unable to locate package nvidia-396
E: No packages found

I'm not sure why is the version 390, when the recommended driver was 396.
But trying to open Nvidia X Server settings does not do anything.
Any help guys?


text:
Q: magento 1.7 product export page goes blank after long time I am using magento 1.7 for my site when I do export for one sku I easily get csv but when I want to export around 2500 product its goes in infinite loop and sometime I get only blank page.
Checking my system log file I get this:
Notice: Undefined index: 0  in /chroot/home/utwomobi/u2mobility.com/html/includes/src/Mage_ImportExport_Model_Export_Entity_Product.php on line 663


text:
Q: How to add an href and img tag via JavaScript The problem I have is when I put a href link in javascript and also img tag, the image won't display.
html='
'+'
Hot Pot Restaurant
 '+ name+"
"+address+"
"+"<img src=/"+image+'
';

A: There seemed to be a lot of typos in your code.
Please see working code below.

let address = 'An Address';
let name = 'Persons Name';
let image = 'https://images.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
let link = 'https://images.google.com/';

html='

Hot Pot Restaurant
 '+ name+'
'+address+'

';

document.write(html);

A: Try to use template literal. It is much easier and cleaner to read your code.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

const title = "Stack Overflow";
const link = "https://stackoverflow.com";
const image= "https://streamdata.io/wp-content/uploads/2018/04/stackoverflow.png";
const html = `

${title}

`;
document.write(html);

A: You have mixed single and double quotes and href is also missing. Try below
html = '
' + '
Hot Pot Restaurant
 ' + name + '
' + address + '
' + '
';


text:
Q: How can I make a Sublime Text project file to only show certain folders? SublimeText has a project-settings file that includes a folder_include_patterns option.
I have a folder called (my app name).project-settings (which according to some research, is the correct name for the file) in the top level of my project. I am trying to make Sublime not show all the files under node_modules except my-module:
{
  "folders": [
    {
      "path": "node_modules",
      "folder_include_patterns": [
        "my-module"
      ]
    }
  ]
}

However SublimeText still shows all the files under node_modules. How can I make a Sublime Text project file to only show certain folders?

A: I assume you don't want to ignore all the other modules in node_modules.
You could ignore your node_modules directory and include your module as another folder.
{
  "folders":
  [
    {
      "folder_exclude_patterns":
      [
        "node_modules",
      ],
      "path": "."
    },
    {
      "path": "node_modules/mymodule"
    },
  ]
}

A: My syntax is correct, but making the file isn't enough to make a dir into a project.
Since there is no 'new project' button in Sublime, you can make a folder with:

*

*Open the folder in Sublime.

*Click Project > Save Project As
This makes:
your_project.sublime-project
{
  "folders": [
    {
      "path": "."
    },
    {
      "path": "node_modules",
      "folder_include_patterns": [
        "my-module"
      ]
    }
  ]
}

your_project.sublime-workspace (left as defaults)
Additionally: you must open the project from the Project menu (otherwise it will still be a folder and ignore the .sublime-project file).


text:
Q: Start Activity with MapFragment from another Activity I developed an application and I need to start a new activity from my menu with a simple button. I made several tests and noticed that if I set the intent-filter of Activity that contains the MapFragment as follows:
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

this works fine without any crashes.
If instead modify the intent-filter in such a way as not to start the Activity soon as you open the app and in particular the edit as follows:
 <action android:name="com.hpdev.maps.MYMAP" />

 <category android:name="android.intent.category.DEFAULT" />

The activity is not started and the app crashes. How can I fix this bug?
I include the code in my activity.java:
public class MyMap extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

}}

My stacktrace:
04-03 20:49:57.637: E/AndroidRuntime(28889): FATAL EXCEPTION: main
04-03 20:49:57.637: E/AndroidRuntime(28889): Process: com.fziviello.altamuragroup, PID: 28889
04-03 20:49:57.637: E/AndroidRuntime(28889): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fziviello.altamuragroup/com.fziviello.altamuragroup.DoveSono}: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2277)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.ActivityThread.access$800(ActivityThread.java:145)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.os.Handler.dispatchMessage(Handler.java:102)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.os.Looper.loop(Looper.java:136)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.ActivityThread.main(ActivityThread.java:5088)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at java.lang.reflect.Method.invokeNative(Native Method)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at java.lang.reflect.Method.invoke(Method.java:515)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:126)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at dalvik.system.NativeStart.main(Native Method)
04-03 20:49:57.637: E/AndroidRuntime(28889): Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:547)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.view.LayoutInflater.inflate(Native Method)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:344)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.Activity.setContentView(Activity.java:1952)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at com.fziviello.altamuragroup.DoveSono.onCreate(DoveSono.java:37)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.Activity.performCreate(Activity.java:5434)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
04-03 20:49:57.637: E/AndroidRuntime(28889):    ... 12 more
04-03 20:49:57.637: E/AndroidRuntime(28889): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.MapFragment: make sure class name exists, is public, and has an empty constructor that is public
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.Fragment.instantiate(Fragment.java:597)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.Fragment.instantiate(Fragment.java:561)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.Activity.onCreateView(Activity.java:4816)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
04-03 20:49:57.637: E/AndroidRuntime(28889):    ... 25 more
04-03 20:49:57.637: E/AndroidRuntime(28889): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.maps.MapFragment" on path: DexPathList[[zip file "/data/app/com.fziviello.altamuragroup-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.fziviello.altamuragroup-1, /vendor/lib, /system/lib]]
04-03 20:49:57.637: E/AndroidRuntime(28889):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
04-03 20:49:57.637: E/AndroidRuntime(28889):    at android.app.Fragment.instantiate(Fragment.java:583)
04-03 20:49:57.637: E/AndroidRuntime(28889):    ... 28 more

A: If all you need to do is start a new Activity from a button, just create an Intent that explicitly points to that Activity in the button's onClickListener. The below is an onClickListener defined in a Fragment's button:
mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), MapActivity.class);
            startActivity(intent);
        }
    });

You need to make sure that all of you Activity's are registered in the AndroidManifest.xml, but they don't all require intent filters. You will need the Main/ Launcher intent filter in the Activity that you want the launcher icon to open, but other Activities don't require intent filters because you can explicitly reference them as I dide in the code above.


text:
Q: NoInitialContextException in Spring boot JPA test I am working on migrating following spring boot test case from spring boot 1 to spring boot 2.
org.springframework 4.3.10 -> 5.3.18
org.springframework.boot 1.5.6 -> 2.6.6
Original Test case :
@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration (classes = {UserProfileTestContext.class, UserProfileLocatorContext.class})
@SpringBootTest (classes = {UserProfileTestContext.class, UserProfileLocatorContext.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("UserProfileLocatorContext")
public class UserProfileLocatorIntegrationTestIT {

    @Autowired
    private UserProfileLocator profileLocator;

    @Test
    public void locate() throws Exception {
        InitialContext ctx = new InitialContext();
        NamingEnumeration<NameClassPair> list = ctx.list("");
        while (list.hasMore()) {
            NameClassPair next = list.next();
            System.out.println(next.getName() + " -> " + next.getClassName());
        }

        profileLocator.locate("user1");
    }

}

When I ran this test case with new versions, I got an error saying
java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class : [@org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper.class), @org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.context.SpringBootTestContextBootstrapper.class)]

I did a web search regarding this and removed the @SpringBootTest tag [1].
After this I am getting a different error when calling the 'locate' method
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

Any idea on what I am missing here?


text:
Q: Why is my error handling with jquery deferred and jsonp data not working? I am just trying to figure out the deferred api and have this nice sample code going with the twitter search api:
var getTweets = function(q) {
    return $.ajax({
        url: 'http://search.twitter.com/search.json?q=' + encodeURIComponent(q),
        dataType: 'jsonp'
    })
};

var getTheDay = function(date){
    var date = new Date(date);
    return date.getDay();
}

var parseTweetData = function(data){
    $.each(data.results, function(index, tweet){
        console.log(tweet.text
        + ' from ' + tweet.from_user_name
        + ' at ' + getTheDay(Date.parse(tweet.created_at) * 1000));
    });
}

var parseError = function(error, xhr) {
    alert('failed')
};

$.when(getTweets(' martin')).then(parseTweetData, parseError);

Getting results back is just fine. The problem comes with the situation where twitter returns a 403 error.
I want to handle that error with my custom error handler but that doesn't seem to be triggered at all. What am I doing wrong? Have I misunderstood the api? How do I write a proper ajax error handler request?

A: According to the $.ajax docs the error handler isn't called for jsonp requests, so it probably wont call in a deferred either.

error
  Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
  A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.

you can try using a timeout to trigger an error callback, so basically we are giving the request some amount of time to be made and when the time expires we assume the request failed.
$.ajax({
    url: 'http://search.twitter.com/search.json?q=' + encodeURIComponent(q),
    dataType: 'jsonp',
    timeout: 5000 /* 5 seconds timeout, plenty of time for the request to complete */
})


text:
Q: How to properly name and conceptualize object data modeling scenario with a Quote object that contains Line Items? This is a object/data modeling and object naming question.
Background
Imagine you are getting a repair quote for a vehicle - you usually get a single sheet, which is called a quote, and on the sheet there are one or more line items indicating repairs to be done, with pricing, quantity, description information.  The quote itself has things like customer name, business name, company logo, address, formatting, etc.
Suppose I write a Quote object, where a quote has zero or more instances of LineItem.
Consider the following code:
class LineItemRepository extends GenericRepository
{
    /**
     * Return Quote Domain entity, populated with line items and metadata
     */
    function getQuote(int $quoteId): Quote
    {
        //selects all line items that belong to a quote with quote_id
        $query = $this->getDoctrine()->createQuery('
            SELECT item
            FROM ' . LineItem::class . ' item
            WHERE item.quoteId = :quote_id
        ');
        $query->setParameter('quote_id', $quoteId);
        $lineItems = $query->getResult();

        //creates & populates a domain Quote object with
        //quote metadata and line items
        $quoteData = $this->getDoctrine()->find(Quote::class, $quoteId);
        $quote = new Quote($quoteData);
        $quote->setLines($lineItems);
        return $quote;
    }
}

Above I have a LineItemRepository that is conceptually "in charge" of managing individual line items, where line items are a part of a quote.  So inside my getQuote method I request all the line items using Doctrine ORM, where line items belong to a particular quote, with a given quote id.  The method returns a Quote object, where the object contains quote metadata (customer info, etc), and line items with their own metadata (quantity, description, etc)
To me this creates a dissonance.  How can a repository that is in charge of individual line items, return a quote, when a Quote is a separate entity almost, which is not a LineItem?  Those are separate concepts and somehow they are mixed together.  Shouldn't it return .. just line items in a group perhaps, like an array for example?
Do I or should I rename LineItemRepository to QuoteRepository instead to help remove this dissonance?  Do I keep things as is?  I am pretty confused.  How do I name things and how do I conceptualize these concepts in my head so that object data modeling makes sense and naming reflects this understanding, and that there is no dissonance?
I am struggling because LineItem and Quote are concepts that are pretty-well connected, and yet separate.  LineItem does not make sense by itself, without being attached to a quote conceptually, so naming things is kind of hard, as they are connected, yet separate.

A: When we talk about SOLID, the S stands for Single Responsability Principle, which means that the class should have only one reason to change.
In this case, the code you have may change both when the Quote or Line changes.
What you could do is to create/use a class named Quote and create a method getQuote, getQuoteLines, getQuoteItems or something, that will return the quote itself with the lines, because the Quote is a composition of Line, at least in the conception, and know the Lines.
In the other way, a Line knows itself and the Quote it belongs, but a Line doesn't know their siblings, thats why you should give the responsability to the Quote class.