问:
How to render the ReactDOM every second?
I'm new to React, I'm trying to follow this ticking clock example but do something a bit different. I'd like the ReactDOM to be rendered in the index.js. Here is my code:

Timer.js:

import React from 'react';

const Timer = () => {
    const tick = () => {
        return new Date().toLocaleTimeString().toString();
    };

    const element = (

Hello World!

It is {tick()} !

    );

    return (
        element
    );
};

export default Timer;```
</div>
</div>
</p>

<p><strong>App.js:</strong> </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>/*jshint esversion: 8 */
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Timer from './Timer'

function App() {
  return (
    <div className="App">
      <Timer />
    </div>
  );
}

export default App;</code>```

index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import App from './App';

setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000);

serviceWorker.unregister();```

But it only prints the current time on screen, not ticking. Why does the code setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000); not work on index.js?

答:
Set the date field to the state object and in tick function use setInterval to set a new value to state using setState. Use state.date value to show the time. React renders new dom each time state is changed using setState function.

A working example of a timer has been given in react docs, giving it a read will help you lots.
https://reactjs.org/docs/state-and-lifecycle.html

Body:
I'm new to React, I'm trying to follow this ticking clock example but do something a bit different. I'd like the ReactDOM to be rendered in the index.js. Here is my code:

Timer.js:

import React from 'react';

const Timer = () => {
    const tick = () => {
        return new Date().toLocaleTimeString().toString();
    };

    const element = (

Hello World!

It is {tick()} !

    );

    return (
        element
    );
};

export default Timer;

App.js:

/*jshint esversion: 8 */
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Timer from './Timer'

function App() {
  return (

      <Timer />

  );
}

export default App;

index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import App from './App';

setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000);

serviceWorker.unregister();

But it only prints the current time on screen, not ticking. Why does the code setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000); not work on index.js?


来源: stackexchange

问:
How Integrate Admob ads on Cordova in 2020?
I convert my html5 game to android studio project through Cordova and PhoneGap, please how I can integrate Admob ads on my project, all tutorial available not working in 2020. </p>

<p>Kind Regards, </p>

答:
use cordova-plugin-admob-free it's working perfect in 2020

check here in github

ContentLicense: CC BY-SA 4.0

Body:
I convert my html5 game to android studio project through Cordova and PhoneGap, please how I can integrate Admob ads on my project, all tutorial available not working in 2020.

Kind Regards,


问:
How to create array of given length and same number?
When using SUMSERIES I need to specify "the array or range containing the coefficients of the power series" but I want to make it so the number of elements is dynamic while the element itself (1) remains the same.
Example:

SUM FROM 0 TO N of x^1,5

```<code>(cell) Length of series N : 7  -- > SUMSERIES(1,5;0;1;{1,1,1,1,1,1,1})
</code>```

But I should be able to change the seven for a 3 and get --> SUMSERIES(1,5;0;1;{1,1,1})

In Java for example you'd declare and instantiate the array --> int[] arr = new int[N];

And then fill in a loop --> for(int i = 0; i <arr.length; i++) {arr[i] = 1,5}

Thanks in advance and sorry if the explanation isn´t clear, it's my first time around hehe

答:
this should work:</p>

```<code>=SUMSERIES(1,5;0;1;SEQUENCE(1,[cell],1,0))
</code>```

Body:
When using SUMSERIES I need to specify "the array or range containing the coefficients of the power series" but I want to make it so the number of elements is dynamic while the element itself (1) remains the same.
Example:

SUM FROM 0 TO N of x^1,5

(cell) Length of series N : 7  -- > SUMSERIES(1,5;0;1;{1,1,1,1,1,1,1})

But I should be able to change the seven for a 3 and get --> SUMSERIES(1,5;0;1;{1,1,1})

In Java for example you'd declare and instantiate the array --> int[] arr = new int[N];

And then fill in a loop --> for(int i = 0; i <arr.length; i++) {arr[i] = 1,5}

Thanks in advance and sorry if the explanation isn´t clear, it's my first time around hehe

Body:
this should work:

=SUMSERIES(1,5;0;1;SEQUENCE(1,[cell],1,0))


问:
How do Cardinalities and Generalization work in UML?
I am trying to understand how Cardinalities and Relationships work with Generalization in simple UML class diagrams. I have this simple example here:

A Player owns exactly 9 Fields, but the distribution of them is irrelevant (i.e. 5 Endfields, 4 Startfields or 1 Endfield and 8 Startfields). The Field class is abstract. If i model this problem as seen above, would a Player have 9 Fields from each type? If so, how do i model this correctly?

答:
If i model this problem as seen above, would a Player have 9 Fields from each type?

not at the same time. In your model a Player is associated to 9 Fields, knowing each Field is a Endfield or-exclusive a Startfield (supposing there are no other classes inheriting Field)

A given instance of Field cannot be both a Endfield and a Startfield, else that means Fields inherits both Startfield and Endfield (but the inheritances are in the opposite direction)

The corresponding classes in Java from your model can be :

```<code>abstract class Field { .... }
class Startfield extends Field { ... }
class Endfield extends Field { .. }
</code>```

so a Player can be in relation with 9 Endfields, or-exclusive 8 Endfields and 1 Startfield, or-exclusive 7 Endfields and 2 Startfield, ..., or-exclusive 1 Endfield and 8 Startfields, or-exclusive 9 Startfields

If you want a Player has 9 Startfields and 9 EndFields your model can be :

[edit]

However if you extend your model adding an other class inheriting Startfield and Endtfield like :

in case a Player is associated to 9 Bothfields in a way it is also associated with 9 Startfield and 9 Endtfield

The multiplicity (9) of the relation concerns Field, for the inheriting classes that depends as you can see

Body:
If i model this problem as seen above, would a Player have 9 Fields from each type?

not at the same time. In your model a Player is associated to 9 Fields, knowing each Field is a Endfield or-exclusive a Startfield (supposing there are no other classes inheriting Field)

A given instance of Field cannot be both a Endfield and a Startfield, else that means Fields inherits both Startfield and Endfield (but the inheritances are in the opposite direction)

The corresponding classes in Java from your model can be :

abstract class Field { .... }
class Startfield extends Field { ... }
class Endfield extends Field { .. }

so a Player can be in relation with 9 Endfields, or-exclusive 8 Endfields and 1 Startfield, or-exclusive 7 Endfields and 2 Startfield, ..., or-exclusive 1 Endfield and 8 Startfields, or-exclusive 9 Startfields

If you want a Player has 9 Startfields and 9 EndFields your model can be :

[edit]

However if you extend your model adding an other class inheriting Startfield and Endtfield like :

in case a Player is associated to 9 Bothfields in a way it is also associated with 9 Startfield and 9 Endtfield

The multiplicity (9) of the relation concerns Field, for the inheriting classes that depends as you can see


问:
Loop query through multiple tables
I would like to the same query which should almost never return any results through multiple tables. The table name is the same except with the addition of the year. So my query looks like this:

```<code>select p.productID, po.name, p.price from prices_2001  p
join products po on p.productID = po.id
where price < 0
</code>```

and I would like to loop through all the years from 2001 to 2020. So it should look like this:

```<code>select p.productID, po.name, p.price from prices_2001  p
join products po on p.productID = po.id
where price < 0

select p.productID, po.name, p.price from prices_2002  p
join products po on p.productID = po.id
where price < 0

select p.productID, po.name, p.price from prices_2003  p    --Looping trough all the tables until 2020
join products po on p.productID = po.id
where price < 0
</code>```

If there are results they can be stored in a temp table. I thought of creating a loop with the table names or creating dynamic sql query. What is the best practice and how can I use this query for all the tables just by executing it once?

Thank you!

答:
To reiterate my comment:

This sounds like a denormalisation problem, really you should have 1 table with a column for the year.

Really, you should be fixing your design.

Anyway, onto the problem: You can do this with dynamic SQL, yes, but you'd be better off fixing the design. This however, create and executes the statement dynamically. i've used FOR XML PATH due to a lack of version tag:

```<code>DECLARE @SQL nvarchar(MAX),
        @CRLF nchar(2) = NCHAR(13) + NCHAR(10);

SET @SQL = STUFF((SELECT @CRLF + N'UNION ALL' + @CRLF +
                         N'SELECT p.productID, po.name, p.price' + @CRLF +
                         N'FROM ' + QUOTENAME(t.[name]) + N'p' + @CRLF +
                         N'     JOIN product po ON p.productID = po.id' + @CRLF +
                         N'WHERE p.price < 0'
                  FROM sys.tables t
                  WHERE t.[name] LIKE N'prices[_]20[0-9][0-9]'
                  ORDER BY t.[name]
                  FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,13,N'') + N';';

--PRINT @SQL; --Your debugging friend

EXEC sys.sp_executesql @SQL;
</code>```

Title: Loop query through multiple tables

Body:
I would like to the same query which should almost never return any results through multiple tables. The table name is the same except with the addition of the year. So my query looks like this:

select p.productID, po.name, p.price from prices_2001  p
join products po on p.productID = po.id
where price < 0

and I would like to loop through all the years from 2001 to 2020. So it should look like this:

select p.productID, po.name, p.price from prices_2001  p
join products po on p.productID = po.id
where price < 0

select p.productID, po.name, p.price from prices_2002  p
join products po on p.productID = po.id
where price < 0

select p.productID, po.name, p.price from prices_2003  p    --Looping trough all the tables until 2020
join products po on p.productID = po.id
where price < 0

If there are results they can be stored in a temp table. I thought of creating a loop with the table names or creating dynamic sql query. What is the best practice and how can I use this query for all the tables just by executing it once?

Thank you!

Body:
To reiterate my comment:

This sounds like a denormalisation problem, really you should have 1 table with a column for the year.

Really, you should be fixing your design.

Anyway, onto the problem: You can do this with dynamic SQL, yes, but you'd be better off fixing the design. This however, create and executes the statement dynamically. i've used FOR XML PATH due to a lack of version tag:

DECLARE @SQL nvarchar(MAX),
        @CRLF nchar(2) = NCHAR(13) + NCHAR(10);

SET @SQL = STUFF((SELECT @CRLF + N'UNION ALL' + @CRLF +
                         N'SELECT p.productID, po.name, p.price' + @CRLF +
                         N'FROM ' + QUOTENAME(t.[name]) + N'p' + @CRLF +
                         N'     JOIN product po ON p.productID = po.id' + @CRLF +
                         N'WHERE p.price < 0'
                  FROM sys.tables t
                  WHERE t.[name] LIKE N'prices[_]20[0-9][0-9]'
                  ORDER BY t.[name]
                  FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,13,N'') + N';';

--PRINT @SQL; --Your debugging friend

EXEC sys.sp_executesql @SQL;


问:
Clarify Objective-C categories in separate file
I have added some methods to existing class in engine by category. This category is declared and implemented in my separate files. Then I include these files (but all engine files stay not modified, so only original declarations are included in engine). Engine is built into static lib and linked with my app. When I call a method of my category the app crashes with error "unrecognized selector sent to instance...". But if I declare category in file with original engine class all works.

Why selector of category is not recognized if it's declared and implemented in separate files? Does order of including files matter?

答: You need to set some flags for the linker... please refer to What does the -all_load linker flag do? for details.</p>

ContentLicense: CC BY-SA 3.0


问:
Python string format x or less digits
Is there a easy one-liner in python 3.x to print a number with x or less decimal places?

I want

```<code>numbers = [7, 7.7, 7.77, 7.777]

for number in numbers:
    print("{:.less than 3}".format(number))
</code>```

to return

```<code>7
7.7
7.77
7.78
</code>```

答:
You can round numbers to desired precision:

```<code>numbers = [7, 7.7, 7.77, 7.777]

for number in numbers:
    print(round(number, 2))

# 7
# 7.7
# 7.77
# 7.78
</code>```

Motivated from @JussiNurminen's answer, you can also do:

```<code>for number in numbers:
    print(f'{number:.3g}')
</code>```

Title: Python string format x or less digits

Body:
Is there a easy one-liner in python 3.x to print a number with x or less decimal places?

I want

numbers = [7, 7.7, 7.77, 7.777]

for number in numbers:
    print("{:.less than 3}".format(number))

to return

7
7.7
7.77
7.78

Body:
You can round numbers to desired precision:

numbers = [7, 7.7, 7.77, 7.777]

for number in numbers:
    print(round(number, 2))

# 7
# 7.7
# 7.77
# 7.78

Motivated from @JussiNurminen's answer, you can also do:

for number in numbers:
    print(f'{number:.3g}')


问:
HazelcastJet kafka throttling
I couldn't find any possibilities to create pipeline in hazelcast-jet-kafka that will limit the throughput to a specific number of elements per time unit, anybody could suggest me possible solutions? I know that alpaka (https://doc.akka.io/docs/alpakka-kafka/current/) has such functionality</p>

答:
You can define this function:

private <T, S extends GeneralStage<T>> FunctionEx<S, S> throttle(int itemsPerSecond) {
    // context for the mapUsingService stage
    class Service {
        final int ratePerSecond;
        final TreeMap<Long, Long> counts = new TreeMap<>();

        public Service(int ratePerSecond) {
            this.ratePerSecond = ratePerSecond;
        }
    }

    // factory for the service
    ServiceFactory<?, Service> serviceFactory = ServiceFactories
            .nonSharedService(procCtx ->
                    // divide the count for the actual number of processors we have
                    new Service(Math.max(1, itemsPerSecond / procCtx.totalParallelism())))
            // non-cooperative is needed because we sleep in the mapping function
            .toNonCooperative();

    return stage -> (S) stage
        .mapUsingService(serviceFactory,
            (ctx, item) -> {
                // current time in 10ths of a second
                long now = System.nanoTime() / 100_000_000;
                // include this item in the counts
                ctx.counts.merge(now, 1L, Long::sum);
                // clear items emitted more than second ago
                ctx.counts.headMap(now - 10, true).clear();
                long countInLastSecond =
                        ctx.counts.values().stream().mapToLong(Long::longValue).sum();
                // if we emitted too many items, sleep a while
                if (countInLastSecond > ctx.ratePerSecond) {
                    Thread.sleep(
                        (countInLastSecond - ctx.ratePerSecond) * 1000/ctx.ratePerSecond);
                }
                // now we can pass the item on
                return item;
            }
        );
}
```

<p>Then use it to throttle in the pipeline:</p>

<pre class="lang-java prettyprint-override"><code>Pipeline p = Pipeline.create();
p.readFrom(TestSources.items(IntStream.range(0, 2_000).boxed().toArray(Integer[]::new)))
 .apply(throttle(100))
 .writeTo(Sinks.noop());
</code>```

The above job will take about 20 seconds to complete because it has 2000 items and the rate is limited to 100 items/s. The rate is evaluated over the last second, so if there are less than 100 items/s, items will be forwarded immediately. If there are 101 items during one millisecond, 100 will be forwarded immediately and the next after a sleep.

Also make sure that your source is distributed. The rate is divided by the number of processors in the cluster and if your source isn't distributed and some members don't see any data, your overall rate will be only a fraction of the desired rate.

Title: HazelcastJet kafka throttling

Body:
You can define this function:

private <T, S extends GeneralStage<T>> FunctionEx<S, S> throttle(int itemsPerSecond) {
    // context for the mapUsingService stage
    class Service {
        final int ratePerSecond;
        final TreeMap<Long, Long> counts = new TreeMap<>();

        public Service(int ratePerSecond) {
            this.ratePerSecond = ratePerSecond;
        }
    }

    // factory for the service
    ServiceFactory<?, Service> serviceFactory = ServiceFactories
            .nonSharedService(procCtx ->
                    // divide the count for the actual number of processors we have
                    new Service(Math.max(1, itemsPerSecond / procCtx.totalParallelism())))
            // non-cooperative is needed because we sleep in the mapping function
            .toNonCooperative();

    return stage -> (S) stage
        .mapUsingService(serviceFactory,
            (ctx, item) -> {
                // current time in 10ths of a second
                long now = System.nanoTime() / 100_000_000;
                // include this item in the counts
                ctx.counts.merge(now, 1L, Long::sum);
                // clear items emitted more than second ago
                ctx.counts.headMap(now - 10, true).clear();
                long countInLastSecond =
                        ctx.counts.values().stream().mapToLong(Long::longValue).sum();
                // if we emitted too many items, sleep a while
                if (countInLastSecond > ctx.ratePerSecond) {
                    Thread.sleep(
                        (countInLastSecond - ctx.ratePerSecond) * 1000/ctx.ratePerSecond);
                }
                // now we can pass the item on
                return item;
            }
        );
}

Then use it to throttle in the pipeline:

Pipeline p = Pipeline.create();
p.readFrom(TestSources.items(IntStream.range(0, 2_000).boxed().toArray(Integer[]::new)))
 .apply(throttle(100))
 .writeTo(Sinks.noop());

The above job will take about 20 seconds to complete because it has 2000 items and the rate is limited to 100 items/s. The rate is evaluated over the last second, so if there are less than 100 items/s, items will be forwarded immediately. If there are 101 items during one millisecond, 100 will be forwarded immediately and the next after a sleep.

Also make sure that your source is distributed. The rate is divided by the number of processors in the cluster and if your source isn't distributed and some members don't see any data, your overall rate will be only a fraction of the desired rate.


问:
How to update user inputted data into JSON
Using javascript, how would I go about creating a function that allows users to edit/update their user profile page (html) that is rendered from the Json file? The user first inputs their data into a page that requests the user response (js file in a routes folder) and then the Json file is rendered under profile html page through another js route.   </p>

```<code>    var data = require("../data.json");

    exports.addUser = function(request, response) {
        console.log(data);
        var name = request.query.name;
        var gender = request.query.gender;
        var height = request.query.height;
        var weight = request.query.weight;
        var newUser = {"name": name, "gender": gender, "height": height, "weight": weight};
        data.users.push(newUser);
        response.render('home');
    }

    // Get all of our user data
    var data = require('../data.json');

    exports.view = function(request, response){
        console.log(data);
        response.render('profile', data);
    };
</code>```

<p>My question is how would I create a function that allow users to make changes to their profile if they have already saved their information once? My app is about the gym with progress as one of the main focus. The user's first inputted information such as weight will not be the same as they progress through the gym, so I want to enable users to edit that information as they progress.   </p>

答:
You would probably want to add an edit user page and find the existing user from the data.users array then edit their information. You could use something similar to the function below.

```<code>exports.editUser = function(request, response) {
    var name = request.query.name;
    var gender = request.query.gender;
    var height = request.query.height;
    var weight = request.query.weight;

    editDetails(data.users[findUser(name, data.users)]);
    response.render('home');

    function editDetails(array_index){
        data.users[array_index].name = name;
        data.users[array_index].gender = gender;
        data.users[array_index].height = height;
        data.users[array_index].weight = weight;
    }

    function findUser(name, array){
        for (let i = 0; i < array.length; i++) {
            if (array[i].name === name) {
                return i;
            }
        }
    }
}
</code>```

The problem with this function would be if two names are the same, then it would edit the first instance of the name. You could add an unique id to make sure that the entry edited is exactly what was intended.

Body:
Using javascript, how would I go about creating a function that allows users to edit/update their user profile page (html) that is rendered from the Json file? The user first inputs their data into a page that requests the user response (js file in a routes folder) and then the Json file is rendered under profile html page through another js route.

    var data = require("../data.json");

    exports.addUser = function(request, response) {
        console.log(data);
        var name = request.query.name;
        var gender = request.query.gender;
        var height = request.query.height;
        var weight = request.query.weight;
        var newUser = {"name": name, "gender": gender, "height": height, "weight": weight};
        data.users.push(newUser);
        response.render('home');
    }

    // Get all of our user data
    var data = require('../data.json');

    exports.view = function(request, response){
        console.log(data);
        response.render('profile', data);
    };

My question is how would I create a function that allow users to make changes to their profile if they have already saved their information once? My app is about the gym with progress as one of the main focus. The user's first inputted information such as weight will not be the same as they progress through the gym, so I want to enable users to edit that information as they progress.

Body:
You would probably want to add an edit user page and find the existing user from the data.users array then edit their information. You could use something similar to the function below.

exports.editUser = function(request, response) {
    var name = request.query.name;
    var gender = request.query.gender;
    var height = request.query.height;
    var weight = request.query.weight;

    editDetails(data.users[findUser(name, data.users)]);
    response.render('home');

    function editDetails(array_index){
        data.users[array_index].name = name;
        data.users[array_index].gender = gender;
        data.users[array_index].height = height;
        data.users[array_index].weight = weight;
    }

    function findUser(name, array){
        for (let i = 0; i < array.length; i++) {
            if (array[i].name === name) {
                return i;
            }
        }
    }
}

The problem with this function would be if two names are the same, then it would edit the first instance of the name. You could add an unique id to make sure that the entry edited is exactly what was intended.


问:
Weblogic t3/t3s over ssh tunnel
I'm having trouble connecting to a weblogic server behind a firewall.

I can connect to the AdminServer using ssh tunnels, I can telnet into the adress and ports and right now it's accessible at https://127.0.0.1:25141/console/ or http://127.0.0.1:25101/console/.

Unfortunately I cannot connect to it ussing a WLST script.

```<code>if __name__ == '__main__':
   from wlstModule import *

username = 'weblogic'
password = 'justsomepassword'
URL='t3s://127.0.0.1:25141'
connect(username,password,URL)
</code>```

The error shown is:

WLSTException: Error occurred while performing connect : Cannot connect via t3s or https. If using demo certs, verify that the -Dweblogic.security.TrustKeyStore=DemoTrust system property is set. : t3s://127.0.0.1:25141: Destination 127.0.0.1, 25141 unreachable; nested exception is:
      javax.net.ssl.SSLException: Received fatal alert: handshake_failure; No available router to destination

Using t3 the exception is:

WLSTException: Error occurred while performing connect : Error getting the initial context. There is no server running at t3://127.0.0.1:25101 : t3://127.0.0.1:25101: Bootstrap to: 127.0.0.1/127.0.0.1:25101' over: 't3' got an error or timed out while trying to connect to 127.0.0.1/127.0.0.1:25101

I've had this kind of problem in the past trying to connect any remote server to JDeveloper so I guess I'm missing some port forwarding. Is there any extra thing that i need to do in order to connect to a WLS behind firewalls?

答:
Add this to the WebLogic startup scripts to allow T3 SSH tunnelling:</p>

```<code>JAVA_OPTIONS="-Dweblogic.rjvm.enableprotocolswitch=true -Djava.net.preferIPv4Stack=true ${JAVA_OPTIONS}"
export JAVA_OPTIONS
</code>```

Title: Weblogic t3/t3s over ssh tunnel

Body:
I'm having trouble connecting to a weblogic server behind a firewall.

I can connect to the AdminServer using ssh tunnels, I can telnet into the adress and ports and right now it's accessible at https://127.0.0.1:25141/console/ or http://127.0.0.1:25101/console/.

Unfortunately I cannot connect to it ussing a WLST script.

if __name__ == '__main__':
   from wlstModule import *

username = 'weblogic'
password = 'justsomepassword'
URL='t3s://127.0.0.1:25141'
connect(username,password,URL)

The error shown is:

WLSTException: Error occurred while performing connect : Cannot connect via t3s or https. If using demo certs, verify that the -Dweblogic.security.TrustKeyStore=DemoTrust system property is set. : t3s://127.0.0.1:25141: Destination 127.0.0.1, 25141 unreachable; nested exception is:
      javax.net.ssl.SSLException: Received fatal alert: handshake_failure; No available router to destination

Using t3 the exception is:

WLSTException: Error occurred while performing connect : Error getting the initial context. There is no server running at t3://127.0.0.1:25101 : t3://127.0.0.1:25101: Bootstrap to: 127.0.0.1/127.0.0.1:25101' over: 't3' got an error or timed out while trying to connect to 127.0.0.1/127.0.0.1:25101

I've had this kind of problem in the past trying to connect any remote server to JDeveloper so I guess I'm missing some port forwarding. Is there any extra thing that i need to do in order to connect to a WLS behind firewalls?

Body:
Add this to the WebLogic startup scripts to allow T3 SSH tunnelling:

JAVA_OPTIONS="-Dweblogic.rjvm.enableprotocolswitch=true -Djava.net.preferIPv4Stack=true ${JAVA_OPTIONS}"
export JAVA_OPTIONS


问:
Oracle UCM RIDC service get folder path using GET_SEARCH_RESULTS
I am using GET_SEARCH_RESULTS ridc calls to perform file search. I need to get folder information of that file being retrieved with result. Tried DOC_INFO also but I didn't get folder name / path information

答:
Answering with the assumption that you are using FrameworkFolders:

The DOC_INFO service will give you the path to the containing folder. It is in the local property fParentPath. If it isn't there, something is wrong.


问:
Laravel not showing image in view
I have stored the path of the user image profile in a database field, when i try to displayed in a view it doesn´t show anything I tried doing this

```<code>@foreach($user as $users)
<img src="{{$users->fotografia}}"  class="user-image" alt="User Image">
@endforeach
</code>```

and in the view shows me the url from the image instead of the image  \10.56.5.92\Fotos_Empleados\10044.jpg

the image is stored in a server image do I need to do a symbolic Link? and If so what would be the right code because the image aren´t stored in folder public or anything like it

答:
Hey, Try this take a look at the examples:

```<code>echo public_path();
// C:\Users\XYZ\laravel\public
</code>```

In Your Case try this

```<code>public_path()."/"."YourDirectoryNameIfExist/{{$users->fotografia}}"
</code>```

VS

```<code>echo url('/');
// http://localhost/laravel/public
</code>```

Title: Laravel not showing image in view

Body:
I have stored the path of the user image profile in a database field, when i try to displayed in a view it doesn´t show anything I tried doing this

@foreach($user as $users)
fotografia}}"  class="user-image" alt="User Image">
@endforeach

and in the view shows me the url from the image instead of the image  \10.56.5.92\Fotos_Empleados\10044.jpg

the image is stored in a server image do I need to do a symbolic Link? and If so what would be the right code because the image aren´t stored in folder public or anything like it

Body:
Hey, Try this take a look at the examples:

echo public_path();
// C:\Users\XYZ\laravel\public

In Your Case try this

public_path()."/"."YourDirectoryNameIfExist/{{$users->fotografia}}"

VS

echo url('/');
// http://localhost/laravel/public


问:
Split a string only the at the first n occurrences of a delimiter
I'd like to split a string only the at the first n occurrences of a delimiter. I know, I could add them together using a loop, but isn't there a more straight forward approach?</p>

```<code>var string = 'Split this, but not this';
var result = new Array('Split', 'this,', 'but not this');
</code>```

答:
In my case this solves my problem:</p>

```<code>const splitted = path.split('/')
const core = splittedPath.slice(0, 2)
const rest = splittedPath.slice(2).join('/')
const result = [...core, rest]
</code>```

Body:
I'd like to split a string only the at the first n occurrences of a delimiter. I know, I could add them together using a loop, but isn't there a more straight forward approach?

var string = 'Split this, but not this';
var result = new Array('Split', 'this,', 'but not this');

Body:
In my case this solves my problem:

const splitted = path.split('/')
const core = splittedPath.slice(0, 2)
const rest = splittedPath.slice(2).join('/')
const result = [...core, rest]


问:
Powershell batch of commands response into JSON
I'm trying to capture a list of users and groups on my windows host.
I can capture the user and groups info and assign them to varaibles $users and $groups with the following commands:

```<code>    $groups=$(Get-WmiObject win32_group | Select Name | Sort Name); $users=$(Get-WmiObject -Class Win32_UserAccount | Select Name | Sort Name)
</code>```

What I can't figure out is how to pass these to the ConvertTo-JSON function where they each get their own keys i.e, I'd like the response to look like this:

```<code>{
    "users": ["john", "geroge", "ringo"],
    "groups": ["drums", "guitar"]
}
</code>```

I have tried a few variations of this, but can't quite get the correct syntax for powershell and the ConvertTo-JSON function.

```<code>    $jsonBlob=$(\"groups\" : $(groups), \"users"\ : $(users); ConvertTo-Json $jsonBlob;
</code>```

Any suggestions on how to achieve this?

答:
Create a PSCustomObject and Pipe that to ConvertTo-Json

```<code>$groups = Get-WmiObject -Class Win32_Group | Sort-Object Name
$users = Get-WmiObject -Class Win32_UserAccount | Sort-Object Name
$jsonBlob = [PSCustomObject]@{"users" = $users.Name;"groups" = $groups.Name} | ConvertTo-Json
</code>```

Body:
I'm trying to capture a list of users and groups on my windows host.
I can capture the user and groups info and assign them to varaibles $users and $groups with the following commands:

    $groups=$(Get-WmiObject win32_group | Select Name | Sort Name); $users=$(Get-WmiObject -Class Win32_UserAccount | Select Name | Sort Name)

What I can't figure out is how to pass these to the ConvertTo-JSON function where they each get their own keys i.e, I'd like the response to look like this:

{
    "users": ["john", "geroge", "ringo"],
    "groups": ["drums", "guitar"]
}

I have tried a few variations of this, but can't quite get the correct syntax for powershell and the ConvertTo-JSON function.

    $jsonBlob=$(\"groups\" : $(groups), \"users"\ : $(users); ConvertTo-Json $jsonBlob;

Any suggestions on how to achieve this?

Body:
Create a PSCustomObject and Pipe that to ConvertTo-Json

$groups = Get-WmiObject -Class Win32_Group | Sort-Object Name
$users = Get-WmiObject -Class Win32_UserAccount | Sort-Object Name
$jsonBlob = [PSCustomObject]@{"users" = $users.Name;"groups" = $groups.Name} | ConvertTo-Json


问:
Angular: Cannot read property 'call' of undefined (when bootstrapping)
Check the update on the bottom!

I have a service that throws an error while the app is bootstrapping. Cannot read property 'call' of undefined. I'm using ng2 2.4.2 and angular-cli 1.0.0-beta.24.

ERROR

Uncaught TypeError: Cannot read property 'call' of undefined at webpack_require (bootstrap 81b10f8…:52) at Object.621 (environment.ts:8) at webpack_require (bootstrap 81b10f8…:52) at Object.450 (src async:7) at webpack_require (bootstrap 81b10f8…:52) at Object.1057 (util.service.ts:35) at webpack_require (bootstrap 81b10f8…:52) at webpackJsonpCallback (bootstrap 81b10f8…:23) at main.bundle.js:1

As you can see it's a problem with the util service - this looks as follows:

```<code>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Project } from '../datatypes/';
import { Response } from '@angular/http';

@Injectable()
export class UtilService {
    constructor(private router: Router) {}

    public redirectToProject(project: Project) {
        let query = project.ProjectName.split(' ')
            .join('-')
            .concat('-' + project.Id)
            .toLowerCase();
        this.router.navigate(['/project', query]);
    }

    public extractData(res: Response) {
        let body = res.json();
        return body || {};
    }
}
</code>```

Strange: When inspecting the source file in chrome it has no syntax highlighting, which would suggest a syntax error - in my opinion there's none though.

Update January 20. 2017

I updated to ng2.4.4 and angular-cli 1.0.0-beta26. The problem is still the same.
While playing around, Arjan found out that it works with beta 21. Will have to check the changes. The problem now isn't in the service above but in the environment.ts file (which has all the defaults).

答: Changing the port for some reason solved this for me ng serve --port 4300

Body:
Check the update on the bottom!

I have a service that throws an error while the app is bootstrapping. Cannot read property 'call' of undefined. I'm using ng2 2.4.2 and angular-cli 1.0.0-beta.24.

ERROR

Uncaught TypeError: Cannot read property 'call' of undefined at webpack_require (bootstrap 81b10f8…:52) at Object.621 (environment.ts:8) at webpack_require (bootstrap 81b10f8…:52) at Object.450 (src async:7) at webpack_require (bootstrap 81b10f8…:52) at Object.1057 (util.service.ts:35) at webpack_require (bootstrap 81b10f8…:52) at webpackJsonpCallback (bootstrap 81b10f8…:23) at main.bundle.js:1

As you can see it's a problem with the util service - this looks as follows:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Project } from '../datatypes/';
import { Response } from '@angular/http';

@Injectable()
export class UtilService {
    constructor(private router: Router) {}

    public redirectToProject(project: Project) {
        let query = project.ProjectName.split(' ')
            .join('-')
            .concat('-' + project.Id)
            .toLowerCase();
        this.router.navigate(['/project', query]);
    }

    public extractData(res: Response) {
        let body = res.json();
        return body || {};
    }
}

Strange: When inspecting the source file in chrome it has no syntax highlighting, which would suggest a syntax error - in my opinion there's none though.

Update January 20. 2017

I updated to ng2.4.4 and angular-cli 1.0.0-beta26. The problem is still the same.
While playing around, Arjan found out that it works with beta 21. Will have to check the changes. The problem now isn't in the service above but in the environment.ts file (which has all the defaults).


问:
how to fix this ConnectionRefusedError?
when i execute this code it shows ConnectionRefusedError: [WinError 10061] No connection could be made because the
 target machine actively refused it</p>

```<code>import os
import smtplib
from flask import *
from flask_mail import *

app = Flask(__name__)
mail = Mail(app)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT']=465
app.config['MAIL_USERNAME'] = os.environ.get('User'  )
app.config['MAIL_PASSWORD'] = os.environ.get('Password' )
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = True

@app.route('/')
def index():
    msg = Message('HEllo',sender=["joyciimmaculate@gmail.com"], recipients = ["joyciimmaculate@gmail.com"])
    msg.body = "hi bulk sms"
    msg.html ="<img src="/static/deepa.jpg" style='width:500px;height:228px;'>"
    mail.send(msg)
    return "mail sent"```

</code>```

答:
Based on the description of the error, this is not a problem with your Python code, but rather that the network connection to smtp.gmail.com is being blocked/rejected (possibly by a firewall or some other network issue).

Note that if you are running this on a home machine, most ISPs will actively block outbound SMTP connections to anything except the ISP's own SMTP servers (some hosting providers also do the same), to prevent spammers from exploiting the service.  You may need to change your settings to use your ISP's outbound mail host instead of connecting directly to smtp.gmail.com.

Title: how to fix this ConnectionRefusedError?

Body:
when i execute this code it shows ConnectionRefusedError: [WinError 10061] No connection could be made because the
 target machine actively refused it

import os
import smtplib
from flask import *
from flask_mail import *

app = Flask(__name__)
mail = Mail(app)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT']=465
app.config['MAIL_USERNAME'] = os.environ.get('User'  )
app.config['MAIL_PASSWORD'] = os.environ.get('Password' )
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = True

@app.route('/')
def index():
    msg = Message('HEllo',sender=["joyciimmaculate@gmail.com"], recipients = ["joyciimmaculate@gmail.com"])
    msg.body = "hi bulk sms"
    msg.html =""
    mail.send(msg)
    return "mail sent"```


问:
How to navigate to other screen in flutter web
I have created a simple code practise flutter web.

I have been trying to navigate between two screen in flutter web. But one i click the button in first screen and navigate to second screen, the second screen is show blank with debug flag at the top right. Once i refresh the second screen data is coming.

How to resolve this issue?

Here is the code

```<code>import 'package:temp/providers/Increment_provider.dart';
import 'package:temp/screens/Detail_screen.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<IncrementProvider>(
      create: (btx) => IncrementProvider(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(

          primarySwatch: Colors.blue,
        ),
        initialRoute: '/',
        routes: {

          DetailScreen.routeName: (ctx) => DetailScreen(),},
        home: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counter = Provider.of<IncrementProvider>(context, listen: false);

    return Scaffold(
      appBar: AppBar(

        title: Text('Main Screen'),
      ),
      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Consumer<IncrementProvider>(builder: (ctx,counter,ch)=>Text(
                '${counter.count}',
                style: Theme.of(context).textTheme.headline4,
              ),

            ),
            FloatingActionButton(
              onPressed: () {
                Navigator.pushNamed(context,DetailScreen.routeName);
              },
              tooltip: 'Press the button',
              child: Icon(Icons.view_agenda),
            ),
          ],
        ),
      ),

      floatingActionButton: FloatingActionButton(
        onPressed: () => counter.incrementor(),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:temp/providers/Increment_provider.dart';

class DetailScreen extends StatelessWidget {
  static const routeName='/Detail_screen';
  @override
  Widget build(BuildContext context) {
    final counter=Provider.of<IncrementProvider>(context);
    return Scaffold(

      body: Center(child:Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('The incremented value is ${counter.count}'),

        ],

      ),),

    );

  }

}

import 'package:flutter/material.dart';

class IncrementProvider with ChangeNotifier{
 int _count=0;

int get count=> _count;

void incrementor (){
  _count+=1;

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

答:
Change your Navigator for:

```<code>Navigator.of(context).pushNamed(DetailScreen.routeName);
</code>```

and your DetailScreen don't need the column as the Center Widget is doing your logic.

Also, with this kind of "weird" behavior, is always good to post here your flutter doctor -v so we can tell if you're using a different version of Flutter, if plugins are up to date, etc.

Also, I'll recommend to fist delete your provider from your DetailScreen to see if that affects the behavior. I tried your code without your Provider class and works using iOS emulator. Plus, to double check, force TextStyle color over your text just to be double sure a dark/light theme from your device is not affecting that as well.

Body:
I have created a simple code practise flutter web.

I have been trying to navigate between two screen in flutter web. But one i click the button in first screen and navigate to second screen, the second screen is show blank with debug flag at the top right. Once i refresh the second screen data is coming.

How to resolve this issue?

Here is the code

import 'package:temp/providers/Increment_provider.dart';
import 'package:temp/screens/Detail_screen.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<IncrementProvider>(
      create: (btx) => IncrementProvider(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(

          primarySwatch: Colors.blue,
        ),
        initialRoute: '/',
        routes: {

          DetailScreen.routeName: (ctx) => DetailScreen(),},
        home: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counter = Provider.of<IncrementProvider>(context, listen: false);

    return Scaffold(
      appBar: AppBar(

        title: Text('Main Screen'),
      ),
      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Consumer<IncrementProvider>(builder: (ctx,counter,ch)=>Text(
                '${counter.count}',
                style: Theme.of(context).textTheme.headline4,
              ),

            ),
            FloatingActionButton(
              onPressed: () {
                Navigator.pushNamed(context,DetailScreen.routeName);
              },
              tooltip: 'Press the button',
              child: Icon(Icons.view_agenda),
            ),
          ],
        ),
      ),

      floatingActionButton: FloatingActionButton(
        onPressed: () => counter.incrementor(),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:temp/providers/Increment_provider.dart';

class DetailScreen extends StatelessWidget {
  static const routeName='/Detail_screen';
  @override
  Widget build(BuildContext context) {
    final counter=Provider.of<IncrementProvider>(context);
    return Scaffold(

      body: Center(child:Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('The incremented value is ${counter.count}'),

        ],

      ),),

    );

  }

}

import 'package:flutter/material.dart';

class IncrementProvider with ChangeNotifier{
 int _count=0;

int get count=> _count;

void incrementor (){
  _count+=1;

  notifyListeners();
}
}

Body:
Change your Navigator for:

Navigator.of(context).pushNamed(DetailScreen.routeName);

and your DetailScreen don't need the column as the Center Widget is doing your logic.

Also, with this kind of "weird" behavior, is always good to post here your flutter doctor -v so we can tell if you're using a different version of Flutter, if plugins are up to date, etc.

Also, I'll recommend to fist delete your provider from your DetailScreen to see if that affects the behavior. I tried your code without your Provider class and works using iOS emulator. Plus, to double check, force TextStyle color over your text just to be double sure a dark/light theme from your device is not affecting that as well.


问:
std::enable_shared_from_this ... Does a new shared_ptr know to take shared_from_this()?
I have a class that derives from enable_shared_from_this ... (Recently been added to std from Boost)

```<code>class Blah : public std::enable_shared_from_this<Blah>
{

};
</code>```

I know I should create shared pointers from an instance like this:

```<code>Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this());
</code>```

Question is, will it take the object's weak_ptr implicitly if I do something like this:

```<code>std::shared_ptr<Blah> bad(new Blah());
</code>```

Or will it just create a seperate shared pointer counter ? (which i suspect)

答:
```<code>Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this()); // bad, *b is not yet owned
</code>```

This is incorrect. For shared_from_this to work, b must already be owned by at least one shared_ptr. You must use:

```<code>std::shared_ptr<Blah> b = new B();
Blah* raw = b.get();
std::shared_ptr<Blah> good(raw->shared_from_this()); // OK because *raw is owned
</code>```

Of course, in this trivial example it is easier to use:

```<code>std::shared_ptr<Blah> good(b);
</code>```

There is nothing intrinsically wrong with:

```<code>std::shared_ptr<Blah> bad(new Blah());
</code>```

Because new B() creates a new B there can be no other separate shared pointer count in existence for the newly created B object.

Body:
I have a class that derives from enable_shared_from_this ... (Recently been added to std from Boost)

class Blah : public std::enable_shared_from_this<Blah>
{

};

I know I should create shared pointers from an instance like this:

Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this());

Question is, will it take the object's weak_ptr implicitly if I do something like this:

std::shared_ptr<Blah> bad(new Blah());

Or will it just create a seperate shared pointer counter ? (which i suspect)

Body:
Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this()); // bad, *b is not yet owned

This is incorrect. For shared_from_this to work, b must already be owned by at least one shared_ptr. You must use:

std::shared_ptr<Blah> b = new B();
Blah* raw = b.get();
std::shared_ptr<Blah> good(raw->shared_from_this()); // OK because *raw is owned

Of course, in this trivial example it is easier to use:

std::shared_ptr<Blah> good(b);

There is nothing intrinsically wrong with:

std::shared_ptr<Blah> bad(new Blah());

Because new B() creates a new B there can be no other separate shared pointer count in existence for the newly created B object.


问:
target first letter of each word in css
I need to change size, color, and weight of every first letter of each word. I am not talking about Capitalize each first letter. I mean that target first letter and apply style according to my choice.
: Click Here to see example about which i am talking.</p>

答:
You should wrap every single word with a tag and use ::first-letter CSS selector .

Also, note that this selector does not work on inline elements. If you want to use it with an inline element, such a , make sure you set display:inline-block (see here for more details: https://stackoverflow.com/a/7631782/11298742)

example :

p span { display: inline-block; font-family: 'Roboto', sans-serif }
p span::first-letter {
    color: red;
    font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet</span></p></code>```

Title: target first letter of each word in css

Body:
You should wrap every single word with a tag and use ::first-letter CSS selector .

Also, note that this selector does not work on inline elements. If you want to use it with an inline element, such a <span>, make sure you set display:inline-block (see here for more details: https://stackoverflow.com/a/7631782/11298742)

example :

p span { display: inline-block; font-family: 'Roboto', sans-serif }
p span::first-letter {
    color: red;
    font-weight: bold;
}

<p><span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet</span></p>


问:
Optimizing Script Pulling Data From Multiple Google Sheets
I want a script to search multiple Google Sheets files and pull specific information from each file to create a master status page that my boss can easily see.  The following code works, it's just really slow (and I'm probably not doing it the easiest way).  What's the best way to speed it up? I'm sure there's some way to set up an array, but I'm lost trying to find it.</p>

```<code>  var ss = SpreadsheetApp.getActive()
  var folder = DriveApp.getFolderById()

// Sets up the rules for what to search
  var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS)
  while (files.hasNext()) {
    var file = files.next()
    var filelog = file.getId()
    var tickets = SpreadsheetApp.openById(file.getId())

//Gets Values from Each File
    var ticketno = tickets.getRange('Form!C1').getValue()
    var jobname = tickets.getRange('Form!C3').getValue()
    var status = tickets.getRange('Form!H1').getValue()
    var assigned = tickets.getRange('Form!C22').getValue()
    var description = tickets.getRange('Form!A18').getValue()

//Sets Values to Master Spreadsheet
    var ssh = ss.getSheetByName("Order Status")
    ssh.insertRowAfter(1)
    ss.getRange('Order Status!A2').setValue(ticketno)
    ss.getRange('Order Status!B2').setValue(jobname)
    ss.getRange('Order Status!C2').setValue(status)
    ss.getRange('Order Status!D2').setValue(assigned)
    ss.getRange('Order Status!E2').setValue(description)
</code>```

答:
I looped the scripts 50 times. Runtime of your script was 259,342 seconds, runtime of 'mine' 83,479 seconds</p>

```<code>function notAsSlow(){

var ss = SpreadsheetApp.getActive()
  var folder = DriveApp.getFolderById("1fgROgjHBssvhaSIy5KWv0BhNFlH3EfTI")

  var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS)

  var array=[];

    while (files.hasNext()) {

      var file = files.next()
      var filelog = file.getId()
      var tickets = SpreadsheetApp.openById(file.getId())

      var dataTickets = tickets.getSheetByName("Form").getDataRange().getValues();

      var ticketno = dataTickets[0][2];
      var jobname = dataTickets[2][2];
      var status = dataTickets[7][0];
      var assigned = dataTickets[21][2];
      var description = dataTickets[17][0];

      array.push([ticketno,jobname,status,assigned,description]);

    }

    var ssh = ss.getSheetByName("Order Status");

    if(array[0]){
      ssh.getRange(ssh.getLastRow()+1,1,array.length,5).setValues(array);

    }

}
</code>```

Body:
I want a script to search multiple Google Sheets files and pull specific information from each file to create a master status page that my boss can easily see.  The following code works, it's just really slow (and I'm probably not doing it the easiest way).  What's the best way to speed it up? I'm sure there's some way to set up an array, but I'm lost trying to find it.

  var ss = SpreadsheetApp.getActive()
  var folder = DriveApp.getFolderById()

// Sets up the rules for what to search
  var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS)
  while (files.hasNext()) {
    var file = files.next()
    var filelog = file.getId()
    var tickets = SpreadsheetApp.openById(file.getId())

//Gets Values from Each File
    var ticketno = tickets.getRange('Form!C1').getValue()
    var jobname = tickets.getRange('Form!C3').getValue()
    var status = tickets.getRange('Form!H1').getValue()
    var assigned = tickets.getRange('Form!C22').getValue()
    var description = tickets.getRange('Form!A18').getValue()

//Sets Values to Master Spreadsheet
    var ssh = ss.getSheetByName("Order Status")
    ssh.insertRowAfter(1)
    ss.getRange('Order Status!A2').setValue(ticketno)
    ss.getRange('Order Status!B2').setValue(jobname)
    ss.getRange('Order Status!C2').setValue(status)
    ss.getRange('Order Status!D2').setValue(assigned)
    ss.getRange('Order Status!E2').setValue(description)

Body:
I looped the scripts 50 times. Runtime of your script was 259,342 seconds, runtime of 'mine' 83,479 seconds

function notAsSlow(){

var ss = SpreadsheetApp.getActive()
  var folder = DriveApp.getFolderById("1fgROgjHBssvhaSIy5KWv0BhNFlH3EfTI")

  var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS)

  var array=[];

    while (files.hasNext()) {

      var file = files.next()
      var filelog = file.getId()
      var tickets = SpreadsheetApp.openById(file.getId())

      var dataTickets = tickets.getSheetByName("Form").getDataRange().getValues();

      var ticketno = dataTickets[0][2];
      var jobname = dataTickets[2][2];
      var status = dataTickets[7][0];
      var assigned = dataTickets[21][2];
      var description = dataTickets[17][0];

      array.push([ticketno,jobname,status,assigned,description]);

    }

    var ssh = ss.getSheetByName("Order Status");

    if(array[0]){
      ssh.getRange(ssh.getLastRow()+1,1,array.length,5).setValues(array);

    }

}


问:
Removing partial duplicate rows (duplicate data in only two columns) from Microsoft SQL Server 2012 table
I have a table of around 7000 rows, a small sample of which is below:

```<code>ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
781        3                   998           896                 4                       1
2098       3                   998           3191                4                       66
3808       4                   998           3191                4                       6555
780        3                   997           2402                4                       34234
3807       4                   997           2061                4                       234
2097       3                   997           2061                4                       6756
</code>```

You will notice that for each Entity_ID, there are multiple rows. For each Entity_ID, there are two or more different Entity_CLASS_IDs.

You can see that in some circumstances two of the rows for each Entity_ID match on ORGANISATION_ID too, but have different Entity_Class_IDs:

```<code>ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
2098       3                   998           3191                4                       66
3808       4                   998           3191                4                       6555
</code>```

Where this is the case i would like to delete the row with the entity class ID = 3.

The resulting tidied up table should be:

```<code>ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
781        3                   998           896                 4                       1
3808       4                   998           3191                4                       6555
780        3                   997           2402                4                       34234
3807       4                   997           2061                4                       234
</code>```

Hopefully I've explained that clearly!?

I've tried to work this out in code myself, but the mix of partial matches is stopping me from getting anywhere near a solution!

Thanks in advance for any help with this.

答:
You can also do this using exists:

```<code>delete from t
where t.Entity_CLASS_ID = 3 and
      exists (select 1
              from t t2
              where t2.Entity_ID = t.Entity_ID and
                    t2.ORGANISATION_ID = t.ORGANISATION_ID and
                    t2.Entity_CLASS_ID <> 3
             );
</code>```

This seems like almost a direct translation of your phrasing of the question.

Body:
I have a table of around 7000 rows, a small sample of which is below:

ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
781        3                   998           896                 4                       1
2098       3                   998           3191                4                       66
3808       4                   998           3191                4                       6555
780        3                   997           2402                4                       34234
3807       4                   997           2061                4                       234
2097       3                   997           2061                4                       6756

You will notice that for each Entity_ID, there are multiple rows. For each Entity_ID, there are two or more different Entity_CLASS_IDs.

You can see that in some circumstances two of the rows for each Entity_ID match on ORGANISATION_ID too, but have different Entity_Class_IDs:

ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
2098       3                   998           3191                4                       66
3808       4                   998           3191                4                       6555

Where this is the case i would like to delete the row with the entity class ID = 3.

The resulting tidied up table should be:

ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
781        3                   998           896                 4                       1
3808       4                   998           3191                4                       6555
780        3                   997           2402                4                       34234
3807       4                   997           2061                4                       234

Hopefully I've explained that clearly!?

I've tried to work this out in code myself, but the mix of partial matches is stopping me from getting anywhere near a solution!

Thanks in advance for any help with this.

Body:
You can also do this using exists:

delete from t
where t.Entity_CLASS_ID = 3 and
      exists (select 1
              from t t2
              where t2.Entity_ID = t.Entity_ID and
                    t2.ORGANISATION_ID = t.ORGANISATION_ID and
                    t2.Entity_CLASS_ID <> 3
             );

This seems like almost a direct translation of your phrasing of the question.


问:
Filter RavenDB query by entries of list
I am working with the python client for ravendb

My goal is to select unique Types and their TypeCount in a certain range of DateTime

Currently I have the following Map and Reduce:

and this gives me the following results:

Now I want to be able to select this in a certain DateTime range. For example, if we only take the BTE type into account, if I would say something along the lines of where Dates > "2020-02-09", I'd want to get the following results:
Type = BTE, TypeCount = 2, Dates = ["2020-02-09T00:50:07.0000890", "2020-02-09T00:59:41.0000210"

答:
You can achieve this by removing the Reduce part of the index and change Dates to Date = pds.DateTime, then you can query the index like this:

```<code>var queryResult = session.Query<Index.Result, Index>()
                        .Where(x => x.Type == "BTE" && x.Date > new DateTime(2020, 2, 9))
                        .ToList();
</code>```

Title: Filter RavenDB query by entries of list

Body:
You can achieve this by removing the Reduce part of the index and change Dates to Date = pds.DateTime, then you can query the index like this:

var queryResult = session.Query<Index.Result, Index>()
                        .Where(x => x.Type == "BTE" && x.Date > new DateTime(2020, 2, 9))
                        .ToList();


问:
How to load JSON data based on selected value
I am new to this and I dont know what I am doing wrong.

In my json file I have several lines but I only need to log the requested

```<code><a href="#" id="get-data" data-id="100" data-foo="100">Get JSON data</a>

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

  <script>

      $('#get-data').click(function () {

          var myDiv = document.querySelector('#get-data');

          var mySetValue = myDiv.dataset.foo

          console.log (mySetValue)
          var showData = $('#show-data');
          var url = 'example.json';
          var data = {
              value: mySetValue
          };
          $.getJSON(url, data)
            console.log(data);
      });

  </script>
</code>```

and this is my json file

```<code>[
{
  "key": "First",
  "value": 100
},{
  "key": "Second",
  "value": false
},{
  "key": "Last",
  "value": "Mixed"
},
  {
  "key": "First",
  "value": 100
},{
  "key": "Last",
  "value": "Mixed"
},
  {
  "key": "First",
  "value": 100
},{
  "key": "Second",
  "value": false
},{
  "key": "Last",
  "value": "Mixed"
}]
</code>```

I need to load only the data associated with the data-foo of my button but instead, i only get one value in return.

What am I doing wrong?

Thank you in advance

答:
I noticed that you are using Jquery as an API, within Jquery there is a function for ajax that you can be using that helps to bring information from an ajax file/response.

Read more about in W3S Jquery Ajax

Your code will result in something like this.

```<code>$.ajax({

    url: '/file.json',
    success: function(data){

        console.log(data);

    }
});
</code>```

Possible problems that can happen

If you are not running this on a PHP server or have "Crossdomain" permission, HTML / PHP will not give you permission to open the "external file"

Ajax is an asynchronous function, this means that if you assign an X value inside, it will only assign the value when the external structure finishes its execution ... In short, it executes what is outside of ajax first and then what is inside, it is possible to solve this with promise and await/async functions

To do an await with a promise you will have to have a "main" function that is an asynchronous function, otherwise this function will not accept the await condition.

Resolving the asynchronous problem.

```<code>async function main(){

    var result = await getAssycFunction();

    console.log(result);

}

function getAssycFunction(){

    return new Promise((result, reject) =>{

        result("Result");

    });

}
</code>```

As you asked me in the comments, to separate the values there is no "magic function", but what can be done is a loop that goes through all the houses and separates in a second array only the ones you want.

```<code>var values = [];

for (var i = 0; i < data.length ; i++) {

    if (data[i]['value'] == 100) {

        values.push(data[i]);
    }

}

result(values);
</code>```

a small note: do not want to hide information from the end user when separating the variables, once you have an Ajax request, the user has access to the ajax file to be able to read.

Body:
I am new to this and I dont know what I am doing wrong.

In my json file I have several lines but I only need to log the requested

Get JSON data

and this is my json file

[
{
  "key": "First",
  "value": 100
},{
  "key": "Second",
  "value": false
},{
  "key": "Last",
  "value": "Mixed"
},
  {
  "key": "First",
  "value": 100
},{
  "key": "Last",
  "value": "Mixed"
},
  {
  "key": "First",
  "value": 100
},{
  "key": "Second",
  "value": false
},{
  "key": "Last",
  "value": "Mixed"
}]

I need to load only the data associated with the data-foo of my button but instead, i only get one value in return.

What am I doing wrong?

Thank you in advance

Body:
I noticed that you are using Jquery as an API, within Jquery there is a function for ajax that you can be using that helps to bring information from an ajax file/response.

Read more about in W3S Jquery Ajax

Your code will result in something like this.

$.ajax({

    url: '/file.json',
    success: function(data){

        console.log(data);

    }
});

Possible problems that can happen

If you are not running this on a PHP server or have "Crossdomain" permission, HTML / PHP will not give you permission to open the "external file"

Ajax is an asynchronous function, this means that if you assign an X value inside, it will only assign the value when the external structure finishes its execution ... In short, it executes what is outside of ajax first and then what is inside, it is possible to solve this with promise and await/async functions

To do an await with a promise you will have to have a "main" function that is an asynchronous function, otherwise this function will not accept the await condition.

Resolving the asynchronous problem.

async function main(){

    var result = await getAssycFunction();

    console.log(result);

}

function getAssycFunction(){

    return new Promise((result, reject) =>{

        result("Result");

    });

}

As you asked me in the comments, to separate the values there is no "magic function", but what can be done is a loop that goes through all the houses and separates in a second array only the ones you want.

var values = [];

for (var i = 0; i < data.length ; i++) {

    if (data[i]['value'] == 100) {

        values.push(data[i]);
    }

}

result(values);

a small note: do not want to hide information from the end user when separating the variables, once you have an Ajax request, the user has access to the ajax file to be able to read.


问:
SPFx: Add a new item to existing List Folder (using pnp)
Does anyone know how to add a new item to a List Folder in Sharepoint Framework?

In this way I can add the item to the list MyList:

```<code>let list = pnp.sp.web.lists.getByTitle("MyList");

list.items.add({
      Title: "itemName"
      }).then(r => {

      console.log(r);
})
</code>```

But I need it being created inside the folder MyList\MyFolder.

I have tried retrieving the folder in this way:

var folder= sp.web.lists.getByTitle("MyList").rootFolder.folders.getByName("MyFolder");

but I cannot find a way to add items inside.

答:
It seems that this operation is not implemented with the sp-pnp-js library.

You should be able to do it using a manual fetch request like this:

```<code>const listTitle = "List Title";
const folderTitle = "Folder Title";
const webUrl = _spPageContextInfo.webAbsoluteUrl;
const url = webUrl + "/_vti_bin/ListData.svc/" + listTitle.replace(/\s/g, "");
fetch(url, {
    method: 'POST',
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        Title: "Item Name",
        Path: webUrl + "/Lists/" + listTitle + "/" + folderTitle
    }),
}).then(console.log);
</code>```

Body:
Does anyone know how to add a new item to a List Folder in Sharepoint Framework?

In this way I can add the item to the list MyList:

let list = pnp.sp.web.lists.getByTitle("MyList");

list.items.add({
      Title: "itemName"
      }).then(r => {

      console.log(r);
})

But I need it being created inside the folder MyList\MyFolder.

I have tried retrieving the folder in this way:

var folder= sp.web.lists.getByTitle("MyList").rootFolder.folders.getByName("MyFolder");

but I cannot find a way to add items inside.

Body:
It seems that this operation is not implemented with the sp-pnp-js library.

You should be able to do it using a manual fetch request like this:

const listTitle = "List Title";
const folderTitle = "Folder Title";
const webUrl = _spPageContextInfo.webAbsoluteUrl;
const url = webUrl + "/_vti_bin/ListData.svc/" + listTitle.replace(/\s/g, "");
fetch(url, {
    method: 'POST',
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        Title: "Item Name",
        Path: webUrl + "/Lists/" + listTitle + "/" + folderTitle
    }),
}).then(console.log);


问:
Run commands using the output of one command and using them as input to the next
Based on the values in the second column, I need to run another command on these values.

```<code>[root@box ~]# for i in $(openstack server list --all -c ID -f value); do openstack server show $i -f value -c name -c project_id | xargs printf '%-60s %s\n'; done
cf1-0                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-3                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-2                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-0                                  ebf0f23f424c4417afd3e7bbf4e3900f
</code>```

Here's an example of what I'm trying to do.

```<code>[root@box ~]# for i in $(openstack server list --all -c ID -f value); do openstack server show $i -f value -c name -c project_id | xargs printf "%-60s eval(openstack project show %s -f value -c name)"; done
 cf1-0                                  eval(openstack project show ebf0f23f424c4417afd3e7bbf4e3900f -f value -c name)
</code>```

The substitution from the second %s in printf works correctly, but I can't figure out how to execute the command.

The command needs to be executed in the same shell, and I cannot use environment variables.

Thanks.

** OUTPUT OF COMMANDS **

Here, -c var1 -c var2 can be placed in any order. -f just means print out the values, not the identifier.

```<code>[root@box~]# openstack server list --all -c Name -c ID -f value
2534ce5a-04da-4c7d-9ad5-b7bc466ae612 cf1-0

[root@box ~]# openstack server show 2534ce5a-04da-4c7d-9ad5-b7bc466ae612 -f value -c name -c project_id
cf1-0
ebf0f23f424c4417afd3e7bbf4e3900f

[root@box ~]# openstack project show ebf0f23f424c4417afd3e7bbf4e3900f -f value -c name
core

Desired output
===============
cf1-0 core
</code>```

答:
Not very familiar with the openstack command, but a simple way of doing this in one line would be using awk with system function.

The command should look similar to this:

```<code>openstack server list --all -c ID -f value | awk -F'\t' '{ printf $1; system("eval openstack project show " $2 " -f value -c name") }'
</code>```

Body:
Based on the values in the second column, I need to run another command on these values.

[root@box ~]# for i in $(openstack server list --all -c ID -f value); do openstack server show $i -f value -c name -c project_id | xargs printf '%-60s %s\n'; done
cf1-0                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-3                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-2                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-0                                  ebf0f23f424c4417afd3e7bbf4e3900f

Here's an example of what I'm trying to do.

[root@box ~]# for i in $(openstack server list --all -c ID -f value); do openstack server show $i -f value -c name -c project_id | xargs printf "%-60s eval(openstack project show %s -f value -c name)"; done
 cf1-0                                  eval(openstack project show ebf0f23f424c4417afd3e7bbf4e3900f -f value -c name)

The substitution from the second %s in printf works correctly, but I can't figure out how to execute the command.

The command needs to be executed in the same shell, and I cannot use environment variables.

Thanks.

** OUTPUT OF COMMANDS **

Here, -c var1 -c var2 can be placed in any order. -f just means print out the values, not the identifier.

[root@box~]# openstack server list --all -c Name -c ID -f value
2534ce5a-04da-4c7d-9ad5-b7bc466ae612 cf1-0

[root@box ~]# openstack server show 2534ce5a-04da-4c7d-9ad5-b7bc466ae612 -f value -c name -c project_id
cf1-0
ebf0f23f424c4417afd3e7bbf4e3900f

[root@box ~]# openstack project show ebf0f23f424c4417afd3e7bbf4e3900f -f value -c name
core

Desired output
===============
cf1-0 core

Body:
Not very familiar with the openstack command, but a simple way of doing this in one line would be using awk with system function.

The command should look similar to this:

openstack server list --all -c ID -f value | awk -F'\t' '{ printf $1; system("eval openstack project show " $2 " -f value -c name") }'


问:
perl two consecutive back ticked shell command do not run
I am trying to write perl script for managing amazon ec2 instances. In part of my code, I have two shell commands, and when I invoke them, the first runs but not the second. I cannot seem to find a good explanation for this. Here is the code:

```<code>$run_instances = 'ec2-run-instances ami-8e1fece7 -k mykey -t t1.micro';
$outp = `$run_instances`;
$outp =~ /INSTANCE\s+(i-\w+)\s/;
$instance_id = $1;
$describe_instances = "ec2-describe-instances $instance_id";
$outp = `$describe_instances`;
$outp =~ /(ec2-(\d+-\d+-\d+-\d+).\S+)/;
</code>```

The problem is $outp here has the output of $run_instances. For some time I could not understand why I was getting the wrong output; then I realised that $describe_instances command does not run.

I looked at the value of $describe_instances, called that from the Linux shell, and it worked fine. I called it from another Perl script, and it worked fine.

Then I gave $outp the output that is captured when $run_instances runs ($outp = "INSTANCE ......"). It worked, so I got the idea that somehow when these two commands run consecutively the second does not run.

One more thing to note is that when I put above code in a loop every time $run_instances works but $describe_instances does not.

I would be really happy if you could provide some light on this :)

Thank you

答:
I suspect the problem is this line:

```<code>$instance_id = $1;
</code>```

$1 is a global variable. One should never use $1 et al untested, since it:

Contains the subpattern from the
  corresponding set of capturing
  parentheses from the last successful
  pattern match

(from perldoc perlvar)

In other words, it is not overwritten if there is no match. What you might do is something like this:

```<code>die $! unless ( $outp =~ /INSTANCE\s+(i-\w+)\s/ );
$instance_id = $1;
</code>```

I try never to use $1 untested, and of course there are many ways to make sure it comes from the right place.

Body:
I am trying to write perl script for managing amazon ec2 instances. In part of my code, I have two shell commands, and when I invoke them, the first runs but not the second. I cannot seem to find a good explanation for this. Here is the code:

$run_instances = 'ec2-run-instances ami-8e1fece7 -k mykey -t t1.micro';
$outp = `$run_instances`;
$outp =~ /INSTANCE\s+(i-\w+)\s/;
$instance_id = $1;
$describe_instances = "ec2-describe-instances $instance_id";
$outp = `$describe_instances`;
$outp =~ /(ec2-(\d+-\d+-\d+-\d+).\S+)/;

The problem is $outp here has the output of $run_instances. For some time I could not understand why I was getting the wrong output; then I realised that $describe_instances command does not run.

I looked at the value of $describe_instances, called that from the Linux shell, and it worked fine. I called it from another Perl script, and it worked fine.

Then I gave $outp the output that is captured when $run_instances runs ($outp = "INSTANCE ......"). It worked, so I got the idea that somehow when these two commands run consecutively the second does not run.

One more thing to note is that when I put above code in a loop every time $run_instances works but $describe_instances does not.

I would be really happy if you could provide some light on this :)

Thank you

Body:
I suspect the problem is this line:

$instance_id = $1;

$1 is a global variable. One should never use $1 et al untested, since it:

Contains the subpattern from the
  corresponding set of capturing
  parentheses from the last successful
  pattern match

(from perldoc perlvar)

In other words, it is not overwritten if there is no match. What you might do is something like this:

die $! unless ( $outp =~ /INSTANCE\s+(i-\w+)\s/ );
$instance_id = $1;

I try never to use $1 untested, and of course there are many ways to make sure it comes from the right place.


问:
Error Code: 1055 incompatible with sql_mode=only_full_group_by
I have been having issues switching to an offline version of the Lahman SQL baseball database. I was using a terminal embed into an EDX course. This command runs fine on the web terminal:

```<code>SELECT concat(m.nameFirst,concat(" ",m.nameLast)) as Player,
    p.IPOuts/3 as IP,
    p.W,p.L,p.H,p.BB,p.ER,p.SV,p.SO as K,
    p.IPOuts+p.W*5+p.SV+p.SO-p.BB-p.L-p.H as PTS,
    p.yearID as Year
FROM Pitching p
Inner Join Master m
    ON p.playerID=m.playerID
WHERE p.yearID=2014 AND p.IPOuts>=50
GROUP BY m.playerID
ORDER BY PTS DESC;
</code>```

Which is running SQL 5.5.46, but when I use my offline version running 5.7.10 I get the following error code:

Error Code: 1055. Expression #1 of SELECT list is not in GROUP BY
      clause and contains nonaggregated column 'stats.m.nameFirst' which is
      not functionally dependent on columns in GROUP BY clause; this is
      incompatible with sql_mode=only_full_group_by

I've been reading a lot of solutions to people's problems, but they haven't helped in this case. That's never happened before, so I think this is either super obvious or maybe I'm getting ok at coding. Anyway, anyone know how to fix this?

答:
You can set the variables in mysql:

```<code>mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
</code>```

Remember NO_AUTO_CREATE_USER will not work with mysql 8.

If that doesn't work just do:

```<code>mysql > set sql_mode = ''
</code>```

Body:
I have been having issues switching to an offline version of the Lahman SQL baseball database. I was using a terminal embed into an EDX course. This command runs fine on the web terminal:

SELECT concat(m.nameFirst,concat(" ",m.nameLast)) as Player,
    p.IPOuts/3 as IP,
    p.W,p.L,p.H,p.BB,p.ER,p.SV,p.SO as K,
    p.IPOuts+p.W*5+p.SV+p.SO-p.BB-p.L-p.H as PTS,
    p.yearID as Year
FROM Pitching p
Inner Join Master m
    ON p.playerID=m.playerID
WHERE p.yearID=2014 AND p.IPOuts>=50
GROUP BY m.playerID
ORDER BY PTS DESC;

Which is running SQL 5.5.46, but when I use my offline version running 5.7.10 I get the following error code:

Error Code: 1055. Expression #1 of SELECT list is not in GROUP BY
      clause and contains nonaggregated column 'stats.m.nameFirst' which is
      not functionally dependent on columns in GROUP BY clause; this is
      incompatible with sql_mode=only_full_group_by

I've been reading a lot of solutions to people's problems, but they haven't helped in this case. That's never happened before, so I think this is either super obvious or maybe I'm getting ok at coding. Anyway, anyone know how to fix this?

Body:
You can set the variables in mysql:

mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

Remember NO_AUTO_CREATE_USER will not work with mysql 8.

If that doesn't work just do:

mysql > set sql_mode = ''


问:
angular 8 prod mode import then catch throws compiler not found error
java spring 5, Angular 8+ with Cli 8+

I have lazy lazy load enable for modules which looks as following and works perfectly fine build with or without --prod flag

```<code>{
  path: 'abc'
  loadChildren: () => import('abc.module').then(m => m.abcModule )
}
</code>```

If server session is expired module loading just blows up and won't do any thing so i added catch block after then as following which builds fine in both with or without prod mode, but with prod mode build when i click on route abc in browser gets following error.

```<code>{
      path: 'abc'
      loadChildren: () => import('abc.module').then(m => m.abcModule )
                          .catch( () => window.location.reload() )

    }

Error: Uncaught (in promise): Error: Runtime compiler is not loaded
Error Runtime compiler is not loaded
at Xi.Gi(main-es2015.50abc434343..js)
</code>```

i am scratching my head not sure about this, can some one help ?

答: problem is solved after i upgraded angular and cli version to 9.</p>

Body:
java spring 5, Angular 8+ with Cli 8+

I have lazy lazy load enable for modules which looks as following and works perfectly fine build with or without --prod flag

{
  path: 'abc'
  loadChildren: () => import('abc.module').then(m => m.abcModule )
}

If server session is expired module loading just blows up and won't do any thing so i added catch block after then as following which builds fine in both with or without prod mode, but with prod mode build when i click on route abc in browser gets following error.

{
      path: 'abc'
      loadChildren: () => import('abc.module').then(m => m.abcModule )
                          .catch( () => window.location.reload() )

    }

Error: Uncaught (in promise): Error: Runtime compiler is not loaded
Error Runtime compiler is not loaded
at Xi.Gi(main-es2015.50abc434343..js)

i am scratching my head not sure about this, can some one help ?


问:
Is there an kotlin equivalent of ?: java operator?
Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

```<code>//java example
//return condition ? a : b;
</code>```

答:
The Kotlin equivalent is:

```<code>if (a) b else c
</code>```

That's the closest to the Java that you can get at this point.

Body:
Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

//java example
//return condition ? a : b;

Body:
The Kotlin equivalent is:

if (a) b else c

That's the closest to the Java that you can get at this point.


问:
Unexpected behaviour of function used in conjunction with lapply/sapply?
This

```<code>mult_six <- function(x) {
  y <- x * 6
}

mult_six(7)
</code>```

returns nothing (as expected), and y is not globally assigned (also as exptected, since assignment takes place in the scope of the function, not in the parent environment - so y returns Error: object 'y' not found - completely normal)

But

```<code>sapply(c(1,2,3), mult_six)
</code>```

returns

```<code>[1]  6 12 18
</code>```

(and lapply() returns the list equivalent).

I do not understand why lapply/sapply would behave any differently to calling the function on each element separately?

答:
We can just wrap with ()

```<code>(mult_six(7))
#[1] 42
</code>```

The assignment to y<- is not needed.  It would be

```<code>mult_six <- function(x) {
     x * 6
  }
</code>```

Body:
This

mult_six <- function(x) {
  y <- x * 6
}

mult_six(7)

returns nothing (as expected), and y is not globally assigned (also as exptected, since assignment takes place in the scope of the function, not in the parent environment - so y returns Error: object 'y' not found - completely normal)

But

sapply(c(1,2,3), mult_six)

returns

[1]  6 12 18

(and lapply() returns the list equivalent).

I do not understand why lapply/sapply would behave any differently to calling the function on each element separately?

Body:
We can just wrap with ()

(mult_six(7))
#[1] 42

The assignment to y<- is not needed.  It would be

mult_six <- function(x) {
     x * 6
  }


问:
CMake Qt5 and AUTOUIC not rebuilding when .ui file touched
I have a Qt5 project, using CMake with AUTOUIC, AUTOMOC, and AUTORCC.

My problem is that if I change one of the .ui files, I expect UIC to run and produce the corresponding ui_XXX.h file. It doesn't. I have the .ui files listed in my add_library(... Foo1.ui Foo2.ui) declaration.

This is on Windows with Visual Studio 2019. I am using the VS solution file produced my CMake. As far as I can tell, the only time Auto UIC runs is if it is building the library; touch any source file, and everything builds as expected. Touch just a .ui file and build, and it doesn't build anything.

Building the application on Linux works as expected.

We just migrated the project to CMake for a common build system between Windows and Linux and quirks like this are annoying some people on the team and we would like to resolve them.

答:
This was a known CMake issue, and was fixed by this merge request (5999). The issue mentions Visual Studio 2017 specifically, but the problem will be the same for other Visual Studio generators.

If you can't update to the version where it was fixed, one work-around is to use the qt5_wrap_ui() command instead of relying on CMAKE_AUTOUIC. This way, a UIC rule is created for each .ui file explicitly listed:

```<code>qt5_wrap_ui(MY_LIB_UI_FILES Foo1.ui Foo2.ui ...)
add_library(MyLib
    # ...
    ${MY_LIB_UI_FILES}
)
</code>```

Body:
This was a known CMake issue, and was fixed by this merge request (5999). The issue mentions Visual Studio 2017 specifically, but the problem will be the same for other Visual Studio generators.

If you can't update to the version where it was fixed, one work-around is to use the qt5_wrap_ui() command instead of relying on CMAKE_AUTOUIC. This way, a UIC rule is created for each .ui file explicitly listed:

qt5_wrap_ui(MY_LIB_UI_FILES Foo1.ui Foo2.ui ...)
add_library(MyLib
    # ...
    ${MY_LIB_UI_FILES}
)


问:
Incorrect output from inner_join of dplyr package
I have two datasets, named "results" and "support2", available here.

I want to merge the two datasets by the only common column name "SNP". Code below:

```<code>> library(dplyr)
> results <- read_delim("<path>\\results", delim = "\t", col_name = T)
> support2 <- read_delim("<path>\\support2", delim = "\t", col_name = T)

> head(results)
# A tibble: 6 x 2
  SNP        p.value
  <chr>        <dbl>
1 rs28436661   0.334
2 rs9922067    0.322
3 rs2562132    0.848
4 rs3930588    0.332
5 rs2562137    0.323
6 rs3848343    0.363

 > head(support2)
# A tibble: 6 x 2
  SNP         position
  <chr>          <dbl>
1 rs62028702     60054
2 rs190434815    60085
3 rs62028703     60087
4 rs62028704     60095
5 rs181534180    60164
6 rs186233776    60177

> dim(results)
[1] 188242      2
> dim(support2)
[1] 1210619       2

# determine the number of common SNPs
length(Reduce(intersect, list(results$SNP, support2$SNP)))
[1] 187613

I would expect that after inner_join, the new data would have 187613 rows.

> newdata <- inner_join(results, support2)
Joining, by = "SNP"
> dim(newdata)
[1] 1409812       3
</code>```

Strangely, instead of have 187613 rows, the new data have 1409812 rows, which is even larger than the sum of the number of rows of the two dataframes.

I switched to the merge function as below:

```<code>> newdata2 <- merge(results, support2)
> dim(newdata2)
[1] 1409812       3
</code>```

This second new dataframe has the same issue. No idea why.

I wish to know how should I obtain a new dataframe whose rows represent the common rows of the two dataframes (should have 187613 rows) and whose columns contain columns of both dataframes.

答:
As already pointed out by @akrun, the data may have duplicates, possibly that is the only explanation of this behavior.

From the documentation of intersect, it always returns a unique value but inner join can have duplicates if the "by" value has duplicates, Hence the count mismatch.

If you truly want to see its right, see the unique counts of by variable (unique key in your case), it should match with your intersect result. But that doesn't mean your join/merge is right, ideally any join which has duplicates in both table A and B is not recommended(unless offcourse you have business/other justification). So, check if the duplicates are present in both the tables or only one of them. If it only found in one of the tables then probably your merge/join should be alright. I hope I am able to explain the scenario.

Please let me know if it doesn't answer your question, I shall remove it.

From Documentations:

intersect:

Each of union, intersect, setdiff and setequal will discard any
  duplicated values in the arguments, and they apply as.vector to their
  arguments

inner_join():

return all rows from x where there are matching values in y, and all
  columns from x and y. If there are multiple matches between x and y,
  all combination of the matches are returned.

Body:
I have two datasets, named "results" and "support2", available here.

I want to merge the two datasets by the only common column name "SNP". Code below:

> library(dplyr)
> results <- read_delim("<path>\\results", delim = "\t", col_name = T)
> support2 <- read_delim("<path>\\support2", delim = "\t", col_name = T)

> head(results)
# A tibble: 6 x 2
  SNP        p.value
  <chr>        <dbl>
1 rs28436661   0.334
2 rs9922067    0.322
3 rs2562132    0.848
4 rs3930588    0.332
5 rs2562137    0.323
6 rs3848343    0.363

 > head(support2)
# A tibble: 6 x 2
  SNP         position
  <chr>          <dbl>
1 rs62028702     60054
2 rs190434815    60085
3 rs62028703     60087
4 rs62028704     60095
5 rs181534180    60164
6 rs186233776    60177

> dim(results)
[1] 188242      2
> dim(support2)
[1] 1210619       2

# determine the number of common SNPs
length(Reduce(intersect, list(results$SNP, support2$SNP)))
[1] 187613

I would expect that after inner_join, the new data would have 187613 rows.

> newdata <- inner_join(results, support2)
Joining, by = "SNP"
> dim(newdata)
[1] 1409812       3

Strangely, instead of have 187613 rows, the new data have 1409812 rows, which is even larger than the sum of the number of rows of the two dataframes.

I switched to the merge function as below:

> newdata2 <- merge(results, support2)
> dim(newdata2)
[1] 1409812       3

This second new dataframe has the same issue. No idea why.

I wish to know how should I obtain a new dataframe whose rows represent the common rows of the two dataframes (should have 187613 rows) and whose columns contain columns of both dataframes.


问:
Having trouble extracting data from a web page with Selenium
This is supposed to connect to the web page, locate the HTML element by XPath, and then memorize the value of the text into a variable.

It connects to the page but it just just gives me the following result:

[[ChromeDriver: chrome on WINDOWS (5b3a1f161e663e550263860f3185a648)] -> xpath: //*[@id="tab-crew"]/div[1]/p/a]

```<code>public String reziser(String x) {
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Ilija Sekaric\\Desktop\\Letterboxd\\chromedriver.exe");
    ChromeDriver driver = new ChromeDriver();
    WebDriverWait wait= new WebDriverWait(driver,10);
    driver.navigate().to(x);
    String element="//*[@id=\"tab-crew\"]/div[1]/p/a";
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(element)));
    WebElement m=driver.findElement(By.xpath("//*[@id=\"tab-crew\"]/div[1]/p/a"));
    String result = String.valueOf(m);

    return result;
}
</code>```

答: As answered by Mr Cas, valueOf() method converts different types of values into string. Try with getText().</p>

Body:
This is supposed to connect to the web page, locate the HTML element by XPath, and then memorize the value of the text into a variable.

It connects to the page but it just just gives me the following result:

[[ChromeDriver: chrome on WINDOWS (5b3a1f161e663e550263860f3185a648)] -> xpath: //*[@id="tab-crew"]/div[1]/p/a]

public String reziser(String x) {
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Ilija Sekaric\\Desktop\\Letterboxd\\chromedriver.exe");
    ChromeDriver driver = new ChromeDriver();
    WebDriverWait wait= new WebDriverWait(driver,10);
    driver.navigate().to(x);
    String element="//*[@id=\"tab-crew\"]/div[1]/p/a";
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(element)));
    WebElement m=driver.findElement(By.xpath("//*[@id=\"tab-crew\"]/div[1]/p/a"));
    String result = String.valueOf(m);

    return result;
}


问:
Creating multiindex for panda dataframe for x and y coordinate and timestamp
I'm stuck with my knowledge of creating a multiindex for a pandas dataframe.
My dataframe is an image with 230 x 640. I have added a column with the timestamp and now I want to create a Multiindex with my x and y coordinate and timestamp. I need the timestamp also as index because I concat multiple frames with different timestamp but with same frame width and height.

Is there a way to create such an index? My objective is to get: Hey value on 2 and 0 is too high.

Image of dataframe without index

My dataframe looks like (val is a temperature value):

```<code> 0    1   2  ..  639  ts

0    val val val ..  val
1    val ..
2    ..
..
229
</code>```

答:
I believe this does what you want.

I'm assuming your "x" is in your rows and your "y" is in your columns and that you want a MultiIndex with ["ts", "x", "y"]:

```<code>(df
 .rename_axis('x').reset_index()
 .set_index(['ts', 'x'])
 .rename_axis('y', axis=1).stack()
 .rename('value')
)
</code>```

Breaking it down:

rename_axis('x').reset_index(): Rename the current index as "x" and turn it into a regular column (which will be needed for the next step.)

set_index(['ts', 'x']): Set the index to be a MultiIndex with ["ts", "x"]. This is pretty similar to the original DataFrame, only with "ts" moved to an index.

rename_axis('y', axis=1): Name the column axis as "y".

stack(): Turn the columns into rows, adding the third component to the MultiIndex. The resulting Series should have the shape you wanted.

rename('value'): Rename the Series as "value", in case you turn it back into a DataFrame with to_frame() that will be its name as a column.

Body:
I'm stuck with my knowledge of creating a multiindex for a pandas dataframe.
My dataframe is an image with 230 x 640. I have added a column with the timestamp and now I want to create a Multiindex with my x and y coordinate and timestamp. I need the timestamp also as index because I concat multiple frames with different timestamp but with same frame width and height.

Is there a way to create such an index? My objective is to get: Hey value on 2 and 0 is too high.

Image of dataframe without index

My dataframe looks like (val is a temperature value):

 0    1   2  ..  639  ts

0    val val val ..  val
1    val ..
2    ..
..
229

Body:
I believe this does what you want.

I'm assuming your "x" is in your rows and your "y" is in your columns and that you want a MultiIndex with ["ts", "x", "y"]:

(df
 .rename_axis('x').reset_index()
 .set_index(['ts', 'x'])
 .rename_axis('y', axis=1).stack()
 .rename('value')
)

Breaking it down:

rename_axis('x').reset_index(): Rename the current index as "x" and turn it into a regular column (which will be needed for the next step.)

set_index(['ts', 'x']): Set the index to be a MultiIndex with ["ts", "x"]. This is pretty similar to the original DataFrame, only with "ts" moved to an index.

rename_axis('y', axis=1): Name the column axis as "y".

stack(): Turn the columns into rows, adding the third component to the MultiIndex. The resulting Series should have the shape you wanted.

rename('value'): Rename the Series as "value", in case you turn it back into a DataFrame with to_frame() that will be its name as a column.