问:
Check if HangFire.JobStorage is instantiated
I have a ASP.NET MVC Application that works as Hangfire client - it enqueues different jobs.  I am using SqlServerJobStorage for Hangfire usage.

For now i am working on a scenario when there is no connection to Hangfire Database, and somewhere in the future connection is being instantiated.

The goal is that my ASP.NET MVC Application should keep working before this moment. After connection restores it should start to enqueue jobs.

So application will throw an exception in Global.asax:

```<code>Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("EshopServiceHangfire");
</code>```

Moreover all job enqueues will also throw exceptions:

```<code> BackgroundJob.Enqueue<ISomeClass>(x => x.DoSomethingGreat(JobCancellationToken.Null));
</code>```

I put the row from Global.asax in a try/catch block, so it will not throw.
When somebody enqueue job, i want to check JobStorage.Current and if it is not initialized, i`l try to init it again with the same code:

```<code>Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("EshopServiceHangfire");
</code>```

Does anybody knows a way to do this? Documentation has no information about this.

Something like Hangfire.GlobalConfiguration.JobStorage.IsInitialized ?

Catching exception from Job enqueue also is a way, but i don`t like it, because it throws non specific

InvalidOperationException: JobStorage.Current property value has not been initialized. You must set it before using Hangfire Client or Server API.

Much appreciated for those who have read up to this place)

答:
You could use the Hangfire.JobStorage.Current static property itself to check Hangfire storage configuration:

```<code>//InvalidOperationException " JobStorage.Current property value has not been initialized"
var storage = JobStorage.Current;

GlobalConfiguration.Configuration.UsePostgreSqlStorage(vaildConnString);

//no exception
storage = JobStorage.Current;
</code>```

Moreover, you could query a database to test the connection:

```<code>JobStorage.Current.GetConnection().GetRecurringJobs();
</code>```

Considering exceptions, I think that throwing an InvalidOperationException instead of something like SqlException is correct. Hangfire core isolated from details of a specific database.

Body:
I have a ASP.NET MVC Application that works as Hangfire client - it enqueues different jobs.  I am using SqlServerJobStorage for Hangfire usage.

For now i am working on a scenario when there is no connection to Hangfire Database, and somewhere in the future connection is being instantiated.

The goal is that my ASP.NET MVC Application should keep working before this moment. After connection restores it should start to enqueue jobs.

So application will throw an exception in Global.asax:

Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("EshopServiceHangfire");

Moreover all job enqueues will also throw exceptions:

 BackgroundJob.Enqueue<ISomeClass>(x => x.DoSomethingGreat(JobCancellationToken.Null));

I put the row from Global.asax in a try/catch block, so it will not throw.
When somebody enqueue job, i want to check JobStorage.Current and if it is not initialized, i`l try to init it again with the same code:

Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("EshopServiceHangfire");

Does anybody knows a way to do this? Documentation has no information about this.

Something like Hangfire.GlobalConfiguration.JobStorage.IsInitialized ?

Catching exception from Job enqueue also is a way, but i don`t like it, because it throws non specific

InvalidOperationException: JobStorage.Current property value has not been initialized. You must set it before using Hangfire Client or Server API.

Much appreciated for those who have read up to this place)

Body:
You could use the Hangfire.JobStorage.Current static property itself to check Hangfire storage configuration:

//InvalidOperationException " JobStorage.Current property value has not been initialized"
var storage = JobStorage.Current;

GlobalConfiguration.Configuration.UsePostgreSqlStorage(vaildConnString);

//no exception
storage = JobStorage.Current;

Moreover, you could query a database to test the connection:

JobStorage.Current.GetConnection().GetRecurringJobs();

Considering exceptions, I think that throwing an InvalidOperationException instead of something like SqlException is correct. Hangfire core isolated from details of a specific database.


来源: stackexchange

问:
KeyCloak 2.3 getting NPE when exporting
My KeyCloak works with h2 db(default) and has some data in it

i want to export the data so i can migrate KeyCloak to mysql

KeyCloak i'm using is 2.3 version
I keep getting the NPE when trying to export the data.

Command that i'm using for exporting is:

 sudo ./standalone.sh -Dkeycloak.migration.action=export -Dkeycloak.migration.provider=singleFile -Dkeycloak.migration.file=/tmp/export.json

Stacktrace:

```<code>Caused by: java.lang.NullPointerException
at org.keycloak.exportimport.util.ExportUtils.exportRealm(ExportUtils.java:227)
at org.keycloak.exportimport.singlefile.SingleFileExportProvider$1.runExportImportTask(SingleFileExportProvider.java:65)
at org.keycloak.exportimport.util.ExportImportSessionTask.run(ExportImportSessionTask.java:35)
at org.keycloak.models.utils.KeycloakModelUtils.runJobInTransaction(KeycloakModelUtils.java:235)
at org.keycloak.exportimport.singlefile.SingleFileExportProvider.exportModel(SingleFileExportProvider.java:58)
at org.keycloak.exportimport.ExportImportManager.runExport(ExportImportManager.java:102)
at org.keycloak.services.resources.KeycloakApplication.<init>(KeycloakApplication.java:148)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:150)
... 19 more
</code>```

答:
I'm not sure if this is the same issue but I was also getting a Null pointer error when trying to do a default export.

The issue for me was due to not setting the alias for an execution in the authentication flow.
https://issues.jboss.org/browse/KEYCLOAK-2494

Basically to maintain ordering of the exported Json files and keep them versionable keycloak is requiring an alias be set so that it can always do consistent sorting.

https://github.com/keycloak/keycloak/commit/c81d0c0898d7b44c0d053ce6666acdad4967bffc

The fix for me was to set an alias field in the config for the execution through the admin console, annoyingly if you've done any configuration before it won't let you update the alias. You'll have to just delete the execution in the admin console and recreate it.

ContentLicense: CC BY-SA 3.0

Title: KeyCloak 2.3 getting NPE when exporting

Body:
My KeyCloak works with h2 db(default) and has some data in it

i want to export the data so i can migrate KeyCloak to mysql

KeyCloak i'm using is 2.3 version
I keep getting the NPE when trying to export the data.

Command that i'm using for exporting is:

 sudo ./standalone.sh -Dkeycloak.migration.action=export -Dkeycloak.migration.provider=singleFile -Dkeycloak.migration.file=/tmp/export.json

Stacktrace:

Caused by: java.lang.NullPointerException
at org.keycloak.exportimport.util.ExportUtils.exportRealm(ExportUtils.java:227)
at org.keycloak.exportimport.singlefile.SingleFileExportProvider$1.runExportImportTask(SingleFileExportProvider.java:65)
at org.keycloak.exportimport.util.ExportImportSessionTask.run(ExportImportSessionTask.java:35)
at org.keycloak.models.utils.KeycloakModelUtils.runJobInTransaction(KeycloakModelUtils.java:235)
at org.keycloak.exportimport.singlefile.SingleFileExportProvider.exportModel(SingleFileExportProvider.java:58)
at org.keycloak.exportimport.ExportImportManager.runExport(ExportImportManager.java:102)
at org.keycloak.services.resources.KeycloakApplication.<init>(KeycloakApplication.java:148)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:150)
... 19 more


问:
How do you make tooltip show up for longer in IE
i got the following

```<code><span id="pageLink" style="cursor:pointer;" onClick="...." title="<%=pHelper.getNameToolTip()%>">
</code>```

in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.

is there a way to make it last longer?

答:
A simple tooltip can be created with just CSS if you do not mind adding a little HTML.

```<code>.tipLink{
  color:#ff3333;
  cursor:pointer;
  position:relative;
}
.tip{
  position:absolute;
  display:none;
  top:10px;
  left:30px;
  background-color:#dddddd;
  border:1px solid black;
  width:100px;
  color:black;
  -webkit-border-radius:5px 5px 5px 5px;
  -moz-border-radius:5px 5px 5px 5px;
  border-radius:5px 5px 5px 5px;
  text-align:center;
}
.tipLink:hover .tip{
  display:block;
}
</code>```

and the HTML will look like

```<code><div>Select as many as apply
<span class='tipLink'>?
<span class='tip'>Press Ctrl to choose more than one option.</span>
</span>
</div>
<br/>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i got the following

<span id="pageLink" style="cursor:pointer;" onClick="...." title="<%=pHelper.getNameToolTip()%>">

in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.

is there a way to make it last longer?

Body:
A simple tooltip can be created with just CSS if you do not mind adding a little HTML.

.tipLink{
  color:#ff3333;
  cursor:pointer;
  position:relative;
}
.tip{
  position:absolute;
  display:none;
  top:10px;
  left:30px;
  background-color:#dddddd;
  border:1px solid black;
  width:100px;
  color:black;
  -webkit-border-radius:5px 5px 5px 5px;
  -moz-border-radius:5px 5px 5px 5px;
  border-radius:5px 5px 5px 5px;
  text-align:center;
}
.tipLink:hover .tip{
  display:block;
}

and the HTML will look like

<div>Select as many as apply
<span class='tipLink'>?
<span class='tip'>Press Ctrl to choose more than one option.</span>
</span>
</div>
<br/>


问:
JS change image if/else
Im trying to change image when function ends. In IF image should change, and in else, image stays the same.

html

```<code>    <img class="owner" id="regina" src="img/uk-profile.jpg" alt="Great Britain">
  <p class="fort"><b>Fort: </b><span  id="wall">1000</span></p>
</code>```

What i have tried in JS

```<code>function finish(){
    var f = document.getElementById('wall');

    if (f>-1) {
        alert("Battle has been won, you now control the region!");
        var g = document.getElementById('regina').src = "img/us-profile";

    }

     else {
        alert("Battle has been lost!");

     }
}
</code>```

答:
Are you trying to check if the text inside "wall" is bigger than -1? if so, this is the way you should check the innerHTML like this:

```<code>if (f.innerHTML > -1)
</code>```

if you are trying to check if wall exist, just check if f returns true:

```<code>if(f)
</code>```

the changing of the src works, it just always go to the else. changing the code to one of the above should help.

Title: JS change image if/else

Body:
Im trying to change image when function ends. In IF image should change, and in else, image stays the same.

html

Fort: 1000

What i have tried in JS

function finish(){
    var f = document.getElementById('wall');

    if (f>-1) {
        alert("Battle has been won, you now control the region!");
        var g = document.getElementById('regina').src = "img/us-profile";

    }

     else {
        alert("Battle has been lost!");

     }
}

Body:
Are you trying to check if the text inside "wall" is bigger than -1? if so, this is the way you should check the innerHTML like this:

if (f.innerHTML > -1)

if you are trying to check if wall exist, just check if f returns true:

if(f)

the changing of the src works, it just always go to the else. changing the code to one of the above should help.


问:
Catch an uploaded csv file using Django (No models, No forms)
I am failing to catch this uploaded csv file. I just want to upload a file, and store into a variable so I can use it later.

template.html

{% block content %}

File content

                <form action="{% url 'plot:printInfo' %}" method="post" enctype="multipart/form-data">
                     {% csrf_token %}
                    <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />

                    <input type="submit" value="Upload" />
                </form>
            {% endblock %}```
</div>
</div>
</p>

<h3>views.py</h3>

```def printInfo(request):
    #PATH = '/Users/xxxxx_000/Desktop/Django/mysqlApp/plot/data/'
    #data = pd.read_csv(PATH + 'SalesJan2009.csv')

    csvfile = request.FILES['file']

    data = pd.read_csv(csvfile)
    html = data.to_html()

    #method implemented below, It allows to add Id field to an HTML table
    finalString = addIdToHtml(html)

    context = {'TableOfData': finalString,}

    #x and y are lists
    return render(request, 'filter.html', context)
```

<p>When I use</p>

```data = pd.read_csv(PATH + 'SalesJan2009.csv')
```

it works pretty fine. Now all I want to do is to replace 'SalesJan2009.csv' by an uploaded file.  How do I do that?

答:
Assuming that you're using pandas.. If you need to replace file content, try following:

```<code>def printInfo(request):
    path = '/Users/xxxxx_000/Desktop/Django/mysqlApp/plot/data/'
    # data = pd.read_csv(PATH + 'SalesJan2009.csv')
    csvfile = request.FILES['file']

    data = pd.read_csv(csvfile)
    html = data.to_html()

    finalString = addIdToHtml(html)
    context = {
        'TableOfData': finalString,
    }

    file_name = path + 'SalesJan2009.csv'
    data.to_csv(file_name, sep='\t', encoding='utf-8', mode='w')

    return render(request, 'filter.html', context)
</code>```

Please note, that existing SalesJan2009.csv file will be erased and populated with new data. You'll need to do some validation for it(new data) before saving.

Body:
I am failing to catch this uploaded csv file. I just want to upload a file, and store into a variable so I can use it later.

template.html

{% block content %}

File content

                <form action="{% url 'plot:printInfo' %}" method="post" enctype="multipart/form-data">
                     {% csrf_token %}
                    <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />

                    <input type="submit" value="Upload" />
                </form>
            {% endblock %}

views.py

def printInfo(request):
    #PATH = '/Users/xxxxx_000/Desktop/Django/mysqlApp/plot/data/'
    #data = pd.read_csv(PATH + 'SalesJan2009.csv')

    csvfile = request.FILES['file']

    data = pd.read_csv(csvfile)
    html = data.to_html()

    #method implemented below, It allows to add Id field to an HTML table
    finalString = addIdToHtml(html)

    context = {'TableOfData': finalString,}

    #x and y are lists
    return render(request, 'filter.html', context)

When I use

data = pd.read_csv(PATH + 'SalesJan2009.csv')

it works pretty fine. Now all I want to do is to replace 'SalesJan2009.csv' by an uploaded file.  How do I do that?

Body:
Assuming that you're using pandas.. If you need to replace file content, try following:

def printInfo(request):
    path = '/Users/xxxxx_000/Desktop/Django/mysqlApp/plot/data/'
    # data = pd.read_csv(PATH + 'SalesJan2009.csv')
    csvfile = request.FILES['file']

    data = pd.read_csv(csvfile)
    html = data.to_html()

    finalString = addIdToHtml(html)
    context = {
        'TableOfData': finalString,
    }

    file_name = path + 'SalesJan2009.csv'
    data.to_csv(file_name, sep='\t', encoding='utf-8', mode='w')

    return render(request, 'filter.html', context)

Please note, that existing SalesJan2009.csv file will be erased and populated with new data. You'll need to do some validation for it(new data) before saving.


答:
If you want to see if wall is more than -1, in your case is 1000, than you need to take value from that element and convert it to a number

Like this:

```<code>function finish(){
    var f = document.getElementById('wall').innerHTML;
    f = parseInt(f)

    if (f>-1) {
        alert("Battle has been won, you now control the region!");
        var g = document.getElementById('regina').src = "img/us-profile.src";
    }

     else {
        alert("Battle has been lost!");
     }
}
</code>```

Title: JS change image if/else

Body:
If you want to see if wall is more than -1, in your case is 1000, than you need to take value from that element and convert it to a number

Like this:

function finish(){
    var f = document.getElementById('wall').innerHTML;
    f = parseInt(f)

    if (f>-1) {
        alert("Battle has been won, you now control the region!");
        var g = document.getElementById('regina').src = "img/us-profile.src";
    }

     else {
        alert("Battle has been lost!");
     }
}


问:
Does CISCO ASA configuration "access-list" protocol name "ip" includes both "tcp" and "udp"?
I have several lines and I wonder if some are shadowed due to this?</p>

答: yes, but it doesnt include protocols like gre etc, if you need vpn tunnels or something similar</p>


问:
Linkedin link share not getting title and description
I am following instructions from linkedin from http://help.linkedin.com/app/answers/detail/a_id/46687/ft/eng

I am using following tags

```<code><meta property="og:title" content="Title of the article"/>
<meta property="og:image" content="http://media.example.com/ 1234567.jpg"/>
<meta property="og:description" content="Description that will show in the preview"/>
<meta property="og:url" content="http://www.example.com/URL of the article" />
</code>```

Problem:

My title, description and image are working perfectly on Facebook but LinkedIn not detecting these information.

答:
It's because Linkedin have an intern cache.
You just have to add your link and add after '?1'

Exemple:
    www.mywebsite.com?1

And the new meta desc is add automatically.

Body:
I am following instructions from linkedin from http://help.linkedin.com/app/answers/detail/a_id/46687/ft/eng

I am using following tags

<meta property="og:title" content="Title of the article"/>
<meta property="og:image" content="http://media.example.com/ 1234567.jpg"/>
<meta property="og:description" content="Description that will show in the preview"/>
<meta property="og:url" content="http://www.example.com/URL of the article" />

Problem:

My title, description and image are working perfectly on Facebook but LinkedIn not detecting these information.


问:
Enforce strict consistency spanning multiple aggregates
Consider the following business requirements:

We have players which can play games. A player can play only one game at a time. A game needs two players.

The system will contain millions of players, and games take about two minutes. Concurrency issues are likely to emerge.

We want to comply to the rule that a single transaction involves a single aggregate. Further, eventual consistency must not lead to accepted games which must be cancelled afterwards (even if a short period of time) due to concurrency issues. Thus, eventual consistency is not really appropriate.

How do we need to define the aggregates and their boundaries to enforce these business rules?

I conceived two approaches:

1. Event-based handshake

Aggregate Player, aggregate Game.

When a game is requested, it pushed a GameRequested-event. The Players subscribe this event and respond with a corresponding event, either GamePlayerAccepted or GamePlayerRejected. Only if both Players have accepted, the Game starts (GameStarted).

Pros:

The aggregate Player is responsible for managing his own availability which corresponds to the domain model

Cons:

The responsibility of starting a Game is scattered throughout multiple aggregates (it seems like "fake"-eventual-consistency)

Much communication overhead

Consistency measures needed, e.g. freeing up the Players if something went wrong

2. Collection-aggregate

Aggregate Player, aggregate GamesManager (with a collection of value-objects ActiveGamePlayers), aggregate Game.

The GameManager is requested to start a new Game with two given Players. The GameManager is able to ensure that a Player only plays once at a time since it's a single aggregate.

Pros:

No consistency-enforcing events such as GamePlayerAccepted, GamePlayerRejected and so forth

Cons:

The domain model seems obscured

The responsibility of the Player to manage availability shifted

We have to ensure that only one instance of GameManager is created and introduce domain-mechanisms which let the client not worry about the intermediary-aggregate

Independent Game-starts disrupt each other because the GameManager-aggregate locks itself

Need for performance optimization since the GameManager-aggregate collects all active game players which will be tens of millions

It seems like none of these approaches are appropriate to solve the problem. I don't know how to set the boundaries to ensure both strict consistency and clarity of the model, and performance.

答:
I would go with the event-based handshake and this is how I would implement:

From what I understand you would need a Game process implemented as a Saga. You will also have to define a Player aggregate, a RequestGame command, a GameRequested event, a GameAccepted event, a GameRejected event, a MarkGameAsAccepted command, a MarkGameAsRejected command, a GameStarted event and a GameFailed event.

So, when the Player A want's to play a game with Player B, Player A receives the RequestGame command. If this player is playing something else then a PlayerAlreadyPlaysAGame exception is thrown, otherwise it raises the GameRequested event and update it's internal state as playing.

The Game saga catches the GameRequested event and send the RequestGame command to the Player B aggregate (this is a Player aggregate with ID equal to A). Then:

If the Player B is playing another game (it knows this by querying its internal playing state) then it raises the GameRejected event; the Game saga catches this event and send a MarkGameAsRejected command to Player A; then Player A raises the GameFailed event and updates its internal state as not_playing.

If the Player B is not playing another game then it raises the GameAccepted event; the Game saga catches this event and send the MarkGameAsAccepted command to Player A aggregate; Player A then emits the GameStarted event and update its internal state as playing.

In order to understand this you should try to model the use-case as if no computers would exist and players would be humans that communicate over printed mail.

This solution is scalable and I understand that this is required.

The other solution doesn't seem doable for milion of players.

A third solution would be to use a colection of active players in a SQL table or a NoSQL colection, without using the Aggregate tactical pattern. For concurency, when setting a pair of players as active, you could use optimistick locking  or transactions where supported (low scalable) or two-phase commits (kind of ugly).


问:
Hamburger toggle icon is not displayed properly.
I am trying to develop an android app which has an ActionBarDrawerToggle hamburger icon. Everything works fine but the hamburger icon is not displayed properly. Its clipped off from the top as you can see in the image. I have tried to adjust the height of the toolbar but no use. Is it something wrong with my layout file, kindly suggest. Below is my main activity file and the image file

<android.support.v4.widget.DrawerLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start"
    tools:context="com.example.xxx.zzz.MainActivity">

    <android.support.design.widget.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/navView"
        app:menu="@menu/drawer_menu"
        app:headerLayout="@layout/header_layout"
        android:layout_gravity="start"
        >

    </android.support.design.widget.NavigationView>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:fitsSystemWindows="true"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/mtoolbar"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:background="@color/colorPrimary"
        android:layout_height="60dp"
        app:layout_collapseMode="pin"
        android:elevation="5dp"
        android:minHeight="?attr/actionBarSize"
        app:theme="?actionBarTheme"
        />

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:background="?attr/colorPrimary"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        >

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:titleEnabled="false"
            app:expandedTitleTextAppearance="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/backdrop"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:scaleType="centerCrop"
                    android:src="@drawable/tea2"
                    app:layout_collapseMode="parallax"
                    app:layout_collapseParallaxMultiplier="0.7"
                    />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/text_view_products"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Our Products"
                        android:textColor="@android:color/black"
                        android:textSize="@dimen/backdrop_title" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Buy online!"
                        android:textStyle="italic"
                        android:textColor="@android:color/black"
                        android:textSize="@dimen/backdrop_subtitle" />

                </LinearLayout>
            </RelativeLayout>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/card_view" />

</android.support.design.widget.CoordinatorLayout>

</android.support.v4.widget.DrawerLayout>```

enter image description here

答:
There was a  small mistake on my part. I needed to put the navigation view part after the coordinator layout part. On doing that it works fine. Modified code follows:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start"
    tools:context="com.example.himangshugogoi.bcd.MainActivity">

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:fitsSystemWindows="true"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/mtoolbar"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:background="@color/colorPrimary"
        android:layout_height="60dp"
        app:layout_collapseMode="pin"
        android:elevation="5dp"
        android:minHeight="?attr/actionBarSize"
        app:popupTheme="@layout/toolbar_layout"
        app:theme="?actionBarTheme"
        />

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:background="?attr/colorPrimary"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        >

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:titleEnabled="false"
            app:expandedTitleTextAppearance="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/backdrop"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:scaleType="centerCrop"
                    android:src="@drawable/tea2"
                    app:layout_collapseMode="parallax"
                    app:layout_collapseParallaxMultiplier="0.7"
                    />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/text_view_products"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Our Products"
                        android:textColor="@android:color/black"
                        android:textSize="@dimen/backdrop_title" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Buy online!"
                        android:textStyle="italic"
                        android:textColor="@android:color/black"
                        android:textSize="@dimen/backdrop_subtitle" />

                </LinearLayout>
            </RelativeLayout>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/card_view" />

</android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/navView"
        app:menu="@menu/drawer_menu"
        app:headerLayout="@layout/header_layout"
        android:layout_gravity="start"
        />

</android.support.v4.widget.DrawerLayout>```

Body:
I am trying to develop an android app which has an ActionBarDrawerToggle hamburger icon. Everything works fine but the hamburger icon is not displayed properly. Its clipped off from the top as you can see in the image. I have tried to adjust the height of the toolbar but no use. Is it something wrong with my layout file, kindly suggest. Below is my main activity file and the image file

<android.support.v4.widget.DrawerLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start"
    tools:context="com.example.xxx.zzz.MainActivity">

    <android.support.design.widget.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/navView"
        app:menu="@menu/drawer_menu"
        app:headerLayout="@layout/header_layout"
        android:layout_gravity="start"
        >

    </android.support.design.widget.NavigationView>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:fitsSystemWindows="true"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/mtoolbar"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:background="@color/colorPrimary"
        android:layout_height="60dp"
        app:layout_collapseMode="pin"
        android:elevation="5dp"
        android:minHeight="?attr/actionBarSize"
        app:theme="?actionBarTheme"
        />

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:background="?attr/colorPrimary"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        >

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:titleEnabled="false"
            app:expandedTitleTextAppearance="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/backdrop"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:scaleType="centerCrop"
                    android:src="@drawable/tea2"
                    app:layout_collapseMode="parallax"
                    app:layout_collapseParallaxMultiplier="0.7"
                    />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/text_view_products"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Our Products"
                        android:textColor="@android:color/black"
                        android:textSize="@dimen/backdrop_title" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Buy online!"
                        android:textStyle="italic"
                        android:textColor="@android:color/black"
                        android:textSize="@dimen/backdrop_subtitle" />

                </LinearLayout>
            </RelativeLayout>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/card_view" />

</android.support.design.widget.CoordinatorLayout>

</android.support.v4.widget.DrawerLayout>

enter image description here

Body:
There was a  small mistake on my part. I needed to put the navigation view part after the coordinator layout part. On doing that it works fine. Modified code follows:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start"
    tools:context="com.example.himangshugogoi.bcd.MainActivity">

    <!--<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    </LinearLayout>-->

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:fitsSystemWindows="true"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/mtoolbar"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:background="@color/colorPrimary"
        android:layout_height="60dp"
        app:layout_collapseMode="pin"
        android:elevation="5dp"
        android:minHeight="?attr/actionBarSize"
        app:popupTheme="@layout/toolbar_layout"
        app:theme="?actionBarTheme"
        />

    <!-- android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" -->
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:background="?attr/colorPrimary"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        >

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:titleEnabled="false"
            app:expandedTitleTextAppearance="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/backdrop"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:scaleType="centerCrop"
                    android:src="@drawable/tea2"
                    app:layout_collapseMode="parallax"
                    app:layout_collapseParallaxMultiplier="0.7"
                    />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/text_view_products"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Our Products"
                        android:textColor="@android:color/black"
                        android:textSize="@dimen/backdrop_title" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Buy online!"
                        android:textStyle="italic"
                        android:textColor="@android:color/black"
                        android:textSize="@dimen/backdrop_subtitle" />

                </LinearLayout>
            </RelativeLayout>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/card_view" />

</android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/navView"
        app:menu="@menu/drawer_menu"
        app:headerLayout="@layout/header_layout"
        android:layout_gravity="start"
        />

</android.support.v4.widget.DrawerLayout>


问:
Over current context presentation with gestures
I am trying to implement the functionality of Youtube's video player. ATM I have a FloatingViewController (the video player) which gets presented modally (overCurrentContext) on a MainViewController which has it's definesPresentationContext set to true.

Everything works fine except the touch recognition (no scrolling) on the MainViewController when I pull down the player into minimized mode. I am pretty sure that this is happening because the FloatingViewController's view (with a clear background) is over every view in the MainVC as it got presented over it.

Mostly looking for any solutions or workarounds...

Yellow thingy is the FloatingVC. The rest is MainVC...

答: The problem was (as I've mentioned) another view (a UITransitionView) underlying the FloatingVC. This view is there because of the present(...) method call. Fixed it by using addChildVC instead and also animating the addition of the VC's view...


问:
Testing containerized microservice with external dependency
So I built a REST API microservice which queries a local Elasticsearch instance and translates the results according to an internal protocol. I built it into a Docker image and I would like to run some unit tests on it in build. Being ES connected to a private Docker network, it isn't reachable by the microservice during build, so the tests obviously fail. I was wondering, is there a way around this situation without having to use some complicated testing framework to do dependency injection? How do you test this kind of containers in your work practice?</p>

答:
I would build the application without any testing. Then I would test it using docker run so you can take the docker network advantages.

Roughly this is more elegant than test in the middle of the build:

docker build -t my_app:1.0-early your application in order to obtain an image.

docker run --network my_test_network my_app:1.0-early /run_test_cases.sh. Return the properly exit code or text.

Depending on the success or not of the test, re tag: docker tag my_app:1.0

You will need to have already created a docker network (docker network create my_test_network), or better use docker-compose.


问:
Count number of shared observations between samples using dplyr
I have a list of observations grouped by samples. I want to find the samples that share the most identical observations. An identical observation is where the start and end number are both matching between two samples. I'd like to use R and preferably dplyr to do this if possible.
I've been getting used to using dplyr for simpler data handling but this task is beyond what I am currently able to do. I've been thinking the solution would involve grouping the start and end into a single variable: group_by(start,end) but I also need to keep the information about which sample each observation belongs to and compare between samples.

example:

```<code>sample  start   end
a   2   4
a   3   6
a   4   8
b   2   4
b   3   6
b   10  12
c   10  12
c   0   4
c   2   4
</code>```

Here samples a, b and c share 1 observation (2, 4)
sample a and b share 2 observations (2 4, 3 6)
sample b and c share 2 observations (2 4, 10 12)
sample a and c share 1 observation (2 4)

I'd like an output like:

```<code>abc 1
ab 2
bc 2
ac 1
</code>```

and also to see what the shared observations are if possible:

```<code>abc 2 4
ab 2 4
ab 3 6
</code>```

etc

Thanks in advance

答:
Here is an idea via base R, </p>

```<code>final_d <- data.frame(count1 = sapply(Filter(nrow, split(df, list(df$start, df$end))), nrow),
                      pairs1 = sapply(Filter(nrow, split(df, list(df$start, df$end))), function(i) paste(i[[1]], collapse = '')))

#      count1 pairs1
#0.4        1      c
#2.4        3    abc
#3.6        2     ab
#4.8        1      a
#10.12      2     bc
</code>```

Body:
I have a list of observations grouped by samples. I want to find the samples that share the most identical observations. An identical observation is where the start and end number are both matching between two samples. I'd like to use R and preferably dplyr to do this if possible.
I've been getting used to using dplyr for simpler data handling but this task is beyond what I am currently able to do. I've been thinking the solution would involve grouping the start and end into a single variable: group_by(start,end) but I also need to keep the information about which sample each observation belongs to and compare between samples.

example:

sample  start   end
a   2   4
a   3   6
a   4   8
b   2   4
b   3   6
b   10  12
c   10  12
c   0   4
c   2   4

Here samples a, b and c share 1 observation (2, 4)
sample a and b share 2 observations (2 4, 3 6)
sample b and c share 2 observations (2 4, 10 12)
sample a and c share 1 observation (2 4)

I'd like an output like:

abc 1
ab 2
bc 2
ac 1

and also to see what the shared observations are if possible:

abc 2 4
ab 2 4
ab 3 6

etc

Thanks in advance

Body:
Here is an idea via base R,

final_d <- data.frame(count1 = sapply(Filter(nrow, split(df, list(df$start, df$end))), nrow),
                      pairs1 = sapply(Filter(nrow, split(df, list(df$start, df$end))), function(i) paste(i[[1]], collapse = '')))

#      count1 pairs1
#0.4        1      c
#2.4        3    abc
#3.6        2     ab
#4.8        1      a
#10.12      2     bc


问:
Is it bad to have your test and production environments on the same machine?
Would it be bad to have things set up so that MySite.com is production and test.MySite.com is test?  Both running off the same machine.  The site doesn't get a lot of traffic.

UPDATE

I am talking about an ASP.NET web application running on a Windows server.

答: It'd be really hard to test whether environment updates (new version of php/perl/python/apache/kernel/whatever) with test and production on the same machine.</p>


问:
Angular 4 - using if else in template error
I am displaying posts with their comments, and for posts with no comments I would like to display a message that there are no comments for that post, so I have tried to set it up like this:

```<code><li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.Summary }}
      <ul *ngIf="currentPost == post && commentsVisible">
        <li *ngIf="currentPost.comments.length > 0;else message" *ngFor="let comment of currentPost.comments" class="comment">
            <p>{{ comment.Name }}</p>
            <p>{{ comment.TemplateName }}</p>
            <p>{{ comment.CreatedByUserName }}</p>
            <p>{{ comment.Preview }}</p>
        </li>
        <ng-template #message>No comments for {{ post.Title }}</ng-template>
      </ul>
  </li>
</code>```

I get an error:

```<code>Unhandled Promise rejection: Template parse errors:
Can't have multiple template bindings on one element. Use only one attribute named 'template'
</code>```

答:
I believe this slight change might resolve the issue for you. Let me know. If not maybe a quick plunker would help.</p>

```<code><li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.Summary }}
      <ul *ngIf="currentPost == post && commentsVisible">
        <li *ngFor="let comment of currentPost.comments" class="comment">
            <div *ngIf="currentPost.comments.length > 0;else message">
              <p>{{ comment.Name }}</p>
              <p>{{ comment.TemplateName }}</p>
              <p>{{ comment.CreatedByUserName }}</p>
              <p>{{ comment.Preview }}</p>
            </div>
           <ng-template #message>No comments for {{ post.Title }}</ng-template>
        </li>
      </ul>
  </li>
</code>```

Body:
I am displaying posts with their comments, and for posts with no comments I would like to display a message that there are no comments for that post, so I have tried to set it up like this:

      {{ post.Summary }}

 0;else message" *ngFor="let comment of currentPost.comments" class="comment">

{{ comment.Name }}

{{ comment.TemplateName }}

{{ comment.CreatedByUserName }}

{{ comment.Preview }}

        <ng-template #message>No comments for {{ post.Title }}</ng-template>

I get an error:

Unhandled Promise rejection: Template parse errors:
Can't have multiple template bindings on one element. Use only one attribute named 'template'

Body:
I believe this slight change might resolve the issue for you. Let me know. If not maybe a quick plunker would help.

<li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.Summary }}
      <ul *ngIf="currentPost == post && commentsVisible">
        <li *ngFor="let comment of currentPost.comments" class="comment">
            <div *ngIf="currentPost.comments.length > 0;else message">
              <p>{{ comment.Name }}</p>
              <p>{{ comment.TemplateName }}</p>
              <p>{{ comment.CreatedByUserName }}</p>
              <p>{{ comment.Preview }}</p>
            </div>
           <ng-template #message>No comments for {{ post.Title }}</ng-template>
        </li>
      </ul>
  </li>


问:
Implementing Sparse Arrays
Q: There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

Sample Input

[Main List]

4

aba

baba

aba

xzxb

[Query]

3

aba

xzxb

ab

Sample Output

2 (aba appears twice appear in the main list)

1 (xzxb appears once in the main list)

0 (ab doesn't appear in the main list)

My Code

```<code>import java.util.*;

public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

int N = scan.nextInt(); // CONTAINS N number of String
String word[] = new String[N]; //Sets N as size of an array

for(int i = 0; i < N; i++){
    word[i] = scan.nextLine();//Stores a word in every index of an array

}

scan.nextLine(); //Flush index??(need help?!)

 int Q = scan.nextInt(); // Stores number of query
   String searchWord[] = new String[Q];//integer for size of query array
    for(int i = 0; i <Q; i++){
        searchWord[i] = scan.nextLine(); // stores query array for comparison
    }

   int counter = 0; // initializing counter

   for(int i=0; i <Q; i++){//Take a query word and check if it exists in word[]
       for(int j =0; j <N; j++ ){//searches for the query word in main List
           if(word[j] == searchWord[i]){// if it exists counter value adds +1
               counter++;
           }
       }
       System.out.println(counter); //print counter
       counter = 0; // reset counter

   }
    }
}
</code>```

First of all the code does NOT work although the logic is seemingly correct (i guess). Also can someone explain me why we need to consume newline left-over by doing

input.nextLine();

src: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Question : https://www.hackerrank.com/challenges/sparse-arrays

^^ And how do I use it in my question. Thank you! :)

答:
c# implementation but can be easily translated to java`
'

```<code>int totalInputs = Convert.ToInt16(Console.ReadLine());
            Dictionary<string, int> dict = new Dictionary<string, int>();
            for(i = 0; i< totalInputs;i++)
            {
                string input = Console.ReadLine();
                if(dict.ContainsKey(input))
                {
                    dict[input]++;
                }
                else
                {
                    dict.Add(input, 1);
                }
            }
            int queries = Convert.ToInt16(Console.ReadLine());
            string[] queryString = new string[queries];
            for(i=0;i<queries;i++)
            {
                queryString[i] = Console.ReadLine();
            }
            foreach(string str in queryString)
            {
                if(dict.ContainsKey(str))
                {
                    Console.WriteLine(dict[str]);
                }
                else
                {
                    Console.WriteLine(0);
                }
            }
</code>```

`

Title: Implementing Sparse Arrays

Body:
Q: There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

Sample Input

[Main List]

4

aba

baba

aba

xzxb

[Query]

3

aba

xzxb

ab

Sample Output

2 (aba appears twice appear in the main list)

1 (xzxb appears once in the main list)

0 (ab doesn't appear in the main list)

My Code

import java.util.*;

public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

int N = scan.nextInt(); // CONTAINS N number of String
String word[] = new String[N]; //Sets N as size of an array

for(int i = 0; i < N; i++){
    word[i] = scan.nextLine();//Stores a word in every index of an array

}

scan.nextLine(); //Flush index??(need help?!)

 int Q = scan.nextInt(); // Stores number of query
   String searchWord[] = new String[Q];//integer for size of query array
    for(int i = 0; i <Q; i++){
        searchWord[i] = scan.nextLine(); // stores query array for comparison
    }

   int counter = 0; // initializing counter

   for(int i=0; i <Q; i++){//Take a query word and check if it exists in word[]
       for(int j =0; j <N; j++ ){//searches for the query word in main List
           if(word[j] == searchWord[i]){// if it exists counter value adds +1
               counter++;
           }
       }
       System.out.println(counter); //print counter
       counter = 0; // reset counter

   }
    }
}

First of all the code does NOT work although the logic is seemingly correct (i guess). Also can someone explain me why we need to consume newline left-over by doing

input.nextLine();

src: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Question : https://www.hackerrank.com/challenges/sparse-arrays

^^ And how do I use it in my question. Thank you! :)

Body:
c# implementation but can be easily translated to java`
'

int totalInputs = Convert.ToInt16(Console.ReadLine());
            Dictionary<string, int> dict = new Dictionary<string, int>();
            for(i = 0; i< totalInputs;i++)
            {
                string input = Console.ReadLine();
                if(dict.ContainsKey(input))
                {
                    dict[input]++;
                }
                else
                {
                    dict.Add(input, 1);
                }
            }
            int queries = Convert.ToInt16(Console.ReadLine());
            string[] queryString = new string[queries];
            for(i=0;i<queries;i++)
            {
                queryString[i] = Console.ReadLine();
            }
            foreach(string str in queryString)
            {
                if(dict.ContainsKey(str))
                {
                    Console.WriteLine(dict[str]);
                }
                else
                {
                    Console.WriteLine(0);
                }
            }

`


问:
MYSQL how to connect with PHP
I need to insert data into the database, but the error. Can someone help me?
.............

CONEXAO.PHP

```<code>$banco = "*****";
$usuario = "*****";
$senha = "*****";
$hostname = "*****";

$conn = mysql_connect($hostname,$usuario,$senha); mysql_select_db($banco) or die( "Não foi possível conectar ao banco MySQL");

if (!$conn) {echo "Não foi possível conectar ao banco MySQL.
"; exit;}
else {echo "Parabéns!! A conexão ao banco de dados ocorreu normalmente!.
";}
mysql_close();
</code>```

......................

CADASTRADO.PHP

```<code>include "conexao.php";
$consulta = "SELECT * FROM servicos";
$con = $conn ->query($consulta) or die ($conn->error); (((error in this line)))
</code>```

...............

MSG ERROR

```<code>Parabéns!! A conexão ao banco de dados ocorreu normalmente!. (CONECTION OK)

Fatal error: Call to a member function query() on resource in /var/www/html/paranalocal.com.br/web/servicos.php on line 4
</code>```

答:
To use mysqli functions you need to create a connection to the database using mysqli.

Replace mysql_connect with the following:

```<code>$conn = new mysqli($hostname , $usuario, $senha, $banco);
</code>```

Title: MYSQL how to connect with PHP

Body:
I need to insert data into the database, but the error. Can someone help me?
.............

CONEXAO.PHP

$banco = "*****";
$usuario = "*****";
$senha = "*****";
$hostname = "*****";

$conn = mysql_connect($hostname,$usuario,$senha); mysql_select_db($banco) or die( "Não foi possível conectar ao banco MySQL");

if (!$conn) {echo "Não foi possível conectar ao banco MySQL.
"; exit;}
else {echo "Parabéns!! A conexão ao banco de dados ocorreu normalmente!.
";}
mysql_close();

......................

CADASTRADO.PHP

include "conexao.php";
$consulta = "SELECT * FROM servicos";
$con = $conn ->query($consulta) or die ($conn->error); (((error in this line)))

...............

MSG ERROR

Parabéns!! A conexão ao banco de dados ocorreu normalmente!. (CONECTION OK)

Fatal error: Call to a member function query() on resource in /var/www/html/paranalocal.com.br/web/servicos.php on line 4

Body:
To use mysqli functions you need to create a connection to the database using mysqli.

Replace mysql_connect with the following:

$conn = new mysqli($hostname , $usuario, $senha, $banco);


问:
Trying to 'Go Live' with our DocuSign integration but no audit logs and "Review Failed"
We have created a DocuSign integration within our Microsoft Word add-in using the C# wrapper library from GitHub (compiled version: v1.6.1.0) and we are now trying to 'Go Live' by following the instructions here.

Unfortunately we have performed 20+ test transactions as required but we cannot see them in the audit logs and when we proceed with the process of reviewing the transactions - the system eventually returns "Review Failed".

We checked the account details (urls + keys) and everything matches.

In our audit logs we cannot see any of the recent activity...

Any idea what we are doing wrong?

答:
You may need to Enable API Request Logging :
https://support.docusign.com/en/articles/API-Request-Logging</p>


问:
Imported a WordPress database to a new host now site doesn't show up
I made a site on one host (bluehost) and now the client wants it on another host (starlogic). Here is what I did:

Exported the database tables from bluehost and imported them into the database created on the starlogic server.

I replaced all of the old domain name references in the sql file with the new domain.

I installed the WordPress theme on the new starlogic server which was created on the old bluehost server.

Before I imported the old database info into the new database the site would show up (without any of the created pages or content of course). After I imported the database info I can get into the WordPress backend but when I go to view the actual site nothing shows up, just a blank white screen.

I am not sure what code if any would be helpful to see so just let me know and I was post it.

答:
I also have this problem. One more place you need to look at is:

```<code>current_theme
</code>```

in export sql file. It pointed to a theme that doesn't exist in the new server.

Body:
I also have this problem. One more place you need to look at is:

current_theme

in export sql file. It pointed to a theme that doesn't exist in the new server.


问:
How to play an android notification sound
I was wondering how I could play a notification sound without playing it over the media stream.  Right now I can do this via the media player, however I don't want it to play as a media file, I want it to play as a notification or alert or ringtone.  heres an example of what my code looks like right now:</p>

```<code>MediaPlayer mp = new MediaPlayer();
mp.reset();
mp.setDataSource(notificationsPath+ (String) apptSounds.getSelectedItem());
mp.prepare();
mp.start();
</code>```

答: You can use Notification and NotificationManager to display the notification you want. You can then customize the sound you want to play with your notification.</p>

Body:
I was wondering how I could play a notification sound without playing it over the media stream.  Right now I can do this via the media player, however I don't want it to play as a media file, I want it to play as a notification or alert or ringtone.  heres an example of what my code looks like right now:

MediaPlayer mp = new MediaPlayer();
mp.reset();
mp.setDataSource(notificationsPath+ (String) apptSounds.getSelectedItem());
mp.prepare();
mp.start();


问:
Bootstrap - Dropdown and mobile menu doesn't work
I'm developing a wordpress website and I'm using bootstrap.

My menu have to allow dropdown menu but when I click it don't open nothing but if I inspect the code the
 are there.

In mobile the toggle shows but I can't open when click. I see dom change when o click but nothing show.

My html is this and the menu shows perfectly in large screens.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

           <img alt="site" src="<?php bloginfo('template_url')?>/images/logo.png">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="true">
                    Toggle navigation

                  </button>

Empresa

Produção

Produção

Equipamentos

Mercados

Qualidade e Ambiente

Qualidade

Ambiente

Notícias

Contactos

```

答:
First of all you need to import jquery in your page. Then try again and show what happens</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

Body:
First of all you need to import jquery in your page. Then try again and show what happens

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


问:
Why does a call to `fn pop(&mut self) -> Result<T, &str>` continue to borrow my data structure?
I am developing some basic data structures to learn the syntax and Rust in general. Here is what I came up with for a stack:

```<code>#[allow(dead_code)]
mod stack {
    pub struct Stack<T> {
        data: Vec<T>,
    }

    impl<T> Stack<T> {
        pub fn new() -> Stack<T> {
            return Stack { data: Vec::new() };
        }

        pub fn pop(&mut self) -> Result<T, &str> {
            let len: usize = self.data.len();

            if len > 0 {
                let idx_to_rmv: usize = len - 1;
                let last: T = self.data.remove(idx_to_rmv);
                return Result::Ok(last);
            } else {
                return Result::Err("Empty stack");
            }
        }

        pub fn push(&mut self, elem: T) {
            self.data.push(elem);
        }

        pub fn is_empty(&self) -> bool {
            return self.data.len() == 0;
        }
    }
}

mod stack_tests {
    use super::stack::Stack;

    #[test]
    fn basics() {
        let mut s: Stack<i16> = Stack::new();

        s.push(16);
        s.push(27);

        let pop_result = s.pop().expect("");

        assert_eq!(s.pop().expect("Empty stack"), 27);
        assert_eq!(s.pop().expect("Empty stack"), 16);

        let pop_empty_result = s.pop();

        match pop_empty_result {
            Ok(_) => panic!("Should have had no result"),
            Err(_) => {
                println!("Empty stack");
            }
        }

        if s.is_empty() {
            println!("O");
        }
    }
}
</code>```

I get this interesting error:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> src/main.rs:58:12
   |
49 |         let pop_empty_result = s.pop();
   |                                - mutable borrow occurs here
...
58 |         if s.is_empty() {
   |            ^ immutable borrow occurs here
...
61 |     }
   |     - mutable borrow ends here
```

Why can't I just call pop on my mutable struct?

Why does pop borrow the value? If I add a .expect() after it, it is ok, it doesn't trigger that error. I know that is_empty takes an immutable reference, if I switch it to mutable I just get a second mutable borrow.

答:
This happens because of lifetimes. When you construct a method which takes a reference the compiler detects that and if no lifetimes are specified it "generates" them:

```<code>pub fn pop<'a>(&'a mut self) -> Result<T, &'a str> {
    let len: usize = self.data.len();

    if len > 0 {
        let idx_to_rmv: usize = len - 1;
        let last: T = self.data.remove(idx_to_rmv);
        return Result::Ok(last);
    } else {
        return Result::Err("Empty stack");
    }
}
</code>```

This is what compiler sees actually. So, you want to return a static string, then you have to specify the lifetime for a &str explicitly and let the lifetime for the reference to mut self be inferred automatically:

```<code>pub fn pop(&mut self) -> Result<T, &'static str> {
</code>```

Body:
I am developing some basic data structures to learn the syntax and Rust in general. Here is what I came up with for a stack:

#[allow(dead_code)]
mod stack {
    pub struct Stack<T> {
        data: Vec<T>,
    }

    impl<T> Stack<T> {
        pub fn new() -> Stack<T> {
            return Stack { data: Vec::new() };
        }

        pub fn pop(&mut self) -> Result<T, &str> {
            let len: usize = self.data.len();

            if len > 0 {
                let idx_to_rmv: usize = len - 1;
                let last: T = self.data.remove(idx_to_rmv);
                return Result::Ok(last);
            } else {
                return Result::Err("Empty stack");
            }
        }

        pub fn push(&mut self, elem: T) {
            self.data.push(elem);
        }

        pub fn is_empty(&self) -> bool {
            return self.data.len() == 0;
        }
    }
}

mod stack_tests {
    use super::stack::Stack;

    #[test]
    fn basics() {
        let mut s: Stack<i16> = Stack::new();

        s.push(16);
        s.push(27);

        let pop_result = s.pop().expect("");

        assert_eq!(s.pop().expect("Empty stack"), 27);
        assert_eq!(s.pop().expect("Empty stack"), 16);

        let pop_empty_result = s.pop();

        match pop_empty_result {
            Ok(_) => panic!("Should have had no result"),
            Err(_) => {
                println!("Empty stack");
            }
        }

        if s.is_empty() {
            println!("O");
        }
    }
}

I get this interesting error:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> src/main.rs:58:12
   |
49 |         let pop_empty_result = s.pop();
   |                                - mutable borrow occurs here
...
58 |         if s.is_empty() {
   |            ^ immutable borrow occurs here
...
61 |     }
   |     - mutable borrow ends here

Why can't I just call pop on my mutable struct?

Why does pop borrow the value? If I add a .expect() after it, it is ok, it doesn't trigger that error. I know that is_empty takes an immutable reference, if I switch it to mutable I just get a second mutable borrow.

Body:
This happens because of lifetimes. When you construct a method which takes a reference the compiler detects that and if no lifetimes are specified it "generates" them:

pub fn pop<'a>(&'a mut self) -> Result<T, &'a str> {
    let len: usize = self.data.len();

    if len > 0 {
        let idx_to_rmv: usize = len - 1;
        let last: T = self.data.remove(idx_to_rmv);
        return Result::Ok(last);
    } else {
        return Result::Err("Empty stack");
    }
}

This is what compiler sees actually. So, you want to return a static string, then you have to specify the lifetime for a &str explicitly and let the lifetime for the reference to mut self be inferred automatically:

pub fn pop(&mut self) -> Result<T, &'static str> {


问:
Regex - Match URL Paths that contain a trailing /
I am trying to match on any incoming requests that don't have a trailing slash. I also want to capture the URL path, to use in a capture group.  Here is what I've gotten so far.

Incoming URL:   http://www.example.com/path/to/

Regex:  http:\/\/www.example.com\/(.*)[.\/]

Here's a link to the regex tester results

This captures what I want, but it always matches on all URLs - not the URLs that don't contain a trailing slash.

The regex processor is PERL based.

What do I need to change?

答:
To match URLs that do not end with /, use a negative lookbehind with an $ anchor like below:

```<code>http:\/\/www.example.com\/(.*)$(?<!\/)
                              ^^^^^^^^
</code>```

$ will assert the position at the end of the string, and the lookbehind will fail the match if there is a slash. See this regex demo.

Another way is with a (?!.*\/$) lookahead:

```<code>http:\/\/www.example.com\/(?!.*\/$)(.*)
                          ^^^^^^^^^
</code>```

See another regex demo.

The (?!.*\/$) negative lookahead will fail the match after finding out that there is / at the end of the string ($). Note that .* (matches any 0+ chars) is necessary to get to the end of the string, you cannot just use (?!\/$).

Body:
To match URLs that do not end with /, use a negative lookbehind with an $ anchor like below:

http:\/\/www.example.com\/(.*)$(?<!\/)
                              ^^^^^^^^

$ will assert the position at the end of the string, and the lookbehind will fail the match if there is a slash. See this regex demo.

Another way is with a (?!.*\/$) lookahead:

http:\/\/www.example.com\/(?!.*\/$)(.*)
                          ^^^^^^^^^

See another regex demo.

The (?!.*\/$) negative lookahead will fail the match after finding out that there is / at the end of the string ($). Note that .* (matches any 0+ chars) is necessary to get to the end of the string, you cannot just use (?!\/$).


问:
Combining rows of the same key into single array
I have a pandas dataframe as follows:

```<code>    error
 0: [[0.1,0.4,-0.3]]
 1: [[-0.6,-0.3,0.2]]
 .
 .
 .
 99: [[0.4,-0.7,0.1]]
</code>```

I would like to combine all values into a single array like this:

```<code> [0.1,0.4,-0.3,-0.6,-0.3,0.2,...,0.4,-0.7,0.1]
</code>```

Is there a fast way to do this using pandas or do I need to iterate over the data and build the array "manually" ?
The data order, in this case, is not important.

In a more general case, how to combine arrays that don't have the same size (e.g. row 0 contains an array of 3 elements, row 1 contains an array of 6 elements,etc...) ?

答:
```<code>df=pd.DataFrame([[0.1,0.4,-0.3],[-0.6,-0.3,0.2]])

df.values.flatten()
</code>```

will return :
array([ 0.1,  0.4, -0.3, -0.6, -0.3,  0.2])

if you would like to append the element by column

```<code>df.values.flatten(order='F')
</code>```

then it will return:
array([ 0.1, -0.6,  0.4, -0.3, -0.3,  0.2])

Body:
I have a pandas dataframe as follows:

    error
 0: [[0.1,0.4,-0.3]]
 1: [[-0.6,-0.3,0.2]]
 .
 .
 .
 99: [[0.4,-0.7,0.1]]

I would like to combine all values into a single array like this:

 [0.1,0.4,-0.3,-0.6,-0.3,0.2,...,0.4,-0.7,0.1]

Is there a fast way to do this using pandas or do I need to iterate over the data and build the array "manually" ?
The data order, in this case, is not important.

In a more general case, how to combine arrays that don't have the same size (e.g. row 0 contains an array of 3 elements, row 1 contains an array of 6 elements,etc...) ?

Body:
df=pd.DataFrame([[0.1,0.4,-0.3],[-0.6,-0.3,0.2]])

df.values.flatten()

will return :
array([ 0.1,  0.4, -0.3, -0.6, -0.3,  0.2])

if you would like to append the element by column

df.values.flatten(order='F')

then it will return:
array([ 0.1, -0.6,  0.4, -0.3, -0.3,  0.2])


问:
The filename, directory name, or volume label syntax is incorrect - virtualenvwrapper
I have virtualenvwrapper-win installed with python3.6 on win7.
When using it, and providing path to another version of python I get these error messages:

```<code>> mkvirtualenv mynew_env --python=d:\python\python35\python.exe
Running virtualenv with interpreter d:\python\python35\python.exe
Using base prefix 'd:\\python\\python35'
New python executable in C:\Users\Bob\Envs\mynew_env\Scripts\python.exe
Installing setuptools, pip, wheel...done.
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
</code>```

How do I fix it?
I tried different slashes in the path to my python installation: backslashes, forward slashes, double backslashes, the result is always the same.

答:
For some reason on the windows version of virtualenvwrapper it appears that you need to specify the options before the name of the environment, so you should initialise it as below:</p>

```<code>mkvirtualenv --python=d:\python\python35\python.exe  mynew_env
</code>```

Body:
I have virtualenvwrapper-win installed with python3.6 on win7.
When using it, and providing path to another version of python I get these error messages:

> mkvirtualenv mynew_env --python=d:\python\python35\python.exe
Running virtualenv with interpreter d:\python\python35\python.exe
Using base prefix 'd:\\python\\python35'
New python executable in C:\Users\Bob\Envs\mynew_env\Scripts\python.exe
Installing setuptools, pip, wheel...done.
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.

How do I fix it?
I tried different slashes in the path to my python installation: backslashes, forward slashes, double backslashes, the result is always the same.

Body:
For some reason on the windows version of virtualenvwrapper it appears that you need to specify the options before the name of the environment, so you should initialise it as below:

mkvirtualenv --python=d:\python\python35\python.exe  mynew_env


问:
How to change the opacity of background without changing the content of it?
I don't know how to make background-image opacity 0.5 and the content full opacity.

.about-section {
  height: 100%;
  padding-top: 50px;
  text-align: center;
  /*background: #eee;*/
  background: url(../images/about.jpg);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  opacity: 0.3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="about" class="about-section">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>

      </div>
    </div>
  </div>
</section></code>```

答:
For the moment, CSS does not offer that possibility (unless your background is just a colour, in which case you can use rgba()).

To achieve this, you can place your .about-section in position: relative; and create a
 inside it (preferably as the first child, or even better, as a ::before pseudo-element) absolutely positioned, with full width and height. You can then tweak its opacity as you wish without affecting the content.

Body:
I don't know how to make background-image opacity 0.5 and the content full opacity.

.about-section {
  height: 100%;
  padding-top: 50px;
  text-align: center;
  /*background: #eee;*/
  background: url(../images/about.jpg);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  opacity: 0.3;
}

About Us

Body:
For the moment, CSS does not offer that possibility (unless your background is just a colour, in which case you can use rgba()).

To achieve this, you can place your .about-section in position: relative; and create a <div> inside it (preferably as the first child, or even better, as a ::before pseudo-element) absolutely positioned, with full width and height. You can then tweak its opacity as you wish without affecting the content.


问:
create a data frame with a function
i have a data.frame with many values and calculations. One of the values is the wind speed. What i did is to calculate different energies from changing wind speeds. I did it manually and built the data frame row by row just like the following:

```<code>zz <- as.data.frame(matrix(seq(100),nrow=5,ncol=3))

zz$V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
         "A_rotor (m^2)")

zz$V2 <- c("2",  # wind_speed
         "1.2",      # density
         "0.00482", # Cd
         "112",     # d_rotor
         "")

zz$V3[1] <- "" # v_in
zz$V3[2] <- "" # density
zz$V3[3] <- "" # Cd
zz$V3[4] <- "" # d_rotor
zz$V3[5] <- as.numeric(pi/4*(as.numeric(zz[4,2]))^2) # A_rotor
</code>```

This is just an excerpt of my data.frame, but i hope you can see my intention.
What i now want is to create always the same data frame with changing parameters, e.g. the wind speed (let's say 3 and 4 m/s).
And it would be also cool to change more than one value at the same time (let's say wind speed 5 and density 1 or wind speed 6 and density 2).
I tried to solve this problem with a function but it did not work. It only gave me a single value but not the complete data frame.

```<code>speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)

make_speed <- function(x)

{
  zz <- as.data.frame(matrix(seq(100),nrow=5,ncol=3))

  zz$V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
           "A_rotor (m^2)")

  zz$V2 <- c("speed_vector[x]",  # v_in
           "1.2",      # density
           "0.00482", # Cd
           "112",     # d_rotor
           "")

  zz$V3[1] <- "" # v_in
  zz$V3[2] <- "" # density
  zz$V3[3] <- "" # Cd
  zz$V3[4] <- "" # d_rotor
  zz$V3[5] <- as.numeric(pi/4*(as.numeric(zz[4,2]))^2) # A_rotor
}

w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")
</code>```

This is the new, revised code:

```<code>speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)
make_speed <- function(x)
{
V1 <- c("v (m/s)","density (kg/m^3)","Cd ()", "d (m)", "A (m^2)", "N/(W*L)",
      "length L (km)", "Width W (km)", "Height H (m)", "coefficient ()",
      "N ()", "J_h (GW)", "J_v (GW)", "f_red ()", "v (m/s)", "J_out (GW)")

V2 <- c(speed_vector[x],  # v
      "1.2",      # density
      "0.00482", # Cd
      "112",     # d
      "",
      "4.1",   # MW/km^2
      "", "",
      "700",    # Height
      "0.44",   # coefficient
      "", "", "", "", "", "")

V3 <- c(rep("",4),
      as.numeric(pi/4*(as.numeric(V2[4]))^2),
      rep("",1),
      as.numeric((16172.5*0.0898)^(1/2)),
      as.numeric((16172.5*0.0898)^(1/2)),
      rep("",2),
      as.numeric(16172.5*0.0898*as.numeric(V2[4])/3.075),

as.numeric(as.numeric(V2[2])/2*as.numeric(V3[8])*1000*as.numeric(V2[9])*
   (as.numeric(V2[1])^3)/10^9),

as.numeric((as.numeric(V2[2])*as.numeric(V2[3])*as.numeric(V3[8])*1000*
   as.numeric(V3[7])*1000*(as.numeric(V2[1])^3))/10^9),

as.numeric(as.numeric(V2[9])+2*as.numeric(V2[3])*as.numeric(V3[7])*1000)/
   ((as.numeric(V2[9])+2*as.numeric(V2[3])*as.numeric(V3[7])*1000)+3/2*
   as.numeric(V3[11])/(as.numeric(V3[8])*1000)*as.numeric(V2[10])*
   as.numeric(V3[5])),

as.numeric(as.numeric(V3[14])^(1/3)*as.numeric(V2[1])),

as.numeric(as.numeric(V2[2])/2*(as.numeric(V3[8])*1000)*as.numeric(V2[9])*
   as.numeric(V3[15])^3/10^9))

zz <- data.frame(V1,V2,V3)
return(zz)
}
w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")
</code>```

an easier example:

```<code>speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)
make_speed <- function(x)
{
V1 <- c("v (m/s)","density (kg/m^3)","Cd ()", "d (m)", "A (m^2)", "N/(W*L)",
"V(m/s)")

V2 <- c(speed_vector[x],  # v
"1",      # density
"2", # Cd
"3",     # d
"4",   # MW/km^2
"5",    # Height
"6"   # coefficient
)

V3 <- c(as.numeric(as.numeric(V2[4]) ^ 2),
as.numeric(as.numeric(V2[1]) + as.numeric(V2[2])),
as.numeric(as.numeric(V2[1]) * as.numeric(V2[2])),
as.numeric(as.numeric(V2[1]) + as.numeric(V2[2]) + as.numeric(V2[3])),
as.numeric(as.numeric(V2[2]) + as.numeric(V3[2])),
as.numeric(as.numeric(V3[1]) + as.numeric(V3[2])))

zz <- data.frame(V1,V2,V3)
return(zz)
}
w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")
</code>```

答:
I cleaned it a bit, let me know if that's what you want:

```<code>speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)

make_speed <- function(x)
{
 V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
             "A_rotor (m^2)")

 V2 <- c(speed_vector[x],  # v_in # it was a string in your question, but it's the only place where x was used so I figured you wanted it as a value
             "1.2",      # density
             "0.00482", # Cd
             "112",     # d_rotor
             "")
  V3 <- c(rep("",4),as.numeric(pi/4*(as.numeric(V2[4]))^2))
  zz <- data.frame(V1,V2,V3) # better to build the data.frame this way than starting with an empty one, and also yours was generating warnings because of number of element not consistent with rows and cols
  return(zz) # the important line that you were missing
}

w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")
</code>```

EDIT for your subsequent issue

The issue you're having now is completely different.

You may want to learn about the functions debugonce and debug.

By running :

```<code>debugonce(speed)
w_speed_3 <- make_speed("w_sp_3")
</code>```

I see that the error is in the line :

```<code>V3 <- c(rep("", 4), as.numeric(pi/4 * (as.numeric(V2[4]))^2),
    rep("", 1), as.numeric((16172.5 * 0.0898)^(1/2)), as.numeric((16172.5 *
        0.0898)^(1/2)), rep("", 2), as.numeric(16172.5 * 0.0898 *
        as.numeric(V2[4])/3.075), as.numeric(as.numeric(V2[2])/2 *
        as.numeric(V3[8]) * 1000 * as.numeric(V2[9]) * (as.numeric(V2[1])^3)/10^9),
    as.numeric((as.numeric(V2[2]) * as.numeric(V2[3]) * as.numeric(V3[8]) *
        1000 * as.numeric(V3[7]) * 1000 * (as.numeric(V2[1])^3))/10^9),
    as.numeric(as.numeric(V2[9]) + 2 * as.numeric(V2[3]) * as.numeric(V3[7]) *
        1000)/((as.numeric(V2[9]) + 2 * as.numeric(V2[3]) * as.numeric(V3[7]) *
        1000) + 3/2 * as.numeric(V3[11])/(as.numeric(V3[8]) *
        1000) * as.numeric(V2[10]) * as.numeric(V3[5])), as.numeric(as.numeric(V3[14])^(1/3) *
        as.numeric(V2[1])), as.numeric(as.numeric(V2[2])/2 *
        (as.numeric(V3[8]) * 1000) * as.numeric(V2[9]) * as.numeric(V3[15])^3/10^9))
</code>```

Looking closer, I see that you're calling V3 to define V3, but V3 doesn't exist, so the function stops with an error.

I don't know what you're trying to do, but you cannot initiate a variable using itself on the right hand side.

Title: create a data frame with a function

Body:
i have a data.frame with many values and calculations. One of the values is the wind speed. What i did is to calculate different energies from changing wind speeds. I did it manually and built the data frame row by row just like the following:

zz <- as.data.frame(matrix(seq(100),nrow=5,ncol=3))

zz$V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
         "A_rotor (m^2)")

zz$V2 <- c("2",  # wind_speed
         "1.2",      # density
         "0.00482", # Cd
         "112",     # d_rotor
         "")

zz$V3[1] <- "" # v_in
zz$V3[2] <- "" # density
zz$V3[3] <- "" # Cd
zz$V3[4] <- "" # d_rotor
zz$V3[5] <- as.numeric(pi/4*(as.numeric(zz[4,2]))^2) # A_rotor

This is just an excerpt of my data.frame, but i hope you can see my intention.
What i now want is to create always the same data frame with changing parameters, e.g. the wind speed (let's say 3 and 4 m/s).
And it would be also cool to change more than one value at the same time (let's say wind speed 5 and density 1 or wind speed 6 and density 2).
I tried to solve this problem with a function but it did not work. It only gave me a single value but not the complete data frame.

speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)

make_speed <- function(x)

{
  zz <- as.data.frame(matrix(seq(100),nrow=5,ncol=3))

  zz$V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
           "A_rotor (m^2)")

  zz$V2 <- c("speed_vector[x]",  # v_in
           "1.2",      # density
           "0.00482", # Cd
           "112",     # d_rotor
           "")

  zz$V3[1] <- "" # v_in
  zz$V3[2] <- "" # density
  zz$V3[3] <- "" # Cd
  zz$V3[4] <- "" # d_rotor
  zz$V3[5] <- as.numeric(pi/4*(as.numeric(zz[4,2]))^2) # A_rotor
}

w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")

This is the new, revised code:

speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)
make_speed <- function(x)
{
V1 <- c("v (m/s)","density (kg/m^3)","Cd ()", "d (m)", "A (m^2)", "N/(W*L)",
      "length L (km)", "Width W (km)", "Height H (m)", "coefficient ()",
      "N ()", "J_h (GW)", "J_v (GW)", "f_red ()", "v (m/s)", "J_out (GW)")

V2 <- c(speed_vector[x],  # v
      "1.2",      # density
      "0.00482", # Cd
      "112",     # d
      "",
      "4.1",   # MW/km^2
      "", "",
      "700",    # Height
      "0.44",   # coefficient
      "", "", "", "", "", "")

V3 <- c(rep("",4),
      as.numeric(pi/4*(as.numeric(V2[4]))^2),
      rep("",1),
      as.numeric((16172.5*0.0898)^(1/2)),
      as.numeric((16172.5*0.0898)^(1/2)),
      rep("",2),
      as.numeric(16172.5*0.0898*as.numeric(V2[4])/3.075),

as.numeric(as.numeric(V2[2])/2*as.numeric(V3[8])*1000*as.numeric(V2[9])*
   (as.numeric(V2[1])^3)/10^9),

as.numeric((as.numeric(V2[2])*as.numeric(V2[3])*as.numeric(V3[8])*1000*
   as.numeric(V3[7])*1000*(as.numeric(V2[1])^3))/10^9),

as.numeric(as.numeric(V2[9])+2*as.numeric(V2[3])*as.numeric(V3[7])*1000)/
   ((as.numeric(V2[9])+2*as.numeric(V2[3])*as.numeric(V3[7])*1000)+3/2*
   as.numeric(V3[11])/(as.numeric(V3[8])*1000)*as.numeric(V2[10])*
   as.numeric(V3[5])),

as.numeric(as.numeric(V3[14])^(1/3)*as.numeric(V2[1])),

as.numeric(as.numeric(V2[2])/2*(as.numeric(V3[8])*1000)*as.numeric(V2[9])*
   as.numeric(V3[15])^3/10^9))

zz <- data.frame(V1,V2,V3)
return(zz)
}
w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")

an easier example:

speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)
make_speed <- function(x)
{
V1 <- c("v (m/s)","density (kg/m^3)","Cd ()", "d (m)", "A (m^2)", "N/(W*L)",
"V(m/s)")

V2 <- c(speed_vector[x],  # v
"1",      # density
"2", # Cd
"3",     # d
"4",   # MW/km^2
"5",    # Height
"6"   # coefficient
)

V3 <- c(as.numeric(as.numeric(V2[4]) ^ 2),
as.numeric(as.numeric(V2[1]) + as.numeric(V2[2])),
as.numeric(as.numeric(V2[1]) * as.numeric(V2[2])),
as.numeric(as.numeric(V2[1]) + as.numeric(V2[2]) + as.numeric(V2[3])),
as.numeric(as.numeric(V2[2]) + as.numeric(V3[2])),
as.numeric(as.numeric(V3[1]) + as.numeric(V3[2])))

zz <- data.frame(V1,V2,V3)
return(zz)
}
w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")

Body:
I cleaned it a bit, let me know if that's what you want:

speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)

make_speed <- function(x)
{
 V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
             "A_rotor (m^2)")

 V2 <- c(speed_vector[x],  # v_in # it was a string in your question, but it's the only place where x was used so I figured you wanted it as a value
             "1.2",      # density
             "0.00482", # Cd
             "112",     # d_rotor
             "")
  V3 <- c(rep("",4),as.numeric(pi/4*(as.numeric(V2[4]))^2))
  zz <- data.frame(V1,V2,V3) # better to build the data.frame this way than starting with an empty one, and also yours was generating warnings because of number of element not consistent with rows and cols
  return(zz) # the important line that you were missing
}

w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")

EDIT for your subsequent issue

The issue you're having now is completely different.

You may want to learn about the functions debugonce and debug.

By running :

debugonce(speed)
w_speed_3 <- make_speed("w_sp_3")

I see that the error is in the line :

V3 <- c(rep("", 4), as.numeric(pi/4 * (as.numeric(V2[4]))^2),
    rep("", 1), as.numeric((16172.5 * 0.0898)^(1/2)), as.numeric((16172.5 *
        0.0898)^(1/2)), rep("", 2), as.numeric(16172.5 * 0.0898 *
        as.numeric(V2[4])/3.075), as.numeric(as.numeric(V2[2])/2 *
        as.numeric(V3[8]) * 1000 * as.numeric(V2[9]) * (as.numeric(V2[1])^3)/10^9),
    as.numeric((as.numeric(V2[2]) * as.numeric(V2[3]) * as.numeric(V3[8]) *
        1000 * as.numeric(V3[7]) * 1000 * (as.numeric(V2[1])^3))/10^9),
    as.numeric(as.numeric(V2[9]) + 2 * as.numeric(V2[3]) * as.numeric(V3[7]) *
        1000)/((as.numeric(V2[9]) + 2 * as.numeric(V2[3]) * as.numeric(V3[7]) *
        1000) + 3/2 * as.numeric(V3[11])/(as.numeric(V3[8]) *
        1000) * as.numeric(V2[10]) * as.numeric(V3[5])), as.numeric(as.numeric(V3[14])^(1/3) *
        as.numeric(V2[1])), as.numeric(as.numeric(V2[2])/2 *
        (as.numeric(V3[8]) * 1000) * as.numeric(V2[9]) * as.numeric(V3[15])^3/10^9))

Looking closer, I see that you're calling V3 to define V3, but V3 doesn't exist, so the function stops with an error.

I don't know what you're trying to do, but you cannot initiate a variable using itself on the right hand side.


问:
CheckIncludeFileCXX does not find header
I'm trying to use the CheckIncludeFileCXX module to verify <gsl/gsl> is present in the system. GSL exists at /usr/local/include/gsl/gsl but generation fails at "GSL not found"

```<code>project(cpp-binaries)
cmake_minimum_required(VERSION 3.2)

include(CheckIncludeFileCXX)
CHECK_INCLUDE_FILE_CXX("gsl/gsl" GSL_LIBRARY)

if(NOT GSL_LIBRARY)
    message(FATAL_ERROR "GSL not found")
endif(NOT GSL_LIBRARY)

add_executable(
    cpp-binaries
    "main.cpp"
)
</code>```

答:
Ok I looked more into CheckIncludeFileCXX and you basically have to specify something with CMAKE_REQUIRED_INCLUDES or else it doesn't know where to search. To give it something, it quietly searches for the include with find_path but still errors out if nothing is found.

```<code>project(gsl_t)
cmake_minimum_required(VERSION 3.2)

find_path(
    gsl_location
    gsl
    HINTS ENV GSLDIR
)

if(gsl_location)
    get_filename_component(gsl_include_dir ${gsl_location} DIRECTORY)
    list(APPEND CMAKE_INCLUDE_PATH ${gsl_include_dir})
endif(gsl_location)

include(CheckIncludeFileCXX)
set(CMAKE_REQUIRED_INCLUDES ${CMAKE_INCLUDE_PATH})
CHECK_INCLUDE_FILE_CXX("gsl/gsl" gsl_found)

if(NOT gsl_found)
    message(FATAL_ERROR "GSL not found. \
                        Try setting the GSLDIR environment variable")
endif(NOT gsl_found)

add_executable(
    gsl_t
    "main.cpp"
)
</code>```

Body:
I'm trying to use the CheckIncludeFileCXX module to verify <gsl/gsl> is present in the system. GSL exists at /usr/local/include/gsl/gsl but generation fails at "GSL not found"

project(cpp-binaries)
cmake_minimum_required(VERSION 3.2)

include(CheckIncludeFileCXX)
CHECK_INCLUDE_FILE_CXX("gsl/gsl" GSL_LIBRARY)

if(NOT GSL_LIBRARY)
    message(FATAL_ERROR "GSL not found")
endif(NOT GSL_LIBRARY)

add_executable(
    cpp-binaries
    "main.cpp"
)

Body:
Ok I looked more into CheckIncludeFileCXX and you basically have to specify something with CMAKE_REQUIRED_INCLUDES or else it doesn't know where to search. To give it something, it quietly searches for the include with find_path but still errors out if nothing is found.

project(gsl_t)
cmake_minimum_required(VERSION 3.2)

find_path(
    gsl_location
    gsl
    HINTS ENV GSLDIR
)

if(gsl_location)
    get_filename_component(gsl_include_dir ${gsl_location} DIRECTORY)
    list(APPEND CMAKE_INCLUDE_PATH ${gsl_include_dir})
endif(gsl_location)

include(CheckIncludeFileCXX)
set(CMAKE_REQUIRED_INCLUDES ${CMAKE_INCLUDE_PATH})
CHECK_INCLUDE_FILE_CXX("gsl/gsl" gsl_found)

if(NOT gsl_found)
    message(FATAL_ERROR "GSL not found. \
                        Try setting the GSLDIR environment variable")
endif(NOT gsl_found)

add_executable(
    gsl_t
    "main.cpp"
)


问:
Insufficient tokens for quota 'administrator' and limit 'CLIENT_PROJECT-100s' of service 'pubsub.googleapis.com' for consumer 'project_number:#'
I sometimes get the following error when creating a subscription:

Insufficient tokens for quota 'administrator' and limit 'CLIENT_PROJECT-100s' of service 'pubsub.googleapis.com' for consumer 'project_number:'

Waiting it out does the trick, but I'd like to increase the quota. In the IAM & Admin section of the Google Cloud Console, I can filter on the Pub/Sub API, but can't find the limit...

答: You are running up against the quota for administrative operations. In the Quotas page, under "Quota type," select "All quotas," then under "Service" select "Google Cloud Pub/Sub API." The quota you want to increase is "Administrator operations per 100 seconds," which you can update up to the maximum allowed limit of 10,000 per 100 seconds, as detailed on the Pub/Sub quota page. Here is a screenshot of the entity you need to update:


问:
Display unique array entries and sum of related entry from separate array
I'm trying to take two arrays that are related, filter one to retrieve the unique values and the other needs to have the sums for the unique values. The indexes for Array 1 match the index for Array 2 that I need to add all the values together to get the sum. For example:

Array 1:

```<code>var arr1 = [7012, 7013, 7015, 7012];
</code>```

Array 2:

```<code>var arr2 = [10, 20, 25, 10];
</code>```

Expected Output:

(first explanation was not great, changing this)

```<code>newArray1 = [7012, 7013, 7015];
newArray2 = [20, 20, 25];
</code>```

Note: I am using Firebase to retrieve the values into the arrays, these are not going to be set indexes.

I'm using Set() to retrieve the unique values:

```<code>var newArr = [...new Set(arr1)];
</code>```

which works perfectly fine.

The trouble I'm having is getting the related values from Array 2 and making a sum. I can create the sum fine by using .reduce() but I'm having trouble figuring out how to get the Array 2 values into a new array based on what they're related to in Array 1.

答:
You could use Map and store the corresponding values with the same keys of array1. Then get the values for summing.

var array1 = [7012, 7013, 7015, 7012],
    array2 = [10, 20, 25, 10],
    map = array1.reduce((m, k, i) => (m.set(k, (m.get(k) || 0) + array2[i])), new Map),
    sum = [...map.values()].reduce((r, v) => r + v, 0);

console.log([...map]);
console.log(sum);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm trying to take two arrays that are related, filter one to retrieve the unique values and the other needs to have the sums for the unique values. The indexes for Array 1 match the index for Array 2 that I need to add all the values together to get the sum. For example:

Array 1:

var arr1 = [7012, 7013, 7015, 7012];

Array 2:

var arr2 = [10, 20, 25, 10];

Expected Output:

(first explanation was not great, changing this)

newArray1 = [7012, 7013, 7015];
newArray2 = [20, 20, 25];

Note: I am using Firebase to retrieve the values into the arrays, these are not going to be set indexes.

I'm using Set() to retrieve the unique values:

var newArr = [...new Set(arr1)];

which works perfectly fine.

The trouble I'm having is getting the related values from Array 2 and making a sum. I can create the sum fine by using .reduce() but I'm having trouble figuring out how to get the Array 2 values into a new array based on what they're related to in Array 1.

Body:
You could use Map and store the corresponding values with the same keys of array1. Then get the values for summing.

var array1 = [7012, 7013, 7015, 7012],
    array2 = [10, 20, 25, 10],
    map = array1.reduce((m, k, i) => (m.set(k, (m.get(k) || 0) + array2[i])), new Map),
    sum = [...map.values()].reduce((r, v) => r + v, 0);

console.log([...map]);
console.log(sum);

.as-console-wrapper { max-height: 100% !important; top: 0; }