Line() in d3 generating NaN

Question: Started D3 and JS a week ago. I am trying to plot a Multi-Series Line chart, and I am stuck trying to figure out why line() is returning NaNs. The x domain is discrete string values ["70","71","72".."80"]. Using d3 v4.
I tried tweaking the X-Y scales, range values etc. Tried to identify fracture point and turns out it was the line().
var XScale = d3.scaleBand();
var YScale = d3.scaleLinear();
XScale.domain(findata.map(d=>d.values.year)).range([0,width]);`

\"findata" is my JS object after importing the data.
YScale.domain([
       d3.min(getmaxscale),        //I separately calculate the min-max
       d3.max(getmaxscale)
]).range([height,0]);

lineGenerator
      .x(function(d){return XScale(d.model) })
      .y(function(d){return YScale(d.avg)});

This is what I tried to check the output:
var a= findata.map(d=>d.value);

console.log(lineGenerator([a[0].model,a[0].avg]));

\testing for a given row.
Output (Incorrect): MNaN,NaNLNaN,NaN
//--------------------------
Sample Data:
[
  {
    "Car": "AMC Ambassador Brougham",
    "MPG": "13",
    "Displacement": "360",
    "Horsepower": "175",
    "Weight": "3821",
    "Model": "73",
    "Origin": "US"
  },
  {
    "Car": "AMC Ambassador DPL",
    "MPG": "15",
    "Displacement": "390",
    "Horsepower": "190",
    "Weight": "3850",
    "Model": "70",
    "Origin": "US"
  },
  {
    "Car": "AMC Ambassador SST",
    "MPG": "17",
    "Displacement": "304",
    "Horsepower": "150",
    "Weight": "3672",
    "Model": "72",
    "Origin": "US"
  },
  {
    "Car": "AMC Concord",
    "MPG": "19.4",
    "Displacement": "232",
    "Horsepower": "90",
    "Weight": "3210",
    "Model": "78",
    "Origin": "US"
  },
  {
    "Car": "AMC Concord",
    "MPG": "24.3",
    "Displacement": "151",
    "Horsepower": "90",
    "Weight": "3003",
    "Model": "80",
    "Origin": "US"
  },
  {
    "Car": "AMC Concord d/l",
    "MPG": "18.1",
    "Displacement": "258",
    "Horsepower": "120",
    "Weight": "3410",
    "Model": "78",
    "Origin": "US"
  },
  {
    "Car": "AMC Concord DL",
    "MPG": "23",
    "Displacement": "151",
    "Horsepower": "0",
    "Weight": "3035",
    "Model": "82",
    "Origin": "US"
  },
  {
    "Car": "AMC Concord DL 6",
    "MPG": "20.2",
    "Displacement": "232",
    "Horsepower": "90",
    "Weight": "3265",
    "Model": "79",
    "Origin": "US"
  }
]

Full code:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>CS590: HW1, Problem 1</title>

Comment: Need a bit more info to help debug this issue. It would really help if you count link to a minimal reproducable example: https://stackoverflow.com/help/minimal-reproducible-example. But, could you add to your post what the output of `XScale.domain()` and `YScale.domain()` print out? These should output the data that was used to create these domains, so here we'd just be checking that the scales were set up correctly. Then you might try logging the output of, say, XScale('90') etc, to check in isolation that the scales are mapping your modal as you expect.
Comment: I checked the scales, they are outputting correctly.
Answer: I haven't been able to fully test your code, but I think that the problem is the following:
You are defining the line generator as:
lineGenerator
  .x(function(d){return XScale(d.model) })
  .y(function(d){return YScale(d.avg)});

And then you are calling it this way:
lineGenerator([a[0].model,a[0].avg])

So when you call the lineGenerator, you are passing model and avg, and then, the line generator is trying to access to model and to avg again, so changing the call to:
lineGenerator([a[0],a[0]])

Might solve the problem
Edit after seeing the example
When you do attr("d", function(d) { return lineGenerator(d.value); }) You are passing the data this way:
{
  avg: (7) [15, 17, 13, 18.75, NaN, 24.3, NaN],
  model: (7) [70, 72, 73, 78, 79, 80, 82]
}

And the line generator expects the data this way:
[
    {avg: 15, model: 70},
    {avg: 17, model: 72},
    {avg: 13, model: 73},
    {avg: 18.75, model: 78},
    {avg: NaN, model: 79},
    {avg: 24.3, model: 80},
    {avg: NaN, model: 82},
]

Right before the ccountry.append("path") line, I did the following and change the data format (this is just an example, I would change the functions that you are using to format them in the correct way):
var lineData = [];
for(var k = 0; k<a[0].avg.length; k++) {
    lineData.push({
        avg: a[0].avg[k],
        model: a[0].model[k]
    });
}

console.log(lineGenerator(lineData));

And the final console.log returned this:
d3-line.html:208 M0,370.3539823008849L20.952380952380953,357.07964601769913C41.904761904761905,343.80530973451323,83.80952380952381,317.2566371681416,125.71428571428571,330.5309734513274C167.61904761904762,343.80530973451323,209.52380952380952,396.9026548672566,251.42857142857142,385.28761061946904C293.3333333333333,373.6725663716814,335.23809523809524,297.34513274336285,377.1428571428571,NaNC419.04761904761904,NaN,460.9523809523809,NaN,502.85714285714283,NaNC544.7619047619047,NaN,586.6666666666666,NaN,628.5714285714286,NaNC670.4761904761905,NaN,712.3809523809523,NaN,733.3333333333334,NaNL754.2857142857142,NaN
Finally, as you can see, there are some NaN in some avg attributes, I replaced them with a random number, replaced the line .attr("d", function(d) { return lineGenerator(d.value); }) with .attr("d", function(d) { return lineGenerator(lineData); }) and then we got a line:
Comment: Worked like a charm! Thanks a lot, Guillermo!!
Comment: Hey Guillermo, agree with you. Thought it would work too. Unfortunately not. Added a sample data and full code. Maybe that helps?
Comment: @Ashwin I just updated the answer, please check the edit.

Line() in d3 generating NaN


intent is not returning data

Question: I am developing an Android project in which I have to send data from one activity to another. But when I'm sending data from one activity to another it is not sending data from one activity to another.
Part of code receiving data from other is:
Intent intent=getIntent();
String str,str1;
str=intent.getExtras().getString("phoneno");
Log.d("completre", "complete");
phonePhoneno.setText(str);

Log.d("complete","complete1");

if(intent.getExtras()==null) {
    txtMessage.setText("u duffer write program properly");
} else {
    str1=intent.getExtras().toString();
    txtMessage.setText(str1);
    Log.d("complete","complete2");
}

Part of code I'm using for sending data from other activity is:
if(v.getId()==R.id.main_act) {
    String str=txtText.getText().toString();
    Intent intent=new Intent(getApplicationContext(), MainActivity.class);
    intent.putExtra("username",str);
    intent.putExtra("phoneno", phoneno);
    startActivity(intent);
}

When I try to receive data by clicking button it is force closing.
in this project i have two activity in first activity i m reading a telephone no. ans sending it to second activity only to save it for future. in the second activity i have an edit text in which i am adding text by voice recognition system after that i am sending both data telephone no and edit text field from 2nd activity to 1st activity by clcking button just shown above (in second part of code) . it is sending phone no but not edit text content(guess) , when i click complete button(to fill both field in 1st activity) then it adds phone no in phone no field but does not add message.
latest  log cat
 when app didn't close itself
  04-13 13:33:46.206: I/TextToSpeech(834): Sucessfully bound to com.svox.pico
04-13 13:33:46.206: W/TextToSpeech(834): speak failed: not bound to TTS engine
04-13 13:33:47.005: I/TextToSpeech(834): Connected to ComponentInfo{com.svox.pico/com.svox.pico.PicoService}
04-13 13:33:47.125: E/test(834): hhhhhhhhhhhhhhhhh
04-13 13:33:47.125: I/Choreographer(834): Skipped 174 frames!  The application may be doing too much work on its main thread.
04-13 13:33:47.575: I/Choreographer(834): Skipped 69 frames!  The application may be doing too much work on its main thread.
04-13 13:33:56.535: W/IInputConnectionWrapper(834): showStatusIcon on inactive InputConnection
04-13 13:33:56.535: I/Choreographer(834): Skipped 174 frames!  The application may be doing too much work on its main thread.
04-13 13:33:56.975: D/dalvikvm(834): GC_CONCURRENT freed 127K, 9% free 3017K/3288K, paused 37ms+5ms, total 108ms
04-13 13:34:00.274: V/(834): Got a contact result: content://com.android.contacts/data/3
04-13 13:34:00.674: V/(834): Got phone no : (986) 743-561
04-13 13:34:00.914: I/Choreographer(834): Skipped 164 frames!  The application may be doing too much work on its main thread.
04-13 13:34:01.244: I/Choreographer(834): Skipped 37 frames!  The application may be doing too much work on its main thread.
04-13 13:34:05.494: I/Choreographer(834): Skipped 139 frames!  The application may be doing too much work on its main thread.
04-13 13:34:05.974: I/Choreographer(834): Skipped 60 frames!  The application may be doing too much work on its main thread.
04-13 13:34:12.965: I/TextToSpeech(834): Sucessfully bound to com.svox.pico
04-13 13:34:12.965: W/TextToSpeech(834): speak failed: not bound to TTS engine
04-13 13:34:13.065: I/TextToSpeech(834): Connected to ComponentInfo{com.svox.pico/com.svox.pico.PicoService}
04-13 13:34:13.155: E/test(834): hhhhhhhhhhhhhhhhh
04-13 13:34:13.155: I/Choreographer(834): Skipped 35 frames!  The application may be doing too much work on its main thread.
04-13 13:34:14.425: I/Choreographer(834): Skipped 308 frames!  The application may be doing too much work on its main thread.
04-13 13:34:15.235: I/Choreographer(834): Skipped 95 frames!  The application may be doing too much work on its main thread.
04-13 13:34:16.265: I/Choreographer(834): Skipped 31 frames!  The application may be doing too much work on its main thread.
 04-13 13:34:20.025: D/completre(834): complete
 04-13 13:34:20.035: D/AndroidRuntime(834): Shutting down VM
 04-13 13:34:20.035: W/dalvikvm(834): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
 04-13 13:34:20.085: E/AndroidRuntime(834): FATAL EXCEPTION: main
 04-13 13:34:20.085: E/AndroidRuntime(834): java.lang.NullPointerException
 04-13 13:34:20.085: E/AndroidRuntime(834):     at com.example.sms.MainActivity.onClick(MainActivity.java:322)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at android.view.View.performClick(View.java:4204)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at android.view.View$PerformClick.run(View.java:17355)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at android.os.Handler.handleCallback(Handler.java:725)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at android.os.Handler.dispatchMessage(Handler.java:92)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at android.os.Looper.loop(Looper.java:137)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at android.app.ActivityThread.main(ActivityThread.java:5041)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at java.lang.reflect.Method.invokeNative(Native Method)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at java.lang.reflect.Method.invoke(Method.java:511)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
 04-13 13:34:20.085: E/AndroidRuntime(834):     at dalvik.system.NativeStart.main(Native Method)

i more thing that i would like to mention here is that when i return from second activity to main without recording any message that i didn't set content of edit text and i tried to send the content to first activity as shown in second part of code it worked ...ideally it should force close itself since edit text had no data ..i could not understand why it is not force closing itself at that time.
Comment: Add the stacktrace, so we can see which exception it's throwing - also if you could point out the line, that crashes the app.
Comment: Considering that your `Activity` is called "MainActivity" and your button id is "main_act", this looks suspect. "main_act.xml" may be the filename of your XML layout file, and this would be a mistake. See my answer edit below.
Comment: should i update the question i.e i should add more code part to make it clear??
Comment: no main.act is my button id i m sure about that.
Comment: And what line is line `322` in your `MainActivity`?
Comment: @Darwind it is line in which i m setting content of phone no field. phonephoneno.settext(str). this line is there in 1st part of code it is commented out as i thought it is working f9.
Comment: Uhm, then the stacktrace isn't really worth anything, because this is the line, that is crashing your app with a `NullPointerException` - clean-build the app and re-install it on your device of choice. After that, post the new stacktrace.
Comment: logcat updated still force close...please help
Comment: anyone please help me :(   ...m waiting
Comment: Ok, so it's crashing the same place - at line 322 in `MainActivity`. That doesn't make sense, if this is still the outcommented code. Can't help you much then. Maybe paste all your code to pastebin.org or upload the full project as a zip file to DropBox and share the link - anything, so we can examine the problem in full.
Comment: just want to know one thing if u don't pass anything in edit text and try to send its content using intent to other activity how should it perform that is it should force close it self or not???
Comment: pasted at pastebin.org my username is rajeevnitj post name is android_voice_sms
Comment: should i make this question more clear and detail  please response hoping for some solution
Comment: question updated ... @Darwind  u were right after a long research i came to the same point it is line no 322 which is causing crash...but i could not find any solution ...it is still returning null pointer exception
Comment: @sid ok I've added an answer to your question - hope you understand and like it ;-)
Answer: Bundle Usage:
Use this to get the variables from your Intent:
Intent intent = getIntent();
final Bundle bundle = intent.getExtras();
if(bundle != null) {
    String username = bundle.getString("username");
    String phoneno = bundle.getString("phoneno");
}

Force Close:

Make sure that the variables str and phoneno are not null for
your intent.putExtra() commands. This could cause your force close.
Make sure that id "main_act" is the unique id defined in the
XML layout file for your button.
Comment: Actually that's not entirely true - the `Bundle` has a `toString()` so it would return a human readable string, or as the documentation states: `Returns a string containing a concise, human-readable description of this object.` - also he checked for `null` - just saying ;-)
Comment: Hehe - sorry didn't see you changed the answer ;-)
Answer: Ok, after a bit of digging, I found out what the problem was...
The problem doesn't have anything to do with the values from the Bundle.
The problem is that you're trying to call setText() and getText() on an EditText called phonePhoneno. This field has never been initialized in the onCreate method of the MainActivity.
So, to fix this NullPointerException, initialize the phonePhoneno to the correct EditText inside your main.xml for MainActivity and you're good ;-)
Maybe it should initialized like this?
phonePhoneno = (EditText) findViewById(R.id.phonenofromcontact);

I don't know?
It looks like a type or an "autocomplete" mistake to be honest :P
Just a little advice: Clean up your code, and you'd probably have found the Exception on your own ;-)
Comment: and yeah u r right problem could be easily found but....u know while checking code v generally skip easy part :P sometimes v have to pay for that (it cost me 1 day in this case ;) :)
Answer: David Manperl right to say that you did something wrong you mean where are changed at Intent.
If you have an intent does not help, you can use another way. There are other ways to pass data another activity.
For example:

SharedPreferences
The Application object is another way though, and it is sometimes easier when dealing with the same state across multiple activities (as opposed to having to get/put it everywhere), or objects more complex than primitives and Strings.
You can extend Application, and then set/get whatever you want there and access it from any Activity (in the same application) with getApplication().

Or try to get data from the Intent in onCreate method of Activity

intent is not returning data


Getting random row through SQLAlchemy

Question: How do I select one or more random rows from a table using SQLAlchemy?
Answer: This is very much a database-specific issue.
I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy:
from  sqlalchemy.sql.expression import func, select

select.order_by(func.random()) # for PostgreSQL, SQLite

select.order_by(func.rand()) # for MySQL

select.order_by('dbms_random.value') # For Oracle

Next, you need to limit the query by the number of records you need (for example using .limit()).
Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; here is good article about it.
Comment: +1. Same as Postgres works for SQLite:  `select.order_by(func.random()).limit(n)`
Comment: If you are using declarative models: `session.query(MyModel).order_by(func.rand()).first`
Comment: Since SQLAlchemy v0.4, `func.random()` is a generic function that compiles to the database's random implementation.
Comment: Thanks @trinth, it worked when I added paranthesis to the end: `session.query(MyModel).order_by(func.rand()).first()`
Comment: You can use order_by('dbms_random.value') in Oracle.
Comment: I've added the import as best as I can tell without SQLAlchemy installed - can someone confirm it's right..? Also edited bernie and Buttons840 suggestions into the answer
Comment: Why `.rand` and `.random`? Shouldn't SQLAlchemy take care of such DB-specific idiosyncrasies for us?
Comment: appears that func.random() does not work with oracle. suggest using `select.order_by(sqlalchemy.literal_column('dbms_random.value'))` to avoid warnings
Answer: Here's four different variations, ordered from slowest to fastest. timeit results at the bottom:
from sqlalchemy.sql import func
from sqlalchemy.orm import load_only

def simple_random():
    return random.choice(model_name.query.all())

def load_only_random():
    return random.choice(model_name.query.options(load_only('id')).all())

def order_by_random():
    return model_name.query.order_by(func.random()).first()

def optimized_random():
    return model_name.query.options(load_only('id')).offset(
            func.floor(
                func.random() *
                db.session.query(func.count(model_name.id))
            )
        ).limit(1).all()

timeit results for 10,000 runs on my Macbook against a PostgreSQL table with 300 rows:
simple_random():
    90.09954111799925
load_only_random():
    65.94714171699889
order_by_random():
    23.17819356000109
optimized_random():
    19.87806927999918

You can easily see that using func.random() is far faster than returning all results to Python's random.choice().
Additionally, as the size of the table increases, the performance of order_by_random() will degrade significantly because an ORDER BY requires a full table scan versus the COUNT in optimized_random() can use an index.
Comment: Isn't this using `flask-sqlalchemy`?
Comment: What about picking samples? Like what  `random.sample()` do? What is optimized way here?
Comment: Open a new question and link to it and I'll take a stab at answering. If possible, specify the underlying flavor of SQL as that influences the answer as well.
Answer: If you are using the orm and the table is not big (or you have its amount of rows cached) and you want it to be database independent the really simple approach is.
import random
rand = random.randrange(0, session.query(Table).count())
row = session.query(Table)[rand]

This is cheating slightly but thats why you use an orm.
Comment: rand = random.randrange(0, session.query(Table).count())
Comment: You choose and create all objects before choose one of
Comment: How about `random.choice(session.query(Table))`?
Answer: There is a simple way to pull a random row that IS database independent.
Just use .offset() . No need to pull all rows:
import random
query = DBSession.query(Table)
rowCount = int(query.count())
randomRow = query.offset(int(rowCount*random.random())).first()

Where Table is your table (or you could put any query there).
If you want a few rows, then you can just run this multiple times, and make sure that each row is not identical to the previous.
Comment: @Jayme: you could use `query.offset(random.randrange(rowCount)).limit(1).first()`.
Comment: Works well for me in a ~500k rows setting.
Comment: Now up at 11 million rows on Oracle.... not so good anymore :-) Linear degradation, but still... I have to find something else.
Comment: @Jayme also, is there a reason to use `.limit(1)` before `.first()`? It seems redundant. Perhaps, `query.offset(random.randrange(row_count)).first()` is enough.
Comment: Update - at around 10 million rows in mysql this actually started to get a little slow I guess you could optimize it.
Comment: @Mario Share when you do :)
Comment: I haven't done any workbench tests, but I changed the query to this: query.offset(random.randint(0, rowCount - 1)).limit(1).first() and it's working fine. But my database is pretty small compared to yours.
Comment: @J.F.Sebastian, I don't remember whether the sql generate was better, or I used it just to not have to handle the IndexError exception in case of no results. Because of accessing "query[0]".
But the docs say that first already applies the limit of one.
Seems you are right again ;)
Comment: @J.F.Sebastian found it here: http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.first
I guess the limit was kept because of another piece of code I used to get pages of random items and reduced it to get just one. Well, anyway thanks!
Answer: Some SQL DBMS, namely Microsoft SQL Server, DB2, and PostgreSQL have implemented the SQL:2003 TABLESAMPLE clause. Support was added to SQLAlchemy in version 1.1. It allows returning a sample of a table using different sampling methods – the standard requires SYSTEM and BERNOULLI, which return a desired approximate percentage of a table.
In SQLAlchemy FromClause.tablesample() and tablesample() are used to produce a TableSample construct:
# Approx. 1%, using SYSTEM method
sample1 = mytable.tablesample(1)

# Approx. 1%, using BERNOULLI method
sample2 = mytable.tablesample(func.bernoulli(1))

There's a slight gotcha when used with mapped classes: the produced TableSample object must be aliased in order to be used to query model objects:
sample = aliased(MyModel, tablesample(MyModel, 1))
res = session.query(sample).all()

Since many of the answers contain performance benchmarks, I'll include some simple tests here as well. Using a simple table in PostgreSQL with about a  million rows and a single integer column, select (approx.) 1% sample:
In [24]: %%timeit
    ...: foo.select().\
    ...:     order_by(func.random()).\
    ...:     limit(select([func.round(func.count() * 0.01)]).
    ...:           select_from(foo).
    ...:           as_scalar()).\
    ...:     execute().\
    ...:     fetchall()
    ...:
307 ms ± 5.72 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [25]: %timeit foo.tablesample(1).select().execute().fetchall()
6.36 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [26]: %timeit foo.tablesample(func.bernoulli(1)).select().execute().fetchall()
19.8 ms ± 381 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Before rushing to use SYSTEM sampling method one should know that it samples pages, not individual tuples, so it might not be suitable for small tables, for example, and may not produce as random results, if the table is clustered.

If using a dialect that does not allow passing the sample percentage / number of rows and seed as parameters, and a driver that does not inline values, then either pass the values as literal SQL text if they are static, or inline them using a custom SQLA compiler extension:
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import TableSample

@compiles(TableSample)
def visit_tablesample(tablesample, self, asfrom=False, **kw):
    """ Compile `TableSample` with values inlined.
    """
    kw_literal_binds = {**kw, "literal_binds": True}
    text = "%s TABLESAMPLE %s" % (
        self.visit_alias(tablesample, asfrom=True, **kw),
        tablesample._get_method()._compiler_dispatch(self, **kw_literal_binds),
    )

    if tablesample.seed is not None:
        text += " REPEATABLE (%s)" % (
            tablesample.seed._compiler_dispatch(self, **kw_literal_binds)
        )

    return text

from sqlalchemy import table, literal, text

# Static percentage
print(table("tbl").tablesample(text("5 PERCENT")))
# Compiler inlined values
print(table("tbl").tablesample(5, seed=literal(42)))

Comment: Has anyone been able to implement this with an Azure SQL db? I'm tring but i get ```
ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Variables are not allowed in the TABLESAMPLE or REPEATABLE clauses. (497) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)')
```
Comment: Sounds like an interesting edge case that the implementation does not cover; by the looks of it passing the percentage or seed as a parameter is not supported. The Azure dialect would need to inline the argument in the query compiler. I can produce an example of that later today.
Comment: @robertfranklin I hope the additions help in getting it to work.
Answer: This is my function to select random row(s) of a table:
from sqlalchemy.sql.expression import func

def random_find_rows(sample_num):
    if not sample_num:
        return []

    session = DBSession()
    return session.query(Table).order_by(func.random()).limit(sample_num).all()

Answer: This is the solution I use:
from random import randint

rows_query = session.query(Table)                # get all rows
if rows_query.count() > 0:                       # make sure there's at least 1 row
    rand_index = randint(0,rows_query.count()-1) # get random index to rows
    rand_row   = rows_query.all()[rand_index]    # use random index to get random row

Comment: This would be incredibly slow on big tables. You would be grabbing every single row and then slicing it up.
Comment: Wow yeah, this is not great. If there is a query to get table record count, that would be a better approach. This was done on a web-app with a small DB, no longer working with that company, so I can't do much about it.
Answer: this solution will select a single random row
This solution requires that the primary key is named id, it should be if its not already:
import random
max_model_id = YourModel.query.order_by(YourModel.id.desc())[0].id
random_id = random.randrange(0,max_model_id)
random_row = YourModel.query.get(random_id)
print random_row

Comment: This fails when you have a gap in your id's.
Answer: Theres a couple of ways through SQL, depending on which data base is being used.
(I think SQLAlchemy can use all these anyways)
mysql:
SELECT colum FROM table
ORDER BY RAND()
LIMIT 1

PostgreSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

MSSQL:
SELECT TOP 1 column FROM table
ORDER BY NEWID()

IBM DB2:
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Oracle:
SELECT column FROM
(SELECT column FROM table
ORDER BY dbms_random.value)
WHERE rownum = 1

However I don't know of any standard way
Comment: Yeah. I know how to do it in SQL (I posted that answer in http://beta.stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql#19568) but was searching for a SQLAlchemy specific solution.

Getting random row through SQLAlchemy


Application of the theorem: A function is continuous if and only if the inverse image of any closed set is closed

Question: Theorem: A mapping $f$ of a metric space $X$ into a metric space $Y$ is continuous on $X$ if and only if $f^{-1}(V)$ is closed for any closed set $V$ in $Y$.
Let $f : (0, 1) \rightarrow \mathbb{R}$ by $f(x) = 0$. Then $f$ is obviously continuous on $(0, 1)$ but the set $\{0\}$ is closed in $\mathbb{R}$ while $f^{-1}(\{0\}) = (0, 1)$ is open in $\mathbb{R}$.
Am I misunderstanding anything of the theorem or where is the problem? Thank you
Answer: Here the domain of $f$ is the space $(0,1)$ with the metric induced by $\mathbb{R}$. But $(0,1)$ is closed (and open) in itself...!
In other words: the propery of being closed or open depends on the ambient space. Here the ambient space is $(0,1)$, not $\mathbb{R}$. And any space $X$ is always closed in itself: the chain of inclusions $X \subseteq \overline{X} \subseteq X$ shows that $\overline{X} = X$, where the closure is taken with respect to $X$.


Distance / Proximity from cck location field ? not from user or node location?

Question: I try to get a distance between cck location nodes / users but I didn't succeed at that point because the only avalaible views field to do that is  "EMPLACEMENT : DISTANCE / PROXIMITY" which concerns node location or user location, not cck location field.
How to get that point ?
Regards,
Yoann
Answer: Results may vary based upon your drupal version, but basically when you create a proximity filter:

the first option is "Node location" but when you click on that:

it will allow you to use a Location CCK field as well.
Comment: Thanks for your answer. Ok  for Location CCK field linked to nodes but it seems there is a problem with Location CCK field linked to users bacause the "Location to use" is not available for "User's Latitude / Longitude from views uid argument". Actually I added a location cck field to users and this field is only available through "node's Latitude / Longitude frow views nid argument".
Comment: You must be on drupal 7 then, and I don't have an answer to that, for in drupal 6 land, you can't add cck fields to users :)  Here we'd add a location field to a content profile node type and then could use that.
Comment: Ok I found a way to use locationn cck field without node or user location. I did as you told me but I needed to add a PHP code to get the initial position of the current user. Now it works fine and I get the correct distances. Thanks for your answer.
Comment: Glad I was able to help out a bit!  You may want to post your code for others to follow.
Comment: ok it's done. Hope it's useful.
Answer: Here is the code I used in the "php code for latitue, longitude" origin section in the "Emplacement: Distance / Proximity field" views :
global $user;
global $databases;
$res = db_set_active('default');
$query1 = db_query("SELECT field_lien_adresse_utilisateur_target_id FROM {field_data_field_lien_adresse_utilisateur} WHERE entity_id = :uid", array('uid' => $user->uid));
$results1 = $query1->fetchAll();
$query2 = db_query("SELECT field_adresse_utilisateur_lid FROM {field_data_field_adresse_utilisateur} WHERE entity_id = :entity_id", array('entity_id' => $results1[0]->field_lien_adresse_utilisateur_target_id));
$results2 = $query2->fetchAll();
$query3 = db_query("SELECT latitude, longitude FROM {location} WHERE lid = :lid", array('lid' => $results2[0]->field_adresse_utilisateur_lid));
$results3 = $query3->fetchAll();
$result['latitude'] = (float) $results3[0]->latitude;
$result['longitude'] = (float) $results3[0]->longitude;
return $result;
Then I got the latitude and longitude of the current user.
Hope it's useful.


A script that verifies that Apache (or any account) has proper permission to navigate to a directory

Question: It seems that Apache needs at least read and execute permission to all the sub-directories of a path in order to serve the files  in the directory.
Does anyone have a script or one-liner that could verify this?
I was thinking perhaps a bash script that will su - apache and then attempt to navigate to each directory in the path. I'm going to try some things out and I'll post if I come up with something that works.
Answer: For Debian:
sudo -u www-data test -r /path/to/file && echo ok

Comment: Does this test fail if you do not have access to `/path/to` but have access to `/path/to/file`. This is what I'm trying to test.
Comment: Outstanding. My tests show that it does exactly what I need!
Comment: Please be aware that `-r` is for files only. If you need to know if Apache is capable of doing a DirectoryIndex on a folder, `test -rx`. /cc @conrad-shultz
Answer: Consider:
#!/bin/bash
# testperms.sh

if [ -r $1 ];
   then echo "Can read file!";
else
   echo "Cannot read file!";
fi

Usage:
 shultzc@lithium:~$ ./testperms.sh /etc/ssl
 Can read file!
 shultzc@lithium:~$ ./testperms.sh /etc/ssl/private
 Cannot read file!

You should be able to adapt that code to your needs.  In combination with sudo it can be used easily to test accessibility of files within directories with +x permissions only (such as many home directories), e.g.:
 shultzc@lithium:~$ sudo -u www-data ./testperms.sh /home/shultzc/testperms.sh
 Can read file!
 shultzc@lithium:~$ sudo -u www-data ./testperms.sh /home/shultzc
 Cannot read file!

Comment: @LuisBruno Ah, brilliant!
Comment: `sudo -u www-data test -r /path/to/file`
Comment: To be honest, I was going to use other flags for `test`, then I read your script and bitch-slapped myself. Anyway, both our scripts fail for the `drwx-----x` case.
Answer: This is what I got (must be run as a user that could su - <test user>:
#!/bin/bash

IFS='/'
CWD='/'

for dir in $2; do

   # Set directory to test
   if [[ $CWD == '/' ]]
   then
      CWD="/$dir"
   else
      CWD="${CWD}/${dir}"
   fi

   # Test if user has access
   if !(su - $1 -c "cd $CWD" 2> /dev/null)
   then
      echo "$CWD - No access for $1"
      exit -1
   fi
done

echo "Access for $1 all the way through $2"

Comment: Way more complicated than required... :-)
Comment: Figured heh. That's why I came to SF. Seems like Luis beat us all on this one!
Answer: The following find commands should be run as root, or at least a user that has full access to the directory tree.  You will need an additional check to verify access to the paths used in the find commands.  This can be accomplished by running the command as the target user.  Failures when running as a non-root user should be dealt with appropriately.
Replace /srv/www with the appropriate directory or directories for your requirements.  Change the user and group appropriately for other users.  If the user belongs to multiple groups, you will need to add additional tests for the secondary groups.  (In many cases just flagging files owned by the secondary groups may be sufficient.)
For a system where apache runs as www-data:www-data the following will find files which can't be read.
find /srv/www ! -type d ! \( -user www-data -perm -400 \) -a ! \( -group www-data -perm -040 \) -a ! -perm -004

The equivalent for accessible directories is:
find /srv/www -type d ! \( -user www-data -perm -500 \) -a ! \( -group www-data -perm -050 \) -a ! -perm -005

For directories that don't need to be listed use 1 instead of 5 in the above.  Files with known names will be accessible, but auto-index generation won't be.
You may also want to ensure only a few files or directories can be written to.  The following finds files and directories that can be written too.
find -L /srv/www \( -user www-data -perm -200 \) -o \( -group www-data -perm -020 \) -a -perm -002


O que significa uma "!" exclamação antes de uma string dentro de um if em C#

Question: Olá, estou com uma duvida em relação a alguns "trechos" de um programa que estou usando para "estudar", a dúvida é, qual o significado de "!" dentro de um if antes de uma string, eu vi alguns tópicos no site explicando, más eu não entendo como funciona no programa que tenho...
if (Connect._state == HostStatus.ONLINEALERT && !string.IsNullOrEmpty(Connect._message))
O código acima é um dos "trechos" que não entendo, agradeço desde já a quem me ajudar...
Answer: Em geral o operador "!" é o "not" lógico, ou seja, uma negação, acredito que seja o mesmo em C# como citado aqui. Esse trecho provavelmente está negando string.IsNullOrEmpty(Connect._message).
Answer: então, string.IsNullOrEmpty indica se uma cadeia de caracteres é null ou empty, ou seja, caso essa variável Connect._message que está sendo passada como parâmetro seja null ou empty, ira retornar um boolean true, caso contrário irá retornar false, mas para satisfazer a condição do seu If, o valor retornado tem que ser false, por conta do sinal de exclamação.
exemplo:
var exemplo = null;
if(string.IsNullOrEmpty(exemplo)){
//a condição deve ser true para prosseguir
//se a variavel exemplo for null ou empty, irá satisfazer a condição do If
//pois a condição pede que o valor seja null ou empty
}

var exemplo2 = 'teste';
if(!string.IsNullOrEmpty(exemplo)){
//a condição deve ser false(por conta do !) para prosseguir
//ele verifica a variável, como nesse caso ela tem valor, o IsNullOrEmpty irá
//retornar false, pois não é null nem empty a variavel
}

Answer: Em várias linguagens de programação você encontrará este caractere como um símbolo de negação. Ele nega um determinado valor.
Em seu exemplo: !string.IsNullOrEmpty(Connect._message)), o método IsNullOrEmpty está verificando se seu texto (Connect._message) é nulo ou vazio. Caso esta verificação retorne verdadeira (true), o símblo ! negará esta informação fazendo com que o resultado final seja falso (false).
O mesmo ocorre no processo inverso, se o resultado de IsNullOrEmpty for falso (false), o símbolo ! negará esta informação fazendo com que o resultado final seja verdadeiro (true).


Derivative to function ratio

Question: Is there a physical meaning for derivative of the function to function ratio? That is, this quantity,
$$
Q(x) = \frac{1}{f(x)}\frac{df(x)}{dx}
$$
Like for instance, if $f$ is the potential energy, this would be work to potential energy ratio.
Or even what can we say about $Q(x)$, say when $Q(x)<0$.
Comment: I also learned that this is called 'logarithmic derivative'.
https://en.wikipedia.org/wiki/Logarithmic_derivative
Comment: This is the scaling factor of the derivitive to the function. This quantity gives an intuition of how the function relates to its gradient.
Answer: This would give
$$
\int\limits_{x_0}^x \!Q(\xi) \, d\xi = \ln \frac{f(x)}{f(x_0)} \iff \\
f(x) = f(x_0) \exp {\int\limits_{x_0}^x \! Q(\xi) \, d\xi}
$$
An example would be a radioactive decay process ($Q$: decay constant)
Another: light absorption ($Q$: attenuation coefficient).
Answer: It is also $\frac {d(\ln(f(x))}{dx}$.    Note that it has units of the units of $f$ divided by length, so it can be a scale length that shows how quickly $f$ changes.
Answer: I know in Physics they use that $\frac{dN}{dt}=Nk$
for various uses so you could use it to show whether a relationship is exponential or not
Comment: Hmmm I think it is quite hard to give a general meaning to something like that, you could also see it as some kind of relative stability.
Comment: I get that - I know the relationship is exponential but wanted to know the physical significance of it. Like mvw says, attenuation coefficient gives a good meaning to it.
Answer: If $f(t)$ measures the size of the population, and $t$ is time, then $Q(t)=f'(t)/f(t)$ is the rate of change of the population per capita.
For example, if each individual reproduces at a constant rate $r$, then $f'(t)/f(t)=r$, so we get exponential population growth $f(t)=f(0) \, e^{rt}$.
But if the per capita growth rate decreases linearly with the size of the population (due to limited resources, for example), $f'(t)/f(t)=r(1-f(t)/K)$, we get logistic growth.
Comment: Thanks! Yes, I can see that in case of basic exponential/logistic model. What if $f(t)$ is the rate $r(t)$, where the growth rate $r$ depends on time? How do we interpret it?
Comment: You mean $Q(t)$? Then you get something which I don't know a name for, but which can be solved by separation of variables: $f'/f=r$ gives $\int df/f=\int r(t) \, dt$, etc.
Comment: No, then I mean the quantity $r'(t)/r(t)$. I know $r$ follows exponential as well, but I don't know what the quantity would mean. It is some sort of relative rate of change of growth over time.
Comment: Well, if $r(t)$ is the per capita growth rate, then $r'(t)/r(t)$ is rate of change of the per capita growth rate per per capita growth rate... :-)

Derivative to function ratio


Let $w<x$ be integers with $x^2-w^2$ beeing a square. Which condition they must satisfy for a $y$ to exist with $y^2-x^2$, $y^2-w^2$ being squares?

Question: Let $(w,x)$ be two integers with $x^2-w^2$ beeing a perfect square. One simple example is $(w,x)=(4,5)$, since $5^2-4^2=9=\square_1=3^2$.
In this case we cannot find a third integer $y$ which satisfies that the differences $y^2-x^2=\square_2$ and $y^2-w^2=\square_3$ are again perfect squares.
A working example would be $(w,x)=(264,520)$ or $(w,x)=(264,561)$, since in both cases an integer $y=1105$ satisfies $y^2-x^2$ and $y^2-w^2$ beeing squares.
My question:
Does there exist a condition on $w,x$ that I may use to quickly check, whether such a third integer $y$ exist? It is quite sufficient (and very helpful) for me if this condition predicts/implies that for given $w,x$ there can be no such $y$.
It would be great, if we could determine this $y$ directly at the same time (although I guess it is almost impossible to obtain $y$ directly without bruteforce).
What I investigated so far:
I searched in various approaches to extract such a condition. For example I found in the paper entitled "Cycles" by R. C. Lyness a condition that produces cycles. For example I could generate:
[[697.   153.   185.   104.   672.   680.  ]
 [697.   705.3  680.   187.2  153.   107.87]
 [697.   491.4  107.87 479.42 705.3  852.81]
 [697.   842.78 852.81 130.43 491.4  473.78]
 [697.   672.   473.78 822.22 842.78 185.  ]
 [697.   153.   185.   104.   672.   680.  ]]

But it seems not to give me a condition that enables me to check whether for two given integers $w<x$ such a third integer $y$ exist. My code for producing Lyness Cycles is given below:
def get_6tuple(tp:list[float]) -> list[float]:
    w = tp[0]
    x = tp[1]
    y = tp[2]
    return [y,w,x,sqrt(x**2-w**2),sqrt(y**2-x**2),sqrt(y**2-w**2)]

def rotate_np(tuple:np.ndarray) -> np.ndarray:
    p = tuple[0]
    v = tuple[4]
    w = tuple[5]
    return [p, np.float(p*w/v), w, np.float(tuple[2]*w/v), tuple[1], np.float(p*tuple[3]/v)]

def generate_cycle_np(triple:np.ndarray) -> np.ndarray:
    res = np.empty((6,6), dtype=np.float)
    tuple = np.array(get_6tuple(triple), dtype=np.float)
    for i in range (0,6):
        res[i]=tuple
        tuple = rotate_np(tuple)
    return res

print(np.array_str(generate_cycle_np([153, 185, 697]), precision=2, suppress_small=True))

Comment: I edited one of my answers to show new developments. I hope you like them.
Answer: I can easily show you that a finite search is enough.
Notice that for positive integers $b>a$, we have $b^2-a^2\geq (a+1)^2-a^2 =2a+1$.
Moreover, $b^2-a^2 \geq b^2-(b-1)^2 =2b-1$.
So if you give me $x$ and want me to determine whether there exist $t>s$ such that $t^2-x^2=s^2$, which is equivalent to $t^2 -s^2 =x^2$, I know that $s$ cannot be bigger than $\frac{x^2 -1}{2}$ and that $t$ cannot be bigger than $\frac{x^2 +1}{2}$. $\blacksquare$
I will leave you to figure out whether there are more efficient algorithms for your purpose.
$\\$
One suggestion:
Suppose you give me $x,w$ and you need me to find $y$ such that $x^2 +a^2 =w^2 +b^2 =y^2 $.
All Pythagorean triples are of the form $(t^2-s^2, 2st, t^2+s^2)$.
The idea would then be to solve $x=t^2-s^2$ or $x=2st$, and then do the same for $w$. This gives you every relevant Pythagorean triple.
Both possibilities $x=2st$ and $x=t^2-s^2=(t-s)(t+s)$ involve nothing more than factorising $x$.
Maybe to make the algorithm even more efficient, you can eliminate some cases based on $\mod{4}$ or something like that.
Comment: I'm afraid that some brute force might be needed. The "neatest" approach will probably, at the bare minimum, involve finding the prime factors of $x$ and $w$, which requires checking every prime up to a certain size.
Comment: Thank you for this first hint/solution. Indeed it would be really great to have a condition that verifies the existence of $y$ using "one shot" (without searching/itearting or recursion).  Your approach, however, is a very good start.
Comment: In this case it would be really great to have a verifier that is as most fast/efficient as possible.
Comment: If brute force is the only way, then we can consider having a very large prime table at hand. Our implementation incorporates a really large prime table.
Comment: Added a suggestion
Answer: For there to be two solutions, the variable $\space y\space$ must have two distinct prime factors of the form
$\space 4x+1, x\in\mathbb{N}.\quad$
There will be
$\space 2^{f-1}\space$
primitive solutions (those with no common divisors)  where
$\space f\space $ is the number of such factors. For example,
$\space 65=5\times13\space$ so there are
$\space 2^{2-1}=2\space $ such solutions. There "can" be
$\space 3\space$ solutions but one of those will be imprimitive like your
$\space 264,520 \space$
where there are non-primitive solutions for each:
$\space(264,448,520)=8\times (33,56,65)\space $ and
$\space(520,576,776)=8\times (65,72,97).\qquad $
To "know" there will be $\space 3\space$ solutions we must also "know" there will be $\space 4\space$ solutions. For example,
$\space 1105=5\times13\times 17\space$ so there are $\space 2^{3-1}=4\space$ solutions.
Note: Wolfram Alpha can find these factors as fast as you can type them
here.
Wolfram Alpha can also provide a list of primes in a defined range and any product and/or power of these where $\space p=4x+1\space$ is a valid $\space y$-value for your purposes.
To find these solutions, we begin with Euclid's formula for generating triples $\space(A,B,C)\space$ where $\space A^2+B^2=C^2.\quad$
Note: ($y=C\space$ in your case.)
$$ A=m^2-k^2,\quad B=2mk,\quad C=m^2+k^2$$
If we solve the $\space C$-function for $\space k\space$ and test a defined range of $\space m$-values, those that yield integers are for valid $\space (m,k)\space$ solutions in the formula.
$$C=m^2+k^2\implies k=\sqrt{C-m^2}\\
  \qquad\text{for}\qquad \bigg\lfloor\frac{ 1+\sqrt{2C-1}}{2}\bigg\rfloor \le m \le \big\lfloor\sqrt{C-1}\big\rfloor$$
The lower limit ensures $m>k$ and the upper limit ensures $k\in\mathbb{N}$.
$$C=1105\implies \bigg\lfloor\frac{ 1+\sqrt{2210-1}}{2}\bigg\rfloor=24 \le m \le \big\lfloor\sqrt{1105-1}\big\rfloor=33\quad \\
\text{and we find} \quad m\in\{24,31,32,33\}\Rightarrow
 k\in\{23,12,9,4\}\\$$
$$f(24,23)=(47,1104,1105)\quad
f(31,12)=(817,744,1105)\\
f(32,9)=(943,576,1105)\quad
f(33,4)=(1073,264,1105)\quad $$
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/134231/discussion-on-answer-by-poetasis-let-wx-be-integers-with-x2-w2-beeing-a-s).
Answer: Edit, too big for a comment.
The triples found where
$\space x^2-y^2, y^2-x^2, y^2-w^2\space$
are all squares depends on the software used to search. In one version, I generated sets of two values and, if their square difference was a square, I tested to see if both values were part of a triple with the same $\space y$-value. We have seen those results.
In another test, I found that
$\space x-y=1\space$ in all cases, e.g.
\begin{align*}
d^2=x^2-y^2\space &\qquad\qquad(w,x,y)\\
d=27720\space&(384199200,384199201,543339720)\\
d=92672\space&(4294049816,4294049817,6072703488)\\
d=185600\space&(17223654596,17223654597,24357925924)\\
d=188160\space &(17702074940,17702074941,25034514463)\\
d=198144\space &(19630499812,19630499813,27761719071)\\
\end{align*}
Finally, I used a formula I developed in $\space 2009 \space$ which generates only the subset of triples where
$\space GCD(A,B,C)\space$ is an odd square. This includes all primitives and some imprimitives that are
$\space 9, 25, 49, 81, \cdots$ multiples of primitives.
\begin{align*}
A&=&(2n-1)^2+  & 2(2n-1)k \\
B&=&           & 2(2n-1)k+ 2k^2 \\
C&=&(2n-1)^2+  & 2(2n-1)k+ 2k^2 \\
\end{align*}
Here is a sample of the sets within the subset that it produces.
$$\begin{array}{c|c|c|c|c|c|}
Set_n & k=1 & k=2 & k=3 & k=4 & k=5\\ \hline
Set_1 & 3,4,5 & 5,12,13& 7,24,25& 9,40,41& 11,60,61\\ \hline
Set_2 & 15,8,17 & 21,20,29 &27,36,45 &33,56,65&39,80,89\\ \hline
Set_3& 35,12,37& 45,28,53& 55,48,73&65,72,97& 75,100,125 \\ \hline
Set_{4} &63,16,65 &77,36,85 &91,60,109 &105,88,137&119,120,169\\ \hline
\end{array}$$
In a new program, I looped values of
$\space(n,k)\space$ and tested those to see if
$\space\sqrt{\mid B^2-A^2\mid}\space$ was an integer. This automatically makes
$\space C^2-B^2=A^2\space\text{and}\space C^2-A^2=B^2.\quad$ Here is a sample of what it finds with user direction $\space 5\space$ sets and $\space 2\space$  triples per set.
\begin{align*}
d^2=\mid x^2-y^2\mid \,&\quad F(n,k)=(w,x,y)\\
d=94930419\, & F(1,6889)=(13779,94930420,94930421)\\
d=94957979\, & F(1,6890)=(13781,94957980,94957981)\\
d=948954599\, & F(2,21781)=(130695,948954608,948954617)\\
d=950610791\, & F(2,21800)=(130809,950610800,950610809)\\
d=2148466763\, & F(3,32773)=(327755,2148466788,2148466813)\\
d=2148728975\, & F(3,32775)=(327775,2148729000,2148729025)\\
d=4295254539\, & F(4,46339)=(648795,4295254588,4295254637)\\
d=4295439911\, & F(4,46340)=(648809,4295439960,4295440009)\\
d=6098386239\, & F(5,55215)=(993951,6098386320,6098386401)\\
d=6101478923\, & F(5,55229)=(994203,6101479004,6101479085)\\
\end{align*}
Here is the code that yielded these data.
110 rem Find w,x,y diff perfect squares
120 print "Enter lowest Set number  "; : input l0
130 print "Enter highest Set number "; : input n9
140 print "Number of Triples per Set  "; : input c9
150 k9 = 10000000
160 print "d^2=\mid x^2-y^2\mid \,&\quad F(n,k)=(w,x,y)\\"
170 for n1 = l0 to n9
180      c1 = 0
190   for k1 = 1 to k9
200     w1 = (2*n1-1)^2+2*(2*n1-1)*k1
210     x1 = 2*(2*n1-1)*k1+2*k1^2
220     d1 = sqr(abs(w1^2-x1^2))
230     if d1 = int(d1)
240       y1 = (2*n1-1)^2+2*(2*n1-1)*k1+2*k1^2
250       print "d=" str$(d1)"\, & ";
260       print "F(" str$(n1)"," str$(k1)")=";
270       print "(" str$(w1)"," str$(x1)"," str$(y1)")\\"
280       c1 = c1+1
290       if c1 = c9
300         k1 = k9
310       endif
320     endif
330   next k1
340 next n1

Comment: @Eldar Sultanow Yes, we can get an imprimitive by multiplying all three terms of a primitive by the same multiple greater than 1. By the way, half of all triples have $\space w>x.\space$ Note the operator in my examples.
Comment: @Eldar Sultanow  Euclid's formula
$\space  A=m^2-k^2,\space B=2mk,\space C=m^2+k^2\space $
generates trivials like
$f(1,1)=(0,2,2)$ and doubles, square multiples, and doubles of square multiples of triples like these:

$$f(3,1)=(8,6,10)=2\times (3,4,5)\\
f(4,2)=(12,16,20)=2^2\times (3,4,5)\\
f(6,3)=(27,36,45)=3^2\times (3,4,5)\\
\quad f(6,2)=(32,24,40)=2\times2^2\times(3,4,5)$$

My formula generates only the odd square multiples like
$$f(2,3)=(27,36,45)=3^2\times (3,4,5)$$
In Euclid's formula
$\space m=2n-1+k.$
Comment: @Eldar Sultanow  I encourage you to explore the output of this program. If you prefer Python, so be it, but this is very fast code, even in BASIC as shown here. Particularly fascinating is that all members of
$\space Set_1\quad 6889\space$
and above are valid triples, as are the first members of all sets
$\space 8193\space$
and above with only $\space28\space$ triples in between.  My email is firstname.lastname@example.com. Let me know what you find.
Comment: @Eldar Sultanow Correction. With higher limits there a more midrange triples but nothing like the apparently unlimited triples at the extremes $6889$ and $8193.$
Comment: @Eldar Sultanow  I made edits which make the code look as far as needed into each set to reveal any number of specified members. You might just consider downloading free Chipmunk basic and running "this" code.
Comment: @Eldar Sultanow  I tried the first three  triples in your list but I could not figure out how to get a square out of any of the differences. I believe the triples are invalid because, starting with the first one,
$\quad d=1562296.95836131\quad f(600,52)=(1562297,130104,1567705)\quad $as opposed to $\quad d=62627172846\quad F(600,176360)=(424348881,62628610480,62630048081)\quad$ which is the first one my program reveals in $\space Set_{600}.\quad$ Also, you are generating only one triple per set instead of what I infer to be the four specified by input. Let me know what you find.
Comment: @Eldar Sultanow  For the examples shown in the answer above, the user entry part looked like this.

\begin{align*}
&\text{ >run }\\
&\text{ Enter lowest Set number  ? 1 }\\
&\text{ Enter highest Set number ? 5 }\\
&\text{ Number of Triples per Set  ? 2 }\\
\end{align*}
Comment: Thank you for this update. Question: We get a subset of the triples -- all primitive ones -- right? If so, we could easily generate all non-primitives by multiplication.
Comment: Thanks for checking. There obviously is a flaw in my code and I am trying to fix it and provide a link with the corrected Python notebook. Which input values `l0`, `n9` and `c9` did you use while running your code?
Answer: Euler has given solution, as re-produced in
Tito Piezas web site. His web site is:
"Collection of algebraic identities".
$y^2-w^2=q^2$
$x^2-w^2=r^2$
$x^2-y^2=p^2$
$(x,y,z)=(434657,420968,150568)$
$(p,q,r)=(108225,393120,407745)$
Comment: I am searching for a general condition in terms of $w$ and $x$.
Comment: Euler imposed the condition, (pqrs) & [(p^2-q^2)(r^2-s^2)] both squares.  He took (p,q,r,s)=(4,9,49,81). He then took (a,b,c,d)=[(pr+qs),(ps-qr),(pr-qs),(ps+qr)].  After which he got (x,y,w)=[(1/2(a^2+b^2),1/2(a^2-b^2),1/2(c^2-d^2)]. Thus we have, (x,y,w)=(434657,420968,150568). And (p,q,r)=(108225,393120,407745). (p,q,r) are related as: {p^2+q^2=r^2].


Spring inject bean into startup class during server start up

Question: My bean is :
@Component
public class KidsServerStartUp implements ServletContextListener
{
     UploadService uplService;

    @Autowired
    public void setUplService( UploadService uplService )
    {
        this.uplService = uplService;
    }
    public void contextInitialized(ServletContextEvent event) {
       System.out.println ( uplService );
    }
}

In web.xml; I am firstly calling spring framework to set all beans ; then setting the startup listener :
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.kids.util.KidsServerStartUp</listener-class>
    </listener>

uplService is getting printed as null !
Comment: You are saying `OptimizeImages` is injected to `UploadService` but your code suggestes `UploadService` is injected to `OptimizeImages`, which one is correct? Where is the task scheduling code written?
Comment: Arun, I have done some re-factoring above so that the problem is more obvious. Thanks for looking into it.
Answer: I think what you are looking for is something like this post.
Since you are using a ServletContextListener spring context will not be used for the creation of the Listener class. But we can get access to the ApplicationContext using the ServletContext.
public class KidsServerStartUp implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
        UploadService uplService = springContext.getBean(UploadService.class);
        System.out.println ( uplService );
    }
}


(discord.py) Bot doesn't respond to any message sent by the member. (No errors encountered)

Question: I am coding a bot for my server. But I can't really seem to find what the problem is. Before I had added a help command (s!help) and a ping command (s!ping) the bot was responding all fine. But after I added it, it just doesn't respond to any command. I even encountered no errors. Please help?
Also: The bot is online and it prints that it is connected to Discord and no errors.
Here's my bot's code:
from keep_alive import keep_alive
import discord
import os
import asyncio

client = discord.Client()

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='SqdNoises\' Lounge'))
    print("Connected to Discord as {0.user}".format(client))

async def on_message(message):
    msg = message.content
    sendmsg = message.channel.send
    author = message.author
    mention = message.author.mention
    reply = message.reply
    channel = message.channel
    typing = message.channel.trigger_typing
    dm = await message.author.create_dm()
    delete = message.delete

    if author == client.user:
        return

    if msg.lower() == 'hi':
      await typing()
      await asyncio.sleep(0.5)
      await sendmsg('hello ' + mention + '!')

    if msg.lower() == 'hello':
      await typing()
      await asyncio.sleep(0.5)
      await sendmsg('hello ' + mention + '!')

    if (msg.lower()).startswith('hi i am new'):
      await typing()
      await asyncio.sleep(0.5)
      await reply('hello new!')

    if (msg.lower()).startswith('ping me'):
      await typing()
      await asyncio.sleep(1)
      await sendmsg('ok, ' + mention + ' ')

    if (msg.lower()).startswith('hi im new'):
      await typing()
      await asyncio.sleep(0.5)
      await reply('hello new!')

    if (msg.lower()).startswith('hi i\'m new'):
      await typing()
      await asyncio.sleep(0.5)
      await reply('hello new!')

    if msg.lower() == 'dm me':
      await typing()
      await asyncio.sleep(0.5)
      await sendmsg('Check your DMs for a message from me!')
      await dm.send('I DMed you as you asked me to. ')

    if msg == 's!ping':
      await typing()
      await sendmsg('**Summon\'s Latency: ' + str(client.latency) + 'ms**')

    if msg == 's!help':
      await typing()
      await asyncio.sleep(1)
      await sendmsg('Oh you need help? Check your DM\'s for a message from me!')
      await dm.send('*Somebody once told me the world is maccaroni...*\n\n**Summon -- Help (s!help)**\n*Please note: This bot is not for use in any other servers. This is just a personal bot for SqdNoises\' Lounge.*\n**Commands:**\n»dm me - DM\'s a message to you.\n»hi - sends you a hello\n»hi i am (message) - replies with \"hello (message)!\"\n»ping me - pings you\n»hi/hello - says hello to you\ns!ping - sends the ping of bot\n\n*Bot made and coded by SqdNoises*')

keep_alive()

token = os.environ['TOKEN']
client.run(token)

Can you please tell me what's wrong?

Thanks in advance. -sqd
Comment: Does the bot appear online?
Comment: @mousetail yes, it even prints that the bot is connected
Comment: Does the bot never respond or only after you try to call `s!help`?
Comment: @mousetail as i mentioned, `But after I added it, it just doesn't respond to any command.` yes it doesnt respond to anything
Comment: @mousetail are you there?
Answer: You didnt put @client.event on top of your async def on_message
Comment: No, you need @client.event in all of your events.
Comment: excuse me, it works if there is @client.event already present
Comment: but still i'll try it if you are saying
Comment: oh wt[REDACTED] no way


Mostrar a data do arquivo no PHP

Question: estou tentando mostrar a data dos respectivos arquivos que estão dentro de um diretório, porém está mostrando apenas a data do ultimo arquivo em todos os arquivos... Alguma ideia?
<?php
$path = "arquivos/";
// Título
echo "
Lista de Arquivos:

";
// Abre a tabela, cria títulos
echo "
";
echo "
 Nome	 ";
echo " Data
";

$data = date("d/m/Y H:i:s", filemtime("$path"));
// Loop que gera registros
foreach (new DirectoryIterator($path) as $fileInfo) {

if($fileInfo->isDot()) continue;

// Imprime linhas de registros
echo "

            getFilename() ."'>".$fileInfo->getFilename()."

       ".$data."

";
}
// Fecha a tabela
echo "
";
?>

Comment: Bom, a variável `$data` não é alterada dentro do laço de repetição, então é esperado que seja exibido o mesmo valor. Você não deveria atualizar o valor dela para cada arquivo?
Comment: A variável `$data` está retornando apenas a data da pasta em `$path`.
Answer: A variável $data está estática pegando apenas a data da pasta atribuída na variável $path.
Use a função getMTime() para pegar as datas da última modificação dos arquivos e formate-as com date().
Troque a linha:
".$data."

Por:
".date("d/m/Y H:i:s", $fileInfo->getMTime())."

Comment: Obrigado, retirei a variável e coloquei direto como vc mostrou. Faltava o fileInfo rsrs

Mostrar a data do arquivo no PHP


Add a nav bar to all templates

Question: I want to show a nav bar on every page.  In PHP, I would write the nav bar then include it on the other pages.  I tried to include or extend the nav bar template into the other templates, but it didn't work.  It only outputs "This is the home page."  How do I correctly include the nav bar in every template?
layout.html
<!doctype html>

        {% block navbar %}

NAVBAR

        {% endblock %}

        {% block content %}
        {% endblock %}

index.html
This is the home page.
{% extends "layout.html" %}

{% block navbar %} {% endblock %}

{% block content %}

This is the homepage!

{% endblock %}

Comment: But how it is possible to highlight which page been active in nav?
Answer: You can include the nav bar in every page.
nav.html

NAVBAR

layout.html: note the {% include 'nav.html' %}
<!doctype html>

    {% include 'nav.html' %}

    {% block content %}
    {% endblock %}

index.html
{% extends "layout.html" %}

{% block content %}

This is the homepage!

{% endblock %}

sometimes, it is a good way to design you web page. You break you page to, for example: head.html, nav.html, footer.html... you can include them in the layout.html to use them.
Comment: Thank you. `{% include 'nav.html' %}` is exactly what I was looking for. I wanted to explicitly keep my base and navbar (etc.) in different files to allow for swapping of navbar, easy editing. But I could not find how to "import" navbar.html into base.html.
Answer: Create a base template with the layout and naviagation that will be common to all pages.  Then extend this template to create the actual pages.  Add blocks to the base template that can be overriden in the others.
base.html
<!doctype html>

        <meta charset="utf-8"/>
        <title>{% block title %} - My Site {% endblock %}</title>

Navbar

        {% block content %}{% endblock %}

index.html
{% extends 'base.html' %}

{% block content %}

{% block title %}Home{% endblock %}

Hello, World!

{% endblock %}

Note that the navbar is just defined in the base template.  It does not need a block, and the content from the child templates will be substituded in after it.
You can use a similar technique to control which item is highlighted in a navigation bar.
Answer: If you want to use the same navbar in every page, you don't need the {% block navbar %}...{% endblock %} in layout.html. Alternatively, you might have to use {{ super() }} as described here.

Add a nav bar to all templates


border set like stack of cards

Question: I am wondering what the best way is solve this problem I have a text block with an image around a border and I can add properties and I want to add a border around it to be like a stack of cards. I'll demonstrate what I mean with pictures. The first picture I have is what displays just now.

The second picture is what I want it to display if there is properties added in this example there would be 5 added properties.
Answer: Use  many borders that overlap, with a non transparent background.
The xaml  appearing order is the painting order.
So the last components appear over the first ones.
All the components are in a grid that allow many children.
<code><Grid>
    <Grid.Resources>
        <system:Double x:Key="width1" >100</system:Double>
        <system:Double x:Key="height1" >30</system:Double>
    </Grid.Resources>

    <Border BorderThickness="1" BorderBrush="Gray"
            Background="White"
            Margin="120 80 0 0"
            Width="{StaticResource width1}"
            Height="{StaticResource height1}" />

    <Border BorderThickness="1" BorderBrush="Gray"
            Background="White"
            Margin="110 90 0 0"
            Width="{StaticResource width1}"
            Height="{StaticResource height1}" />

    <TextBlock Text="+6"
               Padding="20 7 0 0"
               Margin="100 100 0 0"
               Background="Gray"
               Width="{StaticResource width1}"
               Height="{StaticResource height1}"/>

</Grid>
</code>
Note : the use of resources for setting same size to all components
Regards
Comment: Thanks a lot, I was considering using lines but then that would be a lot more code but wasn't sure what would have been more effective :)
Comment: Actually you're right, you may use lines or preferably Rectangles. But borders are cool. they allow to rounded corners ( BorderRadius property)
Comment: next step is to make a custom control that is a sub class of Grid. Add a dependency property for the count. And may be add some few dep. prorperty for the different appearances properties ( color of background, lines ...)

border set like stack of cards


Can I create a fixed grid with singularity?

Question: Last week I discovered the Compass grid Singularity, which is impressing.
I'm going to design my next project based on Singularity.
Unfortunately I need to use a fixed grid (width=1024px).
Is it possible to design a fixed grid with Singularity?
Thanks
Answer: Singularity works a little bit differently than other grid systems in that it only concerns itself with the grid and not the container. If you'd like a fixed container, simply add width: 1024px; to whatever your container class is, and you'll have a fixed width container.
Answer: You're in luck because yes it is possible!
Just set width: 1024px; on whatever element contains your columns:
HTML:

stuff

    stuff

Sass:

  .container {
    width: 1024px;
    margin: 0 auto;
  }

Your markup may be different, but that is one solution.


Erro de certificado

Question: Estou tentando acessar o site e enviar documentos e está dando problema de HTTP, apareceu a seguinte mensagem.
Ocorreu um erro ao fazer a solicitação HTTP para https://mni1g....br/intercomunicacao. Isso pode ser devido ao fato de que o certificado do servidor não está configurado corretamente com HTTP.SYS no caso HTTPS. Isso também pode ser causado por uma incompatibilidade da ligação de segurança entre o cliente e o servidor.
Como eu devo por ?
Answer: Isso acontece pq vc esta tentando fazer uma requisição sem certificado SSL, usando o http ao inves do https, para corrigir, antes de cada solicitação sem SSL coloque:
<code>System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
</code>

Erro de certificado


Late static binding in PHP, vars are being shared between child classes

Question: Maybe my question has been asked several times, but...
I have the following code
abstract class ParentClass
{
    protected static $count=0;
    public static function inc()
    {
        static::$count++;
    }
    public static function getCount()
    {
        return static::$count;
    }
}

class FirstChild extends ParentClass
{

}
class SecondChild extends ParentClass
{

}

And I use it just like this
FirstChild::inc();
echo SecondChild::getCount();

It shows me "1". And as you probably guess I need "0" :)
I see two ways:

Adding protected static $count=0; to each derivative classes
Make $count not integer but array. And do sort of such things in inc and getCount methods:
static::$count[get_called_class()]++;

and
return static::$count[get_called_class()];

But I think these ways are a bit ugly. First - makes me copy/paste, what I'd like to avoid. Second - well, I don't know:) I just don't like it.
Is there a better way to achive what I want?
thanks in advance.
Comment: And why not use non static's ?
Answer: No, you have exactly laid out the two most practical options to address this. PHP cannot work magic; when you declare a static protected property you get exactly that: one property. If the syntax you give did work that might be good news for everyone who needs to do that, but it would be absolutely horrible news for everyone else who expects PHP OOP to behave in a somewhat sane manner.
And for the record, if you don't need a separate counter for all derived classes without exception then I consider the explicit protected static $count = 0 in derived classes that do need one to be a beautiful solution: you want your own counter, you ask for one, and that fact remains written in the code for everyone to see.
Answer: I think for what you're trying to do, having just an interface method (such as getCount()) in the abstract class and the counter in the derivate class, your first choice, is the least worst option. It doesn't make sense to have abstract static count in the parent class if you're not counting all instances for that count.
In general, I think the whole idea is a bit ugly, thus implementations would be ugly, too :)
Answer: You can declare protected static $count=0; for each child class, that way it will be unique for each child class but common for all instances of the classes. That is the most elegant solution to his problem.
abstract class ParentClass
{
    public static function inc()
    {
        static::$count++;
    }
    public static function getCount()
    {
        return static::$count;
    }
}

class FirstChild extends ParentClass
{
    protected static $count=0;
}
class SecondChild extends ParentClass
{
    protected static $count=0;
}


Integrating Dropzone.js into existing HTML form with other fields

Question: I currently have a HTML form which users fill in details of an advert they wish to post. I now want to be able to add a dropzone for uploading images of the item for sale.
I have found Dropzone.js which seems to do most of what I need. However, when looking into the documentation, it appears that you need to specify the class of the whole form as dropzone (as opposed to just the input element). This then means that my entire form becomes the dropzone.
Is it possible to use the dropzone in just part of my form, i.e. by only specifying the element as class "dropzone", rather than the whole form?
I could use separate forms, but I want the user to be able to submit it all with one button.
Alternatively, is there another library that can do this?
Many thanks
Answer: Here's another way to do it: add a div in your form with a classname dropzone, and implement dropzone programmatically.
HTML :

JQuery:
$(document).ready(function () {
    Dropzone.autoDiscover = false;
    $("#dZUpload").dropzone({
        url: "hn_SimpeFileUploader.ashx",
        addRemoveLinks: true,
        success: function (file, response) {
            var imgName = response;
            file.previewElement.classList.add("dz-success");
            console.log("Successfully uploaded :" + imgName);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
        }
    });
});

Note : Disabling autoDiscover, otherwise Dropzone will try to attach twice
Comment: With that, he can't use the default submit button, it doesn't respond to his question
Comment: but this still doesn't use the original form to submit
Comment: this was my issue and you resolved it, ty @Satindersingh
Comment: This helped a lot, you can setup any element as a dropzone if you setup the url manually. I used the success handler to post the filename to a hidden/disabled field in the primary form.
Comment: Its Asynchronous so file get save without submit button, On submit he can save uploaded files name into db
Comment: @Su4p : am glad it helps you,  also you can check blog article link for details explanation along with resize image option while uploading
Comment: @dangel I thought that was what I wanted too, but I am very happy with the resulting solution. I suggest you just submit the uploads right away.
Comment: @clement: OP doesn't want to add 'dropzone' class in form tag, coz this make whole form as dropzone. So with my answer he can add separate div inside form tag or outside form like as popup modal and by jQuery initialize dropzone.
Comment: To the beginners using Dropzone.js. To select a file, you will have to click on the div itself which is in this answer ``
Comment: There is already an option within dropzone.js to set the autoDiscover = false. Setting this option within the document load was too late in the page execution cycle for me.
Comment: Works like charm!
Comment: I got exactly what I'am looking for, thank you  @Satindersingh
Comment: `Dropzone.autoDiscover = false;` was what I looking for
Answer: I had the exact same problem and found that Varan Sinayee's answer was the only one that actually solved the original question. That answer can be simplified though, so here's a simpler version.
The steps are:

Create a normal form (don't forget the method and enctype args since this is not handled by dropzone anymore).
Put a div inside with the class="dropzone" (that's how Dropzone attaches to it) and id="yourDropzoneName" (used to change the options).
Set Dropzone's options, to set the url where the form and files will be posted, deactivate autoProcessQueue (so it only happens when user presses 'submit') and allow multiple uploads (if you need it).
Set the init function to use Dropzone instead of the default behavior when the submit button is clicked.
Still in the init function, use the "sendingmultiple" event handler to send the form data along wih the files.

Voilà ! You can now retrieve the data like you would with a normal form, in $_POST and $_FILES (in the example this would happen in upload.php)
HTML
<form action="upload.php" enctype="multipart/form-data" method="POST">
    <input type="text" id ="firstname" name ="firstname" />
    <input type="text" id ="lastname" name ="lastname" />

    <button type="submit" id="submit-all"> upload </button>
</form>

JS
Dropzone.options.myDropzone= {
    url: 'upload.php',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 5,
    maxFiles: 5,
    maxFilesize: 1,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    init: function() {
        dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
        document.getElementById("submit-all").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });

        //send all the form data along with the files:
        this.on("sendingmultiple", function(data, xhr, formData) {
            formData.append("firstname", jQuery("#firstname").val());
            formData.append("lastname", jQuery("#lastname").val());
        });
    }
}

Comment: +1 This seems to be the only working solution. Instead of doing formData.append one by one, you can also do
```$(":input[name]", $("form")).each(function () {
  formData.append(this.name, $(':input[name=' + this.name + ']', $("form")).val());
});```
(sorry I don't know how to put linebreaks here)
Comment: This solution is nice and works, but it doesn't redirect to the next page anymore, because of preventing the default submit behavior.
Comment: @TIUNDER  you can add redirect in success event
Comment: Not sure why, but I have to use $('#myDropzone').dropzone({...}) instead of Dropzone.options.myDropzone.

Other than that, worked nicely.
Comment: @TIIUNDER - its prepared for sending form info via ajax call without page reload - thats why there is e.preventDefault();
Comment: Is it possible to submit the form after `processQueue()` call? I try to use `submit()` or `click()`, both not work.
Comment: how can i append  another  input file for a single image?
Comment: Perfect! This is the closest i need!
Comment: @doflamingo I found it better to redirect/show confirmation inside the completemultiple event handler. Doing so in the success handler made it execute multiple times (for each file attached), which sometimes even interrupted the form upload altogether.
Comment: I get `Uncaught ReferenceError: dzClosure is not defined` when using this :( Does anyone know how I could fix that?
Comment: is this ajax request?
Comment: @HodorogeaAlexandru use: var dzClosure=this;
Answer: The "dropzone.js" is the most common library for uploading images.
If you want to have the "dropzone.js" as just part of your form, you should do the following steps:
1) for the client side:
HTML :
    <form action="/" enctype="multipart/form-data" method="POST">
        <input type="text" id ="Username" name ="Username" />

                <input name="file" type="file" multiple />

    </form>

        <button type="submit" id="submit-all"> upload </button>

JQuery:

2) for the server side:
ASP.Net MVC
    [HttpPost]
    public ActionResult Create()
    {
        var postedUsername = Request.Form["Username"].ToString();
        foreach (var imageFile in Request.Files)
        {

        }

        return Json(new { status = true, Message = "Account created." });
    }

Comment: Thanks for the post! Solved my problem. Another quick question, this does not work when no images selected(to upload), how to solve this?
Comment: when autoProcessQueue= false no events are fired
Comment: BTW: if you use controller action with model binding and submit your form like this the model will be empty. For some reason this method doesn't bind the actual data to the model.
Comment: @Sato on click event of submit button you can check the length of accepted files on dropzone by using galleryfile.getAcceptedFiles().length and if there is no file uploaded you should submit your form.
Comment: @EdwardChopuryan This is not related to the method of submiting data by dropzone. Likely the problem is on your "naming convention" of input tags on your platform such as ASP.Net MVC.
Answer: I have a more automated solution for this.
HTML:
<form role="form" enctype="multipart/form-data" action="{{ $url }}" method="{{ $method }}">
    {{ csrf_field() }}

    <input hidden id="file" name="file"/>

Drop files here to upload

            You can also click to open file browser

    <button type="submit">Submit</button>
</form>

JavaScript:
Dropzone.options.fileUpload = {
    url: 'blackHole.php',
    addRemoveLinks: true,
    accept: function(file) {
        let fileReader = new FileReader();

        fileReader.readAsDataURL(file);
        fileReader.onloadend = function() {

            let content = fileReader.result;
            $('#file').val(content);
            file.previewElement.classList.add("dz-success");
        }
        file.previewElement.classList.add("dz-complete");
    }
}

Laravel:
// Get file content
$file = base64_decode(request('file'));

No need to disable DropZone Discovery and the normal form submit will be able to send the file with any other form fields through standard form serialization.
This mechanism stores the file contents as base64 string in the hidden input field when it gets processed. You can decode it back to binary string in PHP through the standard base64_decode() method.
I don't know whether this method will get compromised with large files but it works with ~40MB files.
Comment: If you want to add mutiple images you have to remove the html file input and add it quing js for each image $('#fileUpload').append('')  where content is the base64 encoded image.
Comment: This won't work reliably, as the input fields value has a browser capped max size. In my case the uploaded file is capped at 384kb, due to the base64 string not fitting completely into the value.
Comment: How do you decode  and process data from other fields that will be submitted together with the images?
Comment: @sam There is no need to decode the other fields. They are not getting encoded in the first place, only the file gets encoded.
Comment: Can you share some sample code for the html ,javascript and how to retrieve in laravel php.
Comment: the upload process with that html and javascript seems works to me, but  not work when I want to process on server side script.. i dont understand how to decode using base64_decode() on codeigniter controller to upload file :D
Comment: i used file_put_contents() to save decoded image file, it's works.. but the file can't open/view
Comment: @bungdito Sorry, can't say anything about CI. I haven't done file handling in it.
Comment: this will only work for one image, if you try to add more the
 $('#file').val(content); will override the input and only the last image will be sent to the server, how can I change this to send multiple images?
Comment: @AleXzpm Sorry, that was the first and last time I used Dropzone, can't help you for the time being.
Comment: @AleXzpm if you can suggest an edit, please do so, I'll accommodate it. Or you can post a separate answer extending mine.
Comment: This is the only answer that works with a plain form submit, so does not require JS to handle the form submit.
Answer: Enyo's tutorial is excellent.
I found that the sample script in the tutorial worked well for a button embedded in the dropzone (i.e., the form element). If you wish to have the button outside the form element, I was able to accomplish it using a click event:
First, the HTML:
<form id="my-awesome-dropzone" action="/upload" class="dropzone">

        <input name="file" type="file" multiple />

</form>
<button type="submit" id="submit-all" class="btn btn-primary btn-xs">Upload the file</button>

Then, the script tag....
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element

    // The configuration we've talked about above
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 25,
    maxFiles: 25,

    // The setting up of the dropzone
    init: function() {
        var myDropzone = this;

        // Here's the change from enyo's tutorial...

        $("#submit-all").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            myDropzone.processQueue();
        });
    }
}

Comment: You cannot have a form inside a form and submit.
Comment: This doesn't answer the original question. The original question was how to use Dropzone with an existing form, not about the location of the button to trigger the action.
Comment: When I try this, the dropzone-previews container seems to be ignored.  Dropzone just adds the previews to the bottom of the form.  You will need to add 'previewsContainer: '.dropzone-previews',' to your configuration.
Answer: Further to what sqram was saying, Dropzone has an additional undocumented option, "hiddenInputContainer".  All you have to do is set this option to the selector of the form you want the hidden file field to be appended to.  And voila!  The ".dz-hidden-input" file field that Dropzone normally adds to the body magically moves into your form.  No altering the Dropzone source code.
Now while this works to move the Dropzone file field into your form, the field has no name.  So you will need to add:
_this.hiddenFileInput.setAttribute("name", "field_name[]");

to dropzone.js after this line:
_this.hiddenFileInput = document.createElement("input");

around line 547.
Answer: I want to contribute an answer here as I too have faced the same issue - we want the $_FILES element available as part of the same post as another form. My answer is based on @mrtnmgs however notes the comments added to that question.
Firstly: Dropzone posts its data via ajax
Just because you use the formData.append option still means that you must tackle the UX actions - i.e. this all happens behind the scenes and isn't a typical form post. Data is posted to your url parameter.
Secondly: If you therefore want to mimic a form post you will need to store the posted data
This requires server side code to store your $_POST or $_FILES in a session which is available to the user on another page load as the user will not go to the page where the posted data is received.
Thirdly: You need to redirect the user to the page where this data is actioned
Now you have posted your data, stored it in a session, you need to display/action it for the user in an additional page. You need to send the user to that page as well.
So for my example:
[Dropzone code: Uses Jquery]
$('#dropArea').dropzone({
    url:        base_url+'admin/saveProject',
    maxFiles:   1,
    uploadMultiple: false,
    autoProcessQueue:false,
    addRemoveLinks: true,
    init:       function(){
        dzClosure = this;

        $('#projectActionBtn').on('click',function(e) {
            dzClosure.processQueue(); /* My button isn't a submit */
        });

        // My project only has 1 file hence not sendingmultiple
        dzClosure.on('sending', function(data, xhr, formData) {
            $('#add_user input[type="text"],#add_user textarea').each(function(){
                formData.append($(this).attr('name'),$(this).val());
            })
        });

        dzClosure.on('complete',function(){
            window.location.href = base_url+'admin/saveProject';
        })
    },
});

Comment: It is working, But I am uploading 3 images, it is only sending 2 images on the backend.
I have changed this below code:
            maxFiles:   10,
            uploadMultiple: true,
Why it is sending only 2 images?
Comment: I would try with an alternative image and see if its a problem with the files. Alternatively does your PHP/ASP etc give you any errors? It could be the image is too big, not enough disc space, server limits/settings etc.
Comment: No. My PHP has no error. It is uploading images correctly.
However, I got the solution. I changed below lines:
            url: myURL
            uploadMultiple: true,
            parallelUploads: 25,
            maxFiles: 25,
            autoProcessQueue: false,
            addRemoveLinks: true,
Comment: I find your explanations very interesting. I can't get the elements to go to the processing page. I think it has to do with sessions. Could you give an example of the php processing page or indicate why my _FILE and _POST elements are not resolving.
Comment: Just post to a page that does  and analyse it through the Browser console > Networking tab (thats what its called in Chrome) and see what outputs.
Answer: You can modify the formData by catching the 'sending' event from your dropzone.
dropZone.on('sending', function(data, xhr, formData){
        formData.append('fieldname', 'value');
});

Comment: I like this answer - but it would assume that fieldname and value have been populated. This is triggered on the upload which may occur at a separate time to the form submission. In otherwords you can't assume that when sending the image the form is filled out.
Answer: In order to submit all files alongside with other form data in a single request you can copy Dropzone.js temporary hidden input nodes into your form. You can do this within addedfiles event handler:
var myDropzone = new Dropzone("myDivSelector", { url: "#", autoProcessQueue: false });
myDropzone.on("addedfiles", () => {
  // Input node with selected files. It will be removed from document shortly in order to
  // give user ability to choose another set of files.
  var usedInput = myDropzone.hiddenFileInput;
  // Append it to form after stack become empty, because if you append it earlier
  // it will be removed from its parent node by Dropzone.js.
  setTimeout(() => {
    // myForm - is form node that you want to submit.
    myForm.appendChild(usedInput);
    // Set some unique name in order to submit data.
    usedInput.name = "foo";
  }, 0);
});

Obviosly this is a workaround dependent on implementation details. Related source code.
Comment: I basically used this approach, but due to apparent processing delays, in the end hooked up the file content processing under the `myDropzone.on("thumbnail", () => {})` event. Doing the processing immediately on `"addedFile"` the file might still be `undefined` upon access.
Comment: I'm trying to use this and it works in bringing the hidden file input field to the form, and when I submit, the post data shows my field `files[]` but it is blank no matter what I do. Any ideas? Doing it in Laravel if it makes any difference.
Comment: Hello! Why does selected file does upload but if file is dropped then not (error 4)?
Comment: @Ingus Because the hidden input is only used in Dropzone for opening the file picker. For uploading the files, it uses a custom AJAX to the URL specified in config. For security reasons, we cannot modify the files attribute of the `` and hence to allow modifications we need to upload using AJAX.
Answer: Working solution for 5.7.0 version
<form id="upload" enctype="multipart/form-data">
    <input type="text" name="name" value="somename">
    <input type="checkbox" name="terms_agreed">

        <button class="dz-button" type="button">
          Drop files here to upload
        </button>

    <input id="dz-submit" type="submit" value="submit">
</form>

Dropzone.autoDiscover = false;
new Dropzone("#upload",{
      clickable: ".dropzone",
      url: "upload.php",
      previewsContainer: "#previewsContainer",
      uploadMultiple: true,
      autoProcessQueue: false,
      init() {
        var myDropzone = this;
        this.element.querySelector("[type=submit]").addEventListener("click", function(e){
          e.preventDefault();
          e.stopPropagation();
          myDropzone.processQueue();
        });
      }
    });

Answer: Here is my sample, is based on Django + Dropzone. View has select(required) and submit.
<form action="/share/upload/" class="dropzone" id="uploadDropzone">
    {% csrf_token %}
        <select id="warehouse" required>
            <option value="">Select a warehouse</option>
                {% for warehouse in warehouses %}
                    <option value={{forloop.counter0}}>{{warehouse.warehousename}}</option>
                {% endfor %}
        </select>
    <button id="submit-upload btn" type="submit">upload</button>
</form>

Answer: This is just another example of how you can use Dropzone.js in an existing form.
dropzone.js :
 init: function() {

   this.on("success", function(file, responseText) {
     //alert("HELLO ?" + responseText);
     mylittlefix(responseText);
   });

   return noop;
 },

Then, later in the file I put
function mylittlefix(responseText) {
  $('#botofform').append('<input type="hidden" name="files[]" value="'+ responseText +'">');
}

This assumes you have a div with id #botofform that way when uploading you can use the uploaded files' names.
Note: my upload script returned theuploadedfilename.jpeg
dubblenote you also would need to make a cleanup script that checks the upload directory for files not in use and deletes them ..if in a front end non authenticated form :)
Comment: This doesn't submit dropzone images together with other form fields.  What you're doing is uploading images normally, saving the image names, and then re-submitting rest of the form fields with image names.
Answer: Try this

    Drop files here to upload

JS