问:
Changed rules for protected constructors in C++17?
I have this test case:

```<code>struct A{ protected: A(){} };
struct B: A{};
struct C: A{ C(){} };
struct D: A{ D() = default; };

int main(){
    (void)B{};
    (void)C{};
    (void)D{};
}
</code>```

Both gcc and clang compile it in C++11 and C++14 mode. Both fail in C++17 mode:

```<code>$ clang++ -std=c++17 main.cpp
main.cpp:7:10: error: base class 'A' has protected default constructor
        (void)B{};
                ^
main.cpp:1:22: note: declared protected here
struct A{ protected: A(){} };
                     ^
main.cpp:9:10: error: base class 'A' has protected default constructor
        (void)D{};
                ^
main.cpp:1:22: note: declared protected here
struct A{ protected: A(){} };
                     ^
2 errors generated.

$ clang++ --version
clang version 6.0.0 (http://llvm.org/git/clang.git 96c9689f478d292390b76efcea35d87cbad3f44d) (http://llvm.org/git/llvm.git 360f53a441902d19ce27d070ad028005bc323e61)
Target: x86_64-unknown-linux-gnu
Thread model: posix
</code>```

(clang compiled from master Branch 2017-12-05.)

```<code>$ g++ -std=c++17 main.cpp
main.cpp: In function 'int main()':
main.cpp:7:10: error: 'A::A()' is protected within this context
  (void)B{};
          ^
main.cpp:1:22: note: declared protected here
 struct A{ protected: A(){} };
                      ^
main.cpp:9:10: error: 'A::A()' is protected within this context
  (void)D{};
          ^
main.cpp:1:22: note: declared protected here
 struct A{ protected: A(){} };
                      ^

$ g++ --version
g++ (GCC) 8.0.0 20171201 (experimental)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Is this change of behavior part of C++17 or is it a bug in both compilers?

答:
In C++17, rules about aggregates has changed.

For example, you can do this in C++17 now:

```<code>struct A { int a; };
struct B { B(int){} };

struct C : A {};
struct D : B {};

int main() {
    (void) C{2};
    (void) D{1};
}
</code>```

Note that we're not inheriting constructor. In C++17, C and D are now aggregates even if they have base classes.

With {}, aggregate initialization kicks in, and sending no parameters will be interpreted the same as calling the parent's default constructor from the outside.

For example, aggregate initialization can be disabled by changing the class D to this:

```<code>struct B { protected: B(){} };

struct D : B {
    int b;
private:
    int c;
};

int main() {
    (void) D{}; // works!
}
</code>```

This is because aggregate initialization don't apply when having members with different access specifiers.

The reason why with = default works is because it's not a user provided constructor. More information at this question.

Body:
I have this test case:

struct A{ protected: A(){} };
struct B: A{};
struct C: A{ C(){} };
struct D: A{ D() = default; };

int main(){
    (void)B{};
    (void)C{};
    (void)D{};
}

Both gcc and clang compile it in C++11 and C++14 mode. Both fail in C++17 mode:

$ clang++ -std=c++17 main.cpp
main.cpp:7:10: error: base class 'A' has protected default constructor
        (void)B{};
                ^
main.cpp:1:22: note: declared protected here
struct A{ protected: A(){} };
                     ^
main.cpp:9:10: error: base class 'A' has protected default constructor
        (void)D{};
                ^
main.cpp:1:22: note: declared protected here
struct A{ protected: A(){} };
                     ^
2 errors generated.

$ clang++ --version
clang version 6.0.0 (http://llvm.org/git/clang.git 96c9689f478d292390b76efcea35d87cbad3f44d) (http://llvm.org/git/llvm.git 360f53a441902d19ce27d070ad028005bc323e61)
Target: x86_64-unknown-linux-gnu
Thread model: posix

(clang compiled from master Branch 2017-12-05.)

$ g++ -std=c++17 main.cpp
main.cpp: In function 'int main()':
main.cpp:7:10: error: 'A::A()' is protected within this context
  (void)B{};
          ^
main.cpp:1:22: note: declared protected here
 struct A{ protected: A(){} };
                      ^
main.cpp:9:10: error: 'A::A()' is protected within this context
  (void)D{};
          ^
main.cpp:1:22: note: declared protected here
 struct A{ protected: A(){} };
                      ^

$ g++ --version
g++ (GCC) 8.0.0 20171201 (experimental)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Is this change of behavior part of C++17 or is it a bug in both compilers?

Body:
In C++17, rules about aggregates has changed.

For example, you can do this in C++17 now:

struct A { int a; };
struct B { B(int){} };

struct C : A {};
struct D : B {};

int main() {
    (void) C{2};
    (void) D{1};
}

Note that we're not inheriting constructor. In C++17, C and D are now aggregates even if they have base classes.

With {}, aggregate initialization kicks in, and sending no parameters will be interpreted the same as calling the parent's default constructor from the outside.

For example, aggregate initialization can be disabled by changing the class D to this:

struct B { protected: B(){} };

struct D : B {
    int b;
private:
    int c;
};

int main() {
    (void) D{}; // works!
}

This is because aggregate initialization don't apply when having members with different access specifiers.

The reason why with = default works is because it's not a user provided constructor. More information at this question.


来源: stackexchange

问:
facebook app allows only one tab?
i have a business page ob facebook and i want to create 3 tabs for offers, best selling, promotions.
I have create on my website 3 pages without header and footer and show only the main content.

To do this

I have create an app on facebook developers.

i created my first custom facebook tab that show contents of my
webpage which working fine.

When i tried to created another tab clicking add platform the Page Tab is grey meaning that i cant create another tab.

This means that the app can have only one tab ?

and if i want to have 2-3 custom tabs whats the solution ?

Thanks

答:
This means that the app can have only one tab ?

Yes.

and if i want to have 2-3 custom tabs whats the solution ?

To create 2-3 apps.

ContentLicense: CC BY-SA 3.0

Title: facebook app allows only one tab?


问:
Array objects values remove unwanted string
I have the following originaldata  which I would like to remove the div tags from the each objects inside it, leaving it with the content within the tags as the final result, see modifieddata.

What would be the best approach using javascript? filter and map? or something else.

```<code>originaldata = [{
        "name": "john",
        "content": "<div class="ExternalClass06EE5E42165840F48DFA193ACAD4F87A">aa</div>"
    },
    {
        "name": "mary",
        "content": "<div class="ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A">asd</div>"
    }
]

modifieddata = [{
        "name": "john",
        "content": "aa"
    },
    {
      "name": "mary",
      "content": "asd"
    }
]
</code>```

答:
You can create a new element and then insert the content of the originaldata array to the newly created element.

Later on you retrieve the html of the element using innerHTML and overwrite the original originaldata.content with the innerHTML

Working demo

var originaldata = [{
    "name": "john",
    "content": "
aa
"
  },
  {
    "name": "mary",
    "content": "
asd
"
  }
];

for (var i in originaldata) {
  var html = originaldata[i].content;
  var temp = document.createElement('div');

  temp.innerHTML = html;

  var htmlContent = temp.firstChild.innerHTML;

  originaldata[i].content = htmlContent;
}

console.log(originaldata)```

Body:
I have the following originaldata  which I would like to remove the div tags from the each objects inside it, leaving it with the content within the tags as the final result, see modifieddata.

What would be the best approach using javascript? filter and map? or something else.

originaldata = [{
        "name": "john",
        "content": "
aa
"
    },
    {
        "name": "mary",
        "content": "
asd
"
    }
]

modifieddata = [{
        "name": "john",
        "content": "aa"
    },
    {
      "name": "mary",
      "content": "asd"
    }
]

Body:
You can create a new element and then insert the content of the originaldata array to the newly created element.

Later on you retrieve the html of the element using innerHTML and overwrite the original originaldata.content with the innerHTML

Working demo

var originaldata = [{
    "name": "john",
    "content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A '>aa</div>"
  },
  {
    "name": "mary",
    "content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A '>asd</div>"
  }
];

for (var i in originaldata) {
  var html = originaldata[i].content;
  var temp = document.createElement('div');

  temp.innerHTML = html;

  var htmlContent = temp.firstChild.innerHTML;

  originaldata[i].content = htmlContent;
}

console.log(originaldata)


问:
How to stream mp4 video from server using ExoPlayer?
recently i come across google exoplayer which has some cool feture with lack of documentation and support and am new to it , my doubt is how to play mp4 video using server URL. Now let me explain what I have tried so far

I have successfully implemented exoplayer in my project and make it works

But my problem is using my server url first it completes full video buffer then only it starts playing so it takes time ? what i need is it need to play simultaneously after getting each response so that video can be play it fast how can i achieve this. Now let me post what i have tried so far:

```<code>    BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
    TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);

    TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
    LoadControl loadControl = new DefaultLoadControl();
    player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
    simpleExoPlayerView = new SimpleExoPlayerView(this);
    simpleExoPlayerView = findViewById(R.id.player_view);
    simpleExoPlayerView.setUseController(true);
    simpleExoPlayerView.setVisibility(View.VISIBLE);
    simpleExoPlayerView.requestFocus();
    simpleExoPlayerView.setPlayer(player);

    Log.d("url", intent.getStringExtra("videopath") + "?api_key=" + getResources().getString(R.string.dream_factory_api_key) + "&session_token=" + PreferenceUtils.getInstance(this).getStrData(PreferenceUtils.SESSION_TOKEN));
    MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(intent.getStringExtra("videopath") + "?api_key=" + getResources().getString(R.string.fs) + "&session_token=" + PreferenceUtils.getInstance(this).getStrData(PreferenceUtils.SESSION_TOKEN)),
            new CacheDataSourceFactory(this, 100 * 1024 * 1024, 5 * 1024 * 1024), new DefaultExtractorsFactory(), null, null);
    player.prepare(mediaSource);
</code>```

Any help ? am i doing it in right way ? what i need is it needs buffer like youtube play and buffer not like buffer completely then play , Thanks in adavance

答: Instead of ExtractorMediaSource you should probably use DashMediaSource. That is for what you exactly want (buffering while playing).</p>

Body:
recently i come across google exoplayer which has some cool feture with lack of documentation and support and am new to it , my doubt is how to play mp4 video using server URL. Now let me explain what I have tried so far

I have successfully implemented exoplayer in my project and make it works

But my problem is using my server url first it completes full video buffer then only it starts playing so it takes time ? what i need is it need to play simultaneously after getting each response so that video can be play it fast how can i achieve this. Now let me post what i have tried so far:

    BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
    TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);

    TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
    LoadControl loadControl = new DefaultLoadControl();
    player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
    simpleExoPlayerView = new SimpleExoPlayerView(this);
    simpleExoPlayerView = findViewById(R.id.player_view);
    simpleExoPlayerView.setUseController(true);
    simpleExoPlayerView.setVisibility(View.VISIBLE);
    simpleExoPlayerView.requestFocus();
    simpleExoPlayerView.setPlayer(player);

    Log.d("url", intent.getStringExtra("videopath") + "?api_key=" + getResources().getString(R.string.dream_factory_api_key) + "&session_token=" + PreferenceUtils.getInstance(this).getStrData(PreferenceUtils.SESSION_TOKEN));
    MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(intent.getStringExtra("videopath") + "?api_key=" + getResources().getString(R.string.fs) + "&session_token=" + PreferenceUtils.getInstance(this).getStrData(PreferenceUtils.SESSION_TOKEN)),
            new CacheDataSourceFactory(this, 100 * 1024 * 1024, 5 * 1024 * 1024), new DefaultExtractorsFactory(), null, null);
    player.prepare(mediaSource);

Any help ? am i doing it in right way ? what i need is it needs buffer like youtube play and buffer not like buffer completely then play , Thanks in adavance


问:
Why oracle sql not allow sysdate in table creation time for count age?
Query....
I want to try to make check constraints on birthdate and check age should be greater than 18.

```<code>Create table emp
(
Birthdate date,
Check( MONTHS_BETWEEN(SYSDATE,Birthdate))
);
</code>```

Error on above query....why?
Anyone help me...

Why oracle sql not allow sysdate in table creation time for count age?

答:
This is because of Oracle limitation. The reason is SYSDATE is non-deterministic. You can get a different result every time you call it. So the outcome (true/false) can (will) change over time. So Oracle can't guarantee that the expression is always true for every row.

See also https://asktom.oracle.com/pls/apex/asktom.search?tag=sysdate-in-check-constraints

Body:
Query....
I want to try to make check constraints on birthdate and check age should be greater than 18.

Create table emp
(
Birthdate date,
Check( MONTHS_BETWEEN(SYSDATE,Birthdate))
);

Error on above query....why?
Anyone help me...

Why oracle sql not allow sysdate in table creation time for count age?


问:
how to use one thread to listening all subscribe channel for redis？
I use python 3.6.3, the channel build dynamically.
the redis_client build when the client connect to webwsocket server.

I have about 1000 to 100,0000 redis_clients, every redis_client subscribe some channels.

How to use one thread or IOLoop listenning all clients message?
Can you give me an example which the thread can add new pubsub object to listening more channels?

Is there any solution use coroutine replace thread waiting here and can join all coroutine together (can not use joinall as some listener will approach later on.)
I using redis-py library.

答:
IIUC, what you're looking for is Redis' PSUBSCRIBE command. Here's an example that shows how you can use it with redis-py and a listener thread:

```<code>import threading
import redis

class Listener(threading.Thread):
    def __init__(self, r, p):
        threading.Thread.__init__(self)
        self.redis = r
        self.pubsub = self.redis.pubsub()
        self.pubsub.psubscribe(p)

    def run(self):
        for m in self.pubsub.listen():
            if 'pmessage' != m['type']:
                continue
            if '__admin__' == m['channel'] and 'shutdown' == m['data']:
                print 'Listener shutting down, bye bye.'
                break
            print '[{}]: {}'.format(m['channel'], m['data'])

if __name__ == "__main__":
    r = redis.StrictRedis()
    client = Listener(r, '*')
    client.start()

    r.publish('channel1', 'message1')
    r.publish('channel2', 'message2')
    r.publish('channel1', 'message3')

    r.publish('__admin__', 'shutdown')
    print 'Main ended.'
</code>```

Body:
IIUC, what you're looking for is Redis' PSUBSCRIBE command. Here's an example that shows how you can use it with redis-py and a listener thread:

import threading
import redis

class Listener(threading.Thread):
    def __init__(self, r, p):
        threading.Thread.__init__(self)
        self.redis = r
        self.pubsub = self.redis.pubsub()
        self.pubsub.psubscribe(p)

    def run(self):
        for m in self.pubsub.listen():
            if 'pmessage' != m['type']:
                continue
            if '__admin__' == m['channel'] and 'shutdown' == m['data']:
                print 'Listener shutting down, bye bye.'
                break
            print '[{}]: {}'.format(m['channel'], m['data'])

if __name__ == "__main__":
    r = redis.StrictRedis()
    client = Listener(r, '*')
    client.start()

    r.publish('channel1', 'message1')
    r.publish('channel2', 'message2')
    r.publish('channel1', 'message3')

    r.publish('__admin__', 'shutdown')
    print 'Main ended.'


问:
Query to tell me how many times a digit appears in a column
I'm trying to find out how many times each digit appears in a column. I have a database that stores pin numbers for parents that check their kids in and out of a preschool.

The pin numbers are stored in a CHAR(4) column; but they are all numeric.

I have tried:

```<code>SELECT COUNT(pin) AS Count
FROM adult
WHERE pin LIKE '%2%';
</code>```

Which returns these results:

```<code>+-------+
| Count |
+-------+
|   182 |
+-------+
</code>```

But that only tells me how many records have a '2', not how many times it occurs (since a record could have more than 1 '2'. It's also a very manual process to go through each digit 0-9.

I'd like something that would look more like:

```<code>+-----+-----+
|Value|Count|
+-----+-----+
|    0|  204|
|    1|  200|
|    2|  182|
.           .
.           .
.           .
|    9|  203|
+-----+-----+
</code>```

This is beyond my knowledge of SQL. Your help is very appreciated!

答:
You can use substr():

```<code>select substr(t.pin, n.pos, 1) as chr, count(*)
from adult t cross join
     (select 1 as pos union all select 2 union all select 3 union all select 4
     ) n
group by substr(t.pin, n.pos, 1)
order by chr;
</code>```

This extracts each character in the pin and aggregates by the character.  The from clause is equivalent to:

```<code>from ((select substr(col, 1, 1) from adult union all
      (select substr(col, 2, 1) from adult union all
      (select substr(col, 3, 1) from adult union all
      (select substr(col, 4, 1) from adult
     ) t
</code>```

Body:
I'm trying to find out how many times each digit appears in a column. I have a database that stores pin numbers for parents that check their kids in and out of a preschool.

The pin numbers are stored in a CHAR(4) column; but they are all numeric.

I have tried:

SELECT COUNT(pin) AS Count
FROM adult
WHERE pin LIKE '%2%';

Which returns these results:

+-------+
| Count |
+-------+
|   182 |
+-------+

But that only tells me how many records have a '2', not how many times it occurs (since a record could have more than 1 '2'. It's also a very manual process to go through each digit 0-9.

I'd like something that would look more like:

+-----+-----+
|Value|Count|
+-----+-----+
|    0|  204|
|    1|  200|
|    2|  182|
.           .
.           .
.           .
|    9|  203|
+-----+-----+

This is beyond my knowledge of SQL. Your help is very appreciated!

Body:
You can use substr():

select substr(t.pin, n.pos, 1) as chr, count(*)
from adult t cross join
     (select 1 as pos union all select 2 union all select 3 union all select 4
     ) n
group by substr(t.pin, n.pos, 1)
order by chr;

This extracts each character in the pin and aggregates by the character.  The from clause is equivalent to:

from ((select substr(col, 1, 1) from adult union all
      (select substr(col, 2, 1) from adult union all
      (select substr(col, 3, 1) from adult union all
      (select substr(col, 4, 1) from adult
     ) t


问:
How to query huge MySQL databases?
I have 2 tables, a purchases table and a users table. Records in the purchases table looks like this:

```<code>purchase_id | product_ids | customer_id
---------------------------------------
1           | (99)(34)(2) | 3
2           | (45)(3)(74) | 75
</code>```

Users table looks like this:

```<code>user_id  | email              | password
----------------------------------------
3        | joeShmoe@gmail.com | password
75       | nolaHue@aol.com    | password
</code>```

To get the purchase history of a user I use a query like this:

```<code>mysql_query(" SELECT * FROM purchases WHERE customer_id = '$users_id' ");
</code>```

The problem is, what will happen when tens of thousands of records are inserted into the purchases table. I feel like this will take a performance toll.

So I was thinking about storing the purchases in an additional field directly in the user's row:

```<code>user_id | email              | password  | purchases
------------------------------------------------------
1       | joeShmoe@gmail.com | password  | (99)(34)(2)
2       | nolaHue@aol.com    | password  | (45)(3)(74)
</code>```

And when I query the user's table for things like username, etc. I can just as easily grab their purchase history using that one query.

Is this a good idea, will it help better performance or will the benefit be insignificant and not worth making the database look messier?

I really want to know what the pros do in these situations, for example how does amazon query it's database for user's purchase history since they have millions of customers. How come there queries don't take hours?

EDIT

Ok, so I guess keeping them separate is the way to go. Now the question is a design one:

Should I keep using the "purchases" table I illustrated earlier. In that design I am separating the product ids of each purchase using parenthesis and using this as the delimiter to tell the ids apart when extracting them via PHP.

Instead should I be storing each product id separately in the "purchases" table so it looks like this?:

```<code>purchase_id | product_ids | customer_id
---------------------------------------
1           | 99          | 3
1           | 34          | 3
1           | 2           | 3
2           | 45          | 75
2           | 3           | 75
2           | 74          | 75
</code>```

答:
First off, tens of thousands of records is nothing. Unless you're running on a teensy weensy machine with limited ram and harddrive space, a database won't even blink at 100,000 records. </p>

<p>As for storing purchase details in the users table... what happens if a user makes more than one purchase? </p>

ContentLicense: CC BY-SA 2.5

Title: How to query huge MySQL databases?

Body:
I have 2 tables, a purchases table and a users table. Records in the purchases table looks like this:

purchase_id | product_ids | customer_id
---------------------------------------
1           | (99)(34)(2) | 3
2           | (45)(3)(74) | 75

Users table looks like this:

user_id  | email              | password
----------------------------------------
3        | joeShmoe@gmail.com | password
75       | nolaHue@aol.com    | password

To get the purchase history of a user I use a query like this:

mysql_query(" SELECT * FROM purchases WHERE customer_id = '$users_id' ");

The problem is, what will happen when tens of thousands of records are inserted into the purchases table. I feel like this will take a performance toll.

So I was thinking about storing the purchases in an additional field directly in the user's row:

user_id | email              | password  | purchases
------------------------------------------------------
1       | joeShmoe@gmail.com | password  | (99)(34)(2)
2       | nolaHue@aol.com    | password  | (45)(3)(74)

And when I query the user's table for things like username, etc. I can just as easily grab their purchase history using that one query.

Is this a good idea, will it help better performance or will the benefit be insignificant and not worth making the database look messier?

I really want to know what the pros do in these situations, for example how does amazon query it's database for user's purchase history since they have millions of customers. How come there queries don't take hours?

EDIT

Ok, so I guess keeping them separate is the way to go. Now the question is a design one:

Should I keep using the "purchases" table I illustrated earlier. In that design I am separating the product ids of each purchase using parenthesis and using this as the delimiter to tell the ids apart when extracting them via PHP.

Instead should I be storing each product id separately in the "purchases" table so it looks like this?:

purchase_id | product_ids | customer_id
---------------------------------------
1           | 99          | 3
1           | 34          | 3
1           | 2           | 3
2           | 45          | 75
2           | 3           | 75
2           | 74          | 75

Body:
First off, tens of thousands of records is nothing. Unless you're running on a teensy weensy machine with limited ram and harddrive space, a database won't even blink at 100,000 records.

As for storing purchase details in the users table... what happens if a user makes more than one purchase?


答:
SYSDATE is not allowed because the constraint must be either "true" or "false" at any time you look at the data. If you were able to use SYSDATE in a check constraint, you could insert a row that satisfied the constraint at that time, but the constraint would be violated later. No good!

In your example, once the constraint is satisfied at insert time, it can't become "not satisfied" later. But here you are asking Oracle to think. It can't. It just doesn't allow you to use SYSDATE in constraints. Period.

Instead, you should write a simple trigger to do the check for you. Note that you are missing the comparison to 18 * 12 in your purported check constraint; MONTHS_BETWEEN may give some weird results in some cases; and it is always best to write code that mirrors your thinking: in this case the condition (in a trigger, not a check constraint) should be ***

```<code>sysdate >= birthdate + interval '18' year
</code>```

***   EDIT: As Alex Poole points out below, adding INTERVAL to a date may sometimes be as weird as MONTHS_BETWEEN. The safe way to write the check is

```<code>sysdate >= add_months ( birthdate, 18 * 12 )   --  age >= 18 years or 18 * 12 months
</code>```

(That is how I would write it - with the comment to explain the purpose, and 18 * 12.)

Title: Why oracle sql not allow sysdate in table creation time for count age?

Body:
SYSDATE is not allowed because the constraint must be either "true" or "false" at any time you look at the data. If you were able to use SYSDATE in a check constraint, you could insert a row that satisfied the constraint at that time, but the constraint would be violated later. No good!

In your example, once the constraint is satisfied at insert time, it can't become "not satisfied" later. But here you are asking Oracle to think. It can't. It just doesn't allow you to use SYSDATE in constraints. Period.

Instead, you should write a simple trigger to do the check for you. Note that you are missing the comparison to 18 * 12 in your purported check constraint; MONTHS_BETWEEN may give some weird results in some cases; and it is always best to write code that mirrors your thinking: in this case the condition (in a trigger, not a check constraint) should be ***

sysdate >= birthdate + interval '18' year

***   EDIT: As Alex Poole points out below, adding INTERVAL to a date may sometimes be as weird as MONTHS_BETWEEN. The safe way to write the check is

sysdate >= add_months ( birthdate, 18 * 12 )   --  age >= 18 years or 18 * 12 months

(That is how I would write it - with the comment to explain the purpose, and 18 * 12.)


问:
Web flow Exception: No flow execution snapshot could be found with id '1'
I am getting below exception whenever I switch one state to another more then 15 times in web-flow.

```<code>No flow execution snapshot could be found with id '1'; perhaps the snapshot has been removed? . Stacktrace follows:
org.springframework.webflow.execution.repository.FlowExecutionRestorationFailureException: A problem occurred restoring the flow execution with key 'e7s1'
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.webflow.execution.repository.snapshot.SnapshotNotFoundException: No flow execution snapshot could be found with id '1'; perhaps the snapshot has been removed?
... 3 more
</code>```

I am using grails webflow plug-in.

Are anyone have any idea why this is occurring and how to resolve this?

答:
For newer versions of SpringWebflow, as seen here:

https://docs.spring.io/spring-webflow/docs/2.4.4.RELEASE/reference/html/system-setup.html#tuning-flow-execution-repository

You can simple write this on your java configuration code:

```<code>@Bean
public FlowExecutor flowExecutor() {
    return getFlowExecutorBuilder(flowRegistry())
            .setMaxFlowExecutions(5)
            .setMaxFlowExecutionSnapshots(30)
            .build();
}
</code>```

If you want to keep infinite values of Snapshot versions, just set the, maxFlorExecutionSnapshots to -1.

Body:
I am getting below exception whenever I switch one state to another more then 15 times in web-flow.

No flow execution snapshot could be found with id '1'; perhaps the snapshot has been removed? . Stacktrace follows:
org.springframework.webflow.execution.repository.FlowExecutionRestorationFailureException: A problem occurred restoring the flow execution with key 'e7s1'
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.webflow.execution.repository.snapshot.SnapshotNotFoundException: No flow execution snapshot could be found with id '1'; perhaps the snapshot has been removed?
... 3 more

I am using grails webflow plug-in.

Are anyone have any idea why this is occurring and how to resolve this?

Body:
For newer versions of SpringWebflow, as seen here:

https://docs.spring.io/spring-webflow/docs/2.4.4.RELEASE/reference/html/system-setup.html#tuning-flow-execution-repository

You can simple write this on your java configuration code:

@Bean
public FlowExecutor flowExecutor() {
    return getFlowExecutorBuilder(flowRegistry())
            .setMaxFlowExecutions(5)
            .setMaxFlowExecutionSnapshots(30)
            .build();
}

If you want to keep infinite values of Snapshot versions, just set the, maxFlorExecutionSnapshots to -1.


问:
Python - Why backup variable inside loop is being updated if I don't change it value inside?
I want to set the values of matrix W in Wo.
Then, I will go inside a loop and do operations with W. At the end of the loop, I want to restore it to Wo, but I am getting the opposite result, Wo is becoming Wo.

How is that possible? How can I accomplish what I want? I have also tried defining Wo as a global but no result

```<code>W = np.random.rand(5, 10)
global Wo
Wo = W # Back up for the initial values of W

for k in range(0, K):

  for j in range(0, m):       # For every hidden node

    for i in range(0, n):        # For every connection

      # Operations (W get changed)
      W = Wo
</code>```

Then, if I check the value of Wo has been modified, in a way that Wo == W is always True.

What am I missing?

Thanks in advance

答:
To accomplish what you want, you need a deep copy. Otherwise you only create a reference to the same memory.</p>

```<code>import numpy as np
import copy as cp

W = np.random.rand(5, 10)
global Wo

Wo = cp.deepcopy(W) # Back up for the initial values of W

for k in range(0, K):

  for j in range(0, m):       # For every hidden node

    for i in range(0, n):        # For every connection

      # Operations (W get changed)
      W = cp.deepcopy(Wo)
</code>```

Body:
I want to set the values of matrix W in Wo.
Then, I will go inside a loop and do operations with W. At the end of the loop, I want to restore it to Wo, but I am getting the opposite result, Wo is becoming Wo.

How is that possible? How can I accomplish what I want? I have also tried defining Wo as a global but no result

W = np.random.rand(5, 10)
global Wo
Wo = W # Back up for the initial values of W

for k in range(0, K):

  for j in range(0, m):       # For every hidden node

    for i in range(0, n):        # For every connection

      # Operations (W get changed)
      W = Wo

Then, if I check the value of Wo has been modified, in a way that Wo == W is always True.

What am I missing?

Thanks in advance

Body:
To accomplish what you want, you need a deep copy. Otherwise you only create a reference to the same memory.

import numpy as np
import copy as cp

W = np.random.rand(5, 10)
global Wo

Wo = cp.deepcopy(W) # Back up for the initial values of W

for k in range(0, K):

  for j in range(0, m):       # For every hidden node

    for i in range(0, n):        # For every connection

      # Operations (W get changed)
      W = cp.deepcopy(Wo)


问:
Unexpected print() and os.listdir() functionality
```<code>import os

target_dir = "xxx.xxx.xx.xx/path/to/file/dir"
start_seq = "*** Start Sequence ***"
end_seq = "*** End Sequence ***"

def tp_parser(file):
    with open(file) as in_f:
        lines = in_f.readlines()
        f_name = in_f.name[12:16]

        for i, line in enumerate(lines):
            if line.startswith(start_seq):
                start_line = i
            elif line.startswith(end_seq):
                end_line = i

        with open("{0}_Target_Map.txt".format(f_name), "w") as out_f:
            for i, line in enumerate(lines):
                if start_line <= i < end_line:
                    print(line)
                    # out_f.write(line)

for file in os.listdir(os.chdir(target_dir)):
    tp_parser(file)
</code>```

I wrote this script to look through a directory of files, extract a specific part of each file and write it out to a separate text file. Curious if someone can shine some light on what is happening here...

For this part:

```<code>if start_line <= i < end_line:
    print(line)
    # out_f.write(line)
</code>```

If I run the script with print(line) I get back a "UnboundLocalError: local variable 'end_line' referenced before assignment" error. However, running the script with the out_f.write(line) works as intended.

Second slightly less annoying problem is this part:

```<code>for file in os.listdir(os.chdir(target_dir)):
    tp_parser(file)
</code>```

I can't explain to myself why I have to switch to the working directory(i.e. os.chdir(target_dir)) to actually iterate through the files. I'm aware the os.listdir() by itself returns a list of file names but how is that any different if you pass a os.chdir() argument in os.listdir().

Thanks in advance.

答:
Starting by the end, you don't have to switch to the working dir to iterate. I suppose you want to list the target dir right?
So you either change the dir to current with chdir or you specify the dir to listdir. You are using the first one, but chdir changes dir as a lateral effect not as a result. chdir is returning None. So you call listdir with None, which by mere luck accepts None as an hint to use current dir.
You can write

```<code>os.chdir(target_dir)
for file in os.listdir():
    tp_parser(file)
</code>```

or

```<code>for file in os.listdir(target_dir):
    tp_parser(file)
</code>```

As for the first problem, notice that you assign start_line and end_line with conditional statements. I suspect your problem is that sometimes one of the conditions is not met and using the unassigned name later in code brings up the error.

Edit:

There is also another problem with this code, you are writing your output file into the same dir that you are listing. Next time you run the code the code will parse also your last output file. I suppose this is not intended behaviour; but if you go on you'll see that your output files don't have the end marker, as your condition for output excludes it:

```<code>if start_line <= i < end_line: # use of < instead of <= end_line excludes end marker from output
</code>```

So the error in that case is just malformed new input files appearing amongst the others. And this are erraneous coincidences (user error), not Python code unexpected behaviour.

Body:
import os

target_dir = "xxx.xxx.xx.xx/path/to/file/dir"
start_seq = "*** Start Sequence ***"
end_seq = "*** End Sequence ***"

def tp_parser(file):
    with open(file) as in_f:
        lines = in_f.readlines()
        f_name = in_f.name[12:16]

        for i, line in enumerate(lines):
            if line.startswith(start_seq):
                start_line = i
            elif line.startswith(end_seq):
                end_line = i

        with open("{0}_Target_Map.txt".format(f_name), "w") as out_f:
            for i, line in enumerate(lines):
                if start_line <= i < end_line:
                    print(line)
                    # out_f.write(line)

for file in os.listdir(os.chdir(target_dir)):
    tp_parser(file)

I wrote this script to look through a directory of files, extract a specific part of each file and write it out to a separate text file. Curious if someone can shine some light on what is happening here...

For this part:

if start_line <= i < end_line:
    print(line)
    # out_f.write(line)

If I run the script with print(line) I get back a "UnboundLocalError: local variable 'end_line' referenced before assignment" error. However, running the script with the out_f.write(line) works as intended.

Second slightly less annoying problem is this part:

for file in os.listdir(os.chdir(target_dir)):
    tp_parser(file)

I can't explain to myself why I have to switch to the working directory(i.e. os.chdir(target_dir)) to actually iterate through the files. I'm aware the os.listdir() by itself returns a list of file names but how is that any different if you pass a os.chdir() argument in os.listdir().

Thanks in advance.

Body:
Starting by the end, you don't have to switch to the working dir to iterate. I suppose you want to list the target dir right?
So you either change the dir to current with chdir or you specify the dir to listdir. You are using the first one, but chdir changes dir as a lateral effect not as a result. chdir is returning None. So you call listdir with None, which by mere luck accepts None as an hint to use current dir.
You can write

os.chdir(target_dir)
for file in os.listdir():
    tp_parser(file)

or

for file in os.listdir(target_dir):
    tp_parser(file)

As for the first problem, notice that you assign start_line and end_line with conditional statements. I suspect your problem is that sometimes one of the conditions is not met and using the unassigned name later in code brings up the error.

Edit:

There is also another problem with this code, you are writing your output file into the same dir that you are listing. Next time you run the code the code will parse also your last output file. I suppose this is not intended behaviour; but if you go on you'll see that your output files don't have the end marker, as your condition for output excludes it:

if start_line <= i < end_line: # use of < instead of <= end_line excludes end marker from output

So the error in that case is just malformed new input files appearing amongst the others. And this are erraneous coincidences (user error), not Python code unexpected behaviour.


问:
Problems with running Xamarin for Visual Studio 2017
Okay, I've been searching and searching and it seems that people have somewhat similar scenarios concerning my problem, however, none of the solutions presented even offer a sound solution. I've recently installed Visual Studio 2017. I went on to test the Xamarin Android Emulator by creating an app (named "Try") with absolutely nothing on it. Mind you, this is a fresh install of Visual Studio 2017 with JDK 1.8.0_152 and Android 7.1.1 (25). Right off the bat, the build failed. I cleaned the solution and tried to build again. Fail.

I kept getting these errors:

```<code>    Severity    Code    Description Project File    Line    Suppression State
Error       error: <identifier> expected
package try.try;    Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8
_______________________________________________________________________

Severity    Code    Description Project File    Line    Suppression State
Error       error: class, interface, or enum expected
package try.try;    Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8
_______________________________________________________________________

Severity    Code    Description Project File    Line    Suppression State
Error       error: class, interface, or enum expected
package try.try;    Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8
</code>```

Great, so this has to have something to do with R.java 8? I go to the source and get this:

```<code>  /* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package try.try;

public final class R {
    public static final class attr {
    }
    public static final class id {
        public static final int textureView1=0x7f040000;
    }
    public static final class layout {
        public static final int main=0x7f020000;
    }
    public static final class string {
        public static final int app_name=0x7f030000;
    }
}
</code>```

What is wrong here? I haven't even began to start coding or tinkering with Xamarin yet. Can someone please explain?

答: Figured it out. I don't know why, but Visual Studio 2017 put those project files in a completely different location unlike previous versions. Usually, it would have been put here: Documents>Visual Studio 2017>Projects>[Project Name]. It seems that the place you put your project is conflicting with Xamarin somehow. My suggestion would be to change the project location to what I mentioned above and then build the solution again. If that doesn't work, make a new project with the specified location and test it out. I had a similar problem and that fixed it for me.</p>

Body:
Okay, I've been searching and searching and it seems that people have somewhat similar scenarios concerning my problem, however, none of the solutions presented even offer a sound solution. I've recently installed Visual Studio 2017. I went on to test the Xamarin Android Emulator by creating an app (named "Try") with absolutely nothing on it. Mind you, this is a fresh install of Visual Studio 2017 with JDK 1.8.0_152 and Android 7.1.1 (25). Right off the bat, the build failed. I cleaned the solution and tried to build again. Fail.

I kept getting these errors:

    Severity    Code    Description Project File    Line    Suppression State
Error       error: <identifier> expected
package try.try;    Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8
_______________________________________________________________________

Severity    Code    Description Project File    Line    Suppression State
Error       error: class, interface, or enum expected
package try.try;    Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8
_______________________________________________________________________

Severity    Code    Description Project File    Line    Suppression State
Error       error: class, interface, or enum expected
package try.try;    Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8

Great, so this has to have something to do with R.java 8? I go to the source and get this:

  /* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package try.try;

public final class R {
    public static final class attr {
    }
    public static final class id {
        public static final int textureView1=0x7f040000;
    }
    public static final class layout {
        public static final int main=0x7f020000;
    }
    public static final class string {
        public static final int app_name=0x7f030000;
    }
}

What is wrong here? I haven't even began to start coding or tinkering with Xamarin yet. Can someone please explain?


问:
Google Maps Native cordova plugin with Ionic 3 only showing a grey box
I'm trying to get a map showing and alls I get is a grey box with the google logo at the bottom of it. I've looked at the other posts on this website, and tried them all and none of them seem to fix it.
I'm using ionic 3.12.0 with cordova plugin googlemaps 2.0.7
I've made sure the API key is correct and enabled in the dashboard.

I've tried using the tutorials https://ionicframework.com/docs/native/google-maps/ below is the code

```<code>import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 GoogleMapOptions,
 CameraPosition,
 MarkerOptions,
 Marker
} from '@ionic-native/google-maps';

import { Component, Input, ViewChild } from '@angular/core';
import { Platform } from 'ionic-angular';

@Component({
  selector: 'map',
  template: '<div #map id="map"></div>'
})
export class Map {

  map: GoogleMap;
  mapElement: HTMLElement;
  constructor(private googleMaps: GoogleMaps) { }

  setMapLocation(coords: any) {
    this.map.setCameraTarget(coords);
  }

  ionViewDidLoad() {
   this.loadMap();
  }

  loadMap() {
  this.mapElement = document.getElementById('map');

  let mapOptions: GoogleMapOptions = {
    camera: {
      target: {
        lat: 43.0741904,
        lng: -89.3809802
      },
      zoom: 18,
      tilt: 30
    }
  };

  this.map = this.googleMaps.create(this.mapElement, mapOptions);

  // Wait the MAP_READY before using any methods.
  this.map.one(GoogleMapsEvent.MAP_READY)
    .then(() => {
      console.log('Map is ready!');

      // Now you can use all methods safely.
      this.map.addMarker({
          title: 'Ionic',
          icon: 'blue',
          animation: 'DROP',
          position: {
            lat: 43.0741904,
            lng: -89.3809802
          }
        })
        .then(marker => {
          marker.on(GoogleMapsEvent.MARKER_CLICK)
            .subscribe(() => {
              alert('clicked');
            });
        });

    });
}}
</code>```

and the CSS I've added is

```<code>#map {
    width: 100% !important;
    height: 100% !important;
    img{ max-width: none !important; }
    overflow:visible !important;
    z-index: 1;
}

ion-app._gmaps_cdv_ .nav-decor{
  background-color: transparent !important;
}
</code>```

答:
There could be various reasons.

Google Maps Android API (or Google Maps SDK for iOS) should be enabled in your google cloud console.

Check validity and restrictions of your Google API key.

Use ElementRef from @angular/core instead of HTMLElement.

Try this: https://codeburst.io/native-google-maps-and-geolocation-ionic-fe635a00249d

Body:
I'm trying to get a map showing and alls I get is a grey box with the google logo at the bottom of it. I've looked at the other posts on this website, and tried them all and none of them seem to fix it.
I'm using ionic 3.12.0 with cordova plugin googlemaps 2.0.7
I've made sure the API key is correct and enabled in the dashboard.

I've tried using the tutorials https://ionicframework.com/docs/native/google-maps/ below is the code

import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 GoogleMapOptions,
 CameraPosition,
 MarkerOptions,
 Marker
} from '@ionic-native/google-maps';

import { Component, Input, ViewChild } from '@angular/core';
import { Platform } from 'ionic-angular';

@Component({
  selector: 'map',
  template: '

'
})
export class Map {

  map: GoogleMap;
  mapElement: HTMLElement;
  constructor(private googleMaps: GoogleMaps) { }

  setMapLocation(coords: any) {
    this.map.setCameraTarget(coords);
  }

  ionViewDidLoad() {
   this.loadMap();
  }

  loadMap() {
  this.mapElement = document.getElementById('map');

  let mapOptions: GoogleMapOptions = {
    camera: {
      target: {
        lat: 43.0741904,
        lng: -89.3809802
      },
      zoom: 18,
      tilt: 30
    }
  };

  this.map = this.googleMaps.create(this.mapElement, mapOptions);

  // Wait the MAP_READY before using any methods.
  this.map.one(GoogleMapsEvent.MAP_READY)
    .then(() => {
      console.log('Map is ready!');

      // Now you can use all methods safely.
      this.map.addMarker({
          title: 'Ionic',
          icon: 'blue',
          animation: 'DROP',
          position: {
            lat: 43.0741904,
            lng: -89.3809802
          }
        })
        .then(marker => {
          marker.on(GoogleMapsEvent.MARKER_CLICK)
            .subscribe(() => {
              alert('clicked');
            });
        });

    });
}}

and the CSS I've added is

#map {
    width: 100% !important;
    height: 100% !important;
    img{ max-width: none !important; }
    overflow:visible !important;
    z-index: 1;
}

ion-app._gmaps_cdv_ .nav-decor{
  background-color: transparent !important;
}


问:
Make sticky object stop being sticky
I'm about to make a portfolio for my exam. For that we have some articles we have to make for it. Therefore ive made a homepage, which shows the subjects that ive been writing about, and when you click on one of them, you come down to the article instantly.
On the left side there is a new menu which is sat as sticky, and scrolls with the page. The menu only contains the subjects that im going through for that single

My problem is, that the menu KEEPS on scrolling with the page, when it should stop after the article has ended, so a new chapter menu can appear. How do I do that?

Edit: I was on my phone when i wrote it.. But here is the code for the MENU on HTML, CSS and Jquery

  /*** Left Menu ***/
    var navLeftPos = $('#left_menu').offset().top;
    //console.log(navLeftPos)
    $(window).on('scroll', function () {
        console.log($(window).scrollTop())
        if (navTopPos <= $(window).scrollTop()) {
            $('#left_menu').addClass('left_menu')
        }
        if (navTopPos <= $(window).scrollTop() ) {
            $('#left_menu').addClass('left_menu')
        }
        else {
            $('#left_menu').removeClass('left_menu');
        }
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*** Menu sidebar ***/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu {
    float:left;
    width: 30%;
    padding: 1.5% 1.5% 1.5% 5%;
    background-color: #C4E1AC;
}

div#wrapper div#underlayer div#ComputerensHistorie section.left_menu {
    position: fixed;
    top: 105px;
    left: 0;
}

/***** Overskrift *****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu h2 {
    font-family: Frank Ruhl Libre;
    letter-spacing: 2px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu svg {
    width: 60%;
    margin-bottom: 15px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu svg .cls-1 {
    stroke-width: 0.5px;
}

/***** Animations understreg *****/

svg#understreg_et line#streg_tre {
    stroke: #3A8540;
    animation: backandforth 12s linear infinite;
}

svg#understreg_et line#streg_to {
    stroke: #fff;
    animation: backandforth 4s linear infinite;
}

svg#understreg_et line#streg_et {
    stroke: #245328;
    animation: backandforth 6s linear infinite;
}

@keyframes backandforth {
    0% {
        transform: scaleX(1);
    }
    25% {
        transform: scaleX(0.8)
    }
    50% {
        transform: scaleX(0.5);
    }
    80% {
        transform: scaleX(0.8);
    }
    100% {
        transform: scaleX(1);
    }
}

/**** Introduktion *****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu p {
    font-size: 13px;
    line-height: 150%;
    padding-top: 15px;
    font-family: roboto;
}

/**** Navigation ****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav {
    font-size: 13px;
    line-height: 150%;
    margin-top: 10%;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul {}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li {
    list-style-type: none;
}

div#wrapper div#underlayer div#ComputerensHistorie section.left_menu nav ul li.links {
    margin-left: 20px;
    font-family: roboto;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li a {
    text-decoration: none;
    line-height: 150%;
    color: black;
    font-family: roboto;
    font-size: 0.9em;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li a:hover {
    color: #3f824f;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul ul {
    margin-left: 15px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li h2 {
    font-size: 14px;
    text-transform: uppercase;
    border-bottom: 1px solid #000;
    margin-bottom: 10px;
    font-family: roboto;
    padding-left: 5px;
    letter-spacing: 0.5px;
    width: auto;
}</code>```

Computerens historie

                    <svg id="understreg_et" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 8"><defs></defs><title>streg</title><line id="streg_tre" class="cls-1" y1="1" x2="60" y2="1"/><line id="streg_to" class="cls-1" x1="72" y1="4" x2="29" y2="4"/><line id="streg_et" class="cls-1" x1="11" y1="7" x2="46" y2="7"/></svg>

Vores dagligdag er konstant præget af den elektroniske verden, der omgiver os derhjemme, på gaden, arbejdet - alle steder!

Vi forsker hele tiden i hvordan vi kan optimere vores elektroniske viden, hvordan vi kan få det til at se smarter ud og ikke mindst mere praktisk.

Men hvordan startede det hele egentlig?

Kapitler

Lommeregneren som Grundsten

Antikythera - Den tidligste "computer"

Stamfaderen

Den tidlige computer

Konrad Zuse

Z3 Computeren

Referencer

                ```

答:
i don't know what you are dealing with but this might help.

if you dont want it any loner :

```<code>$( ".target" ).hide();
</code>```

if you have access to the code it self you can run this or if you are just a user and seems obsessed with the way it scrolls you can go to console on your browser and add that piece of code.

if you still want to keep it

```<code>var hieght = $('.target').height();
$(window).scroll(function(){
  if(window).scrollTop() > h){
    $('.stickty-menu').css('position','relative');
    // changes position  of sticky menu to relative to end scrolling
  }
});
</code>```

Title: Make sticky object stop being sticky

Body:
I'm about to make a portfolio for my exam. For that we have some articles we have to make for it. Therefore ive made a homepage, which shows the subjects that ive been writing about, and when you click on one of them, you come down to the article instantly.
On the left side there is a new menu which is sat as sticky, and scrolls with the page. The menu only contains the subjects that im going through for that single

My problem is, that the menu KEEPS on scrolling with the page, when it should stop after the article has ended, so a new chapter menu can appear. How do I do that?

Edit: I was on my phone when i wrote it.. But here is the code for the MENU on HTML, CSS and Jquery

  /*** Left Menu ***/
    var navLeftPos = $('#left_menu').offset().top;
    //console.log(navLeftPos)
    $(window).on('scroll', function () {
        console.log($(window).scrollTop())
        if (navTopPos <= $(window).scrollTop()) {
            $('#left_menu').addClass('left_menu')
        }
        if (navTopPos <= $(window).scrollTop() ) {
            $('#left_menu').addClass('left_menu')
        }
        else {
            $('#left_menu').removeClass('left_menu');
        }
    });

/*** Menu sidebar ***/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu {
    float:left;
    width: 30%;
    padding: 1.5% 1.5% 1.5% 5%;
    background-color: #C4E1AC;
}

div#wrapper div#underlayer div#ComputerensHistorie section.left_menu {
    position: fixed;
    top: 105px;
    left: 0;
}

/***** Overskrift *****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu h2 {
    font-family: Frank Ruhl Libre;
    letter-spacing: 2px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu svg {
    width: 60%;
    margin-bottom: 15px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu svg .cls-1 {
    stroke-width: 0.5px;
}

/***** Animations understreg *****/

svg#understreg_et line#streg_tre {
    stroke: #3A8540;
    animation: backandforth 12s linear infinite;
}

svg#understreg_et line#streg_to {
    stroke: #fff;
    animation: backandforth 4s linear infinite;
}

svg#understreg_et line#streg_et {
    stroke: #245328;
    animation: backandforth 6s linear infinite;
}

@keyframes backandforth {
    0% {
        transform: scaleX(1);
    }
    25% {
        transform: scaleX(0.8)
    }
    50% {
        transform: scaleX(0.5);
    }
    80% {
        transform: scaleX(0.8);
    }
    100% {
        transform: scaleX(1);
    }
}

/**** Introduktion *****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu p {
    font-size: 13px;
    line-height: 150%;
    padding-top: 15px;
    font-family: roboto;
}

/**** Navigation ****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav {
    font-size: 13px;
    line-height: 150%;
    margin-top: 10%;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul {}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li {
    list-style-type: none;
}

div#wrapper div#underlayer div#ComputerensHistorie section.left_menu nav ul li.links {
    margin-left: 20px;
    font-family: roboto;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li a {
    text-decoration: none;
    line-height: 150%;
    color: black;
    font-family: roboto;
    font-size: 0.9em;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li a:hover {
    color: #3f824f;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul ul {
    margin-left: 15px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li h2 {
    font-size: 14px;
    text-transform: uppercase;
    border-bottom: 1px solid #000;
    margin-bottom: 10px;
    font-family: roboto;
    padding-left: 5px;
    letter-spacing: 0.5px;
    width: auto;
}

Computerens historie

                    <svg id="understreg_et" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 8"><defs></defs><title>streg</title><line id="streg_tre" class="cls-1" y1="1" x2="60" y2="1"/><line id="streg_to" class="cls-1" x1="72" y1="4" x2="29" y2="4"/><line id="streg_et" class="cls-1" x1="11" y1="7" x2="46" y2="7"/></svg>

Vores dagligdag er konstant præget af den elektroniske verden, der omgiver os derhjemme, på gaden, arbejdet - alle steder!

Vi forsker hele tiden i hvordan vi kan optimere vores elektroniske viden, hvordan vi kan få det til at se smarter ud og ikke mindst mere praktisk.

Men hvordan startede det hele egentlig?

Kapitler

Lommeregneren som Grundsten

Antikythera - Den tidligste "computer"

Stamfaderen

Den tidlige computer

Konrad Zuse

Z3 Computeren

Referencer

Body:
i don't know what you are dealing with but this might help.

if you dont want it any loner :

$( ".target" ).hide();

if you have access to the code it self you can run this or if you are just a user and seems obsessed with the way it scrolls you can go to console on your browser and add that piece of code.

if you still want to keep it

var hieght = $('.target').height();
$(window).scroll(function(){
  if(window).scrollTop() > h){
    $('.stickty-menu').css('position','relative');
    // changes position  of sticky menu to relative to end scrolling
  }
});


答:
MySQL is hugely extensible, and don't let the fact that it's free convince you of otherwise.  Keeping the two tables separate is probably best, not only because it keeps the db more normal, but having more indices will speed queries.  A 10,000 record database is relatively small in deference to multi-hundred-million record health record databases.

As far as Amazon and Google, they hire hundreds of developers to write specialized query languages for their specific application needs... not something developers like us have the resources to fund.

Title: How to query huge MySQL databases?


问:
Incoming Webhooks risks?
Any idea what's the risk exposure when somebody accidentally loses the incoming webhook url for a Microsoft Teams channel?

To my understanding, data like team members or messages  are not accessible and basically the person having the url could potentially just spam the channel but not really extract anything?

答:
The biggest risk is, that (unless I understand something wrong) if someone with malicious intent got that URL, he/she could send Actionable Message with form and send the contents of that form to endpoint that is beyond your control. They could e.g. disguise that form as form provided by HR and requesting some sensitive info.

This seems like a huge hole in security, and I still think/hope that I just understand it wrong.

Title: Incoming Webhooks risks?


问:
Merging table depending on the same key
I want to merge two PHP arrays to third one and I want to depend them on the same key data. I've got data key in two arrays and I want stay with this. I want be depend on First array. I mean I load first array to final_array(), next I adding third key as ESTYMACJA from second array but to the same data from already loaded data key in final_array(). If there is no data key in final_array(), algorithm should add this key to final_array(), add WYKONANIA and copy ESTYMACJA. If it possible I would have also copied ESTYMACJA to the rest of data keys. I will show what I mean in final_array() expectation.

1st array:

```<code>$my_array=[
    ['data'=>'2017-11-27','ESTYMACJA'=>5000],
    ['data'=>'2017-11-30','ESTYMACJA'=>9000]
];
</code>```

2nd array:

```<code>$new_array=[
    ['data'=>'2017-11-01','WYKONANIA'=>3],
    ['data'=>'2017-11-02','WYKONANIA'=>10],
    ['data'=>'2017-11-03','WYKONANIA'=>303],
    ['data'=>'2017-11-04','WYKONANIA'=>327],
    ['data'=>'2017-11-05','WYKONANIA'=>652],
    ['data'=>'2017-11-06','WYKONANIA'=>812],
    ['data'=>'2017-11-07','WYKONANIA'=>817],
    ['data'=>'2017-11-08','WYKONANIA'=>870],
    ['data'=>'2017-11-09','WYKONANIA'=>1070],
    ['data'=>'2017-11-10','WYKONANIA'=>1199],
    ['data'=>'2017-11-11','WYKONANIA'=>1206],
    ['data'=>'2017-11-12','WYKONANIA'=>1220],
    ['data'=>'2017-11-13','WYKONANIA'=>1421],
    ['data'=>'2017-11-14','WYKONANIA'=>1440],
    ['data'=>'2017-11-15','WYKONANIA'=>1904],
    ['data'=>'2017-11-16','WYKONANIA'=>1910],
    ['data'=>'2017-11-17','WYKONANIA'=>1962],
    ['data'=>'2017-11-18','WYKONANIA'=>2234],
    ['data'=>'2017-11-19','WYKONANIA'=>2305],
    ['data'=>'2017-11-20','WYKONANIA'=>2325],
    ['data'=>'2017-11-21','WYKONANIA'=>2250],
    ['data'=>'2017-11-22','WYKONANIA'=>2263],
    ['data'=>'2017-11-23','WYKONANIA'=>2821],
    ['data'=>'2017-11-24','WYKONANIA'=>2890],
    ['data'=>'2017-11-25','WYKONANIA'=>3411],
    ['data'=>'2017-11-26','WYKONANIA'=>3443],
    ['data'=>'2017-11-27','WYKONANIA'=>3501],
    ['data'=>'2017-11-28','WYKONANIA'=>4032]
];
</code>```

final_array() expectation:

```<code>Array
(
    [0] => Array
        (
            [data] => 2017-11-01
            [WYKONANIA] => 3
            [ESTYMACJA] => 5000
        )

    [1] => Array
        (
            [data] => 2017-11-02
            [WYKONANIA] => 10
            [ESTYMACJA] => 5000
        )

    [2] => Array
        (
            [data] => 2017-11-03
            [WYKONANIA] => 303
            [ESTYMACJA] => 5000
        )

    [3] => Array
        (
            [data] => 2017-11-04
            [WYKONANIA] => 327
            [ESTYMACJA] => 5000
        )

    [4] => Array
        (
            [data] => 2017-11-05
            [WYKONANIA] => 652
            [ESTYMACJA] => 5000
        )

    [5] => Array
        (
            [data] => 2017-11-06
            [WYKONANIA] => 812
            [ESTYMACJA] => 5000
        )

    [6] => Array
        (
            [data] => 2017-11-07
            [WYKONANIA] => 817
            [ESTYMACJA] => 5000
        )

    [7] => Array
        (
            [data] => 2017-11-08
            [WYKONANIA] => 870
            [ESTYMACJA] => 5000
        )

    [8] => Array
        (
            [data] => 2017-11-09
            [WYKONANIA] => 1070
            [ESTYMACJA] => 5000
        )

    [9] => Array
        (
            [data] => 2017-11-10
            [WYKONANIA] => 1199
            [ESTYMACJA] => 5000
        )

    [10] => Array
        (
            [data] => 2017-11-11
            [WYKONANIA] => 1206
            [ESTYMACJA] => 5000
        )

    [11] => Array
        (
            [data] => 2017-11-12
            [WYKONANIA] => 1220
            [ESTYMACJA] => 5000
        )

    [12] => Array
        (
            [data] => 2017-11-13
            [WYKONANIA] => 1421
            [ESTYMACJA] => 5000
        )

    [13] => Array
        (
            [data] => 2017-11-14
            [WYKONANIA] => 1440
            [ESTYMACJA] => 5000
        )

    [14] => Array
        (
            [data] => 2017-11-15
            [WYKONANIA] => 1904
            [ESTYMACJA] => 5000
        )

    [15] => Array
        (
            [data] => 2017-11-16
            [WYKONANIA] => 1910
            [ESTYMACJA] => 5000
        )

    [16] => Array
        (
            [data] => 2017-11-17
            [WYKONANIA] => 1962
            [ESTYMACJA] => 5000
        )

    [17] => Array
        (
            [data] => 2017-11-18
            [WYKONANIA] => 2234
            [ESTYMACJA] => 5000
        )

    [18] => Array
        (
            [data] => 2017-11-19
            [WYKONANIA] => 2305
            [ESTYMACJA] => 5000
        )

    [19] => Array
        (
            [data] => 2017-11-20
            [WYKONANIA] => 2325
            [ESTYMACJA] => 5000
        )

    [20] => Array
        (
            [data] => 2017-11-21
            [WYKONANIA] => 2250
            [ESTYMACJA] => 5000
        )

    [21] => Array
        (
            [data] => 2017-11-22
            [WYKONANIA] => 2263
            [ESTYMACJA] => 5000
        )

    [22] => Array
        (
            [data] => 2017-11-23
            [WYKONANIA] => 2821
            [ESTYMACJA] => 5000
        )

    [23] => Array
        (
            [data] => 2017-11-24
            [WYKONANIA] => 2890
            [ESTYMACJA] => 5000
        )

    [24] => Array
        (
            [data] => 2017-11-25
            [WYKONANIA] => 3411
            [ESTYMACJA] => 5000
        )

    [25] => Array
        (
            [data] => 2017-11-26
            [WYKONANIA] => 3443
            [ESTYMACJA] => 5000
        )

    [26] => Array
        (
            [data] => 2017-11-27
            [WYKONANIA] => 3501
            **[ESTYMACJA] => 5000**
        )

    [27] => Array
        (
            [data] => 2017-11-28
            [WYKONANIA] => 4032
            [ESTYMACJA] => 5000

        )

    *[28] => Array
        (
            [data] => 2017-11-30
            [WYKONANIA] => 4032
            [ESTYMACJA] => 9000

        )
</code>```

This code is already what i've done but im stuck right now.

```<code>$x = 0;
while ($x<count($final_array))
{
    if ($new_array == null) {
    break;
    }
    else {
        for ($i = 0; $i < count($new_array); $i++) {
            if ($final_array[$x]['data'] == ($new_array[$i]['data']) {
                $final_array[$x]['WYKONANIA'] = $new_array['WYKONANIA'];
            }
            else {
                array_push($final_array, "data", $new_array[$i]['data']);
                array_push($final_array, "WYKONANIA", $new_array[$i]['WYKONANIA']);
                array_push($final_array, "ESTYMACJA", $final_array[$x]['ESTYMACJA']);
            }
        }
    }
    $x++;
}

$myArray - first array
$new_array - second array
$final_array - final array.
</code>```

答:
```<code>// sort my_array in descending order of dates
rsort($my_array);

foreach($new_array as &$x) {
   foreach($my_array as $i) {
     // Because your dates have a different format, convert them to timestamp
     if(strtotime($x['data']) > strtotime($i['data'])) {
       $x['ESTYMACJA'] = $i['ESTYMACJA'];
       break;
     }
   }
}
</code>```

demo

Title: Merging table depending on the same key

Body:
I want to merge two PHP arrays to third one and I want to depend them on the same key data. I've got data key in two arrays and I want stay with this. I want be depend on First array. I mean I load first array to final_array(), next I adding third key as ESTYMACJA from second array but to the same data from already loaded data key in final_array(). If there is no data key in final_array(), algorithm should add this key to final_array(), add WYKONANIA and copy ESTYMACJA. If it possible I would have also copied ESTYMACJA to the rest of data keys. I will show what I mean in final_array() expectation.

1st array:

$my_array=[
    ['data'=>'2017-11-27','ESTYMACJA'=>5000],
    ['data'=>'2017-11-30','ESTYMACJA'=>9000]
];

2nd array:

$new_array=[
    ['data'=>'2017-11-01','WYKONANIA'=>3],
    ['data'=>'2017-11-02','WYKONANIA'=>10],
    ['data'=>'2017-11-03','WYKONANIA'=>303],
    ['data'=>'2017-11-04','WYKONANIA'=>327],
    ['data'=>'2017-11-05','WYKONANIA'=>652],
    ['data'=>'2017-11-06','WYKONANIA'=>812],
    ['data'=>'2017-11-07','WYKONANIA'=>817],
    ['data'=>'2017-11-08','WYKONANIA'=>870],
    ['data'=>'2017-11-09','WYKONANIA'=>1070],
    ['data'=>'2017-11-10','WYKONANIA'=>1199],
    ['data'=>'2017-11-11','WYKONANIA'=>1206],
    ['data'=>'2017-11-12','WYKONANIA'=>1220],
    ['data'=>'2017-11-13','WYKONANIA'=>1421],
    ['data'=>'2017-11-14','WYKONANIA'=>1440],
    ['data'=>'2017-11-15','WYKONANIA'=>1904],
    ['data'=>'2017-11-16','WYKONANIA'=>1910],
    ['data'=>'2017-11-17','WYKONANIA'=>1962],
    ['data'=>'2017-11-18','WYKONANIA'=>2234],
    ['data'=>'2017-11-19','WYKONANIA'=>2305],
    ['data'=>'2017-11-20','WYKONANIA'=>2325],
    ['data'=>'2017-11-21','WYKONANIA'=>2250],
    ['data'=>'2017-11-22','WYKONANIA'=>2263],
    ['data'=>'2017-11-23','WYKONANIA'=>2821],
    ['data'=>'2017-11-24','WYKONANIA'=>2890],
    ['data'=>'2017-11-25','WYKONANIA'=>3411],
    ['data'=>'2017-11-26','WYKONANIA'=>3443],
    ['data'=>'2017-11-27','WYKONANIA'=>3501],
    ['data'=>'2017-11-28','WYKONANIA'=>4032]
];

final_array() expectation:

Array
(
    [0] => Array
        (
            [data] => 2017-11-01
            [WYKONANIA] => 3
            [ESTYMACJA] => 5000
        )

    [1] => Array
        (
            [data] => 2017-11-02
            [WYKONANIA] => 10
            [ESTYMACJA] => 5000
        )

    [2] => Array
        (
            [data] => 2017-11-03
            [WYKONANIA] => 303
            [ESTYMACJA] => 5000
        )

    [3] => Array
        (
            [data] => 2017-11-04
            [WYKONANIA] => 327
            [ESTYMACJA] => 5000
        )

    [4] => Array
        (
            [data] => 2017-11-05
            [WYKONANIA] => 652
            [ESTYMACJA] => 5000
        )

    [5] => Array
        (
            [data] => 2017-11-06
            [WYKONANIA] => 812
            [ESTYMACJA] => 5000
        )

    [6] => Array
        (
            [data] => 2017-11-07
            [WYKONANIA] => 817
            [ESTYMACJA] => 5000
        )

    [7] => Array
        (
            [data] => 2017-11-08
            [WYKONANIA] => 870
            [ESTYMACJA] => 5000
        )

    [8] => Array
        (
            [data] => 2017-11-09
            [WYKONANIA] => 1070
            [ESTYMACJA] => 5000
        )

    [9] => Array
        (
            [data] => 2017-11-10
            [WYKONANIA] => 1199
            [ESTYMACJA] => 5000
        )

    [10] => Array
        (
            [data] => 2017-11-11
            [WYKONANIA] => 1206
            [ESTYMACJA] => 5000
        )

    [11] => Array
        (
            [data] => 2017-11-12
            [WYKONANIA] => 1220
            [ESTYMACJA] => 5000
        )

    [12] => Array
        (
            [data] => 2017-11-13
            [WYKONANIA] => 1421
            [ESTYMACJA] => 5000
        )

    [13] => Array
        (
            [data] => 2017-11-14
            [WYKONANIA] => 1440
            [ESTYMACJA] => 5000
        )

    [14] => Array
        (
            [data] => 2017-11-15
            [WYKONANIA] => 1904
            [ESTYMACJA] => 5000
        )

    [15] => Array
        (
            [data] => 2017-11-16
            [WYKONANIA] => 1910
            [ESTYMACJA] => 5000
        )

    [16] => Array
        (
            [data] => 2017-11-17
            [WYKONANIA] => 1962
            [ESTYMACJA] => 5000
        )

    [17] => Array
        (
            [data] => 2017-11-18
            [WYKONANIA] => 2234
            [ESTYMACJA] => 5000
        )

    [18] => Array
        (
            [data] => 2017-11-19
            [WYKONANIA] => 2305
            [ESTYMACJA] => 5000
        )

    [19] => Array
        (
            [data] => 2017-11-20
            [WYKONANIA] => 2325
            [ESTYMACJA] => 5000
        )

    [20] => Array
        (
            [data] => 2017-11-21
            [WYKONANIA] => 2250
            [ESTYMACJA] => 5000
        )

    [21] => Array
        (
            [data] => 2017-11-22
            [WYKONANIA] => 2263
            [ESTYMACJA] => 5000
        )

    [22] => Array
        (
            [data] => 2017-11-23
            [WYKONANIA] => 2821
            [ESTYMACJA] => 5000
        )

    [23] => Array
        (
            [data] => 2017-11-24
            [WYKONANIA] => 2890
            [ESTYMACJA] => 5000
        )

    [24] => Array
        (
            [data] => 2017-11-25
            [WYKONANIA] => 3411
            [ESTYMACJA] => 5000
        )

    [25] => Array
        (
            [data] => 2017-11-26
            [WYKONANIA] => 3443
            [ESTYMACJA] => 5000
        )

    [26] => Array
        (
            [data] => 2017-11-27
            [WYKONANIA] => 3501
            **[ESTYMACJA] => 5000**
        )

    [27] => Array
        (
            [data] => 2017-11-28
            [WYKONANIA] => 4032
            [ESTYMACJA] => 5000

        )

    *[28] => Array
        (
            [data] => 2017-11-30
            [WYKONANIA] => 4032
            [ESTYMACJA] => 9000

        )

This code is already what i've done but im stuck right now.

$x = 0;
while ($x<count($final_array))
{
    if ($new_array == null) {
    break;
    }
    else {
        for ($i = 0; $i < count($new_array); $i++) {
            if ($final_array[$x]['data'] == ($new_array[$i]['data']) {
                $final_array[$x]['WYKONANIA'] = $new_array['WYKONANIA'];
            }
            else {
                array_push($final_array, "data", $new_array[$i]['data']);
                array_push($final_array, "WYKONANIA", $new_array[$i]['WYKONANIA']);
                array_push($final_array, "ESTYMACJA", $final_array[$x]['ESTYMACJA']);
            }
        }
    }
    $x++;
}

$myArray - first array
$new_array - second array
$final_array - final array.

Body:
// sort my_array in descending order of dates
rsort($my_array);

foreach($new_array as &$x) {
   foreach($my_array as $i) {
     // Because your dates have a different format, convert them to timestamp
     if(strtotime($x['data']) > strtotime($i['data'])) {
       $x['ESTYMACJA'] = $i['ESTYMACJA'];
       break;
     }
   }
}

demo


问:
How to mark a build unstable in Jenkins when running shell scripts
In a project I'm working on, we are using shell scripts to execute different tasks. Some are sh/bash scripts that run rsync, and some are PHP scripts. One of the PHP scripts is running some integration tests that output to JUnit XML, code coverage reports, and similar.

Jenkins is able to mark the jobs as successful / failed based on exit status. In PHP, the script exits with 1 if it has detected that the tests failed during the run. The other shell scripts run commands and use the exit codes from those to mark a build as failed.

```<code>// :: End of PHP script:
// If any tests have failed, fail the build
if ($build_error) exit(1);
</code>```

In Jenkins Terminology, an unstable build is defined as:

A build is unstable if it was built successfully and one or more publishers report it unstable. For example if the JUnit publisher is configured and a test fails then the build will be marked unstable.

How can I get Jenkins to mark a build as unstable instead of only success / failed when running shell scripts?

答:
I thought I would post another answer for people that might be looking for something similar.

In our build job we have cases where we would want the build to continue, but be marked as unstable.  For ours it's relating to version numbers.

So, I wanted to set a condition on the build and set the build to unstable if that condition is met.

I used the Conditional step (single) option as a build step.

Then I used Execute system Groovy script as the build step that would run when that condition is met.

I used Groovy Command and set the script the following

```<code>import hudson.model.*

def build = Thread.currentThread().executable
build.@result = hudson.model.Result.UNSTABLE

return
</code>```

That seems to work quite well.

I stumbled upon the solution here

http://tech.akom.net/archives/112-Marking-Jenkins-build-UNSTABLE-from-environment-inject-groovy-script.html

ContentLicense: CC BY-SA 4.0

Body:
In a project I'm working on, we are using shell scripts to execute different tasks. Some are sh/bash scripts that run rsync, and some are PHP scripts. One of the PHP scripts is running some integration tests that output to JUnit XML, code coverage reports, and similar.

Jenkins is able to mark the jobs as successful / failed based on exit status. In PHP, the script exits with 1 if it has detected that the tests failed during the run. The other shell scripts run commands and use the exit codes from those to mark a build as failed.

// :: End of PHP script:
// If any tests have failed, fail the build
if ($build_error) exit(1);

In Jenkins Terminology, an unstable build is defined as:

A build is unstable if it was built successfully and one or more publishers report it unstable. For example if the JUnit publisher is configured and a test fails then the build will be marked unstable.

How can I get Jenkins to mark a build as unstable instead of only success / failed when running shell scripts?

Body:
I thought I would post another answer for people that might be looking for something similar.

In our build job we have cases where we would want the build to continue, but be marked as unstable.  For ours it's relating to version numbers.

So, I wanted to set a condition on the build and set the build to unstable if that condition is met.

I used the Conditional step (single) option as a build step.

Then I used Execute system Groovy script as the build step that would run when that condition is met.

I used Groovy Command and set the script the following

import hudson.model.*

def build = Thread.currentThread().executable
build.@result = hudson.model.Result.UNSTABLE

return

That seems to work quite well.

I stumbled upon the solution here

http://tech.akom.net/archives/112-Marking-Jenkins-build-UNSTABLE-from-environment-inject-groovy-script.html


问:
ERROR TypeError: _co.onBlueprintAdded is not a function
cockpit.component.ts . . . ... . . ... . . . . .... .  . . .
.... ......... ....... ........ . . ... .. . ..... . ... . . ...  . . ...

import {Component, EventEmitter, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-cockpit',
  templateUrl: './cockpit.component.html',
  styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
  @Output() serverCreated = new EventEmitter<{serverName: string, serverContent: string}>();
  @Output() blueprintCreated = new EventEmitter<{serverName: string, serverContent: string}>();
  newServerName = '';
  newServerContent = '';
  constructor() { }

  ngOnInit() {
  }
  onAddServer() {
    this.serverCreated.emit(
      {serverName: this.newServerName,
        serverContent: this.newServerContent
      });
  }

  onAddBlueprint() {
    this.blueprintCreated.emit(
      {serverName: this.newServerName,
        serverContent: this.newServerContent
      });
  }
}```
</div>
</div>
</p>

<p>Can anyone explain why I get the following error? I'm a beginner in angular.</p>

<p>app.component.ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  serverElements = [{
    type: 'server',
    name: 'Testserver',
    content: 'Just a Test!!'
  }];

  onServerAdded(serverData: {serverName: string, serverContent: string}) {
    this.serverElements.push({
      type: 'server',
      name: serverData.serverName,
      content: serverData.serverContent
    });
  }

  onBlueprintAdded(blueprintData: {serverName: string, serverContent: string}) {
    this.serverElements.push({
      type: 'blueprint',
      name: blueprintData.serverName,
      content: blueprintData.serverContent
    });
  }
}</code>```

  <app-cockpit
    (serverCreated)="onServerAdded($event)"
    (blueprintCreated)="onBlueprintAdded($event)"
  ></app-cockpit>

     <app-server-element
       *ngFor="let serverElement of serverElements"
       [element]="serverElement"
     ></app-server-element>

```
</div>
</div>
</p>

<p>Error in the console:</p>

```AppComponent.html:2 ERROR TypeError: _co.onBlueprintAdded is not a function
    at Object.eval [as handleEvent] (AppComponent.html:4)
    at handleEvent (core.es5.js:12023)
    at callWithDebugContext (core.es5.js:13493)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13081)
    at dispatchEvent (core.es5.js:8615)
    at core.es5.js:10783
    at SafeSubscriber.schedulerFn [as _next] (core.es5.js:3647)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)
```

bear with me still need to write some stuffs before i can post the question

答: Just re run the ng serve  again, it will make the new Bundle</p>

Body:
cockpit.component.ts . . . ... . . ... . . . . .... .  . . .
.... ......... ....... ........ . . ... .. . ..... . ... . . ...  . . ...

import {Component, EventEmitter, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-cockpit',
  templateUrl: './cockpit.component.html',
  styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
  @Output() serverCreated = new EventEmitter<{serverName: string, serverContent: string}>();
  @Output() blueprintCreated = new EventEmitter<{serverName: string, serverContent: string}>();
  newServerName = '';
  newServerContent = '';
  constructor() { }

  ngOnInit() {
  }
  onAddServer() {
    this.serverCreated.emit(
      {serverName: this.newServerName,
        serverContent: this.newServerContent
      });
  }

  onAddBlueprint() {
    this.blueprintCreated.emit(
      {serverName: this.newServerName,
        serverContent: this.newServerContent
      });
  }
}

Can anyone explain why I get the following error? I'm a beginner in angular.

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  serverElements = [{
    type: 'server',
    name: 'Testserver',
    content: 'Just a Test!!'
  }];

  onServerAdded(serverData: {serverName: string, serverContent: string}) {
    this.serverElements.push({
      type: 'server',
      name: serverData.serverName,
      content: serverData.serverContent
    });
  }

  onBlueprintAdded(blueprintData: {serverName: string, serverContent: string}) {
    this.serverElements.push({
      type: 'blueprint',
      name: blueprintData.serverName,
      content: blueprintData.serverContent
    });
  }
}

  <app-cockpit
    (serverCreated)="onServerAdded($event)"
    (blueprintCreated)="onBlueprintAdded($event)"
  ></app-cockpit>

     <app-server-element
       *ngFor="let serverElement of serverElements"
       [element]="serverElement"
     ></app-server-element>

Error in the console:

AppComponent.html:2 ERROR TypeError: _co.onBlueprintAdded is not a function
    at Object.eval [as handleEvent] (AppComponent.html:4)
    at handleEvent (core.es5.js:12023)
    at callWithDebugContext (core.es5.js:13493)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13081)
    at dispatchEvent (core.es5.js:8615)
    at core.es5.js:10783
    at SafeSubscriber.schedulerFn [as _next] (core.es5.js:3647)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)

bear with me still need to write some stuffs before i can post the question


问:
.updateOne on MongoDB not working in Node.js
I have the following code:

```<code>connection((db) => {
            db.collection('orders')
                .updateOne(
                    { "_id": req.body._id}, // Filter
                    {"name": req.body.name} // Update
                )
                .then((obj) => {
                    console.log('Updated - ' + obj);
                    res.redirect('orders')
                })
                .catch((err) => {
                    console.log('Error: ' + err);
                })
        })
</code>```

I want to change the name in the order but it doesn't update it.
The result in the console is

Updated - {"n":0,"nModified":0,"ok":1}

I tried to read the documentation but it's horrific

EDIT: {$set: {"name": req.body.name}}, didn't work as well

EDIT 2: The passed ID matches the _id in the database. Could it be a problem that I'm querying for plain text ID while in the database it is referred to as "ObjectId('5a42ja...')"

答:
Maybe you should use "$set" in your update query like this :

```<code>{$set: {"name": req.body.name}}, // Update
</code>```

More information in documentation

EDIT

If it doesn't work, this is probably because there is no match with your filter.

Maybe you should try to match with an ObjectId like this :

```<code>var ObjectID = require('mongodb').ObjectID;

// In your request
{ "_id": ObjectID(req.body._id)}, // Filter
</code>```

Hope it helps.

Body:
I have the following code:

connection((db) => {
            db.collection('orders')
                .updateOne(
                    { "_id": req.body._id}, // Filter
                    {"name": req.body.name} // Update
                )
                .then((obj) => {
                    console.log('Updated - ' + obj);
                    res.redirect('orders')
                })
                .catch((err) => {
                    console.log('Error: ' + err);
                })
        })

I want to change the name in the order but it doesn't update it.
The result in the console is

Updated - {"n":0,"nModified":0,"ok":1}

I tried to read the documentation but it's horrific

EDIT: {$set: {"name": req.body.name}}, didn't work as well

EDIT 2: The passed ID matches the _id in the database. Could it be a problem that I'm querying for plain text ID while in the database it is referred to as "ObjectId('5a42ja...')"

Body:
Maybe you should use "$set" in your update query like this :

{$set: {"name": req.body.name}}, // Update

More information in documentation

EDIT

If it doesn't work, this is probably because there is no match with your filter.

Maybe you should try to match with an ObjectId like this :

var ObjectID = require('mongodb').ObjectID;

// In your request
{ "_id": ObjectID(req.body._id)}, // Filter

Hope it helps.


问:
How can I avoid duplicate rows from SQL statement?
My problem is, that the following SQL query returns duplicate rows:

```<code>select
inv.i4201 as pmid,
inv.i4235 as calPlace,
inv.i4204 as device,
inv.i4203 as type,
inv.i4202 as manufacturer,
inv.i4206 as serialNumber,
cal.c2323 as condition,
inv.i4299 as availability,
inv.i4236 as dateRegistration,
max(cal.c2301) as dateCalibration,
inv.i4229 as interval,
max(cal.c2303) as dateExpiry,
inv.i4228 as intervallType,
loc.l2803 as costCenter,
inv.i4242 as location,
cust.k4601 as CustomerNumber,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
calPlace,
device,
type,
manufacturer,
serialNumber,
condition,
availability,
dateRegistration,
interval,
intervallType,
costCenter,
location,
CustomerNumber,
CustomerName

order by pmid;
</code>```

What do I do to get just one row for each pmid with the latest dateCalibration and/or dateExpiry?

答:
I think you might need to investigate further. The real question here is "why are you getting duplicate rows?" Are there duplicate customer records? If so, try using the DISTINCT key word. Since you are joining tables, do some customers have multiple locations? Or multiple calibration records? If so, you will need to determine which records you "want" in your result set. Do you want the first record? Or the latest record? Or is there another condition to determine the data you want to show?

After answering these, then use some aggregate functions such as MAX or MIN or SUM or COUNT etc. It really depends on what data you need to extract.

Body:
My problem is, that the following SQL query returns duplicate rows:

select
inv.i4201 as pmid,
inv.i4235 as calPlace,
inv.i4204 as device,
inv.i4203 as type,
inv.i4202 as manufacturer,
inv.i4206 as serialNumber,
cal.c2323 as condition,
inv.i4299 as availability,
inv.i4236 as dateRegistration,
max(cal.c2301) as dateCalibration,
inv.i4229 as interval,
max(cal.c2303) as dateExpiry,
inv.i4228 as intervallType,
loc.l2803 as costCenter,
inv.i4242 as location,
cust.k4601 as CustomerNumber,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
calPlace,
device,
type,
manufacturer,
serialNumber,
condition,
availability,
dateRegistration,
interval,
intervallType,
costCenter,
location,
CustomerNumber,
CustomerName

order by pmid;

What do I do to get just one row for each pmid with the latest dateCalibration and/or dateExpiry?


问:
Hide and show text by click on div
I have a question concerning an event onclick. I found this code during my research. My question is : even before the click the text already appears, is it possible to hide the text until we click on the actual button. And is it possible to have numerous onclick event working seperately that is o say only open the text above it? Thank you

  <title>Show and hide div with JavaScript</title>

This div will be show and hide on button click

  <button id="button" onclick="showhide()">Click Me</button>

```

答:
In JQuery you can add multiple on click events to a button like so:

     $("#button").on("click", function(){
      $("#newpost").toggle();
     });

     $("#button").on("click", function(){
      $("#secondpost").toggleClass("bold");
     });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#newpost{
  display:none;
}

.bold{
  font-weight:bold;
}</code>```

  <title>Show and hide div with JavaScript</title>

This div will be show and hide on button click

  <button id="button">Click Me</button>

toggle bold

```

The first on click toggles the paragraph above.
The second on click toggles a class on the last paragraph that makes it bold.

Title: Hide and show text by click on div

Body:
In JQuery you can add multiple on click events to a button like so:

     $("#button").on("click", function(){
      $("#newpost").toggle();
     });

     $("#button").on("click", function(){
      $("#secondpost").toggleClass("bold");
     });

#newpost{
  display:none;
}

.bold{
  font-weight:bold;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
 <head>
  <title>Show and hide div with JavaScript</title>
 </head>
 <body>
  <div id="newpost">
    <p>This div will be show and hide on button click</p>
  </div>
  <button id="button">Click Me</button>
  <p id="secondpost">toggle bold</p>
</body>
</html>

The first on click toggles the paragraph above.
The second on click toggles a class on the last paragraph that makes it bold.