Erro de troca de imagens no botão dropdown

Question: Olá.
Tenho um menu dropdown (bootstrap 3.3.7) que possui duas imagens que a troca delas é feita via css.
Quando o menu está ativo o botão módulo não deveria ficar cinza e sim branco.

Essa abaixo está correta.

HTML com PHP que chama o menu

/* Início Botão Módulos */
  .BotaoModulos
{
  background-image: url('../img/icones/new2/modulos_out.png');
  text-align: center;
  display: inline-block;
  background-position: center center;
  background-size: cover;
  width: 40px !important;
  height: 40px !important;
  color: #8B92B1 !important;
  font-size: 12px !important;
  font-family:sans-serif !important;
}
.BotaoModulos li img
{
  display: block;
}
.BotaoModulos:hover
{
  background-image: url('../img/icones/new2/modulos_in.png');
  background-position: center center;
  background-size: cover;
  width: 40px;
  height: 40px;
  color: #fff !important;
  font-size: 12px !important;
  font-family:sans-serif !important;
}
/* Fim Botão Módulos */

.LinkFav1_PF
{
  margin: 0 auto;
  background: #fff;
  width: 90px;
  height: 75px;
  padding-top: 10px;
  padding-right: 15px;
  color: #8B92B1 !important;
}

.LinkFav1_PF:hover
{
  background: rgba(249, 166, 74, 1);
  /*top: -1px;
  padding-top: 1px; */
  color: #fff !important;
  width: 90px;
  height: 75px;
}
.LinkFav1_PF:active ul li
{
  color: #fff;
}

.MenuInfFav
{
  position: relative;
  margin: 0 auto;
  width: 1000px;
  height: 38px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

teste

  Módulos

            <?php echo $this->Html->link(__('List Users'), ['controller' => 'Users', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List UsersProfiles'), ['controller' => 'UsersProfiles', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Profiles'), ['controller' => 'Profiles', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Models'), ['controller' => 'Models', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Groups'), ['controller' => 'Groups', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Maintainers'), ['controller' => 'Maintainers', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Institutions'), ['controller' => 'Institutions', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Campuses'), ['controller' => 'Campuses', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Courses'), ['controller' => 'Courses', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Semesters'), ['controller' => 'Semesters', 'action' => 'index']) ?>

            <?php echo $this->Html->link(__('List Financing Plans'), ['controller' => 'FinancingPlans', 'action' => 'index']) ?>

Answer: Uma solução CSS é utilizar o  estado "focus", ficando assim:
.BotaoModulos:hover, .BotaoModulos:focus
{
  background-image: url('../img/icones/new2/modulos_in.png');
  background-position: center center;
  background-size: cover;
  width: 40px;
  height: 40px;
  color: #fff !important;
  font-size: 12px !important;
  font-family:sans-serif !important;
}

Único problema é que quando vc clicar fora, ele perderá o estado "focus", aí teria que utilizar Javascript pra adicionar/remover uma classe no click, porém como vc está usando o Bootstrap, se não me engano, o dropdown fecha quando clica fora, então deve servir..
Comment: Fiz isso mas não consegui.
Como seria essa questão do js que vc disse?


Vuforia load White Rectangle instead of Video

Question: I have a problem with the app I'm building in Unity. I am using Vuforia to detect an image and to overlay it with a video. It works on the Unity editor, but when I use it on my android, it still detects the image but instead of the video it appears a white rectangle.
Does anyone know how to solve this? Thank you!
Comment: can you add more details , ho do you read video ? are u reading it from Application.PersistanceDatapath ?
Answer: The format .mov wasn't working. I changed it to .mp4 and it worked!


javascript access class method without initializing object

Question: I have a class foo, can I access its public method bar with out initializing fooObj
var foo = function(){
   this.bar = function(){
       console.log("I am bar");
   }
}

I know I can access bar like
var fooObj = new foo();
fooObj.bar();

In other object oriented language like javeif I declare bar static I can access it with class name like foo.bar
Comment: Do not think in terms of "classes". Javascript doesn't have those. It's all just objects with properties.
Answer: There is no static concept like Java but you can do something like
var foo = function(){
   // Constructor specific code
}

foo.bar = function(){
    console.log("I am bar");
}

This is how singleton will be defined in JavaScript
Comment: If you add it to prototype, it should work when you instantiate an object and call the method present in it.
Comment: @ Vigneswaran Marimuthu I didn't get what  I wanted as, deceze said Do not think in terms of "classes". Javascript doesn't have those. It's all just objects with properties.
Comment: @ozil What he meant is there is no concept of classes like in `Java`. If you see JavaScript you can see concepts like functions, objects and properties. Constructors are created using functions not classes in JavaScript. Though ES6 have classes concept but it's relatively new - http://javascriptplayground.com/blog/2014/07/introduction-to-es6-classes-tutorial/


Laravel resource index listing limited amount of records

Question: I have two resources

Organizations

OrganizationUsers (which has FK to Users on user_id)

The User model
class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'picture' ,'role_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Get the role of the user
     *
     * @return \App\Role
     */
    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    /**
     * Get the path to the profile picture
     *
     * @return string
     */
    public function profilePicture()
    {
        if ($this->picture) {
            return "/{$this->picture}";
        }

        return 'http://i.pravatar.cc/200';
    }

    /**
     * Check if the user has admin role
     *
     * @return boolean
     */
    public function isAdmin()
    {
        return $this->role_id == 1;
    }

    /**
     * Check if the user has creator role
     *
     * @return boolean
     */
    public function isCreator()
    {
        return $this->role_id == 2;
    }

    /**
     * Check if the user has user role
     *
     * @return boolean
     */
    public function isMember()
    {
        return $this->role_id == 3;
    }

    /**
     * The organization_user that belong to the user.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function organizations()
    {
        return $this->belongsToMany(OrganizationUser::class);
    }
}

, the Organization model is
class Organization extends Model
{
    protected $fillable = [
        'user_id', 'name' , 'slug', 'is_visible'
    ];

    /**
     * Get the user owner of the organization
     *
     * @return \App\User
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

and the OrganizationUser model is
class OrganizationUser extends Model
{
    protected $fillable = [
        'user_id', 'organization_id', 'is_admin', 'name'
    ];

    /**
     * Get the user
     *
     * @return \App\User
     */
    public function user()
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * Get the organization
     *
     * @return \Organization
     */
    public function organization()
    {
        return $this->belongsTo(Organization::class);
    }

    /**
     * Check if the user is_admin
     *
     * @return boolean
     */
    public function isAdmin()
    {
        return $this->is_admin == 1;
    }

}

When it comes to access these resources
Route::resource('organization', 'OrganizationController');
Route::resource('organizationuser', 'OrganizationUserController', ['except' => ['show']]);

Also, this is the index() of the OrganizationController
class OrganizationController extends Controller
{
    /**
     * Display a listing of the organizations
     *
     * @param \App\Organization  $model
     * @return \Illuminate\View\View
     */
    public function index(Organization $model)
    {
        $this->authorize('manage-users', User::class);

        return view('organizations.index', ['organizations' => $model->all()]);
    }

    ...
}

and the navigation
@can('manage-organizations', App\User::class)

                        {{ __('Organizations') }}

                @endcan

Instead of seeing all of Organizations when going to the index of that resource, I'd like it to list all Organizations where the authenticated user is one of the OrganizationUsers.
How can that be done?
This question has similarities with this one but it's with a different take.
Comment: can you please post  an example of what your Models and resources look like?
Comment: @ccarstens just included that info
Answer: If I know you true, you can use this:
$result = Organization::whereIn('id', function($query){
    $query->select('organization_id')
    ->from(with(new OrganizationUser)->getTable())
    ->where('user_id', Auth::user()->id);
})->get();
// now your result is in $result

But for more accurate response you should explain problem in details.
Comment: @TiagoMartinsPeres李大仁 Do you check my answer? Isn't what you want?
Comment: Where you'd place it in the question snippets?
Comment: you can use my code in each controller you want. you should `use` `Organization` and `OrganizationUser` at top of the controller class.
My code return your result. you can put it in a variable e.g `$result`


Create projects in Azure DevOps - permissions amendment?

Question: In Azure DevOps we've got a number of Project Collection Administrators but they're seeing more projects than they need to - it's almost as though they should be standard users but with permissions to create projects.
Is there a way to set up a group so that people can only see the projects they need and have the ability to create new projects too?
Answer: To create a project, you must be a member of the Project Collection Administrators group or have the Create new projects permission set to Allow. Please refer to this document.
So there is no need to add users to the PCA permission group, just give them the "create new projects" permission.

Then on the Manage user page, you can manage which projects the user can access.


Overwrite properties with MSBuild

Question: I want to declare three properties in my MSBuild file and overwrite one property with the value of another (depending on the target being called), but can't figure out how to do this.  My build file looks something like this:
<PropertyGroup>
   <DeployPath_TEST>\\test-server-path\websites\mysite</DeployPath_TEST>
   <DeployPath_LIVE>\\live-server-path\websites\mysite</DeployPath_LIVE>
   <DeployPath></DeployPath>
</PropertyGroup>

<Target Name="Deploy-TEST">
   <PropertyGroup>
      <DeployPath>$(DeployPath_TEST)</DeployPath>
   </PropertyGroup>
   <CallTarget Targets="Deploy-Sub"/>
</Target>

<Target Name="Deploy-LIVE">
   <PropertyGroup>
      <DeployPath>$(DeployPath_TEST)</DeployPath>
   </PropertyGroup>
   <CallTarget Targets="Deploy-Sub"/>
</Target>

<Target Name="Deploy-Sub">
   <Message Text="Deploying to $(DeployPath)"/>
   <MSBuild Projects="MySolution.csproj" Targets="Rebuild" />

   <ItemGroup>
     <MyFiles Include="**\*"/>
   </ItemGroup>

   <Copy SourceFiles="@(MyFiles)"
         DestinationFiles="@(MyFiles->'$(DeploymentPath)\%(RecursiveDir)%(FileName)%(Extension)')"/>

</Target>

At the moment I'm trying to re-declare the property setting it's value accordingly, but this isn't working.
Answer: Mehmet is right about how to set a property value from another property, but there is a bug/feature in MSBuild which means that if you call CreateProperty and CallTarget in the same Target, your new property will not be globally available to other targets (described here).
So here is the final solution to the problem:
<PropertyGroup>
   <DeployPath_TEST>\\test-server-path\websites\mysite</DeployPath_TEST>
   <DeployPath_LIVE>\\live-server-path\websites\mysite</DeployPath_LIVE>
   <DeployPath></DeployPath>
</PropertyGroup>

<Target Name="SetDeployPath-TEST">
  <CreateProperty Value="$(DeployPath_TEST)">
    <Output TaskParameter="Value" PropertyName="DeployPath"/>
  </CreateProperty>
</Target>

<Target Name="Deploy-TEST">
   <CallTarget Targets="SetDeployPath-TEST"/>
   <CallTarget Targets="Deploy-Sub"/>
</Target>

<Target Name="Deploy-Sub">
  <Message Text="Deploying to $(DeployPath)"/>
  <MSBuild Projects="MySolution.csproj" Targets="Rebuild" />

  <ItemGroup>
    <MyFiles Include="**\*"/>
  </ItemGroup>

  <Copy SourceFiles="@(MyFiles)"
     DestinationFiles="@(MyFiles->'$(DeploymentPath)\%(RecursiveDir)%(FileName)%(Extension)')"/>

</Target>

Comment: Thank you, that was usefull. I am still somewhat new to batching and MS doesn't do a good job explaining related concepts in my opinion. One more note. I actually got away without creating a global property; that narrows the context a bit so it is easier to read the code: Target A calls targets B and C. B sets a list property and C does batching on the value of that property. as mdresser noted setting the property in the same target did not work. Hope it helps someone; I've spent 3-4 hours trying to understand this before I found this post.
Comment: One more point, you say you get notification that only Cat has changed, have you tried to save the changes? Does it work? (I doubt it)
Answer: You can use CreateProperty task to overwrite the value of an existing property.
<Target Name="Deploy-LIVE">
  <CreateProperty Value="$(DeployPath_LIVE)">
    <Output PropertyName="DeployPath" TaskParameter="Value"/>
  </CreateProperty>
  <CallTarget Targets="Deploy-Sub"/>
</Target>

Comment: Haa, just found this article http://weblogs.asp.net/bhouse/archive/2006/03/20/440648.aspx describing a bug/feature with the CreateProperty task.
Comment: This doesn't seem to work for me. I can use the value of the DeployPath property immediately after the CreateProperty block, but it looses it's value within the Deploy-Sub target.
Comment: Interesting I did not know about this bug. I used CreateProperty before but apparently nothing needed to access the overwritten property outside of the target that overwrote it. Thanks.
Answer: I typically avoid the CallTarget task. Much better is to use target dependencies.
Comment: @HaymoKutschbach because of this bug http://sedodream.com/PermaLink,guid,dd6cb1db-c0e4-47f7-ad84-6e59ff6b03d0.aspx and I think CallTarget goes against the mental model of how msbuild should be used. MSBuild is declarative, CallTarget is very imperative. With that said there are some cases when its needed, but u should prefer DependsOn before CallTarget.
Comment: Could you elaborate a little? Why is it better for you?
Comment: Thanks! I agree and it seems the msbuild team encourages DependsOn as well for enabling properties to be set globally in imported projects.
Answer: Besides, you can use following way:
<PropertyGroup>
   <DeployPath_TEST>\\test-server-path\websites\mysite</DeployPath_TEST>
   <DeployPath_LIVE>\\live-server-path\websites\mysite</DeployPath_LIVE>
   <DeployPath></DeployPath>
</PropertyGroup>

<Target Name="SetDeployPath-TEST">
  <CreateProperty Value="$(DeployPath_TEST)">
    <Output TaskParameter="Value" PropertyName="DeployPath"/>
  </CreateProperty>
</Target>

<Target Name="Deploy-Sub" DependsOnTargets="SetDeployPath-TEST">
  <Message Text="Deploying to $(DeployPath)"/>
  <MSBuild Projects="MySolution.csproj" Targets="Rebuild" />

  <ItemGroup>
    <MyFiles Include="**\*"/>
  </ItemGroup>

  <Copy SourceFiles="@(MyFiles)"
     DestinationFiles="@(MyFiles->'$(DeploymentPath)\%(RecursiveDir)%(FileName)%(Extension)')"/>

</Target>

Overwrite properties with MSBuild


Corda Upgradation to V4.6

Question: I am implementing a use case where I upgraded cordapp from V4.5 OS to V4.6 OS. But when I using Corda V4.6 with custom schema on PostgreSQL.
I am facing the issue with the Custom Vault Query, getting errors with the below piece of code.
Sample Code:
FieldInfo attribute1 = null;
            try {
                attribute1 = getField("attributeInCordaSchema", AttributeSchema.PersistentAttribute.class);
            }catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            final String attributeFromService = (String) inputMapObj.get("attribute");
            QueryCriteria generalCriteria = new QueryCriteria.VaultQueryCriteria(Vault.StateStatus.ALL);
            QueryCriteria attribute1Criteria = new QueryCriteria.VaultCustomQueryCriteria(Builder.equal(attribute1, attributeFromService));
            QueryCriteria criteria = generalCriteria.and(attribute1Criteria);
            Vault.Page<OurState> results = getServiceHub().getVaultService().queryBy(OurState.class, criteria);
            List<StateAndRef<OurState>> matchingStates = results.getStates();

ERROR:
net.corda.core.node.services.VaultQueryException: An error occurred while attempting to query the vault: org.hibernate.exception.SQLGrammarException: could not extract ResultSet at net.corda.node.services.vault.NodeVaultService._queryBy(NodeVaultService.kt:646) ~[corda-node-4.6.jar:?]
    at net.corda.core.node.services.VaultService$DefaultImpls.queryBy(VaultService.kt:436) ~[corda-core-4.6.jar:?]
    at net.corda.node.services.api.VaultServiceInternal$DefaultImpls.queryBy(VaultServiceInternal.kt) ~[corda-node-4.6.jar:?]
    at net.corda.node.services.vault.NodeVaultService.queryBy(NodeVaultService.kt:54) ~[corda-node-4.6.jar:?]

Is the way of custom querying the vault has changed?
Answer: While I don't have your exact state on hand, I can try to give an example for 4.6.
As far as I know it hasn't changed, here's my go to example for a vault query using corda 4.6 from the obligation cordapp.
I like to query by the classname personally as that makes things a little simpler for me.
            List<UUID> listOfLinearIds = Arrays.asList(stateLinearId.getId());
            QueryCriteria queryCriteria = new QueryCriteria.LinearStateQueryCriteria(null, listOfLinearIds);
            Vault.Page results = getServiceHub().getVaultService().queryBy(IOUState.class, queryCriteria);
            StateAndRef inputStateAndRefToSettle = (StateAndRef) results.getStates().get(0);
            IOUState inputStateToSettle = (IOUState) ((StateAndRef) results.getStates().get(0)).getState().getData();

source cordapp: https://github.com/corda/samples-java/blob/master/Advanced/obligation-cordapp/workflows/src/main/java/net/corda/samples/obligation/flows/IOUSettleFlow.java#L57-L61
It's also worth mentioning that there's a lot of code examples for latest corda in the docs here: https://docs.corda.net/docs/corda-os/4.7/api-vault-query.html

Corda Upgradation to V4.6


2x2 matrices with sum of diagonal entries equal zero

Question: Is the set of 2x2 matrices with sum of diagonal entries equal zero a vector space over the real numbers under the usual matrix matrix  addition and scalar matrix multiplication?
Answer: Yes. You can check it directly or note that the set is given by
$$
\left\{ \left.
    \begin{pmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \end{pmatrix}
        \right| \, a_{11} + a_{22} = 0
\right\}
$$
and so it is the set of solutions to a linear homogeneous equation and thus a vector space of dimension $4 - 1 = 3$.
Comment: Thanks for the edit! I was wondering for a long time how to make the set theoretic brackets to match the size what they surround.
Comment: but a11+a22 must be zero. Diagonal entries sum is zero
Comment: You are right, but it doesn't matter which linear equation you write - the solution space will still be a vector space.
Answer: Set of all matricess of below type with a,b,c $\in \mathbb{R}$  \begin{bmatrix}
    a &  b\\
    c & -a\\
    \end{bmatrix}
are the $2 \times 2$ matrices of trace zero form a vector subspace of $M(2,\mathbb{R})$ with dimension 3. Since, there are three free arbitrary constants(a,b,c). Vector addition and scalar multiplication closed under usual matrix addition and scalar with matrix multiplication.


How to add custom notification sound - Ionic 4

Question: I am using the FCM plugin together with Firebase Cloud Messaging. Notifications are sent by making an http call to a Cloud Function from which the notification is sent using the device token.
The cloud function looks like this:
<code>  let payload = {
            notification: {
                title: 'Pedido completado',
                body: 'Gracias por usar nuestro servicio!',
                sound: 'boop.mp3',
                priority: "high",
                icon: 'https://res.cloudinary.com/....Moviapp_icono_512x512.png'
            }
        };

admin.messaging().sendToDevice([token], payload);
</code>
My component.ts looks like this
<code>  async getToken(uid) {
    const token = await this.fcm.getToken();
    const body = { token, usuario: uid };
    this.sentTokenToTheServer(body);
  }

  async sendPushNotification(token) {
    const pushURL = `https://us...cloudfunctions.net/pushNotification?token=${token}`;
    this.http.get(pushURL, { responseType: 'text' }).toPromise();
  }
</code>
Notifications work correctly even with a custom icon, but the problem is the sound that remains by default
Answer: first you need to add your mp3 file inside src/assets folder. then add this in config.xml file
<code><resource-file src="src/assets/boop.mp3" target="app/src/main/res/raw/boop.mp3" />
</code>
then notification payload should be like this
<code>{
  "notification":{
  "title":"Pedido completado",
  "body":"Gracias por usar nuestro servicio!",
  "sound":"boop.mp3",
  "click_action":"FCM_PLUGIN_ACTIVITY",
  "icon":"fcm_push_icon"
  }
}
</code>
Comment: can you tell me the setup for  ios ? whare to store the sound and how ?
Answer: For the latest android versions you need to create a notification channel if you'd like to use a custom sound. The documentation of the FCM plugin describes how to do that.


css filter on three sides of element

Question: in the example below I need a drop-shadow on all sides except on the top
I tried this - without success
filter:drop-shadow(-3px 3px 3px rgba(0,0,0,0.3), 3px 3px 3px rgba(0,0,0,0.3));

.story{
width:50vw;
margin:0 auto;
height:50vh;
background:orange;
border-radius:0 0 14px 14px;
filter:drop-shadow(-3px 3px 3px rgba(0,0,0,0.3));
}

Answer: Consider a clip-path that will clip only the top part then you can use a basic box-shadow (or a drop-shadow)

.story {
  width: 50vw;
  margin: 0 auto;
  height: 50vh;
  background: orange;
  border-radius: 0 0 14px 14px;
  box-shadow:0px 3px 5px 3px rgba(0, 0, 0, 0.5);
  clip-path:polygon(-50px 0,calc(100% + 50px) 0,calc(100% + 50px) calc(100% + 50px),-50px calc(100% + 50px))
}

To undestand what the clip-path is doing:

.story {
  width: 50vw;
  margin: 0 auto;
  height: 50vh;
  background: orange;
  border-radius: 0 0 14px 14px;
  box-shadow:0px 0 0 100vmax red;
  clip-path:polygon(-50px 0,calc(100% + 50px) 0,calc(100% + 50px) calc(100% + 50px),-50px calc(100% + 50px))
}

Answer: Not sure if there's a built-in way in css to do this. I copied the div and put it right on top of the first one and added the shadow to the right. Hth...

.story {
  width: 50vw;
  margin: 0 auto;
  height: 50vh;
  background: orange;
  border-radius: 0 0 14px 14px;
  filter: drop-shadow(-3px 3px 3px black);
}

.story2 {
  width: 50vw;
  margin: 0 auto;
  height: 50vh;
  background: orange;
  filter: drop-shadow(2px 3px 3px black);
}

Comment: Or maybe [this](https://stackoverflow.com/a/51731766/1171702).
Comment: drop shadow is visually better than a box shadow, that's why I want the first one. You solution is technically ok, but I hope there is a more native way
Comment: S**t, was that in the original Q? it didn't register.

css filter on three sides of element


Seeking a clarification regarding the bijectivity of the mapping between isometric spaces.

Question: If $X$ and $Y$ are isometric spaces, does the mapping between them $f:X\to Y$ have to be bijective? I feel only injectivity is required to satisfy the relation $$d_y(f(a),f(b))=d_x(a,b)$$
and surjectivity is not needed.
Even this proof of the completion theorem seems to imply $f$ need only be injective. However, my textbook seems to insist $f$ should be bijective. I don't know if surjectivity is a condition that is useful later on.
Thanks in advance!
Comment: Hello, you're of course right that it only need be injective. Consider an inclusion of a subspace. That said, it is a fact that any isometry of a compact metric space with itself is surjective. Maybe that's what they refer to?
Comment: Yes but what if $X$ and $Y$ are different?
Comment: I just gave you an example where this is untrue if X and Y are unequal. Include any proper subspace into the full space.
Comment: A map $f \colon X \to Y$ with the property $d_Y(f(a),f(b)) = d_X(a,b)$ for all $a,\,b\in X$ is an isometric embedding of $X$ in $Y$. Occasionally also called an isometry from $X$ _into_ $Y$. Two metric spaces $X$, $Y$ are called isometric, if there is a bijective isometric map between them. Such a bijective isometry is also sometimes called an isometry _between_ the two spaces. The relation "isometric" between metric spaces is (and should be) an equivalence relation. Note that when dealing with completions, it is supposed that the space to be completed is _dense_ in its completion, therefore
Comment: an isometry from one completion $Y$ of $X$ into another $Z$, that respects the embeddings of $X$ into $Y$ resp. $Z$ automatically is surjective, hence bijective.
Answer: For some people (I personally don't adhere to this definition), the statement '$X$ and $Y$ are isometric spaces' is not equivalent to 'there is an isometry $f\colon X\rightarrow Y$'. This comes down to whether or not you impose the extra condition that isometries are bijective. I would personally call such a map which wasn't necessarily surjective an isometric embedding and then if the map also happens to be surjective I would call it an isometry, so that isometries became the class of isomorphisms in the category of metric spaces. Many authors adopt this position.
However, many others adopt the definition that an isometry* (I'll use a * to distinguish the two definitions) only needs to preserve distance, and so if $f\colon X\rightarrow Y$ is an isometry* then the space $X$ and $f(X)$ are isometric metric spaces. However, $X$ and $Y$ are only isometric if $f(X)=Y$, that is $f$ is surjective.
The moral of the story is that an author should make clear which definition they are using, and a reader should check to see which definition the author is using.


How can we interpret the graph information after certificate in Pynauty?

Question: Cross-posted on pynauty_read_certificate.
Pynauty is a Python/C extension module using library components from the Nauty package by Brendan McKay.
In Pynauty, the function certificate can compute a certificate based on the canonical labeling of vertices. It returns the certificate as a byte string.

certificate

g=Graph(number_of_vertices=19, directed=False,
 adjacency_dict = {
  0: [1, 7, 11, 14, 17, 18],
  1: [2, 3, 4, 5, 6],
  7: [8, 9, 10],
  11: [12, 13],
  14: [15, 16],
  12: [13],
  13: [17],
  17: [18],
  18: [8],
  8: [9],
  9: [10],
  10: [15],
  15: [16],
  16: [2],
  2: [3],
  3: [4],
  4: [5],
  5: [6],
  6: [12],
 },
 vertex_coloring = [
 ],
)
g1=certificate(g)

I will see this:
b'\x00\x00\x00\x00\x00\x80\x01 \x00\x00\x00\x00\x00\x80\x02 \x00\x00\x00\x00\x00\x80\x00\xc0\x00\x00\x00\x00\x00 \x04\x01\x00\x00\x00\x00\x00 \x08\x02\x00\x00\x00\x00\x00 \x00\x03\x00\x00\x00\x00\x00 \x00\x0c\x00\x00\x00\x00\x00 \x00\x14\x00\x00\x00\x00\x00@"\x00\x00\x00\x00\x00\x00@\t\x00\x00\x00\x00\x00\x00\x00\x94\x00\x00\x00\x00\x00\x00@$\x00\x00\x00\x00\x00\x00\x00A\x08\x00\x00\x00\x00\x00\x000\x10\x00\x00\x00\x00\x00@\x80@\x00\x00\x00\x00\x00\x00H\x80\x00\x00\x00\x00\x00@\x00\xe0\x00\x00\x00\x00\x00\xa0\xd2\x00\x00\x00\x00\x00\x00@\x00\x1f'

Is the certificate returned in another form of input graph? I don't know if this process is reversible. Because g1 is in the form of bytes, I can't see the graph it represents, or, in other words, the information about the graph represented by g1 from its result. (Its vertex labels have likely been relabeled based on the canonical labeling).
If it is possible to convert them into the graph6 format for storage, it would indeed be a good choice. This format allows for compatibility with various other tools, such as showg, which can read and manipulate graphs in graph6 format.
Answer: This is using nauty's internal dense format, described in nauty and Traces User's Guide (Version 2.8.6) section 3.
Here's a hacky way to get a graph out of it:
set_length = len(g1) // g.number_of_vertices
sets = [g1[set_length*k:set_length*(k+1)] for k in range(g.number_of_vertices)]
neighbors = [[i for i in range(set_length * 8) if st[-1 - i//8] & (1 << (7 - i%8))] for st in sets]
g_canon = Graph(number_of_vertices=g.number_of_vertices, directed=False, adjacency_dict={i: neighbors[i] for i in range(g.number_of_vertices)})

Check:
>>> certificate(g_canon) == certificate(g)
True
>>> from pynauty import canon_label
>>> canon_label(g_canon)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

(Cross-posted from https://github.com/pdobsan/pynauty/issues/30#issuecomment-1564066767)


Configuration - > Zones admin page missing?

Question: I've installed Drupal Commerce 2 and as explained here:
https://drupal-commerce.readthedocs.io/en/latest/v2/building-blocks/address/zones.html
there should be a "Zones" admin page at Configuration -> Zones. But I don't have that page and I only have "default" zone?!?
Only relevant module I found is:
https://www.drupal.org/project/address_zone
but it exists only for Drupal 7?!
What I'm trying actually is to configure Commerce Product Tax, which exists only for D8 and at screenshot from module page:
https://www.drupal.org/project/commerce_product_tax
... they do have zones "France" and "France (Corsica)", so this should be possible somehow I guess.
How to administrate those zones and why I don't have that page under "Configuration" in my back-end?
Comment: Those are not the official Commerce docs, looks like a mirror that's many years out of date. The official docs are at https://docs.drupalcommerce.org/
Comment: Those docs are outdated, for Address [it shows this](https://drupal-commerce.readthedocs.io/en/latest/_images/address-configure.png) but its not there either. [Once upon a time, it existed](https://www.drupal.org/project/commerce/issues/2352711) tho so I suspect it's the same for zones, it later got removed/replaced.
Answer: Use the European Union VAT

As it has France and France (Corsica)


Prove that the Torus is not homotopy equivalent to $S^1\vee S^1\vee S^2$

Question: Prove that the Torus is not homotopy equivalent to $S^1\vee S^1\vee S^2$.
I need to show that a homotopy equivalence between them doesn't exist, but it seems like the homology groups of the spaces are equal. How can I show it? maybe using fixed point theorem?
Comment: Homotopy equivalent spaces have isomorphic homotopy groups. Hence: If two connected spaces have non-isomorphic fundamental groups, they are not homotopy equivalent.
Comment: Have you considered using homotopy groups (in particular the fundamental group)?
Comment: How can I use them?
Answer: The space $S^1\vee S^1\vee S^2$ is the wedge sum of two circles and one sphere. In particular this space is also known as mouse space.
It is quite easy to see that the fundamental group of $S^1\vee S^1\vee S^2$
is $\mathbb{Z}*\mathbb{Z}\cong\langle a,b| \emptyset \rangle$ ( you can use the Seifert-VanKampen theorem to see it ); whereas the fundamental group of the torus is $\mathbb{Z}\times\mathbb{Z}=\langle a,b | [a,b]=1\rangle$, which is not isomorphic to the previous.
If there was a homotopic equivalence between them; their fundamental groups needs to be isomorphic; but this is not true. So there is not any homotopic equivalence.
Comment: Thank you for the correction :) I don't remember where I read that name; maybe on the Hatcher's book: Algebraic Topology.
Answer: Working over $\mathbb{Z}$ throughout, the cohomology ring $H^*(T^2) = H^1(S^1)\otimes H^1(S^1)$ contains a nontrivial cup product (above dimension $0$), while $H^*(S^1\vee S^1\vee S^2)$ does not.


Nice problem of parametric integral

Question: Evaluate
$$I(a)=\int\limits_0^{\infty}\frac{1}{{\cosh}({\pi}x)(1+ax^2)}dx\;,\;\;\text{with}\;\;a>0$$
For example, if $a=4$,then$I(4)=\frac{1}{2}\log(2)$.
Comment: "Show that"? Did you mean "evaluate"? What've you done so far, though?
Comment: do you want to evaluate the integral ???
Comment: look at this too http://math.stackexchange.com/questions/411058/evaluate-the-integral-int-0-infty-frac11x2-coshaxdx
Comment: Ooo, these are my favorite kind of integrals. You mind sharing where the question came from?
Comment: This is 3.522.4 from Gradshtein & Ryzhik.
Comment: @DavidH Actually,it's a physical problem which can be found in the book$$ Beautiful models :70 years of exactly solved quantum many-body problems $$. Unfortunately, I can't remember the exact page,but in the chapter,somewhat Ising-Heisenberg model.
Answer: i think the OP wants to evaluate it
By using Evaluate the integral $\int_{0}^{\infty} \frac{1}{(1+x^2)\cosh{(ax)}}dx$
$$ I = \int_0^{\infty} \frac{dx}{\cosh(ax)(1+x^2)} $$
$$ u = bx \Rightarrow I = \frac{1}{b}\int_0^{\infty} \frac{dx}{\cosh \left(\frac{a}{b}x \right)\left( 1 + \frac{x^2}{b^2} \right)} $$
put $ \frac{a}{b} = \pi $
Answer: The integrand is even. Switch the integral to $\left(-\infty,\infty\right)$. Use complex integration $\left(~\mbox{Residue}\ \mbox{Theorem}~\right)$. Poles of $\cosh\left(\pi x\right)$ are at
${\rm i}\left(n + 1/2\right)$. $n \in {\mathbb Z}$. The "other piece" has poles at $z = \pm{\rm i}a^{-1/2}$. That's all we need.

Nice problem of parametric integral


Making and finding function $f(x)$ such that $f(x) \to 0$ as $x \to 0$

Question: Find(Make) a function like $f(x)$ that at $x=0$, $f(x)$ goes to $0$ ( not 0 ; $f(0)\neq 0$ , but $f(x)$ is going to $0$ as $x\to 0$)
Comment: The Dirac delta is not a function
Comment: Take any continuous function, such that it is $0$ at $0$, and add a discontinuity just at that point. For example $\delta(x)$
Comment: One example $\left(\frac{\sin x}{x} -1\right)$?
Answer: Define, $f$ on $[0,\infty)$, by,
\begin{align*}
f(x) =
\begin{cases}
 \frac{\ln(1+x)}{x} -1, & \text{if $x\in (0,\infty)$ } \\
1, & \text{if $x=0$ }
\end{cases}
\end{align*}
Also,.by using the fact of removable discontinuity, you can creat easily such functions,
As example,
\begin{align*}  f(x) =
\begin{cases}
1 &  x = 0 \\
x& \text{otherwise}
\end{cases}
\end{align*}


Estimation of probability of the distribution of a continuous random variable

Question: I am trying to find the probability distribution of a continuous random variable X which is defined by
(X=x)=(2−x)(x+1),where 0≤=x≤2
Can anybody help me to find x and mean expected value E(x) ?
Comment: First of all you should evaluate the value of $k$. Use that $\int\limits_{0}^2 f(x) \, dx =1$
Comment: I suppose that $P(X=x)$ in the above really should be $f_X(x)$ (the probability density function of $X$), as for a continuous random variable we have that $P(X=x)=0$.
Answer: You can't find $x$, the question doesn't make sense and I suspect you meant find $k$ so I will proceed with that
A continuous random variable must satisfy the property $\int f(x) dx=1$  or in other words: the sum of all probability must equal to $1$.
To find $k$ we need $k\times\int_0^2(2-x)(x+1)dx=1$, we have $\int_0^2(2-x)(x+1)dx=\frac{10}{3}$ (this was done quickly on WolframAlpha as the goal here isn't to teach you integration) so we have $k\times \frac{10}{3}=1$ which gives us $k=\frac{3}{10}$
For your second question, we have $E(X)=\int xf(x)$ so to find the expected value you should evaluate $\frac{3}{10}\int_0^2x(2-x)(x+1) dx$ which gives $\frac{4}{5}$
Comment: @projectilemotion yes, thank you for pointing it out, op asked as similar question about a discrete random variable like an hour ago so I just copied the initial sentence and forgot this part
Answer: Your question holds a couple of mistakes. First, if you are dealing with continuous random variable then, for any x the probability P(X=x) is equal to 0 by definition. Secondly, the task to find $x$ makes no sense, since $x$ is a name of an argument here.
I would assume that by P(X=x) you mean a probability density function (PDF) $f_X(x)$, which is also defined as 0 everywhere outside $x\in [0,2]$, and will build my answer based on that information.

Find $k$. For a PDF following conditions hold by definition

$f_X(x)\geq0$ for all $x$ (clearly holds);
$\int_{-\infty}^{\infty} f_X(x)dx=1$

Calculating the integral above gives us the equation $\frac{10}{3}\cdot k=1$, thus $k=\frac{3}{10}$.

calculate $E[X]$. By definition,
$$E[X]=\int_{-\infty}^{\infty} xf_X(x)dx = \int_{0}^{2} x\cdot \frac{3}{10}(2-x)(x+1)dx=\frac45$$


Cant remove jslint from sublime text 2

Question: I installed jslint a few weeks ago usig the package installer and never got it to properly work. When saving a file down no matter the extension(.php, .css, .html, etc.) I get this error
[Error 2] The system cannot find the file specified
[cmd:  [u'node', u'C:\\Users\\username\\AppData\\Roaming\\Sublime Text 2\\Packages/JSLint/linter.js', u'--sloppy', u'--indent', u'2', u'--node', u'--nomen', u'--vars', u'--plusplus', u'--stupid', u'--todo', u'C:\\wamp\\www\\child-themes\\wp-content\\themes\\genesischild\\style.css']]
[dir:  C:\wamp\www\child-themes\wp-content\themes\genesischild]
[path: C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Ruby200-x64\bin]
[Finished]

I decided to remove it but everytime I restart sublime it reappears. I have deleted over 20 times the last couple of weeks and it keeps re installing itself. Any way to completely remove jslint from sublime text 2?
Answer: You have to remove it from package control. To do this either go to your package control settings Preferences -> Package Settings -> Package Control -> Settings - User and remove it from the installed_packages list. You can also search the command palette for Package Control: Remove Package. Package Control will install any package in the installed list if it is not on your machine automatically. This is nice to have when moving from machine to machine.
Comment: Thank you very much! I removed it using the `Package Control: Remove Package` this took only a few seconds. I restarted sublime text and it is not showing. Thanks again.

Cant remove jslint from sublime text 2


Proving $(a_n)$ diverges

Question: For  a given sequence $(a_n)$, where $a_1>0$ and for each natural number $n\ge 1$ :
$$a_{n+1}= \dfrac{a_n^2 + 1}{a_n}$$
Prove that a sequence $(a_n)$ diverges.
Proof:
(objectionable evidence)
Lower barrier 0, prove.
$a_n>0$   $\forall n\in N$. $N$ is natural number and $N>1$.
$n=1$
$a_{1+1}=\frac{a_1\cdot a_1+1}{a_1}=a_1+\frac{1}{a_1} >0$
$a_n>0$ $\Rightarrow a_{n+1}>0$ :
$a_{n+1}=a_n+\frac{1}{a_n}>0$, because $a_n > 0$
Monotonics:
$a_n\geq a_{n+1}$
$a_n-a_{n+1}=a_n-a_n-\frac{1}{a_n} < 0$, because $\frac{1}{a_n}>0$
Sequence is growing.
lim $a_{n+1} = A$
lim $a_{n+1} =$ lim $(a_n+\frac{1}{a_n}) =$ lim $a_n +$ lim $\frac{1}{a_n} = A + \frac{1}{A} = \frac{A\cdot A+1}{A}$
....
Is this proof correct? Where are mistakes? The correct end of proof?
Answer: $a_{n+1} = a_n + \dfrac{1}{a_n}\implies a_{n+1}^2 = a_n^2 + 2+\dfrac{1}{a_n^2}\implies a_{n+1}^2 - a_n^2 > 2, \forall n \ge 1 \implies a_n^2 = (a_n^2- a_{n-1}^2)+(a_{n-1}^2-a_{n-2}^2)+(a_{n-2}^2-a_{n-3}^2)+\cdots+(a_2^2-a_1^2)+a_1^2> 2(n-1)+a_1^2 > 2(n-1)\implies a_n > \sqrt{2(n-1)} \implies a_n \to \infty$.

Proving $(a_n)$ diverges


What is the value of the integral $\int_0^\infty 0dx$?

Question: I know that this question might be very simple, but I want to know: what is the value of following integral?
$$\int_0^\infty0dx$$
Answer: The trick with such things is always: look at the definition, and just apply it carefully.

By definition, $\int_0^\infty f(x)dx$ is just $\lim_{r\rightarrow\infty} \int_0^r f(x)dx$, so we just need to calculate $\int_0^r 0dx$ for an arbitrary real $r$.
But $\int_0^r 0dx$ is always $0$ (you should already be comfortable with this).
So $\int_0^\infty f(x)dx=\lim_{r\rightarrow\infty} \int_0^r f(x)dx=\lim_{r\rightarrow\infty}0=0$.

The reason $\int_0^\infty 0dx$ may seem mysterious at first is that it feels like the old "paradox": "What happens when you add infinitely many infinitely small quantities together?" But this "paradox" is also present in integration all the time: $\int_a^bf(x)dx$ is intuitively "the sum of the areas of infinitely many infinitely thin rectangles." So this is a problem that we've already resolved, and the fact that $\int_0^\infty0dx=0$ should be no more mysterious than the general behavior of integration (in fact, it should be less mysterious).
Answer: Hint:
$$\forall t>0: \int_0^t 0 \mathrm{d}x=0$$
Answer: A more intuitive angle: recall that
$$\int_a^b f(x)dx$$
can be analogized as the area between $f$ and the $x$ axis on the interval $[a,b]$. Take $a=0, b \to \infty,$ and $f(x)=0$. Then we have
$$\int_0^\infty 0 dx$$
or, essentially, the area between the line $y=0$ (the $x$-axis) and the $x$-axis, for $x\geq0$. In that light, it should be immediately clear there is $0$ area, and thus the integral is $0$.
Answer: By one definition, the integral is the infinite limit of the sum of the areas of rectangles whose base is $\Delta x$ and whose height is $f(x_i)$. In this case $f(x_i)=0$. So $f(x_i)\Delta x=0$. Summing these, you get, of course $0$ and the limit is $0$.


Fastest way to GZIP and UDP a large amount of Strings in Java

Question: I'm implementing a logging system that needs to encode the log messages with GZIP and send them off by UDP.
What I've got so far is:
Initialization:
DatagramSocket sock = new DatagramSocket();
baos = new ByteArrayOutputStream();
printStream = new PrintStream(new GZIPOutputStream(baos));

This printStream is then passed out of the logger - messages will arrive through it
Then every time a message arrives:
byte[] d = baos.toByteArray();
DatagramPacket dp = new DatagramPacket(d,d.length,host,port);
sock.send(dp);

What stumps me currently is that I can't find a way to remove the data from the ByteArrayOutputStream (toByteArray() only takes a copy) and I'm afraid that recreating all three stream objects every time will be inefficient.
Is there some way to remove sent data from the stream? Or should I look in another direction entirely?
Comment: Note: If the strings are short, they will be larger if GZIPed.
Answer: You must create a new stream for each message; otherwise, every call to toByteArray() will send all previous messages again.
A better approach is probably to wrap the OutputStream of a TCP socket with a GZIPOutputStream:
printStream = new PrintStream(new GZIPOutputStream(sock.getOutputStream()));

Also don't forget to flush the PrintStream after every message or nothing will happen.
If speed is really that important, you should consider to use a DatagramChannel instead of the old (slow) steam API. This should get you started:
ByteBuffer buffer = ByteBuffer.allocate( 1000 );
ByteBufferOutputStream bufferOutput = new ByteBufferOutputStream( buffer );
GZIPOutputStream output = new GZIPOutputStream( bufferOutput );
OutputStreamWriter writer = new OutputStreamWriter( output, "UTF-8" );
writer.write( "log message\n" );
writer.close();

sock.getChannel().open(); // do this once
sock.getChannel().write( buffer ); // Send compressed data

Note: You can reuse the buffer by rewinding it but all the streams must be created once per message.
Answer: It is worth checking that using GZIP will help if speed is important. (It will add some latency)
public static void main(String... args) throws IOException {
    test("Hello World");
    test("Nov 20, 2012 4:55:11 PM Main main\n" +
            "INFO: Hello World log message");
}

private static void test(String s) throws IOException {
    byte[] bytes = s.getBytes("UTF-8");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream outputStream = new GZIPOutputStream(baos);
    outputStream.write(bytes);
    outputStream.close();
    byte[] bytes2 = baos.toByteArray();
    System.out.println("'" + s + "' raw.length=" + bytes.length + " gzip.length=" + bytes2.length);
}

prints
'Hello World' raw.length=11 gzip.length=31
'Nov 20, 2012 4:55:11 PM Main main
INFO: Hello World log message' raw.length=63 gzip.length=80

Comment: GZIP is not my decision here. I'm sending the log messages off to Graylog which forces both GZIP and UDP on me.
Comment: GZIP for compatibility is reasonable.  If you can find a way to combine log entries in batches that will improve efficiency dramtaically. BTW DeflatorOutputStream has a much smaller header/footer if this is an option in the future.
Comment: I would be concerned with running out of heap space if you call `toByteArray()` too many times.
Comment: @heez it's only a problem.if you retain the arrays. Creating short lived objects is relatively cheap compared with compression.
Answer: The answers were helpful with other aspects of my problem, but for the actual question - there is a way to clear the data from a ByteArrayOutputStream. It has a reset() method. It doesn't actually clear the buffer, but it resets the count property to 0 causing it to ignore any data already in the buffer.
Note that writing to a GZIPOutputStream after resetting the underlying ByteArrayOutputStream will cause an error, so I have not yet found a way to reuse everything.


PHP - xdebug remoto utilizando netbeans

Question: Apresentando o ambiente:
Tenho um servidor virtual rodando uma distribuição Debian 7.2 (64bits), neste servidor tenho instalado o Apache 2.2.22 e o PHP 5.4.39
Minha máquina hospedeira roda o OS X 10.11, como IDE de desenvolvimento estou utilizando o Netbeans para PHP.
Explicando o cenário de uso:
Criei um projeto X que é executado em um servidor remoto, ou seja, na máquina virtual Debian citada logo acima. Nas configurações do projeto defini a opção Executar como Web Site remoto (sftp).
Descrevendo o problema:
Instalei o xdebug, editei o arquivo /etc/php5/apache2/php.ini e defini no final do mesmo as configurações abaixo:
<code>zend_extension="/usr/lib/php5/20100525/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_log="/tmp/xdebug.log"
xdebug.idekey=netbeans-xdebug
</code>
Porém, quando utilizo a opção de depuração do netbeans consigo observar que na barra de status fica a menagem - Aguardando Conexão (netbeans-xdebug) - e nada...
Já tentei de tudo mas nada surtiu efeito. Alguém saberia como me ajudar?
Comment: Não precisa trocar o localhost pelo ip? na quarta configuração.
Comment: Já tentei isso, defini como 127.0.0.1 e até cheguei a testar o ip da máquina hospedeira, porém, sem sucesso.
Comment: tente trocar xdebug.remote_host=localhost para o ip da sua máquina de desenvolvimento
Comment: também já tentei isso e não surtiu efeito.
Answer: Problema resolvido.
No caminho /etc/php5/conf.d o arquivo 20-xdebug.ini deve ser alterado para xdebug.ini e efetuado restart do apache.
Tudo ok agora.

PHP - xdebug remoto utilizando netbeans


Covariance of An Empirical Distribution Function Evaluated at Different Points

Question: The problem is extracted from All of Statistics (Exercise 7.5), Larry Wasserman. I don't have a solution manual to the book so I post here the problem together with my attempted answer:
Let $x$ and $y$ be two distinct points. Find $Cov(\hat F_n(x), \hat F_n(y))$.
Here is my attempted answer:
$\hat F_n(x) = \frac{1}{n} \sum I\{ X_i \le x\} $
$\mathop{\mathbb{E}}(\hat F_n(x)) = F(x) $
$\mathop{\mathbb{E}}(\hat F_n(y)) = F(y) $
$Cov(\hat F_n(x), \hat F_n(y)) = \mathop{\mathbb{E}}(\hat F_n(x)\cdot \hat F_n(y)) - \mathop{\mathbb{E}}(F_n(X))\mathop{\mathbb{E}}(F_n(y) $
For (Updated based on Xi'an's answer)
\begin{align*} \mathop{\mathbb{E}}(\hat F_n(x)\cdot \hat F_n(y)) &= \frac{1}{n^2} \mathop{\mathbb{E}}(\sum_i I\{X_i \le x\} \sum_j I\{X_j \le y\}) \\&= \frac{1}{n^2} \mathop{\mathbb{E}}(\sum_{i \neq j} I\{X_i \le x\}I\{X_j \le y\} + \sum_{i = j} I\{X_i \le x\}I\{X_j \le y\}) \\&= \frac{1}{n^2}(nF(\min\{x,y\})+n(n-1)F(x)F(y)) \\&= \frac{1}{n}(F(\min\{x,y\}) + (n-1)F(x)F(y))\end{align*}
Combining the above result together, we have (Updated based on Xi'an's answer):
$$ Cov(\hat F_n(x), \hat F_n(y)) = \frac{1}{n}(F(\min\{x,y\}) - F(x)F(y)) $$
I am not sure if my attempt is correct or not. Could anyone verify the answer or point out if there are any flaws in my arguments?
Answer: Note that
\begin{align*}\text{Cov}(\frac{1}{n} \sum I\{ X_i \le x\},\frac{1}{n} \sum I\{ X_i \le y\})
&=\frac{1}{n^2}\text{Cov}(\sum I\{ X_i \le x\},\sum I\{ X_i \le y\})\\
&=\frac{1}{n^2}\sum_{i=1}^n\text{Cov}(I\{ X_i \le x\},I\{ X_i \le y\})\\
&\qquad\quad{\text{(since the $X_i$'s are independent)}}\\
&=\frac{1}{n}\text{Cov}(I\{ X_1 \le x\},I\{ X_1 \le y\})\end{align*}
and
\begin{align*} \mathop{\mathbb{E}}[I\{X_1 \le x\}I\{X_1 \le y\}] &= \mathop{\mathbb{E}}[I(X_1 \le \min\{x, y\})] \\&= F(\min\{x,y\})
\end{align*}
leading to
$$\text{Cov}(\hat F_n(x), \hat F_n(y)) = \frac{1}{n}[F(\min\{x,y\}) - F(x)F(y)]\tag{1}$$
When writing
\begin{align*} \mathop{\mathbb{E}}(\hat F_n(x)\cdot \hat F_n(y)) &= \frac{1}{n^2} \mathop{\mathbb{E}}(\sum_i I\{X_i \le x\} \sum_j I\{X_j \le y\}) \\&= \frac{1}{n^2} \mathop{\mathbb{E}}(\underbrace{\sum_{i \neq j}}_{n(n-1)\\\text{distinct}\\\text{pairs}} I\{X_i \le x\}I\{X_j \le y\} + \sum_{i = j} I\{X_i \le x\}I\{X_j \le y\}) \\&\overbrace{=}^\text{wrong!} \frac{1}{n^2}(nF(\min\{x,y\})+nF(x)F(y))\end{align*}
the mistake is in not counting the number of distinct pairs $i\ne j$ right: there are $n(n-1)$ of them, rather than $n$. With this correction,
$$\mathop{\mathbb{E}}(\hat F_n(x)\cdot \hat F_n(y))=\frac{F(\min\{x,y\})}{n}+\frac{n-1}{n}F(x)F(y)-F(x)F(y)=\frac{1}{n}[F(\min\{x,y\}) - F(x)F(y)]$$
recovering (1). Here is an illustration of the fit between theory and empirical evaluation of $\text{Cov}(I\{ X_1 \le x\},I\{ X_1 \le y\})$
<code>x=rnorm(1e6)
cov((x<a),(x<b))
pnorm(min(c(a,b)))-pnorm(a)*pnorm(b))
</code>
based on 10³ random pairs (a,b).
Comment: Thanks for pointing it out. Based on your correction, I have edited my argument
Comment: Your solution implies $\mathrm{Cov}(\hat{F}_n(x),\hat{F}_n(y)) = \mathbb{E}(\hat{F}_n(x)\hat{F}_n(y))$. Is that correct? Did you mean $\mathrm{Cov}(\hat{F}_n(x),\hat{F}_n(y))$ instead of $ \mathbb{E}(\hat{F}_n(x)\hat{F}_n(y))$ in the equation following "With this correction,"?


Regression calculation with missing data

Question: In a regression calculation for five pairs of observations one pair of values was lost when data were filed. For the regression of y on x the equation was calculated as
$y=2x−0.1$
The four recorded pairs of values are:
$x:0.1,0.2,0.4,0.3$
$y:0.1,0.3,0.7,0.4$
Find the missing pair of values, using the following data for the four pairs above: $∑x=1,∑x^2=0.3,∑xy=0.47,∑y=1.5$
I managed to find out that $b=1.9$ in $y=a+bx$ when there are four values. The value of constant $a=-0.1$ remains unaltered. As such I am done with the easy part of the question. I have been thinking about simultaneous equations for a while, but again do not really know how to go about finding the values of $x_5$ and $y_5$.
I would appreciate some support that could put me on the right track.
Comment: Please consider adding the self-study tag and reading its wiki excerpt. The edit your question to tell us what you have tried and where you got stuck.
Comment: @mdewey thank you for the tip, I have updated the question a little.
Comment: This meets our standards for self-study questions: it has the tag & explains what the OP has done so far / where they need help. It should be on topic here.
Answer: The most direct way to solve the problem is to start with simple regression equations:
$$\widehat{\beta_1}=\frac{\sum(x_i-\bar{x})(y_i-\bar{y})}{\sum(x_i-\bar{x})^2}\text{ and }\hat{\beta_0}=\bar{y}-\widehat{\beta_1}\bar{x}$$
And of course you already have the formula for $\bar{x}$ and $\bar{y}$.
Since you know both betas and all x and y except for two ones, you have two equations and two unknown values (x and y for the missing observation). With the sums provided by the statement you can group terms and make those equations shorter and workable.
Answer: I have also asked this question on maths.stackexchange and got an answer from user JJacquelin. With the user's permission I have decided to repost the answer here, in case anyone stumbles upon this/similar problem.
HINT :
Before loosing one pair, the linear regression to fit the function
$y=ax+b$ (with 5 pairs) leads to the values of $a=2$ and $b=−0.1$:
$b=\frac{∑y∑x^2−∑x∑xy}{5∑x^2-(∑x)^2}$
$a=\frac{5∑xy−∑x∑y}{5∑x^2−(∑x)^2}$
Let $(X,Y)$ be the missing pair:
$∑x=1+X;∑x^2=0.3+X^2;∑xy=0.47+XY;∑y=1.5+Y$
The $∑$
continues to be for the 5 pairs. Putting them into the above equations :
$\begin{cases}
-0.1=\frac{(1.5+Y)(0.3+X^2)−(1+X)(0.47+XY)}{5(0.3+X^2)−(1+X)^2}\\
2=\frac{5(0.47+XY)−(1+X)(1.5+Y)}{5(0.3+X^2)−(1+X)^2}\end{cases}$
Solve this system of two equations for the two unknowns
$X,Y$.
LATTER ADDITION :
The result of solving is
$X=0.3$, $Y=0.6$
A short way :
One observe that the pairs $(0.1,0.1)$,$(0.2,0.3)$, $(0.4,0.7)$
are exactly on the regression line
$y=2x−0.1$
On the other hand, the pair $(0.3,0.4)$ is not on the regression line since the point should be $(0.3,0.5)$
to be on the regression line, because
$2∗0.3−0.1=0.5$
The missing pair $(X,Y)$ must compensate so that $(0.4+Y)/2=0.5→Y=0.6$


Some technical details about regular functions on quasiprojective varieties

Question: I have some confusion about some very basic notions in algebraic geometry.  I am using Shafarevich but I find the book to be pretty unclear at times.
First, given a quasi projective variety $X$ over an algebraically closed field $\mathbb{k}$ (meaning $X$ is an open subset of a closed subset of projective space) when defining what it means for a function $f:X\to \mathbb{k}$ to be regular on $X$ is it the same thing to say "there are homogeneous polynomials $p$ and $q$ in $n+1$ variables of the same degree such that at every $x\in X$ we have $f(x) = p(x)/(q(x)$" and "about each point $x\in X$ there is an open neighborhood of $x$ in $X$ such that $f$ is the quotient of two homogenous polynomials in $n+1$ variables of the same degree"?  In other words I am asking if, in the Zariski topology, a function locally looks like a quotient of two rational functions must it globally look like a quotient of two rational functions?  This is obviously not true in the usual topology on $\mathbb{C}$ for example but I am confused about the case of the Zariski topology.
Something else I am confused about is the following.  If we have a regular function $f$ on a quasiprojective variety $X$ then the set $X - Z(f)$ is an affine variety.  This I understand.  But it is stated in Shafarevich that that the ring of regular functions on $X-Z(F)$ is the ring of regular functions of $X$ adjoin $\frac{1}{f}$.  It is clear that this is contained in the ring of regular functions, but I don't understand how we know that this is the entire ring.
Answer: For your first question, if $X$ is affine, then $f$ can be seen globally as a polynomial. I believe Shafarevich proves this.
If $X$ is an irreducible quasiprojective in general, let $f=p/q$ locally at a point $x$, for $p$ and $q$ polynomials. If $y\in X$, let $f=r/s$ at $y$. Define
$$Y=\{z\in X:p(z)s(z)-q(z)r(z)=0\}.$$
This is a closed subset of $X$ (since the equation above is homogeneous and can be seen as defining a projective variety which we then intersect with $X$). Moreover, since $f=p/q$ (likewise with $f=r/s$) on an open (and therefore dense) subset of $X$, we see that this closed set contains a dense open set of $X$. Therefore $X=Y$.
Conclusion: You can define $f$ as $p/q$ wherever $q\neq0$. If $q(z)=0$ for some $z$, then you need another representation for $f$ at $z$.
Example: Take $X=\{x^2+y^2-1=0\}\subseteq\mathbb{A}^2$ and $f(x)=x^2/(y^2-1)$. $f$ could possibly have a pole at $y=\pm1$, but when we use the identity $y^2-1=-x^2$, we see that $f(x)$ is actually the constant function $-1$. This is a very boring example but it gets the point across.
For your second question, take a look at Lemma 2 in the section of Quasiprojective Varieties. First assume that $X$ is affine. The equations that Shafarevich finds for the affine variety $X-Z(f)$ are basically the equations for $X$, except that you can replace $T_{n+1}$ by $f$. Try to write the coordinate ring using this, and then see if you can generalize this to an arbitrary quasiprojective variety.
Comment: So basically in an irreducible variety if a function is locally rational it can be viewed as "globally rational" in the sense of being viewed as an element of the field of fractions of the ring of regular functions, but we might not necessarily find a representation which gives all function values?  What then in the case of a non irreducible variety?
Comment: Yes. If the variety is not irreducible, you have to look at each irreducible component.
Comment: So is there an actual example of a variety and a function which is locally rational but not globally rational?  Does this mean that regular functions do not form a sheaf structure on an arbitrary variety?  Or do we simply choose to define a regular function as one which is locally rational so that the gluing axiom is automatically satisfied?
Comment: The problem is that it is more complicated to talk about a rational function when your variety isn't irreducible, since the coordinate ring will no longer be a domain. Regular functions can be made into a sheaf by defining a regular function to be locally rational and defined at every point.


Applying CV2 Grayscale to a Numpy 4D array

Question: While I know how to convert a single color image (32,32,3) to grayscale using CV2:
img = cv2.cvtColor( img, cv2.COLOR_RGB2GRAY )

I need to convert a batch of 60,000 images in a 4D numpy array (60000,32,32,3), how can I achieve that?
Answer: Let's say your 4D array of images is called img_stack with shape (60000,32,32,3).
You could do:
gray_stack = np.empty_like(img_stack[...,0])
for i in range(img_stack.shape[0]):
    gray_stack[i] = cv2.cvtColor(img_stack[i], cv2.COLOR_RGB2GRAY)

Resulting shape is (60000,32,32).
Or you could do:
gray_stack = np.empty_like(img_stack[...,:1])
for i in range(img_stack.shape[0]):
    gray_stack[i,:,:,0] = cv2.cvtColor(img_stack[i], cv2.COLOR_RGB2GRAY)

Resulting shape is (60000,32,32,1).

Bonus Tensorflow solution:
gray_stack = tf.image.rgb_to_grayscale(img_stack, name=None)

Resulting shape will be (60000,32,32,1).
The above OpenCV solutions might actually perform faster.
Answer: One more option using numpy:
grayscale_imgs = np.dot(img_stack, [0.299 , 0.587, 0.114])
grayscale_imgs.shape # => (60000, 32, 32)

More about the weighted sum can be found here


Gráfico com rolagem horizontal c#

Question: Bom dia galera, estou desenhando um gráfico de linha em uma pictureBox com "drawline"s concatenados.
Basicamente o que eu desejo é criar uma barra de rolagem horizontal para navegar pelo gráfico, ou seja, poder percorrer todo gráfico na horizontal usando a barra de rolagem. Segue código que desenha o gráfico.
    void DrawANALISE()
    {
        Graphics g = pcbANALISE.CreateGraphics();
        g.SmoothingMode = SmoothingMode.AntiAlias;

        var lastPoint1 = new PointF(0F, (float)(2 * Height / 5) * 0.5F);
        PointF newPoint1 = new PointF();

        for (int i = 0; i < 6000; i++)
        {
            //aquisicaodata é uma lista onde há 6000 valores para y
            var porcent = aquisicaodata[i] / 5;
            newPoint1.X = (i + 1) * 0.2f;

            if (porcent > 1) porcent = 1;
            var hg = porcent * (2 * pcbANALISE.Height / 5);

            if (porcent >= 1) newPoint1.Y = 2 * pcbANALISE.Height / 5 - hg;
            else newPoint1.Y = 2 * pcbANALISE.Height / 5 - hg - 1;

            using (var p = new Pen(Color.Lime, 0.1f)) g.DrawLine(p, lastPoint1, newPoint1);

            lastPoint1 = newPoint1;
        }
    }

Como no código estou desenhando 1 ponto a cada 0.2 pixels na horizontal e há um total de 6000 pontos, o que resultaria em um total de 1200 pixels na horizontal para desenhar todo gráfico, uma pcb de 500 pixels de largura não é suficiente para exibir todo gráfico. Por isso gostaria de criar uma barra de rolagem horizontal para poder ter a visualização de todo gráfico. Editarei se necessário. Se alguém puder ajudar agradeço muito!
Answer: Basta criar uma variável de controle para a câmera scrollbar:
int camera = 0;

Neste trecho ficaria assim:
for (int i = camera; i < (camera + (pictureBox.Width / 0.2)); i++)

e no evento do scrollbar:
hscrollBar_scroll(EventArgs e, object sender)
{
    camera = hScrollBar.Value * 6000 / 100;
    DrawANALISE();//esqueci de por para redesenhar o gráfico.
}

Se com isso não consegui lhe ajudar posso fazer um controle completo, se preferir.
Comment: Valeu pela atenção novamente Weiner, então amigo, eu fiz aqui desse jeito mas não funcionou a rolagem. Mexo a scrollbar mas o gráfico continua parado.
Comment: se puder continuar ajudando ficaria muito satisfeito.
Comment: Só adicione o método para redesenhar no scrollbar, eu havia esquecido.
Comment: Amigo, até funciona a rolagem dessa maneira, porém o gráfico fica realmente se redesenhando desde o inicio a cada tick da rolagem, o que faz cair muito o desempenho, se eu clico pra deslocar o grafico o programa fica um pouco travado.
Comment: Agora não quer atualizar haha, mostrar o seguinte erro: "System.InvalidOperationException: 'O objeto está sendo usado em outro lugar.".
Comment: e aponta para a seguinte linha : using (var p = new Pen(Color.Blue, 0.1f)) g.DrawLine(p, lastPoint2, newPoint2);
Comment: vou tentar fazer um controle aki para lhe ajudar, mas realmente vc tem a necessidade de desenhar 10 valores em um único pixel, pq axo que nem está sendo mostrado todos esses valores.
Comment: Para a minha aplicação eu necessito de 300 pontos em um segundo amigo
Comment: será que não esta sendo mostrado? poxa, se não estiver to perdendo desempenho atoa
Comment: se você puder fazer esse controle eu agradeço, tentei de várias maneiras porém sem êxito.
Comment: cara, não sei se você sabe me responder isso, mas você sabe se para uma aplicação de visualização e análise de gráfico, com interface para usuários seria melhor usar c# ou java? Não tenho muito conhecimento na área ainda. Creio que os dois são parecidos.

Gráfico com rolagem horizontal c#


drupal_set_message on node edit page shows twice with theme hook

Question: I want to display a value of a field which the user has no access to in a dsm when the user edits the page. The dsm is showing up after saving the node, and while that's fine (I'd even consider it a feature) it's showing the before-edit value of the node.
I believe I've run into this problem but there doesn't seem to be an easy fix. Here's a look at the template.php function.
function themename_form_vakature_node_form_alter(&$form){
    if(isset($form['#node']->field_vacature_scheduled_for_unp)){
        if($form['#node']->field_vacature_scheduled_for_unp['und'][0]['value']){
            $expirydate = date("F j Y",$form['#node']->field_unpublish_date['und'][0]['value']);

            if($form['#node']->field_unpublish_date['und'][0]['value'] < time()){
                drupal_set_message(t("This vacature has expired."),'status',FALSE);
            }
            else{
                drupal_set_message(t("This vacature will expire at: ").$expirydate,'status',FALSE);
            }
        }
    }
}

Basically, the message displayed on the edit page is repeated after a save. I need it to either not repeat or show the correct updated information.
Answer: Form alter changes the form when it's being built for display.
If you want to use the value on the node after update, use a hook like

hook_node_presave or
hook_node_update

instead.
To tweak your code snippet, something like:
/**
 * Implements hook_node_presave
 */
function mymodule_node_presave($node){
  if ($items = field_get_items('node', $node, 'field_vacature_scheduled_for_unp')) {
    $vacature = reset($items); // Use first field item value
    $expirydate = date("F j Y", $vacature['value']);
    $items = field_get_items('node', $node, 'field_unpublish_date')
    $unpublish = reset($items); // Use first field value
    if ($unpublish['value'] < time()) {
      drupal_set_message(t("This vacature has expired."), 'status', FALSE);
    }
    else{
      drupal_set_message(t("This vacature will expire at: "). $expirydate, 'status', FALSE);
    }
  }
}

Comment: This looks promising but how would I show the value on the edit page without it appearing twice (That's more important than getting it to show after saving)
Comment: If you want to show the message when the user goes to edit the node, use hook_node_load instead and check if on edit page, e.g arg(0) == 'node' and arg(2) == 'edit'
Comment: Thanks! I'll still have to do some work to get things working properly but I should be able to get it from here!
Comment: By the way, is there a way to do this in the theme rather than a module?
Comment: `hook_node_load` triggers twice while saving the node. Now I have 2x the old value and 1x the new one.


How to create synthetic mortality data set?

Question: Mortality data for certain countries is available for at the Human Mortality Database (www.mortality.org). However, I would like to develop a multipopulation model that first estimates a mortality model for the reference population (e.g. a whole country) and subsequently incorporate features of this model in the mortality model for a subpopulation  (e.g. a region that has a significant higher mortality experience), which is too small to directly model the longterm trend and cohort effects. Thus, I rather model the difference of the subpopulation from the reference population.
As no data is available for the subpopulation, I would like to generate a synthetic dataset to exemplary show how the model would work. My ideas so far have been to

Merge data from two countries and model it as the reference population and treat the data from the smaller country as the subpopulation. Problem: the populations are not really related and strongly regional-dependent factors such as the cohort effect are totally different for the subpopulation.
A naive approach: Generate a new dataset by assuming a certain size of the population and use the same mortality intensity less x per cent.
Modify the above approach by sampling the percentage drawback e.g. from a uniform distribution in a certain interval.
Answer: Adrian Raftery's ICM webinar from a couple of weeks ago on Bayesian population projections may provide some guidance to addressing your question...
http://www.methods-colloquium.com/#!Adrian-Raftery-Bayesian-Population-Projections/clv6/56180f810cf2c3576e55c39e
As he notes, mortality and population tables are among the most stable of structural factors in national statistics due to the long range "march" of generations or cohorts. This makes their projection much easier, more robust and accurate.
One approach worth considering would be an agent-based simulation of the difficult-to-identify subpopulations based on mortality data as well as the many other developing country population demographic metrics (e.g., TFR) available from, e.g., the UN, the WHO, etc. ABMs are widely used in simulating complex systems. Here are some papers on ABMs:
https://www.google.com/?gws_rd=ssl#q=agent+based+models


How to demostrate Sub-set from flat is a open set

Question: The set C={(x,y);2< x^2 + y^2 < 4}
How can we defined this set as open using the definition.
Comment: ????????? You can't honestly think that is a comprehensible question, can you?
Comment: Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: What definition of open are you using and what are you trying?  Try Picking a point (a,b) in C.  Then 2 < a^2 + b^2 < 4.  Can you find an open  neighbor around (a,b) in which all the points are in C?  In other which every (x,y) in the neighbor 2 < x^2 + y^2 < 4?  How close to (a,b) do (x,y) have to be for that to be true?  Can you draw pictures?
Answer: This is an annulus in the plane. You want to show that it is open directly from the definition. Therefore, it is enough to show that around any point of the annulus, you can find an open disk containing the point which is wholly contained in the annulus. I will explain a procedure for finding such a disk. The details are left to you.
Pick $p \in C$. We can parameterize $C$ in polar coordinates, and then easily draw the normal line from $p$ to the boundary of $C$, since the polar coordinates tell us the angle of the line through the origin that $p$ lies on. Then the distance along this line from $p$ to either the inside or the outside boundary of $C$ is the minimal distance from $p$ to the boundary. Take half the minimum of these two values. The result is a disk which is guaranteed to be contained in $C$. Since $p$ is arbitrary, every point of $C$ is an interior point, and $C$ is open.
The proof relies on the fact that the definition of $C$ uses $<$ and not $\leq$, as otherwise those values could possibly be $0$, in which case the above method does not work.
Answer: Let $(a,b) \in C $
$2 < a^2 + b^2 < 4$
Let $M = \min (4 - (a^2+b^2), (a^2 + b^2) -2) $
Let $\epsilon = \sqrt { M}/2$.
Let $N =\{(x,y)| d( (x,y), (a,b)) < \epsilon $i.e $|\sqrt {(x-a)^2 - (y-b)^2} < \epsilon\} $
Let $(w,z) \in N$.....
To be continued.....


How to understand the singularity of Green's Theorem?

Question: I'm learning complex analysis right now where I encountered the line integral of $\frac{1}{z}$ over a circle containing the origin, e.g. $\int_{\Gamma}{\frac{1}{z}}dz$, where $\Gamma: z(t) = e^{it}, t \in [0,2\pi]$. This is just the integral $\int_{\Gamma}\frac{-ydx+xdy}{x^2+y^2}$that one should encounter when studying Green's Theorem.
Specifically,$$\int_{\Gamma}{\frac{1}{z}}dz = \int_{\Gamma}{\frac{x-iy}{x^2+y^2}(dx+idy) = (\int_{\Gamma}{\frac{x}{x^2+y^2}}dx+\frac{y}{x^2+y^2}dy}) + i(\int_{\Gamma}{\frac{-y}{x^2+y^2}dx+\frac{x}{x^2+y^2}dy}) = i(\int_{\Gamma}{\frac{-y}{x^2+y^2}dx+\frac{x}{x^2+y^2}dy}) = i2\pi.$$
How do I interpret this singularity at the origin? Physically, we know the Green's theorem is a description of circulation/curl. This singularity seems to say that there is a "source of curl" at the origin in some sense such that even though we have the curl vanishing everywhere except for the origion, we still get nonzero circulation. It smells somewhat like when we integrate the delta function $\delta(x)$ in distribution sense. Is there any connection to this?
This is just my blurry understanding of this scenario. I hope someone could help me completely understand this recurrent singularity in mathematics.
Comment: I think it is very misleading to say the origin is a "source of curl", because like you said, the curl vanishes on all of $\Bbb{R}^2 \setminus \{0\}$ (where the things are actually defined); also Green's/Stokes theorem doesn't even apply in this case. So I think it is very misleading to try to relate the line integral to "curl at the origin" by "invoking" Green's theorem when it doesn't even apply
Comment: @peek-a-boo Yes, I understand your point. But the thing is, there must be some concept like the curl that can be defined at the origin (in some weak sense). Just like how we define the derivative of the Heaviside function at the origin (the delta function).
Comment: Do you know about closed forms and exact forms?
Comment: @AlekosRobotis Not yet. I'm studying differential geometry right now. So hopefully I will see them soon. But I've already seen a few concepts in differential forms, e.g. connection forms, structure equations, etc. You can post your answer using differential forms if you think it's indispensable.
Answer: Sorry for the length, hopefully it is somewhat insightful.
This isn't answering the question exactly as you've posed it, but this is some motivation for studying de Rham Cohomology and differential forms. One interpretation of the importance of this integral is that it detects a topological property of $\mathbb{R}^2\setminus \{(0,0)\}$, namely the puncture at the origin. The absence of a point allows us to define the differential form
$$ \omega=\frac{-y}{r^2}dx+\frac{x}{r^2}dy$$
where $r^2=x^2+y^2$. You can just think of this (for now) as a thing that you can integrate along a path $\gamma$ in the obvious way. Let's say $\gamma$ is the unit circle path around the origin oriented counterclockwise. If there were a function $f$ defined on $\mathbb{R}^2\setminus \{(0,0)\}$ so that $df=\omega$, i.e. $\frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy=\omega$, then by Stokes' Theorem we would get that
$$ \int_\gamma\omega=\int_\gamma df=\int_{\partial \gamma}f=0.$$
Indeed, we can see that this is not the case since we can compute the integral and see that it is nonzero. So, we see that there is no function $f$ with $df=\omega$.
Now, let's say that a differential $1-$form is an expression $fdx+gdy$ for $f,g$ smooth functions on $M=\mathbb{R}^2\setminus \{(0,0)\}$. Let's say that a differential $2-$form is an expression of the form $hdx\wedge dy$ where $h$ is a smooth function, and $\wedge$ is what is known as the wedge product of forms. $\wedge$ has the following properties $dx\wedge dx=dy\wedge dy=0$ and $dx\wedge dy=-dy\wedge dx$. It is also bilinear with respect to smooth functions in the sense that
$$ fdx\wedge gdy=fgdx\wedge dy.$$
Denote the $\mathbb{R}-$vector space of $1-$forms $\Omega^1(M)$ and the $\mathbb{R}-$vector space of $2-$forms by $\Omega^2(M)$. We can define a map $d:\Omega^1(M)\to\Omega^2(M)$ called the exterior derivative using the definition of $df$ above for a smooth function (note the double use of $d$). For a $1-$form $\omega=fdx+gdy$, define
$$ d\omega=df\wedge dx+dg\wedge dy.$$
$d\omega$ is a $2-$form. So, we get a sequence of maps
$$ \mathscr{C}^\infty(M)\xrightarrow{d} \Omega^1(M)\xrightarrow{d}\Omega^2(M).$$
You can check by hand that $d\circ d=0$, in the sense that for any $f\in \mathscr{C}^\infty(M)$, $d(df)=0$. It follows that
$$ \operatorname{im}(d:\mathscr{C}^\infty(M)\to \Omega^1(M))\subseteq \ker(d:\Omega^1(M)\to \Omega^2(M)).$$
In particular, $\operatorname{im}(d)\subseteq \ker(d)$ as a subspace (abbreviating the above notation). So, it makes sense to define
$$ H^1_{\text{dR}}(M)=\frac{\ker(d:\Omega^1(M)\to \Omega^2(M))}{\operatorname{im}(d:\mathscr{C}^\infty(M)\to \Omega^1(M))}$$
to be the first de Rham Cohomology group of $M$. It is nothing more than a quotient of vector spaces (hence a vector space). Recalling what we did before, the form $\omega=-\frac{y}{r^2}dx+\frac{x}{r^2}dy$ does not lie in $\operatorname{im} d$, but it does lie in $\ker d$ as you can check by hand. It follows that
$$ \dim_{\mathbb{R}} H^1_{\text{dR}}(M)\ge 1.$$
So, we have shown that the first de Rham cohomology of the punctured plane is nonzero. Actually, $H^1_{\text{dR}}(M)\cong \mathbb{R}$, but no matter. By the Poincaré Lemma from multivariable calculus of forms (which you will probably see soon) we get that $H^1_{\text{dR}}(\mathbb{R}^2)=0$. A nice property of de Rham Cohomology is that it is preserved under homeomorphism (in fact homotopy equivalence), so that if $M$ and $N$ are appropriate topological spaces, then $M\cong N$ implies $H^1_{\text{dR}}(M)\cong H^1_{\text{dR}}(N)$. As a corollary of this, we can see that $\mathbb{R}^2\setminus \{(0,0)\}$ is not homeomorphic to $\mathbb{R}^2$, since they have distinct first de Rham cohomologies.
The elements of $H^1_{\text{dR}}(M)$ are called cohomology classes. One reason the form $\omega$ in question is significant is that it represents a nontrivial cohomology class generating the first de Rham cohomology of the punctured plane. In particular, if someone asked you to explain why the punctured plane and the plane are distinct intuitively, you would say that the former has a puncture, while the latter does not. At a basic level, the observation that this form integrates to a nonzero value around a closed loop indicates that there is a nontrivial first cohomology class. So, this allows us to formalize the notion of having a puncture. There are other ways to formalize this, and this falls naturally under the heading of algebraic topology.

Now, from a complex analytic perspective, a theorem that will be presented soon in your complex analysis studies (if not already) is the following:

If a holomorphic function $f$ defined on a domain $U\subseteq \mathbb{C}$ has a primitive $F$, then $\oint_\gamma fdz=0$ for all closed contours $\gamma$ contained in $U$.

A primitive is a function $F$ such that $F'=f$.
Now, let's examine $f(z)=\frac{1}{z}$, which is a holomorphic function defined on $\mathbb{C}\setminus \{0\}$ (which is topologically the same as a punctured plane). We actually know, essentially, that its primitive is a "function" called $\log z$. There is an issue here, though. To define $\log z$ in any sensible way, we need to make a branch cut. This means we need to remove a ray emanating from the origin in $\mathbb{C}$ to define $\log z$ in a reasonable way. What this really means is: there is no global primitive for $f(z)=\frac{1}{z}$ on $\mathbb{C}\setminus \{0\}$. This is related to the topological problem we discussed above, since using $z=x+iy$ and $dz=dx+idy$, you can compute that $\frac{1}{z}dz$ is a slightly modified version of our form $\omega$ from before.
Actually, the fact that the de Rham cohomology is $1-$dimensional means that in some sense this is the "only" problem function up to equivalence. This is somewhat illustrated by the fact that $\frac{1}{z^n}$ poses no problem for $n\ge 2$. Indeed, $\frac{1}{z^n}$ has primitive
$$ -\frac{1}{n-1}\cdot \frac{1}{z^{n-1}}$$
valid for $n\ge 2$.


Which Forecast Evaluation Metric To Use?

Question: It is a forecasting problem. I need an evaluation metric which penalizes under-predictions more than over-predictions. Also I want it's range in certain interval (say 0-100), so that it becomes easier for comparison of different models. What could be the possible eval metrics / solutions to this?
I've tried MSE, r2 score, MAPE, WMAPE, AMAPE, SMAPE so far.
Comment: [Some people would argue that you should first understand what the purpose of your forecast is before deciding on an appropriate error metric.](https://dfep.netlify.app/sec-forecasting-workflow) (OK, so I authored that.) So: what are you forecasting *for*?
Comment: OK, but *why*? If you are forecasting for target inventories, then you want a quantile forecast (for some aggregate sales depending on your replenishment schedules), and you can elicit those using a pinball loss: https://stats.stackexchange.com/q/471224/1352
Comment: @StephanKolassa I'm forecasting sales.
Answer: The evaluation function and the scaling are distinct issues in my mind. To me, scaling to $0$-$100$ is straightforward: compare to a reasonable baseline model. This is what the usual $R^2$ does by comparing the square loss of your model to the square loss of a baseline model that always predicts the overall mean (I argue here to use the in-sample mean, a stance supported by the statistics literature). For your time series problem, it might be reasonable to compare to a moving target as you get more information with the longer time series, discussed here with a reference to an article from the Review of Financial Studies. I simulate something like this here. Once you have the performance of your baseline model, you do a familiar calculation.
$$
1-\dfrac{\text{
Performance of your model
}}{\text{
Performance of the baseline model
}} $$$$= \dfrac{\text{
Performance of the baseline model
}-\text{
Performance of your model
}}{\text{
Performance of the baseline model
}}
$$
(It might make more sense if the measure of performance is $0$ when the predictions exactly match the true values; I discuss such an issue here (look for "...annoyingly..."). Most measures of performance will give you this, e.g., square loss, absolute loss, and crossentropy loss.)
A possible issue with an $R^2$-style comparison to a baseline is that it will be less than zero of the performance is worse than the baseline. That breaks from your range, but there is no limit to how bad the predictions can be, so I am not sure there should be a lower bound.
To do this, you have to consider an appropriate way to measure the quality of your model and the baseline. Sim of squared deviations/residuals/errors is a popular choice, as is the sum of the absolute deviations. However, you have mentioned an uneven penalty for missing high and missing low. Quantile loss and tilted square loss (not sure of a common name for it) might fit the bill, as they allow you to give different penalties for missing high by $\delta$ and missing low by $\delta$. Then you calculate the quantile or tilted square loss for your model and the baseline model, sticking those into the expression above to get your scaled score.
I encourage readers to consider the comment by Stephan Kolassa about determining what you want to forecast, too, as that can influence if you want quantile loss, tilted square loss, or something else.
Comment: Scaling is a good thing, and also used in forecasting a lot. However, it will not necessarily map into some predefined interval, like [0,100], or anything else.
Comment: @StephanKolassa I'm struggling to see how what I wrote could lead to a value outside of $\left(-\infty, 1\right]$. Do you have an example of non-negative $x$ and $y$ such that $\frac{y - x}{y}>1?$ (I think $1$ is the least upper bound.) Have I misinterpreted your comment?
Comment: As long as both "performances" are positive, I agree that your result will be no larger than 1. But the OP is asking for something between 0 and 100. Would you feed your result into something arctan-like, then scale and shift? Sure, you can do that and end up in the correct interval... it will just not be interpretable any more.


Python - Using same randint value in different functions within class object

Question: I'm quite new in programming and as an exercise, I wanted to try writing a very basic game.
I will not choke you in details. Let me explain where I'm having trouble.
There are 2 players shooting each other. Each turn they spend random amount of bullets between (1,10) and damage the other, and whoever reaches 0 health loses the game.
Right now, I can call random bullet number to shoot the other player. But I want the damage to be related with the amount of bullet used. For example if player1 used 5 bullets that turn, player2 will be damaged 5*10, or if 2 then damaged 2*10 and etc.
And here is my code. I appreciate any kind of help. Thanks!
import random

bullet_spent = random.randrange(1,10)
damage = bullet_spent * 10

# Enemy object
class Enemy():

    def __init__(self,name,hp,ammo):
        self.name = name
        self.hp = hp
        self.ammo = ammo

# Defined actions
    def attack(self):
        bullet_spent = random.randrange(1,10)
        print(self.name + " Shoots. " + str(bullet_spent) + " bullets spent.")
        self.ammo -= bullet_spent

    def be_damaged(self):
        damage = bullet_spent * 10
        self.hp -= damage
        print(self.name + " lost " + str(damage) + " HP.")
        print("Remaining HP: " + str(self.hp))

# Enemy list
player1 = Enemy("Player1",100,50)
player2 = Enemy("Player2",100,50)

Comment: use `return bullet_spent` in `attack()` and use `spent` in `def be_damaged(self, spent)` and run it as `spent = p1.attack()` and then `p2.be_damaged(spent)` or directly `p2.be_damaged(p1.attack())` (if player1 shoot faster then player2)
Comment: You have two *entirely unrelated* variables named `bullet_spent` here - a local variable in `attack()` that gets deducted from `self.ammo`, but not otherwise used (or even available to be used) for anything, and a global variable that's set once at the start of the code and never changed again (this is what's being used in `be_damaged()`).
Comment: You also are deducting bullets and HP without checking availability.  The number of bullets shot, for example, should be the minimum of your random number and the amount of ammo remaining.
Comment: Thanks for your answer.

What would you suggest me about being able to use the same randint number from attack() and put it inside be_damaged() function in a way that the number will act *10 of that number?
Comment: Does one fighter get to take all of their shots before the other, is it a coin toss who gets the next shot, or do they alternate shots until one of them has HP take down to zero?
Comment: @pjs It's turn based. p1 attacks p2, and then p2 attacks p1 until one of them reaches 0 hp. They both have 50 ammo at the start. And they spend random amount of bullets each turn btw (1,10). But the damage will be amount of bullet spent*10.
Comment: So think about what you described.  My HP gets reduced by my enemy's shooting, and vice-versa, while my bullets are reduced by my shooting.  Shooting should be directed at a specific enemy, should deduct the ammo from my inventory, and should "notify" them how much damage they've suffered based on my shooting.  An enemy notifying me that I've been shot should specify how much damage they've inflicted, and I should reduce my HP accordingly.  Your "main" should be able to query HP after each round, and declare a winner.  Organize your code accordingly.
Answer: You should use return bullet_spent in attack()
def attack(self):

    # rest

    return bullet_spent

and bullet_spent as argument in be_damaged()
def be_damaged(self, bullet_spent):

    # rest

and then you can do get value from one player to another
spend1 = p1.attack()
spend2 = p2.attack()

p1.be_damaged(spend2)
p2.be_damaged(spend1)


Import users from a CSV file

Question: How can I import users fom a CSV file in Drupal 8?
I've found this module but it is not updated for Drupal 8:
https://www.drupal.org/project/user_import
I think that I can make an import directly with a MySQL script but is it possible with Drupal (I know I can insert datas directly into database but I don't know if Drupal system will allow that method)?
I've found this question but it is not exactly what i need :
Importing a bunch of users from csv spreadsheet file into Drupal 8
I import data from a csv file and it is not a migration from a drupal site.
Comment: It doesn't matter if the source isn't a Drupal site. Migrate is designed to work with various datasources, which has great support for CSV files of data.
Answer:
I think that I can make an import directly with a MySQL script but is
  it possible with Drupal (I know I can insert datas directly into
  database but U don't know if Drupal system will allow that method)?

Instead of MySQL this would be a Drupal method to insert users by using the Entity API:
<code>$user = User::create([
  'name' => 'foobar',
  'mail' => 'firstname.lastname@example.com',
  'status' => TRUE,
]);
$user->save();
</code>
So if you don't want to use Migrate there are other ways for such a simple import task. You can use a php library of your choice to fetch the data and then add the user entities one by one. I answered a similar question for importing nodes at a time when Migrate was still in alpha: Is there a way to migrate only nodes?
Answer: To make it with Migrate you need to setup Migrate Plus, Migrate Tools and Migrate Source CSV together, there is lot of examples in the web already:
http://valuebound.com/resources/blog/how-to-migrate-users-from-a-csv-file-drupal-8
https://agencychief.com/blog/drupal-8-csv-migration
https://www.mtech-llc.com/blog/lucas-hedding/migrating-using-csv
Comment: Thank you. It is exactly what i need. Your 3 links are really interesting. I've used the 1st one and it works. The 2nd is based on a custom module and i will  try it. The 3rd is written by the maintainer of the D8 Migrate Source CSV contrib module so it s also an excellent article.
Comment: So i can import a list of users. Now, i have to import datas in a custom module that contains datas related to the user. I see it is possible but didn't try it yet : https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/process-plugin-migration_lookup-formerly-migration
Answer: Here I found the solution for it. Please follow this link https://github.com/steveoliver/user_import and install the extended module.
You can import the user data file through this path (path: '/admin/people/import').
Comment: Interesting. I'll try it. But I see that it only handles fname,lname,email. In @drupalranger answer, there are links that explain how to import custom datas (like job, image, etc.)
Answer: User CSV Import is the module you want.
Migrate is a powerful and robust platform for integrating any arbitrary data source, but User CSV Import is tailor made for uploading CSVs of user data.
https://www.drupal.org/project/user_csv_import
There are other modules, like Bulk User Registration, which are less featureful. For example Bulk User Registration doesn't support any fields - you must manually write code to handle fields.

Import users from a CSV file


Can't we sort a "Node module element"?

Question: I'm creating a new content type named "Portfolio".
Image 1: I put a name to the "Title field label": Project Name

Image 2: That thing works as a 'Node module element' in Fields

Image 3: I can't get the Field to sort it below the Project Image

I even can't get this 'Node module element' from Views (using Views module). The sorting problem is specific to "Teasers" in the portfolio page:

I just want the Project Title to sort a bit so that I can place the title just after the Project Image. I'm familiar with WordPress, but a newbie in Drupal.
Comment: After an answer: I got something that I missed: **About Image 3**, I'm afraid, I missed to say that, in both the "Default" and "Teaser" tab, the title is missing.
Comment: Did you try the Display Suite module?
Answer: There are three ways to go about.
1) Use views. In views the Field to add is Content : Title. (Even if you change the name of the title field it is still title. It is just changing the label on the form.)
2) You can install Display Suite Module. Once you install this module you would get additional fields once you select a layout in the layouts section.

Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files.

3) The third method is to work with the node.tpl.php you have a node object. Since you are using teaser the title would be available in a field. All the other fields can be accessed from the node object.
Answer: In image 3, there is another separate tab for editing the order and display of teasers for your content types.
If your content isn't displaying properly in views as a teaser, you can change the format options in your view to show:Fields instead of show:Content , this will then allow you to add specific fields from your content type, and add custom CSS classes to all of your fields for extra formatting in CSS.
Comment: I'm afraid, I missed to say that, in both the "Default" and "Teaser" tab, the title is missing.
Comment: Yes that is correct, in the manage display tab for a content type, you cannot change the order of the title with other fields.

But if you are only worried about displaying the title below an image while in a view, use fields instead of content:teaser. Then you can set the title field to appear below the image field.
Comment: The [Title Module](https://drupal.org/project/title) might be worth looking into, you can replace the default title with a standard field API, which may allow it to appear on the manage display page.

Can't we sort a "Node module element"?