text:
Q: when should I init https connection? I would like to make log in process more safely. And to achieve it i'm thinking to start using https. I have never used it before.
Now on main page user see login link, and div with login form already loaded with the main page together. User click on login link and see immediately LoginForm. in action attributes of form I will put url beginning from htts. So my question: Will these username and password  send out by protected protocol or not ?
P.S. I have no registeres certificate, so most modern browsers actually show page about risks ... so how usually everyone solve such issues?

A: The user's login details will be sent encrypted, but because your main page isn't using HTTPS the user won't see the expected padlock symbol, and might be wary about using the form.
Put it another way: without using View source there's no way for the user to know whether your form is secure or not.
The only fully safe and obvious way to do what you're doing is to serve any page that offers the login form via HTTPS, eg. by redirecting http://mysite.com to https://mysite.com.  Twitter is an example of a site that does this.

A: The entire HTTP request will be encrypted, including headers and query parameters (more details in this answer).
However, you should also make sure the landing page is using HTTPS. A essential point of the security offered by HTTPS is that only the client can really check it: the user has to see it in use via the user interface first. You'll find more details in this OWASP rule (and in this previous answer to a similar question).
As for the browser warnings regarding your cert: you'll need to get a certificate from a CA recognised by most browsers.

A: Best approach would be to always force HTTPS, not just for login and after that, which can usually be accomplished via webserver configuration (you haven't mentioned which webserver you are using).
You will need a certificate issued by a trusted certificate authority, which usually cost money, but there are also free certificates — e.g. by StartSSL (I have no affiliation with them).


text:
Q: Issue with Static Django files on Heroku I have deployed by Django project as a Heroku app, but can not get the static files to work.
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = 'static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

which is exactly what is recommended at Django and Static Assets
I have set DISABLE_COLLECTSTATIC to false with,
$ heroku config:set DISABLE_COLLECTSTATIC=0 --app mathsproject

The file system looks like this,

which shows that the 'static' directory is in the root of my Django project. But I do not see where the 'staticfiles' directory is? Should this be created somewhere?
When running,
$ heroku logs
I typically get errors showing that the static files are missing. And this is obvious in the browser too.
......
2016-07-11T07:39:30.187273+00:00 app[web.1]: Not Found: /static/assets/js/jquery-1.10.2.min.js
    2016-07-11T07:39:30.264037+00:00 app[web.1]: Not Found: /static/assets/img/4.png
    2016-07-11T07:39:30.283627+00:00 app[web.1]: Not Found: /static/assets/img/testimonials/1.jpg
........

Whitenoise has been enabled by adding, to mathProject/wsgi.py
import os

from django.core.wsgi import get_wsgi_application

from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mathsProject.settings")

application = get_wsgi_application()

application = DjangoWhiteNoise(application)

To the bottom of settings.py I put
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

Running
$ heroku run bash

and then,
$ python manange.py collectstatic --noinput

this gives several lines of errors, the last of which is,
OSError: [Errno 2] No such file or directory: '/app/mathsProject/static'

But there is a 'static' directory in 'mathsProject'
Thanks,

A: The static files are recognised when the 'static' directory is inside the Django project directory, which unfortunately had the same name as the whole Django directory. Both were called 'mathsProject'.
Also I set,
$ heroku config:set DISABLE_COLLECTSTATIC=1

This works for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use subquery in Hive I can run below subquery command in MySQL, but it is not working in Hive. Is the Hive format different for subquery from MySQL?
Question:
Write query in hive that shows all orders belonging to a certain day. This day is when the most orders were placed. select data from orders_sqoop
select *
from orders_sqoop
where order_date = (select order_date from orders_sqoop
                    group by order_date
                    order by count(order_id) desc
                    limit 1);

I see below output in hive (cloudera cdh)
NoViableAltException(226@[400:1: precedenceEqualExpression : ( (left= precedenceBitwiseOrExpression -> $left) ( ( KW_NOT precedenceEqualNegatableOperator notExpr= precedenceBitwiseOrExpression )
   -> ^( KW_NOT ^( precedenceEqualNegatableOperator $precedenceEqualExpression $notExpr) ) | ( precedenceEqualOperator equalExpr= precedenceBitwiseOrExpression )
   -> ^( precedenceEqualOperator $precedenceEqualExpression $equalExpr) | ( KW_NOT KW_IN LPAREN KW_SELECT )=> ( KW_NOT KW_IN subQueryExpression )
   -> ^( KW_NOT ^( TOK_SUBQUERY_EXPR ^( TOK_SUBQUERY_OP KW_IN ) subQueryExpression $precedenceEqualExpression) ) | ( KW_NOT KW_IN expressions )
   -> ^( KW_NOT ^( TOK_FUNCTION KW_IN $precedenceEqualExpression expressions ) ) | ( KW_IN LPAREN KW_SELECT )=> ( KW_IN subQueryExpression )
   -> ^( TOK_SUBQUERY_EXPR ^( TOK_SUBQUERY_OP KW_IN ) subQueryExpression $precedenceEqualExpression) | ( KW_IN expressions )
   -> ^( TOK_FUNCTION KW_IN $precedenceEqualExpression expressions ) | ( KW_NOT KW_BETWEEN (min= precedenceBitwiseOrExpression ) KW_AND (max= precedenceBitwiseOrExpression ) )
   -> ^( TOK_FUNCTION Identifier["between"] KW_TRUE $left $min $max) | ( KW_BETWEEN (min= precedenceBitwiseOrExpression ) KW_AND (max= precedenceBitwiseOrExpression ) )
   -> ^( TOK_FUNCTION Identifier["between"] KW_FALSE $left $min $max) )* | ( KW_EXISTS LPAREN KW_SELECT )=> ( KW_EXISTS subQueryExpression )
   -> ^( TOK_SUBQUERY_EXPR ^( TOK_SUBQUERY_OP KW_EXISTS ) subQueryExpression ) );])
        at org.antlr.runtime.DFA.noViableAlt(DFA.java:158)
        at org.antlr.runtime.DFA.predict(DFA.java:116)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceEqualExpression(HiveParser_IdentifiersParser.java:8668)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceNotExpression(HiveParser_IdentifiersParser.java:9690)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceAndExpression(HiveParser_IdentifiersParser.java:9809)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceOrExpression(HiveParser_IdentifiersParser.java:9968)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.expression(HiveParser_IdentifiersParser.java:6584)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.atomExpression(HiveParser_IdentifiersParser.java:6808)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceFieldExpression(HiveParser_IdentifiersParser.java:6879)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceUnaryPrefixExpression(HiveParser_IdentifiersParser.java:7264)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceUnarySuffixExpression(HiveParser_IdentifiersParser.java:7324)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceBitwiseXorExpression(HiveParser_IdentifiersParser.java:7508)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceStarExpression(HiveParser_IdentifiersParser.java:7668)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedencePlusExpression(HiveParser_IdentifiersParser.java:7828)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceAmpersandExpression(HiveParser_IdentifiersParser.java:7988)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceBitwiseOrExpression(HiveParser_IdentifiersParser.java:8147)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceEqualExpression(HiveParser_IdentifiersParser.java:8803)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceNotExpression(HiveParser_IdentifiersParser.java:9690)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceAndExpression(HiveParser_IdentifiersParser.java:9809)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.precedenceOrExpression(HiveParser_IdentifiersParser.java:9968)
        at org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.expression(HiveParser_IdentifiersParser.java:6584)
        at org.apache.hadoop.hive.ql.parse.HiveParser.expression(HiveParser.java:44932)
        at org.apache.hadoop.hive.ql.parse.HiveParser_FromClauseParser.searchCondition(HiveParser_FromClauseParser.java:6530)
        at org.apache.hadoop.hive.ql.parse.HiveParser_FromClauseParser.whereClause(HiveParser_FromClauseParser.java:6438)
        at org.apache.hadoop.hive.ql.parse.HiveParser.whereClause(HiveParser.java:44974)
        at org.apache.hadoop.hive.ql.parse.HiveParser.singleSelectStatement(HiveParser.java:42062)
        at org.apache.hadoop.hive.ql.parse.HiveParser.selectStatement(HiveParser.java:41720)
        at org.apache.hadoop.hive.ql.parse.HiveParser.regularBody(HiveParser.java:41657)
        at org.apache.hadoop.hive.ql.parse.HiveParser.queryStatementExpressionBody(HiveParser.java:40710)
        at org.apache.hadoop.hive.ql.parse.HiveParser.queryStatementExpression(HiveParser.java:40586)
        at org.apache.hadoop.hive.ql.parse.HiveParser.execStatement(HiveParser.java:1529)
        at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1065)
        at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:201)
        at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:166)
        at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:522)
        at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1356)
        at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1473)
        at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1285)
        at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1275)
        at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:226)
        at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:175)
        at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:389)
        at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:781)
        at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:699)
        at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:634)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:136) FAILED: ParseException line 1:47 cannot recognize input near 'select' 'order_date' 'from' in expression specification

A: Using count() + rank():
select * --list all columns here
from
(
select s.*, rank() over(order by cnt desc) rnk
from
(
select s.*,
       count(order_id) over(partition by order_date) cnt
  from orders_sqoop s
) s
) s where rnk=1

Using subquery in the WHERE:
select o.*
  from orders_sqoop o
  where order_date in (select s.order_date from orders_sqoop s group by s.order_date order by count(s.order_id) desc limit 1);

A: Just Change the = to the  In  operator
The IN operator is considered a membership type.  The membership type allows you to conduct multiple match tests compactly in one statement
select *
  from orders_sqoop
 where order_date in  (select order_date from orders_sqoop group by order_date order by count(order_id) desc limit 1);


text:
Q: python list to database column (sqlite) I have a list called
fullpricelist=[373.97, 381.0, 398.98, 402.98, 404.98, 457.97, 535.99, 550.97, 566.98]

I would like to write this list into a slqlite database column, I found the following code from another question and changed it to my situation.
cursor.executemany("""INSERT INTO cardata (fullprice) VALUES (?)""",
                   zip(fullpricelist))

My current script is this
for name, name2, image in zip(car_names, car_names2, images):
    cursor.execute(
        "insert into cardata (carname, carmodel, imageurl, location, Fro, T, companyid) values (?, ?, ?, ?, ?, ?, ?)",
        (name.text, name2.text, image.get_attribute('src'), location, pickup_d, return_d, Rental_ID)
    )

But now I am confused how to add these codes together

A: In your second piece of code, execute() is called and one specific object is stored in the database each loop iteration. This is slow and inefficient.
for price in fullpricelist:
    cursor.execute("""INSERT INTO cardata (fullprice) VALUES (?)""", price)

executemany() reads from an iterable and adds each element of the iterable to the database as a distinct row. If you add many elements to a database and care about efficiency, you want to use executemany()
cursor.executemany("""INSERT INTO cardata (fullprice) VALUES (?)""", fullpricelist)

If you want to include the other columns in your question, your code will be
cursor.executemany("""INSERT INTO cardata (carname, carmodel, imageurl, location, Fro, T, companyid) values (?, ?, ?, ?, ?, ?, ?)""",
        [
             [name.text for name in car_names],
             [name.text for name in car_names2],
             [image.get_attribute('src') for image in images],
             [location]*len(car_names),
             [pickup_d]*len(car_names),
             [return_d]*len(car_names),
             [Rental_ID]*len(car_names)
        ]
    )

This assumes all values for location, pickup_d, return_d and Rental_ID are the same, as you did not provide a list of the values.


text:
Q: Count the rows in a data table where a condition has been met consecutively I am trying to determine a robust way to determine for how many historical rows a condition has been true, for each ID in a table.
Here is the example data:
DT <- data.table(update_date = rep(c("2022-01-01", "2022-01-02",
                                     "2022-01-03", "2022-01-04",
                                     "2022-01-05", "2022-01-06"), times = 2),
                 ID = c(rep("aapl", times = 6), rep("ibm", times = 6)),
        b = c("U1", "U1", "U1", "U2", "U2", "U2", "D1", "D2", "D1", "D3", "D2", "D3") )

DT[, update_date := as.Date(update_date)]

    update_date   ID  b
 1:  2022-01-01 aapl U1
 2:  2022-01-02 aapl U1
 3:  2022-01-03 aapl U1
 4:  2022-01-04 aapl U2
 5:  2022-01-05 aapl U2
 6:  2022-01-06 aapl U2
 7:  2022-01-01  ibm D1
 8:  2022-01-02  ibm D2
 9:  2022-01-03  ibm D1
10:  2022-01-04  ibm D3
11:  2022-01-05  ibm D2
12:  2022-01-06  ibm D3

What I need to calculate is for each row, how long the value in b has existed, done by ID.
So for ID == 'aapl', the value for row 6 would be 3, as the value "U2" has existed for 3 days (or rows).  The value for row 5 would be 2.  The value for row 3 would be 3 again.
For the ID == 'ibm', row 12 would have 1.  Row 11 would have 1 as well as"D2" has only been true for 1 day (or row).
I can loop through each ID, and day, and look backward.  I'm just wondering if there is a more concise way to do this than row by row.

A: Counting consecutive occurrences (i.e. run length) of b for each ID through specified update_date
DT[order(ID, update_date), occurence := 1:.N, by = list(ID, rleid(b))]
DT
#>     update_date   ID  b occurence
#>  1:  2022-01-01 aapl U1         1
#>  2:  2022-01-02 aapl U1         2
#>  3:  2022-01-03 aapl U1         3
#>  4:  2022-01-04 aapl U2         1
#>  5:  2022-01-05 aapl U2         2
#>  6:  2022-01-06 aapl U2         3
#>  7:  2022-01-01  ibm D1         1
#>  8:  2022-01-02  ibm D2         1
#>  9:  2022-01-03  ibm D1         1
#> 10:  2022-01-04  ibm D3         1
#> 11:  2022-01-05  ibm D2         1
#> 12:  2022-01-06  ibm D3         1

Counting occurrences of b for each ID through specified update_date
This includes occurrences that are non-consecutive.
#  Count of occurrences through present row
DT[order(ID, b, update_date), occurence := 1:.N, by = list(ID, b)]
DT
#>     update_date   ID  b occurence
#>  1:  2022-01-01 aapl U1         1
#>  2:  2022-01-02 aapl U1         2
#>  3:  2022-01-03 aapl U1         3
#>  4:  2022-01-04 aapl U2         1
#>  5:  2022-01-05 aapl U2         2
#>  6:  2022-01-06 aapl U2         3
#>  7:  2022-01-01  ibm D1         1
#>  8:  2022-01-02  ibm D2         1
#>  9:  2022-01-03  ibm D1         2
#> 10:  2022-01-04  ibm D3         1
#> 11:  2022-01-05  ibm D2         2
#> 12:  2022-01-06  ibm D3         2

A: DT[, counter := rowid(rleid(b)), .(ID)]

    update_date   ID  b counter
 1:  2022-01-01 aapl U1       1
 2:  2022-01-02 aapl U1       2
 3:  2022-01-03 aapl U1       3
 4:  2022-01-04 aapl U2       1
 5:  2022-01-05 aapl U2       2
 6:  2022-01-06 aapl U2       3
 7:  2022-01-01  ibm D1       1
 8:  2022-01-02  ibm D2       1
 9:  2022-01-03  ibm D1       1
10:  2022-01-04  ibm D3       1
11:  2022-01-05  ibm D2       1
12:  2022-01-06  ibm D3       1

A: You could solve your problem as follow (rleid allows to take into account repeated values of b that are not consecutive within each group, like row 12 or 11 where the value of the variable b is not preceded by the same value):
DT[order(ID, update_date), ndays := seq_len(.N), by=.(ID, rleid(b))]

    update_date     ID      b ndays
 1:  2022-01-01   aapl     U1     1
 2:  2022-01-02   aapl     U1     2
 3:  2022-01-03   aapl     U1     3
 4:  2022-01-04   aapl     U2     1
 5:  2022-01-05   aapl     U2     2
 6:  2022-01-06   aapl     U2     3
 7:  2022-01-01    ibm     D1     1
 8:  2022-01-02    ibm     D2     1
 9:  2022-01-03    ibm     D1     1
10:  2022-01-04    ibm     D3     1
11:  2022-01-05    ibm     D2     1
12:  2022-01-06    ibm     D3     1


text:
Q: Installation of virtualbox-guest-dkms fails Recently I installed Ubuntu into VirtualBox. The problem was that the resolution was really small and it stayed small even when I enlarge it by going to view → switch to full screen. I searched and found this solution:
sudo apt-get install virtualbox-guest-dkms

which fails with this error message:
File "/usr/share/apport/package-hooks/dkms_packages.py", line 98, in <module>
with apport.fileutils.make_report_file(report) as f: AttributeError: 'module' object has no attribute 'make_report_file'
Error! Bad return status for module build on kernel: 3.19.0-25-generic (x86_64)
Consult /var/lib/dkms/virtualbox-guest/4.3.10/build/make.log for more information

Content of the log file:
DKMS make.log for virtualbox-guest-4.3.10 for kernel 3.19.0-25-generic (x86_64)
Mi 18. Nov 11:15:34 CET 2015
make: Entering directory `/usr/src/linux-headers-3.19.0-25-generic'
  LD      /var/lib/dkms/virtualbox-guest/4.3.10/build/built-in.o
  LD      /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/built-in.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.o
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c: In function 'VBoxGuestCommonGetHandledEventsLocked':
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c:82:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     uint32_t u32AllowedGuestCaps = pSession->u32AquiredGuestCaps | (VMMDEV_EVENT_VALID_EVENT_MASK & ~pDevExt->u32AcquireModeGuestCaps);
     ^
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c:2660:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     uint32_t fGenFakeEvents = 0;
     ^
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c: In function 'VBoxGuestCommonIOCtl':
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c:2807:9: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
         VBoxGuestHGCMCallInfoTimed *pInfo = (VBoxGuestHGCMCallInfoTimed *)pvData;
         ^
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest2.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/GenericRequest.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/HGCMInternal.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/Init.o
/Init.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/PhysHeap.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/SysHlp.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VMMDev.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/alloc-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/initterm-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/memobj-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/mpnotification-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/powernotification-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/alloc-r0drv-linux.o
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/alloc-r0drv-linux.c: In function 'rtR0MemAllocExecVmArea':

/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/alloc-r0drv-linux.c:194:9: warning: passing argument 3 of 'map_vm_area' from incompatible pointer type [enabled by default]
         if (!map_vm_area(pVmArea, PAGE_KERNEL_EXEC, &papPagesIterator))
         ^
In file included from ./arch/x86/include/asm/io.h:200:0,
                 from ./arch/x86/include/asm/realmode.h:5,
                 from ./arch/x86/include/asm/acpi.h:33,
                 from ./arch/x86/include/asm/fixmap.h:19,
                 from ./arch/x86/include/asm/apic.h:12,
                 from ./arch/x86/include/asm/smp.h:12,
                 from ./arch/x86/include/asm/mmzone_64.h:10,
                 from ./arch/x86/include/asm/mmzone.h:4,
                 from include/linux/mmzone.h:912,
                 from include/linux/gfp.h:5,
                 from include/linux/slab.h:14,
                 from /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/the-linux-kernel.h:72,
                 from /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/alloc-r0drv-linux.c:31:
include/linux/vmalloc.h:115:12: note: expected 'struct page **' but argument is of type 'struct page ***'
 extern int map_vm_area(struct vm_struct *area, pgprot_t prot,
            ^
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/assert-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/initterm-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/memobj-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/memuserkernel-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/mp-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/mpnotification-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/process-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/semevent-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/semeventmulti-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/semfastmutex-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/semmutex-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/spinlock-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/thread-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/thread2-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/time-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/RTLogWriteDebugger-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/generic/semspinmutex-r0drv-generic.o
/common/alloc/alloc.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/err/RTErrConvertFromErrno.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/err/RTErrConvertToErrno.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/log.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logellipsis.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logrel.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logrelellipsis.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logcom.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logformat.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg1Weak.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg1Weak.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2Add.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2AddWeak.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2AddWeakV.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2Weak.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2WeakV.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/assert.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/thread.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/RTStrCopy.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/RTStrCopyP.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/RTStrCopyP.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strformat.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strformatrt.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strformattype.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strprintf.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strtonum.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/table/avlpv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/time/time.o
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/time/time.c: In function 'VBoxGuest_RTTimeFromString':
...
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf/dirops.c:129:29: error: 'struct file' has no member named 'f_dentry'
     sf_g = GET_GLOB_INFO(dir->f_dentry->d_inode->i_sb);
                             ^
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf/vfsmod.h:144:60: note: in definition of macro 'GET_GLOB_INFO'
 # define GET_GLOB_INFO(sb)       ((struct sf_glob_info *) (sb)->s_fs_info)
                                                            ^
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf/dirops.c:135:16: error: 'struct file' has no member named 'f_dentry'
     inode = dir->f_dentry->d_inode;
                ^
make[2]: *** [/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf/dirops.o] Error 1
make[1]: *** [/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf] Error 2
make: *** [_module_/var/lib/dkms/virtualbox-guest/4.3.10/build] Error 2
make: Leaving directory `/usr/src/linux-headers-3.19.0-25-generic'
~

How can I fix this problem?

A: There is another way to do this, which I prefer.

*

*Open Terminal

*sudo apt-get update && upgrade -y

*Once complete run: sudo apt-get install build-essential

*On the running VirtualBox window along the top select Devices > Insert Guest addons cd image.

*In your terminal navigate to: cd /media/USERNAME/ and run ls to then see what the virtual disc is called in my case it is VBOXADDITIONS_5.0.10_104061 and cd to it.

*Now in the folder run sudo sh ./VBoxLinuxAdditions.run

*Wait for it to finish

*Reboot and Enjoy.

Let me know how you get on.

A: Finally, I managed to solve the problem. In my case, the problem was that I was running older VirtualBox and after updating it, the command virtualbox-guest-dkms worked and I could switch to full screen mode.


text:
Q: Vuex internal dependencies What is the best practice to solve such situation:

*

*state of one vuex component depends on state of another

*this refresh of the first component must be done via action (asynchronous operations)

Now I do it from the visual vue component, in the place, where mutation of the second vuex component is commited, after the commitment. But it seems to me not nice practice to place vuex internal dependencies in visual components. How is it possible to place dependencies logic in vuex code?


text:
Q: Interesting calculus book (Yeah, I've checked all similar questions, and this is not a duplicate)
I'm learning calculus for the first time, and all books I'm seeing is roughly falling into two categories:
a. Contains interesting problems which requires more than half hour to solve, but either doesn't covers the history (so you keep on wondering how on earth one would think of that/what the hell is the point behind this definition), or doesn't covers the conceptual difficulties (eg Understanding what "infinitesemals" of $dx$ actually means, why you can or can't treat $\frac{dx}{dy}$ as a fraction etc).
b. Contains interesting problems and explains motivations and intuition and all that, but is way too hard and requires way too much prerequisites to read.
Is there a good calculus book which doesn't requires you having extra background in calculus, (so develops it from scratch), but contains interesting and hard problems, and also provides the historical background and the intuitions ?
Bonus (but not strictly necessary) if it contains hints to the hard problems.
$:)$

A: My favorite book is the one by Courant. This is part 2.
A modern book that I like is Lax/Terrell.
As for the history, Toeplitz's book is very good, but also very detailed.

A: On OP's request, I am converting my comment into an answer.

I would suggest you to grab a copy of G H Hardy's A Course of Pure Mathematics 10th edition. It should be available free of cost online if you search enough. This book is especially suitable for young students (age 15-16 years) who are totally new to calculus. And it is meant for self study.
The distinguishing feature of the book is the focus on rigor. This is exactly how a mathematics textbook should be written. The concepts of calculus are developed from scratch. The book expects a basic knowledge of algebra (complex numbers are developed in the book itself) and a bare minimum geometry to understand some geometric arguments.
The book also contains very challenging problems (mostly from the infamous Mathematical Tripos which Hardy despised) and Hardy provides hints / solutions to the most difficult problems. The simpler problems are designed to help students learn the application of concepts studied so far.
If one really studies this book completely (even without solving all the challenging problems) one will never face any conceptual difficulties in calculus. I believe much of the conceptual difficulties in calculus are a result of crappy calculus textbooks and such crap is published purposely to justify a first course in real analysis at undergraduate level.
Note: The book is an old classic and some notation / terminology may be outdated. You need to map it with the corresponding new stuff.

A review of this book with some personal touch is available here.


text:
Q: Amazon S3 Forbidden 403 Во время прохождения 13 главы Rails Tutorial столкнулся с невозможностью запустить загрузку картинок на Heroku с помощью CarrierWave, Fog и AWS S3. Каждый раз сталкиваюсь с одной и той же ошибкой:
2019-04-22T16:45:52.736948+00:00 heroku[router]: at=info method=POST path="/microposts" host=anikeef-sample-app.herokuapp.com request_id=b78cf418-1931-42e0-89e5-4e92af697ed4 fwd="95.189.192.65" dyno=web.1 connect=0ms service=1525ms status=500 bytes=1891 protocol=https
2019-04-22T16:45:52.733710+00:00 app[web.1]: D, [2019-04-22T16:45:52.733568 #8] DEBUG -- : [b78cf418-1931-42e0-89e5-4e92af697ed4]    (2.3ms)  ROLLBACK
2019-04-22T16:45:52.734152+00:00 app[web.1]: I, [2019-04-22T16:45:52.734037 #8]  INFO -- : [b78cf418-1931-42e0-89e5-4e92af697ed4] Completed 500 Internal Server Error in 511ms (ActiveRecord: 4.9ms)
2019-04-22T16:45:52.735688+00:00 app[web.1]: F, [2019-04-22T16:45:52.735602 #8] FATAL -- : [b78cf418-1931-42e0-89e5-4e92af697ed4]
2019-04-22T16:45:52.735761+00:00 app[web.1]: F, [2019-04-22T16:45:52.735692 #8] FATAL -- : [b78cf418-1931-42e0-89e5-4e92af697ed4] Excon::Error::Forbidden (Expected(200) <=> Actual(403 Forbidden)
2019-04-22T16:45:52.735764+00:00 app[web.1]: excon.error.response
2019-04-22T16:45:52.735769+00:00 app[web.1]: :body          => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error>AccessDenied<Message>Access Denied</Message><RequestId>1E231D51512F5FCD</RequestId><HostId>viioFqYRTbP07frHGpcfgl+xzN4cZqFMs37oY/dl0kHnzBNxpmoKNgjbQpxvG8kVCxaxFAxGFr0=</HostId></Error>"
2019-04-22T16:45:52.735770+00:00 app[web.1]: :cookies       => [
2019-04-22T16:45:52.735772+00:00 app[web.1]: ]
2019-04-22T16:45:52.735774+00:00 app[web.1]: :headers       => {
2019-04-22T16:45:52.735776+00:00 app[web.1]: "Connection"       => "close"
2019-04-22T16:45:52.735777+00:00 app[web.1]: "Content-Type"     => "application/xml"
2019-04-22T16:45:52.735779+00:00 app[web.1]: "Date"             => "Mon, 22 Apr 2019 16:45:51 GMT"
2019-04-22T16:45:52.735781+00:00 app[web.1]: "Server"           => "AmazonS3"
2019-04-22T16:45:52.735783+00:00 app[web.1]: "x-amz-id-2"       => "viioFqYRTbP07frHGpcfgl+xzN4cZqFMs37oY/dl0kHnzBNxpmoKNgjbQpxvG8kVCxaxFAxGFr0="
2019-04-22T16:45:52.735784+00:00 app[web.1]: "x-amz-request-id" => "1E231D51512F5FCD"
2019-04-22T16:45:52.735786+00:00 app[web.1]: }
2019-04-22T16:45:52.735788+00:00 app[web.1]: :host          => "anikeef-sample-app2.s3-us-east-2.amazonaws.com"
2019-04-22T16:45:52.735789+00:00 app[web.1]: :local_address => "172.17.49.150"
2019-04-22T16:45:52.735791+00:00 app[web.1]: :local_port    => 43620
2019-04-22T16:45:52.735793+00:00 app[web.1]: :path          => "/uploads/micropost/picture/304/sunrise-1756274_1920.jpg"
2019-04-22T16:45:52.735795+00:00 app[web.1]: :port          => 443
2019-04-22T16:45:52.735796+00:00 app[web.1]: :reason_phrase => "Forbidden"
2019-04-22T16:45:52.735798+00:00 app[web.1]: :remote_ip     => "52.219.104.80"
2019-04-22T16:45:52.735800+00:00 app[web.1]: :status        => 403
2019-04-22T16:45:52.735801+00:00 app[web.1]: :status_line   => "HTTP/1.1 403 Forbidden\r\n"
2019-04-22T16:45:52.735803+00:00 app[web.1]: ):
2019-04-22T16:45:52.735927+00:00 app[web.1]: F, [2019-04-22T16:45:52.735866 #8] FATAL -- : [b78cf418-1931-42e0-89e5-4e92af697ed4]
2019-04-22T16:45:52.736039+00:00 app[web.1]: F, [2019-04-22T16:45:52.735966 #8] FATAL -- : [b78cf418-1931-42e0-89e5-4e92af697ed4] app/controllers/microposts_controller.rb:7:in `create'

Так сейчас выглядит config/initializers/fog.rb
if Rails.env.production?
  CarrierWave.configure do |config|
    config.fog_provider = 'fog/aws'
    config.fog_credentials = {
      :provider => "AWS",
      :aws_access_key_id => ENV["S3_ACCESS_KEY"],
      :aws_secret_access_key => ENV["S3_SECRET_KEY"],
      :region => ENV["S3_REGION"]
    }
    config.storage = :fog
    config.fog_directory = ENV["S3_BUCKET"]
    config.cache_dir = "#{Rails.root}/tmp/uploads"
  end
end

Судя по ошибке, проблема должна исходить от AWS. Я пробовал применять разные права пользователям IAM, в том числе AmazonS3FullAccess и AdministratorAccess.
Я пересмотрел все найденные вопросы на SO, но абсолютно ничего мне не помогло, поэтому буду очень благодарен за любую помощь.

A: Все наконец-то заработало только после того, как отключил пункты "Block new public ACLs and uploading public objects" и "Remove public access granted through public ACLs" в разделе S3 >  > Permissions


text:
Q: how to setup wxwidgets on windows for visual studio 2005 i am try to do some GUI stuff and i want to setup wxWidget for visual studio 2005 on windows 7. I read may tutorial and help in last few days but all of them are showing different ways. and none of them work for me. in include c:/wxWidgets-2.9.4/include and /lib directories to visual studio but still it showing wx/setup.h not found.
can any one please give a tutorial for setup wxWidget from scratch.(from downloading required packages to full working example). because i am also confuse which one i should download, they provide many zip forders.

A: @tinman's recipe allows you to build eveything, but it takes a long time.
A simpler recipe, which only builds the necessary library:

*

*Do the installation using the setup package.

*Find the microsoft visual studio build folder.  On my installation this is C:\wxWidgets-2.9.n\build\msw

*Find the solution for your version of visual studio ( e.g. wx_vc8.sln ) and open it.

*Select the configuration you intend to use when building your applications.  ( e.g. DLL Release )

*Build the solution.
Done.  It should take about five minutes on any reasonably powerful machine.

A: The reason there are many zip archives is that from 2.9 onwards they are providing pre-built binary packages for each MSVC version. I have never used these so I cannot comment on those, but they might save you a lot of time building the sources and give you an official library.
I have used the MSW setup package and built from source. This is what I do and it works well for me (except I currently use wx292, VS2008 and Windows 7).
Download the wxWidgets 2.9.4 MSW setup package.
Install it. I assume it will create a directory in c:\wxWidgets-2.9.4.
Create a batch file c:\wxwidgets-2.9.4\build.bat with the following contents. You should replace myvendor with your name so it is clear that it is not an official wxWidgets library build (it will be put in the filenames, so avoid spaces).
@echo off
PUSHD build\msw
call :make

cd ..\..\samples
call :make

cd ..\demos
call :make

cd ..\utils
call :make

POPD
GOTO :EOF

@REM Perform builds with all desired configurations
:make
@REM x86 debug & release multiple DLLs Unicode
nmake -f makefile.vc MONOLITHIC=0 SHARED=1 UNICODE=1 BUILD=debug VENDOR=myvendor
nmake -f makefile.vc MONOLITHIC=0 SHARED=1 UNICODE=1 BUILD=release VENDOR=myvendor

@REM x86 debug & release multiple static libs Unicode
nmake -f makefile.vc MONOLITHIC=0 SHARED=0 UNICODE=1 BUILD=debug VENDOR=myvendor
nmake -f makefile.vc MONOLITHIC=0 SHARED=0 UNICODE=1 BUILD=release VENDOR=myvendor

Open a Visual Studio 2005 command prompt from the Start Menu. This will set up the path to your compiler and libraries correctly.
Change directory to wxWidgets: cd c:\wxWidgets-2.9.4.
Run the build.bat
It should complete after a few hours depending on your computer specifications, or you can REM out the builds for the samples, utils and demos to reduce the time (thanks @ravenspoint). You can also see the examples in c:\wxWidgets-2.9.4\samples and get the Visual Studio project settings from the sample projects to use in your own projects (for example C:\wxWidgets-2.9.4\samples\dialogs\dialogs_vc8.vcproj).
After building the library you will end up with some additional directories under C:\wxWidgets-2.9.4\lib which contains the built libraries, dlls and any build specific headers for that variant. The following directories are created from the builds in my batch script and are tagged with the toolset (vc for Visual C in this case, but could be version specific, e.g. vc80 or a fixed version depending on your build settings) and the type of library. msw in the directory and filenames means MicroSoft Windows. u in the directory and filenames means Unicode. d at the end of directory and filenames means Debug.

*

*C:\wxWidgets-2.9.4\lib\vc_lib: Visual C (vc) Static library (lib) versions of wxWidgets

*

*C:\wxWidgets-2.9.4\lib\vc_lib\mwsu: MicroSoft Windows Unicode specific files

*C:\wxWidgets-2.9.4\lib\vc_lib\mwsud: MicroSoft Windows Unicode Debug specific files

*Also contains a mixture of static libraries for release and debug

*C:\wxWidgets-2.9.4\lib\vc_dll: Visual C (vc) DLL (dll) versions of wxWidgets

*

*C:\wxWidgets-2.9.4\dll\vc_lib\mwsu: MicroSoft Windows Unicode specific files

*C:\wxWidgets-2.9.4\dll\vc_lib\mwsud: MicroSoft Windows Unicode Debug specific files

*Also contains a mixture of DLLs and import libraries for release and debug

In order to use the newly built libraries in your own projects you can follow these steps (I use VS2008 so some of the configuration names might be slightly different):
When you create a new project you need to go to the project properties.
Under Configuration properties -> General -> Environment add the following (so your application can find the DLLs) if you are using the DLLs:
PATH=C:\wxWidgets-2.9.4\lib\vc_dll

Under C/C++ -> General -> Additional Include Directories you need to add the wxWidgets includes in the following order:

*

*"C:\wxWidgets-2.9.4\include\msvc"

*"C:\wxWidgets-2.9.4\include"

The reason for including directory 1 first is that there is a wx\setup.h in that directory. When you include that it tries to determine what compiler, type of library (static or DLL), whether you are using Unicode or not and whether it is debug or release and it automatically includes the correct real wx/setup.h from the one of the subdirectories of C:\wxWidgets-2.9.4\lib.
You then need to go to C/C++ -> Preprocessor -> Preprocessor Definitions and add the following lines:
__WXMSW__

If you want to use the DLL version of wxWidgets instead of the static library you need to add the following line:
WXUSINGDLL

Under Linker -> General -> Additional Linker Directories you need to add the following path if you are using the static libraries:
"C:\wxWidgets-2.9.4\lib\vc_lib"

Or the following path if you are using the DLLs:
"C:\wxWidgets-2.9.4\lib\vc_dll"

In Linker -> Input -> Additional Dependancies you will probably need to add at least the following:
comctl32.lib rpcrt4.lib

And under Resources -> General -> Additional Include Directories you will need to add the following path:
C:\wxWidgets-2.9.4\include


text:
Q: How to escape '@' from sign in username I tried to connect to remote mysql server using mysqlsh, however the current username containers @ so
mysqlsh mysql://userid@salesdeparment:@123.45.678.123:3306/ ....

reported an error
Invalid URI: Illegal character [@] found at position xxx

Because the first @ is actually part of the username userid@salesdeparment, only second @ denote the server ip.


text:
Q: PHP: Calculation on 2 Dimensional Array I have 2 arrays as below:
array(2) { ["2018-05"]=> string(2) "15" ["2018-06"]=> string(3) "100" }
array(1) { ["2018-05"]=> string(1) "5" }

I wish to do calculation to find the difference so it will return:
array(2) { ["2018-05"]=> string(2) "10" ["2018-06"]=> string(3) "100" }

As this is a multidimensional array, I'm not sure how to show the "year-month" as the array key, can someone please enlighten me?
Thanks.

A: Try this code
$a = ["2018-05"=> "15", "2018-06"=> "100" ];
$b = ["2018-05"=> "5"];

$c = $a;

foreach($b as $k=> $i){
    if(array_key_exists($k,$c)){
        $c[$k] = $a[$k] - $b[$k];
    }
    else{
        $c[$k] = 0-$i;
    }
}

A: Assuming that you don't want to take into account same values and you want absolute values, this should work
$els[]["2018-05"]="15";
$els[]["2018-06"]="100";
$els[]["2018-05"]="5" ;
$els[]["2018-05"]="1" ;//added
$els[]["2018-06"]="50";//added

    $newEls = [];

    foreach($els as $key => $el){

        $newEls[key($el)] = $el[key($el)];

          foreach($els as $key2 => $el2){

              if(key($els[$key]) == key($els[$key2]) && $els[$key][key($els[$key])] != $els[$key2][key($els[$key2])]){

              $newEls[key($el)] = abs($els[$key][key($els[$key])] - $els[$key2][key($els[$key2])]);

              }

        }

        }

    echo "<pre>";print_r($newEls);

If you want to keep same values like [0]["2018-05"]="15" and [1]["2018-05"]="15" it's necessary another approach. Because maybe the best approach is to use queues.

A: <?php

$a = ['2018-05'=> '15', '2018-06'=> '100'];
$b = ['2018-05'=> '5'];

$years = array_map(NULL, $a, $b);
$years = array_combine(array_keys($a), $years);

$differences = array_map(function ($year_diffs) : float {

    // Did we get a pair to compare?
    $has_diff = isset($year_diffs[0]) and isset($year_diffs[1]);

    // If we got a pair then compare, else assume we got one.
    $diff = $has_diff ? abs($year_diffs[0] - $year_diffs[1]) : $year_diffs[0];

    return $diff;
}, $years);

var_dump($differences);

https://3v4l.org/BSEui
I've had to assume a few things

*

*$a will always contain the dominate key

*Both arrays contain the same keys as each other without gaps

*There will always be one or two difference numbers

I feel like whatever your real system is, probably violates the above criteria but you'd need to provide more context for a different solution


text:
Q: Draw: vector drawing & technical illustration application I found this very sophisticated Draw application created entirely with the Wolfram Language:
https://github.com/shdlbwr/draw

The documentation is available here:
http://community.wolfram.com/groups/-/m/t/963158
When I execute Draw[] I get the following warning, although I am using Mathematica 11.0.1:

When I create a drawing, save it as a notebook file and execute this file nothing happens, no drawing is seen.
Do you have experience with this application? How can I save drawings e.g. in png format?

A: I just downloaded and tried it. I think this is what one is supposed to do: 1. After you make the drawing first time, like this:

then save the notebook. But the notebook is not not meant to be the drawing in graphics format of course. To obtain the actual drawing, use the copy graphics to clipboard button

Then paste the image from the clipboard to your any graphics program, say paint.exe  and then save it as png or jpg, etc...

The notebook you save, just contains Mathematica code for the drawing itself. Which you open using the menu:

When I open the saved notebook, the drawing is drawn again inside Mathematica Draw app with no problem.
See if this works for you.  Btw, I am using 11.0.1 and I do not get the warning you show.


text:
Q: For Files in .... mysql update I have a batch process that looks like this:
for /F %%a in (Files_april.txt) do (BlaBla_filedecryptionv3.exe -i FullRefresh_%%a.afi -k keys.txt -l customer_layout.txt -o customer_%%a.txt -t d -d \124)
mysql -q -h beast --port=3310 -u jxxxx --password="xxxx" di < load_april.sql
mysql -q -h beast --port=3310 -u xxxxx --password="xxxx" di < exportapril.sql > april.txt

I was wondering if it is possible to take the same idea of the %%a that I used to decrypt the files in a mysql qry.
The load_april.sql looks like:
    load data local infile 'W:\\New DLP\\customer_20140331_0.txt' into table  di.dlp_monthly_201404
fields terminated by '|'
lines terminated by '\r\n';
    load data local infile 'W:\\New DLP\\customer_20140331_1.txt' into table  di.dlp_monthly_201404
fields terminated by '|'
lines terminated by '\r\n';

Where the "20140331_0" and "20140331_1" are what I want replaced so it would be something like this:
load data local infile 'W:\\New DLP\\customer_%%a.txt' into table  di.dlp_monthly_201404
    fields terminated by '|'
    lines terminated by '\r\n';

Is this possible? Any help would be great.

A: You can include an sql query directly on the mysql command line, rather than loading it from a file.  The resulting file would look something like:
for /F %%a [...]
   mysql [...] -e "load data local infile 'path\\%%a.txt' into [...]"
   [...]

Where [...] needs to be expanded according to your needs.


text:
Q: How to detect a filtering is done in Kendo? After filtering being done, I have to select a second page/do something. How can I detect it?
Thank you!

A: Please try with the below code snippet.
<!DOCTYPE html>

    <title>Jayesh Goyani</title>
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.112/styles/kendo.common.min.css">
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.112/styles/kendo.rtl.min.css">
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.112/styles/kendo.default.min.css">
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.112/styles/kendo.mobile.all.min.css">

Let me know if any concern.


text:
Q: Is there a 'natural' bijection between the rational and the natural numbers? I've seen various bijections between the rationals and the naturals (the first being Cantor's Pairing function (the snake looking one) and another being the Calkin Wilf Tree) many times; but I can always remember being slightly disturbed by the lack of 'naturality' in the bijection (before I even knew formally how to express 'naturality'); in some sense the bijections always seemed a bit arbitrary and not inherently part of the structure of the rationals/the naturals.
Recently I've been exposed to some notion of 'naturality' in Category Theory, and loosely I have come to understand a 'natural' bijection as one that in some sense requires no choice of any kind, and arises inherently from the structures involved. Is there a way of talking about the 'naturality' of the bijections between the rationals and the naturals? I'm not even sure which Categories are at play in this scenario, or even if this is a well defined question or not.

A: It is a common misconception that a natural isomorphism (in the categorical sense) is an isomorphism $A \to B$ between two single objects $A,B$ which is natural in some sense. This is not true. The concept of a natural isomorphism applies to functors between two categories. In other words, a natural isomorphism is really a bunch of isomorphisms $F(x) \to G(x)$, one for each object $x$ of the domain of $F$ and $G$. Of course, any object can be regarded as a constant functor, and then any isomorphism between two objects leads to a natural isomorphism between the associated functors, but this is rather boring and has nothing to do with naturality in the common sense.
Your question is about isomorphisms between $\mathbb{N}$ and $\mathbb{Q}$ in the category of sets. [At this point, let me mention that there is no isomorphism between these objects in more interesting categories such as commutative monoids, ordered sets, topological spaces, etc.] As I've said, it does not make much sense to speak of natural isomorphisms here, because we have no functors given. But it is possible to consider the following two functors:
Consider the category $\mathcal{C}$ of semirings with isomorphisms of semirings, and the category $\mathcal{D}$ of sets and isomorphisms of sets. There is a forgetful functor $F : \mathcal{C} \to \mathcal{D}$, and there is a functor $G : \mathcal{C} \to \mathcal{D}$ which maps a semiring to the underlying set of the total ring of fractions of its Grothendieck ring (given by adjoining additive inverses and then multiplicative inverses by regular elements). Thus, $F(\mathbb{N},+,\cdot)=\mathbb{N}$ and $G(\mathbb{N},+,\cdot)=\mathbb{Q}$. Now one might ask if there is a natural isomorphism $F \to G$. But this is not the case.

A: In an earlier post, I have described a bijection between $\mathbb{N}$ and $\mathbb{Q}$ which I consider somewhat less artificial than e.g. Cantor's pairing function. Perhaps it is something like this you are looking for?


text:
Q: "Related Questions" should be "Possible Answers," or at least "Similar Questions" I'm surprised the section containing related questions is called Related Questions, and not Possible Answers, Similar Questions or Possible Duplicates; Related Questions doesn't suggest to me they may contain the answer to my question, which is the only reason why I assume they're listed.
EDIT: Yes, as Jefromi pointed out, I am referring to the section titled Related Questions that appears when the focus leaves from the Title textbox while editing, not the Related questions on the RHS of the page.

A: It's not the only reason they're listed, I think that's a false assumption.  Related topics may not answer your question but may answer your next question or provide you info/tips that'll help on the topic you're on now and later.
Look at it this way, if your assumption was correct, why not call the section "Duplicates"?

A: I have no particular feelings on this, but isn't this just arguing semantics?


text:
Q: JQuery: How to Use IF statement correctly? I have confuse how to use IF statement correctly for this case.
I have some command like:
if($('#use').val() == "choose") {
        //dialog show
        }

i want if $('#use') value like "boom","choose","foo","bar" can open the dialog.
How to write the correct command for this case?

its mean (by logical thinking):
if(#use) value "choose" or "boom" or "foo" or "bar" then dialog show

A: You have an extra parenthesis. "choose")) { should be "choose") {.
if ($('#use').val() == "choose") {
    //dialog show
}

Or splitting it into multiple lines might make the intention clearer.
var canOpenDialog = $('#use').val() == "choose";
if (canOpenDialog) {
    //dialog show
}

UPDATE for your edit. You can use $.inArray to check for multiple values.
var options = ["boom","choose","foo","bar"];

var canOpenDialog = $.inArray(($('#use').val()),options) != -1;
if (canOpenDialog) {
    //dialog show
}

A: var useValue = $('#use').val();
if (useValue == "choose" || useValue == "boom" || useValue == "foo" || useValue == "bar") {
  //do stuff
}

A: You could also use $.inArray().
It will return the index of the searched string in the chosen Array, else return -1
var values = ["boom","choose","foo","bar"];

if ($.inArray($('#use').val(),values) != -1) {
    // do stuff if "boom" is in the array
} else {
    // do stuff if it is not.
}

A: better option is to use $.inArray()
var required= ["boom","choose","foo","bar"];
if ($.inArray(($('#use').val()),required) != -1) {
    // do Whatever you want
}


text:
Q: make new git branch containing full history of only some files I'm in the middle of a refactor that will eventually separate out "the core model" from the API i've built around it.
I have the current (simplified) directory structure:
/root
|-model_core.py
|-model_configuration.py
|-model_frontend.py
|-plot_model.py
|-cool_use_for_model.py

How do I make a new branch, model-core, that contains model_core.pyand model_configuration.py only, as well as their full commit history from the current branch?

A: You have few options to do it:
http://blogs.atlassian.com/2014/04/tear-apart-repository-git-way/
https://lostechies.com/johnteague/2014/04/04/using-git-subtrees-to-split-a-repository/
The main 2 optins are:
git filter-branch

git subtree split --prefix=lib -b split

As mentioned above lets explain in details each options
filter-branch will loop over each commit and then you can checkout only the given files while git subteree split will be a better option in your case.
Explaining both of the option so you can choose which one you prefer.

Sample code:
filter-branch
# Filter the master branch to your directory and remove empty commits
git filter-branch --prune-empty --subdirectory-filter YOUR_FOLDER_NAME filter_from_branch

This will checkout all your desired files from the given folder to the current directory

subtree split

git subtree
git-subtree - Merge subtrees together or split repository into subtrees

git subtree split -P <name-of-folder> -b <name-of-new-branch>

A: I assume you're looking to remove the other files from the branch's history entirely, rather than just a git rm {model_frontend,plot_model,cool_use_for_model,}.py commit. If that covers what you need, though, definitely just do that rather than messing around with your repo's history.
Fair warning: Because this involves rewriting the files out of old commits, your git history will be rewritten and the branches will not agree on the contents of commits. This can make things messy. If you don't know what you're doing, do not do this.
That said, if you create the branch my-core-branch to do this in, then git filter-branch --tree-filter 'rm -f model_frontend.py plot_model.py cool_use_for_model.py' my-core-branch will rewrite history in my-core-branch to remove those files, but leave your other branches' history. The hashes for commits touching those files and also files you're not deleting will no longer match between branches, obviously, so again, for any git newbies reading this, use at your own risk.


text:
Q: Can't Compile Using GCD function calls I am trying to compile a Desktop OS X Cocoa application:
dispatch_sync(dispatch_get_main_queue(), ^{ NSLog(@"Hello World"); });

However, I am getting the following compile time error:
implicit declaration of function dispatch_sync
I have imported these lines:
#import <dispatch/dispatch.h>
#import <dispatch/queue.h>
#import <dispatch/base.h>

The Base SDK is set to 10.6. Anything else to look for? Am I missing an import?
Any ideas?

A: hmm, you shouldn't need to do anything as GCD is part of libSystem and thus should get it for free. Have you set your deployment target to something earlier than 10.6?

A: Had to make sure compiler was set to LLVM GCC 4.2 (was GCC 4.0)


text:
Q: Detecting intervals of inactivity in the tty? (to simulate setterm --blank in fbterm) setterm --blank n allows me to configure the virtual terminal to automatically shut the display off after n minutes of inactivity. Unfortunately, I spend all my time in fbterm, where setterm does not apply.
I've found that I can manually shut the display off with
$ sudo sh -c 'echo 1 > /sys/devices/pci0000\:00/0000\:00\:10.0/0000\:02\:00.0/graphics/fb0/blank'

(and echo 0 to restore it).
Is there any way to detect periods of inactivity in the tty/fbterm, so that I can create a script to simulate a setterm --blank setting?


text:
Q: FacebookAuthenticationResult FacebookOAuthClientAuthorizer not found? I just download the facebook c# sdk.  I am trying to get the facebook silverlight example to work.
I am looking at CSSilverlightInBrowser
When I clicked on the "login" button, it redirect to the file
slfbinbrowserlogin.aspx
and then my browser just said "Compile Error"
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0246: The type or namespace name 'FacebookAuthenticationResult' could not be found (are you missing a using directive or an assembly reference?)
Am I missing out somthing?
thanks
diing


text:
Q: How to use array.push to add value to an array? I would like to add a value with array.push to my first element of array [0] to the field yesterday, I don't know very well what the structure is to be able to add this value. try the following way
var cumpleaños = [
  {
    ayer: "",
  },
  {
    hoy: "12-07-20",
}  ,
  {
    mañana: "12-08-20"
}
];
cumpleaños.push([0].ayer.("12-06-20"))
console.log(cumpleaños[0].ayer)

Thank you very much for the help!

A: You don't need to push anything since you're not adding a new value, you're just modifying an existing value:
cumpleaños[0].ayer = "12-06-20";

As a side note, your data structure would be much more effectively represented by a single object not inside an array:
const cumpleaños = {
    ayer: "12-06-20",
    hoy: "12-07-20",
    mañana: "12-08-20"
};

A: You would do assignment to the first element of the array. (If the oder is always the same)
cumpleaños[0].ayer = "12-06-20"


text:
Q: User interactions on UIPickerview outside of its superview in swift I have UIPickerView inside my view hierarchy, but its not directly inside of my view, when I try to interact with Picker View it doesn't respond. I've tried some answers from StackOverflow but they did not work.
This is one of the answers I found and I thought it would work, I've tried it but it did not work, there is a swift answer in this article and i tried that one.
Capturing touches on a subview outside the frame of its superview using hitTest:withEvent:
Could anybody help me? I can give you some more information if you'll need it
Any Suggestions or links to follow?


text:
Q: Как использовать переданный в функцию аргумент при использовании селектора? Если несложно, скажите, как можно вставить аргумент в селектор?
Ситуация такая: есть функция, которая принимает и создает элемент внутри элемента. При этом id внутреннего элемента будет меняться item1, item2, item3... и т.д., проходя через цикл.
Возможно на примере будет яснее:
Как есть в исполняемом состоянии,но, увы, без приема аргумента (id = item) -
  function createElementsInside() {
    $("#bb-bookblock").append("
1 блок
");
    $("#bb-bookblock").children("#item1").append("
Контент
");
    }

Хотелось бы так
var itemId = 'item1';

function createElementsInside(itemId) {

  $("#bb-bookblock").append("
1 блок
");
  $("#bb-bookblock").children( itemId ).append("
 Контент
");

}

A: var itemId = 'item1';

function createElementsInside(itemId) {
  $("#bb-bookblock").append("
1 блок
");
  $("#bb-bookblock").children("#" + itemId).append("
 Контент
");
}


text:
Q: How do I display an array using XUL elements like a table in HTML I have an array
data = [{'name':'Bob','email':'bob@gmail.com'}]
How can I render this array using XUL elements (like a table in HTML)?
I'm using pure Javascript (do not using any JS framework)

A: How do you want it to look? There's xul:listbox (example), xul:tree, and you can also use HTML table if it's exactly what you need.


text:
Q: Inserting Entity into SQL Compact 4 Table with Identity column using LINQPad I'm trying to insert new records into a SQL CE 4 database with LINQPad and having problems with the identity problem of a table. Let's say I have this simple table for instance:
PEOPLE
Id int IDENTITY(1,1) NOT NULL,
Name nvarchar(100) NOT NULL

I may be doing things the wrong way but I tried this in LINQPad
People person = new Person { Name = "Bob" };
People.InsertOnSubmit(person);
SubmitChanges();

But I get a SqlCeException stating
"The colum cannot be modified. [ Column name = Id ]"

I can insert a record with SQL just fine, that works with no errors from SQL CE or its data provider and SQL CE sets the Id column for me which is what I'm wanting
INSERT INTO PEOPLE (Name) VALUES ('Bob');

Is there another step that I'm missing? I'm not even sure if its a LINQPad issue but thought I'd ask anyways since that's what I'm trying this code with right now.

A: What do you get if you run this in LinqPad
(from dm in this.Mapping.GetTable(typeof(People)).RowType.DataMembers
    select new  { dm.DbType, dm.Name, dm.IsPrimaryKey , dm.IsDbGenerated }
 ).Dump();

In particular, as I understand it,  IsDbGenerated should be true for the id column.
I have a SQL CE 3.5 data file that I have used previously in LinqPad and looking at the SQL generated for inserts it does not mention id

A: This is probably the issue with dbml file. Check whether the column is marked as identity(or whatever this is called in L2S). The thing is that Id cannot appear in the insert query.


text:
Q: Adding an argument to a mathematical function I'm trying to automate a process to produce interpolated geochemical maps.
I've created a loop that essentially starts at column #13 and loops through until #67.
However, part of the IDW code requires the header of the current column for the respective geochemical parameters to be mapped.
For instance; column #13's header is "Ag_ppm", so the original code read:
    LogSr.idw = idw(log10("Ag_ppm") ~ 1 , locations=NGSA.SPDF, newdata=NGSA.grid,
                   maxdist=15000, nmin=4)

I've been able to obtain the header of the column in interest within each loop using (where i increases by 1 each loop; 13, 14, 15 etc.):
    coln <- colnames(NGSA.df[i])

However, when I simply substitute the "Ag_ppm" to coln, the line fails with a given error. I've tried various approaches including paste, although everything still results in the same error.
    LogSr.idw = idw(log10(coln) ~ 1, locations=NGSA.SPDF, newdata=NGSA.grid,
                    maxdist=15000, nmin=4)

Error in log10(coln) : non-numeric argument to mathematical function

Is there a reasonably simple approach using the current method?

A: It is surprising to me that log10("Ag_ppm") doesn't throw the same error, but I have often overcome this problem using get:
LogSr.idw = idw(log10(get(coln)) ~ 1, locations=NGSA.SPDF, newdata=NGSA.grid,
                maxdist=15000, nmin=4)

In most situations, it is a good idea to think of an alternative to using get, but due the the formula (~) here, and the use of the newdata arguemtn, get might be the best solution.


text:
Q: Bandwidth waster algorithm for PHP I am trying to create a software in PHP that can run continuously and keep on wasting bandwidth.
Can anyone one sugggest any solutions.

A: Make a huge file and make it publically accessible then just make a page which loads the image and then calls itself.
(Note this is an infinite loop so you should probably put something in to be able to stop it such as a time constraint or a counter)
Something like this idea might do:
<?php
//waster.php
header('Connection: close');
header('Content-Length: 0');
file_get_contents('http://www.example.com/hugeimage.jpg');
file_get_contents('http://www.example.com/waster.php');

A: In order to waste bandwidth you don't need a continuously running php script. It will waste processing not bandwidth. Just write a PHP script to Display a large Image file and write a utility or script (unix) in a local machine to continuously call that url and download the image and perhaps delete it.
Anyway seems like something evil is going to happen :)

A: Depending on what you are trying to do, you could use a tool like Fiddler to simulate network latency  or slow connection speeds.


text:
Q: Run redux-thunk action without dispatch I am using Redux to manage my app state, and I had an async action made with redux-thunk.
export const login = credentials => dispatch => {
   return doLogin(credentials).then(token => {
      localStorage.setItem('token', token)
      // this dispatch call was there before, but now it has gone,
      // because it is not necessary anymore
      // dispatch({ type: LOGIN_SUCCESS })
   })
}

The thing is that now I have an action which doesn't dispatch any actions into store, just does its job about login and storing token.
Is it okay to have such kind of action? I am not feel so confident about this code, but I don't know how to make it better.

A: You're asking for an opinion on something that doesn't have hard rules, but the rule of thumb is that actions should be a minimal description of something that happened in the application.
Thunkified actions in general are a workaround for this behavior, but in this case it's okay to have this kind of action because even though it doesn't have an effect on Redux state through a reducer, you're using (thunk) middleware to perform side effects, and middleware is designed to respond to actions.
The fact that you're triggering an 'upstream' action that isn't consumed by a reducer downstream doesn't really matter, although it might be a good practice to still dispatch({ type: 'LOGIN_REQUEST' }) at the start and dispatch({ type: 'LOGIN_SUCCESS'}) at the end just so the downstream application has a way to know what is going on if it wants to do something about it later on.

A: There is no rule for that and you don't necessarily need to dispatch any action, but it feels awkward that an action creator dispatches no action at all.
If you really don't need to dispatch any action, perhaps that component shouldn't be connected to Redux at all. An action creator should dispatch actions, if it doesn't, it's not an action creator, it's a function. You could create a simple component with a local function doing that, without bothering to add complexity with Redux.
But if you want to connect it to Redux, it can hardly make any sense to have an action creator that creates no actions. Dispatching actions is what an action creator was designed for.
Try thinking about user experience in this example you've presented in your question. You store your token in the local storage using an action creator or even better with a middleware, but you'll still need to dispatch some actions to let your application know what's going on so it can behave properly, letting your user know what's going on too. For example, I can clearly see room for 3 actions here:

*

*LOGIN_REQUEST: It'll set a state in the store to let the user know the application is trying to login, and disable the inputs so the application doesn't seem to behave crazily. Remember that in localhost the API responses might happen immediately but in a scenario with bad network or overloaded servers it'll take more time.

*LOGIN_SUCCESS: It'll let the application know that a token is now saved into local storage and that the user can be routed to its main page, or just change some elements of the current page to indicate a successful login.

*LOGIN_FAILURE: It'll let the user know that the credentials are invalid and ask him to try again.

Even if you don't route your user to another page after logging in, you might have to change something in the screen to let the user know that login has worked successfully and show an option for logging out. And dispatching actions to have a reducer handle the state mutation for your application is the Redux way to do that.

A: It's matter of taste, but personally I wouldn't tightly couple your action creator with its effects (item set in local storage).
Instead, I'd dispatch an action, e.g. LOGIN_SUCCESS with token passed in as its data. Then have a middleware handling that action type - i.e. set the token in local storage.
This way you buy yourself more flexibility when it comes to how to handle credentials returned by doLogin. You should be pursuing this paradigm of each piece of software doing its own thing and doing it best. So you have a function to authenticate user that then hands over auth token to another piece that knows best how to handle it.


text:
Q: Issue with AngularJS Dropdown I have created AngularJS dependable dropdowns, its working fine with static data from script file. Now how can I bind data to these dropdowns from an URL.  I don't  have a separate url for dropdowns, there is one url delivering everything.
How should I parse the data to get the required output? Iam very new to this,  Will be grateful if anyone can help!!

A: First working Punker here:
http://plnkr.co/edit/okKOeQViflRseqrOYeOY?p=preview
The problem is your question states something and your demo shows something else.
You can directly parse the JSON data on fly using angular then you don't have ng-change function to detect which dropdown was selected. Refer to the below code on how I'm parsing the data in html itself.

                    <am-multiselect class="input-lg"
                                    template-url="multiselect.tmpl.html"
                                    ng-model="selectedcountry" ms-header="Select country" style="width:200px;"
                                    options="c.CountryName for c in table"
                                    ng-change="setState(selectedcountry)"
                                    change="selected()"></am-multiselect>

                    <am-multiselect class="input-lg" multiple="true" ms-selected="{{selectedState.length}} State(s) selected"
                                    ng-model="selectedState" ms-header="Select States"
                                    options="s.STATE for s in table"
                                    ng-change="setCity(selectedState)"
                                    template-url="multiselect.tmpl.html" style="width:500px;"
                                    change="selected()">
                    </am-multiselect>

                    <am-multiselect class="input-lg" multiple="true" ms-selected="{{selectedCity.length}} City(ies) selected"
                                    ng-model="selectedCity" ms-header="Select City"
                                    options="m.CityName for m in table"
                                    template-url="multiselect.tmpl.html" style="width:500px;"
                                    change="selected()"></am-multiselect>

next your second dropdown which is STATE doesn't trigger on change even if the scope is changed.
So use a $watch to see the changes to scope when it happens apply it to the CITY
So your js:
angular.module('app', ['am.multiselect']);

angular.module('app')
  .controller('ctrl', function($scope, $http, $location, $filter,$window) {

    var tableData = {
      "Table": [{
        "CountryUid": 3,
        "CountryName": "INDIA",
        "STATE": "AndraPradesh",
        "CityId": 3,
        "CityName": "Vijayawada"
      }, {
        "CountryUid": 2,
        "CountryName": "USA",
        "STATE": "Florida",
        "CityId": 3,
        "CityName": "Tampa"
      }, {
        "CountryUid": 3,
        "CountryName": "INDIA",
        "STATE": "Assam",
        "CityId": 3,
        "CityName": "Jorhat"
      }]
    };

    var countries = [];
    var states = [];
    var cities = [];

    $scope.table = tableData.Table;
    $scope.countries = countries;
    $scope.states = states;
    $scope.cities = cities;
    $scope.selectedsite = null;
    $scope.selectedState = [];
    $scope.selectedCity = [];

    $scope.setState = function(country) {
      $scope.selectedStates = tableData.Table.filter(function(el) {
        return el.CountryName === country
      });
      $scope.selectedState = $scope.selectedStates.map(function(elm) {return elm.STATE;});
    }
    $scope.setCity = function(state) {
      selectedCity = tableData.Table.filter(function(el) {
        return el.STATE === state
      });
      $scope.selectedCity = selectedCity.map(function(elm) {return elm.CityName;});
    }
    $scope.$watch('selectedStates', function(newVal, oldVal, theScope) {
      $scope.selectedCity = newVal.map(function(elm) {return elm.CityName;});
      console.log(newVal,$scope.selectedCity);
    });

PS: The above plunker isn't very perfect you may some some minor issues which you should be able to solve.


text:
Q: React first value? {movie.episode_run_time &&  {movie.episode_run_time} min. |}

Having done this, I get an array of time 40 60 45 32 min. , how can I get only the first value?

A: {movie.episode_run_time &&  {movie.episode_run_time[0]} min. |}


text:
Q: EntLib Validation problem on GetType(object) - expects string not object? I have an Address object that I am trying to validate data against using EntLib:
Given the following method:
<ValidatorComposition(CompositionType.And, Ruleset:="FraudAnalysis")> _
<NotNullValidator(MessageTemplate:="Billing address is required.", Ruleset:="FraudAnalysis")> _
<TypeConversionValidator(GetType(Address), MessageTemplate:="Billing address must be an address object.", Ruleset:="FraudAnalysis")> _
Public Property BillingAddress() As Address
    Get
        Return _BillingAddress
    End Get
    Set(ByVal value As Address)
        _BillingAddress = value
    End Set
End Property

I create an address object:
            Address thisAddress = new Address();
            thisAddress.Address1 = "12312 Long Street";
            thisAddress.City = "Los Angeles";
            thisAddress.State = "CA";
            thisAddress.Zip = "93322";
            // set billing address to address
            cardX.BillingAddress = thisAddress;

So now at cardX.billingAddress = thisAddress, the BillingAddress property validator (GetType(Address)) should fire.  It seems to fire, but returns this error:
Value to validate is not of the expected type: expected System.String but got Address instead.
Can anyone see the issue here / suggest a fix?
Thanks.

A: I would just get rid of the ValidatorComposition and TypeConversionValidator declarations as I think they are redundant here. That would get rid of your error and a couple of lines of code too.
The property is already strongly-typed to the Address class so there is no way you can set it in code to an object that isn't an Address or isn't polymorphic with Address - having an extra validator to check this is redundant.
The default composition of validators is logical AND anyway, you only need to specify validator composition when you want to OR a group, or use more complex groups that combine AND / OR.


text:
Q: The function "hog.detectMultiScale(frame)" doesn't return any thing I wrote this and it works. but the last function (hog.detectMultiScale) doesn't return any thing. I don't know why.
'''
import numpy as np
import cv2
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

cv2.startWindowThread()

# open video stream
cap = cv2.VideoCapture("E:\\3.mp4")

# the output will be written to output.avi
out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc(*'MJPG'),15.,
    (640, 480))

while (True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # resizing for faster detection
    frame = cv2.resize(frame, (640, 480))
    returns the bounding boxes for the detected objects

    (boxes, weights) = hog.detectMultiScale(frame)

'''


text:
Q: What kind of Javascript rich text editor support formula? Is there a Javascript rich text editor that allows me to choose the formula through the toolbar?

A: Tiny MCE has plugins that can be installed and add equation functionality in the Tiny MCE editor toolbar.
See this plugin for Latex:
https://www.codecogs.com/latex/integration/tinymce_v4/install.php


text:
Q: iOS iCloud: Deleting data doesnt work I currently implement iCloud core data syncing in my ios app.
The data sync works fine but there is a problem.
I have pre filled data that every time will be synced with iCloud when the app launches the first time. The result are duplicates :-(
Is there a smart solution for that issue?
I know that iCloud doesn't care about duplicates, but maybe somebody got an idea or workaround.
I can't find anything useful in the web for that issue...
regards


text:
Q: How does systemd provide data to the service triggered by a socket? The concept behind systemd sockets is to provide a "cheap listener service" that will start the "service that would normally bind that socket but we don't want to run it all the time" once data on the socket is detected.
Once started why can the "service that would normally bind that socket but we don't want to run it all the time" now receive data from the socket?

[Background]
I don't want rsyslog to be started when there is data on /run/systemd/journal/syslog. I want to start it when I need it and don't understand why is it a bad practice to bind it directly to the socket and delete syslog.socket altogether.

A: The imuxsock plugin of rsyslog appears to be aware of systemd's socket activation.
Systemd will create the socket and the file descriptor of that listening socket will be passed to the rsyslog.socket service which will use it.


text:
Q: convert numbers in scientific notation to decimal Write a C program to convert a number in scientific notation to its equivalent decimal form :
Given
8.3e+2 output = 830
2.E-1  output = 0.2
4.3E2  output = 430
Is there any inbuilt library or function in C/C++ which can do this?
or one will have to write his own code, in that case, any easy way to achieve this?

A: try this
#include <iostream>
#include <string>

int32_t main(int32_t argc, char *argv[]) {
    std::string str = "8.3e+2";
    std::cout << std::stod(str) << std::endl;

    return EXIT_SUCCESS;
}


text:
Q: Is it possible to run two SharePoint instances on one server? Simple question : Is it possible to run two SharePoint instances on one server?
With a not so simple answer I suspect.
Thanks,
Peter

A: Three answers:
A server can only be connected to one "config database", meaning you can only run one FARM instance.
A server can host multiple SSPs, so you can run multiple SEARCH, USER PROFILE, MY SITE instances. Not recommended though.
A server can host as many web applications (websites) as you'd like.

A: We've been running multiple instances on different ports, no problem. Great for development. But we haven't been running different versions of SharePoint on the same server

A: You can run multiple web apps on the same server, provided they use different ports and / or different host headers.  They will both be part of the same farm however...

A: If you mean by two SharePoint 2007 instances two installations of the server, then the answer would be no. If you mean two completely different sites with different sitenames, that is possible by making use of hostheaders for each of your web applications.
Running SharePoint 2003 and SharePoint 2007 side by side is possible. I haven't tested running SharePoint 2010 next to SharePoint 2007/2003 though.


text:
Q: Cramer' rule but by substituting rows Cramer's Rule is used to solve $Ax=B$, where $A$ is a $n\times n$ matrix and $B$ is a $n\times 1$ vector. And Cramer's Rule states that $x_k=\frac{|A(k;B)|}{|A|}$, where $A(k;B)$ is substituting the $k$th column of $A$ by $B$ vectors and $x_k$ is the $k$the coordinate in the solution vector.
I am wondering is there any similar versions for substituting the rows of A?

A: Consider the problem $$x^TC=D$$
Taking tranpose, we obtain $$C^Tx=D^T$$
Hence to solve for $x$, Cramer rules says that we can substitute columns of $D^T$ into columns of $C^T$.
This is equivalent to replacing the rows of $D$ into $rows$ of $C$.
Hence, the row version is meant to solve problem of the form of $$x^TC=D$$


text:
Q: Unable to resolve "./SafeAreaContext" I recently set up react-native project with expo and later on I added @react-navigation packages.
It seems like this wasn't enough as NavigationContainer render complains about SafeAreaContext
I tried to install required packages with expo install react-native-safe-area-context ... but It didn't solve it.
Thought deleting node_modules && npm install could help, but it didn't work either.
There were related questions to this issue
, but they didn't provide much help
I will appreciate your help.
Here's what I get in android emulator

terminal
Unable to resolve "./SafeAreaContext" from "node_modules\react-native-safe-area-context\src\index.tsx"
Failed building JavaScript bundle.

App.tsx
import React, { useState } from 'react';
import { AppLoading } from 'expo'
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';

function Test() {
  return (
    <View
      style={{ flex: 1, justifyContent: 'space-between', alignItems: 'center' }}
    >
      <Text>Test</Text>
    </View>
  );
}
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();

export default function App() {
 const [loaded, setLoaded] = useState(false);

  if(!loaded) {
    return <AppLoading
      startAsync={() => Promise.resolve()}
      onFinish={() => setLoaded(true)}/>
  }

  return <NavigationContainer>
    </NavigationContainer>
}

package.json
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@expo/vector-icons": "^10.2.0",
    "@react-native-community/masked-view": "^0.1.6",
    "@react-navigation/bottom-tabs": "^5.5.1",
    "@react-navigation/native": "^5.5.0",
    "@react-navigation/stack": "^5.4.1",
    "expo": "^37.0.12",
    "expo-asset": "^8.1.5",
    "expo-constants": "^9.0.0",
    "expo-linking": "^1.0.1",
    "expo-splash-screen": "^0.2.3",
    "expo-web-browser": "^8.2.1",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
    "react-native-gesture-handler": "~1.6.0",
    "react-native-reanimated": "~1.7.0",
    "react-native-safe-area-context": "0.7.3",
    "react-native-safe-area-view": "^1.1.1",
    "react-native-screens": "~2.2.0",
    "react-native-web": "~0.11.7",
    "react-redux": "^7.2.0",
    "redux": "^4.0.5"
  },
  "devDependencies": {
    "@babel/core": "^7.8.6",
    "@types/react": "~16.9.23",
    "@types/react-native": "~0.61.17",
    "babel-preset-expo": "~8.1.0",
    "typescript": "~3.8.3"
  },
  "private": true
}

A: Installing following two,
npm install --save @react-native-community/masked-view

npm install react-native-safe-area-context

it is work for me

A: Look like cleaning expo cache helped
expo r -c
expo r --help
Usage: start|r [options] [project-dir]
Starts or restarts a local server for your app and gives you a URL to it

 Options:
    -c, --clear           Clear the Metro bundler cache
   ....

expo --version
3.21.3


text:
Q: Download and view pdf using Cordova plugins and Ionic 3 not working Hello I am facing an issue while trying to open a pdf on mobile devices, using ionic 3. Basically I get the pdf from a web service and after decrypting the file, I ask if is being opened from a browser or from an application. If is being opened from the browser, I use in app browser to render pdf and it works like a charm, no problems there, but when is opened from a mobile device like an App I take a different approach, download the file and open it using

Document Viewer plugin
  File
  File Transfer

here is some code, first we make the call to the web service and subscribe to the response:
clickBtn(e) {
 const loading = this.loadingController.create({
   content: ''
});
loading.present().then(() => {
  const productExtractsRq: ProductExtractsRq = this.extractRq;
  productExtractsRq.customer = this.bdbUtilsProvider.getCustomer();
  // get file from WEB SERVICE
  this.transactionsProvider.getProductExtracts(productExtractsRq).subscribe(
    (data) => {
      loading.dismiss();
      // CREATE THE PDF
      this.blob = this.createPdf(data);
      this.url = window.URL.createObjectURL(this.blob);
      // COMPARE WHICH PLATFORM IS ACCESSING THE APP
      if (this.platform.is('core') || this.platform.is('mobileweb')) {
        this.iab.create(this.url, '_system');
      } else {
        this.downloadAndOpenPdf(this.url);
      }
    },
    (ex) => {
      loading.dismiss();
      if (ex.status === 409) {
        this.tsErrorProvider.launchErrorModal(ex.error._error);
      } else {
        this.bdbModal.launchErrModal(
          'Ha ocurrido un error',
          'El extracto no se pudo generar, por favor intenta más tarde.',
          'Aceptar'
        );
      }
    }
  );
});
}

here is the method for when is opened by app:
downloadAndOpenPdf(url: string) {
let path = null;

if (this.platform.is('ios')) {
  path = this.file.documentsDirectory;
} else if (this.platform.is('android')) {
  path = this.file.dataDirectory;
}

// this.document.viewDocument(url, 'application/pdf', {});

const transfer = this.transfer.create();
transfer.download(url, path + 'myfile.pdf').then(entry => {
  toast.present();
  const _url = entry.toURL();
  this.document.viewDocument(_url, 'application/pdf', {});
})
.catch(err => {
  alert(JSON.stringify(err));
  toast.present();
  this.iab.create(url, '_blank');
});
}

and here is the create pdf method, which apparently works fine.
createPdf<Blob>(data: ProductExtractsRs) {
const bytes: string = atob(atob(data.binData));
const byteNumbers = new Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
  byteNumbers[i] = bytes.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
return new Blob([byteArray], { type: 'application/pdf' });
}

So whenever I try to open the pdf I get the error:
{
 "code":2,
 "source":"blob:file:///a44e17fc-1eb7-458a-9130-3d7b4f3a790b",
 "target": "file///data/user/0/io.ionic.starter/files/myfile.pdf",
 "http_status":null,
 "body": null,
 "exception": null
}

And nothing else happens, anyone can tell what am I doing wrong?, remember that the pdf opens with no problem using the in app browser on web app. Any hint will be highly appreciated !


text:
Q: Wordpress responsive menu dont work on mobile and front-page my sample site is here LINK.
Everything on PC works perfectly, but when i want to go on mobile view, my responsive menu dont work and front page is changed fully.
For front-page i used "ThemeIsle Companion", on mobile view, there isnt any of it.
Theme name is Hestia.

A: The responsive website depends on your stylesheet. Sometime some themes don't have responsive layout. You have to write some @media css codes in external/ internal css style sheet and attach with the theme. Click here


text:
Q: URI is the same like relative URL? I am making own URL generator and there is a problem. I have absolute URL and I need to get relative URL from it.
Relative URL is path and query, like URI, so is this the same?

A: the relative url depends on the context.
absolute is: c:/home/user/test.zip
relative (when context is c:/home) to test.zip is: ./user/test.zip (or user/test.zip)


text:
Q: What is the Taylor series expansion of $z^{1/2}$ about origin. Consider $z^{1/2}={re^{i\theta}}^{1/2}=r^{1/2}e^{i\theta/2}$
Now seprate into real and imaginary parts we have
$U=r^{1/2}\cos(\theta/2)$
$V=r^{1/2}\sin(\theta/2)$
Now $rU_r=1/2r^{1/2}\cos(\theta/2)$ and $V_{\theta}=1/2r^{1/2}\cos(\theta/2)$ So it satisfies CR equations and thus the function is analytic.
Now my question is what is the Taylor series expansion of $z^{1/2}$about $z=0$
Moreover what is the vavlue of ${(0+i0)}^{1/2}$

A: When you write $z$ in a polar form in an expression, you are not writing something in terms of $z$, but in terms of $\log z$.
You have said $z^{1/2} = r^{1/2} \exp(i\theta/2)$ but this is not a well-defined function of $z$ for example if $z= -1$ then according to the choice of $\theta$ you can obtain $(-1)^{1/2} = 1$ or $(-1)^{1/2} = -1$.
So this expression is only a function of $r$ and $\theta$ (or equivalently, of $\log z = \log r + i \theta$).
Now what you have written in terms of $l = \log z$, is that "the square root of $\exp l$" should be $ \exp (l/2)$.
Now $l \mapsto \exp(l/2)$ is a nice holomorphic function and everything, so is $l \mapsto \exp l$ and its derivative never vanishes, so by the implicit function theorem, if you pick some $z$ in the image of $\exp$ there is a small open subset containing $z$ where you can have a well-defined map $z = \exp l \mapsto l \mapsto \exp(l/2) = \sqrt z$ which is holomorphic.
But of course, $0$ is not in the image of $\exp$ (and of course $\log z$ and $\sqrt z$ can't be well defined on a neighbourhood of $z=0$). So whenever you use a polar form, the fact that it looks holomorphic, doesn't mean that it is holomorphic at $z=0$.


text:
Q: Synonym not working: USER.SYNONYM_NAME works but SYNONYM_NAME does not I have the following issue:
I have created a synonym for a user in order to call a procedure from another schema, this is the output from the all_synonyms table log into sqlplus as USER_1:
OWNER   SYNONYM_NAME  TABLE_OWNER   TABLE_NAME      DB_LINK    ORIGIN_CON_ID
~~~~~   ~~~~~~~~~~~~  ~~~~~~~~~~~   ~~~~~~~~~~      ~~~~~~~    ~~~~~~~~~~~~~
USER_1  SYN_NAME      ADMIN         PROCEDURE_NAME  NULL       0

But I'm unable to run it using only the synonym name. If I do that I get an OORA-06550. Example:
exec SYN_NAME;
OORA-06550: line 1, column 7: PLS-00201: identifier 'SYN_NAME' must be declared

exec USER_1.SYN_NAME; //works as expected

I've already ran `grant execute on SYN_NAME to USER_1;
Is there anything else I need to set? I'm not sure what I'm missing. Thanks for the help in advance.

A: If I read this correctly the procedure exists in schema admin and you want user_1 to be able to call it.
As admin user:
grant execute on <procedure_name> to user_1;

As user_1:
create synonym <procedure_name> for admin.<procedure_name>;

A: You can see that effect if you change your current_schema. If that matches your user then it works OK:
select user, sys_context( 'userenv', 'current_schema') as schema from dual;

USER                           SCHEMA
------------------------------ ------------------------------
USER_1                         USER_1

create synonym syn_name for admin.procedure_name;

Synonym SYN_NAME created.

exec syn_name;

PL/SQL procedure successfully completed.

But if my session has a different current_schema then the synonym has to be prefixed with my real user name:
alter session set current_schema = user_2;

Session altered.

select user, sys_context( 'userenv', 'current_schema') as schema from dual;

USER                           SCHEMA
------------------------------ ------------------------------
USER_1                         USER_2

select owner, synonym_name, table_owner, table_name
from all_synonyms where synonym_name = 'SYN_NAME';

OWNER                          SYNONYM_NAME                   TABLE_OWNER                    TABLE_NAME
------------------------------ ------------------------------ ------------------------------ ------------------------------
USER_1                         SYN_NAME                       ADMIN                          PROCEDURE_NAME

exec syn_name;

ORA-06550: line 1, column 7:
PLS-00201: identifier 'SYN_NAME' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored

exec user_1.syn_name;

PL/SQL procedure successfully completed.

You may not know you're changing your current schema; it may be happening in a login trigger, possibly to avoid the need for synonyms. You can check your current schema with:
select sys_context( 'userenv', 'current_schema') as schema from dual;

If that actually shows you ADMIN then you don't need the synonym at all, and can just call PROCEDURE_NAME directly, with having to prefix it with the ADMIN schema name.


text:
Q: How to make array case insensitive I am writing a method that takes a string and searches through all the names for any that contain a matching substring, but how to I make the
targetSubstring

which is the name the user has entered into a JTextField and the
namesArray[I].getname()

which is the data from the input file that has been stored in an array, not case-sensitive? So when the user types in for example Sam, I want it to be able to find Sammy and Isamer(since this contains sam inside the name). However, for this to happen I need Sam to not be case-sensitive. So how would I do this? I have tried the .toLowerCase because I thought that would work, but I get different compiler errors. So am I just to using the .toLowerCase right? Here is the last thing I've tried with the .toLowerCase, but it doesn't work.
   if (namesArray[i].getName().toLowerCase.contains(targetSubstring.toLowerCase))

Here is the method...
  private void match(String targetSubstring)
  {
    displayArea.setText("");
    displayArea.append("FIND RESULTS for: " + targetSubstring);
    displayArea.append("\n");
    displayArea.append("\n Name               Best Decade");
    displayArea.append("\n---------------     ---------------");
    for (int i = 0; i < namesArray.length; i++) {
      if (namesArray[i].getName().contains(targetSubstring))
      {
        displayArea.append("\n" + namesArray[i].getName() + "      " +
                        namesArray[i].bestDecade());
      }
     }
  }

A: targetSubstring = targetSubstring.toUpper ();
for (int i = 0; i < namesArray.length; i++) {
  String theName = namesArray[i].getName();
  if (theName.toUpper ().contains(targetSubstring))
  {
    displayArea.append("\n" + theName + "      " + namesArray[i].bestDecade());
  }
 }

A: Alternatively you can use code just like Gregory suggested but with the use of
StringUtils from org.apache.commons.lang
for (int i = 0; i < namesArray.length; i++) {
  String theName = namesArray[i].getName();
  if (StringUtils.containsIgnoreCase(theName, targetSubstring ))
  {
    displayArea.append("\n" + theName + "      " + namesArray[i].bestDecade());
  }
 }


text:
Q: Wait for JavaScript function to finish before proceed This might not be a complicated question but I'm not sure if I'm on the right track here.
My goal is to run a JavaScript function first and when the execution is completely finished (this may take up to a few seconds, but not always) close the window.
The function and closing is triggered by just 1 button:
<button id="myID">Click me</button>

The JavaScript is:
<script type="text/javascript">
    function someFunction() {
        // do some stuff
    }

    document.getElementById('myID').addEventListener("click", function(){
        someFunction();
        window.close();
    });
</script>

This works fine, but can get anyone give some advice if this is a reliable method or not? It is important that execution of the function is fully completed before window.close() is triggered.

A: You can put your window.close() right under your alert();. However, if you would like to add more asynch stuff, you want a callback function like this.
<script type="text/javascript">
    var closeWindow = function() {
        window.close();
    };

    function someFunction(callback) {
        alert('hi');
        callback();
    }

    document.getElementById('myID').addEventListener("click", function(){
        someFunction(closeWindow);
    });
</script>

A: Synchronous javascript will always be run in the top-down order and will always guarantee that instruction one will be finished before instruction two.
But, there is also an asynchronous part (you don't have it here, but for example ajax requests are often asynchronous), that is executed differently and requires callbacks/promises.

A: Your options are:

*

*put window.close(); in the callback function

*use promises this way you can control if the callback execution /if there is an error you can handle it better and not close the window/

A:
someFunction() does some DOM manipulation after a page has loaded

Thats synchronous (the browser might defer the rendering, but were talking about milliseconds here), and therefore it is guaranteed that the DOM manipulation is done before the function returns.