问:
Android Studio networking.httpResponse@4e0cae2
I'm trying to do an application in Android Studio and I have this error when I'm trying to parse a JSON object. My JSON object is here https://api.myjson.com/bins/sk0rv

Can someone help me?

The code for the first activity

```<code>public class HttpConnection extends AsyncTask<String, Void, HttpResponse> {

    URL url;
    HttpURLConnection connection;

    @Override
    protected HttpResponse doInBackground(String... params) {

        try {
            url=new URL(params[0]);
            connection=(HttpURLConnection) url.openConnection();

            InputStream inputStream=connection.getInputStream();
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
            BufferedReader reader=new BufferedReader(inputStreamReader);
            String line=reader.readLine();
            reader.close();
            inputStreamReader.close();
            inputStream.close();
            connection.disconnect();
            return  getHttpResponseFromJson(line);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    private HttpResponse getHttpResponseFromJson(String json) throws JSONException {
        if(json==null){
            return null;
        }
        JSONObject object=new JSONObject(json);
        ExtraInfo extraInfo=getExtraInfoFromJson(object.getJSONObject("ExtraInfo"));

        return new HttpResponse(extraInfo);
    }

    private ExtraInfo getExtraInfoFromJson(JSONObject object) throws JSONException {
        if(object==null)
        {
            return null;
        }

        ExtraInfo extraInfo=new ExtraInfo();
        extraInfo.setPretPromotie(object.getInt("pretPromotie"));
        extraInfo.setNumeFilatelist(object.getString("numeFilatelist"));

        JSONObject timbruInfo=object.getJSONObject("TimbruInfo");

        if(timbruInfo!=null)
        {
            TimbruInfo timbru=new TimbruInfo();

            timbru.setTara(timbruInfo.getString("taraOrigine"));
            timbru.setTematica(timbruInfo.getString("tematica"));
            timbru.setAnAparitie(timbruInfo.getInt("anAparitie"));
            timbru.setPret(timbruInfo.getInt("pret"));
           timbru.setTip(timbruInfo.getString("tip"));

        }
        return extraInfo;
    }

}
</code>```

The code for the second activity

```<code>public class PromotiiActivity extends AbstractActivity{

    private static String URL="https://api.myjson.com/bins/sk0rv";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_promotii);

        HttpConnection connection= new HttpConnection(){
            @Override
            protected void onPostExecute(HttpResponse httpResponse) {
                super.onPostExecute(httpResponse);

                if(httpResponse!=null)
                {
                    Toast.makeText(getApplicationContext(), httpResponse.toString(), Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "is Empty", Toast.LENGTH_LONG).show();
                }
            }
        };
        connection.execute(URL);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuItem item = menu.findItem(R.id.app_menu_promotii);
        item.setVisible(false);
        return true;
    }
}
</code>```

答:
it's because you print the reference to your object

```<code>Toast.makeText(getApplicationContext(), httpResponse.toString(), Toast.LENGTH_LONG).show();
</code>```

you should do this instead

```<code>HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
</code>```

Body:
I'm trying to do an application in Android Studio and I have this error when I'm trying to parse a JSON object. My JSON object is here https://api.myjson.com/bins/sk0rv

Can someone help me?

The code for the first activity

public class HttpConnection extends AsyncTask<String, Void, HttpResponse> {

    URL url;
    HttpURLConnection connection;

    @Override
    protected HttpResponse doInBackground(String... params) {

        try {
            url=new URL(params[0]);
            connection=(HttpURLConnection) url.openConnection();

            InputStream inputStream=connection.getInputStream();
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
            BufferedReader reader=new BufferedReader(inputStreamReader);
            String line=reader.readLine();
            reader.close();
            inputStreamReader.close();
            inputStream.close();
            connection.disconnect();
            return  getHttpResponseFromJson(line);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    private HttpResponse getHttpResponseFromJson(String json) throws JSONException {
        if(json==null){
            return null;
        }
        JSONObject object=new JSONObject(json);
        ExtraInfo extraInfo=getExtraInfoFromJson(object.getJSONObject("ExtraInfo"));

        return new HttpResponse(extraInfo);
    }

    private ExtraInfo getExtraInfoFromJson(JSONObject object) throws JSONException {
        if(object==null)
        {
            return null;
        }

        ExtraInfo extraInfo=new ExtraInfo();
        extraInfo.setPretPromotie(object.getInt("pretPromotie"));
        extraInfo.setNumeFilatelist(object.getString("numeFilatelist"));

        JSONObject timbruInfo=object.getJSONObject("TimbruInfo");

        if(timbruInfo!=null)
        {
            TimbruInfo timbru=new TimbruInfo();

            timbru.setTara(timbruInfo.getString("taraOrigine"));
            timbru.setTematica(timbruInfo.getString("tematica"));
            timbru.setAnAparitie(timbruInfo.getInt("anAparitie"));
            timbru.setPret(timbruInfo.getInt("pret"));
           timbru.setTip(timbruInfo.getString("tip"));

        }
        return extraInfo;
    }

}

The code for the second activity

public class PromotiiActivity extends AbstractActivity{

    private static String URL="https://api.myjson.com/bins/sk0rv";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_promotii);

        HttpConnection connection= new HttpConnection(){
            @Override
            protected void onPostExecute(HttpResponse httpResponse) {
                super.onPostExecute(httpResponse);

                if(httpResponse!=null)
                {
                    Toast.makeText(getApplicationContext(), httpResponse.toString(), Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "is Empty", Toast.LENGTH_LONG).show();
                }
            }
        };
        connection.execute(URL);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuItem item = menu.findItem(R.id.app_menu_promotii);
        item.setVisible(false);
        return true;
    }
}

Body:
it's because you print the reference to your object

Toast.makeText(getApplicationContext(), httpResponse.toString(), Toast.LENGTH_LONG).show();

you should do this instead

HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();


来源: stackexchange

问:
How to set Hint font to italic with TextInputLayout?
How to set Hint font to italic with TextInputLayout in android.
With normal edit strong text text

" Name "

this will work if we set as hint, but not with TextInputLayout.

答:
Create a custom style for your TextInputLayout:

```<code><style name="MyCustomAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textColor">?attr/colorPrimary</item>
    <item name="android:textStyle">italic</item>
    <!-- your custom attributes -->
</style>
</code>```

Then set the style

```<code> <android.support.design.widget.TextInputLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        app:hintTextAppearance="@style/MyCustomAppearance"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Create a custom style for your TextInputLayout:

<style name="MyCustomAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textColor">?attr/colorPrimary</item>
    <item name="android:textStyle">italic</item>
    <!-- your custom attributes -->
</style>

Then set the style

 <android.support.design.widget.TextInputLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        app:hintTextAppearance="@style/MyCustomAppearance"/>


问:
Test controller action by phpunit, symfony
I need to test my controller action and i need advice.
It's how my controller looks:

```<code>class SampleController extends Controller
{
    public function sampleAction(Request $request)
    {
        $lang = 'en';

        return $this->render('movie.html.twig', [
            'icons' => $this->container->getParameter('icons'),
            'language' => $lang,
            'extraServiceUrl' => $this->getAccount()->getExtraServiceUrl(),
            'websiteUrl' => $this->getAccount()->getWebsiteUrl(),
            'myProfileUrl' => $this->getAccount()->getMyProfileUrl(),
            'redirectForAnonUser' => $this->container->get('router')->generate('login'),
            'containerId' => $request->getSession()->get("_website"),
            'isRestricted' => $this->getLicense()->isRestricted(),
            'isPremiumAvaible' => $this->getLicense()->isPremiumAvaible()
        ]);
    }

    private function getAccount()
    {
        return $this->container->get('context')->getAccount();
    }

    private function getLicense()
    {
        return $this->container->get('license');
    }
}
</code>```

And now, normally I test controllers by behat, but this one just render twig and set variables in  so I probably can't test it by behat. I tried to test it by phpUnit and it can work, but what is the best way to mock chain methods? Or maybe you have other way to test it?
btw container is private so I need reflection?
Greetings

答:
There are 2 approaches to test Controllers:

Functional tests. You test whole application together - from fetching data from db to rendering response in Symfony core. You can use fixtures to set-up test data.

Unit test. You test only this method, all dependencies are mocked.

Unit tests are good in testing services with just few dependencies. But for controllers Functional tests are better in most cases.

Functional test with session mocking in you case could look like:

```<code>namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PostControllerTest extends WebTestCase
{
    public function testYourAction()
    {
        $client = static::createClient();

        $user = null;//todo: load user for test from DB here

        /** @var Session $session */
        $session = $client->getContainer()->get('session');

        $firewall = 'main';
        $token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
        $session->set('_security_'.$firewall, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
            $this->client->getCookieJar()->set($cookie);

        $crawler = $client->request('GET', '/your_url');

        $response = $this->client->getResponse();
        $this->assertEquals(200, $response->getStatusCode());

        //todo: do other assertions. For example, check that some string is present in response, etc..
    }
}
</code>```

Body:
I need to test my controller action and i need advice.
It's how my controller looks:

class SampleController extends Controller
{
    public function sampleAction(Request $request)
    {
        $lang = 'en';

        return $this->render('movie.html.twig', [
            'icons' => $this->container->getParameter('icons'),
            'language' => $lang,
            'extraServiceUrl' => $this->getAccount()->getExtraServiceUrl(),
            'websiteUrl' => $this->getAccount()->getWebsiteUrl(),
            'myProfileUrl' => $this->getAccount()->getMyProfileUrl(),
            'redirectForAnonUser' => $this->container->get('router')->generate('login'),
            'containerId' => $request->getSession()->get("_website"),
            'isRestricted' => $this->getLicense()->isRestricted(),
            'isPremiumAvaible' => $this->getLicense()->isPremiumAvaible()
        ]);
    }

    private function getAccount()
    {
        return $this->container->get('context')->getAccount();
    }

    private function getLicense()
    {
        return $this->container->get('license');
    }
}

And now, normally I test controllers by behat, but this one just render twig and set variables in  so I probably can't test it by behat. I tried to test it by phpUnit and it can work, but what is the best way to mock chain methods? Or maybe you have other way to test it?
btw container is private so I need reflection?
Greetings

Body:
There are 2 approaches to test Controllers:

Functional tests. You test whole application together - from fetching data from db to rendering response in Symfony core. You can use fixtures to set-up test data.

Unit test. You test only this method, all dependencies are mocked.

Unit tests are good in testing services with just few dependencies. But for controllers Functional tests are better in most cases.

Functional test with session mocking in you case could look like:

namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PostControllerTest extends WebTestCase
{
    public function testYourAction()
    {
        $client = static::createClient();

        $user = null;//todo: load user for test from DB here

        /** @var Session $session */
        $session = $client->getContainer()->get('session');

        $firewall = 'main';
        $token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
        $session->set('_security_'.$firewall, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
            $this->client->getCookieJar()->set($cookie);

        $crawler = $client->request('GET', '/your_url');

        $response = $this->client->getResponse();
        $this->assertEquals(200, $response->getStatusCode());

        //todo: do other assertions. For example, check that some string is present in response, etc..
    }
}


问:
Google Maps, Making markers show at different zoom levels?
I've got a Google map with around 1000 makers, I need to make it so when at a higher zoom level they are not all shown and then when zooming in they start to show.

Can anyone point me in the right direction.

答: Have you checked out Marker Manager?</p>

ContentLicense: CC BY-SA 2.5

Body: Have you checked out Marker Manager?


问:
SQL SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB)
So I have two tables and I want to use a concat on one of the columns in each table.

TableA

```<code>ColumnA
1
1
2
3
4
4
5
</code>```

TableB

```<code>ColumnX
a
a
b
c
d
d
e
</code>```

And I want to concat these two columns so they end up looking like the below result WITHOUT dublicates

```<code>Result
1|a
2|b
3|c
4|d
5|e
</code>```

So I have tried to do the following:

```<code>SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB) where tableA.Relation = TableB.Relation
</code>```

But I am still getting dublicates!? Why????

答:
you could generate the row_numbers by row_numbers() function & then concat them (SQL Server)

```<code>;with cte as
(
    SELECT *, ROW_NUMBER() over (order by (select 1)) rn FROM <table>
),cte1 as
(
   SELECT *, ROW_NUMBER() over (order by (select 1)) rn FROM <table>
)

select DISTINCT CONCAT(c.ColumnA, '|',c1.ColumnX) from cte c
join cte1 c1 on c1.rn = c.rn
</code>```

Body:
So I have two tables and I want to use a concat on one of the columns in each table.

TableA

ColumnA
1
1
2
3
4
4
5

TableB

ColumnX
a
a
b
c
d
d
e

And I want to concat these two columns so they end up looking like the below result WITHOUT dublicates

Result
1|a
2|b
3|c
4|d
5|e

So I have tried to do the following:

SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB) where tableA.Relation = TableB.Relation

But I am still getting dublicates!? Why????

Body:
you could generate the row_numbers by row_numbers() function & then concat them (SQL Server)

;with cte as
(
    SELECT *, ROW_NUMBER() over (order by (select 1)) rn FROM <table>
),cte1 as
(
   SELECT *, ROW_NUMBER() over (order by (select 1)) rn FROM <table>
)

select DISTINCT CONCAT(c.ColumnA, '|',c1.ColumnX) from cte c
join cte1 c1 on c1.rn = c.rn


问:
Haskell list of int tuples to string
I'm trying to write out my list of tuples from:

```<code>[(8,7),(5,6),(3,3),(9,4),(5,4)]
</code>```

to:

```<code>8 7 5 6 3 3 9 4 5 4
</code>```

this is how far i've come:
(Updated)

```<code>showTuples :: Board -> String
showTuples = unwords . fmap show . concatMap (\(x,y) -> [x,y])
</code>```

I know i'm suppose to map this function to all elements of my list but i can't seem to get it right.

(UPDATE)
It worked, still having problems with the quotation marks though

also type of Board is:

```<code>type Board = [(Int,Int)]
</code>```

答:
This can be done by a foldl too.

```<code>Prelude> foldl (\r (x,y) -> r ++ " " ++ show x ++ " " ++ show y) "" [(8,7),(5,6),(3,3),(9,4),(5,4)]
" 8 7 5 6 3 3 9 4 5 4"
</code>```

If you don't want the preceding whitespace then just do like tail $ foldl (\r (x,y) -> ...

Title: Haskell list of int tuples to string

Body:
I'm trying to write out my list of tuples from:

[(8,7),(5,6),(3,3),(9,4),(5,4)]

to:

8 7 5 6 3 3 9 4 5 4

this is how far i've come:
(Updated)

showTuples :: Board -> String
showTuples = unwords . fmap show . concatMap (\(x,y) -> [x,y])

I know i'm suppose to map this function to all elements of my list but i can't seem to get it right.

(UPDATE)
It worked, still having problems with the quotation marks though

also type of Board is:

type Board = [(Int,Int)]

Body:
This can be done by a foldl too.

Prelude> foldl (\r (x,y) -> r ++ " " ++ show x ++ " " ++ show y) "" [(8,7),(5,6),(3,3),(9,4),(5,4)]
" 8 7 5 6 3 3 9 4 5 4"

If you don't want the preceding whitespace then just do like tail $ foldl (\r (x,y) -> ...


问:
Need to hide title onhover for string in span
I have a title in place for a custom fieldset. "customtag" has its own title. Inside this i have a string displayed under span and for this string i have a custom tooltip in place.

When i hover over the text on the string, i see the custom tooltip and title app

```<code><customtag title="sample-title">
    <span class="truncated-field-name">
        <md-tooltip ng-bind="field_name"></md-tooltip>
    </span>
</customtag>
</code>```

Please refer the image below. Along with the custom tooltip, "Metrics" which is title "property" is also getting displayed,
If i can hide "Metrics" that would solve my problem.

Thanks

答:
I'm not sure if I get it right... Maybe your easiest solution is to just not add the title attribute to the span.

If this is not an option try using JS to add a mouseenter function that removes the title onHover: (jQuery)

```<code>$('customtag["title"]').on('mouseenter', function(e){
   $(this).removeAttr("title");
});
</code>```

Body:
I have a title in place for a custom fieldset. "customtag" has its own title. Inside this i have a string displayed under span and for this string i have a custom tooltip in place.

When i hover over the text on the string, i see the custom tooltip and title app

<customtag title="sample-title">

        <md-tooltip ng-bind="field_name"></md-tooltip>

</customtag>

Please refer the image below. Along with the custom tooltip, "Metrics" which is title "property" is also getting displayed,
If i can hide "Metrics" that would solve my problem.

Thanks

Body:
I'm not sure if I get it right... Maybe your easiest solution is to just not add the title attribute to the span.

If this is not an option try using JS to add a mouseenter function that removes the title onHover: (jQuery)

$('customtag["title"]').on('mouseenter', function(e){
   $(this).removeAttr("title");
});


问:
Instagram OAuth Login returning "Matching code was not found or was already used"
So I have a web app that login to Instagram. Works fine for months. No code changes, and suddenly I'm getting

```<code>{"code": 400, "error_type": "OAuthException", "error_message": "Matching code was not found or was already used."}
</code>```

Logging out of instagram.com on my browser and using my web app to login with instagram oauth.... now it works. And it works repeatedly (logging in and out of my app with instagram oauth). Works fine.

Until I access a www.instagram.com webpage on my browser. Then my oauth login fails again with the same error. And I can't login to my web app with instagram oauth again until I logout of instagram.com itself

答:
This error shows because Access_Token is generated and we are trying to re-generate with same 'CODE'. If you want new ACCESS_TOKEN then you need to re-generate the code and use that CODE to generate the ACCESS_TOKEN.

Here is the sample URL to generate CODE.

https://api.instagram.com/oauth/authorize/?client_id=CLIENT-CODE&redirect_uri=REQUEST-URI&response_type=code&scope=public_content

client_id = Client ID from Instagram

redirect_uri = The URL which you have added for permission on Instagram

scope = To set the permission for new generating CODE.

Body:
So I have a web app that login to Instagram. Works fine for months. No code changes, and suddenly I'm getting

{"code": 400, "error_type": "OAuthException", "error_message": "Matching code was not found or was already used."}

Logging out of instagram.com on my browser and using my web app to login with instagram oauth.... now it works. And it works repeatedly (logging in and out of my app with instagram oauth). Works fine.

Until I access a www.instagram.com webpage on my browser. Then my oauth login fails again with the same error. And I can't login to my web app with instagram oauth again until I logout of instagram.com itself


问:
LinkedIn login integration in AEM
I am trying to integrate login via LinkedIn in my AEM website, but i could not find any well explained solution/process over web. Facebook/Twitter were simple as they come out of the box.

I found this link https://github.com/Adobe-Marketing-Cloud/aem-communities-oauth-sample which is a code that seem to enable this, but how this will work is not very clear.

If you can redirect to a blog post or help me with the process of actually implementing LinkedIn login, that will be of great help!

To add, I am completely new in server side of AEM, i have worked on creating components and templates but never on server side for AEM. This sample is in Java, which is again new to me. How to integrate and make it work is a challenge i am facing.

答:
You need an AEM authentication handler and use OAuth library, There is an article on StackOverflow which can help you in creating OAuth library.
LinkedIn API Authentication using Java</p>

Title: LinkedIn login integration in AEM


问:
template class operator overloading problem
I'm trying to port some Visual C++ (VS2005) code so that it will compile under both VS2005 and C++ Builder XE.  The code that follows compiles fine under VS2005 but under C++ Builder XE, I get the following error:

[BCC32 Error] time_stamp.h(49): E2327 Operators may not have default argument values

Here is the code in question: (time_stamp.h)

```<code>template<typename counter_type>
class time_stamp
{
typedef time_span<counter_type>                     time_span_type;
typedef typename counter_type::value_type   value_type;

public:

/* some code removed for sake of this post, next line is the one causing the error */

friend time_span<counter_type> operator-(const time_stamp<counter_type> &first, const time_stamp<counter_type> &second)
{
  return time_span<counter_type>(first.m_stamp - second.m_stamp);
}

private:

value_type m_stamp;

}
</code>```

The time_span template is as follows (time_span.h):

```<code>template<typename counter_type>
class time_span
{
public:
// TYPES
  typedef counter_type          counter_type;
  typedef typename counter_type::value_type value_type;

/* rest removed for sake of this post */
}
</code>```

The C++ Builder compiler appears to not like the line:
friend time_span operator-(const time_stamp &first, const time_stamp &second)

I'm new to templates and this syntax escapes me or at least the compiler error I can't make sense of.  It appears, to me, that there are no default argument values despite the compiler saying so.  I'm interpreting the error message as saying const time_stamp & is a default value when it looks to me like a passed reference of type time_stamp.

Thanks for reading & replying.  Help understanding as well as fixing is most appreciated.

--- EDIT:

If I re-structure the call above as follows:

```<code>friend time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) );
</code>```

and outside the class definition, I describe the function:

```<code>template<typename counter_type>
time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) )
{
return time_span<counter_type>(first.m_stamp-second.m_stamp);
}
</code>```

I then get this error:

[BCC32 Error] time_stamp.hpp(56): E2082 '-(int (*)(const time_stamp &,const time_stamp &))' must be a member function or have a parameter of class type

答:
try as:</p>

```<code>template<class counter_type>
class .... {
    friend time_span<counter_type> operator-(const time_stamp<counter_type> &first, const time_stamp<counter_type> &second);
};

template<class counter_type>
time_span<counter_type> operator-(const time_stamp<counter_type> &first,
                                  const time_stamp<counter_type> &second)
{
  return time_span<counter_type>(first.m_stamp - second.m_stamp);
}
</code>```

Body:
I'm trying to port some Visual C++ (VS2005) code so that it will compile under both VS2005 and C++ Builder XE.  The code that follows compiles fine under VS2005 but under C++ Builder XE, I get the following error:

[BCC32 Error] time_stamp.h(49): E2327 Operators may not have default argument values

Here is the code in question: (time_stamp.h)

template<typename counter_type>
class time_stamp
{
typedef time_span<counter_type>                     time_span_type;
typedef typename counter_type::value_type   value_type;

public:

/* some code removed for sake of this post, next line is the one causing the error */

friend time_span<counter_type> operator-(const time_stamp<counter_type> &first, const time_stamp<counter_type> &second)
{
  return time_span<counter_type>(first.m_stamp - second.m_stamp);
}

private:

value_type m_stamp;

}

The time_span template is as follows (time_span.h):

template<typename counter_type>
class time_span
{
public:
// TYPES
  typedef counter_type          counter_type;
  typedef typename counter_type::value_type value_type;

/* rest removed for sake of this post */
}

The C++ Builder compiler appears to not like the line:
friend time_span operator-(const time_stamp &first, const time_stamp &second)

I'm new to templates and this syntax escapes me or at least the compiler error I can't make sense of.  It appears, to me, that there are no default argument values despite the compiler saying so.  I'm interpreting the error message as saying const time_stamp & is a default value when it looks to me like a passed reference of type time_stamp.

Thanks for reading & replying.  Help understanding as well as fixing is most appreciated.

--- EDIT:

If I re-structure the call above as follows:

friend time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) );

and outside the class definition, I describe the function:

template<typename counter_type>
time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) )
{
return time_span<counter_type>(first.m_stamp-second.m_stamp);
}

I then get this error:

[BCC32 Error] time_stamp.hpp(56): E2082 '-(int (*)(const time_stamp &,const time_stamp &))' must be a member function or have a parameter of class type

Body:
try as:

template<class counter_type>
class .... {
    friend time_span<counter_type> operator-(const time_stamp<counter_type> &first, const time_stamp<counter_type> &second);
};

template<class counter_type>
time_span<counter_type> operator-(const time_stamp<counter_type> &first,
                                  const time_stamp<counter_type> &second)
{
  return time_span<counter_type>(first.m_stamp - second.m_stamp);
}


问:
How I can give a text in my component a color?
I use angular materials to design my app:

material themes

I use a .scss file:

```<code>@import '~@angular/material/theming';
@include mat-core();
$candy-app-primary: mat-palette($mat-red);
$candy-app-accent:  mat-palette($mat-red, A200, A100, A400);
$candy-app-warn:    mat-palette($mat-red);
$candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent,
$candy-app-warn);
@include angular-material-theme($candy-app-theme);
</code>```

and it works really fine with material components, e.g. like:

```<code><mat-slide-toggle>Slide me!</mat-slide-toggle>
</code>```

My question would be how I can give a text in my component a color:

```<code><h1 class="candy-app-primary">  // this does  not work but I would need something like this
  Welcome to {{title}}!
</h1>
</code>```

答:
Use the mat-color function for colors (ensure that this is in the same file as where you declared your theme):

.candy-app-primary {
    color: mat-color($candy-app-primary);
}
```

Body:
I use angular materials to design my app:

material themes

I use a .scss file:

@import '~@angular/material/theming';
@include mat-core();
$candy-app-primary: mat-palette($mat-red);
$candy-app-accent:  mat-palette($mat-red, A200, A100, A400);
$candy-app-warn:    mat-palette($mat-red);
$candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent,
$candy-app-warn);
@include angular-material-theme($candy-app-theme);

and it works really fine with material components, e.g. like:

<mat-slide-toggle>Slide me!</mat-slide-toggle>

My question would be how I can give a text in my component a color:

  // this does  not work but I would need something like this
  Welcome to {{title}}!


问:
Default SQL Server for Entity Framework
I have two instances of SQL Server - SQLEXPRESS and MSSQLServer 2017. My Entity Framework test application creates database in SQLEXPRESS. Where is it defined which instance of SQL Server Entity Framework should use?

Test application:

```<code>    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class PeopleContext : DbContext
    {
        public IDbSet<Person> People { get; set; }
    }

    static void Main(string[] args) // using DB
    {
        try
        {
            using (PeopleContext ctx = new PeopleContext())
            {
                ctx.People.Add(new Person() { Id = 1, Name = "John Doe" });
                ctx.SaveChanges();
            }

            using (PeopleContext ctx = new PeopleContext())
            {
                Person person = ctx.People.SingleOrDefault(p => p.Id == 1);
                Console.WriteLine(person.Name);
            }

        }
        catch (Exception e)
        {

            Console.WriteLine(e.Message);
        }

        Console.WriteLine("finish");
        Console.ReadLine();
    }
</code>```

UPD:
I have several connection strings in my app.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="LearnCSharpConn_server" providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Database=LearnCSharp;Integrated Security=True" />
    <add name="LearnCSharpConn" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\LearnCSharp.mdf;Integrated Security=True" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
</code>```

How EF decides which one to use?

答:
You could use this:

```<code>public class PeopleContext : DbContext
{
    public PeopleContext() : base("Database") //it makes reference to the connection string defined in the app.config
    {
    }
    public IDbSet<Person> People { get; set; }
}
</code>```

And in your app.config:

```<code><connectionStrings>
<add name="Database" connectionString="Data Source=source;Initial Catalog=Your_database;Integrated Security=True" providerName="System.Data.SqlClient" />
</code>```

Title: Default SQL Server for Entity Framework

Body:
I have two instances of SQL Server - SQLEXPRESS and MSSQLServer 2017. My Entity Framework test application creates database in SQLEXPRESS. Where is it defined which instance of SQL Server Entity Framework should use?

Test application:

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class PeopleContext : DbContext
    {
        public IDbSet<Person> People { get; set; }
    }

    static void Main(string[] args) // using DB
    {
        try
        {
            using (PeopleContext ctx = new PeopleContext())
            {
                ctx.People.Add(new Person() { Id = 1, Name = "John Doe" });
                ctx.SaveChanges();
            }

            using (PeopleContext ctx = new PeopleContext())
            {
                Person person = ctx.People.SingleOrDefault(p => p.Id == 1);
                Console.WriteLine(person.Name);
            }

        }
        catch (Exception e)
        {

            Console.WriteLine(e.Message);
        }

        Console.WriteLine("finish");
        Console.ReadLine();
    }

UPD:
I have several connection strings in my app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="LearnCSharpConn_server" providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Database=LearnCSharp;Integrated Security=True" />
    <add name="LearnCSharpConn" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\LearnCSharp.mdf;Integrated Security=True" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

How EF decides which one to use?

Body:
You could use this:

public class PeopleContext : DbContext
{
    public PeopleContext() : base("Database") //it makes reference to the connection string defined in the app.config
    {
    }
    public IDbSet<Person> People { get; set; }
}

And in your app.config:

<connectionStrings>
<add name="Database" connectionString="Data Source=source;Initial Catalog=Your_database;Integrated Security=True" providerName="System.Data.SqlClient" />


问:
Linq Groupby Elapsed Time
I need to group by a list by owner, town and "timeout".
I will explain "timeout":

```<code>public class Ticket
{
    public int pk { get; set; }
    public string owner { get; set; }
    public string reffering { get; set; }
    public DateTime? created_time { get; set; }
}
</code>```

And I got a List.
I want to create a List> where each sublist contains a list of tickets where created_time is less than 10 seconds.

Here is a sample list of tickets :

```<code>pk   owner   reffering   created_time
#1   John    Sam         15/11/2017 11:33:20
#2   John    Sam         15/11/2017 11:33:21
#3   Pat     Jerry       15/11/2017 11:33:27
#4   John    Sam         15/11/2017 11:33:28
#6   Pat     Jerry       15/11/2017 11:33:35
#5   John    Sam         15/11/2017 11:34:00
</code>```

And I need to get a list of list with

```<code>   pk   owner   reffering   created_time
---#1 Sub List ---
    #1   John    Sam         15/11/2017 11:33:20
    #2   John    Sam         15/11/2017 11:33:21
    #4   John    Sam         15/11/2017 11:33:28
---#2 Sub List ---
    #5   John    Sam         15/11/2017 11:34:00
---#3 Sub List ---
    #3   Pat     Jerry       15/11/2017 11:33:27
    #6   Pat     Jerry       15/11/2017 11:33:35
</code>```

Here my starting code but I can find out how to do this..

```<code>List<List<Ticket>> result = tickets.OrderBy(p => p.created_time).GroupBy(p => new { p.owner, p.reffering }).Select(g => g.ToList()).ToList();
</code>```

Hope some can help especially with the elapsed time.. it makes me crazy!

答:
I'm not quite sure you can do all of this with LINQ, here is my implementation as your references

```<code>var ticketGroups = tickets.OrderBy(x => x.created_time)
                            .GroupBy(x => new { x.owner, x.reffering });
var tensecondTimespam = new TimeSpan(0, 0, 10);
var results = new List<List<Ticket>>();
var ticketTemps = new List<Ticket>();

foreach (var ticketGroup in ticketGroups)
{
    foreach (var ticket in ticketGroup)
    {
        var currentTicket = ticketTemps.LastOrDefault();
        var isWithinTimeRange = currentTicket == null
                                || ticket.created_time.Value - currentTicket.created_time.Value <= tensecondTimespam;

        if (!isWithinTimeRange)
        {
            results.Add(ticketTemps);
            ticketTemps = new List<Ticket>();
        }
        ticketTemps.Add(ticket);
    }
    if (ticketTemps.Any())
    {
        results.Add(ticketTemps);
        ticketTemps = new List<Ticket>();
    }
}
</code>```

The result variable will hold your expected output

Title: Linq Groupby Elapsed Time

Body:
I need to group by a list by owner, town and "timeout".
I will explain "timeout":

public class Ticket
{
    public int pk { get; set; }
    public string owner { get; set; }
    public string reffering { get; set; }
    public DateTime? created_time { get; set; }
}

And I got a List.
I want to create a List> where each sublist contains a list of tickets where created_time is less than 10 seconds.

Here is a sample list of tickets :

pk   owner   reffering   created_time
#1   John    Sam         15/11/2017 11:33:20
#2   John    Sam         15/11/2017 11:33:21
#3   Pat     Jerry       15/11/2017 11:33:27
#4   John    Sam         15/11/2017 11:33:28
#6   Pat     Jerry       15/11/2017 11:33:35
#5   John    Sam         15/11/2017 11:34:00

And I need to get a list of list with

   pk   owner   reffering   created_time
---#1 Sub List ---
    #1   John    Sam         15/11/2017 11:33:20
    #2   John    Sam         15/11/2017 11:33:21
    #4   John    Sam         15/11/2017 11:33:28
---#2 Sub List ---
    #5   John    Sam         15/11/2017 11:34:00
---#3 Sub List ---
    #3   Pat     Jerry       15/11/2017 11:33:27
    #6   Pat     Jerry       15/11/2017 11:33:35

Here my starting code but I can find out how to do this..

List<List<Ticket>> result = tickets.OrderBy(p => p.created_time).GroupBy(p => new { p.owner, p.reffering }).Select(g => g.ToList()).ToList();

Hope some can help especially with the elapsed time.. it makes me crazy!

Body:
I'm not quite sure you can do all of this with LINQ, here is my implementation as your references

var ticketGroups = tickets.OrderBy(x => x.created_time)
                            .GroupBy(x => new { x.owner, x.reffering });
var tensecondTimespam = new TimeSpan(0, 0, 10);
var results = new List<List<Ticket>>();
var ticketTemps = new List<Ticket>();

foreach (var ticketGroup in ticketGroups)
{
    foreach (var ticket in ticketGroup)
    {
        var currentTicket = ticketTemps.LastOrDefault();
        var isWithinTimeRange = currentTicket == null
                                || ticket.created_time.Value - currentTicket.created_time.Value <= tensecondTimespam;

        if (!isWithinTimeRange)
        {
            results.Add(ticketTemps);
            ticketTemps = new List<Ticket>();
        }
        ticketTemps.Add(ticket);
    }
    if (ticketTemps.Any())
    {
        results.Add(ticketTemps);
        ticketTemps = new List<Ticket>();
    }
}

The result variable will hold your expected output


问:
Prevent page redirect on jQuery AJAX call with file Upload
My jQuery AJAX code was running smoothly until I appended the following file field to it:

```<code> 'profile_pic'      : $('input[type=file]')[0].files[0])
</code>```

All the other fields were text fields that were being received and processed just fine through the AJAX call. However, I had to include some code to handle the file uploaded (size, type) on the processing PHP file.

Now on clicking the submit button on the form, the entire page redirects to the PHP file (YES all the data is captured and committed to the database), rather than doing it through AJAX like it was before without redirecting the entire page. What could I have done wrong? Is there an extra parameter I need to put in to further prevent this redirect?

The jQuery AJAX call:

```<code>var formData = {
        'name'              : $('input[name=name]').val(),
        'email'             : $('input[name=email]').val(),
        'superheroAlias'    : $('input[name=superheroAlias]').val(),
        'profile_pic'       : $('input[type=file]')[0].files[0])
    };

    // process the form
    $.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : formData,
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })
</code>```

The code to handle the file upload:

```<code>$target_dir = "image_uploads/";
    $target_file = $target_dir .rand(1,999). basename(str_replace(" ","",$_FILES["profile_pic"]["name"]));
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is an actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["profile_pic"]["tmp_name"]);
        if($check !== false) {
            $uploadOk = 1;
        } else {
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["profile_pic"]["size"] > 500000) {
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
    // if everything is ok, try to upload file
    } else {
        move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $target_file);
    }
</code>```

答:
Actually for sending the form data to the back-end, you don't need to create an object like this. Here you are adding each input values individually. Its not a good manner. You know, how the code will looks like if there is 100 fields in your form ?

Yeah, you can use FormData for getting all the input values from a form. So changing your code as below:

```<code>var formData = new FormData(document.getElementById('#your-form-id'));

// process the form
$.ajax({
    type        : 'POST',
    url         : 'process.php',
    data        : formData,
    dataType    : 'json',
    processData : false,
    contentType : false,
    encode      : true
})
</code>```

Body:
My jQuery AJAX code was running smoothly until I appended the following file field to it:

 'profile_pic'      : $('input[type=file]')[0].files[0])

All the other fields were text fields that were being received and processed just fine through the AJAX call. However, I had to include some code to handle the file uploaded (size, type) on the processing PHP file.

Now on clicking the submit button on the form, the entire page redirects to the PHP file (YES all the data is captured and committed to the database), rather than doing it through AJAX like it was before without redirecting the entire page. What could I have done wrong? Is there an extra parameter I need to put in to further prevent this redirect?

The jQuery AJAX call:

var formData = {
        'name'              : $('input[name=name]').val(),
        'email'             : $('input[name=email]').val(),
        'superheroAlias'    : $('input[name=superheroAlias]').val(),
        'profile_pic'       : $('input[type=file]')[0].files[0])
    };

    // process the form
    $.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : formData,
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })

The code to handle the file upload:

$target_dir = "image_uploads/";
    $target_file = $target_dir .rand(1,999). basename(str_replace(" ","",$_FILES["profile_pic"]["name"]));
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is an actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["profile_pic"]["tmp_name"]);
        if($check !== false) {
            $uploadOk = 1;
        } else {
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["profile_pic"]["size"] > 500000) {
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
    // if everything is ok, try to upload file
    } else {
        move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $target_file);
    }

Body:
Actually for sending the form data to the back-end, you don't need to create an object like this. Here you are adding each input values individually. Its not a good manner. You know, how the code will looks like if there is 100 fields in your form ?

Yeah, you can use FormData for getting all the input values from a form. So changing your code as below:

var formData = new FormData(document.getElementById('#your-form-id'));

// process the form
$.ajax({
    type        : 'POST',
    url         : 'process.php',
    data        : formData,
    dataType    : 'json',
    processData : false,
    contentType : false,
    encode      : true
})


问:
typeof 90/'hi' is NaN while typeof (90/'hi') is number. Why so?
I was playing around the NaN of JavaScript and found some strange behavior while using typeof operator on a result of number/string.
why so?</p>

答:
my guess is that when you write typeof 90/'hi' it first gets the type of 90 (number) and then divides it by 'hi' which produces the NaN. Basically it's equal to 'number'/'hi'.
When you include 90/'hi' in brackets it first gets the NaN from the division of number (90) by string 'hi' and then gets the type of NaN, which is 'number'.


问:
Getting the source code of an iframe
Is there anyway to get the source code of the page that an iframe loaded? I do not wish to CHANGE any of the code, I just want to READ it. I also need to be able to get this using javascript/html.</p>

答: See https://developer.mozilla.org/en/HTML/Element/iframe#Scripting for how Mozilla-based browsers handle it. There should be abstractions in Your Favorite JavaScript Library that will handle the inevitable naming differences between IE, WebKit, Gecko, etc DOMs.</p>

Title: Getting the source code of an iframe


问:
Display Data based on Selected Items Laravel
After selecting data from a dropdown list how can I display a table by the selected data? For example: selected Employee and Month and I need to show table just this employee and from November.

My Controller:

```<code>public function look(Request $request)
{
    $routes = RouteInfo::all();
    return view('admin.look', compact('routes', $routes));
}
</code>```

Thank you for your help

答:
Try this query :

```<code>$routes = RouteInfo::whereHas('users', function ($query) use($request) {
                $query->where('id', $request->userId);
            })
            ->where('id', $request->monthId)
            ->get();
</code>```

Ps : assuming that you have a :

users relationship in the RouteInfo model.

userName and month in your inputs names => $request->userId and $request->monthId else rename them to what you have !

Body:
After selecting data from a dropdown list how can I display a table by the selected data? For example: selected Employee and Month and I need to show table just this employee and from November.

My Controller:

public function look(Request $request)
{
    $routes = RouteInfo::all();
    return view('admin.look', compact('routes', $routes));
}

Thank you for your help

Body:
Try this query :

$routes = RouteInfo::whereHas('users', function ($query) use($request) {
                $query->where('id', $request->userId);
            })
            ->where('id', $request->monthId)
            ->get();

Ps : assuming that you have a :

users relationship in the RouteInfo model.

userName and month in your inputs names => $request->userId and $request->monthId else rename them to what you have !


问:
C# Regex split() without removing the split condition character
I am splitting a string with regex using its Split() method.

```<code>var splitRegex = new Regex(@"[\s|{]");

string input = "/Tests/ShowMessage { 'Text': 'foo' }";

//second version of the input:
//string input = "/Tests/ShowMessage{ 'Text': 'foo' }";

string[] splittedText = splitRegex.Split(input, 2);
</code>```

The string is just a sample pattern of the input. There are two different structures of input, once with a space before the { or without the space. I want to split the input on the { bracket in order to get the following result:

/Tests/ShowMessage

{ 'Text': 'foo' }

If there is a space, the string gets splitted there (space gets removed) and i get my desired result. But if there isnt a space i split the string on the {, so the { gets removed, what i dont want though. How can i use Regex.Split() without removing the split condition character?

答:
In order to not include the curly brace in the match you can put it into a look ahead

```<code>\s*(?={)
</code>```

That will match any number of white spaces up to the position before a open curly brace.

Body:
I am splitting a string with regex using its Split() method.

var splitRegex = new Regex(@"[\s|{]");

string input = "/Tests/ShowMessage { 'Text': 'foo' }";

//second version of the input:
//string input = "/Tests/ShowMessage{ 'Text': 'foo' }";

string[] splittedText = splitRegex.Split(input, 2);

The string is just a sample pattern of the input. There are two different structures of input, once with a space before the { or without the space. I want to split the input on the { bracket in order to get the following result:

/Tests/ShowMessage

{ 'Text': 'foo' }

If there is a space, the string gets splitted there (space gets removed) and i get my desired result. But if there isnt a space i split the string on the {, so the { gets removed, what i dont want though. How can i use Regex.Split() without removing the split condition character?

Body:
In order to not include the curly brace in the match you can put it into a look ahead

\s*(?={)

That will match any number of white spaces up to the position before a open curly brace.


问:
ReferenceError: "Sheets" is not defined
This is my first attempt with script editor. I was assigned to do a script to crate pivot table for google sheet.

```<code>  //creating pivot table through script editor for google sheet
  function addPivotTable() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetName = "Sheet1";

  // Create a new sheet which will contain our Pivot Table
  var pivotTableSheet = ss.insertSheet();
  var pivotTableSheetId = pivotTableSheet.getSheetId();

 // Add Pivot Table to new sheet
 // Meaning we send an 'updateCells' request to the Sheets API
 // Specifying via 'start' the sheet where we want to place our Pivot Table
 // And in 'rows' the parameters of our Pivot Table

  var requests = [{
    // Meaning we send an 'updateCells' request to the Sheets API
    "updateCells": {
        // And in 'rows' the parameters of our Pivot Table
       "rows": {
         "values": [
      {
         // Add Pivot Table to new sheet
        "pivotTable": {
          "source": {
            "sheetId": ss.getSheetByName(sheetName).getSheetId(),
            "startRowIndex": 0,
            "startColumnIndex": 0,
          },
          //create rows from the selected columns
          "rows": [
            {
              "sourceColumnOffset": 14,
              "showTotals": true,
              "sortOrder": "ASCENDING",
            },
          ],
          //show values from the selected columns
          "values": [
            {
              "summarizeFunction": "COUNTA",
              "sourceColumnOffset": 10
            }
          ],
          //display in horizontal layout
          "valueLayout": "HORIZONTAL"
        }
      }
    ]
  },
  // Specifying via 'start' the sheet where we want to place our Pivot Table
  "start": {
    "sheetId": pivotTableSheetId,
  },
  "fields": "pivotTable"
}
 }];

  Sheets.Spreadsheets.batchUpdate({'requests': [requests]}, ss.getId());
}
</code>```

Please do check my code and explain where did i went  wrong as every time im running the script editor error telling sheet is not defined popup.
"ReferenceError: "Sheets" is not defined. (line 46, file "Code")Dismiss"

答:
This an advanced service from google. You need to enable this service before using it.
https://developers.google.com/apps-script/guides/services/advanced
In the script editor, select Resources > Advanced Google services....
In the dialog that appears, click the on/off switch next to the service you want to use.
At the bottom of the dialog, click the link for the Google API Console.
In the console, click into the filter box and type part of the name of the API (for example, "Calendar"), then click the name once you see it.
On the next screen, click Enable API.
Close the API Console and return to the script editor. Click OK in the dialog. The advanced service you enabled is now available in autocomplete.</p>

Title: ReferenceError: "Sheets" is not defined

Body:
This is my first attempt with script editor. I was assigned to do a script to crate pivot table for google sheet.

  //creating pivot table through script editor for google sheet
  function addPivotTable() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetName = "Sheet1";

  // Create a new sheet which will contain our Pivot Table
  var pivotTableSheet = ss.insertSheet();
  var pivotTableSheetId = pivotTableSheet.getSheetId();

 // Add Pivot Table to new sheet
 // Meaning we send an 'updateCells' request to the Sheets API
 // Specifying via 'start' the sheet where we want to place our Pivot Table
 // And in 'rows' the parameters of our Pivot Table

  var requests = [{
    // Meaning we send an 'updateCells' request to the Sheets API
    "updateCells": {
        // And in 'rows' the parameters of our Pivot Table
       "rows": {
         "values": [
      {
         // Add Pivot Table to new sheet
        "pivotTable": {
          "source": {
            "sheetId": ss.getSheetByName(sheetName).getSheetId(),
            "startRowIndex": 0,
            "startColumnIndex": 0,
          },
          //create rows from the selected columns
          "rows": [
            {
              "sourceColumnOffset": 14,
              "showTotals": true,
              "sortOrder": "ASCENDING",
            },
          ],
          //show values from the selected columns
          "values": [
            {
              "summarizeFunction": "COUNTA",
              "sourceColumnOffset": 10
            }
          ],
          //display in horizontal layout
          "valueLayout": "HORIZONTAL"
        }
      }
    ]
  },
  // Specifying via 'start' the sheet where we want to place our Pivot Table
  "start": {
    "sheetId": pivotTableSheetId,
  },
  "fields": "pivotTable"
}
 }];

  Sheets.Spreadsheets.batchUpdate({'requests': [requests]}, ss.getId());
}

Please do check my code and explain where did i went  wrong as every time im running the script editor error telling sheet is not defined popup.
"ReferenceError: "Sheets" is not defined. (line 46, file "Code")Dismiss"


问:
Error:No such property: zipAlignEnabled for class: com.android.build.gradle.internal.variant.ApplicationVariantData
I am getting this error continuously when I try to build my old project in Android Studio 3.0

Here's my gradle file:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.github.triplet.gradle:play-publisher:1.1.4'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'com.google.guava:guava:19.0'
        classpath 'me.tatarka:gradle-retrolambda:3.3.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        flatDir {
            dirs 'libs'
        }
    }
}
</code>```

答: For me the problem was with classpath 'com.github.triplet.gradle:play-publisher:1.1.4'. I upgraded it to com.github.triplet.gradle:play-publisher:1.2.0 and the error went away.

Body:
I am getting this error continuously when I try to build my old project in Android Studio 3.0

Here's my gradle file:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.github.triplet.gradle:play-publisher:1.1.4'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'com.google.guava:guava:19.0'
        classpath 'me.tatarka:gradle-retrolambda:3.3.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        flatDir {
            dirs 'libs'
        }
    }
}


问:
mapping bytes produces int but single element bytes object is required
Mapping a bytes type with the following lambda

```<code>unpack = lambda val: struct.unpack("!b", val)[0]

list(map(unpack, b'\xb1\xbb\n\x0f'))
</code>```

gives the error

```<code>TypeError: a bytes-like object is required, not 'int'
</code>```

The documentation says

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

which explains why an int is passed. So if i would manually loop over the bytes object, i could access the elements with [x:x+1] instead of with [x].

My question now would be if there is a way to make map produce bytes object of length 1, so that the unpack function gets what it expects.

I found that this works

```<code>unpack = lambda val: struct.unpack("!b", bytes(bytearray([val])))[0]
</code>```

but it seems like an ugly workaround to me. Is there a better, more concise way of doing this?

答:
A more concise way doesn't exist yet from what I'm aware. A proposition has been made but it's still a draft.

You still have some other options in order to make it appear more friendly, though. For example, a little generator that produces bytes:

```<code>def iterbytes(b):
    for n in range(len(b)):
        yield b[n:n+1]
</code>```

or, similarly but probably slower:

```<code>def iterbytes(b):
    for i in b:
        yield bytes([i])
</code>```

Then wrap the bytes object in this iterbytes generator:

```<code>list(map(unpack, iterbytes(b'\xb1\xbb\n\x0f')))
</code>```

Since you wrap map in list, i.e you're after a list, I'd probably go with a comprehension instead of a map:

```<code>>>> b = b'\xb1\xbb\n\x0f'
>>> [unpack(b[i:i+1]) for i in range(len(b))]
[-79, -69, 10, 15]
</code>```

Body:
Mapping a bytes type with the following lambda

unpack = lambda val: struct.unpack("!b", val)[0]

list(map(unpack, b'\xb1\xbb\n\x0f'))

gives the error

TypeError: a bytes-like object is required, not 'int'

The documentation says

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

which explains why an int is passed. So if i would manually loop over the bytes object, i could access the elements with [x:x+1] instead of with [x].

My question now would be if there is a way to make map produce bytes object of length 1, so that the unpack function gets what it expects.

I found that this works

unpack = lambda val: struct.unpack("!b", bytes(bytearray([val])))[0]

but it seems like an ugly workaround to me. Is there a better, more concise way of doing this?

Body:
A more concise way doesn't exist yet from what I'm aware. A proposition has been made but it's still a draft.

You still have some other options in order to make it appear more friendly, though. For example, a little generator that produces bytes:

def iterbytes(b):
    for n in range(len(b)):
        yield b[n:n+1]

or, similarly but probably slower:

def iterbytes(b):
    for i in b:
        yield bytes([i])

Then wrap the bytes object in this iterbytes generator:

list(map(unpack, iterbytes(b'\xb1\xbb\n\x0f')))

Since you wrap map in list, i.e you're after a list, I'd probably go with a comprehension instead of a map:

>>> b = b'\xb1\xbb\n\x0f'
>>> [unpack(b[i:i+1]) for i in range(len(b))]
[-79, -69, 10, 15]


问:
DOORS DXL Relational Expression Search
Does anyone have a script that will search one column for a specific text and then copy that text to a new column? The text needs to match the first 3 characters and if they match then copy the entire word which could be up to 8 characters.
Thanks in advance. </p>

答:
Okay, let's assume the attribute you're searching is 'Object Text'

First, we need to create a new attribute to hold our result - we'll call it 'New Attribute'

```<code>create type "String" attribute "New Attribute"
</code>```

Next we need to add this to our view so we can see it. This code counts the number of columns and adds one at the end tied to our new attribute.

```<code>int z = 0
Module m = current
Column c
for c in m do {
    z++
}
c = insert ( column z )
title ( c , "New Attribute" )
attribute ( c , "New Attribute" )
width ( c , 100 )
</code>```

Now we need to actually grab the relevant info and populate our new attribute. Let's say that we are matching the first three characters, and those are 'XYZ'. Also, let's further state that we will then go to the end of the word, so if we find an 'XYZ', go until you hit a space.

```<code>Object o
Regexp string_find = regexp2 "XYZ"
string item_to_search
string word_to_copy
for o in m do {
    item_to_search = o."Object Text"
    if ( string_find item_to_search ) {
        int x = start 0
        int y = end 0
        while ( ( item_to_search[ y ] != ' ' ) && ( y < length ( item_to_search ) ) ) {
            y++
        }
        o."New Attribute" = item_to_search [ x : ( y - 1 ) ]
    }
}
</code>```

I'm sure there's a more elegant way to set this all up, but this is the first solution that occurs to me assuming the constraints you defined are true.

Title: DOORS DXL Relational Expression Search

Body:
Okay, let's assume the attribute you're searching is 'Object Text'

First, we need to create a new attribute to hold our result - we'll call it 'New Attribute'

create type "String" attribute "New Attribute"

Next we need to add this to our view so we can see it. This code counts the number of columns and adds one at the end tied to our new attribute.

int z = 0
Module m = current
Column c
for c in m do {
    z++
}
c = insert ( column z )
title ( c , "New Attribute" )
attribute ( c , "New Attribute" )
width ( c , 100 )

Now we need to actually grab the relevant info and populate our new attribute. Let's say that we are matching the first three characters, and those are 'XYZ'. Also, let's further state that we will then go to the end of the word, so if we find an 'XYZ', go until you hit a space.

Object o
Regexp string_find = regexp2 "XYZ"
string item_to_search
string word_to_copy
for o in m do {
    item_to_search = o."Object Text"
    if ( string_find item_to_search ) {
        int x = start 0
        int y = end 0
        while ( ( item_to_search[ y ] != ' ' ) && ( y < length ( item_to_search ) ) ) {
            y++
        }
        o."New Attribute" = item_to_search [ x : ( y - 1 ) ]
    }
}

I'm sure there's a more elegant way to set this all up, but this is the first solution that occurs to me assuming the constraints you defined are true.


问:
Share mongoDB instance in multiple modules using Express
I new to express. Now i am working in mongodb connection and CRUD activity. I created a connection in connection.js. And i get the database instance in app.js. The same DB instance i need to share register, login and some other modules without calling connection.js in these modules again. Or i need the proper answer to resuse connection in multiple modules in express.

Thanks in Advance,

答:
You can setup a db module like so:

// db.js

```<code>let _db;

module.exports = {
    getDb,
    initDb
};

function initDb(callback) {
    //connect to db and set _db to the new connection.
}

function getDb() {
    assert.ok(_db, "Db has not been initialized. Please called init first.");
    return _db;
}
</code>```

Then somewhere in your app initialization you can do:

//app.js

```<code>const dbmodule = require("./db.js");
initDb(function(err){
    // more app init;
});
</code>```

then in your other modules, say login.js, do:

//login.js

```<code>const dmModule = require("./db")
const db = dbModule.getDb() //at this point the db should have been initialized.
</code>```

Body:
You can setup a db module like so:

// db.js

let _db;

module.exports = {
    getDb,
    initDb
};

function initDb(callback) {
    //connect to db and set _db to the new connection.
}

function getDb() {
    assert.ok(_db, "Db has not been initialized. Please called init first.");
    return _db;
}

Then somewhere in your app initialization you can do:

//app.js

const dbmodule = require("./db.js");
initDb(function(err){
    // more app init;
});

then in your other modules, say login.js, do:

//login.js

const dmModule = require("./db")
const db = dbModule.getDb() //at this point the db should have been initialized.


答:
You can use regular string split, on "{" and trim the spaces off:

```<code>var bits = "/Tests/ShowMessage { 'Text': 'foo' }".Split("{", StringSplitOptions.RemoveEmptyEntries);
bits[0] = bits[0].TrimEnd();
bits[1] = "{" + bits[1];
</code>```

If you want to use the RegEx route, you can add the { back if you change the regex a bit:

```<code>var splitRegex = new Regex(@"\s*{");

string input = "/Tests/ShowMessage { 'Text': 'foo' }";

//second version of the input:
//string input = "/Tests/ShowMessage{ 'Text': 'foo' }";

string[] splittedText = splitRegex.Split(input, 2);
splittedText[1] = "{" + splittedText[1];
</code>```

It means "split at occurrence of (zero or more whitespace followed by {)" - so the split operation nukes your spaces (you want), and your { (you don't want) but you can put the { back with certainty that it will mean you get what you want

Title: C# Regex split() without removing the split condition character

Body:
You can use regular string split, on "{" and trim the spaces off:

var bits = "/Tests/ShowMessage { 'Text': 'foo' }".Split("{", StringSplitOptions.RemoveEmptyEntries);
bits[0] = bits[0].TrimEnd();
bits[1] = "{" + bits[1];

If you want to use the RegEx route, you can add the { back if you change the regex a bit:

var splitRegex = new Regex(@"\s*{");

string input = "/Tests/ShowMessage { 'Text': 'foo' }";

//second version of the input:
//string input = "/Tests/ShowMessage{ 'Text': 'foo' }";

string[] splittedText = splitRegex.Split(input, 2);
splittedText[1] = "{" + splittedText[1];

It means "split at occurrence of (zero or more whitespace followed by {)" - so the split operation nukes your spaces (you want), and your { (you don't want) but you can put the { back with certainty that it will mean you get what you want


问:
Why is the ScrollView jumping up and down when returning to main view on iOS?
I am working on an app using NativeScript with Angular and am running into an issue with the ScrollView element. In short, the issue is that I have an initial view with a list of items and if I press on one of the items to go to a detail view and return to the initial view, the scroll will jump and create a gap on top and then jump back with the gap disappearing.

Here is a GIF of the issue:

As you can see, when you return the the initial view, there is a gap created and I haven't been able to figure out why that happens. The ActionBar is disabled programmatically, I tried removing it altogether or leaving it visible, but it didn't make a difference.

The code that I used is no different than the Angular and TypeScript template that can be installed using the following command: tns create MyApp --ng or can also be found on GitHub.

All I did then is disable the ActionBar and change items.component.html to:

```<code><GridLayout>
  <ScrollView>
    <StackLayout>
      <StackLayout *ngFor="let item of items" [nsRouterLink]="['/item', item.id]">
        <AbsoluteLayout style.backgroundColor="gray">
          <FlexboxLayout left="15" top="110" flexDirection="column">
            <Label [text]="item.id"></Label>
            <Label [text]="item.name"></Label>
          </FlexboxLayout>
        </AbsoluteLayout>
      </StackLayout>
    </StackLayout>
  </ScrollView>
</GridLayout>
</code>```

I have stripped away all unnecessary styling in order to pinpoint what the issue is and it seems like the culprit is the AbsoluteLayout element. Removing it makes the issue go away, but I have been unable to figure out why it causes the issue in the first place. I am fully aware of the existence of the ListView element, but would like to use a fully custom list for more customization.

As for my programming environment, I am running on NativeScript version 3.3.0 with tns-core-modules and tns-ios also on 3.3.0. Everything was tested on an actual iPhone with iOS 11.

So my question is: Why does this issue occur and how can it be solved?

答:
I noticed that the space above the ScrollView is as high as the iOS status bar leading me to believe that this is an iOS specific issue. Furthermore, I found a feature request for a translucent status bar on GitHub. The solution proposed is to add the following to the controller of the page:

```<code>this._page.style.marginTop = -20;
</code>```

This solved my ScrollView issue, the same issue can also be solved by adding a StackLayout with a height of 20 as the first element in a view, but this would ruin most user interfaces.

Body:
I am working on an app using NativeScript with Angular and am running into an issue with the ScrollView element. In short, the issue is that I have an initial view with a list of items and if I press on one of the items to go to a detail view and return to the initial view, the scroll will jump and create a gap on top and then jump back with the gap disappearing.

Here is a GIF of the issue:

As you can see, when you return the the initial view, there is a gap created and I haven't been able to figure out why that happens. The ActionBar is disabled programmatically, I tried removing it altogether or leaving it visible, but it didn't make a difference.

The code that I used is no different than the Angular and TypeScript template that can be installed using the following command: tns create MyApp --ng or can also be found on GitHub.

All I did then is disable the ActionBar and change items.component.html to:

<GridLayout>
  <ScrollView>
    <StackLayout>
      <StackLayout *ngFor="let item of items" [nsRouterLink]="['/item', item.id]">
        <AbsoluteLayout style.backgroundColor="gray">
          <FlexboxLayout left="15" top="110" flexDirection="column">

          </FlexboxLayout>
        </AbsoluteLayout>
      </StackLayout>
    </StackLayout>
  </ScrollView>
</GridLayout>

I have stripped away all unnecessary styling in order to pinpoint what the issue is and it seems like the culprit is the AbsoluteLayout element. Removing it makes the issue go away, but I have been unable to figure out why it causes the issue in the first place. I am fully aware of the existence of the ListView element, but would like to use a fully custom list for more customization.

As for my programming environment, I am running on NativeScript version 3.3.0 with tns-core-modules and tns-ios also on 3.3.0. Everything was tested on an actual iPhone with iOS 11.

So my question is: Why does this issue occur and how can it be solved?

Body:
I noticed that the space above the ScrollView is as high as the iOS status bar leading me to believe that this is an iOS specific issue. Furthermore, I found a feature request for a translucent status bar on GitHub. The solution proposed is to add the following to the controller of the page:

this._page.style.marginTop = -20;

This solved my ScrollView issue, the same issue can also be solved by adding a StackLayout with a height of 20 as the first element in a view, but this would ruin most user interfaces.


问:
Get values from an array of objects
I am looping through my array to get the corresponding field value:

```<code>var someFun = function (nm) {
    var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];

    for (var i=0; i < names.length; i++) {
        if (names[i].name === nm) return names[i].age;
    }
};

var username = 'tom';
var printme = someFun(username);
console.log('hey: ', printme)
</code>```

How can I do the same using Object.keys(), or map, or forEach? Much cleaner and ES6 compliant.

答:
Simply use find

```<code>([{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}].find( (s)=> s.name=="tom" )||{}).age //10

([{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}].find( (s)=> s.name=="tom2" )||{}).age //undefined
</code>```

Demo

var names = [{
  name: 'joe',
  age: 'nine'
}, {
  name: 'tom',
  age: 'ten'
}];

function getAge(names, name) {
  return (names.find((s) => s.name == name) || {}).age;
}

console.log(getAge(names, "tom"))
console.log(getAge(names, "tom2"))```

Title: Get values from an array of objects

Body:
I am looping through my array to get the corresponding field value:

var someFun = function (nm) {
    var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];

    for (var i=0; i < names.length; i++) {
        if (names[i].name === nm) return names[i].age;
    }
};

var username = 'tom';
var printme = someFun(username);
console.log('hey: ', printme)

How can I do the same using Object.keys(), or map, or forEach? Much cleaner and ES6 compliant.

Body:
Simply use find

([{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}].find( (s)=> s.name=="tom" )||{}).age //10

([{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}].find( (s)=> s.name=="tom2" )||{}).age //undefined

Demo

var names = [{
  name: 'joe',
  age: 'nine'
}, {
  name: 'tom',
  age: 'ten'
}];

function getAge(names, name) {
  return (names.find((s) => s.name == name) || {}).age;
}

console.log(getAge(names, "tom"))
console.log(getAge(names, "tom2"))


问:
Tables using JavaMail
I am sending an e-mail using JavaMail and I want to put my message data into a table that will be embedded in the e-mail. The person receiving the message will see the table with the filled in data. How do I go about doing this?</p>

答:
Java Html mail

```<code>    MimeMessage message =mailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
        String htmlMsg = "<body><h4 style='color:green;'> Dear <b style='color:red;'>" + userName.getFirstName() + "</b>,"
                + "\n Your produce information is successfully uploaded with following details, <br><table>"
                + "<tr><td>Item Name     </td><td>  " + produce.getItemName() + "</td></tr>"
                + "<tr><td>Units   </td><td>  " + produce.getMinUnits() + "</td></tr>"
                + "<tr><td>Last date   </td><td> " + produce.getLastDate() + "</td></tr>"
                + "</h4</body>";
        message.setContent(htmlMsg, "text/html");
        helper.setTo(emailId);
        helper.setSubject(subject);
        result="success";
        mailSender.send(message);
    } catch (MessagingException e) {
        throw new MailParseException(e);
    }finally {
        if(result !="success"){
            result="fail";
        }
    }
</code>```

Title: Tables using JavaMail

Body:
Java Html mail

    MimeMessage message =mailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
        String htmlMsg = "<body><h4 style='color:green;'> Dear <b style='color:red;'>" + userName.getFirstName() + "</b>,"
                + "\n Your produce information is successfully uploaded with following details, <br><table>"
                + "<tr><td>Item Name     </td><td>  " + produce.getItemName() + "</td></tr>"
                + "<tr><td>Units   </td><td>  " + produce.getMinUnits() + "</td></tr>"
                + "<tr><td>Last date   </td><td> " + produce.getLastDate() + "</td></tr>"
                + "</h4</body>";
        message.setContent(htmlMsg, "text/html");
        helper.setTo(emailId);
        helper.setSubject(subject);
        result="success";
        mailSender.send(message);
    } catch (MessagingException e) {
        throw new MailParseException(e);
    }finally {
        if(result !="success"){
            result="fail";
        }
    }


问:
How to download file over SSH from remote server in jenkins?
I am using Publish Over SSH plugin in Jenkins to transfer the files over to remote server from local and execute some commands on the remote server.

But, it seems like there is no option available in this plugin to download files from remote server to local.

Can some one assist how can i achieve this?

答:
From a pipeline perspective I have this workaround

First download in you Jenkins server instance

```<code>stage("Download") {
  steps {
    fileOperations([fileDownloadOperation(password: "", targetFileName: "${params.APP_KEY}.zip", targetLocation: "${params.HOME_PATH}", url: "${params.ARTIFACT_URL}", userName: "")])
  }
}
</code>```

and then copy with a scp instrucction

```<code>stage("Download last version") {
  sshagent(['xxxx-xxxx-xxxx-xxxx-xxxx']) {
    sh "scp ${params.APP_KEY_PATH}/${params.APP_KEY}.ZIP ${params.REMOTE_SERVER_USER}@${params.REMOTE_SERVER_URL}:${params.REMOTE_APP_KEY_PATH}"
  }
}
</code>```

For brevity I am avoiding to put another steps that I change a little bit what I do
But the idea is to do the following steps

Download the artifact (locally)

Unzip (locally)

Create a file with the script I want to execute in the remote server (locally)

Copy the script to the remote server

Copy the unziped artifact to the remote server

Execute the script

Body:
From a pipeline perspective I have this workaround

First download in you Jenkins server instance

stage("Download") {
  steps {
    fileOperations([fileDownloadOperation(password: "", targetFileName: "${params.APP_KEY}.zip", targetLocation: "${params.HOME_PATH}", url: "${params.ARTIFACT_URL}", userName: "")])
  }
}

and then copy with a scp instrucction

stage("Download last version") {
  sshagent(['xxxx-xxxx-xxxx-xxxx-xxxx']) {
    sh "scp ${params.APP_KEY_PATH}/${params.APP_KEY}.ZIP ${params.REMOTE_SERVER_USER}@${params.REMOTE_SERVER_URL}:${params.REMOTE_APP_KEY_PATH}"
  }
}

For brevity I am avoiding to put another steps that I change a little bit what I do
But the idea is to do the following steps

Download the artifact (locally)

Unzip (locally)

Create a file with the script I want to execute in the remote server (locally)

Copy the script to the remote server

Copy the unziped artifact to the remote server

Execute the script


问:
Call pyplot from a function to draw multiple lines on the same plot
When I want to drow multiple lines on the same plot, I can just call pyplot.plot(x,y) as many times as I want and then show the plot with pyplot.show(). However, when I define a function to plot, and I call that function multiple times, instead of having multiple lines on the same plot, I get multiple plots. For example:

```<code>import numpy as np
import matplotlib.pyplot as plt

def plotsub(x, y):
    plt.plot(x, y)
    plt.show()

x = np.arange(0,10,1);
y = x*x
plt.plot(x,y)
plt.plot(x*10,y)
plt.show()

plotsub(x,y)
plotsub(x*10,y)
</code>```

The output of the above code is like this:

However, I would like the two calls to plotsub to act just as the way calling plt.plot multiple times acts.

Basically, I am trying to obtain a handle for pyplot to send it to a function as an argument, which I cannot find how to do.

答:
It's because you have plt.show() inside your plotsub function. So each time you call plotsub, matplotlib shows the plot, as expected.

If you only want to show the plot after all your calls to plotsub, you could move that outside the function:

```<code>import numpy as np
import matplotlib.pyplot as plt

def plotsub(x, y):
    plt.plot(x, y)

x = np.arange(0,10,1);
y = x*x

plotsub(x,y)
plotsub(x*10,y)
plt.show()
</code>```

Alternatively, you could leave it inside the function, but make it optional, so you only show in the last call to plotsub. Something like:

```<code>import numpy as np
import matplotlib.pyplot as plt

def plotsub(x, y, show=False):
    plt.plot(x, y)
    if show:
        plt.show()

x = np.arange(0,10,1);
y = x*x

plotsub(x, y)
plotsub(x*10, y, show=True)
</code>```

Finally, to get a reference to the line that you plot in the function, you can return that from the function, like so:

```<code>def plotsub(x, y, show=False):
    line, = plt.plot(x, y)
    if show:
        plt.show()
    return line

l1 = plotsub(x, y)
</code>```

Body:
When I want to drow multiple lines on the same plot, I can just call pyplot.plot(x,y) as many times as I want and then show the plot with pyplot.show(). However, when I define a function to plot, and I call that function multiple times, instead of having multiple lines on the same plot, I get multiple plots. For example:

import numpy as np
import matplotlib.pyplot as plt

def plotsub(x, y):
    plt.plot(x, y)
    plt.show()

x = np.arange(0,10,1);
y = x*x
plt.plot(x,y)
plt.plot(x*10,y)
plt.show()

plotsub(x,y)
plotsub(x*10,y)

The output of the above code is like this:

However, I would like the two calls to plotsub to act just as the way calling plt.plot multiple times acts.

Basically, I am trying to obtain a handle for pyplot to send it to a function as an argument, which I cannot find how to do.

Body:
It's because you have plt.show() inside your plotsub function. So each time you call plotsub, matplotlib shows the plot, as expected.

If you only want to show the plot after all your calls to plotsub, you could move that outside the function:

import numpy as np
import matplotlib.pyplot as plt

def plotsub(x, y):
    plt.plot(x, y)

x = np.arange(0,10,1);
y = x*x

plotsub(x,y)
plotsub(x*10,y)
plt.show()

Alternatively, you could leave it inside the function, but make it optional, so you only show in the last call to plotsub. Something like:

import numpy as np
import matplotlib.pyplot as plt

def plotsub(x, y, show=False):
    plt.plot(x, y)
    if show:
        plt.show()

x = np.arange(0,10,1);
y = x*x

plotsub(x, y)
plotsub(x*10, y, show=True)

Finally, to get a reference to the line that you plot in the function, you can return that from the function, like so:

def plotsub(x, y, show=False):
    line, = plt.plot(x, y)
    if show:
        plt.show()
    return line

l1 = plotsub(x, y)


问:
How to get html from mongodb?
I have collection

```<code>{
    "_id" : 1,
    "title" : "Title",
    "description" : "<p>Text ...</p>",
}
</code>```

I need to get the description in Angular.
But when I output this data, I get a string
Text ...
 instead of a tag

答:
Try this:</p>

```<code><span [innerHtml]="yourObject.description"></span>
</code>```

Title: How to get html from mongodb?

Body:
I have collection

{
    "_id" : 1,
    "title" : "Title",
    "description" : "
Text ...
",
}

I need to get the description in Angular.
But when I output this data, I get a string
Text ...
 instead of a tag

Body:
Try this:

<span [innerHtml]="yourObject.description"></span>


问:
python - Generate a random binary tree with n vertices
I am debugging an algorithms task, and for the purpose of testing I want to generate a binary tree with n vertices rooted at 0, in other words, generate a sequence of pairs so that if the i-th pair in the sequence is (a,b), then the left child of i-th node is a, and the right child is b, except when a (or b) = -1, then i-th node has no left (or right) child. (e. g. a sequence: (1, 2), (-1, -1), (-1, -1) is a tree with the root (0), and two children (1 and 2))
I wrote the following python recursive function, where listAdd is the desired pair list, listDel is all vertices not yet generated, and n is the node currently being looked at:

``` <code>
def generateTree(listAdd, listDel, n):
    if not listDel:
        return
    ifLeft = bool(randint(0,1))
    ifRight = bool(randint(0,1))
    if ifLeft:
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (chosen, listAdd[n][1])
        generateTree(listAdd, listDel, chosen)
    else:
        listAdd[n] = (-1, listAdd[n][1])
    if not listDel:
        return
    if ifRight:
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (listAdd[n][0], chosen)
        generateTree(listAdd, listDel, chosen)
    else:
        listAdd[n] = (listAdd[n][0], -1)
</code>```

However, upon writing it, I noticed that this does not work correctly, as it is possible for the function to stop after just one vertex, if ifLeft and ifRight both come out as false.

So my question is, what is a good way to generate such a tree? I don't need it to be in python, as it's only for generating an input file, all I need is a good algorithm, or another method of representing the tree so that it's easier to generate and can be converted into the desired format.

答:
A simple iterative approach:

```<code>import random

# start with root node and no children
tree = [[-1, -1]]
free_edges = [(0, 0), (0, 1)]

n = 4  # how many nodes do you want?

while len(tree) < n:
    e = random.choice(free_edges)  # select a free edge
    node, child = e
    assert tree[node][child] == -1  # make sure we made no mistake

    k = len(tree)  # index of new node
    tree.append([-1, -1])  # add new node

    tree[node][child] = k  # set new node as child of an old node
    free_edges.extend([(k, 0), (k, 1)])  # new node has two free edges

    free_edges.remove(e)  # edge is no longer free

print(tree)
# [[1, 2], [-1, 3], [-1, -1], [-1, -1]]
</code>```

Randomly insert new nodes into the tree until the total number of nodes is reached.

The free edges are indicated in red. At each step, one free edge is chosen at random. A node is placed at that edge and this node adds two new free edges to the tree.

This procedure does not generate a specific order of nodes. Either the left child or the right child may be inserted into the tree first. I.e. you may get a sequence like [(2, 1), (-1, -1), (-1, -1)]. If this is a problem re-ordering of the nodes may be necessary.

I think this method will on average tend to produce more balanced trees than imbalanced trees because older edges are be considered more often. You may choose not to insert a new node and only remove the free edge with a certain probability. This should shift the tendency towards deeper trees. Just make sure not to remove all edges before being finished :)

Body:
I am debugging an algorithms task, and for the purpose of testing I want to generate a binary tree with n vertices rooted at 0, in other words, generate a sequence of pairs so that if the i-th pair in the sequence is (a,b), then the left child of i-th node is a, and the right child is b, except when a (or b) = -1, then i-th node has no left (or right) child. (e. g. a sequence: (1, 2), (-1, -1), (-1, -1) is a tree with the root (0), and two children (1 and 2))
I wrote the following python recursive function, where listAdd is the desired pair list, listDel is all vertices not yet generated, and n is the node currently being looked at:

def generateTree(listAdd, listDel, n):
    if not listDel:
        return
    ifLeft = bool(randint(0,1))
    ifRight = bool(randint(0,1))
    if ifLeft:
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (chosen, listAdd[n][1])
        generateTree(listAdd, listDel, chosen)
    else:
        listAdd[n] = (-1, listAdd[n][1])
    if not listDel:
        return
    if ifRight:
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (listAdd[n][0], chosen)
        generateTree(listAdd, listDel, chosen)
    else:
        listAdd[n] = (listAdd[n][0], -1)

However, upon writing it, I noticed that this does not work correctly, as it is possible for the function to stop after just one vertex, if ifLeft and ifRight both come out as false.

So my question is, what is a good way to generate such a tree? I don't need it to be in python, as it's only for generating an input file, all I need is a good algorithm, or another method of representing the tree so that it's easier to generate and can be converted into the desired format.

Body:
A simple iterative approach:

import random

# start with root node and no children
tree = [[-1, -1]]
free_edges = [(0, 0), (0, 1)]

n = 4  # how many nodes do you want?

while len(tree) < n:
    e = random.choice(free_edges)  # select a free edge
    node, child = e
    assert tree[node][child] == -1  # make sure we made no mistake

    k = len(tree)  # index of new node
    tree.append([-1, -1])  # add new node

    tree[node][child] = k  # set new node as child of an old node
    free_edges.extend([(k, 0), (k, 1)])  # new node has two free edges

    free_edges.remove(e)  # edge is no longer free

print(tree)
# [[1, 2], [-1, 3], [-1, -1], [-1, -1]]

Randomly insert new nodes into the tree until the total number of nodes is reached.

The free edges are indicated in red. At each step, one free edge is chosen at random. A node is placed at that edge and this node adds two new free edges to the tree.

This procedure does not generate a specific order of nodes. Either the left child or the right child may be inserted into the tree first. I.e. you may get a sequence like [(2, 1), (-1, -1), (-1, -1)]. If this is a problem re-ordering of the nodes may be necessary.

I think this method will on average tend to produce more balanced trees than imbalanced trees because older edges are be considered more often. You may choose not to insert a new node and only remove the free edge with a certain probability. This should shift the tendency towards deeper trees. Just make sure not to remove all edges before being finished :)


答:
```<code>var someFun = nm => {
    const names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];
    const foundName = names.find(name => name.name === nm)

    return foundName ? foundName.age : null
};
</code>```

This replicates what you have above. Although i would personally return the object then age the age from that instead of just returning the age.

Title: Get values from an array of objects

Body:
var someFun = nm => {
    const names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];
    const foundName = names.find(name => name.name === nm)

    return foundName ? foundName.age : null
};

This replicates what you have above. Although i would personally return the object then age the age from that instead of just returning the age.


问:
JPA with QueryDSL select query incorrect result
I have a problem when making a select to a table in a database, the data resulting from it is incorrect. Can there be some kind of Spring cache to update?

```<code>@Service
public class CronogramaService {

    @Autowired
    private CronogramaRepository cronogramaRepository;

    @Autowired
    private EntityManager entityManager;

    public List<Cronograma> findAll() {
        QCronograma cronograma = QCronograma.cronograma;
        return new JPAQuery(entityManager)
            .from(cronograma)
            .list(cronograma);
    }
}
</code>```

Test main

```<code>public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring_config.xml");

    CronogramaService cronoService = context.getBean(CronogramaService.class);

    List<Cronograma> crono = cronoService.findAll();

    for (Cronograma cronograma : crono) {
        System.out.println(cronograma.getDia());
        System.out.println(cronograma.getIdCronograma());
    }

    System.out.println();

    ((ClassPathXmlApplicationContext)context).close();
}
</code>```

The application has 365 days of the year 2018. But the result in id 1 returns me the day 2017-12-31. In the database the data of id 1 is 01-01-2018, and I do not understand what the problem is.

答: We had a similar issue which boiled down to different timezones between application server and database server. Assuming you're using MySQL, try connecting to your database with the serverTimezone parameter set like jdbc:mysql://server:3306/database?serverTimezone=Europe/London</p>

Body:
I have a problem when making a select to a table in a database, the data resulting from it is incorrect. Can there be some kind of Spring cache to update?

@Service
public class CronogramaService {

    @Autowired
    private CronogramaRepository cronogramaRepository;

    @Autowired
    private EntityManager entityManager;

    public List<Cronograma> findAll() {
        QCronograma cronograma = QCronograma.cronograma;
        return new JPAQuery(entityManager)
            .from(cronograma)
            .list(cronograma);
    }
}

Test main

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring_config.xml");

    CronogramaService cronoService = context.getBean(CronogramaService.class);

    List<Cronograma> crono = cronoService.findAll();

    for (Cronograma cronograma : crono) {
        System.out.println(cronograma.getDia());
        System.out.println(cronograma.getIdCronograma());
    }

    System.out.println();

    ((ClassPathXmlApplicationContext)context).close();
}

The application has 365 days of the year 2018. But the result in id 1 returns me the day 2017-12-31. In the database the data of id 1 is 01-01-2018, and I do not understand what the problem is.


问:
Retrieve users private token with Gitlab python API
I am trying to retrieve all users' private token and SSH keys with gitlab API (v4) using an admin private token in my curl requests.

I can get a user SSH key by running the following command :

```<code>curl --header "PRIVATE-TOKEN: my_admin_token" "https://gitlab.my_gitlab.com/api/v4/users/user_id/keys"
</code>```

But I can't find a similar way to get his private token (I need it for further applications in a python script). How can I do that ?

答: Those tokens are not available through Gitlab API, on the other hand, if you want to make API calls as someone else, you can do so with https://docs.gitlab.com/ee/api/README.html#sudo. </p>

Body:
I am trying to retrieve all users' private token and SSH keys with gitlab API (v4) using an admin private token in my curl requests.

I can get a user SSH key by running the following command :

curl --header "PRIVATE-TOKEN: my_admin_token" "https://gitlab.my_gitlab.com/api/v4/users/user_id/keys"

But I can't find a similar way to get his private token (I need it for further applications in a python script). How can I do that ?