Why is apache writing two access log outputs per request?

Question: We are currently running a apache2/mod-php site on docker, deployed to google kubernetes. In order to leverage the severity level filtering of google cloud logging I've created a LogFormat in our apache.conf that writes the logs output as structured JSON. Now I'm seeing two access log outputs in our logs. 1 is the correctly formatted CustomLog and the other seems to be a default access log of some sort.
Here's the apache conf:
  1 LogLevel info
  2
  3 LogFormat "{\"message\": \"%{X-Forwarded-For}i %l %u %t '%r' %>s %b '%{Referer}i' '%{User-Agent}i'\", \"severity\": \"INFO\"}" common
  4 CustomLog /dev/stderr common
  5
  6
  7 ErrorLogFormat "{\"message\": \"[%t] [%l] [pid %P] %F: %E: [client %a] %M\", \"severity\": \"ERROR\"}"
  8 ErrorLog /dev/stderr
  9
 10 <VirtualHost *:80>
 11   ServerName myhost.com
 12   ServerAlias myhost.com
 13   DocumentRoot /var/www/html/public/
 14
 15   <Directory />
 16     AllowOverride All
 17     Order allow,deny
 18     Allow from all
 19
 20     RewriteEngine on
 21     RewriteCond %{REQUEST_FILENAME} !-d
 22     RewriteCond %{REQUEST_FILENAME} !-f
 23     RewriteRule ^(.*)$ index.php?%{QUERY_STRING} [L]
 24   </Directory>
 25
 26   <Directory ~ "\.svn">
 27     Order allow,deny
 28     Deny from all
 29   </Directory>
 30
 31   <Directory ~ "\.git">
 32     Order allow,deny
 33     Deny from all
 34   </Directory>
 35
 36   RemoteIPHeader X-Forwarded-For
 37   RemoteIPTrustedProxy 10.0.0.0/24
 38
 39 </VirtualHost>

My error logs and info logs are showing up correctly in google cloud storage. However I keep seeing other access log entries.
Samples:
This log should not show up
::1 - - [13/May/2016:23:32:06 +0000] "GET /server-status?auto HTTP/1.1" 404 2970 "-" "Sysdig Agent/1.0"

This log should show up
{"message": "- - - [13/May/2016:23:32:06 +0000] 'GET /server-status?auto HTTP/1.1' 404 2720 '-' 'Sysdig Agent/1.0'", "severity": "INFO"}

I've tried a number of different configurations and none of them seem to fix the problem. Any idea where this unwanted access log output is coming from?
Comment: Do you have any other `CustomLog` directive in any other config file? As noted in [Access Log documentation](http://httpd.apache.org/docs/2.4/logs.html#accesslog), "Multiple access logs can be created simply by specifying multiple CustomLog directives in the configuration file."
Comment: We're loading 1 apache.conf file in our Dockerfile
Answer: So it looks like this version of php-apache for docker: FROM php:5.5-apache sends a custom log output to the process out. This makes sense as you would want docker log to actually output something when run.
To remedy this issue we will comment out the following lines:
45 LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
46 LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
47 LogFormat "%h %l %u %t \"%r\" %>s %O" common
48 LogFormat "%{Referer}i -> %U" referer
49 LogFormat "%{User-agent}i" agent
50
#51 CustomLog /proc/self/fd/1 combined


which von Neumann algebras have many sufficiently normal irreducible representations?

Question: Let $M$ be  a von Neumann algebra. We say that $M$ has  many sufficiently normal irreducible representations, namely $\{\pi_i\}$, if $||a||=\sup ||\pi_i(s)||$. For example the second dual of a C*-algebra does.
I am looking for an equivalent condition for this property in term of type theory or some thing else.
Question: $M=?$  if and only if $M$ has many sufficiently normal irreducible representations.
Answer: An irreducible representation $\pi:M\to B(K)$ has range dense in $B(K)$; but, if $\pi$ is normal, the range is all of $B(K)$. As $\ker\pi$ is a weakly closed ideal of $M$, it is of the form $pM$ for some central projection $p\in M$, and we get $(1-p)M\simeq B(K)$.
In other words, $M$ has sufficiently many normal irreducible representations if and only if $M$ is a direct sum $\bigoplus B(K_j)$.
Comment: Dear Martin, I feel some thing is wrong. Your proof says that every von Neumann algebra is of type I that is impossible. It seems you proved that $M$ is embedded in the direct sum $\bigoplus B(K_j)$ which is always true.
Comment: If every vN algebra has the property you want, your question is pointless, isn't it?  In any case, you would have to point me in the direction of the result that shows that those normal irreps exist for an arbitrarily vN algebra.
Comment: Clearly all von Neumann algebras have not this property. For example the second dual of any C*-algebra has this property and $L^{\infty}([0,1])$ has not. I am looking for any charactrization.
Comment: Of course.  Then, why would my argument "say that every von Neuman algebra is of type I"?
Comment: Since in the end of your argument, it was concluded $M=\bigoplus B(K_j)$ . Every projection in this direct sum dominates even a minimal projection which proves $M$ is of type I.
Comment: A von Neumann algebra $\bigoplus B (K_j) $ is obviously of type I. The question is why you seem to assume that I'm saying that $M $ is an arbitrary von Neumann algebra; what I'm assuming is that $M $ satisfies your property.
Comment: In your argument $M$ is mapped via $x\to \oplus\pi(x)$ into \bigoplus B(K_i)   where $\pi$'s run on   irreducible representations. Why is this embbeding onto?
Comment: First: the $\pi's$ run on **some**, **normal**, irreps. As for the argument, it is a typical Zorn Lemma argument. With the idea from the first paragraph one can construct families of pairwise orthogonal central projections $p_j$ with corresponding normal irreps $\pi_j$. Then use Zorn to get a maximal such family.


Static Routes in Custom Fields in Yesod

Question: I'm working on a custom field used to pick datetimes in Yesod (stored as UTCTime). It uses Trent Richardson's timepicker. I actually have it working already. The only problem is that I have the static route to the javascript file in a handler instead of in the custom field. When I move it to the custom field, I get errors. A portion of the code (largely copied from yesod.form.fields) is below:
jqueryDateTimeField :: (RenderMessage site FormMessage, YesodJquery site) => JqueryDaySettings -> Field (HandlerT site IO) UTCTime
jqueryDateTimeField jds = Field
{
    fieldParse = parseHelper $ maybe (Left MsgInvalidDay) Right . readUTC . unpack
  , fieldView = \theId name attrs val isReq -> do
        toWidget [shamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="text" :isReq:required="" value="#{showVal val}">
|]
        addScript' urlJqueryJs
        addScript' urlJqueryUiJs
        addScript $ StaticR js_jquery_ui_timepicker_addon_js -- Bad line here
        addStylesheet' urlJqueryUiCss    --error seems to occurs on the line below
        toWidget [julius|
$(function(){
var i = document.getElementById("#{rawJS theId}");
$(i).datetimepicker({
    dateFormat:'yy-mm-dd',
    changeMonth:#{jsBool $ jdsChangeMonth jds},
    changeYear:#{jsBool $ jdsChangeYear jds},
    numberOfMonths:#{rawJS $ mos $ jdsNumberOfMonths jds},
    yearRange:#{toJSON $ jdsYearRange jds}
});
});
|]
  , fieldEnctype = UrlEncoded
}

The line that says addScript $ StaticR js_jquery_ui_timepicker_addon_js is what's causing problems. I know this because when I put that line in the handler that calls this field, it works. I get an error message saying
DateTime.hs:73:13:
Could not deduce (site ~ App)
from the context (RenderMessage site FormMessage, YesodJquery site)
  bound by the type signature for
             jqueryDateTimeField :: (RenderMessage site FormMessage,
                                     YesodJquery site) =>
                                    JqueryDaySettings -> Field (HandlerT site IO) UTCTime

It goes on, but what bothers me is that the error seems to occur on the wrong line. Line 73 is the one that starts with toWidget. So, my question is, how can you use a static route in a custom field? Please let me know if there is more information I should provide. Thanks.
Answer: This fails because your jqueryDateTimeField is generic, i.e., it'll work with any Yesod site that satisfies the given constraints1, but your StaticR refers to a route constructor defined specifically for your site, which is represented by the App data type (defined in Foundation.hs). The error Could not deduce (site ~ App) means that given your use of StaticR, the compiler expects site to be the same as App always, but your other constraints do not confirm it for the compiler.
One solution to this is simply to make jqueryDateTimeField specific to your site by changing the type signature to:
jqueryDateTimeField :: JqueryDaySettings -> Field Handler UTCTime

Note that Handler is a type synonym for HandlerT App IO — the handler for your site.
While that will work, a better solution is to use YesodJquery's urlJqueryUiDateTimePicker function to get the URL for the date-time picker add-on and adding that as a script. urlJqueryUiDateTimePicker accepts the object representing your site (an App object in this case) and returns Either (Route site) Text — either a route under your site or a text based URL — pointing to the javascript file. You can add that as a script in jqueryDateTimeField using addScriptEither.
Then, you can change App's YesodJquery instance to return your static route.
So, replace addScript $ StaticR js_jquery_ui_timepicker_addon_js with:
app <- getYesod   -- This gets your App object
addScriptEither (urlJqueryUiDateTimePicker app)

And change the urlJqueryUiDateTimePicker method in App's YesodJquery instance to return the route you want to use:
instance YesodJquery App where
    urlJqueryUiDateTimePicker _ = Left $ StaticR js_jquery_ui_timepicker_addon_js

1
In the original type signature, the handler was represented by HandlerT site IO where site satisfies the constraints RenderMessage site FormMessage and YesodJquery site.
RenderMessage site FormMessage requires that site must know how to generate messages from the FormMessage data type.
YesodJquery site requires that the site must have access to static files for jQuery, jQuery UI, and the jQuery UI date-time picker add-on (see here).

Static Routes in Custom Fields in Yesod


Elasticsearch conexão com servidor

Question: Boa tarde!
Estou tentando conectar no Elasticsearch, mas não estou conseguindo, não sei se preciso informa mais alguma coisa na classe  es=Elasticsearch(..)
<code># Import Elasticsearch package
from elasticsearch import Elasticsearch

es=Elasticsearch([{'host':'https://elk-site.....com.br','port':9200}])

print(es.info())
</code>

Ocorreu exceção: ConnectionError
ConnectionError(<urllib3.connection.HTTPConnection object at
0x04EEC6B8>: Failed to establish a new connection: [Errno 11001]
getaddrinfo failed) caused by:
NewConnectionError(<urllib3.connection.HTTPConnection object at
0x04EEC6B8>: Failed to establish a new connection: [Errno 11001]
getaddrinfo failed)   File
"C:\Projetos\Ecommerce\site\Infraestrutura\ELK\Servico\Salvar.py",
line 9, in
print (es.info())

Quando acesso a url ele traz os dados normal.
Comment: Vc está usando algum redirecionador (tipo NGINX)? Baseado no que você postou, no script Python vc está usando a porta TCP 9200 e acessando pelo browser a porta padrão, ou seja TCP 80. Alterar o script para `es=Elasticsearch([{'host':'https://elk-site.....com.br','port':80}])`
Comment: @PauloMarques erra isso mesmo vlw
Answer: Resolvi o problema apontando para a porta 80 e mudando o use_ssl para False.
<code>es = Elasticsearch([{'host': 'elk-site....com.br', 'port': 80, 'use_ssl': False}])
</code>

Elasticsearch conexão com servidor


String comparison equivalence between mysql database and php code

Question: I wonder if it is possible to compare two strings using MySQL and PHP and obtain the same results. In MySQL I have:
a = b collate utf8_general_ci

For PHP I found a promising way to do it with the Transliterator class
transliterator_transliterate($a, 'NFD; [:Nonspacing Mark:] Remove; NFC; Lower();') = transliterator_transliterate($b, 'NFD; [:Nonspacing Mark:] Remove; NFC; Lower();')

Both will do the same most of the time, but it seems that there is no way compare two strings in PHP, both accent insensitive and case insensitive, that is compatible with MySQL.
Does anybody have a better solution to get the same result in PHP and MySQL, or is this something that should be avoided anyway, moving all comparison either to the database or into the application code?
The context is a replication between MySQL and a proprietary database. I have a unique key in the database on a text field in MySQL. On the other side I have thousands of rows in memory, and I would like to filter unique values in PHP without trying to insert them into the MySQL table first. My approach is to use these values as keys in an array, to keep them unique. The problem now boils down to normalizing these keys in a way to treat the same values as the same as the unique index in MySQL is.
Comment: possible duplicate of [Comparing strings in PHP the same way MySQL does](http://stackoverflow.com/questions/471021/comparing-strings-in-php-the-same-way-mysql-does)
Comment: Note that under `ut8_general_ci`  "ß" is equal to "s" (not to "ss", to "s"!), which is completely wrong, and obviously no library comparison in PHP will replicate this behavior. So I would first switch to using `utf8_unicode_ci`, which is slower, but doesn't have this weird behavior. If you are stuck with `utf8_general_ci`, then you will need to write the string comparison, or at least parts of it, manually to replicate that behavior.
Comment: Maybe I'm missing the point here, but why would you want to compare the strings in both PHP and MySQL instead of just one of them (or prefer PHP over MySQL when MySQL may be easier)? If you're trying to filter/limit the data you have to process, it's best to do the comparison with MySQL before PHP has access to it; that's part of the purpose of SQL.
Comment: @agi Your question is justified. I edited my question to explain the context.
Comment: Possibly mbstring functions can help you in this case.
Comment: @OP: Can't you make a restraint on the table (composite key, unique)?
Answer: Even if you achieve it and confirm by some tests, it may not be reliable due to different internal implementation of php and mysql string comparison.
Unlike integers and mathematical calculations, string comparison is usually implemented in a way to satisfy particular needs and can be biased on different languages and platforms. So, there is no guarantee that they will work exactly the same at all times, given you use two different systems.
Secondly, php would be slower for such operations, as compared to mysql.
You can use mysql features to do filtering unique values. For example, you can create a view or temporary table to execute the operation.
For example, views and temporary tables are suitable and a proper way to do such operations.
You can read more here and here
Comment: Database connection is the main overhead but you do it anyway. Once connection exists, other overheads is small.But you will gain a lot on operations like comparing, filtering, sorting, organizing data etc.If you use view, it isnt really inserting into a physical table,but takes a virtual copy of an existing table for temp ops.MySQL's designed for this purpose and is very very efficient in complex data operations like filtering. Checking PHP array key is fine, but other operations on it are expensive,if you know how php array works.If mysql can do something, it's always best to do it there.
Comment: Are you sure about what you say about performance ? I didn't test, but for me, insertion into a ( temporary ) table sounds slower than check if an array key exists, because of the communication overhead between php and mysql.


what will happen if you overwrite a share library (currently mapped by a program) with a new version?

Question: I'm wondering if anyone can expalin what will happen if you overwrite a share library file (currently mapped by a program) with a new version by copying the new *.so over the old *.so?
apparently, it should not affect the existing running program (prog1) which is linked to the old version. but what if you start another program (prog2) which use the same share library? will the prog2 simply map the old version of the library currently used by the running prog1 or a the new version of the share library will get loaded and linked by prog2?
do executables and shared libs have the same notion of file "caching" like the data files do?
does the ld.so detect versions of the share library
I'm working on the Unix platform and assuming the signature of the functions in the new version of share lib remain the same but their implementation has changed.
Comment: The answer may depend in part on the platform.  What happens on Windows is likely different from what happens on Unix.
Comment: Yes, but that should be clarified and made explicit.
Comment: @JonathanLeffler The reference to "ld.so" makes me reasonably confident they're asking about Unix systems.
Comment: Thanks, I updated my question.
Answer: If you unlink the original file and replace it with another file -- which is what a normal cp or mv will do -- nothing particularly surprising happens. Any processes that are already running will continue using the library that was deleted, and any newly launched processes will use the new one.
If you try to overwrite the existing file, you'll find out that's impossible. You'll get an ETXTBSY ("Text file busy") if you try to open a file for write that's currently mapped to executable pages. (This includes both executables and shared libraries.) This protection is implemented by the kernel.
If you somehow manage to bypass those protections and overwrite an executable or shared library which is in use, Bad Things will happen. Any pages from that object which are currently swapped out will be replaced by pages of the new executable when they are paged in, resulting in unexpected behavior -- probably a crash.
Comment: Thanks. I just did a test. the copy was successful, but after that, the running program crashed with core dump.
Comment: thanks. but I think the protection is for the  addresses of the mapped objects in the memory. it would not prevent you from copying a new lib file over the old lib file, which take place in the file system cache and disk blocks level.
Comment: No, the protection I'm referring to covers the entire file. You can't `open()` a file with write access if it's mapped to executable pages.


Access to an inner type

Question: A colleague of mine posted a question on an internal forum which got me thinking about whether this was possible through C#. Basically, he's got an interface as follows:
public interface IProvider<T>
{
    T GetT();
}

Is it possible to use something that implements that interface as a type parameter to another generic class and have access to the type T without re-specifying it? For example:
public class Foo
 where P : IProvider<T>
{
    P p;

    T GetInnerT() { return p.GetT(); }
}

This does not compile, because the type T is not defined and hence can't be used as a parameter for IProvider. Is something like this even possible? Just curious!
Answer: No, he'd need Foo to be generic in both P and T:
public class Foo
 where P : IProvider<T>

otherwise there's no T for the IProvider<T> constraint to be aware of - the fact that it's part of the declaration of IProvider<T> is coincidental. The T in the above declaration is entirely separate (from the compiler's point of view) from the T in IProvider<T>. For example, this would be an equivalent declaration:
public class Foo<TProvider, TProvided> where TProvider : IProvider<TProvided>

Another thing to bear in mind is that an implementation of IProvider<T> could implement it multiple times, for different type arguments:
public class BigProvider : IProvider<string>, IProvider<int>, IProvider<char>

Now what would Foo<BigProvider> mean? It would be ambiguous... whereas with my declaration above, you'd do:
var x = new Foo<BigProvider, int>();

to mean the int-providing aspect of BigProvider.
Answer: No, it's not possible, because your definition doesn't allow for the provision of type T when declaring Foo.  Consider:
var x = new Foo<string>();

What is T in this case?  There is no way to know at compile-time nor at runtime.
As you yourself said: the type T is not defined, and for the class to be valid you have to provide a means of definition.  For example:
public class Foo
 where P : IProvider<T>

Access to an inner type


can we write a script which could be usable to scrape multiple sites

Question: I have written almost 30 different scraping scripts for 30 different websites. A friend of mine told me that it is possible to have a single code file for scraping all these 30 websites and bring it to the dashboard for dynamic scraping (I didn't understand what he means). I know every single website has its own structure and different data is coming from different pages and elements. On the other hand, some websites provide dynamic data instead of static data which I used selenium for its scraping.
I am really not sure about what he was thinking and is it possible to follow a path where I right one single long script file and use it for scraping many websites.
I would appreciate it if anyone having knowledge about this help me with the idea, tutorials, web contents and...
Comment: There are tools like Newspaper which let you define a scraping function for sites with a particular structure, then scrape all sites which you have a scraping function for. Out of the box, like its name implies, Newspaper is for news sites, but the general principle should be obvious.
Comment: my scripts scrape websites that post business opportunities for small businesses. I am scrapping those for my business team so that they get aware of any opportunity posted from another organization. now like I said I have many scripts and each one is different from another. can you suggest to me some topics, technology, libraries ... I follow and search to understand more about this.
Comment: @DRPK yes dear, but I don't think we are on the same path. you are trying to tell me how to use the multiprocessing technique while scrapping( here we are still having our long list of scrappers)  but I am saying the scrapping script should be the same and much general which can be used for scrapping many websites. am I right?
Comment: You are talking about something like Software architecture ? Making Micro-Services ? or you wanna some technologies like Scrapy/Spider https://scrapy.org/ ? did you know about Scrapy? and also you can handle dynamic websites with Splash https://splash.readthedocs.io/en/stable/, splash can works with Scrapy; they made for big/massive web crawler apps even for production.
Comment: @DRPK , hey thank you for your comment, you look so supportive and I appreciate it. can I have your email so that I talk to you over there for more discussion.
Comment: Tnx YW; i updated my answer and added these few things. sure! but we need to find private way to sending our email; do you have any idea ?
Comment: @TalibDaryabi: i have mailed you, did you receive that ? if yes so remove your email address; because its possible to web crawlers (for big IT companies) crawling over nets and extracting these kind of info from websites then you may have too much spam emails in future.
Answer: Yes you can;

Make module for each scraper
Make an main app
Import your modules to the main app
Scrape your target website by using multiprocessing or multithreading methods.

Conceptual Code:
<code># This code will not run!

from multiprocessing import Pool
from Scrapers import Scraper1, Scraper2, Scraper3, ...

def run_each_scraper(get_scraper_object):
    get_scraper_object.run()

def launcher():
    list_of_websites = []
    # use loops here
    reserve_scraper_objects_for_websites = [Scraper1.scrape(list_of_websites[0]),
                                            Scraper2.scrape(list_of_websites[1]),
                                            ...]
    process_objects = Pool(20) # Depends on your system resource
    process_objects.map(run_each_scraper, reserve_scraper_objects_for_websites)

if __name__ == '__main__':
    launcher()
</code>
But if you need some technologies i suggest you to switch in Scrapy/Spider; Also you can handle dynamic websites with Splash, Splash can works with Scrapy. They made for big/massive web crawler apps even for production.
Comment: Multiprocessing and/or multithreading are useful if you need to run things in parallel, which probably eventually you'll probably need if you scale out to thousands of web sites; but for a few dozen, that's probably an unnecessary complication.
Comment: @tripleee yes you are right and there are many methods that we can do his job i just explained one of them, but about unnecessary complication you do not. Unlike many languages python is simple and its modules are simple too. python made for implementing high techs with few lines of code.


How to add a custom set property as field on Mac version?

Question: File > Properties > Custom

I am then trying to insert the variable ('variable') as a field.

'variable' is not listed, nor do any = Formulas seem to work.
In previous windows versions, selecting DOCPROPERTY would allow a custom variable to be selected and inserted. But selecting DOCPROPERTY only causes an Error! No property name supplied.
I am trying to insert a custom field, which would be inserted in multiple places on the document, which could be updated in one place. Such as 'version 1.1'
Comment: Are you trying to do this with VBA code? If not, you have posted your question to the wrong forum. Use SuperUser or Microsoft Answers instead. If you are trying to do this with VBA code, then edit your question and include the code that you have tried so far and describe what is not working.
Comment: Here's where to post this: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-mso_mac
Answer: In order to add a custom field generated throw File -> Properties... -> Custom on Mac OS go to:

Insert tab
Insert a field
Choose Document Information category
Choose DocProperty
Click on Options
Choose your property and click on Ok
Click on Ok


How to pull data formatted for Matlab into R?

Question: I just ran a vendor-supplied program that converts data from their proprietary binary format to what they call a "Matlab format". There are two resulting files from the conversion, a "filename.dat" and a "filename.m".
The "filename.m" file seems to have column heading information in it. The second "filename.dat" file is >13Gigs in size and I can't load it into anything at the moment to inspect it.
How do I go about loading this "Matlab format" data into R?
Comment: You can use EmEditor to open large files.
Answer: This doesn't sound like "Matlab format" (which would be a .mat file).
Rather, the .m-file is a Matlab function or script that is most likely used to read the data in the .dat file.
Have a look at the Matlab documentation to find out how the .m file reads the data, so that you can port the code to R.
Answer: The R package R.matlab can read .mat files. I use it to store 3D arrays from Python and then use them in R. Basically 3D arrays become lists of 2D arrays in R; also variable names get imported and you can call them from the data.frame.
However, see Jonas' answer that your data is not real Matlab format .mat yet.


Additional table not created

Question: I'm trying to add a second table to my application but I'm not having any luck.  The two tables are their own classes and are singletons.  I pass in a reference of the database in the onUpgrade method and again as an instance variable.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    transTable = TransactionTable.getInstance(db);
    sysTable = SystemTable.getInstance(db);

    onCreate( db );

    transTable.updateTable();
    sysTable.updateTable();
}

The onCreate method just calls the create methods in all the tables.
@Override
public void onCreate(SQLiteDatabase db) {
    transTable.createTable();
    sysTable.createTable();
}

The second table, sysTable, doesn't throw and exception while executing the following create statement.
public void createTable() {
    db.rawQuery("CREATE TABLE IF NOT EXISTS " + tableName + " ("
            + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + lastUsed
            + " INTEGER, " + balance + " INTEGER, " + accountName
            + " TEXT, UNIQUE ( " + accountName + " ) )", null);
}

But, when I run a simple query such as the following:
 db.rawQuery("select * from " + tableName, null);

I get an error stating
 android.database.sqlite.SQLiteException: no such table: system_t: ,
 while compiling: select * from system_t

There is no issue with the first table being dropped or created.  Any ideas?
Answer: change createTable method the code:
 db.rawQuery

to
db.execSQL()

Additional table not created


PHP/MYSQLI - BIGINT value change to Negative

Question: I'm facing a wired problem!
I've a table called "student" with one cloumn stuID of type BIGINT,
when i try to assign a value for this column like '20122222222',
if i do it manually it working fine! but with my code it changed to negative value
I searched in stackoverflow for Similar Questions, i found an answer to change the bind_param to string like
$stmt->bind_param('s',$stuID);
I did it and still the same problem
Here's the function
public function insertStudent($stuID)
{
    if($stmt = $this->mysqli->prepare("INSERT INTO student(stuID) VALUES(?)"))
    {
        $stmt->bind_param('s',$stuID);
        $stmt->execute();
        $stmt->close();
    }
    else
    {
        die(printf("Prepared Statement Error: %s\n", $this->mysqli->error));
    }
}

Thank you all
Comment: Is the column type BIGINT UNSIGNED?
Comment: `CREATE TABLE IF NOT EXISTS student (
  stuID bigint(20) NOT NULL,
  PRIMARY KEY (stuID)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;`
Here's the table
Comment: Why are you binding a string `bind_param('s',$stuID);`?
Comment: The soultion was to change the bind to double because

The largest integer supported in this build of PHP. Usually int(2147483647). Available since PHP 4.4.0 and PHP 5.0.5

Source:
http://www.php.net/manual/en/reserved.constants.php#constant.php-int-max
Answer: If you are trying to insert a record. Try this rand(111,999) instead. You will get a unique random numbers starting from 111 to 999. php rand()
Hope it helps.
Comment: The thing is I'm working with student id which already Exist like this.
It a waste of storage if i make another column and name it id and change stuID from BIGINT to VARCHAR or whatever.
Comment: try to echo out the id before going into the database first. so you can figure out what is the error all about. like doing a try catch, examining every line of the code.
Comment: yul757, Yeah i tried, read my comment under my question. i solved the problem.


Change null to 0 in response

Question: I use reactJS and I would like to change each null value to 0 when I display the results of my API call responses and avoid errors. the problem I am having is that every time I want to check the values, the display of 0 does not occur.
The json data from each search returns this:
cases: Object { new: "+14", active: 233, critical: 6, … }
continent: "Asia"
country: "China"
day: "2020-07-23"
deaths: Object { new: null, 1M_pop: "3", total: 4634 }
population: 1439323776
tests: Object { 1M_pop: "62814", total: 90410000 }
time: "2020-07-23T00:45:06+00:00"
<prototype>: Object { … }

As you see there is objects in the object. I need to "scan" all value to changing each null to 0 and display it.
Here my code where the problem is.
//replace Null value to 0
function isNull(object) {
   for (const [key, value] of Object.entries(object)) {
       if (typeof(value) === "object" && value !== null) {
           isNull(value)
       }else if(!value){
          object.value = 0
         }
       }
         return object
   }

thanks by advance.
Answer: I believe your issue stems from here:
else if(!value){
  object.value = 0
}

I believe you want to set the object[key] = 0
So altogether it'd be:
else if(!value){
  object[key] = 0
}

const response = {
  cases: { new: "+14", active: 233, critical: 6 },
  continent: "Asia",
  country: "China",
  day: "2020-07-23",
  deaths: { new: null, "1M_pop": "3", total: 4634 },
  population: 1439323776,
  tests: { "1M_pop": "62814", total: 90410000 },
  time: "2020-07-23T00:45:06+00:00"
 };

function isNull(object) {
    for (const [key, value] of Object.entries(object)) {
        if (typeof(value) === "object" && value !== null) {
            isNull(value)
        }else if(!value){
            object[key] = 0
        }
    }
    return object
}
console.log(isNull(response));
Comment: Ok forget what I said that totally work, i just made a word mistake... shame. Thank you very much for your help Spencer
Comment: Thanks for answered as quickly. In the function , the key show the index of the object ( { country(key) : China(value) } ). I tried with " object[key]" and "object[value]" nothing happened.
Comment: I just updated my answer to include a code snippet. It seems to be working for me in the snippet, are you getting a different output?
Comment: I admit that I don't understand because by rewriting your snippet I actually get the right result but I don't get it displayed on the web page. it just shows me "Today:" instead of "Today: 0".
Comment: If you include the react code where this is being rendered I could help debug that?

Change null to 0 in response


Find all the integral solutions to $2x+3y=200$

Question: What's the best way of going about this?

$$2x+3y=200.$$
Comment: You mean "integer"?
Comment: In general adding some context to your question makes these easier to answer. It also makes for more responses as people sometimes ignore questions with zero context or perspective.
Answer: This called a Linear Diophantine Equation, and the general form is $ax+by=c$. One approach that will solve a variety of equations like this particular one is to note that the $\gcd(2,3)=1$, and applying the Euclidean Algorithm is a general way to do this. In this case, the algorithm takes one line ($3=2 \cdot 1 +1$), and so
$$3=2 \cdot 1 +1 \Rightarrow 3 \cdot 1 -2 \cdot 1 = 1 \Rightarrow 2(-1)+3 (1)=1.$$
Now multiplying across by 200 gives one integral solution, namely
$$2(-200)+3 (200)=200.$$
To find all integral solutions, where $x_0=-200$, $y_0=200$, $d=\gcd(2,3)$, $a=2$, and $b=3$, we can just write
$$x=\frac{b}{d}n+x_0=3n-200, \,\, y=-\frac{a}{d}n+y_0=-2n+200, \,\, n \in \mathbb{Z}.$$
The links above should help you with solving this class of equations and provide greater explanation. I hate posting formulas with no derivation, but such derivations exceed the scope of your question, and are readily available on the internet.
Answer: For this case,
if $2x+3y=200$,
an obvious solution is
$x=100, y=0$.
From this base solution,
all other integer solutions are
$x=100-3n$,
$y=2n$
for integer $n$.
If the solutions are to be
non-negative,
then
$n \ge 0$
and
$100-3n \ge 0$,
so
$0 \le n \le \lfloor(100/3)\rfloor
=33$.
Answer: $2\,|\,y$. $\quad x + 3\,{y \over 2} = 100$.
$\color{#ff0000}{\large\quad x_{n} = 100 - 3n.\quad n = 0,1,2,\ldots,33}$.
$$
200 - 6n + 3y_{n} = 200\,,
\quad
\color{#ff0000}{\large y_{n} = 2n}
$$
$$
\left(100,0\right),\left(97,2\right),\left(94,4\right),\left(91,6\right),\ldots
$$


Subscrever um objeto em JS

Question: Gostaria de saber se existe alguma forma de subscrever o conteúdo de um objeto. Por exemplo:
Tenho dois objetos.
object1 {
 name: '';
 address = 'Rua Mario';
 email: '';
}

object 2 {
 name: 'Carlos';
 email: 'firstname.lastname@example.com';
}

A dúvida ocorre aqui.
this.object1 = this.object2;
console.log(this.object1);

Resultado no console:
object 1 {
 name: 'Carlos';
 email: 'email@example.com';
}

O que eu queria:
object 1 {
 name: 'Carlos';
 address = 'Rua Mario';
 email: 'email@example.com';
}

Qual o meio mais fácil de fazer isso?
Answer: let object1 = {
   name: '',
   address: 'Rua Mario',
   email: '',
}

let object2 = {
    name: 'Carlos',
    email: 'email@example.com'
}

const {name, email} = object2;
object1 = {...object1, name, email};

console.log(object1);

Comment: Sua resposta é boa, tanto é que dei +1, mas, poderia explicar como fez para chegar ao resultado e não apenas publicar a resposta, assim fica mais didático para quem perguntou e para futuras pesquisas!

Subscrever um objeto em JS


Positive subsequence of a double sequence

Question: Suppose for the double sequence $\{a_{m,\,n}\} \subset \mathbb{R}$ we have $\lim_{n\rightarrow\infty}\lim_{m\rightarrow \infty} a_{m,\,n} = L$, where $L \in (0,+\infty]$. In particular, there exists some $n_0$ such that $n > n_0$ implies $\lim_{m \rightarrow \infty}  a_{m,\,n} > 0$. Is it possible to find a subsequence $\{a_{m_k,\,n}\}$ such that $a_{m_k,\,n} > 0$ for all $n > n_0$?
Answer: Well if I get you right, the answer is no. Think of a sequence of the form
$$a_{m,n}=1-\frac{b_n}m.$$
Since for each $n\in \mathbb N$
$$\lim_{m\to\infty} a_{m,n}=1>0,$$
and then for $n>n_0=1$ we have $\lim_{m\to\infty} a_{m,n}>0,$ there should be a subsequence $a_{m_k,n}$ such that for each $n>1$ and —I think you omitted this— for each $k\in \mathbb N$)
$$a_{m_k,n}>0.$$
But suppose, for instance, that $b_n=n$ (or any other sequence which is unbounded above)... In this case, that condition holds if and only if
$$1-\frac nm>0\iff m>n.$$
So no matter how big you choose $m_k$, there will always be infinite numbers $n$ such that $a_{m_k,n}\le 0$.
Note also that this says that the result is not true not only for the chosen $n_0$, but that no matter which $n_0$ such that the first condition holds you choose, the conclusion is always false for this sequence.


Continuity of potential function at an interior point

Question: Suppose $\Omega \subset \mathbb{R}^3$ is closed, bounded, with smooth boundary and the density $\rho: \Omega \to \mathbb{R}$ is continuous.  The potential function is
$$\phi(x) = \int_\Omega \frac{\rho(x')}{|x - x'|} dx',$$
I already showed it continuous for $x \notin \Omega$ and am trying to show it continuous for $x \in \Omega$.
My effort: I take a ball $B_\delta(x_0)$ around a fixed point $x_0$ with $|x-x_0| < \delta$ and look at
$$|\phi(x) - \phi(x_0)| \leq \left|\int_{\Omega- B_\delta(x_0)}\rho(x') \left(\frac{1}{|x-x'|} - \frac{1}{|x_0-x'|}\right) dx'\right|+ \left|\int_{ B_\delta(x_0)}\frac{\rho(x') }{|x_0-x'|} dx' \right| + \left|\int_{ B_\delta(x_0)} \frac{\rho(x')}{|x-x'|} dx' \right|$$
Since the integrand in the first integral is continuous there exists $\delta_0$ such that if $|x - x_0| < \delta_0$ then
$$\left|\int_{\Omega- B_\delta(x_0)}\rho(x') \left(\frac{1}{|x-x'|} - \frac{1}{|x_0-x'|}\right) dx'\right| < \frac{\epsilon}{3}$$
Also convergence of the potential integral means if $\delta$ is small enough then
$$\left|\int_{ B_\delta(x_0)}\frac{\rho(x') }{|x_0-x'|} dx' \right| < \frac{\epsilon}{3}$$
My question is how to show the third integral can be made $< \frac{\epsilon}{3}$ since $B_\delta(x_0)$ is not centered at $x$.
Answer: The Absolute continuity of the Lebesgue integral can be used here. Since the function $\rho(x)/|x-x_0|$ is integrable on the ball $B(x_0, 1)$, it follows that for every $\epsilon$ there exists $\delta>0$ such that if $E\subset B(x_0, 1)$ has measure less than $\delta$, then
$$
\int_E \frac{|\rho(x)|}{|x'-x_0|} dx' < \epsilon
$$
This argument works for both 2nd and 3rd integrals, they don't have to be treated separately.
Comment: Thank you.  That will work for me.  If I wanted to consider only in terms of improper Riemann integration could I make an argument where I excise a ball $B_{\delta'}(x)$ where $\delta' \to 0$ as $\delta \to 0$?
Comment: Yes, you can estimate the contribution of one ball by a larger one with a more convenient center.


Load-Balancing and HA between virtualized guests on same host reasonable?

Question: some time ago a friend showed me his concept of a virtualized web application:

2 Apaches - load-balanced via IPVS/LVS
2 MySQL - HA via DRBD and Heartbeat

The virtualized machines all run under the same hypervisor on the same host.
So I was wondering if this setup is reasonable because I see no advantage.

Host is SPOF
Load-Balancing via IPVS? Host CPU is the bottleneck anyway or can 2 virtualized CPUs handle more interrupts than the Host CPU alone?
MySQL HA? Isn't it faster for the hypervisor restarting a crashed guest than failover via DRBD etc...?

I don't see any advantage in network load-balancing under the same hypervisor since network I/O between guests is mapped memory anyways and therefore fast.
Any ideas, suggestions?
For me it is just overhead and single, beefier guests make more sense...
Comment: Unless you have an imminent migration to more hosts or very odd isolation requirements (like 2 sets of completely seperate human administrators), I see little use to this scenario.
Answer: Agreed on every point. If you had a hypervisor cluster, then it might have made sense, especially with a policy to always keep the guests on different hosts
Answer: Like dyasny already said, the scenario does not make sense at all unless there's a hypervisor cluster. For a single host that kind of hoopla is just plain stupid.
Answer: I think this configuration is only for testing and learning purpose.


Why does the dependent product type need "forall"?

Question: I feel stupid asking this question because it is so fundamental to logic and math. However, in my starting to learn proof theory and now type theory, I have not seen an explanation on why you need the ∀ quantifier for dependent products. It seems like it can be left out / assumed. Let me explain.
Background
In section 4.2: Typing Rules and Dependent Products in Coq'Art: The Calculus of Inductive Constructions, they provide this definition of the dependent product type:

∀v:A,B is the type of the functions that map any v of type A to a term of type B where v may occur in B.

Then they provide the example:
Check le_n.
le_n : ∀n:nat, n ≤ n

So that example is saying

forall n of type natural number, n is less than or equal to n.

Problem
That makes sense, and it comes from how you would write it in classical logic proofs. However, I keep wondering why can't it just be written like this:
Check le_n.
le_n n:nat : n ≤ n

That seems like it means the same thing to me. It means that

for all n of type natural number, n is less than or equal to n.

Or it feels to me it could mean "for any n", which may be different.
In both cases, you need some input to create the type, so it seems like they both mean "dependent type".
Basically, I'm just wondering why you have to include the forall ∀ in the definition (in Coq), when the fact that it's a definition means that it will apply to all cases anyways. Any thoughts?
Answer: Well, it turns out the type of le_n is indeed a dependent product:
le_n : ∀ (n : nat), n ≤ n

The fact that it is displayed as a function with named arguments is syntactic sugar. In fact, when I check le_n in my version of Coq it displays this:
le_n
     : forall n : nat, n <= n

And whenever you write something like this:
Definition f (a1 : T1) (a2 : T2) : T3 -> T4 := ...

Your are really declaring:
Definition f : ∀ (a1 : T1) (a2 : T2), T3 -> T4 := λ a1 a2 → ...


Ratio of difference between convex function of real variables and difference between real variables

Question: Let f be a convex real-valued function. Then the ratio of f(x1) - f(x2) to x1 - x2 should be non-decreasing. I think I know this, but I do not know how to show it. How does this follow from the definition of a convex function?
Answer: Suppose $x<y<x'<y'$. Then $y=\frac {x'-y} {x'-x} x+\frac {y-x} {x'-x} x'$. Note that $\frac {x'-y} {x'-x}$ and $\frac {y-x} {x'-x} $ are positive numbers adding up to $1$. Applying the definition of convexity we get $f(y)\leq \frac {x'-y} {x'-x} f(x)+\frac {y-x} {x'-x} f(x')$. You can re-write this as $\frac {f(y)-f(x)} {y-x} \leq \frac {f(x')-f(y)} {x'-y}$. Next write $x'$ as $\frac {y'-x'} {y'-y} y+\frac {x'-y} {y'-y} y'$. As above this gives $\frac {f(x')-f(y)} {x'-y} \leq \frac {f(y')-f(x')} {y'-x'}$. Combining the two inequalities we have proved we get $\frac {f(y)-f(x)} {y-x} \leq \frac {f(y')-f(x')} {y'-x'}$.
There are other inequalities of this type. If you change only one of the two numbers $x,y$ to a larger number then also the ratio increases. Such inequalities are proved by a similar argument.


Why is the area of a square $a^2$ and volume of a cube $a^3$?

Question: How area and volume emerge from lower dimensions
This might sound as a silly question but I think there is some hidden complexity behind it. Esentially, my question is how is it possible that:

multiplication of something with essentially no area grants you an object with an area.

multiplication of something with essentially no volume grants you an object with a volume.

The thing is, even if I acknowledge that line segment could have some nonzero but really small area (for example a wooden toothpick), why its according-times multiplication would give me an area of a square? If I put these toothpicks together, they still won't fill the appropriate square (see illustration):

I know, that if I discretize it and assign some fundamental "area value" it would make sense, for example having 4 cabbages in a row and 4 rows in a total gives me 16 cabbages... BUT how to make a sense of it for the case with toothpicks etc.?
Thank you very much!
Comment: You seem to be working from a concept of multiplication in which you multiply by adding together some number of copies of an object: $4 \times 4 = 4 + 4 + 4 + 4.$ That is not a good model for multiplication in general: how does it answer $\frac13 \times \frac13$ or $\sqrt2 \times \sqrt2$? And it is not the way we use multiplication for area. We want to measure area and we have chosen the rectangle as the prototype for an object with area, and we *define* its area to be the product of the lengths of two adjacent sides.
Comment: @Athaeneus: We *do not* assign an area to a line segment; we assign only *length* to a segment. We assign area to a rectangle determined by *two* line segments. Speaking a bit philosophically, area is something of an "emergent" property, possessed by neither segment individually but *coming into being* by a combination of those segments. (It's not uncommon to say that a segment has "area zero", but that's really just an informal statement about a rectangle whose "other side" has *length* zero.)
Comment: @DavidK +1 Nice comment! I don't think this was necessarily your intent, but your comment may make it sound like there is no reason to define a 2m×3m rectangle to have area 6m² other than convention. I'd prefer to say we define some unit square to have area 1, and then build up other shapes out of area addition. The  $\frac13\times\frac23$ rectangle has the area of $\frac29$ unit squares primarily because when you put 9 of them together you can form a rectangle that is perfectly covered by 2 unit squares. For things like $\sqrt 2\times\sqrt 2$, we can approximately cover it by 2 squares' worth
Comment: @Athaeneus: How should area *behave*? If nothing else, a figure formed from *finitely*-many copies of another figure *should* have an area equal to the corresponding multiple of the original area. Thus —at least for integer $a$ and $b$— the area of an $a$-by-$b$ rectangle *should be* $a$-times the area of a $1$-by-$b$, which in turn *should be* $b$-times the area of a $1$-by-$1$. Calling the last of these $K$, then an $a$-by-$b$ rectangle *should have* area $abK$. (We easily extend this to *rational* $a$ and $b$; "continuity" gets us to reals.) By convention, we *declare* $K$ to be $1$.
Comment: Finite contiguous $n$-dimensional regions have $n$-dimensional "measures" (lengths for $n=1$, areas for $n=2$, volumes for $n=3$) proportional to $a^n$. Any attempt to get a measure of larger $n$ that is applicable gives $0$. A cube of side length $a$ has edges of total length $12a$ but area $0$, faces of total area $6a^2$ these edges enclose but volume $0$, volume $a^3$ these faces enclose etc.
Comment: A similar point of confusion arises when someone learns that a line is composed of points. How can the length of the line be defined? For example, see [If a point has no dimension and no area how can there be space?](https://math.stackexchange.com/q/508900/139123)
Comment: Well, the question is flawed because it's not that the object has essentially no area, it's that it has exactly no area. The analogy of toothpicks does not hold up to the mathematical idea because toothpicks have some small width to them whereas a line does not. So, if you stack a million toothpicks side by side you may fill up a square of some unspecified width; if you stack a million lines 'side by side' (this is not even a well defined notion) the resulting width of this configuration is still zero. Same reasoning applies to volume
Comment: Well, but then the thing is... Why 4-times a line gives you an area of a square? How does the area emerge from something without it? Maybe I am overthinking it but I search for some fundamental understanding of it.
Comment: Well.. it doesn't. If your line is length $2$, '$4$ times a line' here would give you $8$. The area of the square constructed by taking lines of length $2$ is $2^2=4$. I think you have misunderstood something here. You might be thinking of the perimeter of a square.
Comment: 4 times a line segment gives you four lines that still have 0 area. And four times the length of a 4m line segment gives you a length measurement of 16m, which still doesn't represent any area. Now, (4m)×(4m) gives an area 16m², but there I multiplied by the length 4m, not the counting number 4.
Comment: @MarkS. that example may be confusing the matter further as you chose the only case where '$4$ times the line' coincides with the numerical value of the area of the square with side length of that line
Comment: Alborz: Oh I see my mistake here, I worked with side of a square being 4. I will adjust the question properly, thanks. Now, the main thing is how even any multiplication of something leads to an area...........

Mark S: Alright, but 4m on itself still has no area, right? So I have to multiply it 4 times and then multiply by some elementary unit (m) in which I would like to express it? Do I get it correctly or am I lost once again?
Comment: "4 times and then...(m)" It would be a little weird to separate the 4m into the 4 and the m, but I suppose you can. "Do I get it correctly?" If you find that a helpful way to think about the situation, then yes. I make no claims that it's the only way, and there's probably a lot of philosophy about this I don't know.
Comment: @DavidK This model explanation makes sense to me... BUT I still would have one counter-argument: I use only geometrical model, imagining toothpicks. I visualize this exponatiation as follows: One member of the multiplication gives me a length of toothpick measured in some general length units and the other gives me how many toothpicks I have. The $\frac{1}{3} * \frac{1}{3}$ means I have toothpick of the length $1/3$ and I have only $1/3$ of these toothpicks... I don't see a problem of model interpretation there. Could you provide some material for other multiplication models, please?
Comment: @Athaeneus: See also [this answer of mine](https://math.stackexchange.com/a/1971811/409).
Comment: @Blue I think I see where my problem lies. So the answer, if I understand it correctly, esentially is that we define, by convention, some fundamental unit of area $K$ to be equal to 1, give some elementary area to a line segment in this case $b$ (that $1$-by-$b$ area) and then we use it as common comparison? So the area in a square comes from the fact that we assign some area to a line segment? Otherwise, where would the area of 1-by-b come from? Is that right?
Answer: This is an intuitive answer.
The area of a square of side length $a$ is $a\cdot a$ because the square area may be subdivided into a number of exactly $a\cdot a$ smaller squares that are neither overlapping nor gapped and each small square has a sidelength of 1 and an undetermined area, which we choose to call "unit of area".
Undetermined as it is, all smaller squares have the same area because they are congruent.
The division of a segment of length a into a number of "a" segments of length $\frac{1}{a}$ is not exactly possible in the real world, however in mathematical terms is possible to be done exactly.
The fact that we call the undetermined area as "unit of area" might seem unrigurous but is not. We simply count in terms of that small area which we regard as a reference.
Same logic applies to volumes.
Comment: Ummmmmm.... Does this mean that the setup was never **4 lengths 4 times** but rather **4 units of area 4 times**? Meaning that we have actually never operated with length itself but area instead, while the use of the notation for a length was only a crude simplification of the underlying problem?
Comment: Not sure what you mean by "4 lengths 4 times". A length multiplies into another length and an area multiplies into another area. You operate with length when you subdivide the area of the square by subdividing two adjacent sides of the square, but then you get the original square subdivided into a number of smaller squares.
Answer: You can start by simply defining length on open intervals $(a,b)$ to be $b-a$. Then, in general for cubes $(a_i,b_i)^n\subseteq \mathbb R^n$ define volume to be $\prod (b_i-a_i).$ The Lebesgue theory will then capture the intuition we have for these ideas, with the added benefit that it will also treat non-intuitive situations that arise. Another approach, for example here, uses linear functionals to develop the theory, which is perhaps more direct; and it leads to the same results.
Answer: If we consider infinitesimal strips of width $x$ from one side $ dA= x \cdot dx $, so to start with area did exist in its differential form. Area did not arise from nowhere.
Integrating,
$$ A = x^2 $$
and similarly for the volume.
Comment: Well, but this just shifts the question... Now we could ask why $x * dx$ has any area at all, which is esentially the same problem as before... The question practically being: "Why any multiplication of sole length gives you an area"
Comment: Integrating, $\int x\,dx = \frac12x^2 + C,$ and as a definite integral, $\int_0^a x\,dx = \frac12 a^2,$ so I think this answer is actually wrong. If I were to do this via integration I would integrate $\int_0^a a\,dx.$
Comment: Ok, I tried to model from OP's sketch of  a square window with very thin bars/toothpicks  filling up a full square.
Answer:
...multiplication of something with essentially no area grants you an object with an area...multiplication of something with essentially no volume grants you an object with a volume...

Maybe you're having trouble because your intuitive understanding of "dimension" so naturally connects to common physical length/area/volume examples that it is hard to realize that there is actually a conceptual abstraction happening.

To show how completely abstract "dimensions" really are I'm going to give an example that is entirely unrelated to your length/area/volume examples... the working-world concept of a man-hour.
If you think about it, a man-hour (or rather a worker-hour) is a 2-dimensional concept that combines the two very distinct 1-dimensional concepts of "worker(s)" and "time" into a single new concept.  Can 2-workers fold 100 paper airplanes in an hour? Well then 6-workers could do the same job in 20 minutes, or 1-worker alone could do the job in two hours.
It's a pretty convenient concept, but it's also nice here in that we can understand how it is clearly an abstraction.  We can intuit that workers and time are completely different categories that each contribute to the concept; and we can also understand that a question like "How many 'workers' are in an 'hour'?" shows a muddied understanding of how those two categories are distinct.

Getting back to the length/area/volume examples that you were originally asking about we could maybe decide to think of them in that same kind of abstract way as "worker-hours": is it an "area" or just a "width-length", a "volume" or a "width-length-height"?
There is something strange about how width, length, and height can all be measured with the exact same kinds of basic "distance" units, and it is also a bit amazing  that we can just "rotate" things and say "I'm calling this the direction of length and that the direction of width now." and have it work out.  But none of that changes the fact that the abstract concept of a "width-length-height" is something distinct from the concepts of a "height" or "width-length".
And lastly, the reason why it goes $a$, $a^2$, $a^3$ is simply because we have special words for shapes when the sides are the same.  Any old rectangle could be $a \cdot b$ but if we say that $b=a$ we have $a \cdot b \to a^2$ and call it a square; same thing for 3D box shapes $a \cdot b \cdot c$ if all sides are the same $a=b=c$ just gives  $a \cdot b \cdot c \to a^3$ and we call it a cube.
Answer: In Euclid's geometry you get a square only by constructing it on a given straight line segment (Elements I, 46), not by multiplying a line. Numbers are not involved at all. By the time you get to Descartes' geometry, which makes use of algebra, "squaring" a line yields not a square (area) but another line, a third proportional, with an arbitrary line playing the role of "unit". Similarly, "multiplication" of a line by a line yields a fourth proportional, i.e. another line, not a rectangle. For Descartes as for Euclid, only magnitudes of the same can have a ratio to one another.
So it seems a square is not produced by numerically "squaring" a line, nor a rectangle by multiplying two lines, nor a cube by numerically "cubing" a line. Squares and rectangles and cubes arise only by geometric construction, traditionally with straight-edge and compass. But if we are given a numerical measure of the line(s),we can calculate the measure of the square, rectangle, or cube by taking the "square" or product or "cube" of the number(s). E.g. if line $a$ is two unit-lines in length, then the square built on that line is $2^2=4$ unit-squares in area, and the cube is $2^3=8$ unit-cubes in volume.


What is the name of the dynamically generated elements?

Question: I am generating an interface dynamically but I don't know how to access to the attributes of these since I don't know what name they adopt.
I leave the example interface. I was thinking that maybe they adopt names like: Textbox_1 Textbox_2.... But to be guessing, I preferred to ask.
I leave the example interface.
Main file
    from UIMAIN import *

    class MainWindow(QtWidgets.QMainWindow, Ui_MAIN):
        def __init__(self, parent=None, *args, **kwargs):
            QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
            self.setupUi(self)

            for x in range(3):
                self.Make()

        def Make(self):
            self.scrollAreaWidgetContents = QtWidgets.QWidget()
            self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 387, 177))
            self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")

            self.TRAM = QtWidgets.QFrame(self.scrollAreaWidgetContents)
            self.TRAM.setGeometry(QtCore.QRect(10, 10, 141, 161))
            self.TRAM.setMinimumSize(QtCore.QSize(141, 161))

            font = QtGui.QFont()
            font.setFamily("Verdana")
            font.setPointSize(9)

            self.TRAM.setFont(font)
            self.TRAM.setStyleSheet("background-color: rgb(255, 255, 255);")
            self.TRAM.setFrameShape(QtWidgets.QFrame.StyledPanel)
            self.TRAM.setFrameShadow(QtWidgets.QFrame.Raised)
            self.TRAM.setObjectName("TRAM")

            self.horizontalLayout_2.addWidget(self.TRAM)

    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
        window = MainWindow()
        window.show()
        app.exec_()

UI file
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'MAIN.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MAIN(object):
    def setupUi(self, MAIN):
        MAIN.setObjectName("MAIN")
        MAIN.resize(371, 201)
        self.centralwidget = QtWidgets.QWidget(MAIN)
        self.centralwidget.setObjectName("centralwidget")

        self.AREA = QtWidgets.QScrollArea(self.centralwidget)
        self.AREA.setGeometry(QtCore.QRect(10, 10, 351, 181))
        self.AREA.setMinimumSize(QtCore.QSize(351, 181))
        self.AREA.setStyleSheet("background-color: rgb(189, 189, 189);")
        self.AREA.setWidgetResizable(True)
        self.AREA.setObjectName("AREA")

        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 349, 179))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.gridLayout = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout.setObjectName("gridLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.gridLayout.addLayout(self.horizontalLayout_2, 0, 0, 1, 1)
        self.AREA.setWidget(self.scrollAreaWidgetContents)
        MAIN.setCentralWidget(self.centralwidget)

        self.retranslateUi(MAIN)
        QtCore.QMetaObject.connectSlotsByName(MAIN)

    def retranslateUi(self, MAIN):
        _translate = QtCore.QCoreApplication.translate
        MAIN.setWindowTitle(_translate("MAIN", "MainWindow"))

Comment: Well, you can easily see all the attributes in `Ui_MAIN`, which are what you entered in qt designer. And then you can see all the attributes you created yourself in `MainWindow`. What else do you need to know?
Comment: @ekhumoro You misunderstood, the OP refers to the objects that are created in his loop. If you downvote his question, please reconsider changing that.
Comment: @AlejandroCondori I didn't misunderstand and I didn't downvote. Name binding in pyqt doesn't work any differently to normal python. If you overwrite a variable or attribute, the object will no longer be accessible via that name (although it may still be accessible via other means). There's no magical name creation - the attributes you can see in the current code are all you're going to get, with or without the for-loop.
Answer: If you are talking about the widgets created in MainWindow.Main, they are bound to whatever name you give them. Since you are overwriting the same attributes every time you call Make, the previously created widgets won't be bound to explicit attribute names. If you want easy access to the widgets after creating them you could put them in a container like a list, e.g.
class MainWindow(QtWidgets.QMainWindow, Ui_MAIN):
    def __init__(self, parent=None, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)

        self.scroll_area_widgets = []
        self.TRAM_widgets = []
        for x in range(3):
            self.Make()

    def Make(self):
        scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scroll_area_widgets.append(scrollAreaWidgetContents)

        TRAM = QtWidgets.QFrame(self.scrollAreaWidgetContents)
        self.TRAM_widgets.append(TRAM)

        # rest of setup where self.TRAM is replaced with TRAM and
        # self.scrollAreaWidgetContents with scrollAreaWidgetContents ....

This allows you to access the widgets created in Make via self.TRAM_widgets[] and self.scroll_area_widgets[].
Answer: You have to store every object you create into a variable if you want to get access to them. I suggest creating a list, and each time you create an object store it as an element of that list. Later you can have access to the objects via the index of the lists.
Something like this:
class MainWindow(QtWidgets.QMainWindow, Ui_MAIN):
    def __init__(self, parent=None, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)0
        num = 3
        self.scrollAreaWidgetContents = [None for _ in range(num)]
        for x in range(num):
            self.Make(x)

    def Make(self, index):
       self.scrollAreaWidgetContents[index] = QtWidgets.QWidget()
       self.scrollAreaWidgetContents[index].setGeometry(QtCore.QRect(0, 0, 387, 177))
       self.scrollAreaWidgetContents[index].setObjectName("scrollAreaWidgetContents")

In the example above, I stored every scrollAreaWidgetContents that are created as elements of a list. Do that to all other objects that you create in your loop.


How to make a randomForest algorithm cost-sensitive?

Question: Having used randomForest in R to produce a fairly successful classifier is there any way to emphasise sensitivity over specificity, for example, if the cost of missing a disease is much greater than diagnosing a false positive?
Comment: http://www.biomedcentral.com/content/pdf/1471-2105-10-S1-S22.pdf Using random forest for reliable classification and cost-sensitive learning for medical diagnosis
Comment: Looks like the bst package in R will accept weights for false positive and false negatives. I'm going to leave the question open though, It might be useful to others.
Answer: I don't actually know R package, but if you were able to decrease the cost of False Positives it should work. This is also the rationale of MetaCost by Domingos, that is implemented in WEKA. However, increasing the sensitivity you are going to decrease the specificity, naturally. From the information retrieval point of view, as long as you increase the recall the precision will decrease.
Because Random Forest use Decision Trees as base classifiers and they can output probabilities, you can decrease the cut-off that enable a tree to classify a record as positive. This will make you Random Forest more sensitive but less precise.
Comment: Sure. I'll add that in case of randomForest, OOB votes are in `votes` element of the `randomForest` object; for prediction, one must use `predict` with `type="votes"` or `type="prob"`.
Comment: ...and here's and example on how to do that http://stackoverflow.com/questions/31130053/roc-for-random-forest/31149340?noredirect=1#comment50311605_31149340
Comment: Also another option is to use the weighted Gini gain http://stats.stackexchange.com/a/69335/2719


Execute Query in android searching if a string is contained inside the string inserted in a column

Question: I have a database in an android app and the following are its columns:
public class DBhelper extends SQLiteOpenHelper {
    public static final String COL_TIPO = "ColonnaTipo";
    public static final String COL_DIFFICOLTA="ColonnaDifficolta";
    public static final String COL_INGREDIENTI = "ColonnaIngredienti";

    //code
}

I use this function to make a query on it (TAB is the name of the table):
public Cursor query_filtri(String[] param, String[] p2) {
    String whereClause="";
    String[] whereArgs=new String[50];
    whereClause=COL_TIPO+"=? AND "+COL_DIFFICOLTA+"=?";
    whereArgs=new String[] {param[0],param[1]};

    return  getWritableDatabase().query(TAB,null,whereClause,whereArgs,null,null,null);
}

In param[] there are the values of COL_TIPO and COL_DIFFICOLTA that i am searching, and it works.
In p2[] there are 2 strings: p2[0] = "hi", p2[1]= "try".
I would modify the query to obtain the colums that in  COL_INGREDIENTI contains the worlds hi and try.
For example:
I would try to obtain this
COL_INGREDIENTI "hi, would you try?"

and not this
COL_INGREDIENTI "hi, how are you?"

How can i modify the query? Is there a way to make it not case-sensitive?
Answer: You can add:
AND COL_INGREDIENTI like '%hi%' and COL_INGREDIENTI like '%try%'

From the documentation:

The LIKE operator is case sensitive by default for unicode characters that are beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE

So, if you are using characters inside de ASCII range you don't need to worry about the case


Doubt on an identity vs equation intuition

Question: u+v+w=0  (1)
-u+v+w=0   (2)
Adding (1) and (2) we have
2v+2w=0
or, v=-w   (3)
Substituting (3) in (1) we have
u=0    (4)
y the place where they substituted v=-w in equation (1) while applying the Weiss Zone law is it permissible?I am asking this because I have used those two equations only to arrive at v=-w.Is this not an identity type of approach instead of an equation type?
Comment: Can you post the whole system please?
Comment: There is nothing more other than the two equations.@Dr.SonnhardGraubner. Equation (1) and (2) are the only two equations.
Answer: Adding both equations we get
$$v=-w$$, plugging this in one of the equations above we get
$u-w+w=0$ so $u=0$ and we get
$$[u,v,w]=[0,-w,w]$$
Comment: Yes correct but what allows me to substitute v=-w in the equation u-v+w=0 where I have derived v=-w relation from using the same u-v+w=0.Is this not going to be some of those 5=5 or 6=6 situation?


Um módulo é a mesma coisa que uma classe em Python?

Question: Um módulo é a mesma coisa que uma classe?
Se não quais são as diferenças? Pergunto isto porque segundo o The Zen of Python, devem ser usados módulos em vez de ifs.
O problema é que após pesquisar pareceram-me o mesmo.
Answer: Module
A grosso modo um módulo em Python é um arquivo com membros. Um módulo pode conter classes, funções e variáveis "soltas". Módulos são unidades organizacionais e usam um conceito de modularização.
Um módulo pode ser importado dentro de outros módulos fazendo que todos seus membros (import modulo) ou alguns selecionados (from modulo import classe) estejam disponíveis.
A primeira forma de importação apenas torna os membros disponíveis, a segunda forma ainda facilita o uso tornando desnecessário na maioria das situações a referência explícita do que está usando, mas também pode criar ambiguidades. Ainda é possível importar todos os membros com a segunda forma usando from modulo import *.
O nome de um módulo é o nome do arquivo sem a extensão .py.
Existe ainda um conjunto de módulos organizados em diretórios formando o que se chama pacotes (packages).
Class
Classes servem para criar tipos, para estruturar como objetos serão definidos. Classes possuem estado e comportamento relacionado ao estado, ou seja elas possuem propriedades e métodos que fazem ações relacionadas muitas vezes manipulando as propriedades existentes na classe. Classes são estruturas de dados e usa um conceito de orientação a objeto.
Classes podem ser instanciadas, ou seja, é possível criar objetos e guardá-los em variáveis com base no que foi definido nela. A classe é um modelo a ser seguido, é como se fosse uma planta baixa de uma casa e o objeto será a casa construída.
Tecnicamente classes podem ser usadas também como unidades organizacionais. Neste caso a classe não deveria ser instanciada e provavelmente só teria métodos de classe e variáveis estáticas. Mas este não é o jeito pitônico de fazer já que a linguagem permite obter o mesmo resultado com módulos.
Os membros "normais" de uma classe só podem ser acessados através de uma instância. Eles não existem até que um objeto seja criado com base na classe.
Classes podem ter subtipos, ou seja, pode ter herança e criar uma hierarquia de tipos.
Para usar uma classe basta chamar um construtor dela que se confunde com seu próprio nome:
funcionario = Funcionario("João", 2000) //está criando um objeto com base na classe Funcionario

Coloquei no GitHub para referência futura.
Artigo na Wikipedia sobre classes.
Conclusão
De uma certa forma podemos dizer que os módulos são sobrenomes para as classes e outros membros que formam uma mesma família.
Talvez a ideia de que são a mesma coisa vem do fato que ambos possuem membros (variáveis e funções) mas a forma como eles serão acessados é bem diferente. Para facilitar o entendimento pode-se imaginar um módulo como sendo uma classe que não pode ser instanciada. De fato e em algumas linguagens o módulo é exatamente isto. Não é bem o caso de Python, mas se este pensamento mais ajuda do que atrapalha o seu entendimento, use-o.
Não sei onde você leu que módulos devem ser usados no lugar de ifs, isto parece ter tanto sentido quanto usar gasolina no lugar de aço para fazer um milk-shake. De fato isto já é esquisito considerando o título da pergunta que faz sentido e usei-o para responder. Talvez alguma comparação tenha sido feita para facilitar o entendimento e causou mais confusão.
Answer: Não. Módulo pode ser definido como um arquivo que contém definições de variáveis, funções e classes, criar um módulo pode ser útil em situações que você necessite utilizar as mesmas funções e/ou classes em outros projetos sem ter a necessidade de escrevê-los em cada um.
Veja uma demonstração:
# Modulo1
# Define variaveis
var1 = 1
var2 = 2

# Define algumas funcoes
def ola():
    return "ola!"

def vezesquatro(numero):
    return int(numero) * 4

# Define uma classe
class Foo:
    def __init__(self):
        self.nome  = raw_input("Qual o seu nome:")
        self.idade = raw_input("Qual a sua idade:")
        self.peso  = raw_input("Qual o seu peso:")
    def info(self):
        print "O nome dele e {0}, tem {1} anos e pesa {2} quilos!".format(self.nome, self.idade, self.peso)

Salve o script acima como modulo1.py e crie um outro script e execute o código:
#!/usr/bin/python

import modulo1

print (modulo1.var1)
print (modulo1.var2)

ola = modulo1.ola()
print (ola)

quatro = modulo1.vezesquatro(10)
print ("10 x 4 = {0}".format(quatro))

f = modulo1.Foo()
f.info()

Já uma classe é uma estrutura que abstrai um conjunto de objetos que define o comportamento destes através de métodos e os estados possíveis destes objetos através de atributos.
A resposta do mgibsonbr na questão abaixo aborda esse assunto de um modo mais amplo.

Para Que serve a Class no Python?


Simple point processes and the expected value

Question: When considering simple point processes, how is
$$P(t_{n+1} \in [t;t+dt]) = E[N([t;t+dt])]$$,
where $N(A)$ is the number of points in interval $A$ and $dt$ is the length of an infinitesimal interval. My argument is that it's because we are considering simple point processes - a.k.a there is either zero or one point in an infinitesimal interval. Is that true? If so, I'm feeling that I'm missing something in my argument. I think my question is still why we can say that it's the expected value?
And if it's all wrong, I hope I can get another explanation :)
Comment: My question is, why we can rewrite the probability function to be the expected value? My suggestion was, because there can't occur more than one point at the same time (since we only observe simple point processes), hence the same goes for a infinitesimal interval. However, I want a deeper explanation to since I can't provide it. The idea is specifically about why we can write is an expected value when considering simple point processes. it's not specifically about the infinitesimal interval. I hope this made it more clear?
Comment: I agree it's a different question, but it appears to be about exactly the same issue: namely, how to understand an "infinitesimal" interval.  There's a fundamental difficulty here, because the chance of a point lying in any infinitesimal interval is zero.  And that's exactly what your other question looks like it's trying to ask about.  I therefore would like to suggest you settle on a single best formulation of the issues you are pondering and edit your original question to focus on it.
Comment: Where do you get this equality? Do you have a reference? What does $dt$ mean? In the limit ($dt \to 0$) I imagine that these quantities go to zero. If it is not the limit then equality seems false (I imagine that the righthand side - the expectation of the number of events - can be above 1, while the lefthand side - a probability - must be below 1 by definition).
Comment: What is the meaning of $P(t_{n+1} \in [t;t+dt]) = E[N([t;t+dt])]$, what is $t_{n+1}$ ?
Answer: If a random variable only can take the values 0 and 1 the expected value is equal to the probability of getting 1:
E(X) = 0P(X=0) + 1P(X=1) = P(X=1)
Together with the fact that it is a simple process and appropriate limiting arguments get you heuristically to the result you state.


What is the easiest way to upgrade an EC2 instance type?

Question: In order to upgrade our EC2 instances (or downgrade for that matter) I use the AWS console to "Create Image (EBS AMI)" and then I launch the AMI once it has been created.  Is there a way that would make it possible for me to upgrade/downgrade without having to create the AMI?
Thanks for your help.
Answer: You can check the API tools command ec2-modify-instance-attribute. You need to stop the instance, apply the command and start it again.
I've done this with my Linux AMI's. :)
Answer: The only way to persist changes is via EBS.  AMIs are read-only, though you can always use one AMI to create another.


Animação não está fluida

Question: Opa galera tenho uma div que é meu cabeçalho do site, quero esconder ele ao clicar em um botão e fazer ele aparecer ao clicar em outro botão. Consigo fazer esconder e a movimentação está do jeito que quero, contudo na hora de fazer aparecer de volta não apresenta a mesma fluidez e a imagem não fica na tela, sumindo ao final.

function myMove() {
    var elem = document.getElementById("box-toogle");
    var pos = 0;
 var t = 0;
 var id = setInterval(frame, 5);
    function frame() {
        if (pos == 160) {
            clearInterval(id);
        } else {
            pos--;
            elem.style.top = pos + 'px';
    t++;
        }
}

function myMove1() {
    var elem = document.getElementById("box-toogle");
    var pos = 150;
 var t = 0;
 var id = setInterval(frame, 5);
    function frame() {
        if (pos == 0) {
            clearInterval(id);
        } else {
            pos--;
            elem.style.top = pos + 'px';
    t++;
        }
}
#box-toogle {
 width: 100%;
    height: 150px;
    position: relative;
}

texto

Sou iniciante em javascript, se puderem me ajudar agradeço
Comment: olhando o seu código, os métodos `myMove` e `myMove1` não tem a ultima `}` para encerrar o método, faça a correção e teste novamente.
Comment: As suas funções não estão fechadas, cada uma falta um chaves no final. Aconselho utilizar uma boa IDE para programar, a qual faz highlight nos códigos e ajuda a visualização e percepção destes erros básicos, Netbeans é uma delas.
Comment: Opa me desculpem na hora de copiar e colar acabei esquecendo a ultima  chave, no meu código está fechado certinho e continua não fluido, alterarei o código aqui colado para ficar de acordo. aguardo o parecer de vocês obrigado.
Answer: Este tipo de animações devem ser feitas com CSS.
Nesse caso só precisas de
#box-toogle {
    // ...

    top: 0px;
    transition: top 1s;
}

#box-toogle.escondido {
    top: -100px;
}

e quando o elemento for clicado adicionas ou removes essa classe escondido.
Exemplo:

var header = document.getElementById('box-toogle');
header.addEventListener('click', function() {
    this.classList.toggle('escondido');
});
#box-toogle {
    width: 100%;
    height: 150px;
 border: 2px #ddf solid;
 font-size: 80px;

 top: 0px;
    position: relative;
    transition: top 1s;
}

#box-toogle.escondido {
    top: -100px;
}
texto

jsFiddle: https://jsfiddle.net/zdt1vced/
Comment: @VeteranoKuno1 ainda bem que funcionou. Se quiseres podes marcar a resposta como aceite. Estás a precisar de uma função onload para o código só correr quando a página carrega. Se colocares o teu código dentro de `window.onload = function () { ... };` já deve funcionar num fcheiro externo também. Ou então coloca a tag `
Comment: Sergio muito obrigado, não sei se é uma dúvida de novato mas não consigo fazer funcionar o código que me passaste no jsFiddle executa tranquilamente, agora quando passo para o notepad e executo no navegador o mesmo não acontece, copiei e colei igual me passaste preciso fazer + alguma alteração?

Outra coisa sabes me dizer pq não é recomendado fazer efeitos assim apenas no js?, obrigado imensamente.
Comment: @VeteranoKuno1 sobre CSS vs JS dá uma olhada aqui: http://pt.stackoverflow.com/q/51542/129
Comment: @VeteranoKuno1 em relação a não funcionar na tua página, coloca o JavaScript no final da página. Se não funcionar coloca aqui um pastebin com a página toda.
Comment: Sérgio realmente colocando no final da página funcionou, não entendi pq não funcionou em um js externo. Amolando você um pouquinho + e com preguiça de pesquisar aqui no fórum qual livro você recomenda, estou usando o codeAcademy para aprender o básico + já sinto necessidade de  outras alternativas, abraço e muito obrigado, mesmo!

Animação não está fluida


Qual a diferença e quando utilizar @mixin e @extend em SASS?

Question: Tanto o @mixin como o @extend parecem ter o mesmo objetivo:

Adicionar um bloco de código padrão para uma classe.

Mas se possuem essa mesma finalidade, qual a diferença entre eles? E quando devo utilizar um ou outro?
Comment: Relacionando: [Qual é a diferença entre um mixin e uma function em SASS](http://pt.stackoverflow.com/questions/112485/qual-%C3%A9-a-diferen%C3%A7a-entre-um-mixin-e-uma-function-em-sass)
Comment: Sim, mas o comparativo entre `extend` e `function` é amplo de mais. Já a relação `mixin` vs `extend` é mais próxima. Por exemplo, `function` e `extend` possuem uma distinção bem clara, o que não é o caso de um `mixin` e um `extend`.
Answer: A utilização de @mixin e @extend pode parecer semelhante e ter a mesma finalidade, apesar de isso ser verdade, elas possuem propósitos diferentes bem como seus prós e contras. Ambas, se utilizadas de modo errado, podem se tornar uma baita dor de cabeça.
No começo a gente pode tender a utilizar um ou outro aos montes devido a praticidade que eles nos dão para escrever SASS. Com um @mixin ou @extend você pode resumir inúmeras linhas de códigos. Mas é ai que mora o perigo..
Muitas vezes o que escrevemos em SASS parece perfeitamente prático e perfeito, tudo parece em ordem, mantendo o princípio de DRY, mas tudo vai embora quando olhamos nosso código compilado para CSS.
Por exemplo, o código a seguir pode parecer perfeito em SASS:
@mixin placeHolder {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}
.classe1 {
    @include placeholder;
}
.classe2 {
    @include placeholder;
}
.classe3 {
    @include placeholder;
}
.classe4 {
    @include placeholder;
}
.classe5 {
    @include placeholder;
}

Mas o CSS gerado seria este:
.classe1 {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}
.classe2 {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}
.classe3 {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}
.classe4 {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}
.classe5 {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

Todo o princípio DRY, manutenção de código e simplicidade que em SASS parecia perfeita, foi por água abaixo...
Mas é aí que entra o @extend para a salvação! Veja a mesma lógica com a utilização de @extend:
%placeHolder {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}
.classe1 {
    @extend %placeHolder;
}
.classe2 {
    @extend %placeHolder;
}
.classe3 {
    @extend %placeHolder;
}
.classe4 {
    @extend %placeHolder;
}
.classe5 {
    @extend %placeHolder;
}

Gerando o seguinte código:
.classe1,
.classe2,
.classe3,
.classe4,
.classe5 {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

Perfeito, agora nós conseguimos manter o código simples, limpo, em poucas linhas de código.
MAS.....
Apesar de isso ser verdade, é uma verdade parcial. A utilização de @extend quando feita de modo abusivo pode quebrar todo o princípio básico de seu uso e gerar muitas classes com poucas propriedades, tornando seu código final extremamente bagunçado, com repetição de classes, voltando a estaca zero.
Mas então qual devo usar? E quando devo usar?
Um macete básico que gosto de lembrar é o seguinte:

Mixin: Utilize para gerar seu código de modo dinâmico através de variáveis;
Extend: Utilize para elementos comuns mas que haverá pouca repetição;

Por exemplo, vamos supor que você possua um botão com o mesmo estilo porém com alguns estados de cores. Você poderia fazer da seguinte maneira:
@mixin corBotao($cor, $corHover) {
    border: 1px solid $cor;
    color: $cor;
    &:hover {
        background: $cor;
        color: $corHover;
    }
}
.button--azul {
    @include corBotao(blue, white);
    background: transparent;
    width: 64px;
    height: 48px;
    cursor: pointer;
    text-align: center;
}

Deste modo você irá gerar o seguinte código:
.button--azul {
    background: transparent;
    width: 64px;
    height: 48px;
    cursor: pointer;
    text-align: center;
    /* Gerado pelo mixin */
    border: 1px solid blue;
    color: blue;
    &:hover {
        background: blue;
        color: white;
    }
}

Com isso você pode gerar diversos botões com cores diferentes sem precisar definir manualmente qual cor cada botão terá.
Para exemplificar o uso do @mixin, pode partir do mesmo exemplo anterior e melhorar nosso código. As propriedades de width, height, etc.. São comuns em todos os botões, seja ele azul, vermelho, verde, etc.. Então apenas essas propriedades podemos converter para o uso do @extend:
@mixin corBotao($cor, $corHover) {
    border: 1px solid $cor;
    color: $cor;
    &:hover {
        background: $cor;
        color: $corHover;
    }
}
%padraoBotao {
    background: transparent;
    width: 64px;
    height: 48px;
    cursor: pointer;
    text-align: center;
}

.button--azul {
    @include corBotao(blue, white);
    @extend %padraoBotao;
}
.button--verde {
    @include corBotao(green, white);
    @extend %padraoBotao;
}
.button--vermelho {
    @include corBotao(red, white);
    @extend %padraoBotao;
}

O exemplo acima irá gerar o seguinte código final:
.button--azul,
.button--verde,
.button--vermelho {
    background: transparent;
    width: 64px;
    height: 48px;
    cursor: pointer;
    text-align: center;
}
.botao--azul {
    border: 1px solid blue;
    color: blue;
    &:hover {
        background: blue;
        color: white;
    }
}
.botao--verde {
    border: 1px solid green;
    color: green;
    &:hover {
        background: green;
        color: white;
    }
}
.botao--vermelho {
    border: 1px solid red;
    color: red;
    &:hover {
        background: red;
        color: white;
    }
}

Veja como o código final se manteve limpo, organizado, objetivo e mantendo boas práticas.
O que não seria recomendado, seria utilizar o mesmo extend para outro elemento, por mais que ele possua a mesma característica.
Outro exemplo que eu, particularmente, utilizo o @mixin é para códigos pequenos que serão utilizados em algumas classes, por exemplo o uso de display: flex;. Como ainda precisamos dos vendor-prefix, eu não quero escrever todos eles à mão, mas também não quero gerar um agrupamento de classes complemante sem relação, só por partilharem do mesmo display. Para isso eu utilizo um mixin, mas é um uso controlado com um objetivo bem específico.

Como visto nos exemplos, cada um possui um uso bem específico e destinado. Apesar de serem semelhantes DENTRO DO SASS, quando olhamos nosso CSS eles possuem resultados bem distintos que podem piorar seu código final ao invés de melhorar.
Mas, apesar de toda essa diferença, lembre-se que não é uma regra a ser seguida a risca (como eu mesmo a quebro de vez enquando), tudo se trata de um planejamento e organização do seu código.
Para mais guias de boas práticas em CSS e SASS recomendo ver este projeto que estou elaborando no github, ele está em desenvolvimento constante e também aceito contribuições! Aliás, elas são mais do que bem vindas. Mais experiências geram melhores práticas.


Script para remover assinatura BOM dos arquivo UTF-8

Question: Estou com vário problemas de arquivos em UTF-8 com BOM, varios tokens estao sendo gerado no inicio das páginas, isso faz ocorrer varios problemas nas leituras de arquivos json e desindentação dos componentes HTML. Quase impossível de descobrir pois os tokens são invisiveis. Procurei no google uma forma de alterar todos os arquivos para UTF-8 sem BOM e achei um script em perl para remover a assinatura BOM mas não funcionou. Alguem poderia ajudar. Preciso de um script que altere todos os arquivos do projeto.
Mais informções do problema e o script pode ser encontrada aqui
A minha soluçao por enquanto é ficar garimpando os arquivos e salvando em UTF-8 sem BOM, mas são vários arquivos, por isso pensei em um script, mas não tenho idéia de como fazer.
A solução momentanea para os problemas de token do json eu fiz assim para resolver (POG):
1.Recupero a string apartir da primeira chaves { encontrada.
Pois os tokens são gerados antes dessa chave. Isso resolve momentaneamente. Mas é uma gambiarra.
json = json.substring(json.indexOf("{"),json.length);
objeto = $.parseJSON(json);

Comment: Precisa ser em Perl? E é mesmo necessário um script completo, ou você já está trabalhando em alguma linguagem e pode só incorporar um pequeno trecho de código? Remover o BOM é trivial, basta ler os três primeiros bytes do arquivo e - se eles corresponderem a um certo padrão - criar um novo arquivo do 4º byte pra frente. Assumindo UTF-8, é claro.
Comment: eu quero remover o BOM em todos os arquivos do projeto. o JavaScript foi um exemplo de como consegui dar a volta no problema em uma determinada circunstância. Mas o que eu queria era um código similar a esse feito em perl do site que citei. Mas não consegui fazer funcionar aqui.
Comment: Não precisa ser em Perl,  na verdade nunca programei em Perl. Portanto qualquer linguagem pode ser feito. Eu uso linux as vezes pode ter até um programa que ja faça isso mas eu não conheço.
Obrigado @mgibsonbr, parece simples fazer para um depois que voce explicou, o problema acho que será identificar o formato do arquivo e fazer uma busca em todos os diretorios do projeto.
Comment: Posso tentar fazer se não existir agum script ja pronto.
Comment: Você está usando JavaScript? Resolveria um código para eliminar o BOM no JavaScript, logo antes de você usá-lo? (ou você realmente precisa converter os arquivos localmente?)
Comment: logo vou tentar seguir sua dica e vou tentar fazer o script em python ou em c.
Comment: Eu estou escrevendo uma resposta, é que achei que podia ser algo mais simples.
Comment: pode responder. A sua resposta pode ser útil.
Answer: Um arquivo UTF-8 com BOM é simplesmente um arquivo na codificação UTF-8 em que os primeiros 3 bytes são EF BB BF. Identificar o BOM é portanto uma questão de ler os 3 primeiros bytes e ver se eles correspondem a esse formato. E para eliminar o BOM, é só copiar o restante do arquivo pra saída, sem incluir esses 3 bytes.
Um exemplo em Python (3), bem simplificado (Disclaimer: não testei!), seria:
import os, sys

def tem_bom(arq):
    with open(arq, mode="rb") as f:
        bom = f.read(3)
        resto = f.read()
        if bom == b"\xef\xbb\xbf":
            return True, resto
        else:
            return False, bom + resto

def copiar_pasta(origem, destino, copiar_sempre=True):
    for nome in os.listdir(origem):
        path1 = os.path.join(origem, nome)
        path2 = os.path.join(destino, nome)

        if os.path.isfile(path1):
             bom, resto = tem_bom(path1)
             if bom or copiar_sempre:
                 with open(path2, "wb") as f:
                     f.write(resto)
                 if bom:
                     print("Corrigido arquivo {}".format(path1))

        elif os.path.isdir(path1):
            os.mkdir(path2)
            copiar_pasta(path1, path2, copiar_sempre)

if __name__ == "__main__":
    copiar_pasta(sys.argv[1], sys.argv[2])

Esse exemplo pegaria uma pasta de origem e copiaria todos os arquivos para uma pasta de destino, recursivamente. Cada arquivo que tivesse BOM, ele copiaria sem o BOM. Fiz dessa forma (sem alterar nada na pasta original) pra não correr o risco de sobrescrever nada importante, apenas verifique se a pasta de destino é uma nova pasta, vazia. Adapte se necessário.
Comment: Testei aqui e realmente parece que deu certo era exatamente isso @mgibsonbr, Muito obrigado. Mas está quase 100% @mgibsonbr, fiz o teste aqui e aparentemente removeu o BOM,  porem precisa de correção nas funções `is_file` e `is_dir` que seriam respectivamente `isfile` e `isdir`. E também um outro problema quando vai copiar um arquivo que está dentro de outra pasta o programa n ta  criando a pasta no outro diretorio antes de copiar o arquivo, ai diz que não é possivel copiar pois a pasta no diretorio destino nao existe, nada que uma pequena correção para ficar perfeito.
Comment: @Skywalker Valeu pelas correções! Corrigi aqui, e também acrescentei uma opção na função pra quando o arquivo não tiver BOM não copiar (vai que a pasta é grande, tem muitos arquivos, etc). Só teria que chamar a função passando esse parâmetro com `False`.
Comment: Agora sim @mgibsonbr, acabei de rodar o script no projeto, funcionou, sumiu todos os tokens malditos rsrs. Obrigado mais uma vez. Ficou 10 o script.
Answer: #!/usr/bin/perl -pi
s/^(\xEF\xBB\xBF)//;  ## remove BOM !

Esta versão altera os próprios ficheiros.
Exemplo de uso:
rmbom *.js
ou
perl rmbom file1 file2  *.js  dir/*


Then sum of digits in $M\times N$

Question:
If $\bf{M = \underbrace{777777777777777777777}_{99-times}}$ and $\bf{N = \underbrace{999999999999999999999}_{77-times}},$ Then sum of digits in  $M\times N$

$\bf{My\; Try::}$ We can write $$M = 7(1+10+10^2+\cdots \cdots +10^{98}) = \frac{7}{9}(10^{99}-1)$$
and write $$N = 9(1+10+10^2+\cdots \cdots +10^{76}) = \frac{9}{9}(10^{77}-1) = (10^{77}-1)$$
So $$M\times N = \frac{7}{9}(10^{99}-1)\times (10^{77}-1)=\frac{7}{9}\left[10^{196}-10^{77}-10^{99}+1\right]$$
Now how can i solve it after that, Help required, Thanks
Comment: Why not try some smaller ones that you can do on a calculator, $777\times9$, $77777\times99$, and suchlike, and look for patterns?
Comment: The question is not clear... "Then sum of digit in the product of $M \times N$". Check it please.
Answer: Note that $N=10^{77}-1$, hence $MN=$
$\underbrace{7\dots7}_{99}\cdot(10^{77}-1)=$
$\underbrace{7\dots7}_{99}\cdot10^{77}-\underbrace{7\dots7}_{99}=$
$\underbrace{7\dots7}_{99}\underbrace{0\dots0}_{77}-\underbrace{7\dots7}_{99}=$
$\underbrace{7\dots7}_{76}6\underbrace{9\dots9}_{22}\underbrace{2\dots2}_{76}3$
Hence the digit-sum of $MN$ is $7\cdot76+6+9\cdot22+2\cdot76+3=891$.

Then sum of digits in $M\times N$


Re-use fields in a content type

Question: I have a content type with 4 different sections to it.  At the bottom of each section, there are 2 "Call to action" links.
These links all point to the same 2 urls.  I'd like to be able to set up 2 fields of the type "link" and then re-use those fields 4 times, instead of having to set up 8 links.
Is this possible?
Is there a better way of doing it ?
Comment: use multivalue link field
Answer: If these sections are text or similar, you can create field collections that enclose other fields.

Provides a field-collection field, to which any number of fields can
  be attached.
A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

Re-use fields in a content type


how to reduce the summation value of binary variable to 1 , Integer Linear Programming

Question: I have a binary set of variable Viu whose value can be either 0 or 1 ,
There can be multiple time when(ith value of Viu) V_1_A is assigned value 1
There is another integer Variable Xi which holds some value and is assigned to i when he is assigned the value of 1.....
For eg. when V_1_A is selected  X_1=10;
My linear equation is
V_1_A * X_1_ =10 i:e 1* 10=10
As mentioned above V_1 could get assigned to V_1_A and also V_1_B, I want that the summation of V_1 should not be 2 but should get reduced to 1 so that the value Xi be multiplied only although Vi is selected multiple times.
I am very new to ILP, please help
Comment: V_1_A*X_1=10 is not a linear equation. To fix that, it would help to know what X_1 should be when V_1_A = 0.
Comment: It's not possible to contact users via flags. They can be notified using @SagarikaKhandelwal for example. But it was not needed here, as in certain cases it's automomatic.
Comment: @prubin i need to have something like this: if sum of some variables (V[i,u,p]) is equal or more than 1 then another variable (z[i]) should be equal to 1 else it should be 0. I then want to use Z[i] to multiply with a constant value reserved for indices i Something like If sum of V[i,u,p] >=1 then Z[i]=1 else sum of V[i,u,p] =0 then Z[i]=0
Answer: I'll answer the question raised in one of the comments: how to get Z[i] to take the value 1 if a sum of V[i,...] variables is >= 1 and to take the value 0 if the sum of the V[i,...] is 0, assuming that V and Z are binary. You just need the following constraints:

Z[i] <= sum of V[i,...] (which ensures that Z[i] is 0 when the sum is zero); and
Z[i] >= V[i,...] for every V in the summation (which ensures that Z[i] is 1 if any V[i,...] that is part of the sum is 1.
Comment: Thanks for your help @prubin
For the second constraint did you mean Z[i] >=  sum of i, sum of u, sum of p V[iup], because in that situation how can Z[i] will be 1, since the summation of these indices  be greater than 5 or 8 in case of multiple assignments of i with u and p
Comment: No, I meant that the second constraint is Z[i] >= a single V, repeated for each relevant V.
Comment: I figured it out, Thanks much @Prubin