答:
You don't trust the source of the data. Maybe it will add another | and the number of columns is wrong.

Another approach is guessing that you can trust the timestamp field.

So try to split the line when the field after the timestamp has more dan one character (and split after the first).

```<code>sed -E 's/([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\|.)(.)/\1\n\2/g' file
</code>```

Title: Bash command/script to split line on a certain character

Body:
I would like to split the below data to the expected output:

Raw Data:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Expected Output:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0
931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Basically the \n character is getting lost sometimes in the data and the lines are getting merged. Sometimes more than 1 line gets merged as well (even the opposite happens but we can get to that later).

The data always has 43 columns | separated. The last but one column(42nd) always is a timestamp and the last column is usually 0 or 1.

Trying for the below approach:
If cols > 43
Split 44th column to add \n and print the remaining.
Repeat process until cols=43

echo "${curr}" | awk -F\| ' { if(NF > 43) {for(i=43;i<NF;i++) "sed '${NR}s/\(^0\)/\1\n/p' $i" }}' filename

Body:
You don't trust the source of the data. Maybe it will add another | and the number of columns is wrong.

Another approach is guessing that you can trust the timestamp field.

So try to split the line when the field after the timestamp has more dan one character (and split after the first).

sed -E 's/([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\|.)(.)/\1\n\2/g' file


来源: stackexchange

问:
Get the last string printed in C/C++
I am trying to create a tester using googletest. the problem is that the function that I am testing is returning void and printing a result instead. I want to get the last string printed into the console so I can test the output. the string may include \n.

so I have the function itself:

void f_sequence(char sequenceStr[])
{
   //logic...
    if(condotion1)
        printf("somthing1");
    else if(condotion2)
        printf("somthing2")
(...)
}
```

<p>and then the tester:</p>

<pre class="lang-cpp prettyprint-override"><code>TEST(TesterGroup, TesterName)
{
    f_sequence("input");
    EXPECT_EQ("somthing1", /*how do i get the output?*/);
}
</code>```

Is it possible?

The functions I test are in c, while the Test function itself (the tester) is in c++. the output is printed using printf. I cannot change the function itself. I am using CLion latest version.

答:
I don't know if it's possible to get what was last printed, but if you control the environment before your test function is called, you can redirect where standard output goes, which lets you write it to a file, which you can then check.

See this old answer which IMO was neglected.  The example from it is modified here:

```<code>FILE *fp_old = stdout;  // preserve the original stdout
stdout = fopen("/path/to/file/you/want.txt","w");  // redirect stdout to anywhere you can open
// CALL YOUR FUNCTION UNDER TEST HERE
fclose(stdout);  // Close the file with the output contents
stdout=fp_old;  // restore stdout to normal

// Re-open the file from above, and read it to make sure it contains what you expect.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get the last string printed in C/C++

Body:
I am trying to create a tester using googletest. the problem is that the function that I am testing is returning void and printing a result instead. I want to get the last string printed into the console so I can test the output. the string may include \n.

so I have the function itself:

void f_sequence(char sequenceStr[])
{
   //logic...
    if(condotion1)
        printf("somthing1");
    else if(condotion2)
        printf("somthing2")
(...)
}

and then the tester:

TEST(TesterGroup, TesterName)
{
    f_sequence("input");
    EXPECT_EQ("somthing1", /*how do i get the output?*/);
}

Is it possible?

The functions I test are in c, while the Test function itself (the tester) is in c++. the output is printed using printf. I cannot change the function itself. I am using CLion latest version.

Body:
I don't know if it's possible to get what was last printed, but if you control the environment before your test function is called, you can redirect where standard output goes, which lets you write it to a file, which you can then check.

See this old answer which IMO was neglected.  The example from it is modified here:

FILE *fp_old = stdout;  // preserve the original stdout
stdout = fopen("/path/to/file/you/want.txt","w");  // redirect stdout to anywhere you can open
// CALL YOUR FUNCTION UNDER TEST HERE
fclose(stdout);  // Close the file with the output contents
stdout=fp_old;  // restore stdout to normal

// Re-open the file from above, and read it to make sure it contains what you expect.


问:
react slide out menu state = not setting state?
I'm trying to develop a slide-out menu with routing function for React. for some reason state = {} isn't setting defining sideDrawOpen what could the reasons for this be thanks for your help. the error I get running yarn start is
 "Failed to compile.

./src/App.js
  Line 21:45:  'sideDrawerOpen' is not defined  no-undef

Search for the keywords to learn more about each error."

```<code>import React, { Component } from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';

import main_page from './components/main_page';
import setup_page from './components/setup_page';
import settings_page from './components/settings_page';
import Error from './components/Error';
import Nav from './components/Navigation/Nav';
import SideDrawer from './components/Navigation/SideDrawer';
import Backdrop from './components/Navigation/Backdrop';

export class App extends Component {
   state = {
   sideDrawerOpen: false
   }

   drawerToggleClickHandler = () => {
      this.setState((prevState) =>{
         return {sideDrawerOpen: !prevState,sideDrawerOpen};
      });
   };

  render() {
    let sideDrawer;
    let backdrop;

    if (this.state.sideDrawerOpen) {
      sideDrawer = <SideDrawer />
      backdrop = <Backdrop />
    }
  return (
    <div className="App_margin">
  <Router>
    <div className='App'>
      {sideDrawer}
      {backdrop}
      <Nav />
      <Switch>
        <Route path='/'  component={setup_page} exact/>
        <Route path='/main_page' component={main_page} />
        <Route path='/settings_page' component={settings_page} />
        <Route  component={Error} />
      </Switch>

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

答: !prevState,sideDrawerOpen has a comma, not a .

Body:
I'm trying to develop a slide-out menu with routing function for React. for some reason state = {} isn't setting defining sideDrawOpen what could the reasons for this be thanks for your help. the error I get running yarn start is
 "Failed to compile.

./src/App.js
  Line 21:45:  'sideDrawerOpen' is not defined  no-undef

Search for the keywords to learn more about each error."

import React, { Component } from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';

import main_page from './components/main_page';
import setup_page from './components/setup_page';
import settings_page from './components/settings_page';
import Error from './components/Error';
import Nav from './components/Navigation/Nav';
import SideDrawer from './components/Navigation/SideDrawer';
import Backdrop from './components/Navigation/Backdrop';

export class App extends Component {
   state = {
   sideDrawerOpen: false
   }

   drawerToggleClickHandler = () => {
      this.setState((prevState) =>{
         return {sideDrawerOpen: !prevState,sideDrawerOpen};
      });
   };

  render() {
    let sideDrawer;
    let backdrop;

    if (this.state.sideDrawerOpen) {
      sideDrawer = <SideDrawer />
      backdrop = <Backdrop />
    }
  return (

  <Router>

      {sideDrawer}
      {backdrop}

      <Switch>
        <Route path='/'  component={setup_page} exact/>
        <Route path='/main_page' component={main_page} />
        <Route path='/settings_page' component={settings_page} />
        <Route  component={Error} />
      </Switch>

  </Router>

  );
}
}


问:
Which report do we use for Google Analytics custom triggered events?
I'm created a method that will send a custom event to Google Analytics and it looks like this:

```<code>  uaClick2() {
    console.log("CLICKED UA 2")
    gtag('config', 'UA-146420424388-3', {
      'button_click': 'ua2'
    })
  }

</code>```

When I click the button I see the gtag firing.  Where in the Google Analytics console can I look for these events.

I tried clicking on Report tabs (Realtime, Audience, Acquisition, etc.) but I don't see any reporting with the custom button_click event nor the number of times that the event has occurred.

答:
Your syntax to send an event is wrong.

To send Google Analytics Events on a web page where the global site tag has been added, you need to use the following syntax:

```<code>gtag('event', <action>, {
  'event_category': <category>,
  'event_label': <label>,
  'value': <value>
});
</code>```

https://developers.google.com/analytics/devguides/collection/gtagjs/events

Body:
I'm created a method that will send a custom event to Google Analytics and it looks like this:

  uaClick2() {
    console.log("CLICKED UA 2")
    gtag('config', 'UA-146420424388-3', {
      'button_click': 'ua2'
    })
  }

When I click the button I see the gtag firing.  Where in the Google Analytics console can I look for these events.

I tried clicking on Report tabs (Realtime, Audience, Acquisition, etc.) but I don't see any reporting with the custom button_click event nor the number of times that the event has occurred.

Body:
Your syntax to send an event is wrong.

To send Google Analytics Events on a web page where the global site tag has been added, you need to use the following syntax:

gtag('event', <action>, {
  'event_category': <category>,
  'event_label': <label>,
  'value': <value>
});

https://developers.google.com/analytics/devguides/collection/gtagjs/events


答:
Two ways:

If you're on a POSIX compatibile system, you can redirect the output of the program to a file using >, then read from the file later to confirm that the output is correct.

The other way is something like this:

```<code>freopen("output.txt", "w", stdout);
f_sequence();
freopen("/dev/tty", "w", stdout);
</code>```

for POSIX compatible systems. On other platforms you'd need to change the "/dev/tty" to something else. I'm not aware of a completely portable way to do this.

And then read from output.txt. What the above snippet does is change what stdout is, so that it prints to a file instead of the normal stdout.

Title: Get the last string printed in C/C++

Body:
Two ways:

If you're on a POSIX compatibile system, you can redirect the output of the program to a file using >, then read from the file later to confirm that the output is correct.

The other way is something like this:

freopen("output.txt", "w", stdout);
f_sequence();
freopen("/dev/tty", "w", stdout);

for POSIX compatible systems. On other platforms you'd need to change the "/dev/tty" to something else. I'm not aware of a completely portable way to do this.

And then read from output.txt. What the above snippet does is change what stdout is, so that it prints to a file instead of the normal stdout.


问:
I need add only property a 4 objects
I making a tetris, need add property gravity and move all object,
my problem is that I do it object by object and i would like it can add property for all object

Class Piece:

```<code>interface Figura
{
    void MoverI(); //Izquierda
    void MoverD(); //Derecha
    void RotarI(); //Rotacion
    void RotarD();
    void Gravedad();
}

class Square : Figura
{
    public SolidColorBrush C = new SolidColorBrush();
    public Rectangle _P = new Rectangle();
    public int X,
               Y,
               YDIR = 5,
               XDIR = 10;
    const int TAM = 10;
    protected Canvas c;

    public Square(Canvas c, int X, int Y)
    {
        _P.Width = TAM;
        _P.Height = TAM;
        this.X = X;
        this.Y = Y;
        C.Color = Color.FromRgb(255, 0, 0);
        _P.Fill = C;
        Canvas.SetLeft(_P, X);
        Canvas.SetTop(_P, Y);
        c.Children.Add(_P);
    }

    void Figura.Gravedad()
    {
        Y += YDIR;
        Canvas.SetTop(_P, Y);
    }
</code>```

Class MainWindows

```<code>  public MainWindow()
    {
        InitializeComponent();
        A = new Square(Canvas, 50, 50);
        A1 = new Square(Canvas, 50, 60);
        A2 = new Square(Canvas, 60, 50);
        A3 = new Square(Canvas, 60, 60);

        DP = new DispatcherTimer();
        DP.Interval = new TimeSpan(0, 0, 0, 0, 80);
        DP.Tick += new EventHandler(DP_TICK);
        DP.IsEnabled = true;
        MatrizTetris = new int[100, 100];
    }

    public void DP_TICK(object sender, EventArgs e)
    {
        A.Gravedad();
        A1.Gravedad();
        A2.Gravedad();
        A3.Gravedad();
    }
</code>```

For example:

```<code>        A.Gravedad();
        A1.Gravedad();
        A2.Gravedad();
        A3.Gravedad();
</code>```

other method of making to add all property or regroup A, A1, A2, A3 and add Gravedad?

答:
You could maintain a list of all objects within the class:

```<code>ICollection<Figura> _objects;
</code>```

Initialize this in the MainWindow constructor:

```<code>_objects = new List<Figura> { A, A1, A2, A3 };
</code>```

And then in DP_TICK you can iterate over all of the objects and call your method:

```<code>foreach (var x in _objects)
    x.Gravedad();
</code>```

Title: I need add only property a 4 objects

Body:
I making a tetris, need add property gravity and move all object,
my problem is that I do it object by object and i would like it can add property for all object

Class Piece:

interface Figura
{
    void MoverI(); //Izquierda
    void MoverD(); //Derecha
    void RotarI(); //Rotacion
    void RotarD();
    void Gravedad();
}

class Square : Figura
{
    public SolidColorBrush C = new SolidColorBrush();
    public Rectangle _P = new Rectangle();
    public int X,
               Y,
               YDIR = 5,
               XDIR = 10;
    const int TAM = 10;
    protected Canvas c;

    public Square(Canvas c, int X, int Y)
    {
        _P.Width = TAM;
        _P.Height = TAM;
        this.X = X;
        this.Y = Y;
        C.Color = Color.FromRgb(255, 0, 0);
        _P.Fill = C;
        Canvas.SetLeft(_P, X);
        Canvas.SetTop(_P, Y);
        c.Children.Add(_P);
    }

    void Figura.Gravedad()
    {
        Y += YDIR;
        Canvas.SetTop(_P, Y);
    }

Class MainWindows

  public MainWindow()
    {
        InitializeComponent();
        A = new Square(Canvas, 50, 50);
        A1 = new Square(Canvas, 50, 60);
        A2 = new Square(Canvas, 60, 50);
        A3 = new Square(Canvas, 60, 60);

        DP = new DispatcherTimer();
        DP.Interval = new TimeSpan(0, 0, 0, 0, 80);
        DP.Tick += new EventHandler(DP_TICK);
        DP.IsEnabled = true;
        MatrizTetris = new int[100, 100];
    }

    public void DP_TICK(object sender, EventArgs e)
    {
        A.Gravedad();
        A1.Gravedad();
        A2.Gravedad();
        A3.Gravedad();
    }

For example:

        A.Gravedad();
        A1.Gravedad();
        A2.Gravedad();
        A3.Gravedad();

other method of making to add all property or regroup A, A1, A2, A3 and add Gravedad?

Body:
You could maintain a list of all objects within the class:

ICollection<Figura> _objects;

Initialize this in the MainWindow constructor:

_objects = new List<Figura> { A, A1, A2, A3 };

And then in DP_TICK you can iterate over all of the objects and call your method:

foreach (var x in _objects)
    x.Gravedad();


问:
Raw Data Printing without dialog from PHP / JAVASCRIPT
I am currently adding features to a PHP web application for a client. They require to be able to print some raw data to a ticket / thermal printer direct from the php which will be run on an internet browser from a self service kiosk.

The data needs to printed on the local kiosk's in built ticket printer.

From my preliminary research I understand that I must perform this task using javascript for any client side actions and wondered if anybody knew of any method or example function that will allow the printing of a string to a designated printer / com port which would bypass the printer dialog box?

Thanks in advance for any help

Alex

答:
If it has to be cross browser and platform independent, stop right now and run. There is NOT way, and I mean NO way for Javascript to access information about printers, margins, paper size, and all the variables in printers. Even if your browser has some sort of fast print button, print using default settings and default printers, you have no idea the type of paper, the ink, the margins, etc, and you could be printing on A4 paper, or in the US, our legal size, 8.5" X 11.5".

Browsers, for security, do NOT give javascript any access to this information that is supplied to them by the Windows API and the printer drivers. The closest possible that I know of, is in small networks, where the variables are known, and configured using Internet Explorer's JScript or ActiveX. Short of this, your only other easy option is to write your own web browser/addon/plugin, or to modify one that will run on these platforms, that has this built in capability.

More info available here.

EDIT: Though if you really want to make your life simple, tell them to install Firefox, and check out this article for the simplest solution possible. Also, have you considered VBScript? It has this capability, I've seen it done before.

ContentLicense: CC BY-SA 3.0


问:
Entity Framework: .Add & .SaveChanges() is not adding entity to database
When I am adding an entry

```<code>var objectEntity = new ObjectStaging();
objectEntity .CreatedBy = ClaimsPrincipal.Current.Identity.Name;
objectEntity .ModifiedBy = ClaimsPrincipal.Current.Identity.Name;
objectEntity .Set(ObjectInfo);
database.ObjectStaging.Add(objectEntity);
database.SaveChanges();
</code>```

For some reason, my objectEntity is not being added to my database given the following code. When using the debugger, it moves through database.ObjectStaging.Add(objectEntity);  but does not continue after calling SaveChanges(). Is there a way to know why it is failing to add the entry to the database?

Exception Thrown:

Exception thrown:
  'System.Data.Entity.Validation.DbEntityValidationException' in
  VCC.BrokerPortal.DAO.dll Validation failed for one or more entities.
  See 'EntityValidationErrors' property for more details.

Is there a way to know what specifically did not validate?

Also, I tested the state of the entity using the following lines of code,

```<code>database.ObjectStaging.Add(objectEntity);
var state= brokerPortalDB.Entry(objectEntity).State;
</code>```

state currently shows the value of 'added'.

答:
Thank you!

I ended up looking into the exception thrown and it appears it was related to one of the properties not having proper validation. In this instance I had a [MaxLength] attribute assigned to a field and I was trying to add a value longer than that length allowed.

Body:
When I am adding an entry

var objectEntity = new ObjectStaging();
objectEntity .CreatedBy = ClaimsPrincipal.Current.Identity.Name;
objectEntity .ModifiedBy = ClaimsPrincipal.Current.Identity.Name;
objectEntity .Set(ObjectInfo);
database.ObjectStaging.Add(objectEntity);
database.SaveChanges();

For some reason, my objectEntity is not being added to my database given the following code. When using the debugger, it moves through database.ObjectStaging.Add(objectEntity);  but does not continue after calling SaveChanges(). Is there a way to know why it is failing to add the entry to the database?

Exception Thrown:

Exception thrown:
  'System.Data.Entity.Validation.DbEntityValidationException' in
  VCC.BrokerPortal.DAO.dll Validation failed for one or more entities.
  See 'EntityValidationErrors' property for more details.

Is there a way to know what specifically did not validate?

Also, I tested the state of the entity using the following lines of code,

database.ObjectStaging.Add(objectEntity);
var state= brokerPortalDB.Entry(objectEntity).State;

state currently shows the value of 'added'.


问:
How to extend React functional component on hooks?
I know that it's not recommended approach but anyway I curious about how it could be done via functional components and hooks. Considering the following example: </p>

```<code>class SimpleComponent extends Component {
    method1 = () => {
        console.log('Method 1');
    };

    method2 = () => {
        console.log('Method 2');
    };

    renderMessage2() {
        return (
            <div onClick={this.method2}>Message 2</div>
        );
    }

    render() {
        return (
            <div>
                <div onClick={this.method1}>Message 1</div>
                {this.renderMessage2()}
            </div>
        );
    }
}

class EnhancedComponent extends SimpleComponent {
    method1 = () => {
        console.log('Enhanced Method 1');
    };

    method2 = () => {
        console.log('Enhanced Method 2');
    };

    renderMessage2() {
        return (
            <div onClick={this.method2}>Enhanced Message 2</div>
        );
    }
}
</code>```

<p>How can we achieve such behavior with functional components and hooks? </p>

答:
I don't like this actually, but I think we can do something like that: </p>

```<code>function Message2({ method2Function }) {
    return (
        <div onClick={method2Function}>Message 2</div>
    );
}

function method1() {
    console.log('Method 1');
}

function method2() {
    console.log('Method 2');
}

function SimpleComponent({ Message2Component = Message2, method1Function = method1, method2Function = method2 }) {
    return (
        <div>
            <div onClick={method1Function}>Message 1</div>
            <Message2Component method2Function={method2Function} />
        </div>
    );
}

function EnhancedMessage2({ method2Function }) {
    return (
        <div onClick={method2Function}>Enhanced Message 2</div>
    );
}

function EnhancedComponent() {
    return (
        <SimpleComponent
            Message2Component={EnhancedMessage2}
            method1Function={() => { console.log('Enhanced Method 1'); }}
            method2Function={() => { console.log('Enhanced Method 2'); }}
        />
    );
}
</code>```

Body:
I know that it's not recommended approach but anyway I curious about how it could be done via functional components and hooks. Considering the following example:

class SimpleComponent extends Component {
    method1 = () => {
        console.log('Method 1');
    };

    method2 = () => {
        console.log('Method 2');
    };

    renderMessage2() {
        return (

Message 2

        );
    }

    render() {
        return (

Message 1

                {this.renderMessage2()}

        );
    }
}

class EnhancedComponent extends SimpleComponent {
    method1 = () => {
        console.log('Enhanced Method 1');
    };

    method2 = () => {
        console.log('Enhanced Method 2');
    };

    renderMessage2() {
        return (

Enhanced Message 2

        );
    }
}

How can we achieve such behavior with functional components and hooks?

Body:
I don't like this actually, but I think we can do something like that:

function Message2({ method2Function }) {
    return (
        <div onClick={method2Function}>Message 2</div>
    );
}

function method1() {
    console.log('Method 1');
}

function method2() {
    console.log('Method 2');
}

function SimpleComponent({ Message2Component = Message2, method1Function = method1, method2Function = method2 }) {
    return (
        <div>
            <div onClick={method1Function}>Message 1</div>
            <Message2Component method2Function={method2Function} />
        </div>
    );
}

function EnhancedMessage2({ method2Function }) {
    return (
        <div onClick={method2Function}>Enhanced Message 2</div>
    );
}

function EnhancedComponent() {
    return (
        <SimpleComponent
            Message2Component={EnhancedMessage2}
            method1Function={() => { console.log('Enhanced Method 1'); }}
            method2Function={() => { console.log('Enhanced Method 2'); }}
        />
    );
}


问:
What is the difference between polyfill and transpiler?
What is the difference between a polyfill and transpiler?

I often read the same term used in similar context.

答: Polyfills are scripts that offer to emulate a feature that is not implemented in a browser.</p>


问:
How to read a data struct sent serially from an arduino?
I'm struggling to read a binary data struct with Python3 sent serially from an Arduino Mega 2560.

Arduino Code:

```<code>char userInput;
bool ledState = false;

typedef struct
{
  unsigned long  logTimeStart;
  unsigned long  frequencyOne;
  unsigned long  frequencyTwo;
  unsigned long  frequencyThree;
  unsigned long  frequencyFour;
  unsigned short int  revPowerOne;
  unsigned short int  revPowerTwo;
  unsigned short int  revPowerThree;
  unsigned short int  revPowerFour;
  unsigned short int  tempSensor;
} SDLogger;

SDLogger dataLog;

void setup()
{

  Serial.begin(9600);
  bitWrite(DDRB, 7, HIGH); // Set LED DDR high on port B, pin 7

  dataLog.logTimeStart = millis();
  dataLog.frequencyOne = 4000000000;       // PREDEFINED VALUES FOR TESTING
  dataLog.frequencyTwo = 4000000000;
  dataLog.frequencyThree = 4000000000;
  dataLog.frequencyFour = 4000000000;
  dataLog.revPowerOne = 65000;             // PREDEFINED VALUES FOR TESTING
  dataLog.revPowerTwo = 65000;
  dataLog.revPowerThree = 65000;
  dataLog.revPowerFour = 65000;
  dataLog.tempSensor = 65000;

  Serial.println("<Arduino is ready>");
}

void loop()
{
  checkForSerialMessage();
  delay(1000);
}

void checkForSerialMessage()
{
  Serial.println("checking serial...");
  if (Serial.available() > 0)
  {
     userInput = Serial.read();

     if (userInput == 'a')
     {
      ledState = !ledState;
      bitWrite(PORTB, 7, ledState);
      Serial.println("led");
     }

     if (userInput == 'b')
     {
        Serial.write((byte*)&dataLog, sizeof(dataLog));
     }
  }
}

</code>```

I believe the size of the struct is 30 bytes. My goal is to have the Arduino check the buffer intermittently for a specific character. When that character is received, the Arduino sends a defined data struct to my python interface, which is then unpacked and decoded into something readable by humans. I wrote an alternative command which toggles the Arduino's built-in LED. This was done to understand simple serial interfacing between the software. The LED toggle seems to function as expected, but not the struct commands.

Python Code

```<code>from tkinter import *
from struct import *
import serial
import time

ser = serial.Serial('COM5', baudrate=9600, timeout=1)
root = Tk() # root widget, this has to be first before any other widgets.

BINARY_STRFORMAT = "LLLLLHHHHH"         # Format to match arduino struct
print(calcsize(BINARY_STRFORMAT))       # RESULT IS 30

def toggleLED():
    ser.write(b'a')
    arduinoData = ser.readline().decode('ascii')  # readline functions will read until it sees a newline \n
                                                  #  .decode('ascii')
    print(arduinoData)

def toggleSerial():
    ser.write(b'b')
    arduinoData = ser.readline()
    print(arduinoData)
    unpacked = unpack(BINARY_STRFORMAT, arduinoData)

# in tkinter, everything is a widget:
header = Label(root, text="Read data from Arduino")
led_on = Button(root, text="led on", command=toggleLED)
read_serial = Button(root, text="enable data stream", command=toggleSerial)

# showing Label widget onto screen
header.pack()
led_on.pack()
read_serial.pack()

root.mainloop()
</code>```

When I run the python code, I can use my rudimentary tkinter GUI to toggle the Arduino's LED. But when I attempt to request the data struct, I get a struct error:

struct.error: unpack requires a buffer of 30 bytes
```

I tried to read through the pySerial documentation to see if I could improve how my serial data is received, but I could not find struct references. I'm failing to understand how the struct is sent/received and how it should be read in python.

I'm relatively new to software engineering and serial communication, so please let me know if I need to clarify anything here.

答: Update: thanks to @martineau and @Edward, we learned that Serial.println() was writing data to the same port which was trying to transmit/receive the data struct. This overlap was interfering with the python GUI's ability to parse and decode the binary struct. When the Serial.println() was removed, the python GUI received the expected 30-byte struct.

Body:
I'm struggling to read a binary data struct with Python3 sent serially from an Arduino Mega 2560.

Arduino Code:

char userInput;
bool ledState = false;

typedef struct
{
  unsigned long  logTimeStart;
  unsigned long  frequencyOne;
  unsigned long  frequencyTwo;
  unsigned long  frequencyThree;
  unsigned long  frequencyFour;
  unsigned short int  revPowerOne;
  unsigned short int  revPowerTwo;
  unsigned short int  revPowerThree;
  unsigned short int  revPowerFour;
  unsigned short int  tempSensor;
} SDLogger;

SDLogger dataLog;

void setup()
{

  Serial.begin(9600);
  bitWrite(DDRB, 7, HIGH); // Set LED DDR high on port B, pin 7

  dataLog.logTimeStart = millis();
  dataLog.frequencyOne = 4000000000;       // PREDEFINED VALUES FOR TESTING
  dataLog.frequencyTwo = 4000000000;
  dataLog.frequencyThree = 4000000000;
  dataLog.frequencyFour = 4000000000;
  dataLog.revPowerOne = 65000;             // PREDEFINED VALUES FOR TESTING
  dataLog.revPowerTwo = 65000;
  dataLog.revPowerThree = 65000;
  dataLog.revPowerFour = 65000;
  dataLog.tempSensor = 65000;

  Serial.println("<Arduino is ready>");
}

void loop()
{
  checkForSerialMessage();
  delay(1000);
}

void checkForSerialMessage()
{
  Serial.println("checking serial...");
  if (Serial.available() > 0)
  {
     userInput = Serial.read();

     if (userInput == 'a')
     {
      ledState = !ledState;
      bitWrite(PORTB, 7, ledState);
      Serial.println("led");
     }

     if (userInput == 'b')
     {
        Serial.write((byte*)&dataLog, sizeof(dataLog));
     }
  }
}

I believe the size of the struct is 30 bytes. My goal is to have the Arduino check the buffer intermittently for a specific character. When that character is received, the Arduino sends a defined data struct to my python interface, which is then unpacked and decoded into something readable by humans. I wrote an alternative command which toggles the Arduino's built-in LED. This was done to understand simple serial interfacing between the software. The LED toggle seems to function as expected, but not the struct commands.

Python Code

from tkinter import *
from struct import *
import serial
import time

ser = serial.Serial('COM5', baudrate=9600, timeout=1)
root = Tk() # root widget, this has to be first before any other widgets.

BINARY_STRFORMAT = "LLLLLHHHHH"         # Format to match arduino struct
print(calcsize(BINARY_STRFORMAT))       # RESULT IS 30

def toggleLED():
    ser.write(b'a')
    arduinoData = ser.readline().decode('ascii')  # readline functions will read until it sees a newline \n
                                                  #  .decode('ascii')
    print(arduinoData)

def toggleSerial():
    ser.write(b'b')
    arduinoData = ser.readline()
    print(arduinoData)
    unpacked = unpack(BINARY_STRFORMAT, arduinoData)

# in tkinter, everything is a widget:
header = Label(root, text="Read data from Arduino")
led_on = Button(root, text="led on", command=toggleLED)
read_serial = Button(root, text="enable data stream", command=toggleSerial)

# showing Label widget onto screen
header.pack()
led_on.pack()
read_serial.pack()

root.mainloop()

When I run the python code, I can use my rudimentary tkinter GUI to toggle the Arduino's LED. But when I attempt to request the data struct, I get a struct error:

struct.error: unpack requires a buffer of 30 bytes

I tried to read through the pySerial documentation to see if I could improve how my serial data is received, but I could not find struct references. I'm failing to understand how the struct is sent/received and how it should be read in python.

I'm relatively new to software engineering and serial communication, so please let me know if I need to clarify anything here.


问:
How do you add a favicon to HTML page?
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used realfavicongenerator.net, but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way:

```<code><title>Newsreed | Articles</title>
<link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico">
</code>```

What should I do, because I've been struggling with it for several days now and tere has been no solution on anything.

答: Fairly sure the syntax for the href should be:  href="{% static 'imgs/favicon.ico' %}</p>

Title: How do you add a favicon to HTML page?

Body:
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used realfavicongenerator.net, but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way:

<title>Newsreed | Articles</title>
<link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico">

What should I do, because I've been struggling with it for several days now and tere has been no solution on anything.


问:
How to automatically filter embedding relations data?
I have 2 simple entity related between themselves:

```<code><?php

declare(strict_types=1);

namespace App\Entity;

// use ... ;

/**
 * @ApiResource(
 *     subresourceOperations={
 *         // ...
 *     },
 *     // ... ,
 *     normalizationContext={"groups" = {"category:read"}}
 * )
 * @ ...
 */
class Category
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity="Object", mappedBy="category")
     * @ApiSubresource
     * @Groups({"category:read"})
     */
    private $objects;

    // ...

    public function getObjects(): Collection
    {
        return $this->objects;
    }
}

</code>```

And

```<code><?php

declare(strict_types=1);

namespace App\Entity;

// use ... ;

/**
 * @ApiResource(
 *     // ...
 * )
 * @ ...
 */
class Object
{
    // ...

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Category")
     * @ORM\JoinColumn(nullable=false)
     * @Groups({"object:read", "object:write"})
     */
    private $category;

    /**
     * @ORM\Column(type="boolean")
     */
    private $isActive = true;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Groups({"object:read", "object:write", "category:read"})
     */
    private $name;

    // ...
}
</code>```

I want to get by /api/сategories/{id} related data Objects, where isActive = true. Now I get all the records.

I tried to use QueryItemExtensionInterface andQueryCollectionExtensionInterface, but I still get all the records. fetch ="EAGER" also didn't help me

I clarify, I do not want to get this by subresource /api/categories/{id}/objects. I want to get it using /api/сategories/{id}

I also want this to depend on the role of the user. So that the admin can get all the records and the user only isActive = true

Any ideas how to do this?

答: Use the Boolean Filter with categories?objects.isActive=1. This filter must be set up on the relation property as described here.

Body:
I have 2 simple entity related between themselves:

<?php

declare(strict_types=1);

namespace App\Entity;

// use ... ;

/**
 * @ApiResource(
 *     subresourceOperations={
 *         // ...
 *     },
 *     // ... ,
 *     normalizationContext={"groups" = {"category:read"}}
 * )
 * @ ...
 */
class Category
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity="Object", mappedBy="category")
     * @ApiSubresource
     * @Groups({"category:read"})
     */
    private $objects;

    // ...

    public function getObjects(): Collection
    {
        return $this->objects;
    }
}

And

<?php

declare(strict_types=1);

namespace App\Entity;

// use ... ;

/**
 * @ApiResource(
 *     // ...
 * )
 * @ ...
 */
class Object
{
    // ...

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Category")
     * @ORM\JoinColumn(nullable=false)
     * @Groups({"object:read", "object:write"})
     */
    private $category;

    /**
     * @ORM\Column(type="boolean")
     */
    private $isActive = true;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Groups({"object:read", "object:write", "category:read"})
     */
    private $name;

    // ...
}

I want to get by /api/сategories/{id} related data Objects, where isActive = true. Now I get all the records.

I tried to use QueryItemExtensionInterface andQueryCollectionExtensionInterface, but I still get all the records. fetch ="EAGER" also didn't help me

I clarify, I do not want to get this by subresource /api/categories/{id}/objects. I want to get it using /api/сategories/{id}

I also want this to depend on the role of the user. So that the admin can get all the records and the user only isActive = true

Any ideas how to do this?


问:
What does the "?:^" regular expression mean?
I am looking at this sub-expression (this is in JavaScript):

```<code>(?:^|.....)
</code>```

I know that ? means "zero or one times" when it follows a character, but not sure what it means in this context.

答:
(?:some stuff) means that you don't want to match the expression in the parentheses separately. Normally the pieces of a regexp grouped in parentheses are grouped and can be referenced individually (this is called using backreferences).

See http://www.regular-expressions.info/brackets.html

OwnerDisplayName: levik

ContentLicense: CC BY-SA 2.5

Body:
I am looking at this sub-expression (this is in JavaScript):

(?:^|.....)

I know that ? means "zero or one times" when it follows a character, but not sure what it means in this context.

LastEditorDisplayName: levik

OwnerDisplayName: Eli


问:
How can I define a property type as being a list (list, set, array, collection) of string in my YAML Swagger definition
I am writing a swagger definition file for an API. The API is a for a GET request

```<code>/path/to/my/api:
  get:
    summary: My Custom API
    description: |
      Gets a List of FooBar IDs
    produces:
      - application/json
    tags:
      - FooBar
    responses:
      "200":
        description: successful operation
        schema:
          $ref: "#/definitions/MyCustomType"
</code>```

...

```<code>MyCustomType:
  type: object
  properties:
    myCustomObject
      type: ??? # list of string?
</code>```

答:
None of these comments really seem to answer the question -- How do you define a SET of items in OpenAPI/Swagger?

An array of strings is not the same as a SET

An array of unique strings is not the same as SET

A set is essentially an array of unrepeated enum values.

Given possible string values of facebook, pinterest, twitter, a field named share_type could have values containing one or more of them, ex:

Valid

facebook
twitter
facebook, twitter
facebook, twitter, pinterest

Invalid Items

instagram
facebook, instagram
pinterest, pinterest

Another important distinction is that the values cannot be repeated. This is where the uniqueItems directive can be helpful.

So given the example above, here is what that OpenAPI spec might look like:

share_type:
  type: array
  uniqueItems: true
  items:
    type: string
    enum:
      - facebook
      - pinterest
      - twitter
```

Body:
I am writing a swagger definition file for an API. The API is a for a GET request

/path/to/my/api:
  get:
    summary: My Custom API
    description: |
      Gets a List of FooBar IDs
    produces:
      - application/json
    tags:
      - FooBar
    responses:
      "200":
        description: successful operation
        schema:
          $ref: "#/definitions/MyCustomType"

...

MyCustomType:
  type: object
  properties:
    myCustomObject
      type: ??? # list of string?


问:
How to add a google map to an existing android studio project
I am create an android app where am using android studio as my programming platform. My question is that whether it is possible to create a google map in an EXISTING android studio project. I have seen many places of how to create to a google map in and independent project. But none have shown me how to proceed to creating a google map in an existing one. Help me please!</p>

答:
Old question but for anyone else out there who DOES NOT want to create a new google maps activity just to get the required code you will need to do the following.

In your app build.gradlefile add the following import:

implementation 'com.google.android.gms:play-services-maps:17.0.0'

Under res/values folder create a new file called google_maps_api.xml and enter the following:

```<code><resources>
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE</string>
</resources>
</code>```

Make sure to replace YOUR_KEY_HERE with your google API key.

Next add the following to your AndroidManifest.xml within the application tag:

```<code> <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
</code>```

You can now add the google maps fragment with the following code:

```<code><fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</code>```

Body:
Old question but for anyone else out there who DOES NOT want to create a new google maps activity just to get the required code you will need to do the following.

In your app build.gradlefile add the following import:

implementation 'com.google.android.gms:play-services-maps:17.0.0'

Under res/values folder create a new file called google_maps_api.xml and enter the following:

<resources>
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE</string>
</resources>

Make sure to replace YOUR_KEY_HERE with your google API key.

Next add the following to your AndroidManifest.xml within the application tag:

 <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

You can now add the google maps fragment with the following code:

<fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />


问:
How do I handle the UnhandledPromiseRejectionWarning in Node.JS
I have a few methods that use the request module to get images from URLs and returns it as a Promise, it works but when the image isn't found it rejects the promise with the status code 404. I looked into that warning and it is said that to handle the rejection you have to setup a catch callback after then() but I don't use then(), I use async/await.

This is the code to get the picture:

/**
 * Returns picture from S3
 * @param {String} filename Name of the file with extension
 * @returns {String} Base64 string of the file
 */
getPictureFromS3: function (filename) {
    return new Promise((resolve, reject) => {
        let url = this.getURLFromS3(filename);
        request(url, (err, res, body) => {
            if (err) reject(err);
            if (res.statusCode !== 200) {
                reject(`Invalid status code <${res.statusCode}>`);
            }
            resolve(new Buffer.from(body).toString('base64'));
        });
    });
}
```

<p>And this is how I call the method:</p>

<pre class="lang-js prettyprint-override"><code>try{
    socket.on('server get pictures', () => db.getPictures(data=>{
        if(data!==null){
            data.forEach(async e=>{
                let picture = await utils.getPictureFromS3(e.getFilename());
            });
        }
    }));
}catch(err){
    console.log(err);
}
</code>```

Full warning:

```<code>(node:256) UnhandledPromiseRejectionWarning: Invalid status code <404>
(node:256) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which
was not handled with .catch(). (rejection id: 1)
(node:256) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

Using Node v10.14.2.

答:
There are two problems here

You care trying to do async operation inside forEach which doesn't work with promises. You need to use for..of loop or Promise.all if you can do things in parallel.

The exception is raise inside the listener so it will not bubble up outside so your catch wouldn't be executed. You need to move your try catch inside. Something like this

```<code>socket.on("server get pictures", () =>
  db.getPictures(data => {
    if (data !== null) {
      for(const e of data) {
        try {
          let picture = await utils.getPictureFromS3(e.getFilename());
        } catch (err) {
          console.log(err);
        }
      }
    }
  })
);

</code>```

Body:
I have a few methods that use the request module to get images from URLs and returns it as a Promise, it works but when the image isn't found it rejects the promise with the status code 404. I looked into that warning and it is said that to handle the rejection you have to setup a catch callback after then() but I don't use then(), I use async/await.

This is the code to get the picture:

/**
 * Returns picture from S3
 * @param {String} filename Name of the file with extension
 * @returns {String} Base64 string of the file
 */
getPictureFromS3: function (filename) {
    return new Promise((resolve, reject) => {
        let url = this.getURLFromS3(filename);
        request(url, (err, res, body) => {
            if (err) reject(err);
            if (res.statusCode !== 200) {
                reject(`Invalid status code <${res.statusCode}>`);
            }
            resolve(new Buffer.from(body).toString('base64'));
        });
    });
}

And this is how I call the method:

try{
    socket.on('server get pictures', () => db.getPictures(data=>{
        if(data!==null){
            data.forEach(async e=>{
                let picture = await utils.getPictureFromS3(e.getFilename());
            });
        }
    }));
}catch(err){
    console.log(err);
}

Full warning:

(node:256) UnhandledPromiseRejectionWarning: Invalid status code <404>
(node:256) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which
was not handled with .catch(). (rejection id: 1)
(node:256) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Using Node v10.14.2.

Body:
There are two problems here

You care trying to do async operation inside forEach which doesn't work with promises. You need to use for..of loop or Promise.all if you can do things in parallel.

The exception is raise inside the listener so it will not bubble up outside so your catch wouldn't be executed. You need to move your try catch inside. Something like this

socket.on("server get pictures", () =>
  db.getPictures(data => {
    if (data !== null) {
      for(const e of data) {
        try {
          let picture = await utils.getPictureFromS3(e.getFilename());
        } catch (err) {
          console.log(err);
        }
      }
    }
  })
);


问:
Purpose of mapDispatchToProps in Redux land
Is there a purpose to mapDispatchToProps:

```<code>const mapDispatchToProps = dispatch => {
  return {
    addProductToCart: product => dispatch(addProductToCart(product))
  }
}
</code>```

or is it acceptable to just do this:

```<code>const mapDispatchToProps = dispatch => {
  return {dispatch};
}
</code>```

and then just call:

props.dispatch() in the component

答:
Without mapDispatchToProps:-

```<code>this.props.dispatch(showAlert(message));

</code>```

With mapDispatchToProps:-

```<code>this.props.onShowAlert(message);
</code>```

THis was the main perpose of mapDispatchToProps

Body:
Is there a purpose to mapDispatchToProps:

const mapDispatchToProps = dispatch => {
  return {
    addProductToCart: product => dispatch(addProductToCart(product))
  }
}

or is it acceptable to just do this:

const mapDispatchToProps = dispatch => {
  return {dispatch};
}

and then just call:

props.dispatch() in the component

Body:
Without mapDispatchToProps:-

this.props.dispatch(showAlert(message));

With mapDispatchToProps:-

this.props.onShowAlert(message);

THis was the main perpose of mapDispatchToProps


问:
How to fix canvas size in Mapbox GL?
I'm using Mapbox GL to show a map and crop a fixed size image from the center of it. It works great for a particular resolution I designed it (1920x1080) but when I started to make the page responsive where the map styles width and height changes, the canvas size also started to change!

So, when I crop the image the size should be always different because 300px on a 900px canvas it's not the same map area as 300px on a 2000px canvas. The canvas size even changes drastically if I change the device type from Desktop to Mobile in Chrome.

Is there any way to make the canvas DOM size fixed while scaling the entire map with CSS attributes as it's done on a normal canvas? I tried doing trackResize: false and the canvas DOM size stays fixed but the map is not scaled to fit the container neither.

答:
The solution </p>

```<code><div
    ref={el => this.mapContainer = el}
    style={{
            position: 'absolute',
            top: 0,
            bottom: 0,
            width: '100%',
            height: '100vh',
     }}
 />
</code>```

Title: How to fix canvas size in Mapbox GL?

Body:
The solution

<div
    ref={el => this.mapContainer = el}
    style={{
            position: 'absolute',
            top: 0,
            bottom: 0,
            width: '100%',
            height: '100vh',
     }}
 />


问:
Visualization using Desktop Power BI, Python and flask
I am using flask to create a web api from python functions. My code:

```<code>from flask import Flask, render_template
import pandas as pd
import numpy as np

app = Flask(__name__)

@app.route("/store_on_promo_df")
def store_on_promo_df():

    data_df = pd.read_csv(data_path, header=0)

    is_on_promo_series = data_df['IsPromo'] == True
    data_on_promo_df = data_df.loc[is_on_promo_series]

    return data_on_promo_df
</code>```

Consequently, I would like to have some visualization in Power BI. Therefore, I am using import data from web option in power BI.

Problem: I cannot return a dataframe using flask. And I am not sure what to return so that PowerBI reads my data properly.

Finally, please note that this is helpful in my case because I want to share big data with other teams at different location.

Any help is much appreciated!

答:
I have no experience with Power BI but with a small research, here is how you probably can do it.

Return your data as JSON format and look at this tutorial to add your endpoint to Power BI.

Body:
I am using flask to create a web api from python functions. My code:

from flask import Flask, render_template
import pandas as pd
import numpy as np

app = Flask(__name__)

@app.route("/store_on_promo_df")
def store_on_promo_df():

    data_df = pd.read_csv(data_path, header=0)

    is_on_promo_series = data_df['IsPromo'] == True
    data_on_promo_df = data_df.loc[is_on_promo_series]

    return data_on_promo_df

Consequently, I would like to have some visualization in Power BI. Therefore, I am using import data from web option in power BI.

Problem: I cannot return a dataframe using flask. And I am not sure what to return so that PowerBI reads my data properly.

Finally, please note that this is helpful in my case because I want to share big data with other teams at different location.

Any help is much appreciated!


问:
Is there a way to recover objects from a set in the same order as passed?
I need to recover the elements of a java Set collection interface in the same order they were passed into the set.

How is it possible in java

答:
How about LinkedHashSet ?

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)


问:
Problem with IBM Notes ODBC Connections not clearing out on Domino 9 server
I support an older Lotus Notes application that uses ODBC to connect to Oracle for reading and writing purposes.  Each of the connection objects are being set to Nothing when their routine is complete, but, for some reason, Domino will not drop the connections.  This causes us to have to reboot the Domino server that application resides on every day.  Sometimes, once a day is not enough to keep the program from grinding to a near standstill.  Does anyone have any ideas how to get those connections to drop when the script is done processing?

MJ

答:
It turns out that the ODBC class has a disconnect method.  Who knew?  Sorry to waste everyones's time.  I put in the disconnect and problem was solved.  Not sure why I never noticed it before.  Anyway, thanks for the replies.

MJ


问:
PHP session persistence Different PHP applications, Same host server
I'm, not sure if this is a common use-case, but I'm a normal kind of guy, so I can't believe this is unusual:

I have a server running a LAMP stack.  There are a few PHP applications on the server.  I spotted the other day that two completely different apps are sharing session information.  WTF?!  I get that they do, but why? they trust the server, but why does the server assume that the two apps trust each other?

okay: #1 fix is for one or both use session_name().  That's superb and it does fix the issue if either or both of them do this and neither tries to get the others session by setting the name, but is there a fix where both apps are hostile to each other?  Is there something at the PHP level that can make the sessions independent, regardless of anything the apps might try to do?

Essentially nothing that
https://www.server.com/app1/index.php  does should get access to session info of
https://www.server.com/app2/index.php  etc.....

I thought that setting the path using session_set_cookie_params() would sort this out, but naah, setting this variable to a limited path actually has no obvious effect which is interesting - both apps #can still get to the session stuff or the other - interesting!

I can't believe this is a new issue and yet I don't spot a fix....

Cheers,

turbotas

Example code:

<?php
session_set_cookie_params(3600,"/webapps/test1");
session_name("mysession");
session_start(); ?>

<?php echo session_id(); ?>

```

imagine this code in webapps/test1 and exactly the same in webapps/test2.  I would not expect test2 to be able to use the test1 session state simply by stating a directory outside it's own installation point - I would expect PHP to protect against that.  It doesn't - I get the same session.

答:
As you're coding the different applications, you need to make sure that each one saves its session-information (server side) in different places.  The session.save_path configuration variable, for instance, specifies the host-side directory if you are saving the sessions using files.  If you're storing the session information in a database table, you should be using different tables or more likely different databases.

Thus, even if an identical session identifier is somehow produced, it will produce different results for each application because each one is referencing its own distinct host-side source.

Body:
I'm, not sure if this is a common use-case, but I'm a normal kind of guy, so I can't believe this is unusual:

I have a server running a LAMP stack.  There are a few PHP applications on the server.  I spotted the other day that two completely different apps are sharing session information.  WTF?!  I get that they do, but why? they trust the server, but why does the server assume that the two apps trust each other?

okay: #1 fix is for one or both use session_name().  That's superb and it does fix the issue if either or both of them do this and neither tries to get the others session by setting the name, but is there a fix where both apps are hostile to each other?  Is there something at the PHP level that can make the sessions independent, regardless of anything the apps might try to do?

Essentially nothing that
https://www.server.com/app1/index.php  does should get access to session info of
https://www.server.com/app2/index.php  etc.....

I thought that setting the path using session_set_cookie_params() would sort this out, but naah, setting this variable to a limited path actually has no obvious effect which is interesting - both apps #can still get to the session stuff or the other - interesting!

I can't believe this is a new issue and yet I don't spot a fix....

Cheers,

turbotas

Example code:

<?php
session_set_cookie_params(3600,"/webapps/test1");
session_name("mysession");
session_start(); ?>

<?php echo session_id(); ?>

imagine this code in webapps/test1 and exactly the same in webapps/test2.  I would not expect test2 to be able to use the test1 session state simply by stating a directory outside it's own installation point - I would expect PHP to protect against that.  It doesn't - I get the same session.


问:
Is there a situation that the function CreateFile returns INVALID_HANDLE_VALUE and GetLastError() returns ERROR_ALREADY_EXISTS
I searched MSDN about

```<code>HANDLE WINAPI CreateFile(
  _In_     LPCTSTR               lpFileName,
  _In_     DWORD                 dwDesiredAccess,
  _In_     DWORD                 dwShareMode,
  _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  _In_     DWORD                 dwCreationDisposition,
  _In_     DWORD                 dwFlagsAndAttributes,
  _In_opt_ HANDLE                hTemplateFile
);
</code>```

and if dwCreationDisposition == CREATE_ALWAYS or OPEN_ALWAYS, it says

Creates a new file, always. If the specified file exists and is
  writable, the function overwrites the file, the function succeeds, and
  last-error code is set to ERROR_ALREADY_EXISTS (183). If the specified
  file does not exist and is a valid path, a new file is created, the
  function succeeds, and the last-error code is set to zero. For more
  information, see the Remarks section of this topic.

and

Opens a file, always. If the specified file exists, the function
  succeeds and the last-error code is set to ERROR_ALREADY_EXISTS (183).
  If the specified file does not exist and is a valid path to a writable
  location, the function creates a file and the last-error code is set
  to zero.

So I'm not sure that if the function failed, would GetLastError() be ERROR_ALREADY_EXISTS ?

Please give me an example if so.

Thanks a lot.

答:
Apparently you can have the call to CreateFile with OPEN_ALWAYS fail returning NULL handle and get error 183. This happens to me when I call CreateFile with OPEN_ALWAYS specifying a file in a directory that doesn't exit.

example:
C:\NonExistingDirectory\Myfile.txt

I'm not sure if this is a consistent behaviour on different Windows versions. I got it on Windows 10 using Visual Studio 2015.

Body:
I searched MSDN about

HANDLE WINAPI CreateFile(
  _In_     LPCTSTR               lpFileName,
  _In_     DWORD                 dwDesiredAccess,
  _In_     DWORD                 dwShareMode,
  _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  _In_     DWORD                 dwCreationDisposition,
  _In_     DWORD                 dwFlagsAndAttributes,
  _In_opt_ HANDLE                hTemplateFile
);

and if dwCreationDisposition == CREATE_ALWAYS or OPEN_ALWAYS, it says

Creates a new file, always. If the specified file exists and is
  writable, the function overwrites the file, the function succeeds, and
  last-error code is set to ERROR_ALREADY_EXISTS (183). If the specified
  file does not exist and is a valid path, a new file is created, the
  function succeeds, and the last-error code is set to zero. For more
  information, see the Remarks section of this topic.

and

Opens a file, always. If the specified file exists, the function
  succeeds and the last-error code is set to ERROR_ALREADY_EXISTS (183).
  If the specified file does not exist and is a valid path to a writable
  location, the function creates a file and the last-error code is set
  to zero.

So I'm not sure that if the function failed, would GetLastError() be ERROR_ALREADY_EXISTS ?

Please give me an example if so.

Thanks a lot.


问:
Is there a Python Package to support MySQL with Pycharm
so I was just wondering. I am designing this Kivy app but I currently use .txt files which is messy and just seems like a huge waste of time. I was wondering if there was a package that could read/write/create MySQL databases with python. However, I do use Pycharm and I read a while back that the free version the one I use. May have some limitations with this.

答:
You could use the mysql package for this.

https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html

The PyCharm support for MySQL is just for viewing the data in the database as a programmer or for debugging.


问:
How to save costs when calling BigQuery from a Google Cloud Function
I have 10,000 images added to my google storage bucket on a daily basis.

This bucket has a cloud function event which triggers BigQuery scans

My cloud function checks for existing records in BigQuery 10,000 times a day, which is running up my BigQuery bill to unsustainable amount.

I would like to know if there is a way to query the database once and store the results into a variable which can then be available for all triggered cloud functions?

In summary: query DB  once, store query results, use query results for all cloud function invocations. This way I do not hit BigQuery 10,000+ times a day.

P.S. BigQuery processed 288 Terabytes of data which is an insane bill $$$$$$$$$$$$

答:
That's an insane bill.

Step 1: Set up cost controls. You will never deal with an insane bill again.

How do I turn on cost controls on BigQuery?

Step 2: Instead of querying again, check out the results of the previous job. If it's the same query and data, the same results are still valid. The API method is jobs.getQueryResults().

https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/getQueryResults

Step 3: Cluster your tables. You'll probably find 90% additional cost reductions.

https://medium.com/google-cloud/bigquery-optimized-cluster-your-tables-65e2f684594b


问:
Python 3.7 - Fast way to concatenate strings and write them to disk
Is there a better implementation for:

```<code>file = open("./myFile.txt","w+")
for doc in allDocuments: #around 35 million documents
    file.write(str(doc.number)+"\r\n")
f.close()
</code>```

Currently this implementation is taking 20sec per file

答:
You could buffer the output and write in blocks:</p>

```<code>with open("./myFile.txt", "w") as output:
    lines = []
    for doc in allDocuments:
        lines.append(f"{doc.number}\r\n")
        if len(lines) > 1000:
            output.writelines(lines)
            lines = []
    output.writelines(lines)
</code>```

Body:
Is there a better implementation for:

file = open("./myFile.txt","w+")
for doc in allDocuments: #around 35 million documents
    file.write(str(doc.number)+"\r\n")
f.close()

Currently this implementation is taking 20sec per file

Body:
You could buffer the output and write in blocks:

with open("./myFile.txt", "w") as output:
    lines = []
    for doc in allDocuments:
        lines.append(f"{doc.number}\r\n")
        if len(lines) > 1000:
            output.writelines(lines)
            lines = []
    output.writelines(lines)


问:
CUDA missing host_defines.h centos 7
I'm trying to compile some samples of the CUDA toolkit V6.5 in the environnement Nsight Eclipse edition 6.5 under centos 7.0.

My Nvidia Card is a Quadro K2000.

So my problem is when I try to build one of the samples (in toolkit cuda 6.5):
the following message appears in the Console and I don't know why :

```<code>make all
Building target: ex3
Invoking: NVCC Linker
/usr/bin/nvcc --cudart static -L/usr/include/cuda --relocatable-device-code=false -gencode arch=compute_20,code=compute_20 -gencode arch=compute_20,code=sm_20 -link -o  "ex3"  ./src/matrixMulCUBLAS.o   -lcublas
/usr/bin/crt/link.stub:2:26: erreur fatale: host_defines.h : Aucun fichier ou dossier de ce type
 #include "host_defines.h"
                          ^
compilation terminée.
make: *** [ex3] Erreur 1

17:17:30 Build Finished (took 57ms)
</code>```

Can anybody help me please ?

答: If you are missing these headers, installing cuda-nvcc-10-0 or nvidia-cuda-dev package might help.

Title: CUDA missing host_defines.h centos 7

Body:
I'm trying to compile some samples of the CUDA toolkit V6.5 in the environnement Nsight Eclipse edition 6.5 under centos 7.0.

My Nvidia Card is a Quadro K2000.

So my problem is when I try to build one of the samples (in toolkit cuda 6.5):
the following message appears in the Console and I don't know why :

make all
Building target: ex3
Invoking: NVCC Linker
/usr/bin/nvcc --cudart static -L/usr/include/cuda --relocatable-device-code=false -gencode arch=compute_20,code=compute_20 -gencode arch=compute_20,code=sm_20 -link -o  "ex3"  ./src/matrixMulCUBLAS.o   -lcublas
/usr/bin/crt/link.stub:2:26: erreur fatale: host_defines.h : Aucun fichier ou dossier de ce type
 #include "host_defines.h"
                          ^
compilation terminée.
make: *** [ex3] Erreur 1

17:17:30 Build Finished (took 57ms)

Can anybody help me please ?


问:
Javafx Formatting decimal number textfield
I have a problem with formatting a currency decimal number in TextField. I set the TextFormatter with a class DecimalFormatter that extend a StringConverter which converts a BigDecimal to String and vice-versa.
When I should change the value, if delete all the data and insert a new completed value it works, but if I have to add/change a part of value e.g. 13.00 in 13.10 the change is not applied and re-proposes the old value 13.00.

How can I solve it?

Thank you

public class DecimalFormatter extends StringConverter<BigDecimal> {

    private NumberFormat numberFormat;

....

    @Override
    public String toString(BigDecimal value) {
        if ( value == null )
            value = new BigDecimal();
        return numberFormat.format(value.doubleValue());
    }

    @Override
    public BigDecimal fromString(String value) {
        return new BigDecimal(value);
    }

}

....

tfDecimal.setTextFormatter(new DecimalFormatter());

```

答:
My intention was to manage amounts with decimals separated by a comma in a textfield. I added a filter to allow only double amounts. The complete code:</p>

```<code>
public class DecimalFormatter extends StringConverter {

    private final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ITALY);

    public DecimalFormatter(int fractionsLenght) {
        numberFormat.setMaximumFractionDigits(fractionsLenght);
        numberFormat.setMinimumFractionDigits(fractionsLenght);
    }

    public DecimalFormatter() {
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMinimumFractionDigits(2);
    }

    @Override
    public String toString(BigDecimal value) {
        if ( value == null )
            value = new BigDecimal(0);
        return numberFormat.format(value.doubleValue());
    }

    @Override
    public Decimal fromString(String value) {
        value = value.replaceAll(",", ".");
        return new BigDecimal(value);
    }
}
public class DecimalFilter implements UnaryOperator {

    private static final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();

    private Pattern DIGIT_PATTERN;

    public DecimalFilter() {
        DIGIT_PATTERN = Pattern.compile("-?\\d*(\\" + DECIMAL_SEPARATOR  + "\\d{0,2})?");
    }

    public DecimalFilter(int fractionsLenght) {
        DIGIT_PATTERN = Pattern.compile("-?\\d*(\\" + DECIMAL_SEPARATOR  + "\\d{0," + fractionsLenght + "})?");
    }

    @Override
    public Change apply(TextFormatter.Change aT) {
        return DIGIT_PATTERN.matcher(aT.getText()).matches() ? aT : null;
    }
}

tfDecimalValue.setTextFormatter(
    new TextFormatter(new DecimalFormatter(), new BigDecimal(0), new DecimalFilter()));
</code>```

Body:
My intention was to manage amounts with decimals separated by a comma in a textfield. I added a filter to allow only double amounts. The complete code:

public class DecimalFormatter extends StringConverter {

    private final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ITALY);

    public DecimalFormatter(int fractionsLenght) {
        numberFormat.setMaximumFractionDigits(fractionsLenght);
        numberFormat.setMinimumFractionDigits(fractionsLenght);
    }

    public DecimalFormatter() {
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMinimumFractionDigits(2);
    }

    @Override
    public String toString(BigDecimal value) {
        if ( value == null )
            value = new BigDecimal(0);
        return numberFormat.format(value.doubleValue());
    }

    @Override
    public Decimal fromString(String value) {
        value = value.replaceAll(",", ".");
        return new BigDecimal(value);
    }
}
public class DecimalFilter implements UnaryOperator {

    private static final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();

    private Pattern DIGIT_PATTERN;

    public DecimalFilter() {
        DIGIT_PATTERN = Pattern.compile("-?\\d*(\\" + DECIMAL_SEPARATOR  + "\\d{0,2})?");
    }

    public DecimalFilter(int fractionsLenght) {
        DIGIT_PATTERN = Pattern.compile("-?\\d*(\\" + DECIMAL_SEPARATOR  + "\\d{0," + fractionsLenght + "})?");
    }

    @Override
    public Change apply(TextFormatter.Change aT) {
        return DIGIT_PATTERN.matcher(aT.getText()).matches() ? aT : null;
    }
}

tfDecimalValue.setTextFormatter(
    new TextFormatter(new DecimalFormatter(), new BigDecimal(0), new DecimalFilter()));


问:
How To Manage Routing in Single Page website Angular 9
i have a single page website created by angular and i need to create routing between components same page

this is routing.module:

```<code>export const routes: Routes = [
  {
    path: '',
    component: AppComponent,
    pathMatch: 'full',
  },
  { path: 'about', component: AboutComponent },
  { path: 'services', component: ServicesComponent },
  { path: 'work', component: WorkComponent }

];
</code>```

and next is navbar.Component

```<code>  <li class="nav-item active">
                            <a class="nav-link" [routerLink]="['/']" routerLinkActive="router-link-active">{{'home' |translate}} <span class="sr-only">(current)</span></a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" [routerLink]="['/about']" routerLinkActive="router-link-active">{{'about' |translate}}</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" [routerLink]="['/services']" routerLinkActive="router-link-active">{{'ourServices' |translate}}</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" [routerLink]="['/work']" routerLinkActive="router-link-active">{{'ourWork' |translate}}</a>
                        </li>
</code>```

and next is app.component.html

```<code><app-headder-video [contact]="contact"></app-headder-video>
<app-about></app-about>
<app-services></app-services>
<app-work></app-work>
<app-footer [contact]="contact"></app-footer>```
```

答:
add router-outlet to the  app.component like this</p>

```<code><app-headder-video [contact]="contact"></app-headder-video>
<router-outlet></router-outlet>
<app-footer [contact]="contact"></app-footer>```
</code>```

Body:
i have a single page website created by angular and i need to create routing between components same page

this is routing.module:

export const routes: Routes = [
  {
    path: '',
    component: AppComponent,
    pathMatch: 'full',
  },
  { path: 'about', component: AboutComponent },
  { path: 'services', component: ServicesComponent },
  { path: 'work', component: WorkComponent }

];

and next is navbar.Component

                            {{'home' |translate}} (current)

                            {{'about' |translate}}

                            {{'ourServices' |translate}}

                            {{'ourWork' |translate}}

and next is app.component.html

<app-headder-video [contact]="contact"></app-headder-video>
<app-about></app-about>
<app-services></app-services>
<app-work></app-work>
<app-footer [contact]="contact"></app-footer>```

Body:
add router-outlet to the  app.component like this

<app-headder-video [contact]="contact"></app-headder-video>
<router-outlet></router-outlet>
<app-footer [contact]="contact"></app-footer>```


问:
How to find the total of an 2d array?
Have to input numbers of students & subjects. (Using random marks) I want to print the total marks of students & the total marks of subjects. Here is the code given below.

```<code>import java.util.*;
class Example{
    public static void readMarks(int[][] x){
        Random r=new Random();
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                x[i][j]=r.nextInt(101);
            }
        }
    }
    public static void printMarks(int[][] x){
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                System.out.print(x[i][j]+"  ");
            }
            System.out.println();
        }
    }
    public static int[] findStudenTot(int[][] x){
        int tot[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot[i]+=x[i][j];
            }
        }
        return tot;
    }
    public static int[] findSubjectTot(int[][] x){
        int tot1[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot1[i]+=x[i][j];
            }
        }
        return tot1;
    }

    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        System.out.print("Input no of students : ");
        final int N=input.nextInt();

        System.out.print("Input no of subject : ");
        final int S=input.nextInt();

        int[][] marks=new int[N][S];
        readMarks(marks);

        int[] stTotal=findStudenTot(marks);
        int[] subTotal=findSubjectTot(marks);

        System.out.println("total is : "+stTotal);
        System.out.println("total is : "+subTotal);

    }
}
</code>```

How to print stTotal , subTotal?

If we assume enter 5 for both inputs this output total is : [I@3d4eac69 ...why?
what are these characters & how can I avoid these?

答:
How to print stTotal , subTotal?

Do it as follows:

```<code>System.out.println("total is : " + Arrays.toString(stTotal));
System.out.println("total is : " + Arrays.toString(subTotal));
</code>```

[Update]

Replace the definition of findSubjectTot with the following:

```<code>public static int[] findSubjectTot(int[][] x) {
    int tot[] = new int[x[0].length];

    for (int i = 0; i < x[0].length; i++) {
        for (int j = 0; j < x.length; j++) {
            tot[i] += x[j][i];
        }
    }
    return tot;
}
</code>```

Title: How to find the total of an 2d array?

Body:
Have to input numbers of students & subjects. (Using random marks) I want to print the total marks of students & the total marks of subjects. Here is the code given below.

import java.util.*;
class Example{
    public static void readMarks(int[][] x){
        Random r=new Random();
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                x[i][j]=r.nextInt(101);
            }
        }
    }
    public static void printMarks(int[][] x){
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                System.out.print(x[i][j]+"  ");
            }
            System.out.println();
        }
    }
    public static int[] findStudenTot(int[][] x){
        int tot[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot[i]+=x[i][j];
            }
        }
        return tot;
    }
    public static int[] findSubjectTot(int[][] x){
        int tot1[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot1[i]+=x[i][j];
            }
        }
        return tot1;
    }

    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        System.out.print("Input no of students : ");
        final int N=input.nextInt();

        System.out.print("Input no of subject : ");
        final int S=input.nextInt();

        int[][] marks=new int[N][S];
        readMarks(marks);

        int[] stTotal=findStudenTot(marks);
        int[] subTotal=findSubjectTot(marks);

        System.out.println("total is : "+stTotal);
        System.out.println("total is : "+subTotal);

    }
}

How to print stTotal , subTotal?

If we assume enter 5 for both inputs this output total is : [I@3d4eac69 ...why?
what are these characters & how can I avoid these?

Body:
How to print stTotal , subTotal?

Do it as follows:

System.out.println("total is : " + Arrays.toString(stTotal));
System.out.println("total is : " + Arrays.toString(subTotal));

[Update]

Replace the definition of findSubjectTot with the following:

public static int[] findSubjectTot(int[][] x) {
    int tot[] = new int[x[0].length];

    for (int i = 0; i < x[0].length; i++) {
        for (int j = 0; j < x.length; j++) {
            tot[i] += x[j][i];
        }
    }
    return tot;
}


问:
Using Fabric 2 and Fabric 3 in the same project
I am currently using Fabric3 in a python project and I want to use the azure-cli package. However when I install the package, it appears to break my Fabric3 install:

root ~ $ fab --version

Traceback (most recent call last):

File "/opt/rh/rh-python36/root/usr/bin/fab", line 7, in

from Fabric3.main import program

ModuleNotFoundError: No module named 'Fabric3'

I noticed that the pip install of azure-cli appears to install fabric (2.5.0), and this appears to overwrite some of the fabric files within the "/opt/rh/rh-python36/root/usrbin/fab" script and the "/opt/rh/rh-python36/root/usr/lib64/python3.6/site-packages/fabric/" directory.

So my question is, is there a way to run different versions of Fabric within the same project?

Thanks in advance

答:
I found a way to do this by using python virtual environments.

I created a virtual env, activated the virtual env, installed the pip package, deactivated the virtual env, then used Fabric 3 to call the function in the venv.

```<code>python -m venv azure_cli_venv
. azure_cli_venv/bin/activate
pip install azure-cli
deactivate
</code>```

Fabric3 local call:

```<code>local(f'./azure_cli_venv/bin/az --help
</code>```

Body:
I found a way to do this by using python virtual environments.

I created a virtual env, activated the virtual env, installed the pip package, deactivated the virtual env, then used Fabric 3 to call the function in the venv.

python -m venv azure_cli_venv
. azure_cli_venv/bin/activate
pip install azure-cli
deactivate

Fabric3 local call:

local(f'./azure_cli_venv/bin/az --help


问:
Issues with Setting up gcs backend for terraform
I have been trying to setup a terraform backend to store state files in GCS bucket. I have created a service account which is a project owner and having gcs bucket storage admin access, but still am facing below error:

```<code>Initializing the backend...
Error loading state: 2 errors occurred:
        * writing "gs://terraform-ubuntu-state-maintain/gcp/terraform.tfstate/default.tflock" failed: googleapi: Error 403: Insufficient Permission, insufficientPer
missions
        * storage: object doesn't exist.
</code>```

p.s: the gcs bucket is also created already with the prefix path "gcp".Also permission is given to the service account.

答:
I ran into a similar issue, and it turned out to be the bucket name I was using.
GCS bucket names (like S3 bucket names) are GLOBAL, so often permission-related errors like this:

```<code>Error: Error inspecting states in the "gcs" backend:
    querying Cloud Storage failed: googleapi: Error 403: terraform@xxx.iam.gserviceaccount.com does not have storage.objects.list access to terraform-state., forbidden
</code>```

are NOT permission related, but really errors because you are trying to read from other peoples buckets (a bucket name that someone else is already using).

P.S. the OG has that bucket named terraform-state, which must be getting LOTS of API requests for listing / creating objects...

Body:
I have been trying to setup a terraform backend to store state files in GCS bucket. I have created a service account which is a project owner and having gcs bucket storage admin access, but still am facing below error:

Initializing the backend...
Error loading state: 2 errors occurred:
        * writing "gs://terraform-ubuntu-state-maintain/gcp/terraform.tfstate/default.tflock" failed: googleapi: Error 403: Insufficient Permission, insufficientPer
missions
        * storage: object doesn't exist.

p.s: the gcs bucket is also created already with the prefix path "gcp".Also permission is given to the service account.

Body:
I ran into a similar issue, and it turned out to be the bucket name I was using.
GCS bucket names (like S3 bucket names) are GLOBAL, so often permission-related errors like this:

Error: Error inspecting states in the "gcs" backend:
    querying Cloud Storage failed: googleapi: Error 403: terraform@xxx.iam.gserviceaccount.com does not have storage.objects.list access to terraform-state., forbidden

are NOT permission related, but really errors because you are trying to read from other peoples buckets (a bucket name that someone else is already using).

P.S. the OG has that bucket named terraform-state, which must be getting LOTS of API requests for listing / creating objects...


问:
Serverless federated application state
Is it possible, that by using one of the main OpenID Connect / JWT identity providers (eg. Google Federated Identity) a simple web app could read / write a key value store on that identity provider in the scope of that user?

I know that by using JWT I could claim read access to the user's email for example. But is there a way to persist arbitrary information about that user?

Eg. I make a page where the user can login with Google. After login the user can choose to save favourite colour. Is there a way to persist and retrieve this favourite colour when the user logins from another device, without the need to have that saved in my own DB?

What other alternatives would there be to achieve something like this in a way that I would not have to run and maintain a backend service?

答:
Even if this works as a short term thing it will not scale. In an OAuth architecture any real app needs to store its own data. The 2 main options are:

Store simple data such as favourite colour in UI local storage after login. Be extra sure nothing secure or important is stored here.

Store anything more permanent or sensitive in your back end. This can require the kind of insight in my User Data Management write up.

Title: Serverless federated application state


问:
Django forms question
I want to generate a form from a model. However one of the fields in the model is a CharField, whose value is mostly "Option1" "Option2" or "Option3". If the user chooses "Other" I would like him to be able to type the value of the field.

How can I do this without having to write a whole form by hand?

答:
I think one only way could be to build your own widget and associate that widget with that CharField on a ModelForm

Django Widgets

UPDATE

Here's a sample custom widget implementation that inherits from TextInput:

http://www.kryogenix.org/days/2008/03/28/overriding-a-single-field-in-the-django-admin-using-newforms-admin

Title: Django forms question


问:
Download and build Carthage locally to avoid step in the CI
I am starting using Bitrise as the CI for my iOS app but I'm on the free version, so the build have to take 10 minutes or less.

The main issue is when Bitrise builds my Carthage dependencies, is there a way where I can prebuild it in local, push everything to my repo so I can completely avoid the Carthage step?

At the moment I'm using carthage bootstrap. I have also tried carthage update --cache-builds.

Thanks

答: Use rome https://github.com/tmspzz/Rome, this provides a cloud storage based Carthage cache, your Carthage step will pull pre-built binaries from your choice of cloud storage (S3 for instance).</p>