Laravel eloquent returns an unsigned integer column's records limited to 2147483647

Question: So I have this column in MySQL with unsigned integer data type of which some of the records values are bigger than 2147483647, the max positive number of a signed integer.
I ran a query with Laravel's eloquent ORM but the records with a value bigger than 2147483647 were returned as 2147483647. I read somewhere that eloquent has some issues with windows, which is the OS I'm using right now with XAMPP environment. And so I tried using the query builder instead of eloquent ORM and turned out the values were returned correctly. I haven't tried running the code on the other OS though, I'll try and do it then come back with an update, but finding out in which OS it's working is not the main reason I'm coming here.
I'm still a student right now and new to Laravel, so I was wondering if someone can shed a light on the matter as to what could have caused that and what to consider if I were to use Laravel eloquent in the future.
Comment: I believe your question was answered here:
[Laravel bigInteger being rounded to int in relationship](https://stackoverflow.com/questions/44688889/laravel-biginteger-being-rounded-to-int-in-relationship)
Answer: It's MySQL constraint, so you can just use BIGINT with max value of 18446744073709551615:
$table->bigInteger('votes'); // For columns.
$table->bigIncrements('id'); // For keys.

https://laravel.com/docs/5.3/migrations#columns
Comment: I already did that but turned out to be the same. Still returned 2147483647 with eloquent and correct values with query builder. I checked the table in phpmyadmin before and after i changed the column to bigint and the values there are correct both of the times


Topology proof question?

Question: How to prove that $X_1 := \{(x, y, z) ∈ \mathbb{R}^3 : x^2 + y^2 = 1\} / (S^1 × \{0\} )$ is homeomorphic to the union $X_2$ of two tangent spheres minus two points?
What I know:
Let  $C$ be cylinder $:=\{(x, y, z) ∈ \mathbb{R}^3 : x^2 + y^2 = 1\}$,
$ (S^1 \times \{0\})$ collapses the circle in the $xy$-plane to a point which leaves a double cone connected by a single point which is given by the equation $x^2+y^2=z^2$.
So, firstly, we need to find an identification turning the cylinder into the infinite cone.
Could I please get a hint on how to do that?
Looking at the coordinate function for z, would it be the homeomorphism between 0 to (0,+infinity)
f_z: {0} $\to$ (0,+ infinity)
z $\to$ 1/z
Comment: You or whoever made the edit seem to have missed some curly parentheses in the definition of $\;X_1\;$. Is that an infinite cyclinder *over* (i.e., quotient space) $\;S^1\times\{0\}\;$ , or what? And then you use $\;X_1\;$ *again* ...!?
Comment: It is S^1 x {0} but the curly brackets are not showing up..
Comment: Yes, I see. Some days now the site's MathJax hasn't been working properly. Thank you. Yet, why do you have that slash "/" there? This misleads. Shouldn't it be an equality sign?
Comment: They've fixed it now.
Comment: In your first line there's **still** appears a backslash "/" before $\;(S^1\times \{0\})\;$ ? Why? Shouldn't this be an equality sign instead?
Comment: This is how it is written in the question.
Comment: Then $\;X_1\;$ is **not** the cylinder you denote afterwards as $\;C\;$ ...!
Comment: But isn't x^2+y^2=1 in R^3 the equation of an unbounded cylinder?
Comment: @Useer Yes, it is: that is $\;C\;$ , *not* $\;X_1\;$, which seems to be an infinite cylinder minus a circle, yet I still cannot understand what does $\;S^1\times\{0\}\;$ really means *in the three dimensional real space* . Perhaps they meant $\;\{(x,y,0)\;:\;\;x^2+y^2=1\}\;$ ?
Comment: Would it be the unit circle in the xy plane?
Comment: That's what I think: the quotient space of the infinite cylinder $\;C\;$ by the unit circle on the $\;xy$- plane...
Comment: Could you tell me how to find the map the x,y,z in X_1 to turn it into an infinite cone?
Comment: This is pretty confusing for me. Perhaps someone else with more practice can help: the space $\;S^1\times\{0\}\;$ can be seen, imo, as a circle (which exists in $\;\Bbb R^2\;$ or in any other plane) "coordinated" by that $\;0\;$ there, yet I can't understand how this fits in $\;\Bbb R^3\;$. Sorry.
Comment: @Timbuc The set $S^1 \times \{0\} = \{(x,y,z) \in \mathbb{R}^3: x^2 + y^2 = 1, z = 0\}$ is identified to a point (so we have a modding out by an equivalence relation), hence the forward slash (it's a standard notation, if $X$ is a space and $A \subset X$, we define $X / A$ this way).
Comment: @HennoBrandsma Thanks a lot. I know what a quotient space is and what the backslash means (read the above comments), yet I just couldn't understand why $\;S^1\times \{0\}\;$ is the unit circle on the $\;xy$-plane, though I and the OP already "suspected" it is what you say it is. Is it perhaps a wide agreement in (algebraic or pointwise) topology?
Answer: Consider the two spheres $N$ and $S$, each with radius 1, $N$ with center $(0, 0, 1)$ and $S$ with center $(0, 0, -1)$. Now look at the following map from $C$ to $N \cup S$:
For $(x, y, z) \in C$ with $z > 0$, define $h(x, y, z)$ to be the intersection of the segment from $(x, y, z)$ to $(0, 0, 0)$ with $N$; for $z < 0$, define it to be the intersection of the segment with $S$. (In brief: consider $h$ as "the inverse of stereographic projection from the origin of $A \cup B$ to $C$").
For $(x, y, 0) \in C$, define $h(x, y, z) = (0, 0, 0)$.
I'm going to assume you can prove that $h$ is continuous, and that its image misses only the north pole of $N$ and the south pole of $S$. Let's say that $N$, without its north pole, is $N_0$ and similarly for $S_0$. (Note that $N_0 \cup S_0 = X_2$.) So $h: C \to S_0 \cup N_0$ is a surjection.
Now all that's left is to see that $h$ passes to the quotient. Well, $h$, restricted to
the $z = 0$ circle of $C$, is the constant map to the origin. So we get a map $\bar{h}: X_1 \to S_0 \cup N_0$ defined by
$$
\bar{h}(\pi(p)) = h(p)
$$
where $\pi :C \to X_1$ is the projection onto the quotient.
$\bar{h}$ is the required homeomorphism.
Comment: Sorry for the stupid question but what is A and B?
Comment: My mistake: those were my earlier names for "N" and "S", and I used them by mistake. Fixed now.
Comment: Thank you. Is the mapping i have added into the question for turning the cylinder into an infinite cone correct?
Comment: The domain of your supposed homeomorphism seems to be the single number 0, while the codomain is an interval, so that doesn't really make sense. And there's no homoemorphism from $\mathbb R^3$ to $\mathbb R^3$ that carries the cylinder $C$ onto the double-cone at the origin in the way you're hoping, because it would have to send the whole $S^1 \times \{0\}$ to the origin, hence would not be a homeomorphism.
Comment: Thank you so much. Could you please tell me why neither space(X_1 or X_2) is locally Euclidean?
Comment: Look at a neighborhood of the origin in either $X_1$ or $X_2$: deleting the origin will cause this neighborhood to separate into two components. But deleting a single point from the interior of an open disk in $\mathbb R^2$ never does this. Hence your neighborhood of the origin cannot be homeomorphic to an open disk in $\mathbb R^2$.

Topology proof question?


How do vectors as inputs work in interpreted matlab function block in Simulink?

Question: I have this function writen in matlab:
function out = summa(in1,in2)
out = in1(1)+ in1(2)+ in1(3)+ in1(4)+ in1(5)+ in1(6)+ in2(1)+ in2(2)+ in2(3)

And I've implemented it in simulink as follows:

And inside the matlab function block I've writen
summ(u(1),u(2))

I get the following error:

The function works fine if I input the vectors from the console, as follows:
summa([1 2 3 4 5 6],[1 2 3])

I get 27 as output
What am I doing wrong? I have a feeling the mux does not work like I want it to or that the arguments to the block are incorrect.
Answer: You are correct - the mux block isn't doing what you think.
The input to the Interpreted MATLAB block is a 9 element vector, with u(1) and u(2) being the first two elements of that vector.  Hence in the function in1 and in2 are both scalars and you can't access more than the first/only element of them.  Trying to access in1(2), etc, throws the error you are seeing.
You should use a MATLAB Function block with the following code within it,
function y = fcn(in1,in2)

coder.extrinsic('summa'); % This allows you to call the  external function
y = 0;  % This tells Simulink that the output will be a double
y = summa(in1,in2);

You'll see that the block has 2 inputs, and you should feed the output of your constant blocks into them separately.
Or even better, if possible, don't use the external function at all.  Put all of your code into the function within the MATLAB Function block,
function out = fcn(in1,in2)

out = in1(1)+ in1(2)+ in1(3)+ in1(4)+ in1(5)+ in1(6)+ in2(1)+ in2(2)+ in2(3);

Comment: Thank you I undestand now why it fails. I've modified the summa(u(1),u(2)) to summa(u(1:6),u(7:9)) and it works like I want it to. I am using the intepreted Matlab Function because my tutor told me its better for passing  code from one place to another without problems. And also the function I use is generated automaticly by matlab using the matlabFunction, I simplifyed the problem to it would be more understandable. Thank you again :)


Custom Authentication Page - Apache mod_auth_form - Error 405 Method Not Allowed

Question: I am having trouble trying to get the apache mod auth_form to work.
I have a sub-domain that i wish to protect and use for various administrative features on my website.
When i submit the auth form i get:
Method Not Allowed

The requested method GET is not allowed for the URL /admin/index.html.

I have followed to my best ability the instructions in that docs here:
http://httpd.apache.org/docs/current/mod/mod_auth_form.html
and here:
http://httpd.apache.org/docs/current/mod/mod_session.html
I am also using Apache 2.4.9, with all required modules for this to work loaded.
So i have set up the sub domain as follows:
/index.html (Public root / auth form)
/admin/index.html (The contents of the folder i wish to protect)

/index.html contains the following:
<form method="POST" action="/admin">
    User: <input type="text" name="httpd_username" value="" />
    Pass: <input type="password" name="httpd_password" value="" />
    <input type="submit" name="login" value="Login" />
</form>

For the Vhost block that controls the sub-domain, i have added the following (noting that i am enabling GET and POST for this domain as the default sees these disabled):
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    ServerName mydomain.com
    ServerAlias admin.mydomain.com

    DocumentRoot /var/www/mydomain.com/admin/

    <Directory /var/www/mydomain.com/admin/>
        <LimitExcept GET POST>
             Require all denied
        </LimitExcept>
        Options -ExecCGI -FollowSymLinks -Includes -Indexes -MultiViews
        Require all granted
    </Directory>

    <Location /admin>
        SetHandler form-login-handler
        AuthFormLoginRequiredLocation http://admin.mydomain.com/index.html
        AuthFormLoginSuccessLocation http://admin.mydomain.com/admin/index.html
        AuthFormProvider file
        AuthUserFile /var/www/mydomain.com/admin_inc/.htpasswd
        AuthType form
        AuthName realm
        Session On
        SessionCookieName session path=/private;domain=admin.mydomain.com;httponly;secure;
        SessionCryptoPassphrase secret
    </Location>

</VirtualHost>

In the apache error log I get the following:
[Mon May 19 10:26:38.xxxxxx 2014] [auth_form:error] [pid xxxxx] [client xxxxxx:xxxxx] AH01811: the form-login-handler only supports the POST method for /admin/index.html, referer: http://admin.mydomain.com/

If anyone could explain to me what i have done wrong here in order to create this error, it would be greatly appreciated, thank you!
Answer: I finally got this working, and I had stepped on this question while trying to find solutions to my problems.
You are getting this error because your call is intercepted by the form-login-handler, which only supports POST.
The trick is that the SetHandler directive should only be active for the URL that will be used as the action of the authentication form. All other protected resources should use the same configuration, but without this handler.
Here's a working configuration :
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    ServerName example.com
    ServerAlias www.example.com

    DocumentRoot /var/www/example.com/

    <Location /admin>
        # Protect all resources under /admin with form auth. Note that the login form is NOT under /admin : not sure this is required, but this is how I got it working
        AuthFormLoginRequiredLocation http://www.example.com/index.html
        AuthFormLoginSuccessLocation http://www.example.com/admin/index.html
        AuthFormProvider file
        AuthUserFile /var/www/example.com/.htpasswd
        AuthType form
        AuthName realm
        Session On
        SessionCookieName session path=/private;domain=www.example.com;httponly;secure;
        SessionCryptoPassphrase secret
    </Location>
    <Location /admin/dologin>
        # Since this location is a sub-path of the previous one, it inherits all parameters above
        # It will be the only URL to be able to process form logins, and the only one to require POST
        SetHandler form-login-handler
    </Location>

</VirtualHost>

Of course you need to set your action attribute in the form to the login handler url :
<form method="POST" action="/admin/dologin">
    User: <input type="text" name="httpd_username" value="" />
    Pass: <input type="password" name="httpd_password" value="" />
    <input type="submit" name="login" value="Login" />
</form>

Hope this helps someone (eventhough this thread is 4 years old ! :) )
Answer: You are somehow sending the login credentials with some method that is not POST¹. Maybe double-check your login form?
¹http://code.ohloh.net/file?fid=Pwx9mfavxhieWn8XSiBldWz63zI&cid=h1J7pf7LYjw&s=&fp=305270&mp&projSelected=true#L1127


Selecting Android API level in Qt QMake

Question: I'm using Qt 'qmake' from the command line (no use of QtCreator) am building for an Android target.  No matter what I do it seems to use Android API level 9 in the Makefile it generates.  Is there a command-line option, environment variable, or other method I can use to tell qmake to use a specific Android API level.  I've been searching for a long time and cannot find anything.
Answer: Change environment to ANDROID_NDK_PLATFORM=android- the api-level you want or in QtCreator->Project->Build Environment->Add/update the above variable.
Answer: To choose a specific minimum API level, you need to provide your own Android manifest file.
I know you're not using Qt Creator, but it supports this by being able to generate a new manifest file from a template.
More details available from the Qt Docs on deploying to Android:
http://doc.qt.io/qtcreator/creator-deploying-android.html

You can specify settings for the androiddeployqt tool in Qt Creator and in the project .pro file. To specify settings in Qt Creator, select Projects > Build Android APK > Details.
...
You can use the qmake variables to specify all the settings you need for the androiddeployqt tool and you do not need an Android manifest file until you want to publish the package in an application store. To specify additional settings for APK packages, you can create an Android manifest file and edit it in Qt Creator. Select Create Templates to create the file and to open it in the Android Manifest Editor.

If you're not using Qt Creator you'll presumably need to generate an Android manifest file manually and place it in your source directory.  androiddeployqt should pick it up.

ANDROID_PACKAGE_SOURCE_DIR: This variable can be used to specify a directory where additions and modifications can be made to the default Android package template. The androiddeployqt tool will copy the application template from Qt into the build directory, and then it will copy the contents of the ANDROID_PACKAGE_SOURCE_DIR on top of this, overwriting any existing files.
...
If you, for instance, want to make a custom AndroidManifest.xml for your application, then place this directly into the folder specified in this variable.
...
Note: When adding custom versions of the build files (like strings.xml, libs.xml, AndroidManifest.xml, etc.) to your project, make sure you copy them from the package template, which is located in $QT/src/android/java. You should never copy any files from the build directory, as these files have been altered to match the current build settings.

Selecting Android API level in Qt QMake


IE6 AJAX Response Data Issue

Question: I've been looking all over and i can't find anything to fix this problem.
IE6 only is having an issue with the response of an AJAX call and is erroring because of invalid data (alerting the data shows a single beauitful weird square)
Locally IE6 works perfectly (same page and same data), i've checked and rechecked its calling the correct URL's on the server vs here and its not cross domain or anything like that. It's also actually making the call fine and getting a response (OK status)
Calling the AJAX url on the live server in IE6 via address bar works perfectly and shows all the data fine too.
I've tried forcing the content-type and charset, i've tried turning off compression in the web.config and its still dead... and i'm running out of time :(
FF3.5, IE7, IE8 all perfectly fine locally and on the server. Server is Windows 2008 (Rackspace Cloud) and local is just the built-in dev server from Web Dev Express 2008
Its a MVC C# App.. any ideas would be appreciated!
EDIT:
Not alot i can paste but ok, controller:
<code>    public ActionResult TEST()
    {
        return Content("HI THERE!", "text/plain");
    }
</code>
it was text/html of course to start with.
The javascript is a simple ajaxURL function which loads XMLHttpRequest or MSXML2.XMLHTTP or Microsoft.XMLHTTP. on ready state change, if the readyState == 4 then alert the result and its a square (unless you load the url in the browser directly)
Again the entire site loads fine in all other browsers so i think its more a server/config issue esp as even IE6 works locally. I've made the ajax URL's fully referenced just in case (using code to get host, checking non default port and adding it for localhost etc etc)
Viewing source all the calls to ajaxURL are perfect... i'll try another encoding option other than UTF-8 perhaps and check more compression options.
Surely i'm not the only one to ever come across this? heh
Comment: Your client side AJAX code would be useful
Comment: +1 although I found your question/answer after I tracked the problem down myself. I'm also surprised more people don't come across this given IIS7 compresses dynamic content by default.
Answer: Found the issue, putting here in case others need the info :)
Content-Encoding: gzip
This is killing my IE6 ajax calls, i just need to get it turned off on the host. It also explains why it works locally without returning garbage as gzip isn't set locally.
Now i have to find out why the web.config HttpCompression settings arn't affecting it being compressed
EDIT:
<code><urlCompression doDynamicCompression="false" doStaticCompression="false"></urlCompression>
</code>
This did it, IE6 ajax working server side nicely again, 2:30am now i can go to bed! :D
Answer: Anyone having a similar issue with IE6 and responseText where responseText is a weird square looking character... it's the same problem! Just found this out after hours of searching.
Solution is to send your response with no Content-Encoding. In PHP for example, use the following header:
header('Content-Encoding: none');
Thanks to White Dragon for finally solving this for me.
Answer: I've been experiencing the same sort of problems and discovered that the problems only existed when using IE6 in IETester. When testing on a separate workstation IE6-XP-SP2 the AJAX responses were fine.
Comment: i know this is old now but as a note; i use IEtester and did for the above, locally no problem and remotely the issue came up. However normal clients who use a normal IE6 install were also having the issue. So it seems more like there is *some* IE6 builds with the issue and some without. Which would explain why there isn't a whole lot of info on this problem :)
Answer: I have the same problem, too.
But I try White Dragon's, it doesn't work!
And I found that the data that ajax many times is the same,
so I think is about the request cache.
I set it to no-cache, then I solve the problem.

IE6 AJAX Response Data Issue


Select rows if multiple column values are same (or null)

Question: I have a dataframe
df1:

val0
dir0
val1
dir1
val2
dir2
val3
dir3

a0
up
a1

a2
up
a3
up

b0
up
b1
down
b2
up
b3
up

c0

c1
down
c2
down
c3
down

d0
up
d1

d2

d3
up

e0
up
e1
down
e2
down
e3
up

f0

f1
up
f2

f3

I want to select rows that have only one direction (or null). So [dir0, dir1, dir2, dir3] must either contain only 'up' or only 'down' not both (empty is allowed).
df_out:

val0
dir0
val1
dir1
val2
dir2
val3
dir3

a0
up
a1

a2
up
a3
up

c0

c1
down
c2
down
c3
down

d0
up
d1

d2

d3
up

f0

f1
up
f2

f3

Is there a good (and scalable) way of doing this or do I have to do the hard-coded comparison like:
df_out = df1[( ( (df1['dir0'] == 'up')   | (df1['dir0'].isnull()) ) & ......) |
             ( ( (df1['dir0'] == 'down') | (df1['dir0'].isnull()) ) & ......)]

Answer: You could convert to set and ensure length is ≤ 1:
df[df.filter(like='dir').apply(lambda x: len(set(i for i in x if isinstance(i, str))), axis=1).le(1)]

This is a quite fast approach compared to nunique. Interestingly, one rare case where apply seems faster.
Timing on 60k rows (df = pd.concat([df]*10000, ignore_index=True))

# multiple masks approach
28.4 ms ± 342 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# set approach
274 ms ± 2.37 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# nunique approach
2.86 s ± 25.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

output:
  val0 dir0 val1  dir1 val2  dir2 val3  dir3
0   a0   up   a1   NaN   a2    up   a3    up
2   c0  NaN   c1  down   c2  down   c3  down
3   d0   up   d1   NaN   d2   NaN   d3    up
5   f0  NaN   f1    up   f2   NaN   f3  None

Comment: Let me re-check, I might have done a mistake
Comment: @jezrael yes I had the wrong order, but anyway, the real surprise is between set and nunique, I don't understand it
Comment: Yes, no idea why so slow.
Comment: and remove ` Interestingly, one rare case where apply seems faster.` ;)
Answer: First filter only dir columns by DataFrame.filter, then test for up, missing values or down with test if all values per rows are Trues by DataFrame.all:
df1 = df.filter(like='dir')
m1 = df1.eq('up')
m2 = df1.isna()
m3 = df1.eq('down')

df = df[(m1 | m2).all(axis=1) | (m3 | m2).all(axis=1)]
print (df)
  val0 dir0 val1  dir1 val2  dir2 val3  dir3
0   a0   up   a1   NaN   a2    up   a3    up
2   c0  NaN   c1  down   c2  down   c3  down
3   d0   up   d1   NaN   d2   NaN   d3    up
5   f0  NaN   f1    up   f2   NaN   f3  None

Performance for 60k rows:
df = pd.concat([df]*10000, ignore_index=True)

In [176]: %%timeit
     ...: df1 = df.filter(like='dir')
     ...: m1 = df1.fillna('up').eq('up').all(axis=1)
     ...: m2 = df1.fillna('down').eq('down').all(axis=1)
     ...:
     ...: df[m1 | m2]
     ...:
59.9 ms ± 531 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [177]: %%timeit
     ...: df1 = df.filter(like='dir')
     ...: m1 = df1.eq('up')
     ...: m2 = df1.isna()
     ...: m3 = df1.eq('down')
     ...:
     ...: df[(m1 | m2).all(axis=1) | (m3 | m2).all(axis=1)]
     ...:
     ...:
44.4 ms ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [178]: %%timeit
     ...: df[df.filter(like='dir').apply(lambda x: len(set(i for i in x if isinstance(i, str))), axis=1).le(1)]
     ...:
529 ms ± 25.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Comment: I had not seen, next time let me know, I'll UV ;)
Comment: why did you delete and repost your answer?


How can i add a property(uuid) to existing custom entity base_table?

Question: I want to add uuid property to existing custom entity extending ContentEntityBase.
I've tried to a add the uuid entity key and installed field storage definition by:
function my_module_post_update_adduuid() {
  \Drupal::entityTypeManager()->clearCachedDefinitions();
  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();

  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
  $field_storage_definition = BaseFieldDefinition::create('uuid')
    ->setLabel(new TranslatableMarkup('UUID'))
    ->setReadOnly(TRUE);

  $definition_update_manager->installFieldStorageDefinition('uuid', 'custom_entity_id', 'custom_entity_id', $field_storage_definition);
}

The "problem" is that for custom entity with data_table defined the property is added to the data_table and not to the base_table as expected. If the custom entity doesn't have data table defined the uuid property is written properly in base_table.
Everything seems to work even though the uuid property is defined in data_table but the schema is inconsistent compared to clean install with the uuid key present from the beginning.
Answer: Found a workaround for this:
Step 1: Add uuid to entity keys in annotation.
Step 2: Add custom storage handler in annotation.
Step 3: Create the custom storage handler class extending SqlContentEntityStorage with getCustomTableMapping overridden:
/**
 * Use AddUuidTablemaaping to support adding uuid to base table.
 */
public function getCustomTableMapping(ContentEntityTypeInterface $entity_type, array $storage_definitions, $prefix = '') {
  $prefix = $prefix ?: ($this->temporary ? 'tmp_' : '');
  return AddUuidTableMapping::create($entity_type, $storage_definitions, $prefix);
}

Step 4: Create AddUuidTableMapping extending DefaultTableMapping and override create method.
public static function create(ContentEntityTypeInterface $entity_type, array $storage_definitions, $prefix = '') {
  $table_mapping = new static($entity_type, $storage_definitions, $prefix);

  $revisionable = $entity_type->isRevisionable();
  $translatable = $entity_type->isTranslatable();

  $id_key = $entity_type->getKey('id');
  $revision_key = $entity_type->getKey('revision');
  $bundle_key = $entity_type->getKey('bundle');
  $uuid_key = $entity_type->getKey('uuid');
  $langcode_key = $entity_type->getKey('langcode');

+ // The Magic, without this uuid will be added to dataTable if such exists.
+ if (array_key_exists('uuid', $storage_definitions)) {
+   $uuid_key = 'uuid';
+ }
+ // end Magic.

  $shared_table_definitions = array_filter($storage_definitions, function (FieldStorageDefinitionInterface $definition) use ($table_mapping) {
    return $table_mapping->allowsSharedTableStorage($definition);
  });

  $key_fields = array_values(
    array_filter(
      [$id_key, $revision_key, $bundle_key, $uuid_key, $langcode_key]
    )
  );

  $all_fields = array_keys($shared_table_definitions);
  $revisionable_fields = array_keys(array_filter($shared_table_definitions, function (FieldStorageDefinitionInterface $definition) {
    return $definition->isRevisionable();
  }));
  // Make sure the key fields come first in the list of fields.
  $all_fields = array_merge($key_fields, array_diff($all_fields, $key_fields));

  ...
}

Step 5: Create the field storage definition in post update hook:
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();

/** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
$field_storage_definition = BaseFieldDefinition::create('uuid')
  ->setLabel(new TranslatableMarkup('UUID'))
  ->setReadOnly(TRUE);

$definition_update_manager->installFieldStorageDefinition('uuid', $entity_type_id, 'my_custom_module', $field_storage_definition);

Step 6: Set uuid values for existing entities in baseTable:
$rows = $db_connection->select($entity_type_id, 'e')
  ->fields('e', ['id'])
  ->isNull('uuid')
  ->execute()
  ->fetchAll();

foreach ($rows as $row) {
  $db_connection->update($entity_type_id)
    ->fields(['uuid' => \Drupal::service('uuid')->generate()])
    ->condition('id', $row->id)
    ->execute();
}

Step 7: Update entity type and field storage schema:
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();

$e = $definition_update_manager->getEntityType($entity_type_id);
$keys = $e->getKeys();
$keys['uuid'] = 'uuid';
$e->set('entity_keys', $keys);

$definition_update_manager->updateEntityType($e);
$field_storage_definition = $definition_update_manager->getFieldStorageDefinition('uuid', $entity_type_id);
$definition_update_manager->updateFieldStorageDefinition($field_storage_definition);

This last step will update the entity type definition in db + make uuid field not_null in in baseTable.
Done.
Alternate solution is to use $definition_update_manager->updateFieldableEntityType, but will require overriding storage_schema handler(assuming there are existing entities) for the entity type as it forces not_null for entity keys by default.


Onclick toggle as well as on hover change class without using css hover

Question: I have 3 boxes. Inside each big box(red) there is a small box(black by default but grey on hover).

On hover red box the small box color should change (It's changing now so ok).
When you click red box the black box should change to grey(which is working) and at the same time when you mouse over other boxes then it should do same as point 1(which is working too). But the problem begins here. When you click the red box the black box changes to grey and when you click again that red box the grey box is not changing to black. So the black box should toggle(black to grey and then grey to black) in every click to red box.
I can't use any css :hover effect.

Jquery
<code>$('.libg').click(function () {
    $('this').find('.imagebg').removeClass("clicked").toggleClass('active');
    $(this).find('.imagebg').toggleClass("clicked");
}).hover(

function () {
    if (!$(this).find('.imagebg').hasClass("clicked")) $(this).find('.imagebg').addClass('active');
},

function () {
    if (!$(this).find('.imagebg').hasClass("clicked")) $(this).find('.imagebg').removeClass('active');
});
</code>
Is there anything to do with (data clicked true).
Here is the jfiddle -- http://jsfiddle.net/squidraj/PTZE9/5/
Comment: i found grey boxes toggling back to black in your fiddle!
Comment: It seems to be working the in the fiddle the way you described. However it should $(this) and not $('this').
Comment: What i see wrong is :hover doesn't work after the clicks
Comment: @optionaloptional yes it is but only if you mouseout from the box. Once you click the red box the black box goes green not try to toggle it by clicking again but without moving your mouse out from the red box.
Answer: Remove  extra ' ' from <code>$('this')</code>
Use
<code>$(this).find('.imagebg').removeClass("clicked").toggleClass('active');
</code>
instead
<code>$('this').find('.imagebg').removeClass("clicked").toggleClass('active');
</code>
Demo
Comment: Good spot on. I have removed the ''. But now when you click first time the black box is not changing to grey but if you click 2nd time then it is changing.http://jsfiddle.net/squidraj/PTZE9/10/
Comment: @PrithvirajMitra It works clearly! it toggles between grey and red on every click.
Comment: Dhaval yes it works clearly. But what I want is when you click first time in the red box the black box should change to grey box. It's happening but in next click.
Comment: This is what I was trying to do. Solved now. http://jsfiddle.net/squidraj/PTZE9/17/ Thanks
Comment: @PrithvirajMitra ohh i see! But i don't see any toggle effect
Comment: Sorry mate...here goes the updated version ... http://jsfiddle.net/squidraj/PTZE9/18/
Comment: You can edit my answer and fiddle also so that it can help others :)
Comment: Dhaval that's alright. I won't mind if you please do it for me as you are the one who spotted 'this'. Thanks


Question on Douglas, Banach Algebra, Hardy spaces

Question: In the text by Douglas, Banach Algebra techniques in Operator Theory,  pg. 25, 1.47 Hardy spaces was introduced.
If $\mathbb {T}$ denotes the unit circle in the complex plane, let $\chi_n $ denote the function defined on $\mathbb {T}$ by $\chi_n (z) = z^n$. The set $$H^{\infty}=\{\psi \in L^{\infty}(\mathbb {T}): \frac {1}{2\pi} \int_0^{2\pi} \psi \chi_n dt=0\text { for n=1,2,3,..., } \} $$
is a closed subspace of $L^{\infty}(\mathbb {T})$. Moreover in this case, $H^{\infty}=\{\psi \in L^{\infty}(\mathbb {T}): \frac {1}{2\pi} \int_0^{2\pi} \psi \chi_n dt=0\text { for n=1,2,3,..., } \} $ is the null space of the $w^*$-continuous function
$$\hat\chi_n (\psi)=\frac {1}{2\pi} \int_0^{2\pi} \psi \chi_n dt $$
and hence is $w^*$-closed.
My questions are:

I am very new to $w^*$-continuity, how can one show that the function $\hat\chi_n$ is $w^*$-continuous.
What is the relevance of the last statement. Can one directly use the last argument to conclude that the set $H^\infty$ is  a closed subspace of $L^\infty$?. That is does $w^*$-closeness imply closeness.
Comment: If you don't define $\chi_n$, your space is undefined. Furthermore, $\hat\chi_n$ is not a function. It's a value. What you mean is the functional $\hat\chi_n(\psi) = \int_0^{2\pi}\psi\chi_n\,dt$. And $H^\infty$ is _not_ the null space of that single functional. It's the intersection of all these null spaces.
Comment: For the closedness of $H^\infty$ in $L^\infty$ you don't need weak star. Define $F_n : L^\infty\to\mathbb C$ by $F_n(\psi) := \tfrac 1{2\pi}\int_0^{2\pi}\psi(t)e^{int}\,dt$ (I guess that $\chi_n(t) = e^{int}$). Then $|F_n(\psi)|\le\|\psi\|_\infty$, so each $F_n$ is a continous linear functional on $L^\infty$. Hence, $H^\infty = \bigcap_{n=1}^\infty\ker F_n$ is closed in $L^\infty$. But this does not imply the weak star-closedness.
Comment: @amsmath I've just edited
Comment: You integrate over $[0,2\pi]$. So I doubt that $\chi_n(z) = z^n$. Why do I have to tell you how to ask your question?
Answer: Let $X$ be a Banach space and denote by $X'$ its (topological) dual. For $x\in X$ define the linear functional $F_x : X'\to\mathbb K$ by $F_x(x') := x'(x)$. The weak star topology on $X'$ is the smallest topology on $X'$ such each $F_x$ is continuous.
Here, you have $X = L^1(\mathbb T)$ and hence $X' = L^\infty(\mathbb T)$ in the sense that the map $L^\infty\to X'$, defined by $y\mapsto\left(x\in L^1\mapsto\int_{\mathbb T}xy\,dt\right)$ is an isometric isomorphism. Hence, for $x\in L^1$ you have $F_x(y) = \int xy\,dt$, $y\in L^\infty$. If you put $x_n = e^{int}$, your functional $\hat\chi_n$ exactly equals $F_{x_n}$ and is thus weak star-continuous.
Comment: Thanks a lot... I'll revise and let you know if I have any probs.
Comment: Your conclusion was swift. Pls, I don't  understand how you concluded that $F_{x_n}$ is weak star continuous
Comment: @stackuser Really not? Read it again. It's trivial.


Ruby gems helper method (permitted_to?) in rails console

Question: I am using declarative_authorization. I want to use permitted_to? method in rails console. How can I use it?
Answer: You can use the helper object from your rails console:
helper.permitted_to?

This will give you access to all view helpers in your application (both, rails built in view helpers as well as helpers from any gem you might be using)
Comment: it is latest rails `3.2.21`
Comment: It works in context of `current_user`, better you can use `user.permitted_to?`  instance on console. That is alternate option,


Help to Prove that $\int_{0}^{\pi\over 4}\arctan{(\cot^2{x})}\mathrm dx={2\pi^2-\ln^2({3+2\sqrt{2})}\over 16}$

Question: I need help on proving $(1)$.
$$I=\int_{0}^{\pi\over 4}\arctan{(\cot^2{x})}\mathrm dx={2\pi^2-\ln^2({3+2\sqrt{2})}\over 16}\tag1$$
This is what I have attempted;
Enforcing a sub: $u=\cot^2{x}$ then $du=-2\cot{x}\csc^2{x}dx$
Recall $1+\cot^2{x}=\csc^2{x}$
$$I={1\over2}\int_{1}^{\infty}\arctan{u}\cdot{\mathrm dx\over u^{1/2}+u^{3/2}}$$
Recall $u^3+1=(u+1)(u^2-u+1)$
$$I={1\over2}\int_{1}^{\infty}\arctan{u}\left({A\over u^{1/2}}+{B\over u+1}+{Cu+D\over u^2-u+1}\right)\mathrm du$$
I am stuck at this point.
Can anyone help to prove $(1)$?
Comment: Providing such information may improve your chance of getting an answer. For instance, your link clearly shows the relationship between your integral and the Legendre chi function, which indeed turns out to be a crucial hint toward the computation.
Comment: 1) Where do you get these integrals from? 2) If you let $u=\cot x$ you almost end up with the integral you posted yesterday (I have not seen if that leads all the way).
Comment: @mickep do I get a cup of tea if I tell you where I got the idea of this integral from? http://math.stackexchange.com/questions/1287169/a-curious-equation-containing-an-integral-int-0-pi-4-arctan-left-tanx-the
Answer: We first write $I$ as
$$ I= \frac{\pi^2}{16} + \int_{0}^{\frac{\pi}{4}} \left( \arctan(\cot^2 x) - \arctan(1) \right) \, dx. $$
Now using addition formulas for $\arctan$ and $\cos$, we have
$$ \arctan(\cot^2 x) - \arctan(1)
= \arctan\left(\frac{\cot^2 x - 1}{\cot^2 x + 1} \right)
= \arctan(\cos 2x). $$
Consequently we have
\begin{align*}
I
&= \frac{\pi^2}{16} + \int_{0}^{\frac{\pi}{4}} \arctan(\cos 2x) \, dx \\
&= \frac{\pi^2}{16} + \frac{1}{2}\int_{0}^{\frac{\pi}{2}} \arctan(\sin \theta) \, d\theta,
\end{align*}
where the last line follows from the substitution $\theta = \frac{\pi}{2} - 2x$. The last integral can be computed in terms of the Legendre chi function $\chi_2$:
$$ \int_{0}^{\frac{\pi}{2}} \arctan(\sin \theta) \, d\theta = 2\chi_2(\sqrt{2}-1). \tag{1} $$
For a proof of $\text{(1)}$, see my previous answer for instance. There are only a handful of known special values of $\chi_2$, but thankfully
$$\chi_2(\sqrt{2}-1) = \frac{\pi^2}{16} - \frac{1}{4}\log^2(\sqrt{2}+1) \tag{2} $$
is one of them. Summarizing, we have
$$ I = \frac{\pi^2}{8} - \frac{1}{4}\log^2(\sqrt{2}+1), $$
which coincides with the proposed answer.

Addendum. The identity $\text{(2)}$ follows by plugging $x = \sqrt{2}-1$ to the identity
$$ \chi_2\left(\frac{1-x}{1+x}\right) + \chi_2(x) = \frac{\pi^2}{8} - \frac{1}{2}\log x \log\left(\frac{1-x}{1+x}\right), $$
which can be easily checked by differentiating both sides.
Comment: Solid, as always. Sometimes I think you are a machine! :)
Comment: @mickep, Thank you! I was lucky enough that I quickly recognized the similarity between the proposed answer and the special value $\text{(2)}$. As I already knew the relation $\text{(1)}$, the rest was to manipulate the integral so that it fits into $\text{(1)}$.
Comment: (+1) Man you didn't give me time to think about an approach.
Comment: @SangchulLee, I did get the expression for $I$ before the relation $(1)$ as in your answer and was thinking how to proceed, but by that time you already posted the answer with an addendum. (+1) for the superb speed!
Comment: what a nice approach! (+1)super  440!
Comment: @SangchulLee First of all, great answer(+1)!
I think your identity (1) should be proveable without refering to special functions by employing Feynman's trick, right?
Comment: For evaluation of $\int_{0}^{\frac{\pi}{2}} \arctan(\sin \theta) \, d\theta$ see http://math.stackexchange.com/questions/855517/evaluating-a-sum-involving-binomial-coefficient-in-denominator/1052675#1052675
Comment: @tired, Feynman's trick depends on how you introduce a parameter, but a natural choice seems not helpful since it leads to $$ \int_{0}^{\frac{\pi}{2}} \arctan(r \sin \theta) \, d\theta = \int_{0}^{\arctan r} \frac{\operatorname{artanh}(\sin\theta)}{\sin\theta} \, d\theta = 2\chi_2\left(\frac{\sqrt{r^2 + 1} - 1}{r}\right). $$
Comment: BTW, $\frac{\pi^2}{8} - \frac{1}{4}\log^2(\sqrt{2}+1)=1.013...$ and $I=1.039...$
Comment: @FDP, I am pretty sure you made a mistake when computing $\frac{\pi^2}{8} - \frac{1}{4}\log^2(\sqrt{2}+1)$ as Mathematica 11 gives the same value at least up to 100 digits. Also notice that your answer is exactly the same as I presented.
Comment: You're right, i have forgotten the square and i have forgotten that$(1+\sqrt{2})^2=3+2\sqrt{2}$
Answer: For the evaluation of $\displaystyle J=\int_0^{\tfrac{\pi}{2}}\arctan(\sin x)dx$
Perform the change of variable $y=\sin x$,
$\displaystyle J=\int_0^1 \dfrac{\arctan x}{\sqrt{1-x^2}}dx$
Perform the change of variable $y=\sqrt{\dfrac{1-x}{1+x}}$,
$\begin{align}\displaystyle J&=2\int_0^1 \dfrac{\arctan\left(\tfrac{1-x^2}{1+x^2}\right)}{1+x^2}dx\\
&=2\int_0^1 \dfrac{\arctan(1)}{1+x^2}dx-2\int_0^1 \dfrac{\arctan(x^2)}{1+x^2}dx\\
&=\dfrac{\pi^2}{8}-2\int_0^1 \dfrac{\arctan(x^2)}{1+x^2}dx\\
\end{align}$
$\begin{align}
\displaystyle\int_0^1 \dfrac{\arctan(x^2)}{1+x^2}dx&=\Big[\arctan x\arctan(x^2)\Big]_0^1-\int_0^1 \dfrac{2x\arctan x}{1+x^4}dx\\
&=\dfrac{\pi^2}{16}-\int_0^1 \dfrac{2x\arctan x}{1+x^4}dx\\
\end{align}$
Since,
$\displaystyle \arctan x=\int_0^1 \dfrac{x}{1+t^2x^2}dx$
then,
$\begin{align}
\displaystyle K&=\int_0^1 \dfrac{2x\arctan x}{1+x^4}dx\\
\displaystyle &=\int_0^1\int_0^1 \dfrac{2x^2}{(1+t^2x^2)(1+x^4)}dtdx\\
\displaystyle &=\int_0^1\int_0^1 \left(\dfrac{2t^2}{(1+t^4)(1+x^4)}+\dfrac{2x^2}{(1+x^4)(1+t^4)}-\dfrac{2t^2}{(1+t^4)(1+t^2x^2}\right)dtdx\\
&=\displaystyle 4\left(\int_0^1 \dfrac{t^2}{1+t^4}dt\right)\left(\int_0^1 \dfrac{1}{1+x^4}dx\right)-K
\end{align}$
Therefore,
$\displaystyle K=2\left(\int_0^1 \dfrac{x^2}{1+x^4}dx\right)\left(\int_0^1 \dfrac{1}{1+x^4}dx\right)$
Since,
$\begin{align}\displaystyle \int_0^1 \dfrac{x^2}{1+x^4}dx&=\left[\dfrac{1}{4\sqrt{2}}\ln\left(\dfrac{x^2-\sqrt{2}x+1}{x^2+\sqrt{2}x+1}\right)+\dfrac{1}{2\sqrt{2}}\arctan\left(\sqrt{2}x+1\right)+\dfrac{1}{2\sqrt{2}}\arctan\left(\sqrt{2}x-1\right)\right]_0^1\\
&=\dfrac{1}{4\sqrt{2}}\Big(\pi+\ln\left(3-2\sqrt{2}\right)\Big)
\end{align}$
and,
$\begin{align}\displaystyle \int_0^1 \dfrac{1}{1+x^4}dx&=\left[\dfrac{1}{4\sqrt{2}}\ln\left(\dfrac{x^2+\sqrt{2}x+1}{x^2-\sqrt{2}x+1}\right)+\dfrac{1}{2\sqrt{2}}\arctan\left(\sqrt{2}x+1\right)+\dfrac{1}{2\sqrt{2}}\arctan\left(\sqrt{2}x-1\right)\right]_0^1\\
&=\dfrac{1}{4\sqrt{2}}\Big(\pi-\ln\left(3-2\sqrt{2}\right)\Big)
\end{align}$
Therefore,
$\boxed{K=\displaystyle \dfrac{\pi^2}{16}-\dfrac{1}{16}\Big(\ln\left(3-2\sqrt{2}\right)\Big)^2}$
Therefore,
$\boxed{\displaystyle\int_0^1 \dfrac{\arctan(x^2)}{1+x^2}dx=\dfrac{1}{16}\Big(\ln\left(3-2\sqrt{2}\right)\Big)^2}$
Therefore,
$\boxed{\displaystyle J=\dfrac{\pi^2}{8}-\dfrac{1}{8}\Big(\ln\left(3-2\sqrt{2}\right)\Big)^2}$
Addendum:
$\displaystyle I=\int_0^{\tfrac{\pi}{4}} \arctan\left(\cot^2(x)\right)dx$
Perform the change of variable,
$y=\tan x$,
$\begin{align}I&=\displaystyle \int_0^1 \dfrac{\arctan\left(\tfrac{1}{x^2}\right)}{1+x^2}dx\\
&=\displaystyle \int_0^1 \dfrac{\tfrac{\pi}{2}-\arctan\left(x^2\right)}{1+x^2}dx\\
&=\displaystyle \dfrac{\pi^2}{8}-\int_0^1  \dfrac{\arctan\left(x^2\right)}{1+x^2}dx
\end{align}$
Comment: Oh man, this is an amazing answer, especially since it doesn't rely on any other nontrivial prerequisite theorems (like special values of the Legendre Chi function). Nicely done, sir! (+1)
Answer: Substitute $y=\tan x$, then integrate by parts.
$$\int_0^{\tfrac\pi4} \arctan\left(\cot^2x\right) \, dx = \int_0^1 \frac{\arctan\frac1{y^2}}{1+y^2} \, dy = \frac{\pi^2}{16} + 2 \int_0^1 \frac{y}{1+y^4} \arctan y \, dy \\
= \boxed{\frac{\pi^2}8  - \frac14 \operatorname{arcoth}^2\sqrt2}$$
The last integral is evaluated in a variety of ways here.


Parse data from .xml file and save it to .tsv file in Python

Question: I have a dataset which looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Reviews>
<Review rid="1004293">
    <sentences>
        <sentence id="1004293:0">
            <text>Judging from previous posts this used to be a good place, but not any longer.</text>
            <Opinions>
                <Opinion target="place" category="RESTAURANT#GENERAL" polarity="negative" from="51" to="56"/>
            </Opinions>
        </sentence>
        <sentence id="1004293:1">
            <text>The food here is rather good, but only if you like to wait for it.</text>
            <Opinions>
                <Opinion target="food" category="FOOD#QUALITY" polarity="positive" from="4" to="8"/>
                <Opinion target="NULL" category="SERVICE#GENERAL" polarity="negative" from="0" to="0"/>
            </Opinions>
        </sentence>
...

How can I parse the data from this .xml file to .tsv file in the following format:
["negative", "Judging from previous posts this used to be a good place, but not any longer.", "RESTAURANT#GENERAL"]
["positive", "The food here is rather good, but only if you like to wait for it.","FOOD#QUALITY"]
["negative", "The food here is rather good, but only if you like to wait for it.","SERVICE#GENERAL"]
Thanks!
Comment: SO isn't a code writing service. We're more than happy to help, but we do expect you to make an effort to solve the problem yourself first. Once you've done that and run into difficulties, you can explain the problem you've encountered, include the relevant portions of your code, and ask a specific question related to that code, and we can try to assist. You'll find your experiences here will be much better if you spend some time taking the [tour] and reading the [help] pages to learn how the site works and what our expectations are before posting.
Answer: You can use elementtree package of python to get your desired output. Below is the code which will print your list. You can create a tsv by replacing the print and writing to a tsv file.
The sample.xml file must be present in the same directory where this code is present.
from xml.etree import ElementTree

file = 'sample.xml'

tree = ElementTree.parse(file)
root = tree.getroot()

for sentence in root.iter('sentence'):
# Loop all sentence in the xml
    for opinion in sentence.iter('Opinion'):
    # Loop all Opinion of a particular sentence.
        print([opinion.attrib['polarity'], sentence.find('text').text, opinion.attrib['category']])

Output:
['negative', 'Judging from previous posts this used to be a good place, but not any longer.', 'RESTAURANT#GENERAL']
['positive', 'The food here is rather good, but only if you like to wait for it.', 'FOOD#QUALITY']
['negative', 'The food here is rather good, but only if you like to wait for it.', 'SERVICE#GENERAL']

sample.xml contains:
<Reviews>
<Review rid="1004293">
    <sentences>
        <sentence id="1004293:0">
            <text>Judging from previous posts this used to be a good place, but not any longer.</text>
            <Opinions>
                <Opinion target="place" category="RESTAURANT#GENERAL" polarity="negative" from="51" to="56"/>
            </Opinions>
        </sentence>
        <sentence id="1004293:1">
            <text>The food here is rather good, but only if you like to wait for it.</text>
            <Opinions>
                <Opinion target="food" category="FOOD#QUALITY" polarity="positive" from="4" to="8"/>
                <Opinion target="NULL" category="SERVICE#GENERAL" polarity="negative" from="0" to="0"/>
            </Opinions>
        </sentence>
    </sentences>
</Review>


Cardinality of power sets decides all of cardinal arithmetic?

Question: Assuming ZFC, is it possible to have two models which agree on the cardinality of all the power sets, but disagree on the cardinality of some other cardinal exponentiation (meaning that they agree on the function $F$ such that $F(\alpha) = \beta$ iff $2^{\aleph_\alpha} = \aleph_\beta$, but in one model ${\aleph_\alpha} ^ {\aleph_\beta} = {\aleph_\gamma}$ whereas in the second model ${\aleph_\alpha} ^ {\aleph_\beta} = {\aleph_\delta}$ with $\gamma \neq \delta$)?
Put another way: If we decide (for example by forcing) the cardinality of every power set ($2^{\aleph_\alpha}$ for all $\alpha$), does it automatically decide the result of every possible cardinal exponentiation (${\aleph_\alpha} ^ {\aleph_\beta}$ for all $\alpha,\beta$)?
For example, when we assume GCH, we have an immediate formula for the cardinality of every cardinal exponentiation (see Jech 5.15), and we have no "freedom" to choose alternative values for them.
Comment: By agree on cardinality of the power set, do you mean agree on the actual cardinality of the actual power sets, or just agree on the values of the function $F(\alpha)=\beta$ such that $2^{\aleph_\alpha}=\aleph_\beta$? (In the latter case, for example, any two models of GCH agree but this is not necessarily the situation in the first, stricter, definition.)
Comment: I meant the latter and corrected the statement of the question above.
Answer: The answer is no assuming the existence of a model of $\mathsf{ZFC+GCH}$ having a supercompact cardinal.
First, using Silver's forcing, there is a generic extension $V[K]$ where $\kappa$ is still measurable but $2^{\kappa}=\kappa^{++}$. Then we can use Prikry's forcing to obtain a generic extension $V[K][H]$ of $V[K]$ such that all bounded subsets of $\kappa$ are in $V[K]$, all cardinals are preserved, $\kappa$ is still a strong limit and $\operatorname{cf}\kappa=\omega$. Let $G=K\ast H$.
As we assumed $V\models\mathsf{GCH}$, it's not hard to prove that in $V[G]$ we have $2^\lambda=\lambda^+$  for all $\lambda>\kappa$; since the poset yielding $V[K]$ has size $\kappa^{++}$ in $V$ and the poset giving the extension $V[K][H]$ has size $\kappa^{++}$ in $V[K]$.
Now let us work in $V[G]$.  We have $$\kappa^{\aleph_0}=\kappa^{\operatorname{cf}\kappa}=2^{\kappa}=\kappa^{++},$$ and $$(\kappa^{+3})^{\omega_1}=(2^{\kappa^{++}})^{\omega_1}=2^{\kappa^{++}}=\kappa^{+3},$$ thus we can force  with $Add(\omega_1,\kappa^{+3})$ to obtain a generic extension $V[G][H']$ where $2^{\omega_1}=\kappa^{+3}$, and $2^{\lambda}=\kappa^{+3}$ for all $\omega_1\leq\lambda\leq \kappa^{++}$. In $V[K]$, $\kappa$ is measurable, thus in there  $\kappa=\aleph_\kappa$, so as cardinals are preserved in $V[G]$ we get that $\kappa=\aleph_\kappa$ is also true in $V[G][H']$.
Let $\beta_0$ be such that $2^{\aleph_0}=\aleph_{\beta_0}$ in $V[G]$. Then $\beta_0<\kappa$; as all bounded subsets of $\kappa$ in $V[G]$ are in $V[K]$. We also have $2^{\aleph_0}=\aleph_{\beta_0}$ in $V[G][H']$.
Thus if we consider the following function
$$F(\alpha)=\begin{cases} \beta_0 & \text{if}&\alpha=0 \\\kappa+3 & \text{if}& 1\leq\alpha\leq\kappa+2\\\alpha+1 &\text{if}&\alpha\geq\kappa+3 \end{cases},$$
it follows that for all ordinals $\alpha$, $$V[G][H']\models 2^{\aleph_\alpha}=\aleph_{F(\alpha)},$$
and as the poset we used in $V[G]$ is $<\omega_1$-closed there, we get that $\kappa^{\aleph_0}=\kappa^{++}$ in this extension too.
Now, let $\mathbb P\in L$ be a poset, cardinal preserving, such that if $K'$ is $L$-generic over $\mathbb P$, we have  for all ordinals $\alpha$, $$L[K']\models 2^{\aleph_\alpha}=\aleph_{F(\alpha)}.$$
In $L$, $\kappa$ is inaccesible, and thus in this model $\aleph_\kappa=\kappa$, so as $\mathbb P$ preserves cardinals we get that $\aleph_\kappa=\kappa$ in $L[K']$ too.
Let us work in $L[K']$. The singular cardinals hypothesis is true; since $0^\sharp$ does not exist, so we get that as $2^{\aleph_0}<\kappa$ and $\kappa$ is regular, $\kappa^{\aleph_0}=\kappa$.
Therefore we have that in both models $V[G][H']$ and $L[K']$, $2^{\aleph_\alpha}=\aleph_{F(\alpha)}$ for all ordinals $\alpha$, but
$$V[G][H']\models \aleph_\kappa^{\aleph_0}=\aleph_{\kappa+2}\text{ and }L[K']\models \aleph_\kappa^{\aleph_0}=\aleph_\kappa.$$

Note: This argument should go through with no problem using just a measurable cardinal $\kappa$ of Mitchell order $\kappa^{++}$, working in Mitchell's model for such $\kappa$, using Gitik and Woodin's forcing. However as I'm not that familiar with this method, I used Silver's instead.
Comment: I'm confused why such a complicated solution is necessary. Let $M_1=L[U],$ let $\mathbb{P}$ be Prikry forcing, and $M_2=L[U][G].$ Then $M_i \models GCH$ but $M_1 \models \aleph_{\kappa}^{\aleph_0}=\aleph_{\kappa}$ while $M_2 \models \aleph_{\kappa}^{\aleph_0}=\aleph_{\kappa+1}.$
Comment: I was planning to write such an answer, but you wrote it in far better details. So I'm glad that I wasn't able to!
Comment: @AsafKaragila, I knew I had to rush :^).
Comment: Probably less in the coming month or so. I've got *so much* work, so I will have far less time to write good answers like this. Therefore I'll try to limit them into areas where I know that I have more to say (e.g. foundational questions or AC related things), rather than questions I have less to say (e.g. large cardinals and inner models).
Comment: @ElliotGlazer why don't you turn your comment into an answer?


Como pegar o valor de um formulário específico da página anterior em PHP?

Question: Boa tarde!
Uma página em PHP contém dois formulários form, cada um com um submit. Como obter os dados do form 1, por exemplo, depois de apertar o submit através do POST? Normalmente quando havia só um formulário ele pegava os dados diretamente através do código abaixo: (sendo que CNPJ era o id de um input do formulário):

table {
  float: left;
}
<form id="localizacao" name="localizacao" method="post" action="rastreamento.php" onsubmit=" return false;">

Pesquisa

      Selecione o STATUS:

        <select name="status" id="status">
          <option value="0">Recebido</option>
          <option value="1">Em trânsito</option>
          <option value="2">Encerrado</option>
        </select>

      CNPJ:
      <input name="CNPJ" type="text" id="CNPJ" size="20" maxlength="14" />
        * somente números

        VIAGEM:

      <input name="VIAGEM" type="text" id="VIAGEM" size="20" maxlength="14" />

          <input name="pesquisar" type="submit" id="pesquisar" value="Pesquisar" />

          <input name="limpar" type="reset" id="limpar" value="Limpar!" />

</form>
<form id="alteracoes" name="alteracoes" method="post" action="rastreamento.php" onsubmit="return validaCampoAltera(); return false;">

Modifica

      VIAGEM:
      <input name="VIAGEM" type="text" id="VIAGEM" size="20" maxlength="14" />

      NOVO STATUS:
      <input name="NVSTATUS" type="text" id="NVSTATUS" size="1" maxlength="1" />

      EMBARCACAO:
      <input name="EMBARC" type="text" id="EMBARC" size="20" maxlength="10" />

      DATA SAIDA:
      <input name="DATSAI" type="text" id="DATSAI" size="20" maxlength="10" />

      HORA SAIDA:
      <input name="HORSAI" type="text" id="HORSAI" size="20" maxlength="10" />

      DATA CHEGADA:
      <input name="DATCH" type="text" id="DATCH" size="20" maxlength="10" />

      HORA CHEGADA:
      <input name="HORCHE" type="text" id="HORCHE" size="20" maxlength="10" />

          <input name="atualizar" type="submit" id="atualizar" value="ATUALIZAR" />

</form>

if (isset($_POST["CNPJ"])){
        $CNPJ = $_POST ["CNPJ"];
    }
Comment: @Marvin você só terá acesso aos dados do formulário submetido, se não submeter o primeiro você não vai ter acesso ao dados dele.
Comment: Por favor incluir mais informações e detalhar melhor
Comment: Se são dois formulários, eles serão submetidos de forma individual: ou submete o primeiro, ou o segundo. Submeter um não envia os dados do outro.
Comment: @AndersonCarlosWoss, como fazer com que ele pegue os dados do `formulario1`, por exemplo? Seria algo como `$CNPJ = $_POST ["formulario1.CNPJ"]`?
Comment: Como é o seu código HTML? Qual formulário está submetendo?
Comment: @AndersonCarlosWoss, pergunta editada com o código em HTML.
Comment: Apenas podias usar um botão para submeter os dois formulário ao mesmo tempo, senão penso que não exista forma.
Answer: Cada formulário da página, independente de quantos sejam, é submetido individualmente. Logo, se você tiver dois formulários e cada um tiver o seu submit, somente o formulário no qual o submit foi acionado terá os dados enviados pro servidor, lembrando que cada form deve ter seu submit. No seu caso, se você clicar no submit do formulário "localizacao", só os inputs dele serão enviado via post, mesmo havendo inputs no outro formulário com o mesmo nome. Isso também deve ser tratado no seu back-end, já que ambos os formulários enviam para o mesmo arquivo, seu código deve saber comparar, filtrar e tratar a captação dos dados de acordo acordo ao formulário de origem dos mesmos.
Answer: A solução foi tirar o espaço que havia em onsubmit e colocar true.
onsubmit=" return false;"

para
onsubmit="return true;"

em

<form id="localizacao" name="localizacao" method="post" action="rastreamento.php" onsubmit="return true;">


How to study the maxima and minima of solutions of a differential equation without an explicit solution?

Question: I've been trying to study the differential equation given by $y'=x-y^2$ for a while, and I didn't was even close to a solution. Finally when I gave up I solved this equation with Wolfram Alpha, and it seems that the solution was quite intricate and doesn't seem possible to solve only with elementary functions, see Wolfram's solution.
Now my question is, what are the possible methods to use when I encounter a non-linear equation of like this?, is it possible to say something about it without the need of a computer?.
One thing I saw is that this is similar the Riccati equation $y'=a(x)y^2+b(x)y+c(x)$ using $c(x)=x, a(x)=-1,  b(x)=0$
 and is possible to get a general solution if I know two other solutions: if $f_1,f_2$ are solutions then $f=f_1+C(f_2-f_1)$ is a general solution. The problem here is that I'd need to find particular solutions for the equations, something that I couldn't figure out how to do in the general case.
Answer: The equation has two nullclines $x=\pm\sqrt{t}$, which is where the slope field is horizontal.  Important features of these nullclines:

$x=\sqrt{t}$ begins at $(0,0)$ and increases to $\infty$
$x=\sqrt{t}$ has positive slope everywhere; $x=-\sqrt{t}$ has negative slope everywhere.
Solutions have negative slope above $x=\sqrt{t}$ and below $x=-\sqrt{t}$. They have positive slope between them.

Using the above properties, the following observations can be made.

Putting 1 and 3 together, one can conclude that every solution with positive initial value will decrease until it crosses the upper nullcline at some moment $t=t_0$.
From 2 one can infer that solutions do not cross the upper nullcline in the upward direction, and do not cross the lower nullcline in the downward direction. Therefore, once they get into the region between the nullclines, they stay there.
From 3, solutions increase as long as they are between the nullclines.
Also from 3: if a solution starts below the lower nullcline (negative initial value) it will just continue to decrease.

Conclusions

A solution with positive initial value has one minimum (where it crosses the upper nullcline) and no maxima.
A solution with zero initial value is always increasing.
A solution with negative initial value is either always decreasing (if it never crosses the lower nullcline), or has one minimum (if it crosses the lower nullcline).

Also see my answer to Properties of the solutions to $x'=t-x^2$.


Como limpar a Output Window do Visual Studio?

Question: Estou escrevendo uma aplicação que faz uso do classe debug para escrever na tela Output do VS.
Só que eu gostaria de limpar o conteúdo desta tela através do meu código, pois depois de um tempo ele fica muito poluído. Isso é possível e recomendável (pois acho estranho não ter um método clear para essa classe)?
Comment: Você consegue by Marshal e restrito à versão do VS que você está usando, mas essa prática não faz muito sentido, se o objetivo é log, existem diversas outras alternativas mais enxutas. Ainda mais que ao fazer o deploy da sua aplicação ela deve ser compilada em modo Release, não debug.
Answer: Fonte: https://stackoverflow.com/questions/25627384/how-to-programatically-clean-output-in-visual-studio-2013
<code>// Import EnvDTE and EnvDTE80 into your project
using EnvDTE;
using EnvDTE80;

protected void ClearOutput()
{
    DTE2 ide = (DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0");
    ide.ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug").Clear();
    System.Runtime.InteropServices.Marshal.ReleaseComObject(ide);
}
</code>


WRN: Assembly binding logging is turned OFF

Question: I encountered this error,

WRN: Assembly binding logging is turned OFF.
  To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
  To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

And once I got into the fusion folder, I couldn't find the EnableLog file, can you please help me?
Comment: Try: http://stackoverflow.com/questions/255669/how-to-enable-assembly-bind-failure-logging-fusion-in-net
Answer: You only need to turn assembly bind logging on if you wish to diagnose a problem with loading assemblies. If you need to do this, the best way to turn logging on temporarily is using the Fusion Log Viewer, fuslogvw.exe. Instructions on how to use it can be found here.
Comment: well now the log entry showed detailed information about a failed assembly bind, do you have any suggestions how to deal with it?
Comment: The log of the failed bind will determine what you need to do. Does the assembly exist in the right path? Do you need to install it to the GAC? Is it a missing 3rd party product? Is there a version mismatch? The log will explain
Answer: Updating 'Microsoft.Extensions.Logging.Debug 1.1.0' to 'Microsoft.Extensions.Logging.Debug 1.1.2' solved this problem for me


Bootstrap modal

Question: Estou montando um aplicativo mobile usando asp.net (aspx) e bootstrap modal.
O objetivo desta modal é preencher uma label com a informação contida no atributo "data-marcacao" do href que aciona esta modal. Quando a modal é acionada na 1a tentativa a label não está sendo preenchida. A label está sendo preenchida somente na 2a tentativa de abertura da modal após o myButton "Sim" ter sido clicado na 1a tentativa.
//acionamento

//modal

                    <asp:Label ID="lblModalMarcacao" runat="server"></asp:Label>

                    <button class="btn btn-success btn-md" id="myButton">Sim</button>
                    <button class="btn btn-danger btn-md" data-dismiss="modal">Não</button>

//script

Comment: Mas qual problema exatamente você está tendo?
Comment: A label está sendo preenchida somente após a modal ter sido aberta uma primeira vez e o Button "Sim" ter sido clicado, ou seja, a label está sendo preenchida somente quando a modal é acionada na 2a tentativa de abertura. Na primeira tentativa de abertura a label não está sendo preenchida.
Comment: Descobri o problema. Estava usando um componente ScriptManager no body. Tirei o componente ScriptManager e o problema acabou.
Comment: Ótimo! parabéns, se quiser você mesmo pode postar aqui a solução para ajudar caso outra pessoa tenha o mesmo problema.
Answer: Descobri o problema. Estava usando um componente ScriptManager no body. Tirei o componente ScriptManager e o problema acabou.

Bootstrap modal


MLE and non-normality

Question: What is a non-trivial example of an identifiable model whose MLE is consistent, but the MLE's asymptotic distribution is not normal? Parametric setting and IID sample would be desirable.
Comment: Does $X_i$ i.i.d Uniform on $(0,\theta)$ count as non-trivial?
Comment: It certainly does! And thank you for being such a stubborn and intelligent bunch of atoms. ;-)
Answer: Theorems showing asymptotic normality of the MLE generally hinge on the MLE being in in the interior of the parameter space and the information function existing.  Moran (1971) examines the MLE under non-standard conditions, including when the parameter is on the boundary.  That might be a good place to look if you would like a non-trivial example.
Comment: Thanks, Ben! I'll check the reference.
Answer: To develop StubbornAtom's comment,  if $X_i$ is i.i.d. uniformly distributed on $[0,\theta]$
and you have $n$ samples then the maximum likelihood estimator of $\theta$ is $\hat{\theta}_n=\max\limits_{1\le i \le n}X_i$.
$\hat{\theta}_n$ has a $\mathrm{Beta}(n,1)$ distribution scaled by $\theta$.
As $n$ increases, $n\left(\theta-\hat \theta_n\right)$ converges in distribution to $\mathrm{Exp}\left(\frac1\theta\right)$, not a normal distribution.
or in a handwaving sense, for large $n$, the maximum likelihood estimator $\hat{\theta}_n$ approximately has a reversed and shifted exponential distribution with density $\frac{n x^{n-1}}{\theta^n} \approx \frac n{\theta} \exp\left(\frac{nx}{\theta}-n\right)$ when $0 < x \le \theta$ looking like

MLE and non-normality


Convert mongo shell query to QueryDBObject and execute using spring mongotemplate

Question: Below is the query which i am able to execute on my mongo shell properly.
db.students.update({ _id : 139 }, {$pull : { scores: {type :'homework' }}})

I need to execute the same thing using a Java program / Mongo Spring Template.
Could somebody help show me how to do this?
Comment: Could some body know how to do it using spring mongo template
Answer: Your query might be similar to this:
UpdateResult updateResult = collection.updateOne(eq("_id", 123),
      new Document("$pull", new Document("scores",
          new Document("type", "homework"))
      )
);

Here you've got the documentation of the entire interface and of updateOne in specific.
You also need a connection with the database, so you might want to follow this quick tour to get it done.
EDIT
For doing the same with spring mongo, you can do (as it is documented in the docs) something like this:
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query;
import static org.springframework.data.mongodb.core.query.Update;

...

WriteResult wr = mongoTemplate.updateFirst(new Query(where("accounts.accountType").is(Account.Type.SAVINGS)),
  new Update().pull("students.$.scores", new Document("type", "homework")), Account.class);

PS: This answer probably won't work as is, it's just an example, if you want better help give larger snippets of code.
Comment: -  { "_id" : 15,"name" : "Tambra Mercure","scores" : [{"type" : "exam","score" : 69.1565022533158},{"type" : "quiz","score" : 3.311794422000724},{"type" : "homework","score" : 45.03178973642521},{"type" : "homework","score" : 42.19409476640781 }]}    ------- this is the json i need to remove homework inside array of documents.   this Is the query i am using -  mongoOperation.updateFirst(new Query(where("_id").is(15)), new Update().pull("students.$.scores", "homework"), obj.class);    @VdeVatman
Comment: HI, I got this working -                                                        BasicDBObject ob = new BasicDBObject("_id", Double.valueOf(g.getId()));
BasicDBObject ob2 = new BasicDBObject("$pull",new BasicDBObject("scores", new BasicDBObject("type","homework").append("score", dob)));                           collection.update(ob, ob2)
Comment: nice to hear, try to answer yourselve and automark your own answer as the solution.


Java Midi sequencer stops producing sound after a few times. How do I debug/resolve?

Question: I'm writing some code to play music using the Java sound library.
private Sequencer sequencer ;
...
void play(Sequence sequence) {
    sequencer.open() ;
    sequencer.setSequence(sequence) ;
    sequencer.start() ; // plays sequence
    sequencer.close() ;
}

When I invoke the play method 19 times, sound comes out of my speaker. However, the 20th time I invoke it, no sound comes out. This always happens, no matter what. I need to restart the program to get sound again.
Is there some workaround for this issue? Or some way to debug this? Or some place I can get support on the MIDI sound API?
Comment: Related: http://stackoverflow.com/questions/5972603/terminate-java-midi-output
Answer: I don't know why it stops. Maybe it has something to do with there being only 16 channels in midi, but rather than opening the sequencer multiple times, you can reuse the sequencer and change it's sequence. This is what I have and it works for me:
public void play(Sequence sequence) {
    sequencer.setSequence(sequence);
    sequencer.stop();
    sequencer.setTickPosition(0);
    sequencer.start();
}


MonoDroid OnConfigurationChanged Not Firing

Question: I've seen a number of other questions on the subject, but so far none of the answers have fixed my issue.  I basically just don't want my activity to get recreated every time the screen is reoriented.  From what I've found, the below should work:
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="internalOnly" android:versionCode="1">
  <application android:label="Service Portal">
    <activity android:name =".CallManagement" android:configChanges="orientation"></activity>
  </application>
  <uses-sdk android:minSdkVersion="10" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

CallManagement.cs
public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
    {
        base.OnConfigurationChanged(newConfig);
    }

I've tried changing android:configChanges to "orientation|keyboardHidden".  As I'm targeting API level 10, the suggestion I've seen a number of times to also include "screenSize" does not apply.
I put a breakpoint in the OnConfigurationChanged void and it never catches and OnCreate is definitely continuing to run. What am I doing wrong or am I misunderstanding what this functionality is supposed to do?
Answer: Have you tried screen locking in a particular orientation?
<activity android:name="MyActivity" android:screenOrientation="landscape">.

I lock the screen programatically, I haven't found the layout as good as requesting the orientation and then locking the orientation with the provided int.
If you don't want to lock the screen, but want the activity to resize correctly on orientation change, you might re-consider your design.  Saving game state and then allowing android to re-create the activity is considered the best practice for a dynamic screen.
Comment: I definitely do not want to lock the screen orientation.  Users need to be able to interact with the app in whichever orientation is most comfortable.  The biggest issues I'm having with the change is with Dialogs and a dynamic Spinner. In OnCreate the spinner is given an ArrayAdapter whose options change based on other factors. If I select the item in position 1 and reorient, in OnCreate it bebuilds the list of options based on the new situation during OnCreate and now what is in position 1 is not what was there.
Comment: So - could you save the selection based on some unique option id (name or hash) and then select whichever object matches your saved value, in the on-create?  I very much agree with you that there is little control over the app on screen change, but again, its meant to be a 'feature' not a bug.
Comment: Not really. The item selected in landscape may not even be an option in the spinner when turned portrait and the ArrayAdapter rebuilds in onCreate. The options in the spinner are meant to control workflow, so based on where the user currently is, the options change.  I have the user's selection as soon as the item is selected in the spinner.    I guess I could just always force the spinner to select a generic "Select" item on reorientation.  But that doesn't help with the dialog issue?


How to set sublime as an external editor for jshell?

Question: According to the jshell documentation:

An alternative to editing at the command prompt is to use an external editor. This editor can be used to edit and create snippets, and is especially helpful for multiline snippets. You can configure JShell to use the editor of your choice.

So to implement this, i use the following commands:
jshell> /set editor sublime
|  Editor set to: sublime

And then, i tried to edit a snippet as follows:
jshell> /edit printName
|  Edit Error: process IO failure: Cannot run program "subllime": error=2, No such file or directory

But, i got the above error.
So is it the right way to set editor or something else is required?
I also tried to set Microsoft Word as the editor and specified the exact application path from the Application folder of Mac as follows:
jshell> /set editor /Users/karan.verma/Applications/Microsoft Word.app
|  Editor set to: /Users/karan.verma/Applications/Microsoft Word.app

Even, when i set the editor as "atom", i got the same results:
jshell> /set editor atom
|  Editor set to: atom

But still it shows the same error. Any help?
Comment: Plus one for the specific editors. Just try(assuming you have Atom installed) `/set editor atom` or `/set editor vi` these shall work.
Comment: Try `/set editor "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"`
or
`/set editor subl` if `subl` is already in the `PATH`
Comment: @Bless For me at least, these result in the same error as in the question.
Comment: @nullpointer even it did not worked for atom... Editing the question for the same.
Comment: @KayV Editing the question with operating system tag, I am though pretty sure this is not java-9, jshell specific. I've seem similar issues previously with git as well. Its the application recognition within your OS. for e.g if I simply type `atom` on my terminal, Atom opens up but the same doesn't work for Sublime. That seems to me the cause of why jshell is not able to open the Sublime editor for me at least. And you didn't come back with vim editor result, does that work fine?
Comment: @nullpointer @KayV Just tried on my mac. Can confirm that `/set editor subl -w` works for me.
Can you check if `sublime` or `subl` is in the `PATH`?
Also, does running `"/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"` directly on the terminal start Sublime Text?
Answer: Mightn't have worked for the OP. But worked for me. So, posting it here hoping it helps someone.
If you can type subl on a terminal and if Sublime Text opens (means subl is in PATH), try:
/set editor subl -w

If Sublime Text doesn't open on typing subl on terminal, but running "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" does open Sublime Text (means subl is not in PATH), try:
/set editor "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" -w

-w flag is to wait for the files to be closed in Sublime Text before returning.
Comment: The same applies to `Visual Studio Code`. The same `-w` flag is supported.
Answer: It worked for me by supplying the full path to the sublime executable.  E.g on Windows.
jshell> /set editor c:\sublime3\sublime_text.exe
Answer: You can specify jshell editor via JSHELLEDITOR user/system variable
Answer: In Windows set full path:
   jshell> /set editor C:\Program Files\Notepad++\notepad++.exe

Please do not include inverted commas(" ") in path
In MacOs use inverted commas with path.
Answer: Even i faced same problem as i was giving command
jshell > /set editor "/Applications/Sublime Text.app"
but what's missing is the exact path to bin directory in content folder of sublime.
Solution:
jshell >
/set editor "/Applications/SublimeText.app/Contents/SharedSupport/bin/subl"
Try this it will work 100%.
Comment: This will work in MacOs


How to insert a Jtable data into oracle 11g database

Question: These are the exceptions.we have created a jtable,the data is added to the table by add button.And it is sent to databse through a submit button.But exceptions are generated when the submit button is clicked.Can anyone tell me where the code went wrong??
<code>btnSubmit.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {

    try {

        int count = table.getRowCount();
                        String driver = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driver);
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott", "tiger");
        conn.setAutoCommit(false);
        PreparedStatement pst = conn.prepareStatement("Insert into students(ROLL_NO,NAME,MID1,MID2,Marksinwords) values (?,?,?,?,?)");

        for(int row = 0; row<count; row++)
        {
             String roll = (String)table.getValueAt(row, 0);
             String name = (String)table.getValueAt(row, 1);

                             String MARKS1 = (String)tableModel.getValueAt(row, 2);
            String MARKS2 = (String)table.getValueAt(row, 3);

             String marksinwords = (String)table.getValueAt(row, 4);

             pst.setString(1, roll);
              pst.executeUpdate(roll);
                 pst.setString(2, name);
              pst.executeUpdate(name);
             pst.setString(3,MARKS1 );
              pst.executeUpdate(MARKS1);
             pst.setString(4,MARKS2 );
              pst.executeUpdate(MARKS2);

                 pst.setString(5, marksinwords);

               pst.executeUpdate(marksinwords);
                pst.addBatch();
        }
        pst.executeBatch();
        conn.commit();

            } catch (Exception ex) {

                Logger.getLogger(FacultyTableSubmit.class.getName()).log(Level.SEVERE, null, ex);
            }

    }

});
</code>
Comment: Which exception ?
Comment: I have added the screenshot
Comment: Please never post an exception as a screenshot, always present the text. If you are lucky SO will automatically suggest you a post where you can find the solution if it is able to recognize an exception that already can be found in a prior post. Besides that your exception is not shown completely, it was cut off
Comment: Sure.Thanks for the advice
Answer: Your sequence with the PreparedStatement looks a bit strange to me and you do not need to provide a value when updating it and you do two things, you add it to the db and then again to a batch.
Try it like this:
<code>    for(int row = 0; row<count; row++)
    {
        String roll = (String)table.getValueAt(row, 0);
        String name = (String)table.getValueAt(row, 1);
        String MARKS1 = (String)tableModel.getValueAt(row, 2);
        String MARKS2 = (String)table.getValueAt(row, 3);
        String marksinwords = (String)table.getValueAt(row, 4);

        pst.setString(1, roll);;
        pst.setString(2, name);
        pst.setString(3,MARKS1 );
        pst.setString(4,MARKS2 );
        pst.setString(5, marksinwords);
        pst.addBatch();
    }
    pst.executeBatch();
    conn.commit();
</code>
Comment: I've changed the code.Again the same exceptions @Fredy Fisher


Delete SMS with contentResolver is too slow

Question: I would like to delete all SMS on my phone except the 500 last SMS for each conversation.
This is my code but it's very slow (take about 10 seconds to delete one SMS).
How I can speed up this code :
<code>    ContentResolver cr = getContentResolver();
    Uri uriConv = Uri.parse("content://sms/conversations");
    Uri uriSms = Uri.parse("content://sms/");
    Cursor cConv = cr.query(uriConv,
            new String[]{"thread_id"}, null, null, null);

    while(cConv.moveToNext()) {
        Cursor cSms = cr.query(uriSms,
                null,
                "thread_id = " + cConv.getInt(cConv.getColumnIndex("thread_id")),
                null, "date ASC");
        int count = cSms.getCount();
        for(int i = 0; i < count - 500; ++i) {
            if (cSms.moveToNext()) {
                cr.delete(
                        Uri.parse("content://sms/" + cSms.getInt(0)),
                        null, null);
            }
        }
        cSms.close();
    }
    cConv.close();
</code>
Comment: how many conversations do u have ? and how many sms per conversation did u have in all when you did the delete ?
Comment: I have about 34000 sms and about 100 conversations. But one conversation has 26000 sms
Comment: i guess its a pretty decent time consider that your doing a conditional  double cursor operation on the database. It also depends on the mobile that you use.
Comment: I have an Xperia S and I try in another version to close the two cursor before delete but it still very slow
Answer: One of the main things you can do is batch ContentProvider operations instead of doing 33,900 separate deletes:
<code>// Before your loop
ArrayList<ContentProviderOperation> operations =
    new ArrayList<ContentProviderOperation>();

// Instead of cr.delete use
operations.add(new ContentProviderOperation.newDelete(
    Uri.parse("content://sms/" + cSms.getInt(0))));

// After your loop
try {
    cr.applyBatch("sms", operations); // May also try "mms-sms" in place of "sms"
} catch(OperationApplicationException e) {
    // Handle the error
} catch(RemoteException e) {
    // Handle the error
}
</code>
Up you whether you want to do one batch operation per conversation or one batch operation for the entire SMS history.


Property of the dot product?

Question: If I have vectors $v_1, v_2$ and scalar, real $a$
How is :

$$\overrightarrow{v_1} \cdot a\overrightarrow{v_{2}} = a\overrightarrow{v_1} \cdot \overrightarrow{v_{2}}$$

I don't see how this property holds?
Comment: what Kind of vectors do you have?
Comment: is $$\vec v_1=[x,y,z]$$?
Answer: Suppose
$\overrightarrow{v_{1}} = x_{1} \hat{\textbf{i}} + y_{1} \hat{\textbf{j}} + z_{1} \hat{\textbf{k}} $
and $\overrightarrow{v_{2}} = x_{2} \hat{\textbf{i}} + y_{2} \hat{\textbf{j}} + z_{2} \hat{\textbf{k}} $ , then consider the L.H.S
\
$\overrightarrow{v_{1}}.a\overrightarrow{v_{2}} = (x_{1} \hat{\textbf{i}} + y_{1} \hat{\textbf{j}} + z_{1} \hat{\textbf{k}}).(ax_{2} \hat{\textbf{i}} + ay_{2} \hat{\textbf{j}} + az_{2} \hat{\textbf{k}}) = x_{1}ax_{2} + y_{1}ay_{2}+z_{1}az_{2}$ which is the same when we consider the right hand side , because here in the result the multiplication is commutative as it is in real system.

Property of the dot product?


Error trying to register email credentials with Yagmail and Keyring

Question: I'm using Python3 on a remote machine running Ubuntu 20.10 to send some emails with yagmail. I'm able to send the emails just fine with an application-specific password, as long as the password is spelled out directly in my code.  But when I try to register my email address and password with keyring, I just get an error.
I run the following:
import yagmail
yagmail.register('MY_EMAIL', 'MY_PASSWORD')

And I get:
Traceback (most recent call last):
  File "yag.py", line 3, in <module>
    yagmail.register('MY_EMAIL', 'MY_PASSWORD')
  File "/usr/local/lib/python3.10/dist-packages/yagmail/password.py", line 37, in register
    keyring.set_password("yagmail", username, password)
  File "/usr/lib/python3/dist-packages/keyring/core.py", line 60, in set_password
    get_keyring().set_password(service_name, username, password)
  File "/usr/lib/python3/dist-packages/keyring/backends/chainer.py", line 58, in set_password
    return keyring.set_password(service, username, password)
  File "/usr/lib/python3/dist-packages/keyring/backends/SecretService.py", line 88, in set_password
    collection = self.get_preferred_collection()
  File "/usr/lib/python3/dist-packages/keyring/backends/SecretService.py", line 64, in get_preferred_collection
    raise InitError("Failed to create the collection: %s." % e)
keyring.errors.InitError: Failed to create the collection: Prompt dismissed..

What am I doing wrong?
Answer: I had the same problem and this new env variable resolved it in my case:
export PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring


Views : Make a block related to a page (with flag/addthis/privatemsg as fields in this block)

Question: It's difficult to explain but i'll try to do my best.
I have a basic views (Page) with all my fields displaying.
My purpose is to take some of this fields to display them in a block(on the left sidebar)
This fields i want to display in a block are:

Flag: bookmarks
AddThis: Toolbox
Private msg (send message to the author)

I follow all the screemcast "Taming the beast" (from nodeone.se) especially part 24 when Johan Falk explain how to make a block with a related content to a page (without using page manager)
When i go to my article my url is like that: /fiches-produits-services/100  (100=>[nid])
I follow this step when i create my block:

Add my fields etc.
Add contextual filter : content: nid
click on it, go to WHEN THE FILTER VALUE IS NOT AVAILABLE
Click on Provide default value
Select Content ID from url

But after that nothing, the block isn't here.
When i click on Display all results for the specified field on the same section, the block appears but with all the flags, the privatemsg and socials icons from all my article.
It's not the bahavior i want, i would like to have just the flag related to the article, just the link from private messages related to the article etc.
I don't know if i missed something. In the screemcast he did that with content(article) related with another content (basic page), maybe we can't do that with flag, addThis or privatemsg because it's not really a content (But i don't really know i'm new).
So if someone can help me to understand that, i'll be very grateful.
Answer: I found a way this week to get the good behavior.
i understood my mistake! My url was like that www.example.com/my-product/2 (made with pathauto)
When i selected content ID from URL my block was empty because he couldn't retrieve the good argument from the url (because my node id was in second position)
But when i go to www.example.com/node/2 it works fine
To resolve my problem i select raw value from URL  instead of content ID from URL (because with that option we can select which argument we want to retrieve --that was the second for me because of my custom url)
In summary i follow this step :

Add contextual filter : content: nid
click on it, go to WHEN THE FILTER VALUE IS NOT AVAILABLE
Click on Provide default value
Select raw value from URL
Select the argument you want to retrieve from the url (path component)
I check Specify validation criteria
Validator : content
Filter value format : node id
Action to take if filter value does not validate : no result

It was a stupid mistake :) but i learn some stuff :)


Opposite Clifford-Algebra

Question: for a symmetric bilinearform $\beta$ on a $\mathbb{K}$-vectorspace $V$ the associated Clifford Algebra $Cl(\beta)$ is the associative algebra with unit subject to the relations $$v\cdot v=\beta(v,v)\cdot 1\qquad\forall v\in V.$$It is then often said that $Cl(-\beta)$ is isomorphic to the opposite Algebra $Cl(\beta)^\text{op}$. Why is that?
Cheers, Robert
Comment: I agree on that. In a book i use quite a lot (Budinich, Trautman: "The spinorial chessboard"), which i believe doesn't do stupid mistakes it says the following: The injection $\iota:V\hookrightarrow Cl(\beta)^\text{op}$ is a Clifford map of $(V,−\beta)$ and then extends to the desired Isomorphism $Cl(-\beta)\cong Cl(\beta)^\text{op}$. However, $\iota(v)^2=\beta(v,v)$ so $\iota$ is a Clifford map of $(V,\beta)$, not $(V,-\beta)$... i don't get it.
Comment: I know what the opposite of an algebra is. I want to know why $Cl(-\beta)\cong Cl(\beta)^\text{op}$.
Comment: I don't have an answer, so I'll just make the observation that in the case of an $\mathbb{R}$-vector space where $\beta$ is positive definite, the isomorphism can't take vectors to vectors, because the square of a vector is negative in $Cl(-\beta)$ but positive in $Cl(\beta)^{op}$.
Comment: Now i'm really starting to believe the claim to be wrong. For instance, if $V=\mathbb{R}$ and $\beta(x,y)=-xy$ we see that $Cl(\beta)^\text{op}=\mathbb{C}^\text{op}=\mathbb{C}$ is not isomorphic to $Cl(-\beta)$, which is isomorphic to $\mathbb{R}^2$ with the product $$(a,b)\cdot(c,d)=(ac+bd,ad+bc).$$
Comment: The opposite algebra of an algebra is build by the same elements and the same addition, and the multiplication is the same, but in swapped order.
Answer: First, care is needed! We need the right notion of "op", for behold
$Cl(1) \simeq \mathbb{R}^2 \not\simeq \mathbb{C} \simeq  Cl(-1)$, which as algebras are both commutative!
Over $\mathbb{R}$, the Clifford algebras arise naturally in the braided symmetric monoidal category of $\mathbb{Z}/2$-graded vector spaces, or "super-vector spaces" (alternatively...), as (super-)tensor products of the basic algebras $\mathbb{R}[\varepsilon]$ and $\mathbb{R}[i]$, where $\varepsilon$ and $i$ denote odd roots of $\pm 1$.
As with ordinary vector spaces, there is an isomorphism
$$ \tau : A \otimes B \to B \otimes A, $$
and you need something like this to make an algebra of $A\otimes B$, given the algebra structures on $A$ and $B$ separately:
$$ (A\otimes B) \otimes (A\otimes B) \overset{A\otimes \tau\otimes B}\longrightarrow (A\otimes A)\otimes(B\otimes B) \overset{m_A\otimes m_B}\longrightarrow A \otimes B .$$
Figuring out different ways to define $\tau$ can be confusing at first, but you'll get used to it.
Now, in ordinary vector spaces, the "opposite" product $m^{op}$ is derived from $m$ by pre-composition with the transpose on $A\otimes A$:
$$ m^{op} = A\otimes A \overset{\tau}\to A\otimes A \overset{m}\to A, $$
and the same expression is the "right way" to define the opposite multiplication on a superalgebra; only the $\tau$ means something slightly different for superspaces vs. for ordinary vector spaces.
So, the exercises to start with are to understand $\tau$, and then to verify that $m_{-1}^{op} = m_1 $ and vice-versa --- or, understanding $\tau$, to carry-out the calculation over clifford algebras in full generality.
My favourite reference for superalgebras is Trimble's notes, but now you've read the words "symmetric" and "braided" and "monoidal" together, you can go on digging. Have fun!
Comment: Your favorite reference for superalgebras is...what?
Comment: Sorry, Trimble's notes on superdivision algebras; http://math.ucr.edu/home/baez/trimble/superdivision.html
I can't remember why, but it made an impression. (when I wrote the answer I didn't have 10 rep yet, so it wouldn't let me include a third link)
Comment: No problem.  I took the liberty of editing it into your response (should be visible once the edit is "peer reviewed").  Thanks!
Comment: Do I unterstand you correctly that the reason for my confusion is that i am using the "wrong" definition of $Cl(\beta)^\text{op}$?
Answer: There are different conventions for Clifford algebras, which is confusing.
If I understand your question correctly.
If the  convention for the bilinear form is
$
v . v=\beta(v,v)\cdot 1\qquad\forall v\in V
$
then the algebra is denoted as $\mathcal{Cl}_{p,q}$.
In the opposite convention
$v . v= - \beta(v,v)\cdot 1\qquad\forall v\in V
$
it is equivalent to the algebra $\mathcal{Cl}_{q,p}$.

Opposite Clifford-Algebra


How to dynamically schedule and cancel node-schedule event?

Question: const schedule = require("node-schedule");

let x = schedule.scheduleJob("*/2 * * * *", () => {
  console.log("hi its a scheduled message");
});

x.cancel();

This way we can schedule and cancel a job in node js. But how can it be done dynamically?
Comment: what do you mean by dynamic ? when do you want your job to be scheduled and on what bases so you want to cancel it ?
Answer: Use the below syntax for dynamic schedule of job and settimeout for keeping some time interval for schedule cancel.
const schedule = require("node-schedule");

let time = 1;

let x = schedule.scheduleJob('*/'+time+' * * * *', () => {
  console.log("hi its a scheduled message");
});

let cancel_time = 100000;

setTimeout(() => {
  x.cancel();
}, cancel_time);    //after 100 second


How do i find the combination of strings in a given list that add up to a certain string (without external libraries)

Question: if the string to be formed is 'abcde' and the input list is ['abc', 'd', 'ac', 'ab', 'e', 'abcd']
the different ways to form string 'abcde' will be
(1) 'abc'+'d'+'e'
(2) 'abcd'+'e'
And thus the answer is 2.
How do i approach this problem?
My progress so far ;_;
character1 = input()
n = int(input())    # number of allowed inputs for list
list1 = [input() for i in range(n)]

Comment: First try to find if you have `abcde` in the list. If not, then start chunking and seeing if the combinations of those form the string `abcde`
Comment: yea, but that requires the use of combinations right, I cannot use itertools as this is supposed to be solved without external libraries.
If you have a way, pls elaborate
Comment: Disinclined to exertion Dude: The documentation for [`itertools.combinations()`](https://docs.python.org/3/library/itertools.html#itertools.combinations) shows what it's equivalent to.
Comment: I strongly recommend using itertools.combinations(). Reinventing that wheel is a very lengthy program. You can try to do it but it will be a lengthy code and you will need to create and check for a lot of combinations
Comment: this is a question in the cses problem set.. I don't think we can import libraries in the submitted code.
Answer: You can use a recursive generator function:
d, s = ['abc', 'd', 'ac', 'ab', 'e', 'abcd'], 'abcde'
def get_combos(d, c = []):
  if ''.join(c) == s:
     yield c
  else:
     for i in d:
        if s.startswith(''.join(c)+i):
           yield from get_combos(d, c+[i])

print(list(get_combos(d)))

Output:
[['abc', 'd', 'e'], ['abcd', 'e']]


Are there rules that determine whether a chord belongs to a particular key?

Question: Suppose I have a chord such as FAC. How do I know whether the notes belong to C (Fa La Do') or F (Do Mi Sol) or perhaps another key? Do music theorists have theories for how a key gets established?
In the artificial neural network community, I know connectionists have modeled key recognition using neural networks, but I am not familiar with how music theorists think about this problem.
Comment: Not sure if I understand your question, but the F major chord belongs to any key which contains the notes F, A, and C, i.e. C major (A minor), F major (D minor), Bb major (G minor).
Answer: In isolation, FAC doesn't belong to any key. It's just an F major . When it's put into a piece it goes into context. Usually, a piece IN F will end ON F, and feel that it has ended, without the need for any more to follow. Often, that piece will start ON an F (usually in the first full bar if there's an anacrucis) as well. The feeling of 'home'.
At various other points in the tune, cadences will appear. They will give clues as to whether the song is IN F. If they are Fs themselves, and the song is indeed in F, those points will feel that the song could finish there. If they are, for example, imperfect cadences, they will give the feeling that there is more to come. For example, a middle 8 ending on CEG makes it feel the need for the next part to continue back on FAC. This is known as V-I, the 'I' being F in this case.
Comment: +1 For discussing **context**, which extends beyond music with keys or functional harmony. I can create tone regions, pitch collections, or sonic pallets simply by emphasizing a tone or tones more than others. To that end, how you manipulate the sound is dependent on what you mean to do with it.
Answer: Chords are not bound by any specific key. They stand independent of Key. Any key with the notes F/A/C can have that F Major chord in it. There is also some styles / composers who may write music that has a very loose adherence to key. This chord may come in music if this is the case also.
There is also at times places in music where you move away from the key and us notes that are foreign to the key and this chord may very easily be used then as well.
So in closing chord usage often relies on the notes of the scale for the notes but can at times move away from such an idea. So don't get hang up on the chords = scale idea.


Carregar um arquivo TXT no Access, iniciando a leitura a partir da 10ª linha

Question: Estou carregando via VBA um arquivo TXT para uma tabela do access, mas o arquivo txt tem um cabeçalho com 9 linhas que não preciso, como posso resolver no vba para que o arquivo comece a ser lido a partir da 10ª linha.
Comment: Salve, meu caro! Lembre-se de postar seu código atual, além de indicar eventuais erros.
Answer: Dei uma lida nos métodos relacionados a manipulação de arquivos, e parece que não existe nenhum que busca a posição por linha. Existe a operação seek, mas ela busca a posição no arquivo por byte (ou seja, mais ou menos por caractere).
Assim, a forma mais simples que eu enxergo de ler a partir da décima linha é adicionar um contador no seu código e só salvar a informação a partir da linha que você quer. Por exemplo (você adapta pra sua realidade):
Open "caminhoArquivo" For Input As #1
i = 0
ignorarAteLinha = 9
Do While Not EOF(1)
  i = i + 1
  Line Input #1, conteudoLinha
  If i > ignorarAteLinha then
    Debug.Print conteudoLinha 'Dentro desse if você faz o que precisa
  End if
Loop
Close #1


How to get the "Background-color: Background"-Color in JavaScript?

Question: I think since CSS 3 you can use the Background as Background-color attribute. It says the displayed color is based on the Desktop-Color, so it can variate from client to client.
alert(document.body.style.backgroundColor); returns just background, instead of a color-value.
So how to get the RGB-/Hex-Value of the used color in the specific element?
Comment: What do you get if you use `getComputedStyle()`?
Comment: document.body.style.backgroundColor works for me just fine
Comment: `backgroundColor` returns the background color, not the full background. And `background-color` was already defined in CSS 2.1
Comment: thanks to all, `getComputedStyle` worked for me :)
Comment: I would like to offer some advice: If you can find a way to avoid it, don't set set styles using JS - instead, add/remove classes to be selected and styled by CSS. Helps with [SoC](https://en.wikipedia.org/wiki/Separation_of_concerns#HTML.2C_CSS.2C_JavaScript) for easier code maintenance
Answer: Use getComputedStyle()
// $0 is your htmlElement
window.getComputedStyle($0, null).getPropertyValue('background-color')

Comment: Modern browsers don't need `null`
Comment: @Oriol good to know, anyway, I'll leave it there for compatibility