text:
Q: What is the purpose of std::byte? Now that c++17 has std::byte, I was looking for a way to convert code that reads files to char into code that reads files into byte. A file contains bytes, not a bunch of integers.
Then I read this question and this other question where people argued that reading files into byte is wrong, and that reading files into char is right.
If byte is not designed for the purpose of accessing memory, and by analogy, files, then what is the its purpose? As is quoted in the other two questions:

Like char and unsigned char, it can be used to access raw memory
  occupied by other objects (object representation), but unlike those
  types, it is not a character type and is not an arithmetic type. A
  byte is only a collection of bits, and only bitwise logic operators
  are defined for it.

This sounds like the exact type that should be used for reading files, not characters.

A: You are perhaps misunderstanding things.
byte is very much intended for "accessing memory". You are intended to use the type when the storage is just a sequence of bytes rather than an array of characters.
Iostream types cannot be specialized with byte, since they're designed around characters as their interface. That is, they do not think of files as sequences of bytes; they think of them as sequences of characters. Now, you can certainly read directly into a byte array by using a cast or two. But that's not the way iostream natively thinks.
You have to make a distinction between the way iostream works and the way files work. Iostream is just one file IO library, after all; it is hardly the end-all, be-all of file APIs.
Most file APIs for reading binary data take void* rather than character arrays. std::fread/fwrite, and so forth.
That is, you should think of this, not as a problem with std::byte, but as a problem with iostream. Just another in a long line of them.


text:
Q: Firefox Quantum - select multiple tabs? Is there still no way to select multiple tabs in firefox fox quantum? How about merging two windows into one (this is my reason for selecting tabs)?
There used to be, years ago, some plugins and add-ons but all of the ones I'm familiar with are obsolete from the new firefox plugin setup - and it seems a bit ridiculous to need to install a plugin to accomplish this task to begin with. I feel I must be missing something..
Here are a collection of the firefox keyboard/mouse shortcuts, but I don't see a multiple tab selection option available (keyboard: https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly#w_windows-tabs) (mouse: https://support.mozilla.org/en-US/kb/mouse-shortcuts-perform-common-tasks)

A:
This answer was originally written when add-ons were the only alternative. Now that Firefox can natively select multiple tabs, that is explained first, and the add-ons later.

Firefox can now natively select multiple tabs from the tab bar.
Native tabs selection
To select multiple tabs, press Ctrl or Shift and followed by a click on the mouse primary button for discontinuous or continuous selection respectively. The selected tabs can be managed from the tab context menu, keyboard shortcuts and drag and drop.
This feature is available from the recent releases of Firefox Quantum, and has been mentioned in the Firefox 64 release note.

Enhanced tab management: You can now select multiple tabs from the tab bar and close, move, bookmark, or pin them quickly and easily

The hidden configuration named browser.tabs.multiselect has been included at least from Firefox 62 however, with limited implementation. Some differences can be observed:

*

*Firefox 62 can select multiple tabs (disabled by default), but limited to bookmark, reload, close selected tabs.

*Firefox 63 can select multiple tabs (disabled by default), but limited, yet can additionally move to new window, and close other selected tabs by drag and drop.

*Firefox 64 can select multiple tabs and do everything as per release note.

Tested using Firefox 62, 63, 64 on Linux.
Tabs selection with add-ons
Before tabs selection became native, there are already some add-ons that can do similarly. Firefox with add-ons however, does not behave exactly same as native Firefox or Chrome does. The main reason: Firefox Quantum add-ons are limited by the design of the modernized Firefox add-ons.
Anyway, I have noted two add-ons that can select multiple tabs:

*

*Multiple Tab Handler by Piro (piro_or)

Allows users to select multiple tabs in a window and perform operations on them.

*MultiSelect Tabs by mike_conley

Provides feature to close multiple tabs.

Both add-ons can be installed in Firefox Quantum. Multiple Tab Handler uses a button in the main toolbar, and on the other hand, MultiSelect Tabs uses the sidebar to provide the functions.
Tested add-ons using Firefox 57, 59 on Linux.
TL;DR Firefox can now natively select multiple tabs. Firefox 62 and 63 can do already, but limited and disabled by default. User can now forget the add-ons and do natively.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET MVC 3 Error and Exception Handling with 404 What is the best way to log an exception and give the user the error code that was logged.  Along with this how are 404 errors handled.  I have seen many solutions for both but not together in a way that fits nicely with the mvc model.  Do you have an example too?  Also for 404's is there a way to get the 404 even if the user hasn't logged in to the app?
Is elmah something that should be used in production?
Is there a nuget package that people suggest using?

A: Yes, use elmah, but make sure that access to the log viewer is controlled.
The package is Elmah.MVC, and make sure you read these:
http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx
http://dotnetdarren.wordpress.com/2010/07/27/logging-on-mvc-part-1/


text:
Q: How to merge two sql queries results? One query has GROUP BY I have a table like below
id, date, type, quantity, vendor
'1','2020-04-05','2424A','200','vendor1'

'2','2020-04-05','2424','350','vendor1'

'3','2020-04-05','2424A1','150','vendor1'

'4','2020-04-05','2425','400','vendor1'

'5','2020-04-05','MA5878','200','vendor2'

I am using Java as my backend.
I have tried these queries

*

*SELECT vendor, type, quantity
FROM reports;
vendor, type, quantity
'vendor1', '2511', '200'

'vendor1', '5120', '350'

'vendor1', '2520', '150'

'vendor1', '5114', '400'

*SELECT vendor, SUM(quantity)
FROM reports
where date = '2020-04-05'
GROUP BY vendor;
vendor, SUM(quantity)
'vendor1', '1100'

'vendor2', '20600'

I need to combine the above 2 queries results. Can someone guide me to proceed further.

A: Give this a try:
WITH a AS (
    SELECT vendor, ont_type, quantity
    FROM cpe_portal.ontfereports
), b as (
    SELECT vendor, SUM(quantity) as quantityb
    FROM cpe_portal.ontfereports
    WHERE date = '2020-04-05'
    GROUP BY vendor
)
SELECT a.vendor, a.ont_type, a.quantity, b.quantityb
FROM a join b ON a.vendor = b.vendor


text:
Q: How to use Selenium elements to wait, check, click on without finding the elements again? I am new to Selenium and was using Telerik free testing framework before. Problem is I am not able to understand, how to use elements which are already identified with [FindsBy] to wait, check and click on.
ex:
    [FindsBySequence]
    [FindsBy(How = How.Id, Using = "container-dimpanel")]
    [FindsBy(How = How.CssSelector , Using = ".btn.btn-primary.pull-right")]
    public IWebElement UpdateButton { get; set; }

    internal void ClickUpdateButton(TimeSpan timeout)
    {
        new WebDriverWait(_driver, timeout).
            Until(ExpectedConditions.ElementIsVisible(By.CssSelector(id));
        UpdateButton.Click();
    }

I want my code to wait for update button to be visible and then click on it. But I want to just pass the UpdateButton element rather than using By selector.

*

*not sure if UpdateButton.Enabled will wait until its visible.

A: There is an expected condition for visibility that accepts a WebElement:
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#visibilityOf-org.openqa.selenium.WebElement-
Until also returns the element being waited for, so you can combine this into one line:
internal void ClickUpdateButton(TimeSpan timeout)
{
    WebDriverWait wait = new WebDriverWait(_driver, timeout);
    wait.Until(ExpectedConditions.visibilityOf(UpdateButton)).click();
}

However, in my frameworks I usually add a helper function that does this, as it get's used so much. You can also do similar things with wait until clickable, etc. and have methods that accept a WebElement or a By:
public WebElement waitThenClick(WebElement element)
{
    WebDriverWait wait = new WebDriverWait(_driver, timeout);
    return wait.Until(ExpectedConditions.visibilityOf(UpdateButton)).click();
}

A: The C# client doesn't have a builtin condition to check the visibility for a proxied WebElement.
Moreover the expected condition ExpectedConditions.ElementIsVisible checks that the element is displayed but doesn't check that the element is visible from a user perspective.
So the quickest and most reliable way is to retry the click in a waiter until success:
Click(UpdateButton, 5);

static void Click(IWebElement element, int timeout = 5) {
    var wait = new DefaultWait<IWebElement>(element);
    wait.IgnoreExceptionTypes(typeof(WebDriverException));
    wait.PollingInterval = TimeSpan.FromMilliseconds(10);
    wait.Timeout = TimeSpan.FromSeconds(timeout);
    wait.Until<bool>(drv => {
        element.Click();
        return true;
    });
}

A: Use this function I've written to test for an element, you can just pass in the name. It will return a bool and you could use a loop to wait for the elements to be present.
static public bool verify(string elementName)
{
    try
    {
        bool isElementDisplayed = driver.FindElement(By.XPath(elementName)).Displayed;
        return true;
    }
    catch
    {
        return false;
    }
    return false;
}


text:
Q: How to get desired FireFox last tab behavior? All tabs should be the same; so if any of the have a 'close' button, they all should, including the last tab. I see no reason that a tab's close button should suddenly vanish simply b/c that tab has become the last one open. If I have N tabs open, and park the mouse over the left-most tab's close button, this vanishing close button trick means now I have to make a large mouse move to get to the app's close button. Unsat. Mouse moves = too many milliseconds wasted.
Closing the last tab should NOT take me to my home page, or any other page whatsoever. I want the browser to close with the last tab. I do not expect or want "new tab" behavior when I click a Close button.
Now, I've gone into about:config and played with browser.tabs.closeWindoWithLastTab, but this setting oversteps its purpose; while it does make the browser close, for some inexplicable reason, it also suppresses the last tab's close button!
I have tried the "last tab close button" add-on, and while this does restore the close button, the add-on oversteps by taking the liberty of turning closeWindowWithLastTab off.
Is there some way out of this pickle? Is it too hard to just code things to provide simple, orthogonal actions, so that everybody can config the UI to their liking, and not just to a few pre-fab configurations that the developers think everyone should like?
Btw, FF 13.0.1 on ms windows

A: You can configure the Last Tab Close Button add on to close the last window intead of opening about:newtab.
Steps:

*

*Press Ctrl + Shift + A to open the Add-ons Manager.

*Click Options in the Last tab close button entry.

*Choose Close window.

*Click OK.


text:
Q: What does it mean "I'm old. I've seen a lot of bubbles burst. :)"? I met a women who was in Silicon Valley asked,

"You must have seen the bubble burst then?"

She replied back saying,

"I'm old. I've seen a lot of bubbles burst. :)"

What does it mean? Is that a wordplay?

A: I believe she means that she has seen several boom and bust cycles. Historically there are regularly periods of economic growth followed by contraction.

A: I don't think so, I think she just means that she has been around long enough to see multiple "bubbles" burst. Maybe she's 300+ years old and remembers this one.

A: In addition to the two fine answers already given, it is worth considering the context given in the first line of the OP. As an inhabitant of Silicon Valley, one needn't even be particularly old to have seen multiple bubbles burst, given the nature of the dot-com boom either side of the turn of the century. Conversely, she may consider having witnessed so many bubbles burst to have aged her.


text:
Q: Kafka producer and consumer in seperate EC2 instance I have 2 ec2 instances one for Kafka broker and the other for Kafka Consumer. May i know how to connect both the ec2 instance to communicate with each other. If i produce a message in my broker i need to get it in the consumer.
Basically, i am looking for that part of configuration where i need to give the consumer information in the broker ec2 instance and vice versa (whichever way it works) . Do i need to use some api or something ?
I have tried in a single node cluster and it worked.

A: It does not matter you are hosting your broker in ec-2 or elsewhere as long as it is accessible to consumer.
A sample consumer in Java using StringDeserializer for both key and value. You need to use the KafkaConsumer API if you are accessing from a Java program
 Properties props = new Properties();
 props.put("bootstrap.servers", "YOUR_KAFKA_BROKER_ADDRESS");
 props.put("group.id", "test");
 props.put("enable.auto.commit", "true");
 props.put("auto.commit.interval.ms", "1000");
 props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
 props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
 KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
 consumer.subscribe(Arrays.asList("foo", "bar"));
 while (true) {
     ConsumerRecords<String, String> records = consumer.poll(100);
     for (ConsumerRecord<String, String> record : records)
         System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
 }

https://kafka.apache.org/10/javadoc/?org/apache/kafka/clients/consumer/KafkaConsumer.html

A: If you're using Kafka across machines, you need to configure the listeners correctly. This article explains how: https://rmoff.net/2018/08/02/kafka-listeners-explained/

A:
where i need to give the consumer information in the broker

Brokers don't push messages to consumers, so you wouldn't give the information for the consumer to any broker
Any code that works against a single broker should work for more than one, assuming network settings are configured properly


text:
Q: SQL: Is there a data type for just *letters* only? I need a data type for letters only so then i could test for Erroneous please help

A: Short answer:
No.
Long answer:
This kind of validation logic is best done in your application layer. The database should be responsible for persisting data and validating relationships, nothing more. If you have a validation requirement, chances are it's non-trivial, so you'll need a more expressive language to define it than MySQL stored procedures and triggers can provide.


text:
Q: Quickselect C-implementation returning unexpected values I've implemented the following quick-select algorithm in C using pointers instead of arrays to allow for dynamic memory allocation.
#include <stdio.h>
#include <stdlib.h>

int random(int min, int max)
{
    return rand() % (max + 1 - min) + min;
}

int quickselect(int *a, int l, int k)
{
    int piv = *(a+random(0, l));

    int *less = malloc(sizeof(int)*l), *great = malloc(sizeof(int)*l); //allocate to the max possible size
    int l_len = 0, g_len = 0;

    for (int i = 0; i <= l; i++)
        if (*(a+i) < piv)
            *(less+l_len++) = a[i]; //set "array indice" (dereferneced pointer) and increment array len
        else if (*(a+i) > piv)
            *(great+g_len++) = a[i];

    less = realloc(less, sizeof(int)*l_len); //re-allocate appropiate to the proper size
    great = realloc(great, sizeof(int)*g_len);

    if (k <= l_len)
        return quickselect(less, l_len, k);
    else if (k > l - g_len)
        return quickselect(great, g_len, k - (l - g_len));
    else
        return piv;
}

int main()
{
    int a[] = {5,2,6,3,7,1,0};
    printf("%d", quickselect(a, sizeof(a)/sizeof(*a), 1));
    return 0;
}

When run, I'm getting unexpected values ranging from the negative millions to the positive millions. The randomness of the function makes this hard to debug. Any help?


text:
Q: wrong SET format. Not sure which one I did wrong In short I am trying to do log for an error of my imacros script. If it reach page with a heading Chapter One, means the previous code not working.
TAG POS=1 TYPE=H1 ATTR=TXT:Chapter<SP>One EXTRACT=TXT

SET !VAR2 EVAL("var text=\"{{!EXTRACT}}\"; if(text==\"Chapter One\") {iimPlay("code: ADD !extract {{!NOW:yyyymm}}\nADD !extract {{!COL2}}\nADD !extract Cannot<SP>Access<SP>Page\nSAVEAS TYPE=EXTRACT FOLDER=* FILE=logs.txt");iimPlay("0-DeleteAll.iim");};text;")

The error pointing at this line.
SET !VAR2 EVAL("var text=\"{{!EXTRACT}}\"; if(text==\"Chapter One\") {iimPlay("code: ADD !extract {{!NOW:yyyymm}}\nADD !extract {{!COL2}}\nADD !extract Cannot<SP>Access<SP>Page\nSAVEAS TYPE=EXTRACT FOLDER=* FILE=logs.txt");iimPlay("0-DeleteAll.iim");};text;")

wrong format of SET command, line 43 (Error code: -910)

Not sure which one.
It must be obvious part.

A: The error is the result of an unescaped double-quote character inside the EVAL string, specifically at character position 79 on the line containing the SET command. Since the main parameter to EVAL is a string value, any embedded quotes must be escaped using the \ character, e.g. \".
But more importantly, even if you fix the embedded quote characters, this code will not work because you cannot call iimPlay or any other iMacros scripting interface method inside of EVAL. The Javascript engine used by the EVAL command runs in a different context than the main Javascript engine used by the browser, so calls to iimPlay will result in "iimPlay is not defined" (Error code: -1001).


text:
Q: Rewrite url in Silex PHP Framework I am new in Silex Framework and I have a problem with url rewriting.
Question :
When I type this in browser -> http://localhost/mysite/ It is working and it loads index view.
$app->get('/', function() use($app) {

    return $app['twig']->render('index.twig.html');

});

But when I type http://localhost/mysite/about
$app->get('/about', function() use($app)
{
    return $app['twig']->render('about.twig.html');
});

It gives me following error : The requested URL http://localhost/mysite/about was not found on this server.
If I type this url http://localhost/mysite/index.php/about
This url is working, I don't understand why? I need load this view without this index.php in the url. How can I do it? Thanks in advance.

A: Use this as the contents of your .htaccess file (based on the one provided by the Symfony Standard Edition).
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^index\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]
    RewriteRule .? %{ENV:BASE}/index.php [L]
</IfModule>

A: You are using Silex in a subdirectory:
http://localhost/mysite/index.php/about

therefore you have to adjust the RewriteBase of your .htaccess, try this:
<IfModule mod_rewrite.c>
  Options -MultiViews
  RewriteEngine On
  RewriteBase /mysite
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^ index.php [QSA,L]
</IfModule>

If your server is running Apache >= 2.2.16 you can use the the FallbackResource instead of the above code, try this single line:
FallbackResource /mysite/index.php

A: The problem was in rewrite_mode in Apache. I changed Apache default config -> " AllowOverride All "
http://www.jarrodoberto.com/articles/2011/11/enabling-mod-rewrite-on-ubuntu
And I added .htaccess file. It is working, thanks for everybody!


text:
Q: Fetch Domain name of UPN alias Need a help in LDAP.
I have created an UPN alias testServer.ad for domain demo.com in active directory.
Now how do i fetch domain from UPN alias, from code base.
Any help on this!


text:
Q: Should I Hash via PHP or JavaScript? I am trying to create my own login system and I was wondering what is the best way to hash a password?
Should I just use the function from PHP SQL hash('SHA512' password) or should I use JavaScript for it?
I have already made the system to hash via PHP SQL with SHA512, but if it's more secure with JavaScript I wouldn't mind shifting.
So what I am  asking for is, what is the pros and cons for hashing with JavaScript and for PHP.
And could be cool if you could tell me too what it means to SALT, haven't really understood what it exactly means, and why I should do it.
And yes, I know there are lot's of good login system I can just copy/paste, but this is mostly for understanding how it all works and getting some experience.

A: There's the obvious concern of the user might have JavaScript disabled. This can be "resolved" by having your encoding system prepend something that can't be inserted, such as \x01 or a similar non-printable character. In this way, your server can check if the first character is \x01 and if it isn't then it can apply whatever JavaScript is supposed to do.
So with that issue resolved, you need to also consider that anything in the JavaScript is plainly visible. Any malicious user can easily read your JS source code and find out exactly how the encryption is done. Therefore, you can't rely exclusively on JavaScript to encrypt your data. You must also use server-side code to further secure it.
On the plus side, anything that prevents passwords from being sent as plain text via HTTP is a good thing, however that's what SSL (https://) is for.
So basically, encrypting in JavaScript can be seen as "poor man's SSL", however it doesn't really provide any more security than what the server can do.


text:
Q: app.post on parse heroku server is unauthorized I am trying to post to my server from twilio, but I am getting a 403 error. Basically my parse-heroku serve is rejecting any request from twilio. I am working with TWIMLAPP and masked numbers. I am having trouble posting to a function in my index file when a text goes through. In my TWIMLAPP my message url is https://parseserver.herokuapp.com/parse/index/sms Any help is appreciated. These are the errors in twilio
var app = express();
app.use(require('body-parser').urlencoded());
app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://www.twilio.com');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);

res.setHeader("X-Parse-Master-Key", "xxxxxxx");

res.setHeader("X-Parse-Application-Id", "xxxxxx");

// Pass to next layer of middleware
  next();
});

app.post('/sms', twilio.webhook({ validate: false }), function (req, res) {
  console.log("use-sms")
  from = req.body.From;
  to   = req.body.To;
  body = req.body.Body;

  gatherOutgoingNumber(from, to)
  .then(function (outgoingPhoneNumber) {
    var twiml = new twilio.TwimlResponse();
twiml.message(body, { to: outgoingPhoneNumber });

res.type('text/xml');
res.send(twiml.toString());
  });
});


text:
Q: How many ways can you fill a list with $n$ slots with $m$ letters, $mI've been trying to solve this problem and haven't had any luck. I also haven't been able to find anything online. Clearly there are $m^n$ ways if we do not need to use each one once, but what restriction gets placed if we do? Some must be duplicated, but not all.
EDIT: I'm very tired and massively miswrote this question at first. I explained this in the comments to a response, but it seems to have been deleted now. Sorry to anyone who answered the first question.

A: This is an application of the principle of inclusion-exclusion.  You can start with the answer $m^n$ that you give for the case where there is no requirement that each letter be used at least once.  Since this count includes words that don't use all of the letters, you can subtract these away.  There are $(m-1)^n$ words that omit a particular one of the letters, and there are $m$ possibilities for the omitted letter.  Subtracting these gives $m^n-m(m-1)^n$ words.  But you've subtracted away too much since words that omit exactly two of the letters got subtracted twice.  You can add these back: there are $\binom{m}{2}$ choices for the two omitted letters, and $(m-2)^n$ words you can make with the remaining letters.  This gives $m^n-m(m-1)^n+\binom{m}{2}(m-2)^n$.  But words that omit exactly three of the letters still are not counted correctly...
Continuing in this way, the principle of inclusion-exclusion implies that there are
$$\sum_{j=0}^m(-1)^j\binom{m}{j}(m-j)^n$$
words that use each letter at least once.
This equals $m!\lbrace{n\atop m}\rbrace$, where $\lbrace{n\atop m}\rbrace$ is the Stirling number of the second kind.
Addendum: The Stirling number of the second kind $\lbrace{n\atop m}\rbrace$ is usually defined as the number of partitions of a set of $n$ objects into $m$ non-empty unlabeled subsets.  Think of the $n$ objects as the letter slots.  The partition determines which slots get the same letter.  But since the subsets are unlabeled, there are $m!$ ways of assigning the $m$ letters to the $m$ subsets.

A: Permutations are exactly what you describe.  For example:
"GFEDCBA" is a permutation of "ABCDEFG"
"ABC"     is NOT a permutation of "ABCDEFG"

Thus, the number of rearrangements possible (requiring every letter to be used once) is $n!$

A: It depends on the number of repititions each letter have, you have
to divide $n!$ (which is the number of permutations when all the
letters are considered distinct, even if it the same letter) by ִ$$r_{1}!\cdot...r_{k}!$$
Where $k$ is the number of distinct letters and $r_{1},...,r_{k}$
is the number of repetitions each letter have.
Can you see why ?


text:
Q: Partitioning During Installation, Reinstalling Ubuntu, Backup donwloaded Repositories I am new to Ubuntu and I have just finished installing 13.10 amd64 on my PC. This will replace my Windows 7 as my only OS.
I just want to clarify some issues that've been bugging me. I tried reading posts with the same topics but I just can't wrap my head to it yet.
I partitioned my 80GB drive into:

*

*/root: 30GB (sorry for the confusion, I actually meant /)

*/home: 40GB

*/var : 3GB

*swap : 4GB (2GB of mem)

Please correct me if I'm wrong about these:

*

*All of the users' documents are saved in their respective folders in /home. But say I want to clean install (format) Ubuntu, I don't need to make backups of /home and /var as they are on separate partitions. But when re-installing, do I just choose /root and format and it will recognize all the partitions (not making another /home and /var inside /root)?

*Downloaded packages (from all the repositories) and all their dependencies are saved in /var. So after re-installing on the same PC (assuming I'm offline), it will just use the latest updates in /var if I choose to update? And if all the installed apps and their dependents are all in there, all I need to do is re-install them without encountering errors? I have also read that you can back them up using aptoncd and then adding the DVD to the sources. So if I download all the high ranking apps using Synaptic, could I then have an all-in-one DVD installer?

*30GB for / is excessive because the bulk of files will either be in /home (personal, downloads, music, videos) or /var (updates, packages, installed apps)?
Please excuse me for asking such a question but I really want to explore and learn more.

A: You seem to have the right ideas about some things, but I'm not sure about the packages.
As for /root, you've got it wrong. The Filesystem Hierarchy Standard (FHS) has a good article at Wikipedia.
/ is referred to as root, but you've put /root on a separate partition(probably confusing the two; there's really no need to put /root separately.). Also, I see no need to put /var on a separate partition.
In case it was unclear, / is your main filesystem - your root partition. If during installation you make another partition to be used at /home, as you have, then after installation when you browse to /home from / it will be like any other folder, but it will actually be kept on another partition.
If I were you, I would install with 2 partitions (not including swap): / and /home.
If you've got an SSD and a HDD, as I do, put the above on your HDD and put /boot on your SSD for faster boot times.
BTW, this is less a question for Ask Ubuntu and more a discussion. I suggest taking it to ubuntuforums.org.

A: Re-installation scenario
You re-installation scenario deserves a bit of further explanation. Usually I install only once and don't need to reinstall as I did when I was running Windows XP years ago, because the system felt sluggish or it became a abnormal esoteric habit to maintain performance by doing regular nLite installs. (It was not only XP's fault, but also the performance characteristics of HDDs.)
Re-installation of the same distribution release will become more and more unlikely as you get to know your way around. Rather than worrying about re-installation you should plan for backups and know how to restore them. With that in place, even release upgrades, where almost every package is new and things may break you're save and can rollback until bugs are fixed.
However, as I found out when writing the answer to this question: Reinstalling Ubuntu without formatting partition - what folders are deleted?
May 27 21:21:02 ubuntu clear_partitions: Removing var/backups from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/cache from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/crash from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/games from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/lib from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/lock from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/log from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/mail from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/not-formatted from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/opt from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/run from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/spool from / (/dev/sda1).
May 27 21:21:02 ubuntu clear_partitions: Removing var/tmp from / (/dev/sda1).

The installer will clean a lot of folders in /var (and others), among them /var/cache which contains /var/cache/apt where the downloaded packages are stored. You wouldn't want to mount you var partition during your re-install scenario.
Folders with huge diskusage
The biggest folder on a typical installation apart /home (depending on if your users store files or do everything in a webbrowser) should be /usr, because that is where most of the files from the compressed packages are getting extracted to. If you don't clean your package cache, as you intend to do, /usr may be twice as big as /var/cache/apt or even bigger.
If you install a lot of proprietary packages/applications /opt may also grow in size. Steam on the other hand let's you choose where to install but uses /home/$USER/.local/share/Steam by default.


text:
Q: I want to plot scatter plot by every 2 columns ,meet error as Error : non-numeric argument to binary operator code as below:
Raw=mtcars
cn=colnames(Raw)
sapply(1:7,function(i)ggplot(data=Raw,aes(x=Raw[,i],y=Raw[,i+1])+
                                            geom_line()+geom_point(size=4,shape=20)+
                                            labs(x='totality_accuray',y=cn[i]))
)

can help out what's issue to get this error reminder:Error in aes(x = Raw[, i], y = Raw[, i + 1]) + geom_line() :
  non-numeric argument to binary operator

A: Custom plotting function that take two named variables:
plotFn <- function(x,y, df){
           ggplot(df,aes_string(x,y)) +
           geom_line() +
           geom_point(size=4,shape=20)
          }

plotFn("disp", "cyl", mtcars)

Grabbing a list of variables for x and y axis:
Raw <- mtcars
cn <- colnames(Raw)

arg <- lapply(1:(ncol(Raw)-1), function(x) list(x = cn[x],
                                    y = cn[x+1]))

Plotting 10 plots:
lapply(arg, function(i) plotFn(i[["x"]], i[["y"]], Raw))


text:
Q: error Performing erlang migration to another node I have 2 nodes - rabbit2 and rabbit3. Everything is working fine until I start cluster then I did the command:
scp -r rabbit2:/var/lib/rabbitmq/.erlang.cookie /var/lib/rabbitmq/.erlang.cookie

And after successfully transferring the failed nodes:


text:
Q: MySqli Object properties are null I am stumbling into the following issue.. I am trying to retrieve some information from my DB using Ajax, however, my query is failing for some reason, when trying to debug it by analyzing the information within the mysqli_object, all the properties are null:
I printed the contents of the object of the console:
affected_rows:null
client_info:null
client_version:null
connect_errno:null
connect_error:null
errno:null
error:null
error_list:null
field_count:null
host_info:null
info:null
insert_id:null
protocol_version:null
server_info:null
server_version:null
sqlstate:null
stat:null
thread_id:null
warning_count:null

Why can this happen?
Here's my Ajax call:
$('#npClientName').keyup(function(){
  var txt = $(this).val();
  if (txt == "") {
    $('#npClientList').fadeOut();
    return false;
  }

  $.ajax({
    method: 'POST',
    url: '/fitcoControl/Resources/PHP/Clientes/fetchPopupClientList.php',
    data:{txt: txt},
    success: function(result){
      rsp = JSON.parse(result);
      console.log(rsp);

      if (rsp.code != "1") {
        $('#npClientList').html("
Hubo un error al cargar la lista de clientes...
");
        console.warn("Error en el query: " + rsp.response);
      } else {
        $('#npClientList').html(rsp.response);
      }
      $('#npClientList').fadeIn();
      clientSelector();
    },
    error: function(exception){
      console.error(exception);
    }
  });
});

And here's my PHP code:
$root = $_SERVER['DOCUMENT_ROOT'];
$data = array(
  'code'=>"",
  'response'=>""
);

$txt = "'%" . $_POST['txt'] . "%'";

require $root . "/fitcoControl/Resources/PHP/DataBases/Conexion.php";
$query = "SELECT * FROM ct_cliente";

$stmt = $conn->prepare($query);
//$stmt->bind_param('s', $txt);
$stmt->execute();

$resultados = $stmt->get_result();
$num_rows = $stmt->num_rows;

if (false) {
  $data['code'] = 2;
  //$data['response'] = $num_rows;
} else {
  $data['code'] = 1;
  $data['system'] = $conn;
  while ($a = mysqli_fetch_assoc($resultados)) {
    $idCliente = $a['pk_cliente'];
    $nc = $a['nombreCliente'];
    $data['response'] .= "
$nc
";
  }
}

$json = json_encode($data);

echo $json;

Ideas?


text:
Q: Problem moving a MySQL data directory to a new drive I have an EC2 instance and am trying to move the mysql data directory from the default drive to another EBS volume. I moved the mysql directory in /var/lib/mysql to the new destination and then modified the my.cnf file to point the data directory to the new location. I then tried to restart mysql I get the following message.
MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED]

I am running the default distribution of linux that comes with a new EC2 instance. Below are details to the my.cnf file and mysqld.log. Any suggestions on what I may be doing wrong?
my.cnf
[mysqld]
#datadir=/var/lib/mysql
datadir=/root/appfinder/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

Set permissions for folder
chmod -R 777 /root/appfinder/mysql

mysqld.log
110616 18:37:53 mysqld_safe Starting mysqld daemon with databases from /root/appfinder/mysql
/usr/libexec/mysqld: Table 'plugin' is read only
110616 18:37:53 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
InnoDB: Log scan progressed past the checkpoint lsn 0 37356
110616 18:37:53  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
InnoDB: Doing recovery: scanned up to log sequence number 0 44233
110616 18:37:53  InnoDB: Starting an apply batch of log records to the database...
InnoDB: Progress in percents: 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66$
InnoDB: Apply batch completed
110616 18:37:53  InnoDB: Started; log sequence number 0 44233
5110616 18:37:53 [ERROR] Fatal error: Can't open and lock privilege tables: Table 'host' is read only
110616 18:37:53 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

A: I tried to remount my EBS volumes to /myFolder rather than /root/myFolder. This seems to have corrected the permission issues.

A: /root/appfinder/mysql director must be owner mysql. For this, chown mysql:mysql
/root/appfinder/mysql and chown -R mysql:mysql /root/appfinder/mysql/.
All data files for mysql must be owner mysql.

A: I had similar problem.
Here are my steps that did work on Ubuntu 12.04 Lts:
Want to move datafiles from /var/lib/mysql to /newdir_path/newdir

*

*sudo mysql stop

*sudo rsync -av /var/lib/mysql /newdir_path/newdir

*sudo gedit /etc/mysql/my.cnf, change datadir to /newdir_path/newdir

*sudo gedit /etc/apparmor.d/usr.sbin.mysqld, change:

*
          instead of:

*

*/var/lib/mysql/ r,

*/var/lib/mysql/** /rwk

          enter:

*

*/newdir_path/newdir/ r,

*/newdir_path/newdir/** rwk,

*sudo /etc/init.d/apparmor restart

*(!!!) sudo chown mysql:mysql /newdir_path

*sudo start mysql


text:
Q: Литература по WEB-программированию Образование не из IT сферы. Решил учится самостоятельно.  с основ HTML и CSS
учил по книге - Квинт И. "HTML, XHTML и CSS на 100 %", на данный момент начал учить JavaScript.

Интересует литература по JavaScript и другим языкам и технологиям WEB-программирования. Подскажите в какой последовательности что учить и что читать. (просьба не давать много книг по одному и тому же на выбор - посоветуйте лучше одну которую вы считаете наиболее успешной) План по обучению который я составил для себя:

*

*HTML 4.01;

*CSS 2;

*SSi;

*JavaScript;

*ООП;

*jQuery;

*JSon;

*AJAX;

*БД (MySQL);

*PHP 5.3;

*Zend Framework;

*Java.

A: PHP

*

*Моей первой книжкой по PHP, которая до сих пор остаётся моей настольной, не смотря на то, что местами устарела и потёрлась - была PHP : Карманный Справочник Кристиана Уэнца от  изд-ва "Вильямс".

*В качестве глупой настольной книги, где можно чтонить посмотреть, я использую книгу Колисниченко о разработке веб-приложений. Не ждите от неё многого, но она хороша.

*Книга Мэтта Зандстры PHP. Объекты, шаблоны и методики программирования весьма хороша для погружения глубже в ооп.

*Книга Питера Ловейна "Объектно-ориентированное программирование на PHP5" - весьма хороша своими налядными примерами. Она даёт чёткое понимание удобства ООП.

A: *

*List of freely available programming books

*PHP tutorial that is security-, accuracy- and maintainability-conscious?

*Книги по JavaScript, HTML5, Node.JS

*Материал по PHP

*Поиск профессиональной литературы

*Книги по HTML5 и CSS3

A: *

*Практика

*Всё что непонятно - google / yandex

Просто Интернет технологии настолько быстро развиваются, что из книг можешь взять только основы. Всё остальное будет не актуально. Поэтому всю информацию в IT лучше брать с просторов интернета - с форумов, с сайтов веб дизайна и т.д. (ИМХО).
Единственное что, ООП можете почитать книжку, чтобы стать ближе к IT, а все остальное в процессе разработки чего-либо. :)
A: http://www.codecademy.com/ онлайн обучение


text:
Q: Sample DateTime Format given Regex Pattern I've reviewed the Regex documentation online but can't seem to make much progress on this.
I'm trying to understand what the format of a DateTime is given a specific regex pattern.
So what would a sample DateTime string look like that followed this regex pattern:
[1-9][0-9]{3}\-.+T[^\.]+(Z|[\+\-].+)

Currently I'm passing in the following DateTime:
2016-03-10T23:34:32.1898018Z

to a web service that validates the contents based on the regex described above (which is failing).
Any help would be appreciated.

A: It looks like if you remove your milliseconds from your test input, it would match. Therefore, if you want that format to match, you could change the regex to read
[1-9][0-9]{3}\-[0-1]?[1-9]\-[0-3]?[0-9]+T.+[\.][0-9]+(Z|[\+\-].+)

A: The regex you mention can parse those kinds of dates :

*

*2009-06-15T13:45:30-07:00 (UTC-7 timezone)

*2009-06-15T13:45:30+07:00 (UTC+7 timezone)

*2009-06-15T13:45:30Z ("Z" for UTC timezone)

if you want to parse this date 2016-03-10T23:34:32.1898018Z (with milliseconds), change the regexp to :
[1-9][0-9]{3}\-.+T[^\.]+\.[0-9]+(Z|[\+\-].+)


text:
Q: Is this javascript snippet considered bad? I like making my code as succinct as possible but maybe this is unreadable?
var filters = {};
function addFilter(type, name) {
  filters[type] && filters[type].push(name) || ( filters[type] = [name] );
}

or even (as pointed out in answers):
var filters = {};
function addFilter(type, name) {
  filters[type] ? filters[type].push(name) : ( filters[type] = [name] );
}

-edit--
Not unreadable but maybe bad style? The alternative would have been to write out
var filters = {};
function addFilter(type, name) {
  if (!filters[type]) {
    filters[type]= [];
  }
  filters[type].push(name);
}

A: Languages have idioms and patterns for good reasons. In particular, Javascript has the if/else statement that is designed precisely for this purpose. Code should be written so that it is easy to read, because in the future it will be read far more often than it is written.
I would not accept the above "succinct" code in a code review.

A: You could at least use a ternary:
filters[type] ? filters[type].push(name) : ( filters[type] = [name] );

Alternatively, you could use the expanded version of your code, but a little more succinctly:
if ( ! filters[type] ) filters[type] = [];

filters[type].push(name);

This results in two statement being run when the array is first created, but I find this way more readable.

A: I would say unnecessarily unreadable. It also depends on what you are working on and who you are working for. If you are sure that you are the only person going to be supporting this application, then maybe this would be fine.

A: Is readable but also misleading. What i expect from function called addFilter is to add some filter or if such a exists i should get exception or false or -1 (something that tells me its duplicated)

A: You're missing a ; after var filters = {} and also, the second form is way better because it's easier for a new coder to understand it stright away (or yourself in the future).
You could use your first form and comment it, but as Sammy Larbi said in Common Excuses Used To Comment Code, if your feel your code is too complex to understand without comments, your code is probably just bad.

A: Using && and || might be a little confusing to Javascript guys who're more familiar with ternaries.
function addFilter(type,name) {
    filters[type] ? filters[type].push(name) : filters[type] = [name];
}


text:
Q: Any reliable method to rotate uploaded pictures in the right direction? Some times ago i wrote a method to read out the EXIF-data from a uploaded picture in a online-community. After i got the orientation from the picture, i rotated the file in the right direction. Only a short part from my script:
public function rotate($sourceFile, $targetFile, $orienation)
{
    switch($orienation){
        case 3: $degrees = '180'; break;
        case 6: $degrees = '90'; break;
        case 8: $degrees = '270'; break;
        default: $degrees = '0';
    }

    $file = $sourceFile . DS . $targetFile;
    $rotate = GlobalConfig::BIN_IMAGICK_CONVERT . ' -rotate ' . $degrees . ' ' . $file . ' ' . $file;
    exec($rotate);
}

My script is working. But my question is, how other big guys like
facebook, handle the rotation from uploaded pictures? Because my solution is certainly not the best.

A: I believe a better approach would be to use the GD Library, the code goes something like this
// input
$image = 'myfile.jpg';

//read orientation information from EXIF

$exif = exif_read_data($filename);
$ort = $exif['IFD0']['Orientation'];

//then based on $ort you can determine the rotation degree,
//check the link below for more info

//rotation degree
$degrees = 180;

// create "image object"
$source = imagecreatefromjpeg($image) ;

// rotate
$rotate = imagerotate($source, $degrees, 0) ;

// set the header
header('Content-type: image/jpeg') ;

// output
imagejpeg($rotate) ;

more info: Exif Orientation Tag


text:
Q: how does python class specical method work? I have a Cell class
class Cell :
    def __init__(self,char):
        self.char=char
        self.image='_'

    def __str__(self):
        return self.image

    def __eq__(self,other):
        return self.image == other.image

    def __ne__(self,other):
        return not self.image == other.image

then I have two Cell objects a and b, why I can use expression like "if a != b:" to compare these two object. How does b get inside of a and call the eq method to make the comparison

A: b doesn't get inside.  When an operator is used, Python first looks for the magic method on the left-hand argument.  If the appropriate magic method is defined there, it is called.  If it doesn't return NotImplemented, then that's the result.  If the method doesn't exist (or it returns NotImplemented), then the magic method is called on the right-hand argument.  (For arithmetic operators, the right-hand arguments gets a separate method, __radd__ being the right-hand version pf __add__, __rsub__ for __sub__, etc.).
So in your version, it calls __ne__ on a and that's it.  The magic method is never called on b.
This behavior is described in the documentation.

A: Saying if a == b is equivalent to if a.__eq__(b).
Likewise, saying if a != b is really if a.__ne__(b). Both methods return boolean values.
Each class inherits default special methods for comparing equality and inequality, but these can be overridden if explicitly defined.

A: The other answers are the proper answer.
I just wanted to mention that __ne__ has a bug related to precedence. It should be defined as:
return not (self.image == other.image)
Which is best expressed as:
return not (self == other)
Don't Repeat Yourself.


text:
Q: Batch mv or rename in bash script - append date as a suffix After much searching and trial and error, I'm unable to do a batch mv or rename on a directory of files.  What I'd like to do is move or rename all files in a directory so that the mv'd or renamed file has $date (+ '%Y%d%m') added to the original suffix.
All the original files have unique prefixes but are either .xml or .txt so I'd like to go from org_prefix.org_suffix -> org_prefix.org_suffix.DATE
I've tried this:
$ mv /directory/* /directory/*$(date (+ '%Y%m%d')

but always get /directory/*.actualdate' is not a directory error.
I've tried this:
$ for f in *; do mv $ $f.$(date +'_%m%d%y'); done

but I get mv: cannot stat '$'; No such file or directory
Lastly, I've even tried this:
$ rename 's/*/.test/' *

just to see if I could change all the files to org_prefix.test but nothing happens (no errors, nada, zip)
Any help greatly appreciated.

A: The proper way to loop through files (and e.g., print their name) in the current directory is:
for file in *; do
    echo "$file"
done

How will you append the date? like so, of course:
for file in *; do
    echo "$file.$(date +%Y%m%d)"
done

And how are you going to do the move? like so, of course:
for file in *; do
    mv -nv -- "$file" "$file.$(date +%Y%m%d)"
done

I've added:

*

*-v so that mv be verbose (I like to know what's happening and it always impresses my little sister to watch all these lines flowing on the screen).

*-n so as to no overwrite an otherwise existing file. Safety first.

*-- just in case a file name starts with a hyphen: without --, mv would confuse with an option. Safety first.

If you just want to look through the files with extension .banana, replace the for with:
for file in *.banana; do

of for files that contain the word banana:
for file in *banana*; do

and so on.
Keep up with the bananas!

A: $ mv /directory/* /directory/*$(date (+ '%Y%m%d')

This does not work, because the * is expanded to a list of all files, so after the expansion the command will be something like:
mv /directory/file1 /directory/file2 /directory/file3 /directory/file1_date /directory/file1_date ...

So you have specified many destinations, but the syntax for mv allows only one single destination.
for f in *; do mv $ $f.$(date +'_%m%d%y'); done

Here you forgot the f after the $, that's why you get the error message.
for f in *; do mv $f $f.$(date +'%m%d%y'); done

I think this should work now, but don't forget to quote all the variables!
Finally:
for f in *; do mv "$f" "$f.$(date +'%m%d%y')"; done

Edit: When there are characters directly after a variable, it's good practice to use {} to make clear that they are not part of the variable name:
for f in *; do mv "$f" "${f}.$(date +'%m%d%y')"; done


text:
Q: java tesseract error in linux "Unable to load library 'tesseract': libtesseract.so" I am using tess4J ocr library in eclipse and is working fine in my windows. But when i want to run that java program in linux it is giving an error "Unable to load library 'tesseract': libtesseract.so: cannot open shared object file: No such file or directory".
I dont have any permissions on linux  to install the tesseract or any other software . Just i can use the jar files and run the java program by calling the shell script.Please  help me on this . As I am thinking my problem will be solved by getting libtesseract.so file or help me how to get libtesseract.so in windows so that i will use that in linux . Please help and thank in advance

A: It is enough to install Tesseract for Linux using command:
sudo apt-get install tesseract-ocr

now you can check tesseract version, using command:
tesseract -v

Please note, that for Tesseract 3.03 you can use Tess4j version 2.0.
Another version may give you errors because of incompatibility.
You can get more info about different version compatibility in Change Log, or here.

A: In My case (centos) I copied all the files (having lept or teesseract keyword in file name) from folder

/usr/local/lib

to folder

/usr/lib64

and it solved my problem

A: On Linux, Tess4J calls on Tesseract native library libtesseract.so to work. If you can't build or install Tesseract on Linux, you're in tough luck. Maybe if you can cross-compile to a .so on Windows using Cygwin or Mingw.

A: You have to set -Djava.library.path so the file can be found or tweak your standard library path to include the location of the .so in .bashrc by extending system's LD_LIBRARY_PATH

A: You need to install without root and specify the path of your libtesseract.so
Install elsewhere / without root
Tesseract can be configured to install anywhere, which makes it possible to install it without root access.
To install it in $HOME/local:
./autogen.sh
./configure --prefix=$HOME/local/
make install
To install it in $HOME/local using Leptonica libraries also installed in $HOME/local:
./autogen.sh
LIBLEPT_HEADERSDIR=$HOME/local/include
 ./configure \ --prefix=$HOME/local/ --with-extra-libraries=$HOME/local/lib
make install

A: I also had same problem. Tesseract libraries was aslo present under /usr/local/lib directory.Still I was getting this error. Actually this is linking problem. so you have to provide the /usr/local/lib path to the resolver path in the /etc/ld.so.conf.d/libc.conf file. make entry of path in this file or you can create any new conf file in the same dir.


text:
Q: Multiple charts in SAP Business Objects Webi? Has anyone tried dynamic charts (multiple charts based on data available)  in SAP Business Objects WebI?
I did try the sections which is available in WebI, However, I need to place charts side-by-side while sections show charts one below other

A: You can most certainly place charts side-by-side. I created a report based on the eFashion universe returning Year, Quantity sold, and Sales revenue. I have one table displaying the raw data and three side-by-side charts.


text:
Q: How to get a variable from JavaScript to ColdFusion I'm currently working on one issue and I need some help. I'm working on HTML code that fills in special machine labels. It is a kind of web page on where people fill in the number of lines and text size, then enter the text of the lines they want the resulting table to contain in each line.
I need advice on how to save JavaScript variable to cf variable. We use ColdFusion to link the code to DB.
Here is a small sample of the problem.
for(let a = 1; a <= g_rowCounter; a++){
    text = getVal('i_row-input_' + a);
    g_texts.push(text);
}

Is there anyone who would encounter a similar problem or know how to solve it?
Thank you for all the answers.
Here is for reference whole code to lock at the problem.

        <meta charset="UTF-8">
        <title>Stitek</title>

      <cfform>
        Zvol počet řádků štítku

        <cfselect name="srows" id="i_row-count" onchange="vygenerujInputy()">
            <option value="0" name="m00" size="50" maxlength="30" type="text">0
            <option value="1" name="m01" size="50" maxlength="30" type="text">1
            <option value="2" name="m02" size="50" maxlength="30" type="text">2
            <option value="3" name="m03" size="50" maxlength="30" type="text">3
            <option value="4" name="m04" size="50" maxlength="30" type="text">4
            <option value="5" name="m05" size="50" maxlength="30" type="text">5
        </cfselect>

        velikost textu (milimetry)  <cfinput type="number" name="quantity" id="i_velikost-textu" min="6" max="75" range = "6,75" validate = "integer">

      </cfform>

        <button onclick="vygenerujTabulku()" class="c_form-button">Náhled štítku</button>

      <cfform>

        <cfset pr1 = "input1">
        <cfset pr2 = "input2">
        <cfset pr3 = "input3">
        <cfset pr4 = "input4">
        <cfset pr5 = "input5">
      <cfset pr6 = "vyska">
      <cfset pr7 = "sirka">

      <cfoutput>#pr1#
#pr2#
#pr3#
#pr4#
#pr5#
#pr6#
#pr7#
</cfoutput>

        <cfselect name="swidth" id="i_sirka-ramecku" onchange="vygenerujTabulku()">
        </cfselect>
      </cfform>

A: As stated in the comments, in order to use the values in CF, the form data must be submitted to the CF server via an http request (ajax, basic form submit, etc..).
For example, perform a simple form post:

*

*Add method="POST" and a submit button to the form

*Assign a name to the label fields. Otherwise, their values won't be sent to the server.

 // Dynamically assign the names "label_1", "label_2", etc..
 function createRowInput(number, defText){
     // ...
     input.setAttribute('name', 'label_' + number);
     // ...
 }

 <form method="post" action="TheReceivingPageHere.cfm">
     Zvol počet řádků štítku

     ... more code ....

     <input type="submit" value="Odeslat hodnoty">
 </form>

Dump the form scope on the receiving page, and you'll see something like this when the form is submitted:

Use the number of fields, i.e. form.srows, to extract the label values dynamically
<cfparam name="form.sRows" default="0">

<cfloop from="1" to="#form.srows#" index="r">

    <cfset variables.labelValue = form["label_"& r]>

    ... do something with values...
</cfloop>


text:
Q: ArgumentError: wrong number of arguments when trying to build from Heroku I'm trying to build my application in Heroku and I'm getting this error on the logs:
Running: rake assets:precompile
       rake aborted!
       ArgumentError: wrong number of arguments (given 3, expected 2)
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/type/adapter_specific_registry.rb:9:in `add_modifier'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/type.rb:27:in `add_modifier'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/connection_adapters/postgresql_adapter.rb:834:in `<class:PostgreSQLAdapter>'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/connection_adapters/postgresql_adapter.rb:72:in `<module:ConnectionAdapters>'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/connection_adapters/postgresql_adapter.rb:44:in `<module:ActiveRecord>'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/connection_adapters/postgresql_adapter.rb:22:in `<main>'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/connection_adapters/connection_specification.rb:191:in `spec'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:950:in `establish_connection'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/connection_handling.rb:60:in `establish_connection'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/railtie.rb:136:in `block (2 levels) in <class:Railtie>'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/lazy_load_hooks.rb:71:in `instance_eval'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/lazy_load_hooks.rb:71:in `block in execute_hook'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/lazy_load_hooks.rb:62:in `with_execution_control'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/lazy_load_hooks.rb:67:in `execute_hook'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/lazy_load_hooks.rb:43:in `block in on_load'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/lazy_load_hooks.rb:42:in `each'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/lazy_load_hooks.rb:42:in `on_load'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activerecord-5.2.0/lib/active_record/railtie.rb:132:in `block in <class:Railtie>'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/railties-5.2.0/lib/rails/initializable.rb:32:in `instance_exec'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/railties-5.2.0/lib/rails/initializable.rb:32:in `run'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/railties-5.2.0/lib/rails/initializable.rb:61:in `block in run_initializers'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/railties-5.2.0/lib/rails/initializable.rb:60:in `run_initializers'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/railties-5.2.0/lib/rails/application.rb:361:in `initialize!'
       /tmp/build_575f45fc/config/environment.rb:5:in `<main>'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/railties-5.2.0/lib/rails/application.rb:337:in `require_environment!'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/railties-5.2.0/lib/rails/application.rb:520:in `block in run_tasks_blocks'
       /tmp/build_575f45fc/vendor/bundle/ruby/3.0.0/gems/sprockets-rails-3.4.2/lib/sprockets/rails/task.rb:61:in `block (2 levels) in define'

Here is the Gemfile:
source 'https://rubygems.org'

# rails
gem 'rails', '5.2.0'

gem 'jquery-rails'

gem 'pg'

# gem 'mini_racer'

gem 'puma'
gem "puma_worker_killer"

gem 'net-ssh'
gem 'sprockets'

gem 'sys-proctable'
gem 'tzinfo-data'

gem 'bootsnap', '>= 1.4.2'

# error tracking
gem 'rollbar'

# assets
gem 'uglifier', '>= 1.3.0'

# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks

# -------------------------------
gem 'sass-rails', '>= 6'
gem 'slim-rails'
# -------------------------------

gem 'coffee-rails'
gem 'font-awesome-sass', '~> 6.0.0'

# forms
gem 'simple_form'
gem 'link_to_add_fields'

# meta tags
gem 'meta-tags'

# Parse xls files
gem "roo"

# Create pdf grid
gem 'prawn', '~> 2.1'
gem 'prawn-templates', '~> 0.0.4'

# Create Carrousel
gem "jquery-slick-rails"
# spring speeds up development by keeping your application running in the background. Read more: https://github.com/jonleighton/spring
group :development do
  gem 'spring', '~> 3.1.1'
  gem 'better_errors'
  gem 'binding_of_caller'
  gem 'byebug'
  gem "rails-erd"
  gem "bullet"
  gem "letter_opener"
  gem "aws-sdk"
  gem "rb-readline"
  gem 'rack-mini-profiler', require: false
end

# authentication
gem 'devise', git: 'https://github.com/heartcombo/devise', branch: 'main'

# access levels
gem 'cancancan'

# friendly urls
gem 'friendly_id'

# custom validation for urls
gem 'validate_url'

# keeps session in active record so session can be bigger than 4kb
gem 'activerecord-session_store'

gem 'kaminari'

group :test, :development do
  # specs
  gem 'rspec-rails'

  # interactive debug
  # gem 'pry-rails'

  # javascript specs
  gem 'jasmine-rails'

  # jquery for javascript specs
  gem 'jasmine-jquery-rails'
end

group :test do

  # test coverage
  gem 'simplecov'

  # feature specs
  gem 'launchy'
end

gem 'ckeditor', "~> 4.2.4"
# gem 'redactor-rails'
gem 'sitemap_generator'

gem 'business_time'
gem 'holidays'

gem 'mini_magick'
gem 'carrierwave'
gem 'carrierwave-aws'
gem 'premailer-rails'
gem 'remotipart'
gem 'inline_svg'

gem 'wrgem'

gem 'rails_12factor', group: :production
gem 'rufus-scheduler'
gem 'correios-frete'
gem 'correios-cep'
gem 'rubyzip',  "~> 0.9.9", :require => ['zip/zip', 'zip/zipfilesystem']
gem 'sidekiq'

gem 'raygun4ruby'

gem 'memcachier'
gem 'dalli'

gem 'tinyerp_ruby'

gem 'ransack', '~> 2.1'
gem 'rmagick'

gem 'rack-tracker'

gem "jquery_context_menu-rails"

gem 'rails_autoscale_agent'

gem 'heroku-deflater', :group => :production

gem 'canonical-rails', github: 'jumph4x/canonical-rails'

gem 'omniauth'
gem 'omniauth-facebook'
gem 'omniauth-google-oauth2'
gem 'facebookbusiness', '~> 0.11.0.0'

gem 'axlsx'

# performance analytics
gem 'newrelic_rpm', '~> 6.7.0.359'

# gem 'rqrcode'

gem "figaro"

gem 'rest-client'
gem 'pagarme'

gem "paranoia", "~> 2.2"

gem 'chartkick'
gem 'groupdate'

gem 'recaptcha'

gem 'nokogiri'

# Use react on rails
gem 'webpacker'
gem 'react-rails'

# -------
# API

# Auth
gem 'jwt'
gem 'simple_command'

# Serializers
gem 'fast_jsonapi'
gem 'active_model_serializers', '~> 0.10.10'
gem 'active_model_serializers-jsonapi_embedded_records_deserializer'

# Clone active_record objects
gem 'amoeba'

# QR code
gem 'rqrcode'
gem 'mimemagic', '~> 0.3.6'

gem 'lazyload-rails'

gem 'active_link_to'

gem 'paper_trail'
gem 'active-campaign-rails'

gem 'dotenv-rails', groups: [:development, :test]

gem 'sprockets_better_errors', groups: [:development, :test]

I have tried downgrading rails version, changing ransack version but nothing works, I still cannot build the project, It works fine on my localhost, but Heroku just won't build.

A: I have found the answer. For those who are getting this, you must specify the rails version to '2.5.3' in the Gemfile:
source 'https://rubygems.org'

ruby "2.5.3"


text:
Q: Spring-mvc + Spring-Security + Thymeleaf - Error Resolving Template I'm following a simple online tutorial for building a Spring + Spring Security + Thymeleaf + Maven project and I'm getting the following error:
[ERROR] [tomcat-http--4 02:00:16] (TemplateEngine.java:process:1085) [THYMELEAF][tomcat-http--4] Exception processing template "login": Error resolving template "login", template might not exist or might not be accessible by any of the configured Template Resolvers
Feb 24, 2015 2:00:16 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/hub] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "login", template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "login", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1228)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1011)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:955)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:146)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:279)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

It looks like for some reason it is not resolving the login page but even though the login page is at the correct location. If I point to the users.html page that page loads and there are no errors. Must be something very simple I'm missing out on. Can someone please assist?
The following are my config classes:
public class ApplicationInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    //Load application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(ApplicationContext.class);
    rootContext.setDisplayName("hub");

    //Context loader listener
    servletContext.addListener(new ContextLoaderListener(rootContext));

    //Dispatcher servlet
    ServletRegistration.Dynamic dispatcher =
            servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

}

ApplicationContext class:
@Configuration
@ComponentScan(basePackages = {"com.motodoc.hub.*"})
@EnableWebMvc
@Import({SpringDataConfig.class, ThymeleafConfig.class, SecurityConfig.class})
@ImportResource("classpath:trace-context.xml")
@PropertySource("classpath:spring.properties")
public class ApplicationContext extends WebMvcConfigurerAdapter {

// Maps resources path to webapp/resources
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

// Only needed if we are using @Value and ${...} when referencing properties
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    PropertySourcesPlaceholderConfigurer propertySources = new PropertySourcesPlaceholderConfigurer();
    Resource[] resources = new ClassPathResource[] {
            new ClassPathResource("spring.properties") };
    propertySources.setLocations(resources);
    propertySources.setIgnoreUnresolvablePlaceholders(true);
    return propertySources;
}

// Provides internationalization of messages
@Bean
public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource source = new ResourceBundleMessageSource();
    source.setBasename("messages");
    return source;
}
}

ThymeleafConfig class:
@Configuration
public class ThymeleafConfig {

@Bean
public ServletContextTemplateResolver templateResolver() {
    ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    resolver.setOrder(1);
    return resolver;
}

@Bean
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver());
    return engine;
}

@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(templateEngine());
    return resolver;
}
}

SpringSecurityConfig class:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  auth.inMemoryAuthentication().withUser("mkyong").password("123456").roles("USER");
  auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
  auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**");
  }

@Override
protected void configure( HttpSecurity http ) throws Exception
{
    http
        .authorizeRequests()
        .antMatchers("/**").authenticated()
        .antMatchers("/resources/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .loginPage("/login")
        .permitAll()
        .defaultSuccessUrl("/users")
        //.failureUrl("/login.html?authfailed=true")
        .and()
    .logout()
        .invalidateHttpSession(true)
        .logoutUrl("/logout")
        .deleteCookies("JSESSIONID")
        .logoutSuccessUrl("/");
}
}

SecurityInit class:
public class SecurityInit extends AbstractSecurityWebApplicationInitializer {

}

A: Maybe you have a conflict with the resolvers of thymeleaf and springSecurity. You have set your loginPage configuration as 'login' and thymeleaf is expecting 'login.html'. Have you tried to change .loginPage("/login") for .loginPage("/login.html") ?

A: Just remove the suffix code from config.
resolver.setSuffix(".html");

A: In the ThymeleafProperties class that the default prefix for views is classpath:/templates/ and the default suffix is .html. So change your html to src/main/resources/templates/login.html, as shown in the following image


text:
Q: Is there any way by which I can save files to icloud in Cordova I'm using cordova-sqlite-plugin, according to its documentation, the database file will be backed up by iCloud if I put it to a right directory. But it's not working. I thought perhaps iCloud dosen't support sqlite file, so I dump the data into a sql file, and put it to Libary/Cloud directory, still not working.

A: Try adding this to your config.xml.
<preference name="BackupWebStorage" value="cloud" />


text:
Q: Reading Serial Port in Perl I'm bit tired of reading serial port, using Perl first of all Perl is not my primary development tool, I'm from PHP background.
So please guide me in a right way. my intention is to read the data from a weight machine to a web page, I already did a lot of research on this topic.
The browser app cannot read serial port data directly so I choose the user end machine can be installed with a server (Apache) and do the task with PHP and web application can read the result using an Ajax call to localhost url the idea is working great on Linux machines but on windows PC it stuck.
I understand PHP can't read data from serial port in windows like Linux so I choose Perl to do the stuff. I did some search an got few codes and last 8 hours I'm fighting with that :(
#!E:\xampp\perl\bin\perl.exe
# The above line is perl execution path in xampp
# The below line tells the browser, that this script will send html content.
# If you miss this line then it will show "malformed header from script" error.

  print "Content-type: text/plain\n\n";
  # use strict; use warnings;
  use Win32;
  require 5.003;
  use Win32::SerialPort qw( :STAT 0.19 );
  print "here";
  $PortObj = new Win32::SerialPort ("COM3") || die "Can't open COM3: $^E\n";
  print "here";
  $PortObj->user_msg(ON);
  $PortObj->databits(8);
  $PortObj->baudrate(9600);
  $PortObj->parity("none");
  $PortObj->stopbits(1);
  $PortObj->handshake("rts");
  $PortObj->buffers(4096, 4096);

  $PortObj->error_msg(1);  # prints major messages like "Framing Error"
  $PortObj->user_msg(1);

  $PortObj->write_settings || undef $PortObj;

  print "here";
  # $PortObj->save($Configuration_File_Name);
  $PortObj->read_interval(100);    # max time between read char (milliseconds)
  $PortObj->read_char_time(5);     # avg time between read char
  $PortObj->read_const_time(100);

   print "here";
   $string_in = $PortObj->read("200");

   print $string_in
  # $PortObj->baudrate(300);
  # $PortObj->restart($Configuration_File_Name);  # back to 9600 baud

  $PortObj->close || die "failed to close";
  undef $PortObj;

The code is not working but on forum and many other places it says working like here , here, this and this.
Im unable to find what is this means "use Win32::SerialPort qw( :STAT 0.19 );"
is that something like importing that library with version number. ?
I'm already installed  Xampp with Perl and activePerl Win32::serialport 0.22 and its API but when I run the code it return an error like
Error message:
End of script output before headers: serial.pl

500 Error
Any idea ??
Solved
For reading section I use the code below.
# warn "here";
  my ($ser) = @_;
  my ($numChars, $c);
  my $line = '';
  do {
    do {
      ($numChars, $c) = $PortObj->read(1);
      #print "$numChars read=$c\n";
    } while ($numChars < 1);
    # print $c;
    $line .= $c;
  } while ($c ne "\n");
   print $line;

The code works fine from CLI so I just put a PHP file to read the perl script and return the data.

A:
use Win32::SerialPort qw( :STAT 0.19 );

This is the same as
use Win32::SerialPort ':STAT', '0.19';

The :STAT imports a number of useful status constants, and is explained under Exports in the documentation for the module
The 0.19 is part of Perl, and is insisting that the version of Win32::SerialPort must be 0.19 or later. The current version is 0.22. If you change 0.19 to 0.23 then you will see the effect it has


text:
Q: Convert bitmap to ImageSource give NullReference exception I've got WCF service to send image as a stream to client app.
My client app gets the stream :
 Stream imageStream = client.GetImage();

When I use this code:
imageStream.CopyTo(stream);
int size = (int)stream.Length;
stream.Seek(0, SeekOrigin.Begin);
BitmapFrame bf = BitmapFrame.Create(stream,
    BitmapCreateOptions.None,
    BitmapCacheOption.OnLoad);
cam_img.Source = bf;

It work's fine but I need apply some filters to image before assign to source.
So I need bitmap. First, I convert Stream imageStream to byte array and then I use some code I find on forums:
byte[] tab_img;
using (var memoryStream = new MemoryStream())
{
    imageStream.CopyTo(memoryStream);
    tab_img= memoryStream.ToArray();
}

Bitmap bm;
using (MemoryStream mStream = new MemoryStream())
{
    mStream.Write (tab_img, 0, tab_img.Length);
    mStream.Seek(0, SeekOrigin.Begin);

    bm = new Bitmap(mStream);

    Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
    Bitmap bm_post = filter.Apply(bm);

    ImageSourceConverter c = new ImageSourceConverter();

    object source = new ImageSourceConverter().ConvertFrom(bm_post);
    ImageSource is1 = (ImageSource)source;
    cam_img.Source = is1;
}

but I still get NullReferenceException in line
object source = new ImageSourceConverter().ConvertFrom(bm_post);


text:
Q: Why does a rising integer with no influence crash my program This is my code and it works as expected. But after adding a rising integer (even though it has no influence on the code) my code doesn't work as expected

#include <iostream>

int i;
int j = 0;
int nums[] = {};
int co = 0;

void rq1() //rq = request
{
    std::cout << ("How many numbers?");
    std::cin >> i;
}

void rq2 ()
{
    int n2 = 0;
    for (int n = 1; n <=  i; n++)
    {
        std::cout << n2 + 1 << (". number?");
        std::cin >> nums[n2];
        n2++;
    }
}

void sort ()
{
    for (int n4 = 0; n4 < i; n4++)
    {
        int k = j + 1;

        for (int n3 = 1; n3 < i; n3++)
        {
            if (nums[j]==nums[k])
            {
                if (j<k) {std::cout << j << "," << k << std::endl; k++;}
                else {k++; return;}
            }
            else {k++;}
        }

        j++;
    }
}

int main()
{
    rq1();
    rq2();
    sort();
}

Input: 4 numbers (1,2,1,2)
Output: (0 , 2)
(1 , 3)
But after adding co++ the Output is (0,2) but expected Output is (0 , 2)
(1 , 3)
{
    for (int n4 = 0; n4 < i; n4++ )
    {
        int k = j + 1;

        for (int n3 = 1; n3 < i; n3++)
        {
            if (nums[j]==nums[k])
            {

                if (j<k) {std::cout << j << "," << k << std::endl; k++; co++;}
                else {k++; return;}
            }

            else {k++;}
        }

        j++;
    }
}

I don't know why my outputs changes. I mean int co doesn't do anything else

A:
int nums[] = {};

This array variable has no elements. This isn't allowed in C++. The program is ill-formed.

std::cin >> nums[n2];

Here you access the empty array outside of its bounds. The behaviour of the program is undefined.

I don't know why my outputs changes.

It's because the behaviour of the program is undefined.


text:
Q: Limit count of threads for python script I have a python 2.7 script on a CentOS linux server which had a bug starting new threads until I could not login to the server anymore.
Is there a way to tell the python runtime not to create/start/use more than 50 threads (and to throw exceptions instead or kill the script) to prevent this problem, or do I have to implement this in the script myself?
The threads are started via thread.start_new_thread().

A: According to the documentation on the python threading module (the newer threading module) you can call an active_count() method on the module and find out how many threads are running. Now, I understand that you are using the lower-level thread module, so I looked into it by running:
import thread
dir(thread)

This produced the list:
['LockType', '__doc__', '__name__', '__package__', '_count', '_local', 'allocate', 'allocate_lock', 'error', 'exit', 'exit_thread', 'get_ident', 'interrupt_main', 'stack_size', 'start_new', 'start_new_thread']

(I show this because it is very useful in finding out what modules contain, specifically in the interactive terminal)
You can see that the thread module contains a _count field, which when called (e.g. thread._count()) should return the number of threads running (you could check this value and raise exceptions when it exceeds your maximum).
Of course, the underscore in front of _count means that the method is treated, somewhat like a private method. However, in Python you can still access it.


text:
Q: pmf for a function of random variables I have an independent sequence of random variables  such that P($X_n = \pm1) = \frac{1-2^{-n}} {2} $
 and P($X_n = 2^ k)=2^{-k}$ for k = n+1,n+2,...
Define a new sequence of random variables by $Y_n = X_n$ if $X_n = \pm1$
$Y_n = 0$ otherwise.
Find P($Y_n = y)$
How to do this?
I have so far proven $X_n$ and $Y_n$ to be tail equivalent. I have to prove Lyapunov's condition for sum of $Y_n$ which I will be able to if I can find E($Y_n)$ but that is where I am stuck.


text:
Q: Finding the extrema of $f(a):=\left\vert\frac{4}{3a}\sin\left(\frac{a}{4}\right)\left(4-\cos\left(\frac{a}{4}\right)\right)-1\right\vert$ Let $0<a<\pi$.
Find the minimum and maximum:
$$f(a):=\left\vert\frac{4}{3a}\sin\left(\frac{a}{4}\right)\left(4-\cos\left(\frac{a}{4}\right)\right)-1\right\vert.$$


text:
Q: How to reduce archive size in iOS So I have just shocked that I ran out of space in my Mac book, then I try to find out what really fills up my space. This machine is only used for iOS app development (react native 0.64), and one thing that I also tried to do is cleaning up the archives of my Xcode. To my shock, like every single archive is taking 1.5GB space, but the app itself only like 20MB in play store. So I guess every single archives also contains extra data that I'm not sure important or not.
another thing that I notice is that the app archiving can take around 30 minutes alone, while the android release build only take 3 minutes to build an the .apk size of android is only 30MB.
My question here is:

*

*how to somehow reduce the space taken by archive?

*if no. 1 doesn't work, how to auto delete archive after upload to TestFlight or play store?

*is there a way to reduce the archiving time taken?

A: To delete unused XCode data in iOS, I am using DevCleaner (that is set to remove archives/build data every week automatically):
https://apps.apple.com/us/app/devcleaner-for-xcode/id1388020431?mt=12

A: you can delete this folder every now and again to get more space
/Users/user/Library/Developer/Xcode/DerivedData
use fastlane to make builds much faster and you can automate a whole bunch of processes
this tutorial is dated but I still use it as a reference
https://docs.fastlane.tools/getting-started/cross-platform/react-native/


text:
Q: How to shift all values from an array but remove the last value I have an array like this :
const arr = [1, 2, 3, 4, 5];

And I want to shift all the values and remove the last value and put 0.
My array should look like this after the operation :
[2, 3, 4, 5, 0]

How to do this ?

A: here is one approach

const arr = [1, 2, 3, 4, 5];
            arr.shift()
            arr.push(0)

 console.log(arr)

second approach

const arr = [1, 2, 3, 4, 5];
v=arr.slice(1,arr.lenth)
console.log([...v,0])

A: In case someone finds this useful in java. Note - this approach will manipulate the original array
    private void circularArray(int originalArray[]) {
    for (int i = 0; i < originalArray.length -1; i++) {
        originalArray[i] = originalArray[i+1];
    }
    originalArray[originalArray.length -1] = 0;
}


text:
Q: Is there any standard approach for defining projects in an ASP.NET MVC solution? How should I logically define an ASP.NET MVC solution? Into how many projects must I divide my solution? Is there a standard approach for this? Like for example, a model class library, an MVC web application (comprising controllers & views), a unit test project, a repository project etc... What are the different types of project one can come up with?

A: The answer is really depends. Depends of the scale of your project. You can have it all in one project (main MVC one) of you can split it further. The canonic form for this projects is something like that:
project.WEB
project.Common (here belongs common functionality between projects, so helpers, utilities, even some extension methods belong there)
project.Model (Data entities)
project.BL //(Business Logic)
project.DAL //(Data Access Layer or Persistence)
project.Tests

*note the "project" is your namespace root. How ho handle namespace naming you can check it there: namespace naming conventions
And the you can split it further and further. However I would suggest that you do not exaggerate with splitting it any further. When you will have to do it you will know (one project grow too much, there are logic separations ...). You try to follow the principle YAGNI.
And one more thing. If you want to be there "by the book" check it out DDD - Domain Driven Desing: http://msdn.microsoft.com/en-us/magazine/dd419654.aspx.

A: This is a very broad question, but i will give you an example of what I did on my previous project. Firstly, it will depend on the complexities of the overall application, and the developers personal preference. A simple app could very well fit inside a single MVC 4 application.
Web Project - for the views using MVC4
Application - for business logic)
Data - for repositories and webservice methods)
Domain - for the objects used in the app
Utilities - for common functionality that needs to be used in more than one project

The example above fitted the project very nicely allowed me to separate all the concerns making it more maintainable.


text:
Q: How to set AUTO_INCREMENT default value and rate of increase in MySQL 5.6 I want 'ProjectID' to start at 1000 and increment by 100.
How do I set an AUTO_INCREMENT default value and rate in MySQL 5.6? In other words, if I want to create a primary key that starts at 1000 and increases by 100, how do I do that in MySQL?
CREATE TABLE IF NOT EXISTS PROJECT(
ProjectID Int(4) AUTO_INCREMENT PRIMARY KEY,
ProjectName Char(20) NOT NULL,
DepartmentName Char(30) NOT NULL,
MaxHours Int(14) NOT NULL,
StartDate Char(10) NOT NULL,
EndDate Char(10) NULL)
ENGINE=InnoDB AUTO_INCREMENT=1000;

I want 'ProjectID' to start at 1000 and increment by 100.

A: Start with empty table.
ALTER TABLE tblName AUTO_INCREMENT = 1000;

Perform your insert to this special 100 gap table in one and only one place.
Let's call that place a stored proc (not mandatory).
Commit to the discipline of that approach.
In that stored proc lock the table, do an insert.
DECLARE a query as a "string" and then execute that string via a Prepared Statement. That string is like the above Alter Table but with auto_increment=xxxx
Where xxxx=max(ProjectID)+100
Unlock table. Exit stored proc.
The reason is that Alter Table tblName auto_increment = variable_name will barf. So it needs to be an executed Prepared Statement.
Edit as promised:
drop schema wpc;
CREATE SCHEMA IF NOT EXISTS WPC;

use wpc;

CREATE TABLE IF NOT EXISTS department
(
    Department varchar(30) NOT NULL,    -- chg
    BudgetCode int(20) NOT NULL,
    OfficeNumber int(10) NOT NULL,
    Phone varchar(12) DEFAULT NULL, -- chg
    PRIMARY KEY (Department)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS employee
(
    EmployeeNumber int(4) AUTO_INCREMENT,
    FirstName varchar(25) NOT NULL, -- chg
    LastName varchar(25) NOT NULL, -- chg
    Department varchar(30) NOT NULL DEFAULT 'Human Resources',
    Phone varchar(17) DEFAULT NULL, -- chg
    Email varchar(100) NOT NULL,

    PRIMARY KEY (EmployeeNumber),
    UNIQUE KEY Email (Email),
    KEY DepartmentFK (Department),

    CONSTRAINT DepartmentFK
    FOREIGN KEY (Department)
    REFERENCES department (Department) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS project
(
    ProjectID INT(4) NOT NULL AUTO_INCREMENT,
    ProjectName VARCHAR(30) NOT NULL, -- chg
    Department VARCHAR(30) NOT NULL,  -- chg
    MaxHours INT(3) NOT NULL DEFAULT '100',
    StartDate datetime NOT NULL, -- chg
    EndDate datetime DEFAULT NULL, -- chg

    PRIMARY KEY (ProjectID),
    KEY ProjectFK (Department),

    CONSTRAINT ProjectFK
    FOREIGN KEY (Department)
    REFERENCES department (Department) ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=LATIN1 AUTO_INCREMENT=1000;

CREATE TABLE IF NOT EXISTS assignment
(
    ProjectID INT(4) NOT NULL AUTO_INCREMENT,
    EmployeeNumber INT(4) NOT NULL,
    HoursWorked INT(4) NOT NULL,

    PRIMARY KEY (ProjectID),
    -- UNIQUE KEY EmployeeNumber (EmployeeNumber), -- kill this dupe, plus it won't be unique
    -- KEY ProjectFK1 (ProjectID), -- don't have this it is already a PK
    KEY EmployeeFK1 (EmployeeNumber), -- keep this as it won't be unique
    -- duplicate and unnecessary keys just slow down system. you had 4. you need 2

    CONSTRAINT EmployeeFK1
    FOREIGN KEY (EmployeeNumber)
    REFERENCES employee (EmployeeNumber),

    CONSTRAINT ProjectFK1
    FOREIGN KEY (ProjectID)
    REFERENCES project (ProjectID) ON DELETE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;

show table status like '%'; -- auto_incs look good

insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Dismantle Kryptonite','Engineering',1000,'2015-04-01',null);
-- fk error, good, do dept first. BUT NOTE this failure screws up auto_inc so next insert is 1001 yikes
-- so re-do, drop schema, create schema, skip failed first insert above and start below:
insert department (Department,BudgetCode,OfficeNumber,Phone) values ('Engineering',111,222,null);
insert department (Department,BudgetCode,OfficeNumber,Phone) values ('Human Resources',107,223,null);
select * from department;
-- all looks well
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Dismantle Kryptonite','Engineering',1000,'2015-04-01',null);
select * from project; -- projectId 1000
alter table project auto_increment=1010;
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Fire old employees','Human Resources',2,'2015-04-02',null);
alter table project auto_increment=1020;
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Regret, Hire back','Human Resources',2,'2015-04-02',null);
alter table project auto_increment=1030;

select * from project;

fk's look good and as expected. Try employee:

insert employee (EmployeeNumber,FirstName,LastName,Department,Phone,Email) values (222,'Donald','','bad-dept','1','d@g.com');
insert employee (EmployeeNumber,FirstName,LastName,Department,Phone,Email) values (222,'Donald','','Engineering','1','d@g.com');
insert employee (EmployeeNumber,FirstName,LastName,Phone,Email) values (223,'Kris','','2','k@g.com');
insert employee (EmployeeNumber,FirstName,LastName,Phone,Email) values (2277,'Kim','','3','kim@g.com');
select * from employee;
insert employee (FirstName,LastName,Phone,Email) values ('Auto','','44','auto1@g.com'); -- 2278
do a re-do of everything top to bottom but skipping employee inserts except the below to run:

insert employee (FirstName,LastName,Department,Phone,Email) values ('Donald','','Engineering','1','d@g.com');
insert employee (FirstName,LastName,Phone,Email) values ('Kris','','2','k@g.com');
insert employee (FirstName,LastName,Phone,Email) values ('Kim','','3','kim@g.com');
select * from employee;
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Hire Joe','Human Resources',2,'2015-05-02',null);
alter table project auto_increment=1040;
insert employee (FirstName,LastName,Phone,Email) values ('Jason','','66','jj@g.com');
select * from employee;
select * from project;

A: Create table:
CREATE TABLE IF NOT EXISTS PROJECT(
 ProjectID Int(4) AUTO_INCREMENT PRIMARY KEY,
 ProjectName Char(20) NOT NULL,
 DepartmentName Char(30) NOT NULL,
 MaxHours Int(14) NOT NULL,
 StartDate Char(10) NOT NULL,
 EndDate Char(10) NULL)
 ENGINE=InnoDB AUTO_INCREMENT=1000;
Then type:
SET @@AUTO_INCREMENT_INCREMENT=100;
Now ProjectID is a surrogate key that starts at 1000 and increases by 100.
https://dev.mysql.com/doc/refman/5.0/en/replication-options-master.html#sysvar_auto_increment_offset
Thank you @NorbertvanNobelen !