Best way to store objects with images locally on disk in Flutter?

Question: I'm making a super simple cookbook (like literally, for food) app for one single person, so I haven't been thinking that I want/need to use a database or any internet connectivity. When the user creates a recipe, the recipe object contains a bunch of strings and an image, like this:
class Recipe {
 String _title;
  Image _picture;
  Uint8List _imageBytes;
  int _prepTime;
  int _cookTime;
  int _totalTime;
  String _description;
  List<String> _ingredientList;
  List<String> _directionsList;

....
}

The user will probably create around 20 recipes. There need not be any profiles, since I'm literally just making the app for one person. The recipes are the only app data that need to persist.
So far, I have tried to encode each recipe as a JSON and then save it to shared_preferences (note the _imageBytes field that I tried to use for this purpose). But not only does this seem like a really inefficient way to do things, I haven't even been able to get it to work. It seems confusingly difficult to get information on this: how would one normally store such information locally in a Flutter app, without using a database? Or is a database the way to go here?
Answer: To persist data efficiently in Flutter using a local database, such as SQLite, is the way to go:

Import the right dependecies:

import 'dart:async';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

Open the DB:

WidgetsFlutterBinding.ensureInitialized();
// Open the database and store the reference.
final Future<Database> database = openDatabase(
  join(await getDatabasesPath(), 'recipes_database.db'),
);

Create the table:

final Future<Database> database = openDatabase(
  join(await getDatabasesPath(), 'doggie_database.db'),
  onCreate: (db, version) {
    return db.execute(
      "CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TITLE)", // all the properties here
    );
  },
  version: 1,
);

Create methods to insert and retrieve entries:

Future<void> inserRecipe(Recipe recipe) async {
  final Database db = await database;
  await db.insert(
    'recipe',
    recipe.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}
Future<List<Recipe>> recipes() async {
  final Database db = await database;

  final List<Map<String, dynamic>> maps = await db.query('recipes');

  return List.generate(maps.length, (i) {
    return Recipe(
      title: maps[i]['title'],
      // ... all the properties here
    );
  });
}

Since our class, Recipe, contains files, and more specifically images, we could store the Image as an URL and take advantage of the Cache to retrieve it:
var image = await DefaultCacheManager().getSingleFile(recipe.picture);

Comment: Does it matter how I name the URL?
Answer: You need path provider package and flutter cache manager.
Following is an example that demonstrates how a network image can be stored with cache manager.
import 'dart:async';
import 'dart:io' as Io;
import 'package:image/image.dart';

import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path_provider/path_provider.dart';
class SaveFile {

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }
  Future<Io.File> getImageFromNetwork(String url) async {

    var cacheManager = await CacheManager.getInstance();
    Io.File file = await cacheManager.getFile(url);
    return file;
  }

  Future<Io.File> saveImage(String url) async {

    final file = await getImageFromNetwork(url);
    //retrieve local path for device
    var path = await _localPath;
    Image image = decodeImage(file.readAsBytesSync());

    Image thumbnail = copyResize(image, 120);

    // Save the thumbnail as a PNG.
    return new Io.File('$path/${DateTime.now().toUtc().toIso8601String()}.png')
      ..writeAsBytesSync(encodePng(thumbnail));
  }
}


How to get frequencies for the major and minor Pentatonic scales

Question: I'm trying figure out how get the frequencies of pitches from the pentatonic scales. To start, I build a chromatic scale tuned in 440 starting on D (67 semitones below A440), using this equation.
2 -67/12 x 440hz =  9.177hz
So I can build a chromatic frequency table using a ratio to find semitones: 21/12 = 1.0595
<code>    9.1770 * 1.0595 = 9.7227
    9.7227 * 1.0595 = 10.3009
   10.3009
   10.9134
   11.5623
   12.2499
     .
     .
     .
  415.3047
  440.0000
  466.1638
  493.8833
  523.2511
  554.3653
  587.3295
  622.2540
</code>
My question is how to extract the pentatonic (major and minor) frequencies from my chromatic table?
I need this for all these scales: C • D • E • F • G • A • B
Comment: I'm a bit unclear on what you're asking - do you want the frequencies of CDEFGAB (google it), a formula for finding the frequencies of the various notes in a scale given a starting pitch, or something else?
Comment: `how extract the pentatonic (major and Minor) frequencies from my chromatic table?`for example how get the Pentatonic frequencies from Minor F ?
Comment: I've edited your question somewhat. If I've missed something important, feel free to roll back or re-edit.
Answer: Using Equal Temperament
There are a few things to consider when building a pentatonic scale. It looks like you used the formula for equal temperament in building your table, which is

fn = f0 * (21/12)n

Where f0 is a known frequency (usually A440) and n is the number of halfsteps you are from f0. (See here for more info.) | Google can do this math for you, just change the 1 in the search bar to number of semitones you are from A440.
From this you can generate a table, as you have done. I'd suggest adding a column to your table with what note names you are referring to, like
A   | 440.0000
A#  | 466.1638
From there you can easily figure out what the frequencies of the notes are if you know their names. Relative to "normal" major scales, the major pentatonic scale is made up of tones 1, 2, 3, 5, 6. In A these would be A, B, C#, E, F#. Relative to the minor scale, a minor pentatonic uses 1, 3, 4, 5, 7, which correlate to A, C, D, E, G. Just look those up on your table, and you have the frequencies.
The formula can also be used with a standard unit of length, so you could determine string length, pipe length, etc.

Using Pythagorean Tuning
However, you might not want to use equal temperament for working out a pentatonic scale. After all, the pentatonic scale doesn't necessarily have much to do with the 11-tone scale equal temperament describes.
Pythagoras based his fifths on perfect 3:2 relationships. A pentatonic scale can be easily built knowing only the relationships between fifths and octaves, which are 2:1 relationships. For more information, look here.
So starting from A 440,

E = 440 * 3 / 2 = 660
B = 660 * 3 / 2 = 990
F# = 990 * 3 / 2 = 1485
C# = 1485 * 3 / 2 = 2227.5

Now we know all the frequencies of the pitches in a pentatonic scale, it's just a matter of dividing by 2 until we get to the right octave. All the frequencies need to end up between 440 and 880.

A = 440
B = 990 / 2 = 495
C# = 2227.5 / 4 = 556.875
E = 660
F# = 1485 / 2 = 742.5

Ratios for all notes can be computed by simply using 1 as your starting pitch:

A = 1
B = 9/8
C# = 81/64
E = 3/2
F# = 27/16

The minor scale can be built similarly by going up a fifth to E and then down fifths through D, G, C. Any other scale can be built simply by picking a different starting note. Using this method, all frequencies can easily be worked out exactly on paper, but it really doesn't work well for scales other than pentatonic scales. For why, read up on the development of temperament.
Comment: @user2721828 - I think there might be something off with your list. It only shows the frequencies corresponding to the pitches D F# B. The notes of the major pentatonic scale in D should be D E F# A B. From [here](https://en.wikipedia.org/wiki/Piano_key_frequencies#List)  the frequencies of the lowest possible set of those notes on the piano is D: 36.7081
E: 41.2034
F#: 46.2493
A: 55.0000
B: 61.7354
Comment: this not make sense for me, the major pentatonic frequencies in D is  `9.1770
   11.5623
   13.7500
   18.3540
   23.1247
   30.8677
   36.7081
   46.2493
   61.7354
   73.4162
   97.9989
  123.4708
  146.8324
  195.9977
  246.9417
  329.6276
  391.9954
  493.8833
  659.2551
  783.9909` does not match with your results
Comment: By pythagorean tuning, you'd get D: 36.6666
E: 41.15625
F#: 46.40625
A: 55
B: 61.875 (all exact except for D, a repeating decimal), which you can see are slightly different as the intervals aren't tempered at all. They are still quite close though.


Xcode static library seems to change architecture on build

Question: Here's a bit of background before I dive into the question. My ultimate goal is to compile the source of a c++ static library for the architectures arm64, armv7, armv7s, i386, and x86_64, and then package the libraries into a fat library so that I can use them during iOS development. This will enable me to use the simulator and a device with the same library.
Here's my issue. I'm trying to test the i386 version of the library, on it's own, using the iPhone 5 simulator. I compiled the static library for i386 as follows:
./configure --enable-utf8-only --disable-shared --host=i386-apple-darwin LDFLAGS="-L." CC="/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" CXX="/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++"

then
make CXXFLAGS="-arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator10.3.sdk" CCFLAGS="-arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator10.3.sdk"

This resulted in my static library, libtest.a. I then ran the follow to verify the libraries architecture
jamespc:Desktop $ lipo -info libtest.a
input file libtest.a is not a fat file
Non-fat file: libtest.a is architecture: i386

Everything seemed to look good so far. Next I added the library to my Xcode project and tried to build the project. When building the project I get the following warning and error.
ld: warning: ignoring file
    /Users/cleandev/Library/Developer/Xcode/DerivedData/MyProject-hjtfdovfmdsubkejojqknkmqkzps/Build/Products/Debug-iphonesimulator/libtest.a,
    file was built for archive which is not the architecture being linked (i386):
    /Users/cleandev/Library/Developer/Xcode/DerivedData/MyProject-hjtfdovfmdsubkejojqknkmqkzps/Build/Products/Debug-iphonesimulator/libtest.a
Undefined symbols for architecture i386:
    ...
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Perplexed by error I ran lipo on my static lib again, this time using the path listed in the warning, in the derived data folder.
jamespc:Debug-iphonesimulator $ lipo -info libtest.a
input file libtest.a is not a fat file
Non-fat file: libtest.a is architecture: x86_64

I'm confused as to why the library appears to have a different architecture associated with it when I take a look at it in the derived data.
Is the way I'm compiling the static library wrong?
Is there something I might be doing wrong in my Xcode build settings?
Thank you for taking the time to read my question
Comment: Hey James.libtest.a is architecture: i386 error meaning fat file not contain i386 support. Please refer video https://www.youtube.com/watch?v=j_SQ8zw0Sq0
Answer: I guess the framework was not compiled for the iOS Simulator's architecture, which is i386. Xcode only compiles a framework for the target architecture.
Please follow this tutorial: http://www.raywenderlich.com/65964/create-a-framework-for-ios
It may help.


Tricky Polar Line integral problem

Question: I need to calculate the following line integral over the curve C:
$$\int_C e^{\sqrt{x^2+y^2}} ds $$
where $C$ is the circuit bounded by $r = a, \varphi = 0$ and $\varphi = \pi/4$.
I tried separating the integral into these three parts and got an answer of $(\pi/4)ae^a$
However, the answer the book gives (the problem is from Demidovich's Problems in Analysis) is
$$(\pi/4)ae^a + 2(e^a - 1)$$
The $e^a - 1$ term comes from evaluating the integral over the bounds of the curve $\varphi = 0$ and $\varphi= \pi/4$. But I thought these would cancel out, and not add up.
Comment: You should accept the result of Math Lover.
Comment: Please check that my Latex-ification (placing formulas between dollar signs etc.) of your text is correct.
Comment: @nacho just noticed your field is a scalar field. So pls check that in your integral.
Comment: @MathLover are you saying the book's answer is actually right? It's a scalar field, yes, but I still think what I said holds true.
Comment: Yes given it is a scalar field, it should not matter the direction. Regardless of direction, you are traversing through the same set of points. So integral should be same. That is why I said to check how you set up your integral.
Comment: You are evaluating the path length. If you go from A to B and then back, your path length will be $L=2|AB|$
Answer: a) Between point $(0,0)$ and $(a,0)$, $\vec r(t) = (t,0), 0 \leq t \leq a$.
$I_1 = \displaystyle \int_C f(\vec r(t)) \ |r'(t)| \ dt = \int_0^a e^t \ dt = e^a - 1$
b) Between point $(\frac a {\sqrt2},\frac a {\sqrt2})$ and $(0,0)$, $\vec r(t) = (\frac a {\sqrt2} - t, \frac a {\sqrt2} - t), 0 \leq t \leq \frac a {\sqrt2}$.
$I_2 = \displaystyle \int_0^{a / \sqrt2} \sqrt2 \ e^{(a - \sqrt2 t)} \ dt = e^a - 1$
c) over circular segment, as you calculated.

Tricky Polar Line integral problem


Finite number of subgroups $\Rightarrow$  finite group

Question: I'm trying to prove that any group $G$ of infinite order has an infinite number of subgroups.
I think that if the group has an element of infinite order, then it's easy because I can take the groups generated by the powers of this element.
What if it doesn't? Every element generates a cyclic subgroup. Every element belongs to at least one cyclic subgroup (that generated by itself). So the group is the union of its cyclic subgroups. If all these are finite, we would have to have an infinite collection of subgroups anyway.
Is that correct?
Comment: +1 for showing your work.
Comment: Yup, that's correct :)
Answer: Yes, it's correct, though perhaps somewhat disorganized.
The fact that a group is a union of its cyclic subgroups holds regardless of any hypothesis on the group. So you can state and prove that first.
Then: an infinite cyclic group has infinitely many (cyclic) subgroups. So, a group is infinite if and only if it has infinitely many cyclic subgroups: If the group is finite, then it has only finitely many subsets, so finitely many subgroups, so finitely many cyclic subgroups. If the group is infinite, then being a union of its cyclic subgroups, either one of the cyclic subgroups is infinite (and hence there will be infinitely many cyclic subgroups, since that subgroup has infinitely many cyclic subgroups), or else there are infinitely many finite cyclic subgroups in the union. Either way you are done.
That is your argument, just organized a bit more.
Answer: I might be oversimplifying, but it seems to me that if G has infinite elements, it has an infinite number of cyclic subgroups, one for each g in G.
Comment: Generally, many different elements will give the same subgroup; e.g., $g$ and $g^{-1}$ give the same cyclic subgroup. So you must argue somehow that you still have infinitely many, even after taking into account the repeats.
Comment: They don't have to be all different.


Harmony behind Guthrie Govan's Wonderful Slippery Thing

Question: The tune can be found here:

Main chord progression is:
Bm7 - D9 - Gmaj7 - F#7b9

My understanding is that it's actually:
i - V/vi - vi - V

With D9 being secondary dominant for Gmaj7.
However, something strange happens later, the harmony changes in the main part:
Bm7 - D9 - Gmaj7 - F#7b9
E11 - E9 - Gmaj7 - F#7b9

Are we still in the key of Bm7?
Where did E11 and E9 came from?
Comment: E11 can be seen as a D chord with E in the bass and so has two notes in common with Bm7
Answer: Let's take a look at an E11 chord (or an alternate name, an E9sus4). What do we have? An E root then assuming the 3rd is omitted (good move and usually done) B-D-F#-A or a Bm7/E, a 1 chord with 4 in the bass in Bm. The next chord, an E9 basically gives you a 4-3 voice leading between the two. Now in Bm the diatonic 4 chord is E minor unless you use the ascending melodic minor scale, in which case it's an...E7! The E7 IV chord is also a diatonic chord if you're in the Dorian mode. What's my point? They're basically IV chords. Non-diatonic, yes but few songs are completely diatonic anyway.
MANY songs incorporate a IV7 in them. A few examples are "Mr. Magic", "Oye Como Va", Almost every blues tune ever written and pretty much every James Brown song that goes "to the bridge" (the IV7). The middle section of this song where it goes to E for a while can be interpreted as a modulation and that's legitimate but to me it's just hanging out on the IV chord for a while.
Answer: I know what you mean, but there's no 'key of Bm7'. There's a key of B minor, and that's indeed where we seem to be.
There's a simple and sufficient explanation that E11 and E9 are chromatic chords.   That IS a thing!
Some would be happier if we justified them as being 'borrowed' from some other key.  Sorry, I don't want to look at it that way.  It isn't helpful.  They're chromatic.
Answer: To my ear, the two E chords are a temporary, direct modulation to E major. They take advantage of the root movement from G to F# and also serve to set up the bridge. (Note that jazz and blues allow for the interpretation of a major key even when the minor seventh is present.[1])
In a different context, E might be interpreted as IV borrowed from B major, but while it is literally the case, I don't think it explains the overall sound any better than just thinking in terms of root movement. Similarly, other "standard" explanations, like treating the F#7 as a common-tone chord with E, I think also stretch the theory too far.

[1] Although Jazz, blues, and popular music harmonies are often in line with the common practice model of tonality, the don't adhere strictly to it. The presence of the ♭7 in major is a good example: it is frequently treated as a consonance rather than a dissonance. The bridge of this piece is a perfect example. The underlying harmony is E7, but the whole section is clearly perceived as E major rather than A major, as common practice tonality would demand.


Can robust standard errors be less than those from normal OLS?

Question: I'm reading about Robust Standard Error Estimators for Panel Models from the developer of plm R package (Millo, 2017: 21). But my question is not about software.
In the example I see that some heteroscedasticity robust standard errors are in fact less than those in benchmark OLS. I thought that we normaly expected robust errors to be at least as large as their OLS counterparts.
Below you see the comparison of different HC procedures, for the same model with coefficients arranged by columns.

My question concerns this situation. Is it fine in general and how to interpret this fact if, i.e. in real model, such a change in s.e. changes the significance of a coefficient?
Answer: OLS gives every point equal weight in estimating the error of the estimates. The variance/error is estimated as
$$\widehat{\text{Var}(\beta) }= \hat{\sigma} (X^TX)^{-1} $$
A weighted least squares estimator might use an estimate like
$$\widehat{\text{Var}(\beta) }= \hat{\sigma} (X^TWX)^{-1} $$
The weights might make some points more and others less important. As a result the estimates of the standard error can improve for some coefficients.
In the example figure below an OLS estimator would assume that the variance is constant. As a result it would give the points near the origin the same weight as the points far from the origin. However, a robust regressor might give the points near the origin more weight because of the smaller variance. As a result that robust estimator will estimate a lower error for the intercept term. (And as we can see with our naked eye, the intercept is clearly around 0, but OLS will not see this because it assumes equal variance)
Comment: thank you for the answer. I did not get the final point. Do you mean that OLS s.e.'s report insignificant intercept, and we cannot be sure if it is truely zero; but with some `W` we may become more confident about 0 intercept?
Answer: Yes they can be smaller than the standard variance estimates. The reason is that even in the case of linear models, robust standard errors are biased but consistent. Their variance estimates might be (severely) biased downwards due to this small-sample bias, see Imbens & Kolesar (2016, The Review of Economics and Statistics; ungated working paper version here):

Second, and this has been pointed out in the theoretical literature before [e.g. Chesher and Jewitt, 1987], without having been appreciated in the empirical literature, problems with the standard robust EHW and LZ variances and confidence intervals can be substantial even with moderately large samples (such as 50 units / clusters) if the distribution of the regressors is skewed.

Imbens, G. W., & Kolesar, M. (2016). Robust standard errors in small samples: Some practical advice. Review of Economics and Statistics, 98(4), 701-712.
Comment: The second link doesn't seem to work. Generally, I find that including a full citation is most helpful because titles don't change while links can become obsolete.
Comment: Thanks @dipetkov, I added the citation. The link works for me both on mobile as well as on my computer.
Comment: Thanks. Then we can infer you are probably accessing the link through the Princeton University network. The paper is on SSRN: [NBER Working Paper No. w18478](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2164602) though it might not be the final version.
Answer: If the response is, conditionally on the covariates, Gaussian, then we know that OLS are best linear unbiased estimators by Gauss-Markov theorem; no other estimator can have lower variance than OLS.
If the Gaussian assumption is not met we have no such guarantee anymore. Indeed, since the influence function (IF) of the OLS estimator is unbounded and the variance of the OLS estimator is proportional to the IF, then the variance of the estimator is unbounded as well. In practice, this means that even a single aberrant observation can drive away the OLS estimate along with its variance.
On the other hand, robust estimators (e.g. Huber (1964) DOI: 10.1214/aoms/1177703732, Hampel et al. (1984) DOI:10.1002/9781118186435, etc.) typically have a bounded IF, thus they deliver bounded estimates with bounded variance.
The point of this is that a "bad" observation will have only a limited impact on the robust estimate and its variance, whereas it can have a large effect on an estimate obtained from an estimator with unbounded IF such as OLS.
Comment: @garej by the Gaussian-Markov Thm, only if we are under the true model, the robust se $\geq$ then OLS se. With observed data the inequality is not true anymore, but the point is that if the observed data have outliers, a robust procedure will "kill" them whereas OLS will be driven by them. So if you suspect your data may have outliers, forget about OLS and use robust estimates.
Comment: so how to interpret this fact? Should I try to find some outliers in the data and run regressions again? I've found the same effect in my own research data.
Comment: The above stream of robust statistcs generally recommends let observations get donweighted by the procedure (no outlier removal). There are other streams of robust statistcs that work on methods for detecting outliers.But detecting outliers is subject to uncertainty (just like hypothesis testing). If you remove outliers, inference based on the remaining observation may be biased and has to be adjusted. If you are interested on this second stream try googling for "inference after outlier removal" or something similar.
Comment: to be clear, I'm a bit confused that robust s.e. make some of important variables statistically significant, while OLS s.e. - not. I'm not sure how to deal with this.


Restart multiple Azure VMSS with time shedule with Powershell Script

Question: I have multiple windows and Linux VMSS machines in azure, I need to recreate the pods, particularly with the windows machine after x days of creation.
I need to implement it with help of Powershell script.
Thank you.
Answer: You can use the Restart-AzVmss command to restart a scale set.


BS4 - returning 'None' when requesting Span

Question: I have (another) quick question on BS4 when I am trying to take a price from a website.
A snippet of the html code is below:

        Tecsound SY50 Self Adhesive (7.26m2)

<bdi>£61.50</bdi> (<bdi>£73.80</bdi> inc vat)

The price I am trying to get to is the £61.50 (which is the full price without GB taxes).
my attempt is:
import requests
from bs4 import BeautifulSoup

url = requests.get("https://www.the-website.co.uk")
vari = url.content
soup = BeautifulSoup(vari, "html.parser")
price = soup.find('span', {'class': 'woocommerce-Price-amount amount'})
print(price)

Output:
None

... and I have tried a similar:
import requests
from bs4 import BeautifulSoup

url = requests.get("https://www.the-website.co.uk")
vari = url.content
soup = BeautifulSoup(vari, "html.parser")
span = soup.find('span', {'class': 'woocommerce-Price-amount amount'})
price = span.text
print(price)

this produces the error:
AttributeError: 'NoneType' object has no attribute 'text'

The second error is expected, as I am clearly not picking up the information with my request, so there is nothing or to show, or 'None' as shown in my first example.
Please can somebody help me to correctly pluck the information I require from the html text?
Comment: If the information is populated by Javascript after the page loads, you'd need to execute that Javascript to fetch the information. I believe Selenium is capable of that.
Comment: Try the function `print(vari)` to look to the request answer, then carefully look to it. You either need particular headers, or cookies for the request, or as @carcigenicate said, the information came lately with javascript.
Answer: As mentioned by Carcigenicate you should use selenium - You also could improve your question by providing the real url.
Example
from selenium import webdriver
from bs4 import BeautifulSoup
from time import sleep

url = "https://soundproofingstore.uk/product/tecsound-sy50-self-adhesive/"

driver = webdriver.Chrome(executable_path=r'C:\Program Files\ChromeDriver\chromedriver.exe')

driver.get(url)
sleep(3)
soup = BeautifulSoup(driver.page_source,"lxml")
price = soup.find('span', {'class': 'woocommerce-Price-amount amount'}).get_text()
print(price)

driver.close()

Output
£61.50


How to Reload a Custom Drupal Theme (Without the Command Line)

Question: How do I reliably reload a custom Drupal theme I am developing without access to the command line? Just clearing the caches before I perform the load only works sometimes.
FWIW, we are promised command-line access in the future (security issues yet to be ironed out) but not anytime soon.
Comment: What do you mean by "reload a theme"? Theme regions? settings? libraries? hooks? templates?
Comment: I meant reload all of the files of the theme.
Comment: Is this local dev? turn off caching? `Just clearing the caches before I perform the load only works sometimes` should work all the time, restart server?
Answer: The steps that so far work reliably for me with Drupal 8.9.1 to load a custom theme again without command-line access are:

Install and enable the Devel module. (You will only need to do this once.)
Put your site into maintenance mode.
Turn on Devel -> Settings -> Rebuild the theme registry on every page load.
Clear the caches.
Load the new copy of the theme from Appearance -> Install new theme -> Upload a module or theme archive to install.
Clear the caches.
Reload one of your pages to verify your theme changes.

The second "Clear the caches" (6) might be redundant.
So far, this has worked like a champ once I figured out all of the necessary steps.
Comment: Also make sure you don't have CSS and JS Aggreggation turned on under Development > Performance.
Comment: Too true, prkos.


Is it correct to choose a model based on variable type or variable distribution?

Question: I have a dependent variable that is Poisson distributed, but it is not 'count' data or data collected over a given time period.  It is discreet and positive, with values from 1-10, and it is heavily left-skewed, with a mean of about 1.7.
The variable is from a survey question with 10 possible answers, basically an ordinal scale variable.  Can I use Poisson or negative-binomial regression for this even though the variable is not a traditional 'count' variable?
Answer: Suggest this is a binomial distribution problem with $n=10$. The probability mass function is
$$Pr(k;n,p) = \Pr(X = k) = {n\choose k}p^k(1-p)^{n-k}\;.$$
Here is a comparison of synthetic binomial mass data from 100 samples with a probability, $p$, of 0.17, for $n=10$ questions and the binomial mass function itself in percentage. The x-axis shows $k$, the number of successes in $n=10$ trials. The mean is $np=10\times0.17=1.7$.

The binomial mass is in light red, the simulated data is in light blue, and the overlap is purple colored.


Como fazer uma função com quantidade de parâmetros 'infinita'?

Question: Como faço uma função em JavaScript que pode receber uma quantidade infinita de parâmetros?
Quando me refiro a infinita, tenho ciência que existe um limite, mas quero fazer uma função onde a pessoa possa passar quantos parâmetros ela quiser: um, dois, cinco, dez, e que faça a mesma coisa para cada parâmetro passado para ela.
Um exemplo simples seria algo como:
function multiplicar(n1, n2, n3, n4) {
  return n1*n2*n3*n4;
}

Só que ao invés de aceitar 4 parâmetros, aceite uma quantidade de 2 a quantos a pessoa colocar (dado o limite suportado pela linguagem)
Como uma pergunta bônus, caso saibam, qual seria o limite de parâmetros que uma função pode receber em JavaScript?
Comment: Relacionada: [Para que serve o operador '…' no Javascript?](https://pt.stackoverflow.com/q/266612/5878)
Comment: Relacionada: [Quais são as melhorias que a implementação do Spread Operator trará para o javascript?](https://pt.stackoverflow.com/q/111497/5878)
Comment: Relacionada: [Existe um padrão de projeto ou recomendação que define a quantidade ideal de parâmetros que uma função deve ter?](https://pt.stackoverflow.com/q/315355/5878)
Answer: Utilize os 3 pontos antes de um parâmetro. Ele serve para que você utilize n parâmetros.
Seu nome é Spread e pode ser visto mais sobre na documentação.

n será um array dentro da função multiplicar

function multiplicar(...n) {
  let valor = n.reduce(function (valorAcumulado , valorAtual) {
    return valorAcumulado *= valorAtual;
  }, 1)
  console.log(valor);
}

multiplicar(2,3,4);

Recomendo a leitura: Para que serve o operador '…' no Javascript?
Comment: Entendi, obrigado. Se é que posso perguntar isso aqui, existe uma forma de eu me referir a um parametro específico entre a quantidade indefinida de parametros? Pelo que eu entendi eu pegaria o index de n?
Comment: @MáttheusSpoo `n` será um array. Consegue entender?
Comment: Sim, eu entendi isso, estava realmente confirmando se meu raciocínio estava correto (se eu poderia usar n[3] para me referir ao quarto parametro passado na função, por exemplo)

Novamente obrigado.
Comment: @MáttheusSpoo sim, pode usar do jeito que se referiu!


Diagnosing unexpected downtime in a VPS setting

Question: I currently operate a Debian VPS with Linode to host a website. Yesterday, the entire VPS became unresponsive for about 40 minutes. Checking the graphs that Linode provides I see that the entire system seems to have ground to a halt during this time:

Checking dmesg just yields a bunch of iptables denied messages, but I suspect that these are as a result of the firewall operating correctly, since they're mostly obviously unreasonable (e.g. UDP packets, nonsense TCP packets, etc).
How would I go about diagnosing what happened, and take steps to prevent it from happening again?
Comment: A whole Linode datacenter [ground to a halt](http://status.linode.com/incidents/0hv086dx5jbf) yesterday. It was big news.
Answer: The first thing you do, if you can't reach your VPS, is to contact your provider. If they have them, check their status page or Twitter feed for information about any incidents affecting multiple customers. Then, if necessary, contact them.
In your case, the time on your graphs corresponds exactly to a DDoS attack directed at Linode yesterday.
Comment: Ah, thank you. It had not occurred to me that the fault may be any other than my own. I am very glad to know that this was "a thing" and not just a mystery "welp i guess it's offline for unknown reasons".


What is the difference between impredicativity and recursion?

Question: I'm looking to know the difference between the concepts of impredicativity and recursion.
For impredicativity, I've got this defintion from wikipedia:

Something that is impredicative, in mathematics and logic, is a self-referencing definition.

And this one for recursion:

Recursion occurs when a thing is defined in terms of itself or of its type.

Even after reading these articles I don't get the subtlety here.
In what are they different?
Thank you
Comment: Recursion has a precise math definition; see e.g. [Recursive definition](https://en.wikipedia.org/wiki/Recursive_definition#Principle_of_Recursive_Definition). The concept of [Predicative (and Impredicative) definition](http://www.iep.utm.edu/predicat/) is more vague.
Comment: You can see the post: [understanding-predicativity](https://math.stackexchange.com/questions/2133360/understanding-predicativity).
Comment: Recursion is the absence of the restriction from defining one part of a thing in terms of another part of that thing.
Answer: Maybe the moral is: don't always believe the first thing you read on Wikipedia??? [Actually, a lot of the more detailed explanations of mathematical topics on Wikipedia can be pretty good: but sometimes, as here, the thumbnail summary sketches can be misleading or worse.]
So: a better thumbnail definition of impredicativity would be along the following lines

A definition of an object $X$ is  impredicative if it quantifies over a collection $Y$ to which $X$ itself belongs.

Some impredicative definitions seem fine -- e.g. "the tallest man in the room" picks out an object by a quantification over men in the room, including the tallest one. Other impredicative definitions look more problematic. A famous troublesome case is the Russell set -- which we try to define by quantifying over all sets including, supposedly, the Russell set itself.
And a better thumbnail definition of recursion might say something like this

A recursive procedure or function is one that can call the results of its own previous application.

So for example, we define the exponeniation function over the naturals recursively in terms of a prior application of the same function as when we write $x^{y + 1} = x^y * x$. We define the well-formed formulae of a formal language by clauses like 'if $\alpha$ is a wff, so is $\neg\alpha$', so the wff-forming procedure can call the outputs of previous rounds of wff-formation.
We can now see these are very different ideas. Defining a class of widgets by recursion involves thinking of it as built up, stage by stage, by repeated application of some procedure (where we can feed back the results of earlier applications into another application of the procedure). It is the very paradigm of a constructive idea: we go, by recursive steps, to the constructed class. On the other hand, picking out $X$ from a totality of widgets by an impredicative definition goes in the opposite direction, we go from the totality to one of its members -- we have to think of the widgets as already somehow given to us, and then we then pick out $X$ by reference to that totality, and that might be very non-constructive.
Comment: It would be nice if someone could give example definitions in formal logic to see the difference between these two types of definition.


Focus Follows Mouse on MacOS

Question: PROBLEM: how to implement focus follow mouse for all windows / apps on MacOS?
CONTEXT: terminal commands such as "defaults write com.apple.terminal FocusFollowsMouse -string true" implement the desired behavior ONLY for terminal windows.
SIMILAR POST: Implement "Mouse Follows Focus" on MacOS
Answer: This is the answer: https://github.com/sbmpost/AutoRaise
Works perfectly.
For the precise, classic behaviour of "focus follows mouse", without raising the window, it must be compiled with the suggested flags
<code>make CXXFLAGS="-DOLD_ACTIVATION_METHOD -DEXPERIMENTAL_FOCUS_FIRST" && make install
</code>
and then run with the options:
<code>/Applications/AutoRaise.app/Contents/MacOS/AutoRaise delay=0 focusDelay=1
</code>
Comment: "it" refers to the tool AutoRaise, which must be compiled with command in the answer.
make is a tool for automated building and the "flags" mentioned are just parameters passed to make (i.e., CXXFLAGS="-DOLD_ACTIVATION_METHOD -DEXPERIMENTAL_FOCUS_FIRST") to configure the build process.
Comment: @Addlai, you OK there, bud? ;)
Comment: AutoRaise now has a built-in option to focus on hover (with option to set delay as well) without raising the window
Comment: What do "the window" and "it" refer to in the sentence 'For the precise, classic behaviour of "focus follows mouse", without raising the window, it must be compiled with the suggested flags'? The only 'make' command I'm familiar with is for automating build processes in software development. I have no idea what this answer is talking about.
Answer: Yabai Window Manager also has an autofocus implementation, along with window borders and other features. It may be overkill for this specific use case, but for people looking for this feature because they came from another TWM it may be helpful.
Answer: Note for users with Case Sensitive file systems (like many of us) the command should be
defaults write com.apple.Terminal FocusFollowsMouse -string YES
note the "T" in terminal.  Otherwise terminal will ignore the setting.  Also in Monterey I used Xcode to edit the plist and found that  FocusFollowsMouse was already present but as a boolean and not a string.  The entry must have type string with value YES to work properly.
Once the above changes were made terminal worked with FocusFollowsMouse on my new M1 MacBook Pro with Monterey.
Answer: This is what I use successfully on Mojave and Big Sur on an M1 Mac:
defaults write com.apple.terminal FocusFollowsMouse -string true
Comment: This doesn't work for all applications but I've found the answer: https://github.com/sbmpost/AutoRaise

Focus Follows Mouse on MacOS


Reset Drupal 7 Site: NIDs, Revision VIDs, Taxonomy Term and Categories, etc

Question: Is there a way to keep an entire Drupal 7 site intact, excluding content?
Basically after creating a test environment with many nodes, terms, revisions, etc, I would love to be able to delete all the content/taxonomy and have the IDs reset as well.
Thanks in advance for any help.
Answer: Delete all module does what you want :)

This module is used to delete all content and/or users from a site.
  This is mainly a developer tool, which can come in handy in several
  cases, listed below.
Comment: Awesome. Thank you for the quick reply. I can't believe I wasn't aware of this module!


Callback when all ajax is loaded

Question: i have this code
var chapterNameArr = ['firstchapter','secondchapter','thirdchapter','fourthchapter','fifthchapter','sixthchapter','seventhchapter'];

$.each(chapterNameArr, function( index, value ) {

    var $chapterCont = $("#"+value);

    $.ajax({
      url: "scripts/templates/"+value+".html",
      cache: false,
      success: function(data){
        var $data = $(data);
        $chapterCont.append($data);
      }
    });

});

I want to execute a function when all content from ajax calls are successfully loaded. How do I do that ?
Comment: Keep track of what is loaded in your `success` handler.
Answer: The proper way to invoke a callback once multiple requests are done, is to use jQuery $.when function:
http://api.jquery.com/jquery.when/
I really suggest you read through the documents regarding this function
and the 'deferred' concept ( http://api.jquery.com/Types/#Deferred )
Should be something like this ( just as an example )
var chapterNameArr = ['firstchapter','secondchapter','thirdchapter','fourthchapter','fifthchapter','sixthchapter','seventhchapter'];
var pendingAjax = []

$.each(chapterNameArr, function( index, value ) {

    var $chapterCont = $("#"+value);

    var ajax = $.ajax({
      url: "scripts/templates/"+value+".html",
      cache: false,
      success: function(data){
        var $data = $(data);
        $chapterCont.append($data);
      }
    });

    pendingAjax.push(ajax)
});

$.when.apply($, pendingAjax).done( successCallback ).fail( failCallback)

Answer: $.active returns the number of active Ajax requests. Use $.active==0 means no ajax requests are active. You could also use ajaxStart and ajaxStop to keep track of when requests are active
Code :
var ajaxRequestsTimer = setInterval(isAjaxRequestsCompleted, 10000);

function isAjaxRequestsCompleted(){
    if($.active == 0) {
        clearInterval(ajaxRequestsTimer);
        $(document).trigger('ajaxRequestsCompleted');
    }
}

$(document).on('ajaxRequestsCompleted',function(){
    // insert the code here to execute after all ajax requests completed

})

Comment: Thanks but can you explain with code please ? Not sure I understand
Comment: i updated my answer with code. Check it and let me know

Callback when all ajax is loaded


How to put the result from a column in the top of the result?

Question: I have this sql:
SELECT x, y FROM table WHERE x = 'a' OR y = 'a'

In the result it will show something like this:
NOTE: the letters bellow represents the value returned from the column x and y.
a = x
b  = y
a
b
b
a
b

I want to get the results from the column x first. Like this:
a
a
b
b
b

Is it possible? The only way i found was to make two sql for both column and then use UNION;
Answer: You can use conditional logic in the group by:
SELECT x, y
FROM table
WHERE x = 'a' OR y = 'a'
ORDER BY (x = 'a') DESC;

MySQL treats a boolean value like an integer, with 0 for false and 1 for true.  Hence the DESC so the true values are first.
Answer: Below answer is considering you are using SQL Server.
SELECT x FROM table WHERE x = 'a'
union all
SELECT y FROM table WHERE y = 'a'
order by 1

in the order by clause, 1 represents first column. Alternatively you can replace it with column name.


Sorting non-english characters in multilingual website

Question:
I'm having an issue with finding good approach to make sorting works
  in a Drupal Views.
I've multilingual website (1 database for all languages). Few
  languages are sorted wrong.
I've read that the real issue is on database layer, however I can't set
  any specific encoding there, since database contains many different
  languages.
What would be the most correct approach to make sorting works?
  The minimum I need atm is a sorting in a Drupal Views.

Any good approach of solving such issues?
Comment: I think that until you've sorted out things on the db layer, this question is going to be off-topic. Check what encoding you currently have on your db, and do some research on that topic. Then you can move the focus to "How can I get Views to handle X as Y", which would be on-topic.
Comment: @letharion I agree, that 'right' solution must be done on db layer, however I think it is to late (I would be happy to be wrong), since we have only 1 database for all languages for almost 1 year. What would you recommend me to do in such case?
Answer: It may help to somebody.
I end up with doing a simple module (which I'm gonna improve later) that inject COLLATE while doing query to Database so it sort everything properly.
Please feel free to comment this solution :)
<code><?php

/**
 * @file
 * Implements hook_views_query_alter().
 *
 * it adds 'COLLATE utf8_language_ci' to languages that are not supported by default
 * so far there are only few languages we have issues with.
 */
function views_collate_sorting_views_query_alter(&$view, &$query) {
  // views where we want to enable collation
  $views = array(
    'dictionary_overview'
  );

  // exit if the current view is not specified
  if (!in_array ($view->name, $views)) {
    return FALSE;
  }

  // define list of languages we support
  $map = array(
    'da' => 'utf8_danish_ci',
    'sv' => 'utf8_swedish_ci',
    'nb' => 'utf8_danish_ci',
    'es' => 'utf8_spanish_ci',
    'pl' => 'utf8_polish_ci',
  );

  // get current utf8
  $l = $GLOBALS['language']->language;

  if (!array_key_exists ($l, $map)) {
    return FALSE;
  }

  // get current utf8 language which we are going to add to all sort fields
  $utf8 = $map[$l];

  // add COLLATE utf8_xx_ci to all sort criteria
  $orderby = &$query->orderby;
  foreach ($orderby as &$order) {
    $order['field'] .= ' COLLATE ' . $utf8;
  }
}
</code>


Configure postfix to use Google Apps SMTP relay in a Google Compute Engine instance

Question: What are the steps to set up postfix as SMTP relay that uses the Google Apps SMTP relay. There are a bunch of tutorials on the web that explain how to use the smtp.gmail.com gateway with SASL authentication but I could not find a working configuration for the Google Apps relay smtp-relay.google.com as described here, especially one that is specific to Google Compute.
I have setup the smtp relay service with 'Only addresses in my domains' as described here and verified that the IP is in fact the one I connect from.
I know that Google compute does not allow Port 25 as outgoing port as described here.
I am using debian linux or a debian derivative.
I have setup postfix as detailed in the docs but all i get in the mail.log is:
postfix/smtp[720]: send attr reason = host smtp-relay.gmail.com[22.214.171.124] said:
550-5.7.1 Invalid credentials for relay [188.8.131.52]. The IP address you've
550-5.7.1 registered in Google Apps SMTP Relay service doesn't match domain of
550-5.7.1 the accountthis email is being sent from. If you are trying to relay
550-5.7.1 mail from a domain that isn't registered under your Googles Apps
550-5.7.1 account or has empty envelope-from, you must configure your mail
550-5.7.1 server either to use SMTP AUTH to identify the sending domain or to
550-5.7.1 present one of your domain names in the HELO or EHLO command. For
550-5.7.1 more information, please visit
550 5.7.1  https://support.google.com/a/answer/6140680#invalidcred kg2sm505213wjb.4 - gsmtp (in reply to MAIL FROM command)

Answer: Install postfix with apt-get install postfix.
When asked select "satellite system" or the option with smarthost. Accept the defaults of everything else for now.
Edit your main.cf according to the following file:
/etc/postfix/main.cf
# a file which should contain the google apps domain
myorigin = /etc/mailname
# if your google apps domain is in mydestination, remove it, or postfix will attempt to deliver your mail locally
mydestination = ...., localhost

# Google Apps Relay SMTP, must use Port 587 because, 25 is blocked
relayhost = [smtp-relay.gmail.com]:587

# Force ehlo behavior
smtp_always_send_ehlo = yes
smtp_helo_name = <yourappsdomainhere>

# Enable TLS
smtp_use_tls=yes
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

# limit smtp to loopback interface & compute engine doesn't support ipv6
inet_interfaces = loopback-only
inet_protocols = ipv4

# These lines can be used, if the result is not as expected
# debug_peer_list = smtp-relay.gmail.com
# debug_peer_level = 2

Restart postfix with service postfix restart. All should be good.
This may not be the cleanest all all solutions, but it works for me.
Comment: My emails were sended from something like "email@example.com". I created a "/etc/postfix/generic" file that mapped "email@example.com" to "firstname.lastname@example.com" (the one I have configured within G Suite" and added a line containing "smtp_generic_maps = hash:/etc/postfix/generic" to my postfix configuration file and after running "sudo postmap /etc/postfix/generic" and "sudo service postfix restart" it worked.
Comment: This has worked for me half. I am now able to send mail from my command line with `echo "body of your email" | mail -s "This is a Subject" -a "From: firstname.lastname@example.com" firstname.lastname@example.com`, but when I am trying to send mail with PHP mail() function, I get a message in my mail.log file which says: "Invalid credentials for relay". Do you know how to fix this?
Comment: hm make sure that you can send email via `sendmail` command from the cli. Then check your php.ini, php should send mail via sendmail. Check whether php sends email with a correct sender address (meaning the sender must be compliant with the allowed senders that your configured in your google apps cpanel).
Comment: Thanks for you quick comment. I searched further and found the "better" way of doing it. The way with the authentication. If you are interested, I could share the summary I wrote about it.
Comment: I'd say that depends on your solution. This question is about the SMTP relay functionality. If you authenticate as a regular user the solution is quite simple and also much more restricted. If you have a different approach using the smtp relay I'd be very interested in your solution.
Comment: Check my answer, hopefully it is helpful for you!
Comment: I get this error: "The IP address you've 550-5.7.1 registered in your G Suite SMTP Relay service doesn't match domain of 550-5.7.1 the account this email is being sent from. If you are trying to relay 550-5.7.1 mail from a domain that isn't registered under your G Suite account 550-5.7.1 or has empty envelope-from, you must configure your mail server 550-5.7.1 either to use SMTP AUTH to identify the sending domain or to present 550-5.7.1 one of your domain names in the HELO or EHLO command."
Answer: I have searched the internet for a few days to find the solution which you and I were looking for.
Be sure you have set the SMTP relay settings under Apps > Google Apps > Gmail > Advanced settings in your Google Apps account as follows:

Be sure you have installed postfix and libsasl2-modules.
sudo apt-get update
sudo apt-get install postfix
sudo apt-get install libsasl2-modules

Postfix configuration
During the Postfix configuration set the following settings:

General type of mail configuration: Internet with smarthost.
Mail name: example.com (fully qualified domain name)
Relay host: [smtp.gmail.com]:587

Your /etc/postfix/main.cf file should look like this:
myhostname = yourdomain.com
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases

myorigin = /etc/mailname
mydestination = yourdomain.com

relayhost = [smtp.gmail.com]:587
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all

# Use IPv4 protocol
inet_protocols = ipv4

# enable SASL authentication
smtp_sasl_auth_enable = yes

# disallow methods that allow anonymous authentication.
smtp_sasl_security_options = noanonymous

# where to find sasl_passwd
smtp_sasl_password_maps = hash:/etc/postfix/sasl/passwd

# Enable STARTTLS encryption
smtp_use_tls = yes

# where to find CA certificates
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Create a /etc/postfix/sasl/passwd file and add your Google Apps username and password as follows:
[smtp.gmail.com]:587 email@example.com:yourpassword

Now create the hash db file for Postfix by running the postmap command:
sudo postmap /etc/postfix/sasl/passwd

Secure your Password and Hash Database files so that only root could read and write them:
sudo chown root:root /etc/postfix/sasl/passwd /etc/postfix/sasl/passwd.db
sudo chmod 0600 /etc/postfix/sasl/passwd /etc/postfix/sasl/passwd.db

Restart Postfix by:
sudo /etc/init.d/postfix restart

If you have installed mailutils you could test sending mails by:
echo "body of your email" | mail -s "This is a Subject" -a "From: email@example.com" firstname.lastname@example.com

If your mail is not received, check your mail.log file for any error messages:
sudo tail -f /var/log/mail.log

I have written a more detailed article: http://dev.robbertvermeulen.com/postfix-google-apps-smtp-relay-google-compute-engine/
Comment: I'm not sure you're actually using the smtp relay. It looks like you're simply using smtp with user authentication (something i wanted to avoid in my setup). You could test it by removing the relay settings in the cpanel and see if it still works - it shouldn't, but if I'm right it will.
Comment: I confirm what @konqi said. You are using Gmail SMTP server (smtp.gmail.com) and not the G suite SMTP relay (smtp-relay.gmail.com). You can see the difference [here in Gmail documentation](https://support.google.com/a/answer/176600?hl=en).


Where is it documented that fields included in the entity_keys are 'required' regardless of the required property value in the field definition?

Question: I've created a custom entity. One of the fields I've added is an entity reference field that was created calling BaseFieldDefinition::setRequired(FALSE). When I installed my module and tried to add a new instance of my custom entity, I got an error when that field was not set, even though it was defined as not required.
For reference, this is the field definition I'm using.
$fields['publisher'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Publisher'))
  ->setRequired(FALSE)
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings', array(
    'target_bundles' => array(
      'publisher' => 'publisher'
    ),
    // 'sort' => array(
    //  'field' => 'name'
    // )
  ))
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'title' => t('Pubs'),
    'type' => 'options_select',
    'weight' => 4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

This is the error I got.

Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity
constraint violation: 1048 Column 'publisher' cannot be null: INSERT
INTO "series"...

The database table for this custom entity contains the following fields.

It's evident that, even though this field has been created calling setRequired(FALSE), it must be set.
To solve this issue, I found that I can manually update my database table's properties so that the field's 'Null' property is set to 'Yes', though this is clearly not a preferred approach.
Then I found How do I allow an entity reference to be null in my custom entity? where one of the answer states that fields included in the entity_keys annotation must be set, regardless of the value set with setRequired().
Where is this kind of information documented?
This isn't documented in Creating a content entity type in Drupal 8. In fact, I had the impression it was mandatory to list all the fields in this annotation array.
Answer: The Drupal documentation - as the Drupal source code itself - has been provided by the contribution of the Drupal developer community. You will find, that it oftentimes isn't 100% complete nor up-to-date, as many of the developers ensure that code is working and more or less documented in the source code, but neglect the online documentation a bit while going on solving other issues or implementing different features. The documentation you mentioned even has a banner stating

This documentation needs work. See "Help improve this page" in the sidebar.

An experienced Drupal developer "just knows" such details from previous encounters with similar issues. If not sure, such a developer would also search the Drupal code base to see how the properties are used. Thanks to generally applied coding standards, extended source code documentation, and search features of modern IDEs, it's quite easy to read the Drupal code for any PHP developer; even easier for those that work with Drupal on a daily base.
If the source code doesn't offer answers, this StackExchange group or using a proper search engine may help to answer some Drupal questions relatively quick as well. The best explanation I found using a simple search is a citation from Daniel Siphos excellent "Drupal 8 Module Development" book:

Entity keys
The entity API defines a set of keys that are consistent across all entity types and by which common entity information can be retrieved. Since not all entity types need to have the same fields for storing that data, there is a mapping that can be done in the annotation for these

Which means, that the annotation property entity_keys is there to translate commonly used properties of entities (such as their ID, label or bundle) to their corresponding database fields that may be named differently for any entity type (e.g., nid/pid/..., title/name/..., type/variant/...). This allows the entity API to define common getter methods like ::id(), ::getLabel() or ::bundle() that can be used throughout the entire Drupal application in entity listing classes, the fields API, condition plugins, and so on, and therefore shouldn't be empty.
If you ever encounter a piece of Drupal documentation that appears to be incomplete, is missing cruicial information, or lacks information that the original contributors of the documentation page didn't deem worth mentioning, you can

Log in, click Edit, and edit this page
Log in, click Discuss, update the Page status value, and suggest an improvement
Log in and create a Documentation issue with your suggestion

(Shamelessly copied from the sidebar of beforementioned article in the Drupal documentation. ;)
Comment: Thank you for the in depth response. I had a feeling this was a tribal knowledge detail that just happened to be not so easy to gleam from the standard docs or the codebase commenting for the lesser experienced, like myself. Glad to know at least that I'm using the right resources. In the end it was starting this question that led to the answer on this forum. Also thanks for the tip on how to help improve the documentation when I find details like this difficult to interpret, I'll definitely try to do that.
Answer: There isn't any documentation about that.
In SqlContentEntityStorageSchema::getSharedTableFieldSchema(), there is the following comment. (The relevant part is For now, we only hardcode 'not null' to a few "entity keys", in order to keep their indexes optimized.)
// A shared table contains rows for entities where the field is empty
// (since other fields stored in the same table might not be empty), thus
// the only columns that can be 'not null' are those for required
// properties of required fields. For now, we only hardcode 'not null' to a
// few "entity keys", in order to keep their indexes optimized.
// @todo Fix this in https://www.drupal.org/node/2841291.

Fix NOT NULL handling in the entity storage and 'primary key' changes when updating the storage definition of an identifier field has been opened to remove the code that mark as NOT NULL some of the entity keys given for an entity type.
As a side note, the current workaround isn't to manually edit the database schema, but to override the getSharedTableFieldSchema() method implemented by the entity storage_schema handler.
This is what done by the File entity type, for example.
handlers = {
  "storage" = "Drupal\file\FileStorage",
  "storage_schema" = "Drupal\file\FileStorageSchema",
  "access" = "Drupal\file\FileAccessControlHandler",
  "views_data" = "Drupal\file\FileViewsData",
},
base_table = "file_managed",
entity_keys = {
  "id" = "fid",
  "label" = "filename",
  "langcode" = "langcode",
  "uuid" = "uuid",
  "owner" = "uid",
}

Drupal\file\FileStorageSchema::getSharedTableFieldSchema() contains the following code.
// Entity keys automatically have not null assigned to TRUE, but for the
// file entity, NULL is a valid value for uid.
if ($field_name === 'uid') {
  $schema['fields']['uid']['not null'] = FALSE;
}
return $schema;

Comment: "more or less documented in the source code" ;)
Comment: I know, it's not the best way.


Use administration theme for verified users when adding or editing content

Question: I'm having a problem with the administatration theme. I want verified users to see the administration theme when they are adding or editing content. Right now only the admin user sees the administration theme and verified users see the standard theme. Is it possible to also enable this for verified users?
Thanks!
Answer: Enable View the administration theme permission for verified/authenticated users.


Showing a module over $C[0,1] $ is not free

Question:
Define $R:= \lbrace f \in C [0,1] \mid f(0)=f(1) \rbrace$, $V:= \lbrace f \in C [0,1] \mid f(0)=-f(1) \rbrace$.
$V$ is an $R$-module. I have no idea how to show it is not free.

I have tried to construct some function that hope can show $V$ has no independent set, but I find it hard to show it is continuous such that belongs to $R$.
Is there any  other way to show $V$ is not free?
Thanks in advance!
Comment: This is a fun example...
Comment: Moreover, one can show that $V\oplus V\simeq R\oplus R$.
Answer: If $f_1,f_2\in V$, then we have $(f_2^2)f_1-(f_1f_2)f_2=0$, so every two elements of $V$ are linearly dependent. Suppose that $V$ is free. Then $V$ is cyclic, that is, $V=Rf$. Since $f(0)f(1)\le0$ it follows that $f$ vanishes at a point $a\in[0,1]$. On the other side, $V$ contains functions that don't vanish at $a$.
Comment: Wow, so this example also involves some basic knowledge from analysis, that was fun! Thanks for your help


Fading multiple divs with JS

Question: I have two or in future may be more divs with background images in css. I would like to fade them in and out in a loop.
I am trying to do something like this but it doesn`t work.

$(window).load(function(){
var divs = $('.fade');

function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;

    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }

    var next = divs.eq(nextIndex);

    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });

    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();
#one {
   background-image: url("Test_bg.jpg");
margin-top: -150px;
min-height: 100%;
background-attachment: fixed;
}

#two {
   background-image: url("Test_bg1.jpg");
margin-top: -150px;
min-height: 100%;
display: block;
background-attachment: fixed;
}

Answer: You are mising }) at the end with causes syntax error

$(window).load(function(){
var divs = $('.fade');

function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;

    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }

    var next = divs.eq(nextIndex);

    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });

    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();
})
#one {
  color: red
}

#two {
  color: blue
}

a

b

Fading multiple divs with JS


Multiple Python installations on Windows - when were they last used?

Question: We have a few Windows machines that have multiple Python installations on them, for various reasons. Who doesn't love legacy systems?
In a bit of a clean up effort, I'd like to attempt to figure out which ones are actually in use. As far as I can see, I have two options in this:

Go through all the products manually and see what paths they reference
Find some kind of indicator of use, so I can script this task and keep my sanity

I'm somewhat attached to my sanity, so the second option is definitely my preference.
I'm aware that there are plenty of places that someone might have installed Python, so I'll be attempting to cover these off to find individual Python installations before then trying to confirm if they're in use or not.
Has anyone had to do something similar in the past and found a 'use indicator' of a specific Python installation?
Answer: Look into system variables for anything python related and: Anaconda and virtual env.
https://docs.python.org/2/using/windows.html
At installation python updates some sys env variables and on top of that virtual envs can be used https://docs.python-guide.org/dev/virtualenvs/ . If the the python installation directory there is a pip installation that can also help :)
Comment: I appreciate the pointers, but these are the bits I know about. I guess the question could be better phrased without the use of Python, how can you tell the last execution time of a .exe?
Comment: There should be some traces inside Application or system log if the exe logs there, you can go ahead and filter them for the specific .exe. There are additional traces in the %APPDATA% folder and so on, but for that you will need a full forensics look at it and I don't know if it's worth it


Akka actor testing

Question: Since I am currently writing Testcases for my Akka application (http://doc.akka.io/docs/akka/snapshot/scala/testing.html) I was wondering if there is a way to test the interface of an actor. What I mean with that, is that I 'd like to check if the receive method of a target actor handles a message A or no. Imagine the following scenario:
Actor A can handle message b and c. Actor B wants to send mesage b and a to actor A. To ensure that this works out nice, I would like to write a test case that ensures that actor A is processing messages a and b.
Answer: It depends on what you want to test.
Since the receive method is a PartialFunction, you can do isDefinedAt tests like so:
$ sbt test:console
scala> import akka.actor._
scala> import akka.testkit._
scala> class MyActor extends Actor {
         def receive = {
           case n: Long => println("Got %d".format(n))
           case s: String => println("Got %s".format(s))
         }
       }

scala> implicit val system = ActorSystem()
system: akka.actor.ActorSystem = akka://default

scala> val myActor = TestActorRef[MyActor]
myActor: akka.testkit.TestActorRef[MyActor] = TestActor[akka://default/user/$$a]

scala> val underlying = myActor.underlyingActor
underlying: MyActor = MyActor@365d7762

scala> underlying.receive.isDefinedAt(123L)
res0: Boolean = true

scala> underlying.receive.isDefinedAt("banana")
res1: Boolean = true

scala> underlying.receive.isDefinedAt(true)
res2: Boolean = false

scala> underlying.receive.isDefinedAt(123)
res3: Boolean = false

scala> underlying.receive.isDefinedAt(null)
res4: Boolean = false

scala> system.shutdown()

Comment: A team member of mine posted a followup question to this one: http://stackoverflow.com/questions/21725473/creating-a-testactorref-results-in-nullpointerexception

Akka actor testing


How to enable VT extensions on a Dell inspiron 1545

Question: I am trying to install a centos virtual host on my ubuntu laptop but I cannot enable the VT extensions in the BIOS.
I have updated to the latest BIOS from Dell the processor is a core 2 duo so it definitely supports the VT extensions.
Any ideas?
Answer: Which Core 2 Duo? Not all Core 2s have the VT extensions.
JR
PS See http://www.intel.com/products/processor_number/chart/core2duo.htm for a list of which Core 2's support VT.
Answer: Some vendors, like Sony, for my Vaio, disable Intel VT and do not provide a BIOS option to turn it on, even though the processor supports it fine. I managed to enable it on my Vaio, but not without a serious amount of research, luck and trouble.
If there is not option in your BIOS and you are sure your specific Core2Duo supports VT, complain at Dell Support and / or hope someone was able to binary patch your BIOS. I was lucky with the last option. Maybe there is such a patch for your BIOS too.
UPDATE: According to post in this thread the T6400 and T5800 does not support Intel VT. One of those is - according to Google - the processor in your laptop...
Comment: Agreed wzzrd, as far as I can tell none of the processors available on that model support hardware virtualisation.
Comment: thanks for the info I did not know that my processor did not support the extension I wrongly assumed all core 2 duos had the extension
Answer: You can check the processor flags using cpuinfo or grep "vmx" /proc/cpuinfo | uniq


I get the following error in console when I try to install python-espeak

Question: ERROR: Command errored out with exit status 1:
     command: 'C:\Users\carli\AppData\Local\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\carli\\AppData\\Local\\Temp\\pip-req-build-pw2vgo81\\setup.py'"'"'; __file__='"'"'C:\\Users\\carli\\AppData\\Local\\Temp\\pip-req-build-pw2vgo81\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\carli\AppData\Local\Temp\pip-record-47y3xo5u\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\carli\AppData\Local\Programs\Python\Python310\Include\python-espeak'
         cwd: C:\Users\carli\AppData\Local\Temp\pip-req-build-pw2vgo81\
    Complete output (17 lines):
    running install
    C:\Users\carli\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
      warnings.warn(
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.10
    creating build\lib.win-amd64-3.10\espeak
    copying espeak\__init__.py -> build\lib.win-amd64-3.10\espeak
    running build_ext
    creating build\temp.win-amd64-3.10
    creating build\temp.win-amd64-3.10\Release
    creating build\temp.win-amd64-3.10\Release\espeak
    "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Users\carli\AppData\Local\Programs\Python\Python310\include -IC:\Users\carli\AppData\Local\Programs\Python\Python310\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\cppwinrt" /EHsc /Tpespeak/espeakmodulecore.cpp /Fobuild\temp.win-amd64-3.10\Release\espeak/espeakmodulecore.obj
    espeakmodulecore.cpp
    espeak/espeakmodulecore.cpp(23): fatal error C1083: No se puede abrir el archivo incluir: 'espeak/speak_lib.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'C:\Users\carli\AppData\Local\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\carli\\AppData\\Local\\Temp\\pip-req-build-pw2vgo81\\setup.py'"'"'; __file__='"'"'C:\\Users\\carli\\AppData\\Local\\Temp\\pip-req-build-pw2vgo81\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\carli\AppData\Local\Temp\pip-record-47y3xo5u\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\carli\AppData\Local\Programs\Python\Python310\Include\python-espeak' Check the logs for full command output.

Comment: https://stackoverflow.com/questions/50607994/installing-espeak-using-pip-in-python-3-6
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Do you have espeak installed? The python package you're trying to install is a wrapper, meaning it allows you to use the espeak functionality from within python.
Once you have espeak installed, make sure it's included in your PATH environment variable.
If python-espeak installation still doesn't work, there are more espeak wrappers available that may have been better maintained. Look here: https://github.com/espeak-ng/espeak-ng/
Answer: python-espeak is a just a wrapper for it to work in python, so you need to have espeak installed and in your PATH variable for this to work.
https://github.com/espeak-ng/espeak-ng/blob/master/docs/guide.md
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31304638)


A biblioteca  faz parte do padrão ANSI C?

Question: Estava procurando como trabalhar como números grandes em e encontrei um blog que fala que era possível trabalhar utilizando a biblioteca ,  queria saber se ela faz parte do padrão ANSI C ?
Comment: Não. Ela está instalada em algum lugar reconhecido pelo compilador como padrão, mas não pertence ao padrão da linguagem.
Comment: biblioteca padrão para trabalhar com grandes números? Não tem não. Toda implementação de `BigNumber` ou `BigInteger` que eu conheça utiliza uma biblioteca de terceiros para tal.
Comment: Mas bibliotecas para isto, não pegar uma que faz outra coisa que tem por acaso algo que faça o que deseja, mas não seja o objetivo dela :)
Comment: Vixe, queria trabalhar com números grandes e essa biblioteca tinha resolvido mas, não vou poder utilizar ela, teria outra biblioteca que seja padrão para trabalhar com números grandes ou um código que faça esse trabalho
Comment: Alguma em específico ? Recomenda algum material para resolver meu problema ?
Comment: Considerando que o OpenSSL tem uma licença até que conveniente, e tem para praticamente qualquer plataforma, provavelmente poderia continuar usando essa mesma. Agora, se usa OpenSSL só pra isso, como o @Maniero mencionou, uma alternativa dedicada talvez seja mais interessante. Por outro lado, se a aplicação usa OpenSSL, use o que já tem.
Answer: As bibliotecas padrões não fornecem suporte para operações aritméticas com valores de mais de 64 bits.
Operações com números inteiros grandes podem ser feitas com a utilização de uma biblioteca da GNU chamada gmplib.
Segue um exemplo onde os dois argumentos (inteiros grandes) passados para a main() são multiplicados e seu resultado exibido na tela:
#include <gmp.h>
#include <stdio.h>

#define MAX_BUF_LEN    (128)

int main( int argc, char * argv[] )
{
    char res[ MAX_BUF_LEN ];

    mpz_t a, b, c;

    mpz_init(a);
    mpz_init(b);
    mpz_init(c);

    mpz_set_str( a, argv[1], 10 );
    mpz_set_str( b, argv[2], 10 );

    mpz_mul( c, a, b );

    mpz_get_str( res, 10, c );

    printf("%s\n", res );

    mpz_clear(a);
    mpz_clear(b);
    mpz_clear(c);

    return 0;
}

compilando:
$ gcc -lgmp -Wall bigintmul.c -o bigintmul

Testando:
$ ./bigintmul 1234567890123456789012345678901234567890 9876543219876543219876543219876543210

Saída:
12193263124676116335924401657049230176967230591384377380136092059011263526900

Checando:
Comment: Importante o autor verificar se a licença da lib recomendada permite o uso onde ele precisa. Provavelmente seria bom mencionar também alguma alternativa com licença MIT ou BSD.


Diagnosing Unresponsive Windows Service

Question: I have seen this happen on occasion on our Windows 2008 servers running in AWS EC2 where we have Windows Service which becomes unresponsive. I am not able to find anything in the event logs, or a crash dump. Any ideas, or advice on how to go about diagnosing the root cause of these failures? I have access to the C# source code of the services, but they are not logging any exceptions.
Comment: How do you **know** the services are unresponsive? If you have additional information on why you think the services are unresponsive, could you post that information in your question?
Comment: I know that the service is unresponsive because incoming requests will time out. When I go to the services administrator, the service shows as "Running", however I am unable to restart, or stop the service. I have to actually kill the process in order to restart it.
Answer: I think your best bet would be to involve the AWS Developer Forums by posting your issue or by contacting AWS Support. I can give you a few basic suggestions.
Outdated drivers
There is a post where a user had a issue with a dump file he was unable to understand and he was recommended to list third party drivers that seem to have led to the instance crashing in this post EC2 instance crashing/dumping.
The command pnputi -e lists all third-party drivers and maybe this is your issue too.

Pnputil.exe is a command line utility that you can use to manage the driver store. You can use Pnputil to add driver packages, remove driver packages, and list driver packages that are in the store.
 (Microsoft TechNet)
PNPutil.exe Webpage
The post then goes on to mention that there were possibly outdated drivers installed, which would have to be updated.
Modify Source Code
Seeing as you have the C# source code for the service, you could go ahead and modify the code to create entries in a log file at certain points in the code. Adding a timestamp to the output will help pinpoint your issue.
Resources
Could the service be consuming to much resources on the AWS instance? See if the service is consuming to much memory or processor time. This could result in the service becoming unresponsive.
Contact AWS Support
Post your issue in the Sub-Forum that best matches your issue in the Discussion Forums > Category : Amazon Web Services
Without further details, it's hard to provide you with a solution on how you could go about fixing your problem. You have to have some data to go from to produce a solution.

Diagnosing Unresponsive Windows Service


Returning function variable error ~local variable 'user' referenced before assignment~, Python

Question: I've written a function and I wanted to return a variable from that function, but I keep getting an error
local variable 'user' referenced before assignment
My function is:
    def txtelm():

    # Updates date field to the current date
    if textElement.name == "DATE":
        textElement.text = strftime("%y %m %d")

    if textElement.name == "CHECK":
        textElement.text = "AB"

    # First code block replaces the "Drawn" title block initials
    if docauthor == "Mike" and textElement.name == "DRAWN":
        textElement.text = "MM"
        user = "mm"
        #print user

    elif docauthor == "Amy" and textElement.name == "DRAWN":
        textElement.text = "AB"
        user = "ab"
        #print user

    elif docauthor == "Ian" and textElement.name == "DRAWN":
        textElement.text = "IB"
        user = "ib"

    elif docauthor == "Chris" and textElement.name == "DRAWN":
        textElement.text = "CM"
        user = "cm"

    elif docauthor == "Cynthia" and textElement.name == "DRAWN":
        textElement.text = "CC"
        user = "cc"

    return user

Further down my code, I call the function:
for textElement in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        txtelm()
        user = txtelm()
        if textElement.name == "PATH":
        textElement.text = outloc + "\\" + sitename.replace(" ", "_") + "_" + trunc + strftime("%d%b%y") + "_" + user

I set some print messages to print 'user', but it doesn't seem to be returning anything. Before I created the function I had the code within it, hardcoded below the 'for loop' and it worked....so I'm stumped as to why it's not returning any values.
Any suggestions?
Comment: marginally easier to read text formatting: `textElement.text = os.path.join(outloc, "%s_%s%s_%s" % (sitename.replace(" ", "_"), trunc, strftime("%d%b%y"), user))`
Answer: Your function takes no arguments, but uses a variable 'textElement'. You need to define your function thus:
txtelm(textElement):

and call it thus:
user = txtelm(textElement)

The the value of textElement from the loop code will be passed into the function.
I'm not sure what the first call to txtelm() is for - it doesn't seem to be doing anything.
Edit:
I spoke too soon - there are several problems here. First the above, then the definition of 'user': because each definition is within an 'if', when none of them match it won't be declared at all. Add:
user = ""

to the top of your function to prevent this.
Edit again: 'docauthor' also doesn't seem to be defined - perhaps it should be another argument to the function?
Comment: Ah yes, that's because your 'return' is outside of the scope of the declaration(s) of user. Per another answer, put 'user = ""' at the top of the function.
Comment: Python doesn't have block scope.
Comment: Thanks for all the input. I revamped my if else statement to if textElement.name == "DRAWN": if docauthor == "Mike": do the rest. This seemed to have cleared it up. docauthor is a user input varaible called at the beginning of the script. Sorry for the confusion on that.
Answer: I guess that none of your if/elif statements are true.
Comment: do a final `else` where you raise an `exception`. Like this.. `raise ValueError(docauthor, textElement.name)`
Answer: There's a a chance that user is never declared before trying to return it. Set user as an empty string at the start of txtelm()
def txtelm():
   user = ""

And then test if user is not empty
for textElement in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        txtelm()
        user = txtelm()
        if user == "":
           #handle the error


Qual código de status HTTP usar para indicar falha de validação?

Question: Quando um método em uma API web detecta que houve falha na validação dos dados de uma entidade a ser adicionada ou atualizada existe algum código HTTP que seja padrão de ser enviado? Por enquanto estou usando o código 400 (bad request), mas não sei se existe outro mais recomendado pra esse tipo de falha.
Comment: Essa pergunta é boa, mas acredito que seja baseada em opiniões devido ao fato das RFCs não serem claras nesse ponto, sendo possível haver várias interpretações, e, portanto, opiniões sobre qual é o código adequado.
Comment: O Pablo tem razão, mas acho que pode ter sim uma resposta específica baseada no consenso geral.
Answer: Sua pergunta é boa, mas, no entanto, acredito que ela seja baseada em opiniões. A escolha do código adequado deve ser feita em função do que estabelece a RFC em vigor. No entanto, como qualquer outra norma, nem sempre a RFC é clara, sendo possível interpretá-la de várias maneiras.
Segue as minhas considerações sobre as respostas já dadas e a minha opinião.
1. Em que e onde devo procurar fontes para perguntas como essa?
Em primeiro lugar, a RFC que diz respeito a isso e que está em voga no momento é a 7231. Se tiver familiaridade com inglês, sugiro que a leia para criar suas próprias opiniões também.
2. Sobre não utilizar código 200
Embora em algumas frameworks para web retornem 200 no caso de requisições com dados inválidos, não acredito que esse deva ser o código adequado.
De acordo com o item 6.3 da 7231, códigos 2xx indicam que a requisição do cliente foi recebida, compreendida e aceita.
Logo, se o objetivo de uma requisição POST é, por exemplo, criar um novo objeto no servidor e isso não é feito em função de dados inválidos, não considero que deva ser retornado o código 200 dizendo que a requisição foi um sucesso, mas sim um código que indique que algum erro ocorreu no processamento dos dados enviados.
3. Sobre utilizar o código 400
Se pensarmos que os dados enviados também fazem parte da requisição, se eles estiverem inválidos e, portanto errados, nada mais justo que retornar um código 400, que indica uma má requisição.
Definição do método POST
Olhando a definição do método POST na RFC fortalece essa ideia. De acordo com o item 4.3.3, uma requisição POST está pedindo para que um determinado recurso (ou resource) processe os dados presentes na requisição de acordo com a semântica do recurso. Logo, se você envia um dado que que não possui significado para servidor, a requisição não será entendida e não deverá ser processada.
Definição da classe 4xx e do código 400
Outro argumento para fortalecer o uso do código 400 é a definição da classe 4xx e sua própria definição:
A classe 4xx possui códigos para quando o cliente comete algum erro. Se você entende que o cliente é responsável pelo envio de dados válidos (e que a validação no servidor é feita por medida de segurança) 4xx parece ser a classe adequada. É importante notar que a classe 4xx, de acordo com a RFC, deve sempre retornar uma explicação do erro para o cliente.
O código 400, por sua vez, indica que o servidor não pode, não é capaz ou simplesmente não irá processar a requisição por erro do cliente (o erro de enviar dados que não possuem significado de acordo com o recurso solicitado).
É importante lembrar que a RFC não lista os erros que um cliente pode cometer, listando apenas alguns exemplos (erro de sintaxe é um deles).
4. Logo...
Concluindo, o cliente é responsável por enviar dados que façam sentido para o servidor, e, se não faz, isso deve ser considerado um erro do cliente. Portanto, sugiro que utilize o código 400 e, como previsto na RFC, envie uma mensagem explicando o erro, dizendo que os dados não são válidos.

Bônus: Métodos que definitivamente você não deve utilizar
418: não é um código presente na RFC em vigor e não possui nenhum valor semântico para validação de dados.
405: deve ser usado apenas quando o método da requisição não é aceito pelo servidor e não os dados em si.
Answer: Aviso de opinião
Essa resposta expressa a minha opinião e de maneira alguma representa uma interpretação oficial ou mais correta.
Erro 400
RFC 7321

The 400 (Bad Request) status code indicates that the server cannot or
     will not process the request due to something that is perceived to be
     a client error (e.g., malformed request syntax, invalid request
     message framing, or deceptive request routing).

O erro 400 significa que o servidor recusa-se a processar a requisição devido a um erro por parte do client-side e não há problema algum em usar ele. Eu, pessoalmente, prefiro manter ele para erros na requisição em si, e não para seus dados. Alguma bibliotecas podem enviar bug reports automáticos por padrão devido a essa resposta.

200 - OK
Você pode enviar a resposta como 200, informando que a requisição ocorreu com sucesso, o que é verdade. E então no conteúdo da resposta escrever se a API validou ou não e quais foram os erros. Essa é a opção que eu uso e recomendo, já que gosto de separar a requisição em si dos dados dela.
405 - Método não permitido
Acredito ser a segunda melhor opção, aqui vai a descrição oficial traduzida:

Foi feita uma solicitação de um recurso usando um método de pedido que não é compatível com esse pedido.

Exemplo: usando GET em um formulário, que exige que os dados sejam apresentados via POST.
418 - Eu sou um bule de chá
Esse status foi criado como uma pegadinha de primeiro de abril e é inutil, então acho que como ele não tem uso, você poderia atribuir um uso "especial" para ele.
Comment: A RFC 7231 não diz nada a respeito de low-level e tampouco lista os erros que um cliente pode cometer, apenas cita exemplos. Logo não há problema algum em utilizar o 400 conforme você sugere. Além disso, o cliente deveria garantir que os dados enviados para o servidor estão válidos. Dessa forma o sistema para reportar bugs automáticos continuaria sendo útil em te dizer que o cliente não está está validando corretamente. Fora isso, o servidor deve prover uma mensagem adequada para o erro de processamento ocorrido, não havendo dúvidas para o desenvolvedor do cliente.
Comment: @PabloPalácios Obrigado pela informação acabei de reler o RFC e vou editar a resposta.
Answer: Pode usar o 400 mesmo.
A definição em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html diz:

The request could not be understood by the server due to malformed
  syntax. The client SHOULD NOT repeat the request without
  modifications.

traduzindo...

A solicitação não pôde ser entendida pelo servidor devido à sintaxe
  mal formada. O cliente não deve repetir a solicitação sem
  modificações.
Comment: Lucas, cuidado com sua fonte pois a RFC 2616 está obsoleta e foi quebrada em várias outras. A RFC 7231 é a que está em voga e que diz respeito sobre o assunto dessa questão.
Comment: Reforço também que deve ter cuidado com isso. Veja que a pergunta é clara referente a erros em parâmetros e não a erros no protocolo. O uso do erro 400 é para erros de sintaxe, por exemplo, um header que tenha erro de digitação como "contnt-type".. o correto seria "content-type".. Entendeu? Isso causa um erro 400 pela má formatação. Não tem relação alguma com parâmetros providos por GET, POST, PUT, DELETE..
Comment: @DanielOmine a nova RFC não deixa explicito qual tipo de erro deve ser retornado, dando como exemplo erros de sintaxe.


ABCD is a rectangle. $AB=1$, $AD=\sqrt{3}$. Using $B$ as the center and $BA$ as the radius,

Question: ABCD is a rectangle. $AB=1$, $AD=\sqrt{3}$. Using $B$ as the center and $BA$ as the radius, draw a circle that intersects $BC$ at $E$. $P$ is a point on arc $AE$. Draw circle $B$'s tangent line through point $P$ that intersects $AD$ at $S$ and $BC$ at $T$. If $ST$ bisects $ABCD$ into two parts of equal area, how long is $ST$?
Triangles $ADB$ and $DBC$ are 30-60-90 triangles, but I don't know how to use the information. I tried assuming that point $P$ is on diagonal $DB$ and solved to get $ST$ is $\frac{2\sqrt{3}}{3}$ but I don't think my teacher will accept that as a valid solution. Please help me out!
Answer: You're absolutely right.  A line segment bisects a rectangle into two regions of equal area if and only if it passes through the center $O$ of the rectangle. You can show by the Pythagorean theorem  that $BO=1$, so it lies on the arc $AE$ and therefore the only possible point $P$ where the tangent will pass through $O$ is $P=O$ itself.
Good job saving yourself a half-ton of ugly algebra!
Comment: @user546770 LOL, not at all!  I wrote up the whole thing in GeoGebra expecting it to be ugly, but $\sqrt 3$ is a magic number that just happens to make the circle pass through the center of the rectangle.
Comment: Oh gosh I'm dumb... thank you so much!


Date Format's getLongDateFormat() isn't displaying the day of the week

Question: I've created a private method to receive a Date, and format it so it looks like "Sunday, August 10, 2014":
private String formatDate(Date date){
        java.text.DateFormat dateFormat = android.text.format.DateFormat.getLongDateFormat(getActivity().getApplication());
        return dateFormat.format(date);
    }

In my fragment's OnCreateView method, I use that method to set a button's text:
mDateButton.setText(formatDate(new Date()));

When I run my app, however, it just says "August 10, 2014." This doesn't make sense to me, since the Android documentation says that getLongDateFormat() should be displaying the day of the week (http://developer.android.com/reference/android/text/format/DateFormat.html#getLongDateFormat(android.content.Context)). Am I using getLongDateFormat() incorrectly?
I'm using Android API Level 19 as my target.
Comment: @hakiko that doesn't answer my question. My question is specifically about getting getLongDateFormat() to work as documented.
Comment: @Marina Did you ever figure out why the getLongDateFormat of android.text.format.DateFormat does not actually do what is advertised in the android reference guide? I see all of the answers here just provided a workaround for the issue.
Comment: `getDate()` is [deprecated](http://developer.android.com/reference/java/util/Date.html#getDay()) so it might gives you some problems
Comment: @mt0s, sorry I was being unclear: getDate() is a method I implemented, but essentially, it will lead to new Date() being called. I've made the change in my question to be more clear. thanks!
Comment: http://stackoverflow.com/a/25215560/1848929
Comment: @Marina can you test to return dateformat instead, I think that Dateformat is formatted inn its toString method
Comment: Query long date format string and add "EEEE " to it, if it doesn't have it already.
Comment: As of today, it still does what @Marina originally reported.
Answer: private String SetFormatDate(Date date) {
    java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
    return dateFormat.format(date);
}

Comment: I like it because it's so concise.
Answer: I just had the same problem, it just displayed the date (without weekday). I've found another method of getting the appropriate date string:
android.text.format.DateUtils.formatDateTime(getApplicationContext(),
millis,
android.text.format.DateUtils.FORMAT_SHOW_WEEKDAY | android.text.format.DateUtils.FORMAT_SHOW_DATE | android.text.format.DateUtils.FORMAT_SHOW_YEAR);

It's a static function and you can easily define which parts you want to have in your date string. The representation is localized.
see http://developer.android.com/reference/android/text/format/DateUtils.html
Answer: Also you can do like this
private String formatDate(Date date){
    java.text.DateFormat df = android.text.format.DateFormat.getLongDateFormat(getActivity().getApplicationContext());
    return android.text.format.DateFormat.format("EEEE", date) + ", " + df.format(date);
}

Answer: private String formatDate(Date date)
{
    return DateFormat.format("EEEE, dd MMMM yyyy", date);  //import      android.text.format.DateFormat;
}

Output : Tuesday, 27 October 2015
First argument is the format string and the second one is the current date.
You can change the format of the date by changing the first argument i.e. format string. Check out the symbols in the Symbol Column and also the variations in the Example Column in the picture below.
See this image for format strings reference

For more format strings symbols check out http://developer.android.com/reference/java/text/SimpleDateFormat.html
Hope this helped


agent.googleapis.com/agent/ no metric found

Question: I'm trying to set an instance group managed autoscaling based on memory_usage. I installed the agent on my GCP windows server VM and I'm able to see metrics on the Stackdriver dashboard. Now, when I set the metrics type agent.googleapis.com/agent/memory_usage on the instance_group configuration panel, GCP tells me that there is no data to use. I don't understand why.
Comment: I have added answer to your question at this [google discussion thread](https://groups.google.com/forum/#!topic/gce-discussion/X6LA0-8mFak), if still having any issue, post on [gce-discussion thread](https://groups.google.com/forum/#!topic/gce-discussion/X6LA0-8mFak) to continue
Answer: In order to autoscale your VMs based on RAM usage it is required that you create a custom metric that makes use of Stackdriver monitoring.
The custom metric name should begin with "custom.googleapis.com/" followed by a simple name or a path name.
See here for detailed info on creating custom metrics.
As the OP points out, the Stackdriver agent must be installed on the instance(s) in order for certain metrics to be measured, including memory usage. Info on installing the agent can be found here and a list of the additional metrics that require the installation of the agent can be found here.
Once you've created a custom metric, it can then be added to an Instance Group so that it controls the scaling of the instances in that group.There is some useful information here that explains how to do this.
Comment: My issue was related to a malfunction of the windows agent. As we can read on this [thread](https://groups.google.com/forum/#!topic/gce-discussion/X6LA0-8mFak) they've started to investigate it. In the meanwhile, I've made a [nodejs module](https://github.com/beinnova/windows-stackdriver-monitor) which does what the agent was supposed to do. If not the right way, but it helps me to achieve the goal.