i18n URL format with language parameter always in URL

Question: I'm working on a new website and I have a question regarding internalization (i18n) and SEO.
Here's the case. I'm using this CodeIgniter code to translate my website in 2 languages.
Let's say these languages are English and Dutch.
When using this code, people visiting mydomain.com are redirected to mydomain.com/en/defaultcontrollername
where English is the default language.
I will have a simple selectbox where users can switch to Dutch. The url will then be the same, except "en" is replaced with "nl".
Now my question is: is it bad practice in terms of SEO that the default language is always present in the URL? Also, does an immediate redirect to mydomain.com/en/defaultcontrollername after opening mydomain.com have effect on SEO?
Is it better to always use a default language and present that first, or to "guess" the language based on browser headers?
Last but not least: do I also have to translate my controller names.
Comment: So what do u want exactly?...I mean you always need that 'en' and 'nl' say language identifier in your Url or not?
Comment: This particular piece of CodeIgniter always supplies the language parameter in the URL. I'm not sure if that is the best approach though.
Comment: OKay...thats Not at all necessary to supply languageparameter even single time....I have Made One website recently supporting four Language without language in url....What can you do is store your default langugae say 'en' in cookie and map language file for en and load content from der...if user change the langage then replace the value in cookie by new langage and map it to the path of your langage file same as value in cookie...so you don't need to change Url
Comment: I know you can use cookies and sessions. But that seems really bad for SEO purposes.
Answer: See: How should I structure my urls for both SEO and localization?
Having a folder (or subdomain, or top level domain) with the language is the preferred setup for optimal SEO.
You can translate words in the URL itself (the controller name in your case).

It makes the URLs look more appealing to non-English users.
Any non-ASCII characters have to be URL encoded (UTF-8).
URLS can get very long with even a few international characters.
Browsers often show URLs not encoded in the URL bar but they get copied and pasted encoded.
Comment: So it is OK to ALWAYS have the language in the URL, even for the default language? thanks
Comment: Yes, it is fine even for the default language.  Wikipedia does that.


Automatically rename non-dot-notation property names

Question: In visual studio (or other common javascript/typescript IDEs), is there a simple way to rename properties in a class and automatically rename them in other places of the code where they are not in dot-notation as well?
The issue appears e.g. when properties are accessed with bracket notation obj["prop"] instead of obj.prop or when listing subsets of property names for some reason:
class C {
  constructor(
    public name: string,
    public age: number,
    public id: string
  ){}
};
let obj = new C("bob", 30, "abcdef");
let interesting = ["name", "age"];
console.log(`${interesting[0]}: ${obj[interesting[0]]}, ${interesting[1]}: ${obj[interesting[1]]}`);

I don't know of a good way to associate such strings with property names (apart from typing the strings as keyof C, which would at least give a compiler error after renaming) or IDEs smart enough to understand the relation.
There was the fancy idea of transforming everything into dot notation, with a method taken from a related question - namely converting a dummy function containing only an unused statement of the property access to string and parsing that. Then the common IDEs would rename it aswell. However, this introduces code which is completely unnecessary for the application itself and is not very robust unless written with extreme care - as e.g. Function.toString is partly implementation dependant.
Is there no practical way except doing most of it manually?
Comment: please don't format your classes as one-liners. it's hard to read.
Comment: It is imposible. IDE is not humman. It can detect when your string contains string and when it contains property name very hardly. If you have defined interface why you do not access it via dot?
Comment: Accessing properties by string index on object in JavaScript is way to hell.
Comment: Well, i guess it is not possible. Unless there was a way to tell the IDE what property a string refers to (possibly via typescript types), it would be pretty hopeless anyways.
Answer: It is possible if you replace hardcoded strings with variables that store property names
https://stackoverflow.com/a/47707719/2167309
var person = {};
person.firstname = 'Jack';
person.address = "123 Street";

function getPropertyName(obj, expression) {
    var res = {};
    Object.keys(obj).map(k => { res[k] = () => k; });
    return expression(res)();
}

let propertyName = getPropertyName(person, o => o.address);
console.log(propertyName); // Output: 'address'


How to use python diff_match_patch to create a patch and apply it

Question: I'm looking for a pythonic way to compare two files file1 and file2 obtain the differences in form of a patch file and merge their differences into file2. The code should do something like this:
diff file1 file2 > diff.patch
apply the patch diff.patch to file2 // this must be doing something like git apply.

I have seen the following post Implementing Google's DiffMatchPatch API for Python 2/3 on google's python API dif_match_patch to find the differences but I'm looking for a solution to create and apply patch.
Answer: First you need to install diff_match_patch.
Here is my code:

import sys
import time
import diff_match_patch as dmp_module

def readFileToText(filePath):
 file = open(filePath,"r")
 s = ''
 for line in file:
      s = s + line
 return s

dmp = dmp_module.diff_match_patch()
origin = sys.argv[1];
lastest = sys.argv[2];

originText = readFileToText(origin)
lastestText = readFileToText(lastest)

patch = dmp.patch_make(originText, lastestText)
patchText = dmp.patch_toText(patch)

# floder = sys.argv[1]
floder = '/Users/test/Documents/patch'
print(floder)
patchFilePath = floder
patchFile = open(patchFilePath,"w")
patchFile.write(patchText)

print(patchText)


Removing Visual Studio Code current code block highlight

Question: Does anyone know how to turn off the current code block highlighting, it only highlights the block of code you are currently editing. In the picture its the fun yellow line. I think it was added in 1.22.2
Comment: I'm using VS Code insiders 1.23.0-insider and I can *not* replicate your code highlighting. Maybe it's some plugin that does this? Have you tried disabling all of your extensions and see if it persists?
Comment: Your a legend! It was not surprisingly 'Bracket Pair Colorizer' extension. I swear it wasn't working like that before I upgraded, who knows. Thanks again!
Answer: It's a feature of Bracket Pair Colorizer plugin that I think you're using. See the plugin's marketplace page for settings guide.
Comment: Thanks for your help, it was driving me bonkers.


How to correctly write url for #hashtag in Django

Question: I want to insert data with modal form and show it on current page. Page already show data on table and modal form, now i need to add modal form to urls.py.
 path('viewpost/#add_data_Modal', views.createpost, name='createpost'),

Comment: The part after the `#` (including the `#`) is *never* send to the server: that is the fragment identifier: https://en.wikipedia.org/wiki/Fragment_identifier
Comment: related: https://stackoverflow.com/questions/58048620/how-to-get-entire-current-url-in-django/58048704#58048704
Answer: You could use a RedirectView for this:
from django.views.generic import RedirectView
from django.urls import reverse

class ViewpostRedirectView(RedirectView):
    def get_redirect_url(*args, **kwargs):
        hash_part = "add_data_Modal"  # the data you want to add to the hash part
        return reverse("createpost") + "#{0}".format(hash_part)

Then in your urls.py you would have something lime this:
path('viewpost/', views.createpost, name='createpost'),
path('viewpost/modal/', views.ViewpostRedirectView.as_view(), name='createpost_modal')

The viewpost/modal/ url will redirect to the viewpost/ url with the hash part appended to it.
Answer: I find another simpler way to do it, I suggest passing the hashtag as a query string to the view then reverse redirect there, so
in urls.py keep it the simple
 path('', views.home, name='main-home')
in home function in views.py
@csrf_exempt
def home(request):
    hashtag = request.GET.get("hashtag", "")
    if hashtag:
        return HttpResponseRedirect(reverse("main-home") + "#{0}".format(hashtag))
    context = {}
    return render(request, 'index.html', context)

and in the html u can pass any hashtag you want

Team

Contact


Why does 'promisify' cause node to ignore a function?

Question: I wrote the following code:
var express = require('express');
var app = express();
var Promise = require('bluebird');
var counter = {};
counter.num = 0;

function incr(counter) {
   counter.num = counter.num + 1;
}

app.get('/check', function(req, res) {
   Promise.promisify(console.log)(counter.num)
       .then(Promise.promisify(incr)(counter.num))
       .then(console.log(counter.num));
   res.end("OK");
});

app.listen(4000);

I expect the following operations to take place synchronically:
1. print counter.num (=0)
2. increment counter.num
3. print the new counter.num (=1)
This is what I get:

0 [Function]
0

Why didn't operation 2 take place? and Why do I get a "[Function]" in the console?
Answer: Your situation is not appropriate for Promise.promisify().
Assuming you are using Bluebird, then Bluebird's Promise.promisify() expects the following:

The function you're promisifying must take a callback as it last argument  (often referred to as the node.js async calling convention).
That callback must be called with the argument (err, data) when the function has completed its operation.
The err value must be falsey when the function is successful and the result is passed in the data argument.  The err value must be truthy when there is an error and then err is the error value.

Your use of .promisify() does not match any of these conditions.
Since the purpose of promises is to track or coordinate asynchronous operations, it does not appear that you should even be using promises for this particular code.   Because all your counter operations are synchronous you can just do this:
app.get('/check', function(req, res) {
   console.log(counter.num);
   incr(counter);
   console.log(counter.num);
   res.end("OK");
});

Answer: promisify is for async functions. console.log is a sync function. Bluebird expects function to be promisified has callback function for last arguments.
And I don't see any reason you might want to use promise in your question situation.


Help me to understand what element_child() does

Question: Can anybody help me understand what element_child is doing?
It is called as element_children($form) where form contains keys like "cancel", "submit" and "#redirect".
This snippet from common.inc
/**
 * Check if the key is a child.
 */
function element_child($key) {
  return !isset($key[0]) || $key[0] != '#';
}

/**
 * Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
 */
function element_children($element) {
  return array_filter(array_keys((array) $element), 'element_child');
}

Answer: Suppose you have an array as the following (it's an array as accepted from the form API):
  $form['example_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Testing text'),
    '#default_value' => '',
    '#size' => 45,
    '#maxlength' => 45,
    '#required' => TRUE,
    '#description' => t('This is an example form demonstrating forms usage in the installer profiles tasks. Enter any text to see what happens.'),
  );

  $form['continue'] = array(
    '#type' => 'submit',
    '#value' => t('Continue'),
  );

  $form['errors'] = array();
  $form['#action'] = $url;
  $form['#redirect'] = FALSE;

If you execute element_children($form) will return an array containing the following indexes:

example_text
continue
errors

When $key is a string $key[0] is the first character of that string. The value of !isset($key[0]) || $key[0] != '#' is TRUE when the string $key is empty, or when the first character of that string is not #; array_filter() returns an array containing the keys and values for which the function referred as second argument returns TRUE.
The reason to do this is that, in the array used by the form API, keys starting with # are considered properties of that form field (or of the form), while keys that don't start with # are considered child of that form field; in the example code I used, '#redirect' is a property of the form, while 'example_text' is a form field that is child of the form.
Comment: If the string is empty, `$key[0]` is undefined, and the next expression would cause the "access to a not defined variable" error; `!isset($key[0])` avoids the other expression is evaluated, and it is necessary, as an empty string is not used for properties.
Comment: Many thanks! But isn't $key[0] deprecated syntax in php? It should be using $key{0} instead?
Comment: The [PHP documentation](http://php.net/manual/en/language.types.string.php) doesn't report that `$key[0]` is deprecated. As far as I remember, the last introduced syntax is `$key[0]`, while `$key{0}` was introduced first. I prefer using `$key[0]`, as it reminds me of the array access.
Comment: Is it? I just now read the book: PHP5 and Mysql Bible and the author mentions that [i] syntax is deprecated (PHP4) and {i} is the recommended one. This fact confused me as Drupal code is scrutinized by expert people ..
Comment: What is the point of checking with !isset($key[0]) for checking the first character? I can imagine no case where first character of a string is not set. So this will check only an empty or non-existant string. If it is non-existant why does it need to return true?


What does "open divisions" mean in a USTA tournament?

Question: Most (adult) tournaments I've entered have divisions indicated by NTRP level - i.e. MW(3.0, 4.0) means that men and women who are rated 3.0 or 4.0 can enter. Some of them, though, are listed as MWOp.
What does "open" mean? Does it just mean that people of any rating can enter, but they would be matched up (at least in early rounds) with players who have similar ratings, or does it mean that it's a free-for-all, where the tournament director could match up a 2.5 player with a 5.0 player?
Comment: It's cheaper than a tennis lesson and if there's double elimination, you'll automatically get to play against 2 pros for like $30. I think it's a steal.
Answer: Like JW said, they are open to players of all ages, but most importantly, they are open to all skill levels also - which means they are the most competitive. Many professional level tour events have the name "Open" in them (French Open, US Open, Australian Open, etc) because they are "Open level" events - meaning anyone can enter the qualifying (or pre-qualifying) draws if they're willing to pay the entry fee. You will usually only see professional level players enter though, because most open divisions are full of very talented players.
Another reason why open divisions exist are because at the higher skill levels of the game they are fewer players available to put into a tournament draw so they have to combine the upper skill level players together to have enough. They are plenty of players generally at the 2.5-4.5 level, but at 5.0 and above there generally aren't enough 5.0, 5.5, 6.0, etc. to have a division or "draw" just for that specific skill level. With an "open" division, anyone above, say the 4.5 level can enter and generally expect to draw an opponent that is of similar skill level.
To answer the last part of your question - generally a tournament director doesn't know the rating level of a player in open divisions unless they have self-rated or already have a USTA rating - but most people at the lower rating level (like 2.5) know enough not to enter themselves into the open draw of a tournament. I have never been a tournament director (though I know some people that have) and they generally know the names of most players that enter their open division and know that they belong there.
Comment: Well, this is a tournament at a small park district club, so I doubt there will be professional-level players there. I can also guarantee that the tournament director will NOT know the names of most of the people entered. And NTRP rating is required on the entry form, so the director will know the rating of every player before creating the draw.
Comment: In that case it is a little surprising to have an Open draw, since those are usually offered only for higher level players. I am guessing the NTRP divisions end at 4.0 and open is for 4.5 and above?
Comment: No, that's my point. The entire tournament is listed as "open division". Anyone can register and must include their rating, but it's not listed as "MW(2.5,3.0,3.5,4.0, Op)" or anything like that. Here's what the site says: "MW(Op)s,SE; X(Op)d,SE".
Comment: Oh - my only guess then it that the number of participants doesn't warrant divisions for different skill levels and they're just leaving the whole thing open because there will be varying levels of skill.
Comment: In other words, my 3.0 self could absolutely end up playing someone who's 5.0. Wonderful! Just what my self-esteem needs :o)
Answer: According to the definition on the USTA site:

Open division are open to players of all ages.

In this context, open appears to refer strictly to the age of the player, and not the rating.
Comment: I very much hope you're right!


How do I display the attachment's file size of a node?

Question: Is there any way in Drupal 7 to display the attachment's file size of a node through the manage file / display of the file field, or is this programmatically achieved?
Comment: Are you using the media module with file entity?
Answer: You can do this hardcoded with the $node object by doing so (preferably in theme_preprocess_node in template.php) :
If you field field_my_field as a single value :
$file = field_get_items('node', $node, 'field_my_file');
if ($file) {
    $file_size = $file[0]['filesize'];
    $file_size_formated = format_size($file_size);
}

If you field field_my_field as a multiple value :
$files = field_get_items('node', $node, 'field_my_file');
if ($files) {
    $files_size_formated = array();
    foreach ($files as $key => $file) {
        $file_size = $file['filesize'];
        $files_size_formated[] = format_size($file_size);
    }
}

In template.php you should have something like this :
// This function allow one preprocess_node function per content type
function mytheme_preprocess_node(&$vars) {
  $node = &$vars['node'];
  // Preprocess function for each node type
  $function = __FUNCTION__ . '_' . $node->type;
  if (function_exists($function)) {
    $function($vars);
  }
}

function mytheme_preprocess_node_my_content_type(&$vars) {
  $node = &$vars['node'];
  $file = field_get_items('node', $node, 'field_my_file');
  if ($file) {
      $file_size = $file[0]['filesize'];
      $vars['file_size_formated'] = format_size($file_size);
  }
}

Then in you node--my-content-type.tpl.php you can print your var $file_size_formated where you want like this for example :

<?php print $file_size_formated; ?>

Comment: Ok thanks, so in the template.php I should have:
`function cs_emcdda_preprocess_node(&$variables) {
    $file = field_get_items('node', $node, 'field_pub_file');
    if ($file) {
        $file_size = $file[0]['filesize'];
        $file_size_formated = format_size($file_size);
    }
}

and in my custom node template

`
Comment: You need to get $node, for that add `$node = &$vars['node']` at the beginning of your function. Also add a condition on `$node->type == 'your_content_type'`
Comment: Ok, its working great, thank you so much fo your help @pbonnefoi, the website does not allow me vote in your answer, as soon as its possible, you have my vote :)
Comment: I think you can mark the answer as the right answer for now (it will give you some reputation I think ;-))
Answer: You can also modify the theme function theme_file_link in your template.php to add the file size to link with something like this:
function YOURTHEME_file_link($variables) {
  // ...

  $file_size = format_size($file->filesize);

  return '
' . $icon . ' ' . l($link_text, $url, $options) . '' . $file_size . '
';
}

Comment: This is better and clearer than the accepted answer.


any way to retrieve a circular reference value

Question: I wrote th following program to see feature called circular reference in perl.
my $foo = 100;
$foo = \$foo;
print "Value of foo is : ", $$foo, " " , $foo;

the output was:
Value of foo is : REF(0x21b632c) REF(0x21b632c)

but i was wondering where the value 100 gone can any one help me.or is it a memory leak?
Comment: The value of 100 was clobbered.  That is no different than saying, `$f = 100`, and then saying `$f = 'foobar'`.  The old value is lost.
Comment: Also, as perl uses a reference-counted garbage collector (plus a mark-and-sweep for circular references), there is no memory leak either.
Comment: @Phylogenesis, actually a circular reference *is* a memory leak, because the clean-up doesn't happen until the program exits.
Comment: @Phylogenesis It's new for me that Perl does mark-and-sweep – are you confusing this with CPython? OP's code will absolutely leak memory (`$foo` has a refcount of two, and will never drop to zero unless the circle is broken by reassignment or reference weakening). However, the scalar `100` will be garbage-collected.
Comment: @amon It seems the mark-and-sweep is only run on exit. See [this question](http://stackoverflow.com/questions/2972021/garbage-collection-in-perl).
Comment: @dan1111 To be fair, my point about the memory leak was a direct answer to the question about whether the scalar value leaks.
Comment: @Phylogenesis, fair enough.
Answer: The value 100 was overwritten. When you assign a value into a variable, it replaces the previous value.
my $foo = 100;
$foo = "a string here";

The value 100 has gone. The same thing happens in your code above. The only difference is what kind of value was put in there.


Criar moldura para lista de item

Question: Preciso criar uma moldura para um item de uma listView porém não tenho ideia de como fazer isso
Comment: Você pode utilizar [CardView](https://developer.android.com/guide/topics/ui/layout/cardview.html) para obter este tipo de efeito.
Answer: Hoje é recomendado o uso do RecyclerView ou CardView no lugar do ListView, mas, se ainda assim, se você precisa fazer uso do ListView que no caso terá layout customizado, veja a documentação do Android sobre Adapter para ListView. Uma possibilidade seria estender de BaseAdapter.
Basicamente, você usaria na View onde ficará sua lista um ListView convencional e criaria um adaptador no Java com as especificidades do seu ListView, incluindo o layout e métodos do que deve ocorrer ao pressionar um item da lista ou pressionar durante um tempo maior.
Já na atividade relacionada ao ListView, crie um objeto do adapter e faça uso do método setAdapter(ListAdapter l) para vincular seu adaptador personalizado ao ListView.
Você pode conferir aqui um exemplo.
Answer: Se você quiser customizar a ListView, eu recomendo esse tutorial aí:
https://androiddevbr.wordpress.com/2013/12/09/tudo-sobre-listview/
Explicam tudo direitinho!
Espero ter ajudado!

Criar moldura para lista de item


Backpropagating convolution with big image to train (comparably) small filter

Question: I was thinking about convolutions in neural networks and backpropagating them, and then I came across something I would like touched on.
Suppose I have a very high-resolution image that I'm using in a convolution in my neural network:

That means the output image from this convolution would also be big. Now, we want to train the filter to minimize some cost $C$, and to do that we need the derivative of $C$ w.r.t. the filter, $F$, which would be:
$$
\frac{\partial C}{\partial F} = \frac{\partial C}{\partial z} \cdot \frac{\partial z}{\partial F} = \frac{\partial C}{\partial z} \cdot \frac{\partial}{\partial F}[X * F]
$$
$$
\frac{\partial C}{\partial F} = X * \frac{\partial C}{\partial z}
$$
Where $z = X * F$ (i.e. our convolution operation).
Considering that $\frac{\partial C}{\partial z}$ is the same size as $z$, we're basically convolving a big image with a (still) big image to find $F$'s derivative, and here is where my problem lies; if we're convolving an image with another image of almost the same size, it's more like we're just getting the weighted sum of all the values in the image.
$$
\begin{bmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{bmatrix} * \begin{bmatrix}
1 & 4 & 7 \\
2 & 5 & 8 \\
3 & 6 & 9
\end{bmatrix} = \begin{bmatrix}
1+8+21+8+25+48+21+48+81
\end{bmatrix}
$$
While, yes, $\frac{\partial C}{\partial z}$ is going to be smaller than $X$, the difference here would be negligible, the difference between just a few values compared to the size of these high-resolution images would mean practically nothing. This means, the values in the filter $F$ would all have (almost) the same gradients, and the same changes would be made all across the board. I doubt a filter updating like this could truly train, but maybe I'm wrong.
Is this an actual problem? If so, solution/s? If not, why?
Thanks
Comment: I'm confused by/don't understand your question. However, to get better insight into convolution, consider that convolution can be performed as a matrix multiplication on an "unrolled" image. The "unrolling" operation is known as "im2col" -- https://towardsdatascience.com/how-are-convolutions-actually-performed-under-the-hood-226523ce7fbf
Comment: @YaroslavBulatov Thanks for showing "im2col", it looks quite interesting. I'm afraid I'm not sure how to better present my question. If you would like to elaborate further then maybe I could improve it.
Answer: The difference between a few pixels compared to the size of these high-resolution images doesn't have to be "negligible". Let's look at a simpler problem first:
If we're finding the gradient of the filter $F$ using $X * \frac{\partial C}{\partial z}$, where $X$ is a very big image (and subsequently so is $\frac{\partial C}{\partial z}$), then why shouldn't these gradients' values blow up? If, for example, $X$ was a grayscale image with each pixel's brightness being from $0.0$ - $1.0$, and $\frac{\partial C}{\partial z}$ being arbritrary, you could imagine how, depending on the distribution of $\frac{\partial C}{\partial z}$, big convolutions with lots of values like this could blow up.
$$
\begin{bmatrix}
0.70 & 0.17 & 0.28 \\
0.06 & 0.77 & 0.27 \\
0.85 & 0.23 & 0.27
\end{bmatrix} * \begin{bmatrix}
0.23 & 0.59 \\
0.46 & 0.64 \\
\end{bmatrix} = \begin{bmatrix}
0.7817 & 0.7313 \\
1.0063 & 0.615
\end{bmatrix}
$$
So, how come when convolving $X$ and $\frac{\partial C}{\partial z}$, where each value in the resulting output could be made of thousands of values, they don't add up and become very big? Well, if the distribution of $\frac{\partial C}{\partial z}$ has a mean of $0$, then the output of this convolution should also have a mean of $0$ (because there would be an equal number of positive and negative values, and so they cancel each other out), and thus wouldn't blow up.
This is also then the case for the original question; if $\frac{\partial C}{\partial z}$ has mean $0$, then these thousands of values just converge to $0$, and the difference of a few pixels isn't "negligible" any more.
Of course, this resolution is based on the assumption that the upstream gradient would have a mean of $0$, which is not a given fact. This problem is actually well known, called "exploding/vanishing gradients", and there are measures against it, such as batch normilization (scales and shifts input to mean $0$ and standard deviation $1$), better initialization (such as Xavier initialization) and so on.
So, this can be a problem given the upstream gradient isn't normilized, in which case the gradients can get unstable and explode (as well as update the same, observed in the question). This is a well known problem and can be fixed with multiple things (a few of which mentioned above).


Path (alias) does not work after migration, nor Content view

Question: I'm using the migrate (7.x-2.x-dev) module to import a node(s) from static HTMLs to Drupal 7, and I want to set the path the same as the original directory/filename.  I have defined in my migration class as follows,
$this->addFieldMapping('path', 'filename');
$this->addFieldMapping('pathauto')->defaultValue(0);

and it seems to be working - when I open the imported node in the edit mode, I see the correct path in the path field, and the Generate automatic URL alias checkbox is unchecked.
However, the path is not working.  Say, when the path is set to be info/legacy.html, and the node is 21,
http://localhost/node/21

is fine, whereas
http://localhost/info/legacy.html

returns 404 (Page not found).
In fact, the node is not listed in the Content page /admin/content either.  I found the node number (21 in this case) by browsing directly the SQL database (the entry of the node in the database looks no different from other nodes).
Everything else looks fine, I mean, all the fields related to the node are imported as I intend.  But the above-mentioned 2 points are weird...
Why is it so, and how can I achieve the above?  Any idea?
Answer: Actually, I have just found out it was due to the i18n setting of the node and site.  The language of the node was set to be ja (Japanese), correctly.  Probably because of that,
http://localhost/info/legacy.html

does not work (HTTP 404), but
http://localhost/ja/info/legacy.html

does display the node imported.
Similarly, the Content manager does not display the node in the default-language mode (English) /admin/content, however it does display the newly imported node in Japanese /ja/admin/content.  I should note I allow all the URL (Path prefix), Session, User, Browser in the language configuration (/admin/config/regional/language/configure) in my environment.
My browser's HTTP request, when I test, is
"Accept-language": ja

So, I expected when I opened
http://localhost/info/legacy.html

it would open the node in Japanese, following the browser's request, as opposed to 404, but it does not, apparently.
Hmm, I guess it is likely my understanding of the i18n handling in Drupal is not sufficient.  Anyway, I think this can be solved with the redirection module in Drupal, after investigating and finding out how to set it up during migration.  I didn't want the default URI to be something like node/21, but if it is ja/info/legacy.html, I am fine with it, as long as the redirection works.
[Edit: 2014-10-06]
I have figured out why.  In my i18n setting of Drupal, URI-path-prefix is checked and is given the highest priority, where English is default with its language-code for path-prefix being undefined.  Hence,
http://localhost/info/legacy.html

is the English version of the content, which does not exist.  When I define the language-code of English (en) for path-prefix, then the access to the URI brings up the Japanese version, if my browser's preferred language is Japanese (and the i18n of the site is configured to accept the browser's preferred language at the lowest priority), because the URI is not any more specific for the English version.
Another note is the redirection module works only when redirecting to a node URI [or path without the language-code prefix (added on 2014-10-11)].  The redirection to, for example,
/ja/info/legacy.html
does not work well, as it can bring up the path of
http://localhost/ja/ja/info/legacy.html

in some cases.
[Edit: 2014-10-11]
The whole point (and much more) is covered and summarised in the document published at drupal.org:  https://www.drupal.org/node/2354755


How to make path directory generic and dynamic for any user?

Question: I have trace32 installed at C drive  and have mentioned that directory in my code. Suppose if some other user run this code in their system, the code does not work because the user has installed application in different location. How can I make this  directory generic and dynamic and make it work for all users?
Comment: You could make it so your program has a configuration file and used the [`configparser`](https://docs.python.org/3/library/configparser.html) module to deal with it (i.e. get the path of where trace 32 is installed from it).
Answer: You have multiple possibilities. Bevor explaining them some generic tips:

Make the TRACE32 system path configurable, not a path inside the installation. In your case this would be r"C:\T32". This path is called t32sys or T32SYS.

Make sure you use os.path.join to concatenate your strings, so it works on the users operating system: os.path.join(r"C:\T32", "bin/windows64")

Command line arguments using argparse. This is the simplest solution which requires the user to start the Python script like this: python script.py --t32sys="C:\t32".

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--t32sys", help="TRACE32 system directory.")
args = parser.parse_args()
t32sys = args["t32sys"]

Instead of command line parameters you could also use a configuration file. For this you can use the built-in configparser module. This has the advantage that the user doesn't need to specify the directory as a command line argument, but the disadvantage that the user needs to be aware of the configuration file.

Configuration file (example.ini):
[DEFAULT]
t32sys = C:\T32

import configparser

parser = configparser.ConfigParser()
parser.read("example.ini")
args = parser["DEFAULT"]
t32sys = args["t32sys"]

Environment variables using os.environ. T32SYS is a environment variable often used for this, but it's not ensured to be set. So you have to tell users that they have to set the variable before using your tool. This approach has the advantage to work in the background, but also in my opinion a little bit obfuscating. I'd only use this in combination with argparse or configparse to override.

import os

t32sys = os.environ.get('T32SYS')

You can of course combine multiple ways with fallbacks / overrides.


Determine $f(x)$ knowing $f(x)+f(x+\varepsilon)$

Question: I encountered a problem at work that, in my opinion, has a fundamental mathematical reasoning to determine its solvability.

Due to an unwitting software configuration, my associate recorded the audio of our meeting twice, resulting in the audio sounding like the sum of the original signal combined with a slightly delayed copy of itself.
The final audio file can be thought as a time-dependent signal $g(t)$ that is related to the original audio signal, $f(t)$, by the following equation
$$g(t) = f(t) + f(t+\varepsilon)$$
Knowing $g(t)$ and $\varepsilon$ is it possible to approximate $f(t)$, either analytically or numerically?

My primary intuition was that it would be possible, but now it feels like trying to unscramble two eggs after they were mixed in a bowl.
Comment: @TravisWillse: in general I think there will be uncertainty up to functions period $2\epsilon$ where the second half is the negative of the first.  You could try to smooth this out, but then precision errors could start to creep into the calculations.
Comment: Assuming $f(t)$ is nonzero only for $t \in [0, T]$ we get $g(t-\epsilon) = f(t)$ for $t \in [0, \epsilon)$. So we recover $f$ exactly on $[0, \epsilon)$. Then $g(t-\epsilon) = \underbrace{f(t-\epsilon)}_{known} + f(t)$ for $t \in [\epsilon, 2\epsilon)$. In this way we can perfectly recover $f(t)$ for all $t \in \mathbb{R}$ by piecing the solutions together over intervals $[0, \epsilon), [\epsilon, 2\epsilon), [2\epsilon, 3\epsilon)$ and so on.
Comment: The approach of @Michael will accumulate sampling errors. As the distortions are audible, the delay $ϵ$ is substantial, frequency-dependent cancellation does occur in the spectrum of human perception. Reconstruction from nearly erased data is always an ill-posed problem.
Comment: $f$ cannot always be recovered. For example, if $g(t) = 0$ and $\epsilon = \pi$, $f(t)$ could be any of the infinitely many functions $f(t) = A \sin t$.
Comment: More generally, for any $\epsilon$, signals with frequency an odd multiple of $\frac{\pi}{\epsilon}$ cannot be detected.
Comment: @Henry Right, and any such function will decompose into a (possibly infinite) linear combination of the functions I mention.
Comment: Nice approach @Michael, I believe that it would be especially useful for larger values of $\varepsilon$ or in performance-sensitive restoration algorithms.
Comment: https://dsp.stackexchange.com/q/36264/21075
Answer: A possible avenue, mathematically, may be the Fourier transform.
Let
$$
\newcommand{\FF}{\mathcal{F}}
\newcommand{\dd}{\mathrm{d}}
\FF[f](\xi) := \int_{-\infty}^\infty f(x) e^{-2\pi i \xi x} \, \dd x
$$
denote the usual one-dimensional transformation for $f$.
We know two properties:

$\FF$ is linear, in the sense that given $\alpha,\beta \in \mathbb{C}$, we have $\FF[\alpha f + \beta g] = \alpha \FF[f] + \beta \FF[g]$

$\FF$ satisfies certain time-shift properties. In particular,
$$
\FF[f(x-x_0)](\xi) = e^{2\pi i x_o \xi} \FF[f](\xi)
$$

Consequently, if $g(x) = f(x) + f(x+\varepsilon)$, then
$$\begin{align*}
\FF[g](\xi)
&= \FF[f(x) + f(x+\varepsilon)](\xi) \\
&= \FF[f](\xi) + e^{-2\pi i \varepsilon \xi} \FF[f](\xi) \\
&= \FF[f](\xi) \Big( 1 + e^{-2\pi i \varepsilon \xi} \Big)
\end{align*}$$
Therefore, assuming we know $g,\varepsilon$,
$$
\FF[f](\xi) = \frac{\FF[g](\xi) }{ 1 + e^{-2\pi i \varepsilon \xi}}
$$
To recover $f$, one uses the similarly-defined inverse Fourier transform,
$$
\FF^{-1}[f](x) := \int_{-\infty}^\infty f(\xi) e^{2\pi i \xi x} \, \dd \xi
$$
or, more appropriately,
$$
f(x) = \FF^{-1}\Big[ \FF[f] \Big](x) := \int_{-\infty}^\infty \FF[f](\xi) e^{2\pi i \xi x} \, \dd \xi
$$
However, there are no guarantees it would be easy to calculate this inverse, and depending on the $\varepsilon,\xi$ involved it might not even be well-defined (say, if the exponential in the denominator evaluated to $-1$). Based on the other comments, issues may even arise for certain types of $f$.
Comment: (+1) An excellent answer. We can see in your derivation the problem with the signals with angular frequency an odd multiple of $\frac{1}{2 \epsilon}$---these are exactly the signals for which the denominator $1 + e^{-2 \pi i \epsilon \xi}$ of your expression for $\mathcal{F}[f](\xi)$ always vanishes. In that sense, those signals are the only components for which your procedure is not defined. In practice there may be numerical issues with components of the signal whose angular frequency is close to the forbidden value, where the denominator becomes very small.
Comment: Ohhhhhh I see, that explains the comment about the multiples of $1/(2 \varepsilon)$, I don't know why I didn't think to actually see what would cause those undefined values. Thanks Travis!
Comment: You cannot really convolve $g$ with the inverse transform of $\frac{1}{1+e^{-2\pi i \epsilon \xi}}$ as it seems to have no inverse transform.
Comment: Brilliant! When working with discrete-time signals, such as data in a digital audio file, I believe this process translates to determining the DFT of $g$, dividing each sample $G(n)$ by $1+\exp(−2\pi n i\varepsilon)$ so that the IDFT of the result is the recovered data.
Answer: Assume that $f$ is (locally approximated by) a straight line, $f(t) = at + b$.  This gives us:
$$f(t + \epsilon) = a(t + \epsilon) + b = at + b + a\epsilon$$
$$g(t) = 2at + 2b + a\epsilon$$
We now have two coefficients to solve for, so assume that we know $g(t_1)$ and $g(t_2)$, giving us the system of equations:
$$g(t_1) = (2t_1 + \epsilon)a + 2b$$
$$g(t_2) = (2t_2 + \epsilon)a + 2b$$
Solving for $a$ and $b$ gives:
$$a = \frac{g(t_2) - g(t_1)}{2(t_2 - t_1)}$$
$$b = \frac{(2t_2 + \epsilon)g(t_1) - (2t_1 + \epsilon)g(t_2)}{4(t_2 - t_1)}$$
And plugging these into the formula for $f$ gives:
$$f(t) = \frac{(2(t - t_1) - \epsilon)g(t_2) - (2(t - t_2) - \epsilon)g(t_1)}{4(t_2 - t_1)}$$
If we choose $t_1 = t$ and $t_2 = t + \epsilon$, then this simplifies to:
$$\boxed{f(t) = \frac{3g(t) - g(t + \epsilon)}{4}}$$
If $f$ is expressible as a Taylor series, then the maximum error in this approximation is $\frac{1}{4}\epsilon^2 |f''(t)|$.
Answer: Υοur second feelings are correct from a purely mathematical point of view. For a given $\varepsilon$, there are many functions $f$ such that $f(t) = - f(t + \varepsilon)$ for all $t$. For such an $f$, $g(t) = 0$ for all $t$, and so $g$ gives no information about $f$ apart from that fact that $f(t) = f(t + \varepsilon)$ for all $t$.
It may be possible to retrieve some information about $f$, if you make some assumptions about it based on the physics of the situation (which make my above contrived example highly unlikely). Probably some kind of machine learning approach would be a good place to start. MSE is probably not the best forum to ask if you are interested in following that up.
Comment: For numerical estimation, I've no doubt @PrincessEev's answer is the way to go. For the machine learning, the kind of thing I have in mind is that you'd sample some actual meetings recording $f$ and calculating $g$ for some typical values of $\epsilon$ (BTW, do you know $\epsilon$?), then you'd attempt to train a system to recover $f$ from $g$. It would be interesting to know how that compares in practice with the Fourier transform approach.
Comment: Thank you for your input! As for numerically estimating $f(t)$, I wonder which mathematical conditions should be verified to make it viable. For instance, considering  $\varepsilon\to 0$ (the delay is relatively small).
Comment: The machine learning approach is a great idea for a project, I wonder how the quality and the algorithmic efficiency of each restoration process differ. And yes, I can determine $\varepsilon$ by inspecting how frequency and power change with time. In a plot such as: http://mres.uni-potsdam.de/index.php/2020/07/08/analyzing-music-in-the-time-and-frequency-domain-using-matlab/ we can identify the time that a frequency outliers takes to repeat itself and estimate $\varepsilon$ like that.
Answer: You problem is one of deconvolution:
$$
g(t) = f(t) \ast \left( \delta(t) + \delta(t+\epsilon) \right) = f(t) \ast h(t),
$$
where $h(t) = \delta(t) + \delta(t+\epsilon)$. In the frequency domain, this is
$$
G(\omega) = F(\omega) \cdot H(\omega).
$$
Thus, to recover $f(t)$, we deconvolve $g(t)$ with $h(t)$:
$$
f(t) = \mathcal{F}^{-1} \left( { G(\omega) \over H(\omega) } \right),
$$
where $\mathcal{F}$ is the inverse Fourier transform. For the system to be solvable, $H(\omega) \neq 0$.
There are better ways to do deconvolution that are more stable, but the above is the gist of it and where I would suggest you start.


Não retorna resultado PHP

Question: Tenho o seguinte problema, estou a tentar fazer uma tabela onde no local do resultado retorne um valor mas de momento nada aparece. Agradecia imenso a vossa ajuda

    Objetivo 1

            <input id="DataInicio" type = "date" class = "datepicker" name = "DataInicio" />

            <input id="DataFim" type = "date" class = "datepicker" name = "DataFim" />

            <input id="avInicial1" type="text" class="validate"
                   autocomplete="off" name="AvInicial"
                   onchange="calculaResultado(1)">

            <input id="meta1" type="text" class="validate" autocomplete="off"
                   name="Meta" onchange="calculaResultado(1)">

            <input id="AvIntercalar" type="text" class="validate"
                   autocomplete="off" name="AvIntercalar">

            <input id="avFinal1" type="text" class="validate"
                   autocomplete="off" name="Avfinal" onchange="calculaResultado(1)">

            <input disabled id="resultado1"/>

Não retorna resultado PHP


Is it valid to perform Bayesian optimization and MCMC sampling with nested model parameters?

Question: I am trying to think of a way to perform a somewhat complicated Bayesian optimization problem involving model parameters which are nested within other functions in the forward problem, and I am wondering if this is alid from a theoretical perspective or if I am violating one of the criterion for MCMC sampling methods.
To simplify the problem to it's most basic situation, I have some data vector, $\mathbf{d}$ (with error $\mathbf{\sigma}$ and length $N$) from which I want to ascertain some model, $\mathbf{m}$. I have a forward operator, $F(\mathbf{m})$ which takes a model and computes predicted data, $\mathbf{d_p}$. From this, I construct a log likelihood function using a chi-square misfit assuming Gaussian errors:
$$\chi^2 = (\mathbf{d}-F(\mathbf{m}))^T\mathbf{C_d}^{-1}(\mathbf{d}-F(\mathbf{m}))$$
where $\mathbf{C_d}$ is an $N$ x $N$ matrix with $\mathbf{\sigma}$ on the diagonal.
My question concerns the forward operator, $F(\mathbf{m})$.
In my scenario, the forward operator is complicated and contains many nested functions. For example, suppose I have 5 model parameters, $m_1, m_2, ... m_5$. In my situation I might have:
$a = P(m_1)$
$b = Q(a, m_2, m_3)$
$c = R(a, b, m_4, m_5)$
$\mathbf{d_p} = S(a,b,c)$
where $P, Q, R,$ and $S$ are some very complicated functions. In order to actually compute predicted data, $\mathbf{d_p}$, I need $a,b$, and $c$. But my model parameters of interest are in $\mathbf{m}$.
Is this nested-variables approach valid for sampling the posterior?
Note: I have tried implementing the problem as written using a known model and I run into various problems. First and foremost the MCMC sampler gets "stuck" in an area of low probability (even though I know that there is a better solution with higher probability since I am using a known model). This does not happen if I try to sample $a, b$ and $c$ as model parameters. So I am wondering if there is some theoretical violation of the method.
Comment: (a) the $\chi^2$ expression is unlikely to be a likelihood function. Do you mean log- or negative log-likelihood? (b) I do not understand the distinction between $F(\mathcal m)$ and $\mathcal{d_p}$. (c) The model parameter is $\mathcal m$ and thus should be the one simulated, while $a,b,c$ are deterministic functions of $\mathcal m$. This seems unrelated with the use of MCMC or another simulation technique.
Comment: (a) Yes it should be log likelihood as you say. (b) $d_p = F(m)$ (i.e. in order to compute predicted data ($d_p$), I need to pass my model parameters through some function $F(m)$). (c) $m_1, m_2, m_3, ...$ are the unknown model parameters. As such $a, b, $ and $c$ are also unknown (and depend on $m$). I am trying to sample the posterior distribution (of e.g. $m$) given the likelihood (and some prior which at this point are just upper and lower limits on the modelled parameters).
Answer: Considering a likelihood function
$$\exp\{-(\mathbf d-F(\mathbf m))^2/\sigma^2\}$$
is equivalent to assume the observation is Normal. The posterior distribution is hence
$$\pi(\mathbf m|\mathbf d) \propto \exp\{-(\mathbf d-F(\mathbf m))^2/\sigma^2\} \pi(\mathbf m)$$
which can be simulated by an MCMC algorithm, no matter how complex the transform $F(\cdot)$ is. Simulating directly and jointly the triplet $(a,b,c)$ is feasible, but this requires the projected prior $\pi^\bot(a,b,c)$ to be available in close form.


How to Remove a VM From Hyper-V Without Deleting the Configuration File?

Question: I'm in the process of moving a number of virtual machines that are homed on shared storage (a file share, though shared cluster disk would work as well) to a new VM host with access to the same shared storage.  The new host is a different build version (moving from Windows Server 2012 Beta to Windows Server 2012 RC - though this same process could be used with migrations of Windows Server 2008/2008 R2 to Windows Server 2012 as well), so I cannot migrate the machine with inbox tooling.
I need to remove the VM from management of the source Hyper-V host in order to import the VM to the new Hyper-V host.  I want to retain the configuration file, so I can import the VM as it stands and not need to reconfigure it.
The VHD files are rather large and they are staying on the same file share, so I'd rather not duplicate them during the move process.
Answer: It is called configuration only export / import. Did you check this article by Ben Armstrong, Hyper-V Program Manager? Similar solutions are also described here and here.
Answer: It's insane that this is not built into HyperV manager, or at least as a flag to the Remove-VM commandlet.
I use a set of VMs produced by a co-worker. He exports them from his server and then I import them into my dev machine. When he has a new version, I want to import that but keep the old version around until I know the new one works. They have the same GUID so I can't have them in HyperV manager side-by-side.
What I do is go to the VM folder and just create a copy of the Virtual Machines. Then I delete the VM from hyper-v, which cause the config files from that folder to be removed. Then I just copy them back from my copy of the folder.
In my case this is not too hard, because each VM is fully contained in a single folder:
VM1
  - Virtual Hard Disks
  - Snapshots
  - Virtual Machines   (this is the folder to backup)
VM2
  - Virtual Hard Disks
  - Snapshots
  - Virtual Machines   (this is the folder to backup)

If your VMs config files are kept somewhere else you have to find the GUID of it and make a backup of it. This works as good, but is a bit more work


Ler arquivo com list comprehension só funciona na primeira vez

Question: fhand = open('text.txt', mode = 'r')
txtfile = [item.split()[0] for item in fhand]
txtfile2 = [item.split()[1] for item in fhand]
print(txtfile)
print(txtfile2)

Por que que o segundo list comprehension não está funcionando?
Mesmo se for exatamente igual, até o mesmo índice, o txtfile2 sempre aparece como uma lista vazia quando coloco ele no print.
Comment: `fhand` é um gerador e geradores só podem ser iterados apenas uma vez. Com a primeira list comprehession você já consome todo o seu gerador, por isso o segundo fica vazio. Como está usando o mesmo valor nas duas listas, o ideal é que faça ambas as lógicas em apenas um laço de repetição.
Comment: @Woss Negativo, `fhand` é um [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper). Diferente de um objeto da classe `generator`, caso seja chamado o método `seek`, o ponteiro pode voltar para a posição inicial da *stream*.
Comment: O objetivo do programa é quebrar o texto no arquivo em linhas ou em palavras?
Answer: Depois que você faz o primeiro for:
txtfile = [item.split()[0] for item in fhand]

O arquivo será lido até o fim. Então na próxima iteração não haverá mais nada a ser lido, e por isso a segunda lista fica vazia (imagine que fhand possui um "ponteiro interno" que indica a posição do arquivo em que ele está: ao fazer um for, todo o arquivo é lido e esse "ponteiro" estará apontando para o final do arquivo, por isso o segundo for não encontra mais nada para ler).
Nesse caso, uma alternativa é não usar list comprehension, e processar cada linha do arquivo de modo a obter os dados de cada uma das listas, e inseri-los separadamente:
txtfile = []
txtfile2 = []
with open('text.txt', mode='r') as fhand:
    for item in fhand:
        itens = item.split()
        txtfile.append(itens[0])
        txtfile2.append(itens[1])
print(txtfile)
print(txtfile2)

Note que usei with, que garante que o arquivo será fechado ao final.

Claro que se quiser, dá para fazer usando list comprehension:
with open('text.txt', mode='r') as fhand:
    txtfile, txtfile2 = map(list, zip(*[ item.split() for item in fhand ]))

Primeiro eu crio uma lista contendo as linhas devidamente splitadas, depois eu passo esta lista para zip, que retorna tuplas contendo os elementos de cada uma dessas sublistas (a primeira tupla contém o primeiro elemento do split de cada uma das linhas, e a segunda tupla contém o segundo), e por fim mapeio estas tuplas para list, para que se tornem listas, que por sua vez são colocadas em txtfile e txtfile2.
Mas na minha opinião é mais simples fazer o primeiro loop acima. Entendo que list comprehensions são legais e tal, mas você não deveria forçar o uso de algum recurso se este não se mostrar uma boa alternativa (e no caso, acredito que não seja, pois acho que o código ficou desnecessariamente mais complicado).

Como disseram nos comentários, uma outra alternativa é usar seek para que o "ponteiro" volte para a posição inicial do arquivo:
fhand = open('text.txt', mode = 'r')
txtfile = [item.split()[0] for item in fhand]

fhand.seek(0) # volta para o início do arquivo
txtfile2 = [item.split()[1] for item in fhand]

Só que aí você irá ler o arquivo duas vezes (e irá fazer o split em todas as linhas novamente), o que nesse caso me parece desnecessário, pois com a solução anterior você lê o arquivo apenas uma vez e já faz tudo que precisa.


Fender Stratocaster center pickup gets in the way of palm muting

Question: I have been playing guitar for probably about 10 years now and my primary guitar at the moment is an American Deluxe Fender Stratocaster with a humbucker for the bridge pickup and 2 single coils.  The tone of the guitar is beautiful and the fingerboard moves like butter, but I've always had trouble finding the right way to palm mute using this guitar.
The center pickup sits directly under where the pick naturally wants to be and always seems to be in the way... If I try to compensate by moving my hand right or left, my palm is no longer in the ideal spot to palm mute effectively.

When I'm not palm muting I simply strum in the space between the neck and center pickup, but I like to play a lot of heavier stuff which uses excessive palm muting.  The position of the center pickup just makes it feel awkward.
I know there's ton's of people out there who own Strats.  Even if you don't like metal, every style of music uses palm muting in one form or another.
How have you overcome this problem?
Answer: I see two options here. (The third one would be changing your hand position, but you've tried that already and it doesn't work). One would be to see if you really need to move your pick so deep into the strings. I play a Strat and when I palm mute, my pick is also right above the middle pick up but I rarely touch it because my pick doesn't go that deep. The other obvious option is to lower the middle pick up. Very little might be enough to avoid hitting it with the pick. The down side is of course that you lose some volume from the middle pick up. You might also try to just lower the top side of the pick up (because there's where the pick will touch) while leaving the lower end at its normal height. In this way you'll only lose a bit of volume in the lower strings, not in the higher ones.
But it is indeed a common problem. I've seen people rip out their middle pick up for that very reason. Oh, that's the third option then!
Comment: I actually more commonly scrape it when playing the higher strings since the pickup is more raised up for those strings.  Unfortunately it looks like a problem I just have to live with or somehow adapt to... My pickups are all at the recommended height and if I'm very careful I won't hit the middle pickup while palm muting, but it is still annoying.
Comment: @tjwrona1992: If the pick-up negatively affects your playing, you should do something about it. If I were you I'd lower it as much as necessary. If you feel that the sound becomes unbalanced when combining the middle PU with the other PUs, then you need to lower the other ones as well. The loss in output is no big deal with today's amplifiers. The instrument needs to be adapted to your needs, not the other way around. And don't worry about "recommended heights" for PUs, because if you look at the settings of pro players, you'll find that everybody chooses them differently.


How to find unique words from file linux

Question: i have  a big file, teh lines look like this
Text numbers etc. [Man-(some numers)] is lot of this Man-somenumbers is repeat in few lines, i want to count only unique Mans -words. I cant use unique file , because text before Man words is always different in each line.
How can i count only unique Man-somenumbers  words in file ?
Comment: A combination of `grep` and `wc` or `lc` should be a good start.
Answer: If I understand what you want to do correctly, then
grep -oE 'Man-[0-9]+' filename | sort | uniq -c

should do the trick. It works as follows: First
grep -oE 'Man-[0-9]+' filename

isolates all words from the file that match the Man-[0-9]+ regular expression. That list is then piped through sort to get the sorted list that uniq requires, and then that sorted list is piped through uniq -c to count how often each unique Man- word appears.
Comment: It worked without -o option also. When used -o option it said invalid option. I am using windows and using the commands inside GIT BASH from GIT installation.


Git cant create pull request | different commit histories | bfg --delete-files | git merge --allow-unrelated-histories

Question: For the past year we've been working with a staging and master branches, testing our changes before merging to master.Now when trying to pull request from staging to master I'm facing an error message on GitHub saying "master and staging are entirely different commit histories."
This worked perfectly well until we needed some help from Fiverr developers and decided to mess with our history - deleting the history of an env.ts file that in the past had a mistaken commit with api keys and sensitive data.
So to cover this mistake, I decided to run bfg --delete-files /src/env.ts
Which is supposed to delete the file from history, leaving just the latest version.
Well, it worked, the history of this file was deleted - so no more sensitive data there.
Fast forward a week - I want to merge some new change from staging to master and aparently the branch have lost sync. Github is showing me for staging that "This branch is 644 commits ahead of, 634 commits behind master." And when trying to create a pull request "master and staging are entirely different commit histories.".
I've seen this question with the answer from PaianuVlad23, suggesting to run "git merge staging --allow-unrelated-histories".
But I would love to receive your help tailored to my unique case of deleting history.
Creating a new staging branch is out of the question currently, I really want to get this back in sync.
Executed :
bfg --delete-files /src/env.ts
This changed my history and apparently staging and master are no longer in sync.
Now I'm afraid of proceeding without proper consultation.
I've also tried to find git experts on fiverr and upwork, but I couldn't really find anyone who dealt with similar cases.
Edit : checked my master branch on github, thats what I'm currently seeing
master seems compltely cut off from all other branches history wise
Answer: The same commit id means both commits are the same and have the same histories. If you change or delete a commit, all following commits have to be rewritten with new ids.
When you deleted those files you changed those commits. Git wrote new commits with new commit ids, and had to also rewrite all the following commits.
But any tags and branches will remain pointing at the old history. It's likely master is pointing at the new history, and staging is pointing at the old history.
a - b - c - d - e [staging]
     \
      c1 - d1 - e1 - f - g [master]

(Note: Github and git log both lie and show a linear history. A tool such as GitKraken or git log --graph --decorate will show the true history.)
In the example above, c got rewritten which means d and e also got rewritten. master points at the new history, staging at the old history. There's also a couple new commits to master (f and g) just to make the example interesting.
If there have been no commits to staging, simplest thing would be to delete staging and recreate it so it points at commit g (master)
$ git branch -f staging master
a - b - c - d - e
     \
      c1 - d1 - e1 - f - g [master]
                           [staging]

If there have been commits to staging, let's say h - i, you can rebase staging on master. If you just rebase, it might resurrect the deleted file in b. So you have to tell it to only rebase part of staging. Probably just the new part.
In the example below, we want to move h and i ontop of master. So we'll tell Git to rebase from e (but not including e) to staging (which is i).
a - b - c - d - e - h - i [staging]
     \
      c1 - d1 - e1 - f - g [master]

$ git switch staging
$ git rebase --onto master e staging
a - b - c - d - e - h - i
     \
      c1 - d1 - e1 - f - g [master]
                          \
                           h1 - i1 [staging]

The unreferenced commits will be garbage collected.
You may have to also recreate your tags on the new history.
Comment: The last scenario is probably most aligned with what I currently have,
Before seeing your answer, I switched to master and tried running git merge staging --allow-unrelated-histories.
This pulled up commits staging had ahead (c,d,e) in your example.
I then created 'x' on master to fix env.ts.

I'm getting this message after doing git switch staging :
Your branch and 'origin/staging' have diverged,
and have 635 and 644 different commits each, respectively.

It suggests git pull, should I pull or follow your original advice of git rebase master?
(just want a unified history)
Comment: also huge thanks for taking the time to explain what went wrong, its really helpful, your answer would have fixed my initial problem so I'm accepting it, but would really appreciate advice about my comment with what to do now that I made more mess by being hasty T_T
Comment: @AntonOlshanetsky 1) You do *not* want to merge them, do not pull (which will merge). Merging will bring that env.ts into master's history. 2) Everything can be undone, just don't delete your local clone, and don't force push anything. 3) If you're unclear about rebasing, try reading https://git-scm.com/book/en/v2/Git-Branching-Rebasing
Comment: @AntonOlshanetsky I've updated the rebase instructions to be more specific.
Comment: Ok I'm confused, my local staging is probably the only 'proper' branch I currently have.
With master having 'y' - merge commit that shouldnt be there, and 'x' some patch.
How to salvage this haha?
You said everything can be undone? how to undo what I did on master without another 'revert' commit that would complicate the history further?
Comment: @AntonOlshanetsky I can't advise further without seeing your history for the relevant parts. `git log --graph --decorate --oneline`. From your Github screenshot, staging only appears to be one commit ahead (what are you committing to staging?); if so that change can be [cherry picked](https://www.atlassian.com/git/tutorials/cherry-pick) onto master, then recreate staging off of master.


Difference between hook_node_view() and template_preprocess_node() with seeing messages

Question: When I add a form to a node's render tree using hook_node_view(), eg
<?php

/**
* Implements hook_node_view().
*/
function MODULE_node_view($node, $view_mode, $langcode){
  if ($node->nid == 9 && module_exists('contact')) {
    module_load_include('inc', 'contact', 'contact.pages');
    $cForm = drupal_get_form('contact_site_form');
    //$cForm['#action'] .= '?destination=' .    request_path();
    $node->content['contact_form'] = array(
    '#markup' => drupal_render($cForm),
    '#weight' => 20,
    );
  }
}

then I get my messages displayed right after the submission.
I do the same thing with template_preprocess_node(), the messages are displayed one request after the submission.
I suspect this is related to the execution order.  Can someone shed some light on the difference here?
Answer: It is the execution order. hook_node_view() acts on the node object as it is being assembled. When template_preprocess_node() is called, the node is ready to be rendered. For instance you may use template_preprocess_node() to change the date format.
Comment: Why does this result in the messages being one-page behind, though?
Comment: thx - but when is the form rendered ? (inbetween ;))
Answer: It is indeed related to execution order and how messages are handled by the theme layer.
The $messages variable (which contains system messages) is processed and output at the page level (page.tpl.php) which occurs before node (node.tpl.php). So by the time you invoke drupal_get_form() from your node preprocessor, $messages has already been set up.
So, although $_SESSION['messages'] has been populated with the validation errors via drupal_get_form(), these won't appear until a page refresh.
hook_node_view(), on the other hand, is outside the theme layer and is invoked even before page processing begins, which is why it works.  But if you want to make the change at the theme level, a workaround is to set up the messages manually after you call drupal_get_form() in template_preprocess_node():
$contact_form = drupal_get_form('contact_site_form');
$contact_form['#prefix'] = theme('set_messages');

Thanks to rémy for originally pointing out the problem on our site.
Comment: thx for the conclusion :D


Quotient of surface of genus 2

Question: Let $g$ be the quotient map from $M_2$ to $M_1$ (namely torus). Why $g$ induces isomorphism on $H_2$?
Also, Hatcher talks about the degree of $f$ from sphere to sphere in his book. Can it be generalized to any map between topological spaces $X$ and $Y$, if the highest homology groups of $X$ and $Y$ are $Z$? How?
Comment: What are $M_2$ and $M_1$?
Comment: surface of genus 2, surface of genus 1
Answer: For your first question, the simplest is probably to see that this is already true at the 2-cell level...
For you second question, see this page on the degree.
Comment: The reason why I asked the second question is because I want to see this problem geometrically.
Answer: It depends on the map, sometimes you will not get an isomorphism of $H_2$: For instance, suppose that $f: M_2\to M_1$ is a branched cover of degree $2$, then
$$
|H_2(M_1):f_*(H_2(M_2))|=2.
$$
More generally, you can realize any finite index.
See here for a geometric interpretation of degree in the smooth setting. This should answer many questions that you have. In general, one can define $n$-th degree for a map $f: X\to Y$, it is simply the index
$$
|H_n(Y): f_*(H_n(X))|.
$$
However, this notion is not very geometric once you leave the realm of topological $n$-manifolds (or pseudo-manifolds).
Comment: Does surjective map induce surjective map in homology? I mean, consider $\Delta$-complex.
Comment: As I said, the answer is negative: Branched covers are surjective.
Comment: What if this quotient map is squeezing one torus of $M_2$ into one point?
Comment: Then this has degree 1, as I said, you can get any finite number.
Comment: Can you explain why it has degree 1?
Comment: @Wwk: Preimage of a generic point has cardinality 1.
Answer: Let me update what I've learned now. We can actually define the degree of a map $f$ between two connected closed orientable n-manifolds $M$ and $N$, which is problem 3.3.7 in Hatcher's book on Page 258. Also it equals to the sum of local degree of $f$, which is problem 3.3.8.
The idea to prove 3.3.8 is similar to Hatcher's proof for spheres in section 2.2 (Proposition 2.30)
Just use the following commutative diagram. (I use two arrows to represent a diagonal arrow, since amscd doesn't support diagonal arrows)
$$
\require{AMScd}
\begin{CD}
@<\cong<< H_n(U_i,U_i-x_i) @>f_*>> H_n(V, V - y)\\
@VVV @VV k_i V @VV\cong V \\
H_n(M , M - x_i) @<p_i<< H_n(M , M - f^{-1}y) @>f_* >> H_n(N, N - y)\\
@AAA @AA j A @AA\cong A \\
@<\cong<< H_n(M) @>f_*>> H_n(N)
\end{CD}
$$

Quotient of surface of genus 2


Drupal 8 How to fix "URL is Incomplete" error at Facebook Instant Articles

Question: When I try to submit my HTML code for Facebook's new Instant Articles, I get the error below. This is the only error I get and it is displayed at the bottom of the pasted code.
URL is Incomplete: The URL used for this media element is missing information. We have automatically filled in information for you. Please check that the URL is now correct and complete.
Any idea how to fix that?
img src="/sit/to/img/" - wont work
img src="http://mydomain.de/path/to/img/"
help me please
Answer: As I understand it, the Pathologic module should fix this issue for you.

Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to "break;" for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site's RSS feeds. See more example use cases on the documentation page.
Comment: Pathologic Did not solve the problem
Comment: Did you configure it properly?
Comment: Probably yes, in the configuration I put the full path, in the filters of the editor it also turned it on, it probably did not help me, I need the same plug-in only for the field image.   sorry for my English
Comment: @АлексейМоргун Have you enabled pathologic filter on /admin/config/content/formats?


How does the formal definition of limit deal with functions that are not defined at multiple points, maybe even entire intervals?

Question: So the formal definition:
$(\forall \epsilon > 0)(\exists \delta > 0)(\forall x \in \mathbb{R})(0 < \mid x - x_0 \mid < \delta \implies \mid f(x) - L \mid < \epsilon)$
If this is true then we say $\lim_{x \to x_0} f(x) = L$. In my opinion, this really only makes sense if the function is defined for all values of $\mathbb{R} - \{x_0\}$. Say the function is not defined at a point different from $x_0$, call it $x_1$, then the expression  $\mid f(x_1) - L \mid < \epsilon$ doesn't make sense and we can't really assign a truth value to it, and so we can't really know if a specific $\delta$ that includes $x_1$ is good or not.
I thought about it and came up with two possible solutions, but I have my doubts about both. First we could modify the definition of limit so that it only works for values where the function is defined, for instance if $A \subseteq \mathbb{R}$ and the function is defined as $f:A \to\mathbb{R}$, we could tweak the formal definition so that it says:
$(\forall \epsilon > 0)(\exists \delta > 0)(\forall x \in A)(0 < \mid x - x_0 \mid < \delta \implies \mid f(x) - L \mid < \epsilon)$
This solution has a problem and the problem is that if a function is only defined at one point, call it $x_0$, then the limit as $x$ approaches $x_0$ would exist because the implication would always be vacuously true, but we don't want the limit to exist in such cases.
The second solution, which I think is the more natural one, is to define $\mid f(x) - L \mid < \epsilon$ as false when $f(x)$ is not defined for that specific value of $x$. This solution has the side effect that in order for the limit to be defined at a point $x_0$, the function would have to be defined on an open interval that contains $x_0$, with the possible exception of $x_0$ itself. The problem with that is that I was arguing with someone about it and they told me the limit should exist even when the function is not defined on one side of $x_0$, as long as it is defined on the other side.
So what is it then? How do you deal with functions that are not defined in points other than $x_0$?
Answer: For us to talk about the limit of $f$ at $x_0$, we require $x_0$ to be an accumulation point of the domain of $f$, that is, that for every $c>0$ there is some $x\in \operatorname{Dom}(f)$, with $x\neq x_0$, in $(x_0-c,x_0+c)$.
This is equivalent to saying that there exists a sequence in the domain of $f$ that converges to $x_0$ but is never actually equal to $x_0$.
In other case, $x_0$ is called an isolated point (of the domain) and it does not make sense to talk about the limit of $f$ at $x_0$.
Comment: OK, so I imagine that means if we have a function defined at $[2, 3]$ and nothing else and we want the limit at $3$, by your definition $3$ is an accumulation point, right? So the limit could exist in that case. But by my second interpretation it cannot exist since it's not defined on an open interval that contains $3$. How exactly do you make sense of the expression $\mid f(x) - L \mid < \epsilon$ when $f(x)$ is not defined? What is its truth value?
Comment: The limit at $3$ could perfectly exist. We do **not** need $f$ to be defined at an open interval around $3$. In your formal definition of limit, you need to force both $x\in \operatorname{Dom}(f)$ and $0<|x-x_0|<\delta$.
Comment: But the problem with doing that is that it would be equivalent to my first interpretation and that has the problem that limit would exist even if $x_0$ is not an accumulation point, for instance, the limit would exist if the function is only defined at one point. Consider a function only defined at $x_0$, then $x \in Dom(f) \text{ and } 0 < \mid x - x_0 \mid < \delta$ would be false for all values of $x$ and $\delta$, thus $(x \in Dom(f) \text{ and } 0 < \mid x - x_0 \mid < \delta) \implies (\mid f(x) - L \mid < \epsilon)$  would be true for all $\epsilon$, the limit would exist.
Comment: The definition requires $x_0$ to be an accumulation point. If it isn't, there's nothing to talk about.
Comment: I see, then the right approach would be my first interpretation of only checking values of $x$ that are in the domain, as well as specifying that $x_0$ must be an accumulation point. I decided to double check if this was the case in the book Mathematical Analysis by Zorich and seems that this is exactly what he does, but he uses the concept of a limit point, is that the same or equivalent to an accumulation point?
Comment: Yes, a limit point is the same as an accumulation point.


define recursive function in let form

Question: Is it possible in Clojure to define a recursive function inside a let form or should a letfn be used instead? For instance, can I do the below using let?
(defn blowStackExample []
  (letfn [(blowStack []
            (blowStack))]
    (blowStackExample)))

Comment: possible duplicate of [Non tail-recursive anonymous functions in Clojure](http://stackoverflow.com/questions/5626641/non-tail-recursive-anonymous-functions-in-clojure)
Answer: The way you can do it is by naming the anonymous function inside the fn form:
(defn blow-up-stack-example []
  (let [blow-up-stack (fn a [] (a))]
    (blow-up-stack)))

(blow-up-stack-example)

define recursive function in let form


Unable to migrate users

Question: I have been using the migrate module to migrate users from Drupal 7.59 to Drupal 7.59. I encounter the following error.
Migration for NonDomainUserMigration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054     [error]
Unknown column 'pgid' in 'on clause', in /app/includes/database/database.inc:2227

What could be the issue? I can't find any pgid column in the drupal database.
the following is my User migration code
<?php
abstract class NonDomainBaseMigration extends Migration {

  // A Migration constructor takes an array of arguments as its first parameter.
  // The arguments must be passed through to the parent constructor.
  public function __construct($arguments) {
    parent::__construct($arguments);

    // With migrate_ui enabled, migration pages will indicate people involved in
    // the particular migration, with their role and contact info. We default the
    // list in the shared class; it can be overridden for specific migrations.
    $this->team = array(
      new MigrateTeamMember('Moses Liao', 'email@example.com',
        t('Tech Lead')),
    );

    Database::addConnectionInfo('legacy', 'default', array(
      'driver' => 'mysql',
      'database' => 'zaobao_drupal',
      'username' => 'root',
      'password' => 'password',
      'host' => 'mysqldb',
      'prefix' => '',
    ));
  }
}

class NonDomainUserMigration extends NonDomainBaseMigration {
  public function __construct($arguments) {

    parent::__construct($arguments);
    $this->description = t('Legacy Zaobao Drupal 7 system Users');

    $query = Database::getConnection('default', 'legacy')
    ->select('users', 'u')
    ->fields('u');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationUser();

    $source_key = array(
      'pgid' => array('type' => 'int',
                      'unsigned' => TRUE,
                      'not null' => TRUE,
                      'description' => t('Source ID'),
                     )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key,
      MigrateDestinationNode::getKeySchema(), 'legacy', array('track_last_imported' => TRUE));

    $this->addSimpleMappings(
      array(
        'uid',
        'name',
        'pass',
        'mail',
        'theme',
        'signature',
        'signature_format',
        'created',
        'access',
        'login',
        'status',
        'timezone',
        'language',
        'picture',
        'init',
        'data',
      )
    );
  }
}

Comment: You are using a source id key that does not exist. It should be uid.
Answer: its seems to me that pgid is wrong. Should be uid for users

Unable to migrate users


Performance implications of many user roles

Question: How does each additional user role affect Drupal performance? Looking for insights from benchmarking (preferred) and/or code analysis.
Specifically:

Do additional user roles impact performance on a per page request
basis? (e.g. every page view will be slower for every user, or no?)
Is the performance impact of additional roles proportional to the number of modules installed? (eg performance hit proportional to
#roles * #modules, or no?)
Answer: I don't have any hard stats but based on several years of experience and knowing how Drupal works I would be extremely surprised if adding another user role made any appreciable difference at the page request level. The only difference will be when a user has multiple roles, but the amount of extra data required per role is tiny.
I have profiled page loads for all sorts of different site setups and never seen an issue relating to the number of user roles.
Having said that, adding extra roles can make administration more complicated, so you won't want to add new ones without a good reason. If you were to create a hundred user roles the main permissions panel would be unusable but I would be willing to bet that the effect on normal page loads would be negligible.


Normalize Weights in fitting a curve

Question: I am trying to fit a curve to set of data points. I have a set of weights that I want to assign each point while fitting. My question is that should i normalize the weights or use the weights as they are?
Are there any pros and cons of following one approach over the other.
Pardon me if the question is all too basic and it would really help if you can point me to some literature.
Comment: If no weights are used, they are all implicitly equal to 1.0. If all wights are set equal to 2.0, then the same results should still be given as no individual data point has more or less weight than any other data point. So the weights are relative, for example if all weights are set to 0.1 except for a single data point where it is set to 0.2 should give the same results as setting all weights to 10, except for that same point having a weight of 20. Normalization of the weights should not change their relative size, so it should have no effect.
Comment: Thanks a lot James, but wouldnt that depend on the way way we normalize..if we do a simple average, then what you say is right, but otherwise there might be some difference, right?
Comment: Well, if one of the normalized weights had a value of zero then the associated point is no longer used in the regression. So it does seem possible to normalize incorrectly.
Answer: Since you have not specified how your "weights" enter your particular model, it is not possible to definitively say what you can and can't do with them.  However, in most models that use weights, the model is amenable to any weighting vector that has non-negative weights.  It is usually possible to scale the weights to "normalise" them, but in most models this is not necessary.  Nevertheless, it can make sense to normalise a weighting vector to make it comparable to the standard case where there is no weighting.
In a standard statistical analysis, all the data points have the same weighting in the analysis, which means that they all have an implicit weight of one.  Thus, in a standard analysis with $n$ data points you could say that you have an implicit weighting vector $\mathbf{u} = (1, ..., 1)$.  Since there are $n$ values, we have $||\mathbf{u}|| = \sqrt{n}$.  Hence, if you want to normalise a weighting vector $\mathbf{w}$ to give the magnitude of the standard case you would usually set the normalised weight vector as:
$$\tilde{\mathbf{w}} \equiv \mathbf{w} \cdot \frac{\sqrt{n}}{||\mathbf{w}||} \quad \quad \quad \implies \quad \quad \quad ||\tilde{\mathbf{w}}|| = \sqrt{n}.$$
Comment: Thanks a lot for the answer Ben. The weight themselves are normally distributed and taken from another distribution - is this what you mean when you say how the weights enter the model?
Comment: @nimbus3000: When you say that they are normally distributed, does this mean you have some negative weights?  What does that mean exactly?
Comment: No, all positive weights....the weights are a measure of volatilities which are normally distributed...they cant be negative
Comment: @nimbus3000: Just be careful here, because the normal distribution generates values over all the reals, including negative values.  In any case, what I mean when I talk about weights "entering a model" is that in regression, GLMs, etc., there is usually provision for an allowance for weights on the observations.  The models are usually constructed in a way that normalisation of the weights is unnecessary, but the above method gives a simple normalisation that can be used to obtain a fixed norm.

Normalize Weights in fitting a curve


How can I generate Unix timestamps?

Question: Related question is "Datetime To Unix timestamp", but this question is more general.
I need Unix timestamps to solve my last question. My interests are Python, Ruby and Haskell, but other approaches are welcome.
What is the easiest way to generate Unix timestamps?
Comment: @A.B.Carroll Can you please explain as an anwer how your online tool provides Unix timestamps? Please, attach a manual etc for it. It seems to provide a lot of data but I cannot really follow what is the target.
Comment: `gettimeofday` is the POSIX and Linux syscall name: https://stackoverflow.com/questions/11765301/how-do-i-get-the-unix-timestamp-in-c-as-an-int/11765379#11765379 TODO: why `strace date +%d` not call it?
Comment: If you work with, and increment time ranges (e.g. minutes, days, hours), I wrote a tool for my own use recently https://unixtime.ninja
Answer: In Linux or MacOS you can use:
date +%s

where

+%s, seconds since 1970-01-01 00:00:00 UTC. (GNU Coreutils 8.24 Date manual)

Example output now 1454000043.
Comment: On Solaris:
  truss date 2>&1 | grep ^time | awk '{print $3}'
Comment: BSD date supports also +%s. Probably universal, as `date` is normally defined in POSIX.2.
Comment: @ĽubomírMlích On a SmartOS host (SunOS 5.11 joyent_20171026T003127Z), I've both `/usr/bin/date +%s and `/usr/xpg4/bin/date +%s` working. Combined with the POSIX.2 recommendation, I think this works on all Solaris too.
Comment: Note: to add 60 seconds: `date -v+60S +%s` to add 1 day: `date -v+24H +%s` and so on . . .
Comment: How to generate milliseconds upto 3 digit only ?
Comment: One liner for Fish shell users who want a `ut` command that copies to clipboard: `abbr --add ut "date +%s | xsel --clipboard"` (may have to install `xsel` package. ut = unixtime, you could also use the latter.
Comment: If you'd like to show timestamp till specific day, we can use: `date +%s -d YYYYMMDD` (Replace YYYY MM DD with year, month, and day)
Answer: in Ruby:
>> Time.now.to_i
=> 1248933648

Comment: for rails you can use `Time.zone.now.to_i`. Though it'll give the same o/p as `Time.now.to)_i` but `Time.zone.now.to_i` is the `Rails` way.
Comment: In Rails, `./bin/rails runner "p Time.current.to_i"` is another solution.
Answer: In Bash 5 there's a new variable:
echo $EPOCHSECONDS

Or if you want higher precision (in microseconds):
echo $EPOCHREALTIME

Comment: I think this one is the most useful of all I've seen
Comment: In case of `zsh` one may need to load the `zsh/datetime` module (https://zsh.sourceforge.io/Doc/Release/Zsh-Modules.html#The-zsh_002fdatetime-Module) using the command `zmodload zsh/datetime` before being able to use these variables.
Answer: curl icanhazepoch.com
Basically it's unix timestamps as a service (UTaaS)
Comment: Service [offline](https://major.io/2022/07/28/extra-icanhazip-services-going-offline/) since 17th august 2022
Comment: Heh, nice. This inspired me to add a similar feature to my hobby site. `curl -L -H "Accept: application/json" unixtimesta.mp` will give you `{"datetime":"Thu, 19 Jul 2018 12:01:21 GMT","timestamp":1532001681}`
Answer: In python add the following lines to get a time stamp:
>>> import time
>>> time.time()
1335906993.995389
>>> int(time.time())
1335906993

Answer: $ date +%s.%N

where (GNU Coreutils 8.24 Date manual)

+%s, seconds since 1970-01-01 00:00:00 UTC
+%N, nanoseconds (000000000..999999999) since epoch

Example output now 1454000043.704350695.
I noticed that BSD manual of date did not include precise explanation about the flag +%s.
Comment: FYI, `%N` isn't documented the man page for date in macOS 10.13.1 (High Sierra) and doesn't work. The sample output I got is: `1523342391.N`.
Comment: On macOS there's `gdate` in Homebrew https://apple.stackexchange.com/a/135749/181223
Comment: Why do you include nanoseconds by `+$N`? Is it included in the UNIX timestamp in some systems?
Answer: In Perl:
>> time
=> 1335552733

Answer: The unix 'date' command is surprisingly versatile.

date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"

Takes the output of date, which will be in the format defined by -f, and then prints it out (-j says don't attempt to set the date) in the form +%s, seconds since epoch.
Comment: `date: invalid option -- 'j'`
Comment: That's a GNU date extension, not in the Unix standard (POSIX).
Answer: First of all, the Unix 'epoch' or zero-time is 1970-01-01 00:00:00Z (meaning midnight of 1st January 1970 in the Zulu or GMT or UTC time zone).  A Unix time stamp is the number of seconds since that time - not accounting for leap seconds.
Generating the current time in Perl is rather easy:
perl -e 'print time, "\n"'

Generating the time corresponding to a given date/time value is rather less easy.  Logically, you use the strptime() function from POSIX.  However, the Perl POSIX::strptime module (which is separate from the POSIX module) has the signature:
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) =
                                     POSIX::strptime("string", "Format");

The function mktime in the POSIX module has the signature:
mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

So, if you know the format of your data, you could write a variant on:
perl -MPOSIX -MPOSIX::strptime -e \
    'print mktime(POSIX::strptime("2009-07-30 04:30", "%Y-%m-%d %H:%M")), "\n"'

Answer: in Haskell
import Data.Time.Clock.POSIX

main :: IO ()
main = print . floor =<< getPOSIXTime

in Go
import "time"
t := time.Unix()

in C
time(); // in time.h POSIX

// for Windows time.h
#define UNIXTIME(result)   time_t localtime; time(&localtime); struct tm* utctime = gmtime(&localtime); result = mktime(utctime);

in Swift
NSDate().timeIntervalSince1970 // or Date().timeIntervalSince1970

Answer: For completeness, PHP:
php -r 'echo time();'

In BASH:
clitime=$(php -r 'echo time();')
echo $clitime

Comment: for bash we already have the `date` command, so I don't think it is necessary to call php from there.
Answer: In Haskell...
To get it back as a POSIXTime type:
import Data.Time.Clock.POSIX
getPOSIXTime

As an integer:
import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime

Answer: public static Int32 GetTimeStamp()
    {
        try
        {
            Int32 unixTimeStamp;
            DateTime currentTime = DateTime.Now;
            DateTime zuluTime = currentTime.ToUniversalTime();
            DateTime unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            return 0;
        }
    }

Answer: Let's try JavaScript:
var t = Math.floor((new Date().getTime()) / 1000);

...or even nicer, the static approach:
var t = Math.floor(Date.now() / 1000);

In both cases I divide by 1000 to go from seconds to millis and I use Math.floor to only represent whole seconds that have passed (vs. rounding, which might round up to a whole second that hasn't passed yet).
Comment: This is wrong. Both methods return `milliseconds` not seconds and unix timestamp is the number of `seconds` that have elapsed since January 1, 1970 00:00 UTC. You can use JS, just divide by 1000 and round: `Math.round(Date.now()/1000)`
Comment: @LukasLiesis must've been pre-coffee that day, I've updated my answer although I opted for `Math.floor` instead of `Math.round`.  Cheers
Answer: If I want to print utc date time using date command I need to using -u argument with date command.
Example
date -u

Output
Fri Jun 14 09:00:42 UTC 2019

Answer: nawk:
$ nawk 'BEGIN{print srand()}'

Works even on old versions of Solaris and probably other UNIX systems, where '''date +%s''' isn't implemented
Doesn't work on Linux and other distros where the posix tools have been replaced with the GNU versions (nawk -> gawk etc.)
Pretty unintuitive but definitelly amusing :-)
Answer: For Unix-like environment the following will work.
# Current UNIXTIME
unixtime() {
  datetime2unixtime "$(date -u +'%Y-%m-%d %H:%M:%S')"
}

# From DateTime(%Y-%m-%d %H:%M:%S)to UNIXTIME
datetime2unixtime() {
  set -- "${1%% *}" "${1##* }"
  set -- "${1%%-*}" "${1#*-}" "${2%%:*}" "${2#*:}"
  set -- "$1" "${2%%-*}" "${2#*-}" "$3" "${4%%:*}" "${4#*:}"
  set -- "$1" "${2#0}" "${3#0}" "${4#0}" "${5#0}" "${6#0}"
  [ "$2" -lt 3 ] && set -- $(( $1-1 )) $(( $2+12 )) "$3" "$4" "$5" "$6"
  set -- $(( (365*$1)+($1/4)-($1/100)+($1/400) )) "$2" "$3" "$4" "$5" "$6"
  set -- "$1" $(( (306*($2+1)/10)-428 )) "$3" "$4" "$5" "$6"
  set -- $(( ($1+$2+$3-719163)*86400+$4*3600+$5*60+$6 ))
  echo "$1"
}

# From UNIXTIME to DateTime format(%Y-%m-%d %H:%M:%S)
unixtime2datetime() {
  set -- $(( $1%86400 )) $(( $1/86400+719468 )) 146097 36524 1461
  set -- "$1" "$2" $(( $2-(($2+2+3*$2/$3)/$5)+($2-$2/$3)/$4-(($2+1)/$3) ))
  set -- "$1" "$2" $(( $3/365 ))
  set -- "$@" $(( $2-( (365*$3)+($3/4)-($3/100)+($3/400) ) ))
  set -- "$@" $(( ($4-($4+20)/50)/30 ))
  set -- "$@" $(( 12*$3+$5+2 ))
  set -- "$1" $(( $6/12 )) $(( $6%12+1 )) $(( $4-(30*$5+3*($5+4)/5-2)+1 ))
  set -- "$2" "$3" "$4" $(( $1/3600 )) $(( $1%3600 ))
  set -- "$1" "$2" "$3" "$4" $(( $5/60 )) $(( $5%60 ))
  printf "%04d-%02d-%02d %02d:%02d:%02d\n" "$@"
}

# Examples
unixtime # => Current UNIXTIME
date +%s # Linux command

datetime2unixtime "2020-07-01 09:03:13" # => 1593594193
date -u +%s --date "2020-07-01 09:03:13" # Linux command

unixtime2datetime "1593594193" # => 2020-07-01 09:03:13
date -u --date @1593594193 +"%Y-%m-%d %H:%M:%S" # Linux command

https://tech.io/snippet/a3dWEQY
Answer: With NodeJS, just open a terminal and type:  node -e "console.log(new Date().getTime())" or node -e "console.log(Date.now())"
Answer: In Rust:
use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let now = SystemTime::now();
    println!("{}", now.duration_since(UNIX_EPOCH).unwrap().as_secs())
}

Answer: If you need a Unix timestamp from a shell script (Bourne family: sh, ksh, bash, zsh, ...), this should work on any Unix machine as unlike the other suggestions (perl, haskell, ruby, python, GNU date), it is based on a POSIX standard command and feature.
PATH=`getconf PATH` awk 'BEGIN {srand();print srand()}'

How can I generate Unix timestamps?


Why adding two large integers whose result greater than int.MaxValue doesn't throw overflow exception?

Question: If we are using the following loop in a program, the loop never ends in C# 4.0
for (int i = 1; i <= int.MaxValue; i++)
{
}

This is because adding 1 to int.MaxValue (2147483647) will not result in an overflow exception, but results in -2147483648 (taking into consideration 32bit int and 2's compliment).
int i = int.MaxValue;
Console.WriteLine(i + 1);

It seems the behavior changed recently. See the question Arithmetic operation caused OverflowException .What could be the reason behind this change?
Comment: This loop should end when `i == int.MaxValue`.
Answer: Overflow exceptions for integer (and other integral types) are only done in checked contexts.
So, this will cause an exception:
checked
{
 int i = int.MaxValue;
  Console.WriteLine(i + 1);
}

They are not set to do this by default as they are more expensive than simply overflowing.
From MSDN:

The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.

And:

Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword.

This is not a recent change - C# has been like this from  day one. What you see in the question is VB.NET code, which is by default in a checked context.
So, keeping to defaults, overflowing code in VB.NET will throw an exception, but identical code in C# will not.
Comment: That's interesting.  I didn't realize that the differences between VB.Net and C# were more than skin-deep.


Displaying three different states in Windows Store / WinRT in XAML with templates

Question: I have provided the mockups of three different forms that represent an Employee object when it is null, in edit state and saved state. I'm not using WPF or Silverlight, but WinRT / Windows Store.
There are few different ways to achieve this UI. The first approach is to have three different user controls. That is too much to manage when there are 10 of such entities - 30 forms to manage the state of an entity. A single usercontrol containing a contentcontrol with three different data templates and a contenttemplateselector is easy to manager than the previous approach.
I know VisualStateManager is suitable for controls whose visual state has to change based on events. Is VisualStateManager useful for a UI scenario that I described above? Or using a contentcontrol with a contenttemplateselector is the right approach to solve this?
The technical challenge is the app has numerous entities/objects and the first screen (Empty State) at least should be reusable for all the entities. The second and third forms can't be because they are different for every entity.
Please share your approach to this problem - DataTemplate Vs VisualStateManager Vs Style?
Comment: I see someone has voted to close this question and I think this is because you are inviting personal opinions, while StackOverflow is about answering questions rather than more philosophical/opinionated chats.
I'd suggest rewording the question to keep it up.
Comment: Are you asking about whether `DataTemplate` or VSM is better for your scenario? Is this going to be more of a full-screen design or just a list item?
Comment: Yes. I'm not that familiar with VSM, so don't know whether VSM is the best for scenarios like this. This is a full-screen design. You will see only the form on the entire screen.
Answer: Either option should work just as well, though with VSM you can get animated transitions, while with just templates - you won't.


Can I add fields to bundle classes?

Question: The docs I've found so far tell how to add bundle-specific fields in either hook_entity_bundle_field_info() or in bundleFieldDefinitions() in my content entity class.  While those work it seems cumbersome since they put all bundle field definitions in the same place.  Since bundle classes extend a content entity class, it seems like it would be a lot cleaner to define additional fields in the bundle class they belong to.
Is that possible?
I've tried both implementing bundleFieldDefinitions() and overriding baseFieldDefinitions() in my bundle class, but it appears they never get called there.
Comment: Your .module file looks like it's still implementing hook_entity_bundle_info_alter().  See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_bundle_info/9.4.x and define your bundles like this
$bundles['my_type']['my_bundle'] = [
    'label' => t('My bundle'),
    'class' => MyBundle::class
  ];
Comment: Is your module available publically? Trying to implement bundle class but not able to succeed
Comment: This is currently a work project.  I do plan on creating an example module and making that public when I get this all figured out.
Comment: Cool, I have created a module if you can have a look , pls let me know what went wrong. I used the different hook in . module as you suggested in different thread but still no success. https://git.drupalcode.org/project/omdb_api
Comment: For your bundle fields, see https://api.drupal.org/api/drupal/core%21modules%21system%21tests%21modules%21entity_schema_test%21entity_schema_test.module/9.4.x
Answer: I was able to do this by implementing bundleFieldDefinitions in both my content entity class and my bundle class.  The bundle class defines its fields, then the entity class bundleFieldDefinitions() determines the bundle and calls the appropriate bundle class bundleFieldDefinitions()

Can I add fields to bundle classes?