How to create human readable live dump of SQL Server Database (all tables, all fields, all values)?

Question: how can I get a Dump of a database with many tables to a flat file that is human readable quickly? Like csv or SQL create/update phrases. Or any binary format that can be viewed from a text viewer is fine.
The data export from management studio only allows one table at a time (?) which is not enough, I need all, there are many. Or how to circumvent this?
Actually I need to find some data in the database and understand which table and which column it belongs. We need this in a live system that belongs to us but the 3rd party developers are not reachable now, but for us it is enterprise critical to get it quickly.
I can access the db also in ms access, but to write such code would take too much time now (unless it is already available in this form)
There is also aqua data studio 4.7.2 available here
<code>Microsoft SQL Server Management Studio                      9.00.3042.00
Microsoft Analysis Services-Clienttools                     2005.090.3042.00
Microsoft Data Access Components (MDAC)                     2000.086.3959.00 (srv03_sp2_rtm.070216-1710)
Microsoft MSXML                     2.6 3.0 6.0
Microsoft Internet Explorer                     7.0.5730.13
Microsoft .NET Framework                        2.0.50727.3603
Betriebssystem                      5.2.3790
</code>
Answer: Write up your SELECT statement which joins all tables and deposits the results into a new table. After your are satisfied with the returned data you can export that single table to XLS or whatever format you may want.
This still will require you to do the joins... but in the end it should be exactly what you want. I don't know of a free product which would do this automatically for you.
Comment: this sounds intersting. how would i join 2 tables with different fileds without enumerating the fields?
Comment: Are these relational tables or are they completely unrelated? If they're relational tables you shouldn't have a problem with enumerating the fields. If they're not related then I would think you'd be forced into dumping each table to xls.

I'm not familiar with aqua data studio but did some searching around anyways. A more recent version supports the export of data to a variety of formats (including csv): http://www.aquafold.com/docs-exporttool.html

Please let me know how that works out. Good luck.
Answer: This is how I did it:
Download xampp from http://apachefriends.org, unzip, configure and start it, now there is a mysql server running on localhost
Migrate the SQL-Server database to the xampp mysql instance, using the mysql migration toolkit:
http://dev.mysql.com/doc/migration-toolkit/en/index.html
Go to http://localhost, there is an xampp phpmyadmin instance running, export the just created database as a single csv file. It can be necessary to increase php script maximum runtime or split the database in various parts (choosing only part of all the tables for each export)
Comment: of course it is possible to use an existing mysql server for this, but if there isnone available downloading xampp is probably the fastest solution


cyclic groups -class is prime number

Question: How can I prove that a group $G$, such that $|G| = p$, where $p \in \mathbb{P}$,
is cyclic?
Comment: What's your definition of $\;G_p\;$ , for $\;p\;$ a prime??
Comment: "The class of group"  seems to be a non-standard, particular term. But "number of elements, or **order of the group**,  is easy to understand
Comment: G is a group which has p numbers or the class of group is p
Answer: Suppose $\;G=\{g_1,...,g_p\}\;$ and let $\;1\neq g_i\in G\;$. Look at the cyclic subgroup $\;\langle\,g_i\,\rangle\,\le\,G\;$.
Now apply Lagrange's Theorem: what can you say of the order of that subgroup? And then...?
Answer: Here |G| = p (prime). Consider a non-identity element 'a' of the group G. By Corollary of  Lagrange's Theorem, |a| divides |G|. So, |a| = p = |G| (Since, a ≠ e ). Thus, 'a' generates G. Hence we conclude that G is cyclic.

cyclic groups -class is prime number


How to extract the values from a gridded data only along a straight line consisting of multiple latitude and longitude pair points

Question: I have gridded 4D (lonlatplevtime) data, where lon and lat represent longitude and latitude, and plev designates the vertical pressure level. I want to extract the data only along a straight line of multiple longitude-latitude pair points so that I can finally obtain 3D (xplev*time) data, where x represents the dimension of lon-lat pair points. Now, the straight line has 781 longitude-latitude pair points. However, the sizes of the longitude and latitude in the gridded data are 501x1 and 901x1, respectively.
Earlier, I successfully extracted the value from the same 4D data only for a station location (i.e., only a latitude-longitude point) using the following CDO command line:
cdo -remapnn,"lon=77.222_lat=28.588" data.nc data_NewDelhi.nc

But this time I want to extract data from the same gridded data but only along the straight line of 781 latitude-longitude pair points, and then store the data in the new netcdf file. Thus, the final netcdf file should have a size of 781 * plev * time.
So, my question is: Is there a command line in CDO to perform this operation?
Comment: How to create a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)
Comment: Welcome to SO. While I'm sure people on here can help you, this is a programming forum. Please revise the question so that it is purely about programming and doesn't require any scientific knowledge. I work with CDO all the time, but I have no idea what CALIPSO is. Just write it as a programming question, and then we can help
Comment: Hello @RobertWilson, I modified my question again to make a pure programming question. I believe that this will not require any scientific knowledge. Can you please guide me to solve this problem?Is there any way to do this calculation using CDO?Thank you for your time and consideration.
Answer: To do this using CDO you first need to create an unstructured grid file. The example below will work for 2 data points. Replace it with the 70 grid points you need. Just call a file grid and put the following in it.
gridtype = unstructured
gridsize = 2
xvals = 0 10
yvals = 0 10

Once you have defined that file, you can regrid in CDO in a similar way to what you have shown:
cdo remapnn,grid in.nc out.nc

Comment: Dear Robert, Thank you for the response. I just need small clarifications from you. (1) Do you mean that I should create a text file 'grid.txt' (i.e., using the Linux command 'nano grid.txt') and paste the following line in it? (2) For 781 longitude-latitude pair points, the lines should be replaced with 'gridsize= 781' . Right? (3) Do 'xvals' and 'yvals' mean the corresponding values of the longitude and latitude, respectively? I am really looking forward to hearing from you. Thank you for your time and consideration.
Comment: Please read the CDO user guide, which explains how to set up grids. https://code.mpimet.mpg.de/projects/cdo/embedded/cdo.pdf
Comment: Okay. I accepted your answer.


Explaining why $i^n$ can only be equal to $1,i,-1,-i$

Question: How can I explain why $i^n$ can not have any other values than $1,i,-1,-i$ for all $n \in \mathbb{N}$?  Should I write it out as a sequence $i^n= 1,i,-1,-i,1,i,-1,-i,1,...$ and say that it repeats after every 4th term?
Comment: Prove that $i^4=1$, so $i^{n+4}=i^n$ for every $n$.
Comment: Prove it by induction on $n.$
Answer: You might want to think of it this way.
$i$ is just a way to symbolize the vector $(0,1)$ in $\mathbb{R^2}$.
When we consider the product of $(0,1)$ with itself, that is $(0,1)^n=i^n$, what happens in each iteration (that is, each time we multiply) is that the vector's length remains the same while it is rotated by $90^{o}$ anticlockwise*.
There are only four possible positions where we might end up, $(0,1), (0,-1), (1,0), (-1,0)$ which correspond to the values $i, -i, 1, -1$.
*indeed, let $z=x+iy$.
Then $zi=(x,y)*(0,1)=(-y,x)=w$ where $|z|=|w|$ and the points $(x,y), (-y,x)$ are the edges of a right triangle, the other edge being the origin $O$.
Answer: Well, $i$ is a primitive fourth root of unity: $i$, $i^2=-1$, $i^3=-i$ and $i^4=1$.
Algebraically, $i$ is a (formal) root of the real polynomial $x^2+1$, i.e., $i^2+1=0.$, i.e., $i^2=-1$. Then $i^3= i^2\cdot i= -i$ and $i^4=i^2\cdot i^2 = (-1)\cdot (-1)=1.$
Comment: You can use $i^n=\left( -1 \right) ^{n/2}$


Prove that if $ \lim_{x \to 0}g(x)=0$, then $\lim_{x \to 0} g(x) \cdot \sin(1/x) = 0 $

Question: This is the Problem 21 from Chapter 5 of M. Spivak's "Calculus". It states:

Prove that if $ \lim_{x \to 0}g(x)=0$, then $\lim_{x \to 0} g(x) \cdot \sin(1/x)  = 0 $

That's how I approached the problem. First, we know that $\sin(1/x)$ does not approach any limit as $x$ approaches $0$. However, we also have that $ \left | \sin(1/x)  \right | \leq 1 = M $ for all $x$ near $0$.
Since $\lim_{x \to 0} g(x) = 0$, we can make $g(x) \cdot sin1/x$ as close to zero as we want.
I am not sure how to prove this formally though. That's what I've come up with so far.
Since $M = 1$, we can have $ |g(x) \cdot M|  < \epsilon $ for any $\epsilon$. Thus, $|g(x)| < \dfrac {\epsilon}{|M|} = \epsilon $. However, I am stuck in converting this into statements about $\delta$ and generalizing for $M$ other than $1$. Need your help.
Answer: For $\epsilon>0$ we need to find a $\delta>0$ such that $|g(x)\sin \frac{1}{x}-0|< \epsilon$ for all $0<|x|<\delta$. $$\left|g(x)\sin \frac{1}{x}\right|< |g(x)|$$
As $\lim_{x \to 0}g(x)=0 \implies \exists \delta>0$ for the same $\epsilon$ such that $|g(x)|< \epsilon$  for $0<|x|<\delta$ Hence $$\left|g(x)\sin \frac{1}{x}\right|< |g(x)|<\epsilon$$ for the same $\delta$.
Edit for strict inequality
Comment: We need find a $\delta$ such that $|g(x)\sin(1/x)|\le \epsilon$ as per the definition of limits of functions. As we have already chosen $\epsilon>0$, and the functions are defined we can estimate this.
Comment: Yes, but everywhere in the book it is written: ' f(x) approaches the limit L near a if for any E > 0, there is a D > 0 such that, for all x if 0<|x-a|<D, then |f(x)-L|<E." Thus I was confused by the <= sign.
Comment: You are right. Technically, its the open balls (open interval) we consider.
Answer: We have
$$-g(x)\le g(x)\sin\frac1{x}\le g(x)$$
for all $x\ne 0$. Note that $$\pm g(x)\to 0\text{ as }x\to 0.$$ Therefore, by the pinching theorem, we have
$$g(x)\sin\frac1{x}\to 0\text{ as }x\to 0.$$
Comment: Thanks, that exercise about limits of f(x)<=g(x)<=h(x) was actually in the Problem 13 of Chapter 5 but I skipped it :(


Onchange and depends methods with self containing NewObjectId as records

Question: As far as I understand the execution of the methods with decorators @onchange and @depends, almost always the argument 'self' in both is a recordset with this format:
res.partner(1, 2, 3) (for example in this case for the res.partner model)
What represents the records on which the decorated methods will be applied.
In cases where the ORM does not recover the id in the database, it is because it is an element that has not yet been recorded.
This is what I learned from books about Odoo's theory and that worked for me so far.
Two weeks ago, after updating third-party modules, I began to notice that in my own modules the self argument always returned me (for example):
res.partner(odoo.models.NewId object at 0x7f8c0f604768,)
And so for each of the methods with these decorators.
This for me indicates that it does not recover the id in the database and only returns its address in memory.
I tried many things, to delete all the own modules and to re-clone them or, create a new database and only install the own modules or, create a new base but with only Odoo modules and use a clean module created by the scaffold command or, delete the IDE and reinstall it, until testing in an instance on another computer and installing my own modules. But I always get the same result.
Before these two weeks the methods in my own modules used the self correctly. And the only updates were to third-party modules.
Another thing of interest is that both the third-party modules and the Odoo modules do recover the recordset in the self variable (according to the theory), but not for my own modules (not even for the basic module that is built using the scaffold command).
My questions are:
- Why the variable self uses the record in this way?
- How can I correct this bug if it were?
Thanks so much in advance!! :)
Comment: Can you include the code for at least one of the methods you are using? Make sure to include which class it's a part of too.
Comment: Actually that's not a bug. Just look into `BaseModel.onchange` and you will see, that the record the onchange is happening on will be replaced by a `NewId` record and the origin will be kept in in this record's `_origin` attribute. That feature/logic is used since introduction of the "new" API in Odoo v8 (IIRC).
Answer: It's fine for onchange methods for me now. But in depends methods I understood that the self variable always had a recordset. The images show a simple module created with scaffold command and using the debug system in Pycharm. I just stopped in a method with @depends decorator and that's the result.
Comment: In this case `self` could be a recordset. So the code is wrong. You need to loop over self and set the value for each object


How can I let a plugin depend on another module?

Question: Is it possible to let a plugin depend on a module (other than the declaring one)?
Use case: I want to create a field widget plugin that should depend on the 'date_all_day' contrib module, but I don't want the entire declaring module depend on this.
Is it possible to declare this in the annotation?
E.g.
<code>/**
 * @FieldWidget(
 *   id = "my_daterange",
 *   label = @Translation("Date and time range + All day"),
 *   field_types = {"daterange"},
 *   dependencies = {"date_all_day"}
 * )
 */
class MyPlugin {...}
</code>
The plugin should only become available if both the declaring module and the dependency module are enabled.
Answer: Yes, this is possible.
You may declare a dependency on a module by using the "provider" key in the annotation. For your example, this would look like:
<code>/**
 * @FieldWidget(
 *   id = "my_daterange",
 *   label = @Translation("Date and time range + All day"),
 *   field_types = {
 *     "daterange"
 *   },
 *   provider = "date_all_day"
 * )
 */
class MyPlugin {...}
</code>
Note that you can only list ONE provider, but of course that provider module can depend on other modules ...
This is a feature added to the DefaultPluginManager in order to allow plugins to declare a dependency on one (and only one) module. This only works for plugins that use a plugin manager derived from DefaultPluginManager.
Specifically, @FieldWidget plugins are managed by the WidgetPluginManager, which DOES subclass DefaultPluginManager, so this will work. (Most, if not all, core plugin managers subclass DefaultPluginManager.)
Answer: First, it's probably preferable to use the provider option if you can.
However, Field widgets and formatters also make use of an isApplicable() method. You can use this for any additional logic to determine whether your widget should be available for a field, a field in the subset of fields defined in your annotation.
You can use this method to limit the widget to just a datetime field with a particular machine name, or only datetime fields on nodes, etc.
You can also use it for your case, to check if other modules are enabled.
Comment: Nice! If I could I would accept both answers because this is an essential part of the picture.
Comment: In practice, checking on moduleExists() isn't very useful for plugins because it can only be called after the plugin is discovered and made available as a selection in the UI. If the plugin depends on another module through inheritance or implementation, or by injecting a service provided by that other module, etc, then moduleExists() won't help. You have to prevent the plugin from being discovered in the first place or the code will fail. Even in the best case, a moduleExists() check will still allow your plugin to be selected and used - it will just prevent the plugin code from functioning.
Comment: Obviously, it's preferable to [use the provider option](https://drupal.stackexchange.com/a/299021/48114) if you can. While you are correct that, with this approach,you cannot use dependency injection to inject services from dependencies you're checking in `isApplicable()`, you could just access them from the service container via `Drupal::service('etc')`. Additionally, if a field formatter or field widget's `isApplicable()` method returns false then the widget can't be selected in the interface - it would stop people from selecting it.
Comment: As a possible alternative, is there an alter hook that fires in the discovery phase?


Is it possible to use an Elastic Load Balancer on an IIS Server accepting BITS Uploads?

Question: I have a website hosted on EC2 using IIS 8.5. I've got a virtual directory with BITS uploads enabled, and everything works over http and now https when my URL points to the instance's public EIP.
The design calls for using an Elastic Load Balancer in front instance(s). The trick is, when I connect an ELB, I start to get 500 errors for the BITS sessions. We've determined that when we don't use the ELB, the jobs complete correctly.
The specific BITS errors we were seeing in the IIS logs were "Invalid Index." inside of an HTTP 500 error. See this question about tracking down BITS error codes.
We have a hypothesis that since BITS uses extended HTTP verbs (such as BITS_POST) that maybe some of the ELB magic was mangling our headers. Before I try setting up WireShark to dig deeper, I wanted to check if anyone else has encountered this problem.
Answer: Despite AWS claiming that ELB supports all HTTP verbs as of late 2013, I am experiencing the same issue and have had to settle for using TCP forwarding to get BITS uploads to work through the ELB.
Details:
I have two Server 2012 R2 VMs, one on an vSphere 5.5 cluster at a colo (VM1), the other at AWS (VM2), both fully patched as of 6/1/2016. VM1 utilizes PowerShell (Start-BitsTransfer -TransferType Upload) to push files to VM2 (running IIS 8.5 with both HTTP and HTTPS bindings, the latter using a CA-issued certificate).

HTTP BITS uploads from VM1 to VM2's Elastic IP succeed.
HTTPS BITS uploads from VM1 to VM2's Elastic IP succeed.
HTTPS BITS uploads from VM1 to VM2's ELB configured for HTTPS (layer 7) with SSL offloading, pointed at the instance's HTTP binding fail.
HTTPS BITS uploads from VM1 to VM2's ELB configured for TCP forwarding (layer 4; no SSL offloading) to the instance's HTTPS binding succeed.

Bullet point 3 is what I (and it seems you) wanted but Option 4 is what I've settled for and it works.
Error details for posterity (/the 50 people a year who stumble across this question): Investigating option 3, VM1 throws the following error:
PS C:\> $error[0] | Select-Object *
writeErrorStream      : True
PSMessageDetails      :
Exception             : System.Exception: Invalid index.

TargetObject          :
CategoryInfo          : InvalidOperation: (:) [Start-BitsTransfer], Exception
FullyQualifiedErrorId : StartBitsTransferCOMException,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at


Kivy app just load then closed in android

Question: I've built my app on windows using bash and buildozer, it's successfully done, then I've put the apk on my android 7 phone, but it's just loading then closed without any message or anything. How can I solve this?
Comment: How we can help you without any clue?Please read [mcve] and [ask] and provide us a better description of your problem please.
Comment: Try running `buildozer android deploy run logcat` with your phone connected to your PC. Then have a look at the logcat output.
Answer:
Put some break points and debug the code to check where what is going on!
Comment: i did so but in vain
Comment: your given information is not enough to dig in @ashrafkhaled
Answer: this is my code  , i dont know why cant i run the api
<code>import kivy
from kivy.core.window import Window
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.properties import ListProperty
from kivy.uix.button import Button
from kivy.lang import Builder
from ipify import get_ip
import geocoder
from datetime import datetime

class MainPage(GridLayout):
    # runs on initialization
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        #used for grid
        self.cols = 1

        #Labels
        self.IP_label = TextInput(text = " IP Address " , height = Window.size[0]*0.16)
        self.Mac_address = TextInput(text = "MAC Address" , height = Window.size[0]*0.16)
        self.GPS = TextInput(text = "GPS(Lat,Lon)" , height= Window.size[0]*0.16)
        self.time_stamp = TextInput(text = "Time" , height = Window.size[0]*0.16)

        #buttons
        self.get_ip = Button(text = " Get IP "  , height = Window.size[0]*0.16  , on_press = self.get_public_ip)
        self.get_loc = Button(text = "get_Loc" , height = Window.size[0] , on_press = self.get_location_mac_time)

        #adding widgets
        self.add_widget(self.IP_label)
        self.add_widget(self.Mac_address)
        self.add_widget(self.GPS)
        self.add_widget(self.time_stamp)
        self.add_widget(self.get_ip)
        self.add_widget(self.get_loc)

    #functions
    def get_public_ip(self,instance):
        ip = get('https://ip.seeip.org').text
        self.IP_label.text = 'My public IP address is: {}'.format(ip)
        with open('Public_IP.txt', 'w') as k:
            print('My public IP address is: {}'.format(ip) , file = k)

    def get_location_mac_time(self,instance):
        g = geocoder.ip('me')
        Time_now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        k= tuple(g.latlng)
        my_dict = {}
        for idx, val in enumerate(k):
            my_dict["v{}".format(idx)] = str(val)

        self.Mac_address.text = "The MAC address is : "+':'.join(re.findall('..', '%012x' % uuid.getnode()))
        self.GPS.text = my_dict['v0'] + ',' +  my_dict['v1']
        self.time_stamp.text = "timestamp :"+ Time_now
        with open('loc_mac_time.txt', 'w') as f:
            print(Time_now, "    ",my_dict['v0'],"    ",my_dict['v1'],"    " ,':'.join(re.findall('..', '%012x' % uuid.getnode())),file=f)

class test_app(App):
    def build(self):
        return MainPage()

if __name__ == "__main__":
    test_app().run()

and no error to show i swear , i cant build the api i dont know why
</code>


First order logic, CNF

Question: What steps do I need to follow to convert the next statements into CNF? Wich are the resulting clauses?

$H \leftrightarrow C \vee D$
$R \rightarrow \neg D$
$R \wedge H$
$H \leftrightarrow C$

Thank you.
Answer: First, be clear what CNF: Conjunctive Normal Form means, and understand why the examples listed in the linked Wikipedia entry are in CNF. Then you'll see that your third expression:
$(3)\; R \land H\,$ is already in conjunctive normal form. Note that $R\lor H$ is also in conjunctive normal form.
One obvious mnemonic for remembering what CNF allows is to remember $C$ is for conjunction, and think of $N$ as "negation."
You want to end with an expression of the form $P$ or of the form $P \land Q$ or of the form $P \land Q \land R \land \cdots$ depending on the number of variables and clauses needed. But note that

Each $P, Q, R$ can represent a literal or the negation of a literal (literals are simple propositions without connectives: in your first question, e.g. $H, C, D$ are each literals, and in your second question, $\lnot D$ is a negated literal.
each $P, Q, R$, etc, may represent a propositional clause within which the only connective is the $\lor$ connective between literals and/or negated literals: e.g. $$A \land (\lnot B \lor C) \land (E \lor F \lor \lnot G) \land \lnot Z$$ is of the form $P \land Q \land R \land S$ where $P := A, \;Q:=(\lnot B \lor C),\;R = (E\lor F \lor \lnot G),\; S = \lnot Z$
No literal appears more than once by itself or in a clause.

I'll leave the first expression to you, in hopes that you can learn from the following examples:
$(2)\quad R \rightarrow \lnot D\equiv (\lnot R \lor \lnot D)$
$(4)\quad H \leftrightarrow C \equiv (H\rightarrow C) \land (C\rightarrow H)\equiv (\lnot H \lor C) \land (\lnot C \lor H)$
The right-most propositions in $(2)$ and $(4)$ are now in conjunctive normal form.
Comment: See what you can get from "unpacking" the first statement. Feel free to post as a comment here what you get for the first statement, and I'll be happy to confirm, or correct you.
Comment: The first expressions CNF is the next one: (¬HvCvD)and(¬CvH)and(¬DvH) ? Thanks for your help @amWhy

First order logic, CNF


Switching from graphql-js to native graphql schemas?

Question: Currently trying to switch from graphql-js to literal GraphQL types/schemas, I'd like to know if anyone has had any experience with this.
Let's take this really simple one :
const Person = new GraphQLObjectType({
name: 'Person',
  fields: () => ({
    name: {
      type: GraphQLString,
      description: 'Person name',
    },
  }),
});

I'd like to switch to the native GraphQL schema syntax i.e
type Person {
  # Person name
  name: String
}

However this would have to be incremental, and given the use of graphql-js, the best solution for now would be to parse GraphQL template literals to GraphQLObjectType (or any other type for that matter). Does anyone have experience doing this, I cannot seem to find any library for it unfortunately.
Answer: import { printType } from 'graphql';

printType(Person)

output:
type Person {
  """Person name"""
  name: String
}

Here is the demo:
import { expect } from 'chai';
import { printType, printSchema, buildSchema, GraphQLSchema } from 'graphql';

import { logger } from '../util';
import { Person } from './';

describe('test suites', () => {
  it('convert constructor types to string types', () => {
    const stringTypeDefs = printType(Person).replace(/\s/g, '');
    logger.info(printType(Person));

    const expectValue = `
      type Person {
        """Person name"""
        name: String
      }
    `.replace(/\s/g, '');
    expect(stringTypeDefs).to.be.equal(expectValue);
  });

  it('buildSchema', () => {
    const stringTypeDefs = printType(Person);
    const schema = buildSchema(stringTypeDefs);

    expect(schema).to.be.an.instanceof(GraphQLSchema);
  });

  it('printSchema', () => {
    const stringTypeDefs = printType(Person);

    const schema = printSchema(buildSchema(stringTypeDefs));

    logger.info(schema);

    const expectValue = `
      type Person {
        """Person name"""
        name: String
      }
    `.replace(/\s/g, '');

    expect(schema.replace(/\s/g, '')).to.be.eql(expectValue);
  });
});

source code:
https://github.com/mrdulin/nodejs-graphql/blob/master/src/convert-constructor-types-to-string-types/index.spec.ts
Comment: Unfortunately this doesn't work, for our case we want it the other way around. But thank you, I skipped the 'graphql-js' utilities, seems like there is 'buildSchema' which is perfectly indicated here :)
Comment: @AlexandreGomes Sorry. Did I understand your question correctly? I understood that you want to convert `constructor object type definition` to `string type definition`?
Comment: That's what I want to do in the project indeed, moving the types codebase `GraphQL schema language.`. But for that to be achieved, it is needed to have a way to convert `GraphQL Schema language` to `Schema object`. Could you modify your answer to point to the `buildSchema` utility, so I can accept it as an answer ?
Comment: Good ! Thank you :)
Answer: You can use graphql-cli to extract a native graphql schema from a graphql server. All you need to do is..

Download the tool | npm i -g graphql-cli
Run graphql init in the directory of your project to
create .graphqlconfig file
Start your graphql server
Run graphql get-schema and this will generate a your schema in native graphql

SAMPLE .graphqlconfig
{
  "projects": {
    "my_sample_project": {
      "schemaPath": "schema.graphql",
      "extensions": {
        "endpoints": {
          "local": "http://localhost:8080/graphql"
        }
      }
    }
  }
}

We leverage the auto-generation of graphql schema/queries/mutations for our CI workflows.


How do I Create Bootstrap Thumbnail Items in DivShot?

Question: DivShot is looking really awesome, finding it really useful as I'm a newbie to Bootstrap. One thing i cant see in there is how to create Thumbnail grids (http://twitter.github.io/bootstrap/components.html#thumbnails). Is there a away of doing this or am i missing something?
Cheers
Malcolm
Answer: Edit:
Unfortunly there is no thumbnail possibility in divshot. But divshot has a nice included html editor and u can add the thumbnail syntax there.
The css is always available via the bootstrap.css
Comment: Thanks Denny, the screenshot you have on there is of the 'Image' element whereas the 'Thumbnail' element can be used for more complex info like a list of e-commerce products etc. hope that makes sense and apologies if I ma missing something within the image element that does this but still cant see how to do this
Comment: Thanks Denny, much appreciated, I thought that might be the case but wanted to check. I can create this code no problem


Can an intercepting player be down by contact that occurs before the interception?

Question: Consider a scenario where a receiver runs a post route to the goal line. A linebacker drops back into coverage, jumps, and tips the pass right before the goal line. In the act of deflecting the pass, the linebacker collides with both the intended receiver and another teammate in coverage. His momentum carries him into the endzone as he flies through the air, but the collision knocks him over upon landing. The pass is tipped multiple times by both offensive and defensive players and somehow passes right in front of the linebacker. He lunges from his knees, extends his arms, and catches the ball before it touches the ground. He is not touched by any player after the initial collision.
Can he get up and advance the ball now, or is he down by contact? If he is down, is he down at the 1 yard line (where the contact occurred) or for a touchback (where he caught the ball)? Would changing certain details (like how many players tip the ball) affect the ruling?
Comment: If he WAS down by contact I believe he would get the ball at the 20 due to his forward progress taking him into the end zone.
Answer: Your original question:

Can an intercepting player be down by contact that occurs before the interception?

The answer is NO.
Until the interception is made there is no possession of the ball.  Until possession of the ball is established, contact by an opposing player can not result in a player being down by contact.  There is often incidental contact between players before a catch and that is not considered the act of tackling because there is not yet possession of the ball.  From NFL Rules Section 36, Article 3: Change of Possession:

A change of possession occurs when a player of the defensive team secures possession of a ball that has been kicked, passed, or fumbled by a player of the offensive team, or when the ball is awarded to the opposing team by rule. A change of possession includes, but is not limited to:
An interception of a forward pass

Therefore after possession has changed, the interceptor becomes a new runner and contact must be made by the Offense (in your example) before he gets off the ground.

Can he get up and advance the ball now, or is he down by contact?

If no contact is made after the interception (and thus the change in possession) he may advance the ball until tackled unless he is touched before his body, knee, elbow, etc. are separated from the ground.


Abrir ou form1 ou form2 na inicializacao do programa winform

Question: tenho um programa em vb6 e possui dois botoes - Uma mara scanner e outro para consulta de imagens escaneadas.
Criei um programa em c# winform em que no projeto tem 2 forms - um form1 para o scanner e outro form2 para as consultas das imagens scaneadas. Os dois no .Net funcionam perfeitamente. Gostaria de saber se existe como fazer com que ao executar o programa .net , através de um parametro 1 ou 2 , escolher qual dos forms irão executar atravéz do VB6
No vb pretendo dependendo do botão clicado, ira gravar em uma tabela ou 1 ou 2 . No botão escolhido, ira chamar a aplicação atraves do shell.
Iniciando a aplicação, consultarei a tabelacom o parametro escolhido e abrirei o form solicitado.
Só não sei como fazer isso no .net c#.
o inicio do Program.cs esta assim no .net
[STAThread]
static void Main()
{
    ConsultaImagens2 f2 = new ConsultaImagens2();
    Application.Run(f2);
    MainFrame f1 = new MainFrame();
    f1.Close();

    MainFrame mf = new MainFrame();
    ConsultaImagens mf = new ConsultaImagens();
    Application.Run(mf);
    MainFrame mf1 = new MainFrame();
    mf1.Close();
}

Comment: Você quer que o usuário escolha qual aplicação (form1 ou form2) executar, ao abrir o programa? você pode criar um novo **form** com opções e um botão que ira checar essas opções e abrir o respectivo programa,
Answer: Sim, isso é completamente possível. Para isso você pode usar os parâmetros no método Main. Como você vai chamar o executável pelo prompt, é só fazer

C:\AlgumaPasta > nomeAplicacao.exe ConsultaImagens2

O código fica mais ou menos assim:
Obs: Não entendi porque instanciar aquele MainFrame então o removi.
[STAThread]
static void Main(string[] args)
{
    Form formAbrir;

    if(args[1] == "ConsultaImagens2") //a posição 0 é sempre o caminho do arquivo
        formAbrir = new ConsultaImgens2();
    else
        formAbrir = new ConsultaImagens();

    Application.Run(formAbrir);
}

Comment: Para um dos botões estou colocando a seguinte rotina em shell, e ao rodar só abre o form  ConsultaImagens :   Como segue    "ShellExecute Me.hwnd, "open", "C:/ScannerSefaz_V08/EscaneamentoSefaz.exe " & ConsultaImagens2 & " ", "C:/", "C:/", vbNormalFocus" Passei parametros para args  e esta abrindo corretamente no c#
Comment: Então tem algo errado na passagem de parâmetros
Comment: Esta sintaxe esta correta ou devo trocar? ShellExecute Me.hwnd, "open", "C:/ScannerSefaz_V08/EscaneamentoSefaz.exe " & ConsultaImagens2 & " ", "C:/", "C:/", vbNormalFocus" ?
Comment: Perfeito JBueno, deu certo. eu só estava dando espaco em branco no shelll. Ja corrigi                     ShellExecute Me.hwnd, "open", "C:/ScannerSefaz_V08/Consulta/ConsultaEsc", "C:/", "C:/", vbNormalFocus


Good text on Differential manifolds?

Question: I am new in field of topology.I am finding a good self readable text on differential
manifolds.
Comment: you can try "INTRODUCTION TO SMOOTH MANIFOLDS" -JOHN LEE
Comment: prerequisites to read this book i am 3rd year engineering undergrad
Answer: Introduction to Smooth Manifolds by John M. Lee
This is the standard, comprehensive textbook suitable for self-study. I strongly recommend you to try this.
Comment: Spivak's "Differential Geometry, Vol. 1" complements Lee nicely!
Comment: prerequisites to read this book i am 3rd year engineering undergrad

Good text on Differential manifolds?


Drupal 7 views Contextual filters with Page & Blocks

Question: I have an issue and i'm hoping to get some advise.
I have a view created that show content based on the url:
eg:
domain.com/item/one
Shows fields for my node with the title one
domain.com/item/two
Shows fields for my node with the title two
etc etc.
The path for the PAGE in views is set to /item
What I'm having trouble with is I need to have a BLOCK (becuase I'm making it collapsable) show under that page with the specific URL show the body field for that node.
eg:
domain.com/item/three
Shows fields for my node with the title three as well as a block that show the body field for node three
I have set the Contextual filter for the PAGE to:
Content: Title

When the filter value is NOT in the URL
Show "Page not found"

Exception value : Empty (All removed)

Under More:
Case : Lowercase
Case in path : Lowercase

Transform spaces to dashes in URL : Checked

This works for the page but please let me know if I have set this up incorrectly.
I have set the same Contextual filter for BLOCK and it works in views preview but not on the page with the URL:
domain.com/item/three
I also tried adding Global: Null Contextual filter before the Content: Title filter which allowed me to put item/three in the preview and it works (before worked with just three). This also didn't work on the actual page.
Any advise on this would be greatly appreciated.
Answer: Contextual filters works well for any display type that has a path. A path makes it easy for views to determine what information should be passed into the contextual filters.
The problem with blocks is that they don't have a path. Views does not look at the current url and automatically pass values to the filters because it has no idea which parts of the url to use.
You can get around this by using Default Values (or page manager/panels, but that's a whole other topic).
In the settings for your block contextual filter, you will want to override the configuration and select Provide a default value. Under type choose Raw value from URL and set the Path component to 2 (the path component will be different depending on your URL, but for domain.com/items/node-title the component is 2)

When you assign your block to a region, you probably want to set the allowed paths so this block won't show up anywhere else. The path component is "hard coded" so if your path ever changes you will need to adjust it.
Comment: You're likely better off using "Content ID from URL" as "raw value" allows partial matches. E.g. "blog/post-1" will display content from "blog/post-11".
Comment: Thanks for this, and although I feel a little dirty using this method I have already spent too long trying to find a better one.


Integrate a function of $\cos(x)$

Question: I wish to calculate $\int_0^{2\pi} \cfrac{dx}{(1-2 t\cos x+t)^2}$ for $|t|<1$.
I already know that $\int_0^{2\pi} \cfrac{dx}{1+k\cos x}=\cfrac{2\pi}{\sqrt{1-k^{2}}}$ for $|k|<1$
and  that $\left|\cfrac{1}{(1-2t\cos x+t)^2}\right| \leq \left| \cfrac{1}{1+k\cos x} \right|$.
I also know that the answer is $\cfrac{2\pi}{1-t^{2}}$.
How can I get this answer? Is there any theorem such as the series comparison test for integrals?
Thanks a lot!
Comment: This integral is improper for some values of $t$ (if I am not wrong, for $t > 1/3$).
Answer: \begin{align*}
\int_0^{2\pi} \frac{dx}{(1-2t\cos x+t)^2} &= \oint_{|z| = 1} \frac{1}{(1-2t (z+z^{-1})/2 + t)^2} \frac{dz}{iz} \\
&= -\oint_{|z| = 1}\frac{iz}{(t z^2-tz-z + t)^2}\,dz
\end{align*}
$$z = \frac{t+1 \pm \sqrt{-3t^2+2t+1}}{2t}$$
Now with the restriction $|t|<1$, find which root(s) are in the contour $|z|<1$ and use residue theorem to evaluate the integral.
Answer: One proof could be by replacing cos x for (e^ix+e^-ix)/2 and using Cauchy residue theorem
Comment: Not even an answer. I would like the exact derivation.
Comment: this is not a math class parcly
Comment: But you have not shown how the Cauchy residue theorem allows you to derive the given answer.

Integrate a function of $\cos(x)$


bootstrap pull-right adding extra space

Question: I am using pull-right on a div that sits inside a container div but for some when I use a pull right on the div it makes the div wider so that it isn't flush with the right side of the page.  Ive used Chrome to inspect the element but I can't figure out where this extra width is coming from.  It isn't the padding or the margin the container just seems to be wider?
Problem can be seen here at the top of the page where all the social media icons are.
http://puntachivosurfcamp.com/

      ...

Comment: would adding the class `text-right` in addition to `pull-right` be what you are looking for?
Comment: Thanks for the answer that did achieve the desired look but I'm still curious about where the width was coming from, the same thing happened if I tried to pull the individual links right as well they ended up being wider than the images.
Answer: There is no such extra space but the text is just aligned to the left although the container you are talking about is pull-right but the objects in it aren't. So:

Apply text-right as well on your pull-right div to align the text to right side :)
Apply pull-right to every object present in the div aka social media icons (but I recommend the first approach)

Explanation:
The width of the container is greater then the width of all the object in it so when the objects in the container will be left aligned it will show us as if some extra space was present on the right side but as soon as we align the text to the right we see that now the space has been vanished and the objects have now come on the extreme right of your page.
Comment: I just applied text-right to the container and removed the div altogether.  However when the pull-right class is removed from the div with the images the div is no wider than the images (no space to the right).  If pull-right is applied then the div is wider than all the images.

bootstrap pull-right adding extra space


autocomplete field show name pass uid to form

Question: In my module I'd like to allow admin/moderator to add some user specific settings e.g. user steve1 has to work between 8am and 3pm.
To make work easier for the admin I'd lke to use autocomplete field for choosing user.
Suggestions are made via user name, but to form, I need to pass uid instead of a name.
Is this possible via modyfinig my autocomplete code, or should I change provided name to uid during form_submit operation?
$matches = array();
$query = db_select('users', 'u');

$return = $query
  ->fields('u', array(
    'uid',
    'name'
  ))
  ->condition('u.name', '%' . db_like($string) . '%', 'LIKE')
  ->range(0, 10)
  ->execute();

foreach ($return as $row) {
$matches[$row->name] = check_plain($row->name);
}

// return for JS
drupal_json_output($matches);

Answer: In your foreach you can add it
foreach ($return as $row) {
   $matches[$row->name . '[uid:' . $row->uid . ']'] = check_plain($row->name);
}

And in your submit handler you can find it with a simple preg_match like this one :
preg_match('/\[uid:(\d+)\]/', $form_state['values']['user_autocomplete'], $matches);
$uid = $matches[1];

Note that the $matches variable are not the same from the auto-complete part and the submit handler part.
Answer: http://drupal.org/node/1044286#comment-4062056 - that's much more complicated but also more flexible solution for passing more values with an autocomplete field.


Find range of $y=\sin{\sqrt{x+2}}$

Question: How can I find range of this function and draw it?
$y=\sin{\sqrt{x+2}}$
I found domain
$$x+2>=x$$
$$x>=-2$$
Comment: Well $\sqrt{x+2}$ is going to range over $\mathbb{R}_{\geq 0}$ so $\sin \mathbb{R}_{\geq 0}$ will range over $[-1, 1]$.
Comment: Range of is simply $[-1,1]$.
Comment: What is the range of sqrt(x+2), and if that range is then fed into the sin function then what will be the output?
Answer: The  Range of the sin function in the form $$C\sin(kx)$$ is simply:     $$[-C,C]$$  if your Domain is within the general form:                     $$[2n\pi,(2n+2)\pi], n\in \mathbb N$$ and since your domain satisfies the condition,       the range is :$$[-1,1]$$

Find range of $y=\sin{\sqrt{x+2}}$


Show that $\left. \frac{d}{dp}\right|_{p=1} \left[ \int f^p \, d\mu \right]^{1/p} =\int f \log(f) \, d\mu$

Question: The following is supposed to draw a connection between Lp norm and entropy: f is a probability density below:
$$\left. \frac{d}{dp}\right|_{p=1} \left[\int f^p \,d\mu\right]^{1/p} =\int f \log(f) \,d\mu$$
My derivation always reveals the LHS to be 0. What I did wrong?
$$\frac{d}{dp} \left[ \int f^p d\mu\right]^{1/p} = \left(\int f^p \, d\mu\right)^{1/p} \log \left(\int f^p \, d\mu\right) \cdot  \left(-p^{-2} \right) \cdot \int f^p \log(f) \, d\mu$$
which is $0$ when $p=1$ (since $\log\left(\int f^p \, d\mu\right)=\log1=0$).
Comment: I suspect that it should have $+\int f^p log(f)d\mu$ not $\cdot \int f^p log(f)d\mu$ in the derivative expression.
Comment: Check your application of leibniz integral rule
Comment: Isn't this just chain rule? I don't see why it is plus not multiplication.
Comment: I looked at Leibniz integral rule. I don't know what I did wrong.
Comment: I was being stupid but the advice above doesn't make much sense either.
Answer: Write $h(p)=\int f^pd\mu$. $h'(p)=\int f^p\log(f)d\mu.$
Then we have
$$\frac{d}{dp}(h(p)^{1/p})=\frac{d}{dp}(e^{\frac{\log(h(p))}{p}})=e^{\frac{\log(h(p))}{p}} \frac{\frac{p}{h(p)}h'(p)-\log(h(p))}{p^2}$$
When p=1, the above evaluates to
$$h'(1)=\int f^p \log(f)d\mu.$$


Internet not available in Windows Server 2008

Question: There is a Windows Server SP2 machine in my office and it is not a domain server. No internet connection is possible in it from today.
First of all, I checked windows server 2008 cannot connect to internet and https://stackoverflow.com/questions/26821620/having-internet-connectivity-issues-in-windows-server-2008-r2 . These are not my issue
This system used to loose internet connection previously and a restarting was enough to solve it. But today restarting, troubleshooting or whatever I tried didn't solved this issue.
I searched a lot in Google, but found nothing helpful. I did a 'ipconfig /all' and this was the result

In this image it is written 'Tap Windows Adapter V9'. What is that ?
This is 'Network and Sharing Centre'

As you can see there is a 'Local Area Connection 4'. When internet connection was available there was one more 'Local Area Connection'.
Also I did 'ping' with 188.8.131.52 and with my router.Both was 100 % loss.
I only know this much to describe, because am not much familiar with Server editions. If you found this question as a stupid one don't ignore. Help me first and then do down-vote or delete... Help please.... If you want to know any more ask me. I will reply what ever I know.
Comment: You have neither a valid IP address nor a default gateway.  This suggests a failure among the following:  network card, cable, switch, DHCP.  Check all of these.
Answer: You are getting an APIPA address (169.x.x.x), normally meaning that your DHCP server is unavailable and you are getting incorrect IP details
Normally for servers, you would assign them a static IP address
Also basic networking knowledge would also tell you that without a default gateway, you aint going to get out onto the internet.
Comment: Can you define it a little more ?
Answer: I think you have a problem with your network card, because your primary connection has "TAP-Windows Adapter V9" in description, which is usualy provided by openvpn for using a VPN.
Check your network card.
Try to uninstall any software you installed before you got this problem.


How would I prove that this is a linear transformation?

Question: Let $n$ be a positive integer and $Tr : R^
{n×n} → R$ denote the trace function on $n×n$ matrices
(i.e. the function that sums the diagonal entries of a matrix.)
How do I prove that $Tr$ is a linear transformation?
Answer: To prove that something is a linear transformation, you must show that it distributes across sums and scalar multiplication, i.e. show that $\text{Tr}(A+B) = \text{Tr}(A) + \text{Tr}(B)$ and $\text{Tr}(\lambda A) = \lambda\text{Tr}(A)$.
In each case, I recommend writing out some arbitrary matrices and showing what the trace does to each. I.e., take: $$A = \left[ \begin{array}{ccc}
a_{11} & \cdots & a_{1n} \\
\vdots & \ddots & \vdots \\
a_{n1} & \cdots & a_{nn}
\end{array}\right] \hspace{10pt}\text{and}\hspace{10pt} B = \left[ \begin{array}{ccc}
b_{11} & \cdots & b_{1n} \\
\vdots & \ddots & \vdots \\
b_{n1} & \cdots & b_{nn}
\end{array}\right]$$ and see what the trace of each individually is, the trace of the sum is, and the trace of a scalar multiple of one is, and show that the trace "factors out" of each of those operations.


How is delta method used here in approximating the square root of a normal random variable?

Question: I am reading this example where the distribution is given by $Y=\frac{\sigma^2\chi^2_{n-1}}{n-1}.$ By CLT, $Y\sim\mathcal{N}(\sigma^2,\frac{2\sigma^4}{n-1}).$ Up to here it was all clear to me.
Then my textbook said the sitribution of $2\sqrt{Y}$, using Delta Method, is approximately $\mathcal{N}(2\sigma,\frac{2\sigma^2}{n-1}).$
However I cannot seem to use Delta Method to get the aforementioned variance. I thought the statement maybe missing out a $n$ term? I thought the variance should be $\frac{2\sigma^2}{(n-1)n}$ because we have to divide by $n$ at the end when applying Delta Method?
Answer: The statement from the textbook is correct. If we define $f(y)=2\sqrt y$, we have $f'(y)=1/\sqrt y$. By the delta method, we approximate:
$$\begin{align}
\text{Var}(2\sqrt Y)&=f'(\mathbb E[Y])^2\cdot\text{Var(Y)}\\
&=\frac{1}{\sigma^2}\cdot\frac{2\sigma^4}{n-1}\\
&=\frac{2\sigma^2}{n-1}
\end{align}$$
Which agrees with the textbook result.


Conditional expectation of hierarchical model parameters via marginalisation

Question: Firstly apologies, I have fairly limited mathematical skills so there is a good chance that my question is simple or obvious.
I have a model in which I want to calculate the conditional expectation of the data given some higher-level model parameters, in order to gain an intuition on how the higher level parameters relate to the data. This would be done by marginalising out the intermediate parameters.
It was suggested to me to use nested iterated expectations to get to this point but I am having difficulty understanding exactly how to do this. Here is the model for clarity, though I am happy to deal with arbitrary distributions and (attempt to) work through the math myself. Here $X$ is a matrix of integers, $i\in\{1,\dots, q\}, j\in\{1,\dots,r\}$.
$$
X_{ij} \sim \text{Multinomial}(p_{\cdot j}) \\
p_{\cdot j} = (p_{ij}, \dots, p_{gj}) \sim \text{Dirichlet}(\alpha_{\cdot j}) \\
\alpha_{\cdot j} = (\alpha_i, \dots, \alpha_g) \\
\alpha_{ij} \sim \text{log-Normal}(\mu_i, \sigma^2_i)
$$
In this case I would like to know the form of $\mathbb{E}\left[X_{ij} | \mu_i, \sigma^2_i\right]$. The "obvious" or brute-force way to do this would (I think) be to write the joint distribution $\Pr(X_{ij}, p_{ij}, \alpha_{ij}, \mu_i, \sigma^2_i)$ and integrate $\mathrm{d}p$ $\mathrm{d}\alpha$ but this is likely intractable.
My understanding is that the nested iterated expectation approach would amount to evaluating
$$
\mathbb{E}\left[X_{ij}\right] = \mathbb{E}\left[\mathbb{E}\left[X_{ij}|p_{ij}\right]\right] \text{where} \\
\mathbb{E}\left[X_{ij}|p_{ij}\right] = \mathbb{E}\left[\mathbb{E}\left[p_{ij}|\alpha_{ij}\right]\right]
$$
...and so on. Is this a correct intuition for this approach? Alternatively, is there another way to approach the problem?
Comment: The Dirichlet Process/Chinese Restaurant Process may be of interest to you :)!
Comment: I am hoping to expand this model to a DM mixture model and CRP in time!
Answer: I received some guidance on this topic so I'd like to return and add an answer. Bear in mind I don't have a formal math/stats background so my notation is  likely to be a bit off.
I think that my intuition of the nested iteration approach was mostly correct (I thought this was too simple!). For this Dirichlet-Multinomial model, the nested iterated expection is as follows:
$$
\mathbb{E}[X_{ij}|\mu_i, \sigma_i] =  \mathbb{E}\left[\mathbb{E}[X_{ij}|p_{ij}]\right] \\
\text{where} \\
\mathbb{E}[X|p_{ij}] = \mathbb{E}\left[\mathbb{E}[p_{ij}|\alpha_{ij}]\right] \\
\text{where} \\
\mathbb{E}[p_{ij}|\alpha_{ij}] = \mathbb{E}\left[\mathbb{E}[\alpha_{ij}|\mu_i, \sigma_i]\right]
$$
The expectation of these distributions are closed form and widely known (eg Wikipedia).
$$
\mathbb{E}[X_{ij}|p_{ij}] = np_{ij} \ \text{where n is the sum of} \ X_j \\
\mathbb{E}[X_{ij}|\alpha_{ij}] = n\mathbb{E}[\alpha_{ij}] = n\frac{\alpha_{ij}}{\sum_{i=1}^q \alpha_{ij}}
$$
From here I would like to continue and plug in the expectation of the log-normal distribution, but it is not that easy in this case because we of course have dependence between the $\alpha_{ij}$s.
As noted in two recent papers (1 and 2), we can instead approximate this model. Since the marginal distribution of multinomial is binomial, we can approximate the model using a Poisson or negative binomial distribution for each $i$ as long as $q$ is large. When $q$ is small, I may have to return and attempt to solve this more formally.


Create chart for user count of user role using chart module(c3 lib) in Drupal 8?

Question: I want to use chart module(c3 lib) of drupal 8 to show a chart of user count for different roles using views.
E.g.
<code>Role Name  Total user
a             5
b             10
c             13
</code>
I achieved above table using aggregation in views. I followed this guideline to create a chart but when I create chart attachment and add it to parent, the value of child replace the value in the parent chart.It should merge.
Any help would be appreciable.
Answer: This is an issue of needing to be sure that you first set the format of the attachment display to "This chart attachment (override)", and then adjusting the format settings. Don't forget to attach your "Chart attachment" display to the appropriate display.
I wanted to set the style plugin to do this by default (see this issue: https://www.drupal.org/project/charts/issues/2899035), but I am unable to find any documentation on how to do this programmatically.


pyautogui is not working in ubuntu 18.04 . hotkeys not working outside the editor while it works inside the editor

Question: hello everyone i am using ubuntu 18 and python 3.6 but here is a bit of problem in pyautogui
it's writing and mouse functions are doing great but hotkeys got some problem
hotkeys are doing there jon inside the editor in my case it's pycharm but not outside the editor any kind of code for example:-
'ctrl' + 'alt' + 's' opens the settings in pycharm so the code
import pyautogui
pyautogui.hotkey("ctrl", "alt", "s")

works perfeclty
but code like
import pyautogui
pyautogui.hotkey("alt", "tab")

everyone knows what it does but it doesn't work
i've tried this also
import pyautogui
pyautogui.keyDown("alt")
pyautogui.press("tab")
pyautogui.keyUp("alt")

but same thing nothing happens
Answer: Ran into the same problem
Here's what worked for me :
pyautogui.keyDown('alt')
pyautogui.keyDown('tab')
pyautogui.keyUp('tab')
pyautogui.keyUp('alt')

Comment: this does seems to work so do you think the  problem is with press command?


If value is true update some columns, if not update anothers

Question: i will try to explain my "issue"
i have two tables
Table1
id      parent_id     name                  active
2008    10          name0                      Y
200801  2008        child of name0             Y
200802  2008        child of name0             Y
201102  10434344    child of name0             Y

Table2
old_id  new_id     name                active     id_father_new
2008    10         name0                  N           0
200801  202101    child of name0          N          2021
200802  202102    child of name0          N          2021
2011    10        new name0               Y           0
201101  201101    child of new name0      Y          2011
201102  10434344  child of name0          Y          2011
201102  201103  child of new name0        Y          2011

How u can see, the first table have some id, id_parent and active field.
The other one have the same columns and new information and new records to add in table1.
All new records in table2 was inserted in table1 with left join and now i need to do an update in table1 with the information in table2 but only if active field in table2 is Y updated  id, id_parent and active field, if active field is N in table2 just update active field in table1
So, table1 should be like this:
Table1
    id        parent_id     name             active
    2008         10         name0                 N
    200801      2008        child of name0        N
    200802      2008        child of name0        N
    201102      2011        child of name0        Y
    10434344    2011        child of name0        Y
    2011        10          new name0             Y
    201101      2011        child of new name0    Y
    201103      2011        child of new name0    Y

in the first three records only change active field to N because in table2 they were active = N
if i do this:
update u
        set u.id = s.new_id,
            u.parent_id = s.new_father_id,
            u.active = s.active
        from table1 u
        inner join table2 s on u.new_id = s.old_id
        where s.active like 'Y'

obviously only update rows with active = Y, and three first columns they remain with their same values, so its necessary make another update for field active:
update u
        set u.active = s.active
        from table1 u
        inner join table2 s on u.new_id = s.old_id

The biggest question is, ¿its possible to do this only with one update?, maybe with cursor ? CASE statement in set ? or just two updates its acceptable in good practices of sql
Thanks for your time
Comment: Can't you use a case-statement within your first update and leave away the where? Where is the problem? You proposed this already.
Comment: even though your OP is about the update but realistically there is an issue with your design.. hierarchical structure only needs 2 tables (well in this case)... one for names master and one for relationships...  then apply CTE parent-child to display the tree.... therefore updating these are done independently.
Comment: You should change `LIKE 'Y'` for `= 'Y'`
Comment: @Christian4145 yeah i know but i can't figure out how can do it
Comment: @maSTAShuFu exactly with cte i can view all the tree and managment table1 with out problems but the porpuse of the second table is not to lost old id's and id parents (requeriments of my work). i need them for update around 45 more tables (with no foreing keys or cascade (i dont designthat))
Answer: You could use IIF or a CASE statement and reassign the old value if the condition is not true.
update u
set u.id = IIF(s.active like 'Y', s.new_id, u.id),
    u.parent_id = IIF(s.active like 'Y', s.new_father_id, u.parent_id),
    u.active = s.active
from table1 u
inner join table2 s on u.new_id = s.old_id

Comment: this work, thanks i try to do that but with my 0 expertise i failed
Comment: @Carlos - glad to help and thank you for the clear question and your attempts to solve it.


Testes paralelos usando Selenium/TestNg e Banco de dados

Question: Tenho 1165 testes cases e isso ta demorando 36 horas para rodar + rodar isso tudo em 3 diferentes browsers e estou ficando louca com essa demora.
A minha dúvida é se tem como rodar testes paralelos usando selenium/testng sendo que suas classes precisam acessar o mesmo banco de dados?
Vou tentar explicar melhor.
Digamos que eu tenha a classe chamada TesteParaCartaoDeCredito, essa classe tem vários testes dentro que acessam o banco de dados, como por exemplo, criar novo cartão de credito, alterar os limites, bloquear cartão e por ai vai.
Hoje se eu tento rodar em paralelo, usando chrome e firefox por exemplo, meu segundo test case sempre falha, porque o primeiro browser já rodou o mesmo teste e já alterou isso lá no banco de dados (por exemplo o primeiro browser rodou o teste de bloquear o cartão e ai o segundo browser quando roda qualquer outro, falha).
Qualquer ideia é bem vinda.
Answer: No seu teste rondando em paralelo você consegue clonar a sua base? Caso positivo você poderia ter duas bases para rodar em paralelo. Nesse caso uma não iria interferir na outra porque estão apontando para bases diferentes


Putting checkboxes below an AChartEngine graph

Question: I would like to include some checkboxes below the graph, but have no idea how to do so. As it stands, the graph is sortav taking over the whole screen, so I suppose I should start by making it smaller, which I also don't know how to do.
This is what it currently looks like when I try to show the checkboxes:

Also, here is my current xml code for the layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ViewGraphActivity" >

<LinearLayout
    android:id="@+id/chart_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/tv_title"
    android:orientation="horizontal" >
</LinearLayout>

<LinearLayout
    android:id="@+id/checkbox_container"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/checkBoxTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="View which lines:" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="103dp"
        android:orientation="horizontal" >

        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Distance" />

        <CheckBox
            android:id="@+id/checkBox2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="28dp"
            android:text="Time" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="271dp"
        android:layout_height="34dp"
        android:layout_marginTop="34dp"
        android:orientation="horizontal" >

        <CheckBox
            android:id="@+id/checkBox3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Velocity" />

        <CheckBox
            android:id="@+id/checkBox4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="28dp"
            android:text="Calories" />
    </LinearLayout>
</LinearLayout>

Answer: For your checkbox_container:
android:layout_centerVertical="true" => android:layout_alignParentBottom="true"

Comment: Thank you for your help. I am assuming it worked because the check boxes aren't on the chart anymore, however they disappeared and I still have no idea how to make the chart a bit smaller to see if I can see the check boxes... =/
Comment: @theJuls Well that's rather easy too, you just set `android:layout_above="@+id/checkbox_container"` in your 'android:id="@+id/chart_container"' element.
Comment: Thanks it worked! It turns out I was doing the opposite: putting android:layout_belo="@+id/chart_container" on the checkbox_container. Not sure why this one works over ther other. No matter though, it works just fine now :)
Comment: It's possibly because the behavior of `wrap_content` for charts made them take up all the available space, which forced checkboxes off the screen. Since checkboxes have rather small, predictable height, you're now telling charts to make sure they consider whatever height checkboxes need, not vice versa, that's why it works.


Como aumentar tamanho de arquivo sql no phpMyAdmin?

Question: Como aumentar o tamanho do arquivos sql, para importação, no phpMyAdmin, do MAMP?
Comment: Não sei exatamente qual a finalidade da pergunta.
Mas muito tempo atrás eu tinha problemas com importação de arquivos grandes no MySQL (ficava corrompido).

Com base nisso recomendo o uso do programa Heidi SQL pra importação de dados. Ele executa o arquivo em partes o que evita muitos problemas.
Answer: Se entendi bem o que você quer fazer, você apenas precisará acessar o seu arquivo php.ini e alterar o valor da propriedade upload_max_filesize.
Comment: Já fiz isso, mas não adiantou.
Quando entro na pasta de configuração, ou bin, não lembro agora, existem várias pastas com versões diferentes do php. Eu entro na mais recente, 5.6.alguma coisa, acesso o php.ini e alterei. Achei estranho não ter mudado.


Steps to optimize an IIS server for PHP

Question: I've inherited a very slow PHP site running on IIS and I'm trying to maximize it's performance. The issue is all in the Time to First Byte (TTFB), with 1500ms TTFB for an almost empty page and an average of 2500ms TTFB on most pages. The Database Query times (the DB is hosted on another server) are acceptable and connection/download speeds are in the tens of ms at most; the speed of processing the PHP seems to be the only issue, it uses almost 100% of one core of the server's dual core CPU to serve a single page request.
It is currently running IIS 6.0, PHP 5.2.5 and Cake PHP 1.2, and I am working on bringing it up to IIS 7.0, PHP 5.3.6 and Cake 1.3.10, as well as installing a PHP caching component after I get the PHP version upgraded. PHPinfo() shows "server API" as ISAPI, we have Fast CGI installed, Fast CGI is preferred, correct?
Are there any other steps I should go through to ensure the server is running optimally for PHP? I want to ensure I'm getting the most out of the server before I attempt to run Apache along with IIS to run my PHP site instead (on the production server there are other sites residing on the same server).
Answer: You'll almost certainly get more bang for your buck out of unsucking the code; a bit of light profiling and optimisation from someone who knows what they're doing should get things under some sort of control (1500ms of a full core is a lot of CPU cycles).  Only once you've got some handle on how bad the code is should you start looking at the server -- there's a lot fewer places you can make a real mess of that (to the level of needing 1.5 seconds of CPU time to produce anything useful, anyway -- that's ridiculous).
Comment: The code isn't great but it seems CakePHP's calls are eating up most of the processing (a very simple session-driven page displaying a header and a few links takes 1.5s to load), there doesn't seem to be much TO optimize aside from Cake's core (it IS an old version). Regardless I'd like to make sure my environment is optimal before I start messing with the code. It's not mine so that's it's own challenge, and I'd like to be sure it's the problem before I start.
Comment: @sirtap: Just because it's Cake eating cycles, don't assume the problem is Cake's problem. More likely the code is doing something stupid with Cake. Also Cake. (Needed to say Cake one more time.)
Comment: Yeah, I doubt that everyone who uses CakePHP has a minimum of a 1.5 second page load time -- I doubt it'd get much use if it really was that inefficient.
Answer: You can try using Phalanger.
It is a PHP compiler for .Net, and as you are running a windows server with IIS, this seems to be the best option, as it will increase performance of the PHP application.
Answer: As others have said, the root problem is the inefficiency of how the application was built, so if you can fix that, do so.
Once that is out of the way, I have noticed notable performance increases after switching to IIS 7 with FastCGI and non-thread-safe PHP 5.3.  I think the bulk of the improvement is with FastCGI and NTS PHP 5.3, which is entirely possible and easy to do under IIS 6.
This has cut page processing times by about 40% for me.

Steps to optimize an IIS server for PHP


Restore button and end date from receipt for auto renewable IAP

Question: I am developing one commercial app (app having different tools to calculate) where I implemented auto-renewable subscriptions. I am able to test it properly.
How my app works:

App web services allow user to use app free for three months.
User is asked to get subscribe for an year to use tools.
Once payment is done, receipt is validate and stored at web services.
Once subscription period get collapsed, auto renewable subscription come to play.

My questions:

Is adding restore button is any way compulsory? Referring Is restore button necessary for Auto-renewable subscriptions?, it says restore button is not required in auto subscription.
After payment; receipt is been passed to web server and web server validate receipt. Is their any mechanism to get expiry date from receipt or with the help of receipt?

Thanks!
Answer: As per my knowledge on inapppurchase .. Auto-renewable subscription is acceptable for magazines ..like this only ... see the guidelines... I kept Auto-renewable for my app like webservices ...they reject my app and they suggest me to keep non-renewable subscriptions.. Now coming up to storing the receipt in your webserver .. how you can store your receipt in your webserver? based on the appleid we want to store the receipt .. but apple doesnot provide User appleid ...because all transactions is based on apple id only..i think storing the receipt is not the right way...You can keep Restore button to restore the previous transactions .. in these restore process you can get the previous transactions like product id and the transaction receipt .. you can pass this receipt to the storekit framework . then you will get the response 0 or 21006 like this based on the response you want to unlock the content...
Answer: For

query 1: Currently i am stock to
Is restore button necessary for Auto-renewable subscriptions?
solution.
and for query 2 i found that i can extract below details from
receipt:

NSString *kReceiptBundleIdentifier              = @"BundleIdentifier";
NSString *kReceiptBundleIdentifierData          = @"BundleIdentifierData";
NSString *kReceiptVersion                       = @"Version";
NSString *kReceiptOpaqueValue                   = @"OpaqueValue";
NSString *kReceiptHash                          = @"Hash";
NSString *kReceiptInApp                         = @"InApp";
NSString *kReceiptOriginalVersion               = @"OrigVer";
NSString *kReceiptExpirationDate                = @"ExpDate";
NSString *kReceiptInAppQuantity                 = @"Quantity";
NSString *kReceiptInAppProductIdentifier       = @"ProductIdentifier";
NSString *kReceiptInAppTransactionIdentifier   =
 @"TransactionIdentifier";
NSString *kReceiptInAppPurchaseDate                = @"PurchaseDate";
NSString *kReceiptInAppOriginalTransactionIdentifier   =
 @"OriginalTransactionIdentifier";
NSString *kReceiptInAppOriginalPurchaseDate        =
 @"OriginalPurchaseDate";
NSString *kReceiptInAppSubscriptionExpirationDate = @"SubExpDate";
NSString *kReceiptInAppCancellationDate         = @"CancelDate";
NSString *kReceiptInAppWebOrderLineItemID       = @"WebItemId";


How to calculate the sphere within an octahedron of six spheres?

Question: Apologies if you've already spent a lot of time answering this one but I've spent a lot of time looking for the answer here without success unfortunately.
If I bunch six spheres together to form an octahedron then how do I calculate the size of sphere that fits at the centre of those six spheres?
I assume the answer to be some expression of the size of spheres containing it?
Comment: Are the spheres all the same size?  If not, it's possible that the six spheres might not be able to form an octahedron, or the size of the inner sphere might be variable depending on how the spheres are arranged.
Answer: If the spheres are all the same size, then this isn't too hard to calculate.
Taking a cross section of a regular octahedron gives a square.  If $R$ and $r$ are the radii of the outer and inner spheres, respectively, then $2R + 2r$ equals the diagonal of this square, $R\sqrt2$.  Solving for $r$ yields
$$r = (\sqrt 2 - 1) R \approx 0.414 R.$$


Finding the values of $x$ where the series converges absolutely and conditionally

Question: So I have a question about the convergence of a series here:
It says:

Find the radius and interval of convergence, then identify the values of $x$ for which the series converges absolutely and conditionally
$\displaystyle \sum_{n=1}^{\infty} (\text{csch}(n))x^n$

I already found the radius of convergence. It's $e$. The interval of convergence is $(-e,e)$. I checked the endpoints and they both diverge.
So I know for all values of $x$ on the interval $(-e,e)$, the series converges absolutely. What about the conditional convergence though? How do I show that part? I'm a little confused on that. I don't even think that would ever happen.
Answer: The series is not convergent at $x=\pm e$ [ Note that $\frac {e^{n}} {e^{n}-e^{-n}}=\frac 1 {1-e^{-2n}}$ which does not tend to $0$ as $ n \to \infty$. A series $\sum a_n$ cannot converge (even conditionally) unless $a_n \to 0$.
Comment: No. It's definitely $(-e,e)$. You get $|\frac{1}{e}x|<1$ or $|x|0$. Then for $\sum  \cosh (n)x^{n}$ to converge both $\sum e^{n}x^{n}$ and $\sum e^{-n}x^{n}$ must converge. This requires both $ex$ and $\frac x e$ to be bounded by $1$. So we must have $x <\frac 1 e$.
Comment: But my sum isn't $\text{cosh}(x)$. It's $\text{csch(x)}$.
Comment: @FutureMathperson I have edited my answer.


How do you create an index for unique variables in sas?

Question: I am trying to combine the odds ratios outputted from two models with different adjustments in SAS:
i.e:
ods output oddsratios=adjustedOR1(rename=(OddsRatioEst=OR1);
 proc logistic data=dataname;
      model y= b d c a e; run;

ods output oddsratios=adjustedOR2 (rename=(OddsRatioEst=OR2);
 proc logistic data=dataname;
      model y= b d c; run;

proc sort.....
data Oddsratios (keep=Effect OR1 OR2);
merge adjustedOR1 adjustedOR2; by effect; run;

Problem is that if I sort and merge by the Effect variable, I lose the order in which I put the explanatory variables in the model.
Is there anyway to assign an index to the variable according to the order I put it in the model, so that the final table will have the effect column in the order: b d c a e?
Thanks for your help
Answer: I suggest creating a new sequence variable in your "primary" dataset with the sort order you want. then re-sorting the merged result by that variable:
data adjustedOR1;
   set adjustedOR1;
   sortkey = _n_;
run;
proc sort data=adjustedOR1;
   by effect;
run;
proc sort data=adjustedOR2;
   by effect;
run;
data Oddsratios (keep=Effect OR1 OR2 sortkey);
   merge adjustedOR1 adjustedOR2;
      by effect;
run;
proc sort data=Oddsratios;
  by sortkey;
run;

This would be a bit more generic than hard-coding the sort sequence as Keith suggests using PROC SQL (which also works by the way).
And thanks to Keith for providing a practical example!
Comment: Good answer Bob, I imagine it comes down to how many effects variables there are and in what further steps the data is used.  I always prefer to look at data rather than visualise it in my head, hence the example. (plus I know the solution I'm proposing works!)
Comment: Thanks Bob and Keith! I ended up using Bobs example as it was the quickest and because I had a mixture of continuous and categorical variables. But Keiths one would be good to modify for the macro I'm writing. Thanks again!
Answer: I think the easiest way to sort your data is to do the merge in Proc Sql and use a case statement in an 'order by' clause. Here is an example.
ods output oddsratios=adjustedOR1(rename=(OddsRatioEst=OR1));
 proc logistic data=sashelp.class;
      model sex= height age weight; run;

ods output oddsratios=adjustedOR2 (rename=(OddsRatioEst=OR2));
 proc logistic data=sashelp.class;
      model sex= height age; run;

proc sql;
create table Oddsratios as select
a.effect,
a.or1,
b.or2
from    adjustedOR1 as a
            left join
        adjustedOR2 as b
            on a.effect=b.effect
order by
    case a.effect
        when 'Height' then 1
        when 'Age' then 2
        when 'Weight' then 3
    end;
quit;

Answer: If you want to just change the order in which the variables appear in the data set, you can use the retain statement:
data Oddsratios (keep=Effect OR1 OR2);
 retain b d c a e;
 merge adjustedOR1 adjustedOR2;
 by effect;
run;

This isn't really what retain is for, but it works.
But I wonder why you care what the order of the variables in the data set is. You can specify the order when you display results with proc print, for example.
Comment: b,d,c,a,e are values of the variable 'Effect', rather than separate variable names.  I believe the question relates to custom sorting of a specific variable
Answer: Simplest answer I think that is still fairly flexible is to create an informat from your original dataset.  Then during the merge you can create a new variable with the numeric order variable and sort by that afterwards.
Another solution would be to merge in a fashion not requiring a sort - create a hash table, for example, or create a format out of the odds ratio 2 dataset and append it on in a simple data step rather than via merge.
data have;
input effect $;
datalines;
b
d
c
a
e
;;;;
run;

data for_format;
set have;
fmtname='EFF';
type='j';
hlo='s';
start=effect;
label=_n_;
keep hlo type fmtname start label;
run;

proc format cntlin=for_format;
quit;

proc sort data=have;
by effect;
run;

data want;
set have; *your merge here instead;
by effect;
eff_order=input(effect,$EFF.);
run;

proc sort data=want;
by eff_order;
run;
proc print data=want;
run;


Margens bugadas no CSS

Question: Estou tentando colocar uma borda numa imagem, mas o resultado é que a margem se estende por toda horizontal da página, como mostra no print.

A ideia é que a margem fique ao redor da imagem e de sua legenda...
No HTML:

Google Glass

Uma nova maneira de ver o mundo.

No CSS:
figure.foto-legenda {
    border: 8px solid white;
    box-shadow: 1px 1px 4px black;
}

O professor também instruiu a incluir o seguinte trecho, a fim de evitar que a margem se "desalinhe" à imagem ao redimensionar a janela do navegador:
figure.foto-legenda img {
    width: 100%;
    height: 100%;
}

Ao fazer isso, aparentemente a borda se encaixa direitinho, mas a imagem fica gigantesca...
P. S.: Eu já tentei remover os textos da legenda, mas o resultado foi o mesmo.
Comment: Importante você [edit] sua pergunta e explicar de maneira objetiva e pontual a dificuldade encontrada, acompanhada de um [mcve] do problema e tentativa de solução. Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Answer: Se entendi bem a pergunta, o que faltou aí foi vc declarar um tamanho máximo para o conteiner, ou seja, o lugar que os outros elementos irão se encaixar, que no caso aí é a tag figure. No caso do meu exemplo, a imagem que coloquei tem a largura (width) de 536px:

figure.foto-legenda {
  max-width: 536px;         /* seta o tamanho fixo */
  border: 8px solid white;
  box-shadow: 1px 1px 4px black;
}

figure.foto-legenda img {
  width: 100%;
  height: 100%;
}

Google Glass

Uma nova maneira de ver o mundo.

Comment: Bernardo, não sei dizer exatamente pois teria que ver os código, mas, tem uma grande possibilidade de este ser o motivo. Se não me engano o **HTML5** só foi lançado em 2014 oficialmente, acho eu, então provavelmente até o próprio HTML do curso aí seja uma versão inferior aos dos browsers atuais. Por isso, talvez, muitas das coisas que o professor mostra como fazer difere da maneira atual. A dica é sempre procurar fazer cursos mais atuais possíveis, pois, as tecnologias mudam muito rápido e evoluem muito de uma versão para outra!
Comment: A sua solução deu certo, muito obrigado; só fico curioso pelo motivo de que o professor não teve que fazer isso... Será que pode ser porque a aula é de 2013 e de lá pra cá mudou o funcionamento dessas propriedades ou algo assim?

Margens bugadas no CSS


Notation: $L_p$ vs $\ell_p$

Question: $L_p$ is often used to describe a norm, or a vector space with that norm  (see e.g. wikipedia).
Is $\ell_p$ (typically, or canonically) a different notation for the same concept, or is it used to indicate something different?
Comment: $\ell^p$ spaces are particular cases of $\mathbb{L}^p$ spaces. Usually, one uses $\ell^p$ when the underlying space is $\mathbb{Z}$ or $\mathbb{N}$, but I believe I've already seen such things as $\ell^p (\mathbb{Z}^n)$ (everything is done with the counting measure). Since it is a special case, there are a few properties that hold for $\ell^p$ spaces and not for general $\mathbb{L}^p$ spaces, such as $\ell^p \subset \ell^q$ if $p \leq q$.
Comment: Traditionally, $\ell^p$ is used when the norm involves a summation, while $L^p$ is used when the norm involves an integral.  Of course, in modern Lebesgue theory, a summation is a special case of an integral.
Answer: $\ell^p$ spaces are a special case of $L^p$ spaces.
If $(X,\mu)$ is a measure space, $L^p(X)$ (or $L^p_{\mathbb{R}}(X)$) is the (Banach) space of all measurable functions
 $f\colon X\to \mathbb{R}$ such that $$\int_X |f|^p\,d\mu\lt \infty.$$
In the special case in which $X=\mathbb{N}$ and $\mu$ is the counting measure, functions $f\colon\mathbb{N}\to\mathbb{R}$ can be taken to be sequences of elements of $\mathbb{R}$, and the integral is the sum of the terms of the sequence. That is, $L^p(\mathbb{N})$ is the set of sequences $(x_i)$ such that $\sum |x_i|^p\lt\infty$. To denote this special case, which occurs very often, we use $\ell^p$.
(You can replace $\mathbb{R}$ with any normed vector space, replacing the absolute value with the norm.)
Comment: @Joe: The $()^{1/p}$ is what you do in order to calculate the $p$-norm; but $f$ is in $L^p$ if and only if $\int |f|^p d\mu$ is finite. Similarly, the $p$-norm of a sequence in $\ell^p$ is $(\sum |x_i|^p)^{1/p}$, but whether a sequence is in $\ell^p$ or not is determined by looking at $\sum |x_i|^p$.
Comment: For L p space or l p space, I was wondering when to use subscript and when to use superscript? Why is that?
Comment: @Tim: One usually uses superscript, because it is mnemonic that the $p$ is the exponent in the condition, and because it leaves the subscript available to indicate the range of the functions.
Comment: Shouldn't there be a $()^{1/p}$ in there somewhere (e.g. the Euclidean norm)?
Comment: @ArturoMagidin: Thanks! I suspect there is some inconsistency in superscript or subscript in  your reply.
Comment: @Tim: Yes. I was following Joe's lead, but then was forced to go to the "usual" because I wanted the subscript for $\mathbb{R}$...
Comment: When dealing with a Vector Norm what should be used? See - https://math.meta.stackexchange.com/questions/27044.

Notation: $L_p$ vs $\ell_p$


Make Songs from Major Scale sound like Romany/Balkan/Hindi

Question: We are trying to make songs sound "gypsy". We tried using double harmonic scale, but we're not sure how are we gonna make the chords fit the scale. Most of the songs we play are on major scale.
Anyone here knows how should we change the chords to make it sound gypsy?
Comment: The trouble is that "gypsy jazz" is a term, while I've never heard of "Roma jazz".
Comment: @ToddWilcox Others embrace the term http://www.unionromani.org/union_in.htm `The UNION ROMANI is a non-profit, non-governmental organisation which is concerned with defending the gypsy community` or perhaps https://gypsycouncilusa.org/
Comment: The word "gypsy" is offensive to many Roma people. Perhaps you can re-word this question to eliminate the word?
Answer: The common way to create chords that fit the scale is simply to stack thirds above each scale pitch using only pitches from the scale.
In other words, let's say you're using the double harmonic scale based on C:

Let's just use those seven pitches to create triadic structures above each scale tone:

Playing around with these chords should automatically start to create the effect you're seeking.

But perhaps more importantly, you'll want to mimic Eastern progressions and melodic tropes in order to really get the sound you're looking for. A V–I progression won't really work with this scale, since the V triad isn't even a triad (nor is the vii chord). Instead you'll want to use something like ♭II–I at cadences (in this case, D♭ major moving to C major), which is a really common phrase ending in this style of music.
In addition to the V and vii chords not being true triads, you may want to stay away from the augmented ♭VI chord. As such, try initially limiting yourself to just I, ♭II, iii, and iv—C, D♭, Em, and Fm—and see if you're on the right track.
Comment: Does this mean, if I have a chord progression like, C - G - Am - F, to follow the double harmonic scale, I'll play it as, C - G (with no fifth) - Ab+ - Fm? Or do I have to change the chord progression and possibly all the chords?
Comment: If you want to modify a major chord progression to fit into this double harmonic scale, then yes, that's what you would do. But that doesn't necessarily mean that the resulting sound will be what you're looking for. You'll want to look for typical chord progressions in that style (like the `♭II–I` that I mentioned) and try and work with those.


How to modify Card-IO manual entry screen

Question: I want to modify Card.IO manual entry screen and place a button on that screen.
Is it possible to do so?
Answer: Dave from card.io here.
The source code to card.io is available (Android repo, iOS repo). So you are welcome to fork the relevant repo and make any changes you desire.
Comment: I see there is MIT license involved. Is it safe in terms of Legal issues to modify the code and using it for Commercial Purpose?

Also Could you please let me know I need to include whole source repo in my project to do any modification or can I include selective files in my project and change it.


Definition of finite-by-nilpotent

Question: In group theory what are definitions of:

finite-by-nilpotent,
nilpotent-by-finite,
abelian-by-finite,
or in general: *-by- *?
Comment: I really cannot imagine why this question was closed! What are the "many possible answers"?
Comment: In what context have you encountered these expressions?
Comment: @MarkBennet on a paper about finite conjugacy groups.
Answer: A group $G$ is called X-by-Y if it has a normal subgroup $N$ that belongs to the class X and the quotient $G/N$ belongs to the class Y.
Comment: But unfortunately many authors use the opposite convention, i.e. a normal subgroup $N$ in $Y$ with $G/N$ in $X$. This means that when anyone you don't know refers for example to a nilpotent-by-abelian group, then you have to ask them which convention they are using, because it really could be either.

Definition of finite-by-nilpotent


Remove [NOT FOR REPLICATION] from all Identity columns of Database tables

Question: I have a Database which is containing lot of tables with Identity columns set to [NOT FOR REPLICATION]. in SQL Server 2008 R2
Is there any way that I can remove this constraint from all tables from Management Studio or any Query thanks.
Create Table mytbl (
[EmpId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,

I tried this but it is removing one by one.
ALTER TABLE dbo.tblAttendance ALTER COLUMN Id
         DROP NOT FOR REPLICATION;

Answer: Microsoft provides a system stored procedure to turn on and off the NOT FOR REPLICATION setting.  The stored procedure is sys.sp_identitycolumnforreplication.  We can use this system stored procedure along with sp_msforeachtable to remove the NOT FOR REPLICATION setting from all tables:
EXEC sp_msforeachtable @command1 = '
declare @int int
set @int =object_id("?")
EXEC sys.sp_identitycolumnforreplication @int, 0'

Comment: Thanks. In my case the above did not solve the problem,this command will remove replication from database tables if replicated database was copied and attached. I solved my problem by going in Management Studio >Replication>Local Publications node and uncheck the replication from my database.
Comment: Thanks - this removes `NOT FOR REPLICATION` on my local db, but does not work on the Azure db. Any idea how?
Comment: By 'Does not work' I guess you get an error about `sp_msforeachtable`? I suggest you generate a script that creates a list of the required `EXEC sys.sp_identitycolumnforreplication @int, 0` statements.
Answer: I found that sys.sp_identitycolumnforreplication didn't work in my Ent. SQL 2008R2 or SQL 2012 instances (wil test in 2016 next).  This little snippet worked for me.  Set @debug as you see fit, to either run it, or copy-paste-run.
set nocount on
declare @loop int = 1, @debug bit = 1, @schema sysname, @table sysname, @column sysname, @status int, @sqlStatement nvarchar(1000)
declare repl_cursor cursor for
SELECT
      [schema] = object_schema_name([object_id])
    , [table] = object_name([object_id])
    , [column] = [name]
    , IsIdNotForRepl = COLUMNPROPERTY([object_id], [name], 'IsIdNotForRepl')
    , [--script] = 'alter table [' + object_schema_name([object_id]) + '].[' + object_name([object_id]) + '] alter column [' + [name] + '] DROP NOT FOR REPLICATION'
FROM sys.columns
        WHERE 1=1
        and COLUMNPROPERTY([object_id], [name], 'IsIdNotForRepl') = 1
        and object_schema_name([object_id]) <> 'sys'
order by 1,2

open repl_cursor
fetch next from repl_cursor into @schema, @table, @column, @status, @sqlStatement
WHILE @@FETCH_STATUS = 0
BEGIN
    print '--loop: ' + cast(@loop as varchar(3)) + '; table: [' + @schema + '].[' + @table + '].[' + @column + ']; status = ' + case when isnull(@status,3) = 3 then 'NULL' else cast(@status as varchar(2)) end
    print @sqlStatement + char(10)

    if @debug = 0 exec(@sqlStatement)

    FETCH NEXT FROM repl_cursor into @schema, @table, @column, @status, @sqlStatement
    set @loop +=1
END

close repl_cursor
deallocate repl_cursor
go

Comment: this works for all versions of SQL server and should be the best answer. Thanks for the script Abelian
Comment: Perhaps your compatibility level was too old?
Comment: This is the best answer on this page


Latent growth curve model: The variance-covariance matrix of the estimated parameters (vcov) does not appear to be positive definite

Question: I have run a latent growth curve model in R using lavaan and got the below warning. It would be good to hear suggestions on how to resolve this warning. The full output is below.
Note that I dummy-coded one covariate (i.e., employment). However, removing one of the dummy coded variables (i.e., FTvUN_w0) seems to lead to the error disappearing. However, I would like to avoid this 1) for consistency; as I have several other models where I have it included, and 2) for completeness; so all levels of the dummy coded variable are included.
Warning in lav_model_vcov(lavmodel = lavmodel, lavsamplestats = lavsamplestats,  :
  lavaan WARNING:
    The variance-covariance matrix of the estimated parameters (vcov)
    does not appear to be positive definite! The smallest eigenvalue
    (= 1.563215e-16) is close to zero. This may be a symptom that the
    model is not identified.

Below is the lavaan output:
lavaan 0.6.14 ended normally after 176 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        37

  Number of observations                           423
  Number of missing patterns                         1

Model Test User Model:
                                              Standard      Scaled
  Test Statistic                                36.265      38.407
  Degrees of freedom                                33          33
  P-value (Chi-square)                           0.319       0.238
  Scaling correction factor                                  0.944
    Yuan-Bentler correction (Mplus variant)

Model Test Baseline Model:

  Test statistic                               262.614     270.880
  Degrees of freedom                                62          62
  P-value                                        0.000       0.000
  Scaling correction factor                                  0.969

User Model versus Baseline Model:

  Comparative Fit Index (CFI)                    0.984       0.974
  Tucker-Lewis Index (TLI)                       0.969       0.951

  Robust Comparative Fit Index (CFI)                         0.975
  Robust Tucker-Lewis Index (TLI)                            0.953

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)              -2079.951   -2079.951
  Scaling correction factor                                  1.020
      for the MLR correction
  Loglikelihood unrestricted model (H1)      -2061.819   -2061.819
  Scaling correction factor                                  0.984
      for the MLR correction

  Akaike (AIC)                                4233.902    4233.902
  Bayesian (BIC)                              4383.655    4383.655
  Sample-size adjusted Bayesian (SABIC)       4266.241    4266.241

Root Mean Square Error of Approximation:

  RMSEA                                          0.015       0.020
  90 Percent confidence interval - lower         0.000       0.000
  90 Percent confidence interval - upper         0.040       0.043
  P-value H_0: RMSEA <= 0.050                    0.995       0.988
  P-value H_0: RMSEA >= 0.080                    0.000       0.000

  Robust RMSEA                                               0.019
  90 Percent confidence interval - lower                     0.000
  90 Percent confidence interval - upper                     0.041
  P-value H_0: Robust RMSEA <= 0.050                         0.993
  P-value H_0: Robust RMSEA >= 0.080                         0.000

Standardized Root Mean Square Residual:

  SRMR                                           0.019       0.019

Parameter Estimates:

  Standard errors                             Sandwich
  Information bread                           Observed
  Observed information based on                Hessian

Latent Variables:
                   Estimate  Std.Err  z-value  P(>|z|)
  i =~
    PAL_w0            1.000
    PAL_w1            1.000
    PAL_w2            1.000
    PAL_w3            1.000
  s =~
    PAL_w0            0.000
    PAL_w1            1.000
    PAL_w2            2.000
    PAL_w3            3.000

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  i ~
    RTL_pcn_log_z     0.017    0.040    0.423    0.672
    pc1               3.151    3.579    0.880    0.379
    pc2              -2.436    3.515   -0.693    0.488
    pc3               1.787    3.701    0.483    0.629
    pc4               1.627    3.634    0.448    0.654
    pc5               0.219    3.866    0.057    0.955
    pc6              -3.702    4.061   -0.912    0.362
    AGE_w0           -0.044    0.009   -4.730    0.000
    SEX_w0            0.046    0.085    0.539    0.590
    EDU_w0           -0.002    0.031   -0.066    0.947
    FTvRE_w0         -0.048    0.153   -0.318    0.751
    FTvPT_w0         -0.049    0.214   -0.228    0.819
    FTvSE_w0          0.097    0.230    0.422    0.673
    FTvUN_w0          0.047    0.659    0.071    0.943
  s ~
    RTL_pcn_log_z    -0.006    0.017   -0.361    0.718
    pc1              -1.462    1.521   -0.961    0.336
    pc2               1.282    1.781    0.720    0.471
    pc3              -1.175    1.831   -0.642    0.521
    pc4              -1.675    1.522   -1.101    0.271
    pc5               0.168    1.342    0.125    0.901
    pc6              -0.011    1.624   -0.007    0.995
    AGE_w0            0.002    0.004    0.538    0.591
    SEX_w0           -0.022    0.035   -0.638    0.524
    EDU_w0            0.005    0.014    0.342    0.732
    FTvRE_w0         -0.085    0.084   -1.015    0.310
    FTvPT_w0         -0.041    0.102   -0.400    0.689
    FTvSE_w0         -0.148    0.107   -1.381    0.167
    FTvUN_w0         -0.154    0.222   -0.695    0.487

Covariances:
                   Estimate  Std.Err  z-value  P(>|z|)
 .i ~~
   .s                -0.030    0.021   -1.442    0.149

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .PAL_w0            0.000
   .PAL_w1            0.000
   .PAL_w2            0.000
   .PAL_w3            0.000
   .i                 7.482    0.677   11.045    0.000
   .s                -0.009    0.298   -0.031    0.975

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .PAL_w0            0.553    0.069    7.982    0.000
   .PAL_w1            0.575    0.044   13.194    0.000
   .PAL_w2            0.503    0.040   12.676    0.000
   .PAL_w3            0.442    0.053    8.320    0.000
   .i                 0.239    0.054    4.449    0.000
   .s                 0.022    0.012    1.861    0.063

Thanks in advance for any help!
Answer: There's nothing obvious in the output that suggests that you did something wrong.
(It's sort of interesting that your scaled chi-square is higher than your unscaled chi-square, this is pretty unusual, but not a problem.)
Lavaan is warning you that your model might be unidentified. It's not sure, and there's no real way for lavaan to know.
The way to find out is to run the model with a few different sets of starting values. If it converges to the same solution, it's probably identified, if ti doesn't, then it's not identified.
(This is not a lavaan specific problem, so I have edited the question to make it more general, and therefore suitable for CrossValidated.)
Note: You can also run this model as a mixed model using lme4::lmer(), it might be worth trying that to see if you get the same result or warning.
Comment: Yes, that also seems a likely reason (or even the combination of both).
Comment: Thank you very much, Jeremy! Can I just check whether it could have something to do with the fact that I have predictors of the slope when the slope variance is not significant?
Comment: Ah, interesting. Yes, I didn't notice that. It might be. Significance of slope variance is a weird thing because significance is asking if the variance is larger than zero. The variance can't be less than zero, and it would be pretty weird for it to be zero.
Comment: I'm now thinking it's due to the low number of participants in the dummy coded group "FTvUN_w0" (i.e., 2 people or 0.47%)- does this sound plausible?

This would explain why removing it prevents the error, although perhaps this is not advisable for dummy coded variables (as then these two participants would be assumed to be in the reference category by the model?).

Thanks again!