问:
How to extract matching values from a column in a dataframe when semicolons are present in R?
I have a large dataframe of published articles for which I would like to extract all articles relating to a few authors specified in a separate list. The authors in the dataframe are grouped together in one column separated by a ; . Not all authors need to match, I would like to extract any article which has one author matched to the list. An example is below.

```<code>Title<-c("A", "B", "C")

AU<-c("Mark; John; Paul", "Simone; Lily; Poppy", "Sarah; Luke")

df<-cbind(Title, AU)

authors<-as.character(c("Mark", "John", "Luke"))

df[sapply(strsplit((as.character(df$AU)), "; "), function(x) any(authors %in% x)),]
</code>```

I would expect to return;

```<code>Title   AU
  A      Mark; John
  C      Sarah; Luke
</code>```

However with my large dataframe this command does not work to return all AU, it only returns rows which have a single AU not multiple ones.

Here is a dput from my larger dataframe of 5 rows

```<code>structure(list(AU = c("FOOKES PG;DEARMAN WR;FRANKLIN JA", "SIMS DG;DOWNHAM MAPS;MCQUILLIN J;GARDNER PS",
"TURNER BR", "BUTLER J;MARSH H;GOODARZI F", "OVERTON M"), TI = c("SOME ENGINEERING ASPECTS OF ROCK WEATHERING WITH FIELD EXAMPLES FROM DARTMOOR AND ELSEWHERE",
"RESPIRATORY SYNCYTIAL VIRUS INFECTION IN NORTH-EAST ENGLAND",
"TECTONIC AND CLIMATIC CONTROLS ON CONTINENTAL DEPOSITIONAL FACIES IN THE KAROO BASIN OF NORTHERN NATAL, SOUTH AFRICA",
"WORLD COALS: GENESIS OF THE WORLD'S MAJOR COALFIELDS IN RELATION TO PLATE TECTONICS",
"WEATHER AND AGRICULTURAL CHANGE IN ENGLAND, 1660-1739"), SO = c("QUARTERLY JOURNAL OF ENGINEERING GEOLOGY",
"BRITISH MEDICAL JOURNAL", "SEDIMENTARY GEOLOGY", "FUEL", "AGRICULTURAL HISTORY"
), JI = c("Q. J. ENG. GEOL.", "BRIT. MED. J.", "SEDIMENT. GEOL.",
"FUEL", "AGRICULTURAL HISTORY")
</code>```

答:
in Base-R you can access it like so </p>

```<code>df[sapply(strsplit(as.character(df$Names, "; "), function(x) any(authors %in% x)),]

    Title            Names
1     A Mark; John; Paul
3     C      Sarah; Luke
</code>```

Body:
I have a large dataframe of published articles for which I would like to extract all articles relating to a few authors specified in a separate list. The authors in the dataframe are grouped together in one column separated by a ; . Not all authors need to match, I would like to extract any article which has one author matched to the list. An example is below.

Title<-c("A", "B", "C")

AU<-c("Mark; John; Paul", "Simone; Lily; Poppy", "Sarah; Luke")

df<-cbind(Title, AU)

authors<-as.character(c("Mark", "John", "Luke"))

df[sapply(strsplit((as.character(df$AU)), "; "), function(x) any(authors %in% x)),]

I would expect to return;

Title   AU
  A      Mark; John
  C      Sarah; Luke

However with my large dataframe this command does not work to return all AU, it only returns rows which have a single AU not multiple ones.

Here is a dput from my larger dataframe of 5 rows

structure(list(AU = c("FOOKES PG;DEARMAN WR;FRANKLIN JA", "SIMS DG;DOWNHAM MAPS;MCQUILLIN J;GARDNER PS",
"TURNER BR", "BUTLER J;MARSH H;GOODARZI F", "OVERTON M"), TI = c("SOME ENGINEERING ASPECTS OF ROCK WEATHERING WITH FIELD EXAMPLES FROM DARTMOOR AND ELSEWHERE",
"RESPIRATORY SYNCYTIAL VIRUS INFECTION IN NORTH-EAST ENGLAND",
"TECTONIC AND CLIMATIC CONTROLS ON CONTINENTAL DEPOSITIONAL FACIES IN THE KAROO BASIN OF NORTHERN NATAL, SOUTH AFRICA",
"WORLD COALS: GENESIS OF THE WORLD'S MAJOR COALFIELDS IN RELATION TO PLATE TECTONICS",
"WEATHER AND AGRICULTURAL CHANGE IN ENGLAND, 1660-1739"), SO = c("QUARTERLY JOURNAL OF ENGINEERING GEOLOGY",
"BRITISH MEDICAL JOURNAL", "SEDIMENTARY GEOLOGY", "FUEL", "AGRICULTURAL HISTORY"
), JI = c("Q. J. ENG. GEOL.", "BRIT. MED. J.", "SEDIMENT. GEOL.",
"FUEL", "AGRICULTURAL HISTORY")

Body:
in Base-R you can access it like so

df[sapply(strsplit(as.character(df$Names, "; "), function(x) any(authors %in% x)),]

    Title            Names
1     A Mark; John; Paul
3     C      Sarah; Luke


来源: stackexchange

问:
Flutter Custom Rectangle
How do I draw something like below using the CustomPainter class in Flutter?

Ignore the "Batch" label in the middle. I just want to achieve that border/box shape with spaces in between the border line.

答:
Try this

You can check it on Github

Or try it on DartPad

```<code>import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ScanPainter(
            size: 200,
            color: Colors.grey,
          ),
        ),
      ),
    );
  }
}

class ScanPainter extends StatelessWidget {
  final double size;
  final Color color;

  ScanPainter({
    @required this.size,
    this.color = Colors.grey,
  }) : assert(size != null);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: size,
      width: size,
      child: Stack(
        children: [
          Positioned(
            top: 0.0,
            left: 0.0,
            child: _buildRotatedPart(
              0,
              size * .2,
            ),
          ),
          Positioned(
            top: 0.0,
            right: 0.0,
            child: _buildRotatedPart(
              1.5708,
              size * .2,
            ),
          ),
          Positioned(
            bottom: 0.0,
            right: 0.0,
            child: _buildRotatedPart(
              3.14159,
              size * .2,
            ),
          ),
          Positioned(
            bottom: 0.0,
            left: 0.0,
            child: _buildRotatedPart(
              4.71239,
              size * .2,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRotatedPart(double radians, double size) {
    return Transform.rotate(
      angle: radians,
      child: CustomPaint(
        painter: ScanCustomPainter(color: this.color),
        size: Size(size, size),
      ),
    );
  }
}

class ScanCustomPainter extends CustomPainter {
  final Color color;

  ScanCustomPainter({
    @required this.color,
  }) : assert(color != null);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()..color = this.color;
    var path = Path();
    double baseHeight = size.height;
    double baseWidth = size.width;

    path.moveTo(0, baseHeight);
    path.lineTo(0, baseHeight * .5);
    path.quadraticBezierTo(0, 0, baseWidth * .5, 0);
    path.lineTo(baseWidth, 0);
    path.lineTo(baseWidth, baseHeight * .3);
    path.lineTo(baseWidth * .6, baseHeight * .3);
    path.quadraticBezierTo(
        baseWidth * .3, baseHeight * .3, baseWidth * .3, baseHeight * .6);
    path.lineTo(baseWidth * .3, baseHeight);

    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(ScanCustomPainter oldDelegate) => false;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Flutter Custom Rectangle

Body:
Try this

You can check it on Github

Or try it on DartPad

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ScanPainter(
            size: 200,
            color: Colors.grey,
          ),
        ),
      ),
    );
  }
}

class ScanPainter extends StatelessWidget {
  final double size;
  final Color color;

  ScanPainter({
    @required this.size,
    this.color = Colors.grey,
  }) : assert(size != null);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: size,
      width: size,
      child: Stack(
        children: [
          Positioned(
            top: 0.0,
            left: 0.0,
            child: _buildRotatedPart(
              0,
              size * .2,
            ),
          ),
          Positioned(
            top: 0.0,
            right: 0.0,
            child: _buildRotatedPart(
              1.5708,
              size * .2,
            ),
          ),
          Positioned(
            bottom: 0.0,
            right: 0.0,
            child: _buildRotatedPart(
              3.14159,
              size * .2,
            ),
          ),
          Positioned(
            bottom: 0.0,
            left: 0.0,
            child: _buildRotatedPart(
              4.71239,
              size * .2,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRotatedPart(double radians, double size) {
    return Transform.rotate(
      angle: radians,
      child: CustomPaint(
        painter: ScanCustomPainter(color: this.color),
        size: Size(size, size),
      ),
    );
  }
}

class ScanCustomPainter extends CustomPainter {
  final Color color;

  ScanCustomPainter({
    @required this.color,
  }) : assert(color != null);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()..color = this.color;
    var path = Path();
    double baseHeight = size.height;
    double baseWidth = size.width;

    path.moveTo(0, baseHeight);
    path.lineTo(0, baseHeight * .5);
    path.quadraticBezierTo(0, 0, baseWidth * .5, 0);
    path.lineTo(baseWidth, 0);
    path.lineTo(baseWidth, baseHeight * .3);
    path.lineTo(baseWidth * .6, baseHeight * .3);
    path.quadraticBezierTo(
        baseWidth * .3, baseHeight * .3, baseWidth * .3, baseHeight * .6);
    path.lineTo(baseWidth * .3, baseHeight);

    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(ScanCustomPainter oldDelegate) => false;
}


问:
Code condensing/efficiency
I'm writing a string replacing function to replace smiles with there actual image location but the code is going to be very big and messy because of all the nested ifs but i cant think of a more efficient way of writing the code.</p>

```<code>Public Function exchangeSmilies(ByVal postString As String) As String
    Dim ChangedString = postString
    ChangedString.ToLower()
    If ChangedString.Contains(":)") Then
        ChangedString = ChangedString.Replace(":)", GetSmilieMapPath("smile.gif"))
        If ChangedString.Contains(":p") Then
            ChangedString = ChangedString.Replace(":p", GetSmilieMapPath("toungue.gif"))
            If ChangedString.Contains(";)") Then
                ChangedString = ChangedString.Replace(";)", GetSmilieMapPath("wink.gif"))
                If ChangedString.Contains("<3") Then
                    ChangedString = ChangedString.Replace("<3", GetSmilieMapPath("heart.gif"))
                End If
            End If
        End If
    End If
    Return ChangedString
End Function

Public Function GetSmilieMapPath(ByVal SmilieImage As String) As String
    GetSmilieMapPath = "<img src=" & Chr(34) & "../Images/Smilies/" & SmilieImage & Chr(34) & ">"
    Return GetSmilieMapPath
End Function
</code>```

答: I haven't done vb.net for a long time so I can't give you exact code. But the basic idea is this: Make a map where it contains keys of symbols (":)") and values of filename ("smile.gif"). Make that a static member variable. Then just iterate over the map and do your if (string contains map.key) then replace map.key in string with f(map.value). </p>

ContentLicense: CC BY-SA 3.0

Title: Code condensing/efficiency

Body:
I'm writing a string replacing function to replace smiles with there actual image location but the code is going to be very big and messy because of all the nested ifs but i cant think of a more efficient way of writing the code.

Public Function exchangeSmilies(ByVal postString As String) As String
    Dim ChangedString = postString
    ChangedString.ToLower()
    If ChangedString.Contains(":)") Then
        ChangedString = ChangedString.Replace(":)", GetSmilieMapPath("smile.gif"))
        If ChangedString.Contains(":p") Then
            ChangedString = ChangedString.Replace(":p", GetSmilieMapPath("toungue.gif"))
            If ChangedString.Contains(";)") Then
                ChangedString = ChangedString.Replace(";)", GetSmilieMapPath("wink.gif"))
                If ChangedString.Contains("<3") Then
                    ChangedString = ChangedString.Replace("<3", GetSmilieMapPath("heart.gif"))
                End If
            End If
        End If
    End If
    Return ChangedString
End Function

Public Function GetSmilieMapPath(ByVal SmilieImage As String) As String
    GetSmilieMapPath = ""
    Return GetSmilieMapPath
End Function


问:
React native on layout change (listen view position)
I want to listen the position of a view I am moving with a pan responder. I am using the onLayout prop to get the width, height, x and y positions, but it only runs when the first render. Any ideas?

Here is the code:

```<code>import React, { useState, useRef } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  StyleSheet,
} from "react-native";

const WINDOW_HEIGHT = Dimensions.get("window").height;

export default function Cropper({ photo }) {
  const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future

  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dy: pan.y }]),
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

 const onLayout = (event) => {
    const {
      nativeEvent: { layout },
    } = event;

    // Recalculate top and buttom views' height (setNativeProps)
  };

  const panStyle = {
    transform: pan.getTranslateTransform(),
  };

  return (
    <View style={styles.container}>
      <View style={styles.blurView} />
      <Animated.View
        onLayout={(event) => onLayout(event)}
        {...panResponder.panHandlers}
        style={[
          styles.cropper,
          panStyle,
          {
            height: height,
          },
        ]}
      />
      <View style={styles.blurView} />
      <View style={styles.bottomButtonsContainer}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  blurView: {
    flex: 1,
    width: "100%",
    backgroundColor: "rgba(0, 0, 0, .9)",
  },
  cropper: {
    width: "100%",
    backgroundColor: "red",
  },
  bottomButtonsContainer: {
    position: "absolute",
    bottom: 0,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    height: 120,
  },
});
</code>```

What I am trying to do is get the middle view position when the user moves it, and then recalculate the top and buttom views' height.

答:
if you're pulling in onLayout as a prop
export default function Cropper({ photo }) { should look like export default function Cropper({ photo, onLayout }) {

Otherwise, I agree with the response saying you likely need to declare onLayout.

Body:
I want to listen the position of a view I am moving with a pan responder. I am using the onLayout prop to get the width, height, x and y positions, but it only runs when the first render. Any ideas?

Here is the code:

import React, { useState, useRef } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  StyleSheet,
} from "react-native";

const WINDOW_HEIGHT = Dimensions.get("window").height;

export default function Cropper({ photo }) {
  const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future

  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dy: pan.y }]),
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

 const onLayout = (event) => {
    const {
      nativeEvent: { layout },
    } = event;

    // Recalculate top and buttom views' height (setNativeProps)
  };

  const panStyle = {
    transform: pan.getTranslateTransform(),
  };

  return (
    <View style={styles.container}>
      <View style={styles.blurView} />
      <Animated.View
        onLayout={(event) => onLayout(event)}
        {...panResponder.panHandlers}
        style={[
          styles.cropper,
          panStyle,
          {
            height: height,
          },
        ]}
      />
      <View style={styles.blurView} />
      <View style={styles.bottomButtonsContainer}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  blurView: {
    flex: 1,
    width: "100%",
    backgroundColor: "rgba(0, 0, 0, .9)",
  },
  cropper: {
    width: "100%",
    backgroundColor: "red",
  },
  bottomButtonsContainer: {
    position: "absolute",
    bottom: 0,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    height: 120,
  },
});

What I am trying to do is get the middle view position when the user moves it, and then recalculate the top and buttom views' height.


问:
dots and whitespaces in filepath location, importing file in pandas
I have a file in windows remote server which I'm trying to read in a pandas dataframe. The file path has white spaces and dots in it. Following is what I'm trying to do but its not working for me.

file_location = '\\servername\foldername\folder name\5. folder_name\foldername - 0331v7\filename.txt'

df = pd.read_csv(filelocation, sep = '|')

I'm getting the no such file exists error. I tried to prefix the file_location string with r and thats not working too. I would appreciate if someone could help me with this.

答:
Backslahes are used to tell the parser that the next character should be interpreted as an escapce sequence and not a regular character/operator.
For example if you want to print " you have to use the escape sequence \":

```<code>print("This is a quotation mark: \".")
</code>```

Output:

```<code>This is a quotation mark: ".
</code>```

If you are using a single backslash the next character is marked as escape sequence and therefore makes the path invalid. To get around this you can either use the escape sequence for backslash wich is \ or in most cases you can use a forward slash as most librarys automatically convert it to a backslash on windows.

Body:
Backslahes are used to tell the parser that the next character should be interpreted as an escapce sequence and not a regular character/operator.
For example if you want to print " you have to use the escape sequence \":

print("This is a quotation mark: \".")

Output:

This is a quotation mark: ".

If you are using a single backslash the next character is marked as escape sequence and therefore makes the path invalid. To get around this you can either use the escape sequence for backslash wich is \ or in most cases you can use a forward slash as most librarys automatically convert it to a backslash on windows.


问:
Spring security applying filters to specified endpoint and HttpMethod
I've been trying to add a custom filter in specific operations on a given rest controller.
In my configuration I'm trying to add this filter to only specific HttpMethods like : POST,DELETE, PATCH.
With this I wanted to set a configuration that would allow all GET operations to be ignored by the filter, but it seems that the filter is always trying to authenticate GET operations.
This is my base configure method on my WebSecurityConfigurerAdapter:

```<code>@Override
   protected void configure(HttpSecurity http) throws Exception {
       http
               .formLogin().disable()
               .csrf().disable()
               .logout().disable()
               .addFilter(new CustomSecurityFilter(authenticationManager()))
               .authorizeRequests()
               .antMatchers(HttpMethod.DELETE, "/v1/call/{id}").hasAnyRole("ADMIN,EDITOR")
               .antMatchers(HttpMethod.PATCH, "/v1/call/**").hasAnyRole("ADMIN,EDITOR")
               .antMatchers(HttpMethod.PUT, "/v1/call/{id}/disable").hasAnyRole("ADMIN,EDITOR")
               .antMatchers(HttpMethod.POST, "/v1/call").hasAnyRole("ADMIN,EDITOR");
   }
</code>```

Is there another way to set the filter to ignore GET operations? In this case if the match is for "/v1/call/{id}"

答: You can add antMatchers(HttpMethod.GET, "/v1/call/{id}").permitAll() to allow your GET requests to pass.

Body:
I've been trying to add a custom filter in specific operations on a given rest controller.
In my configuration I'm trying to add this filter to only specific HttpMethods like : POST,DELETE, PATCH.
With this I wanted to set a configuration that would allow all GET operations to be ignored by the filter, but it seems that the filter is always trying to authenticate GET operations.
This is my base configure method on my WebSecurityConfigurerAdapter:

@Override
   protected void configure(HttpSecurity http) throws Exception {
       http
               .formLogin().disable()
               .csrf().disable()
               .logout().disable()
               .addFilter(new CustomSecurityFilter(authenticationManager()))
               .authorizeRequests()
               .antMatchers(HttpMethod.DELETE, "/v1/call/{id}").hasAnyRole("ADMIN,EDITOR")
               .antMatchers(HttpMethod.PATCH, "/v1/call/**").hasAnyRole("ADMIN,EDITOR")
               .antMatchers(HttpMethod.PUT, "/v1/call/{id}/disable").hasAnyRole("ADMIN,EDITOR")
               .antMatchers(HttpMethod.POST, "/v1/call").hasAnyRole("ADMIN,EDITOR");
   }

Is there another way to set the filter to ignore GET operations? In this case if the match is for "/v1/call/{id}"


问:
How to input parameters into Selenium RC TestSuite?
I have to test few sites which sales the same things, but they have an another template.

So I want to run each MainTestClass with giving some input parameter, let's say :

java -jar SeleniumServerStandalone-2.0b2.jar -port 5555 (template_id=5)

Is it possible?

```<code>class MainTestCases(unittest.TestCase):
    def setUp(self):

        #self.template_id=template_id I want something like that
        self.verificationErrors = []

        self.selenium = selenium("localhost", 5555, "*chrome", "http://www.google.com/")
        time.sleep(5)
        self.selenium.start()

    def test_test1(self):
        if self.template_id==1:
        ...
        elif self.template_id==2:
        ...
    def test_test2(self):
        if self.template_id==1:
        ...
        elif self.template_id==2:
        ...
    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()
</code>```

答:
Now, I use this solution:

Create suite test which runs testcases:

import unittest
from Flights.FlightsTestCases import FlightsTestCases
import sys
from Flights.FlightTemplate import FlightTemplate

def suite():

```<code>    testSuite= unittest.TestSuite()
    testSuite.addTest(FlightsTestCases('test_test1'))

    FlightsTestCases.www_address='http://testpage.pl/'
    FlightsTestCases.flight_template=FlightTemplate.Test

    #FlightsTestCases.www_address='http://productionpage.pl/'
    #FlightsTestCases.flight_template=FlightTemplate.Production

    return testSuite

if __name__ == "__main__":
    result = unittest.TextTestRunner(verbosity=2).run(suite())
    sys.exit(not result.wasSuccessful())
</code>```

change set_up to something like:

class FlightsTestCases(unittest.TestCase):
    www_address = None
    flight_template = None
    xml_report_generator = None

```<code>def setUp(self):
    self.verificationErrors = []
    if self.www_address == None:
        self.selenium = selenium("localhost", 5555, "*chrome", "http://testpage.pl/")
    else:
        self.selenium = selenium("localhost", 5555, "*chrome", self.www_address)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have to test few sites which sales the same things, but they have an another template.

So I want to run each MainTestClass with giving some input parameter, let's say :

java -jar SeleniumServerStandalone-2.0b2.jar -port 5555 (template_id=5)

Is it possible?

class MainTestCases(unittest.TestCase):
    def setUp(self):

        #self.template_id=template_id I want something like that
        self.verificationErrors = []

        self.selenium = selenium("localhost", 5555, "*chrome", "http://www.google.com/")
        time.sleep(5)
        self.selenium.start()

    def test_test1(self):
        if self.template_id==1:
        ...
        elif self.template_id==2:
        ...
    def test_test2(self):
        if self.template_id==1:
        ...
        elif self.template_id==2:
        ...
    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

Body:
Now, I use this solution:

Create suite test which runs testcases:

import unittest
from Flights.FlightsTestCases import FlightsTestCases
import sys
from Flights.FlightTemplate import FlightTemplate

def suite():

    testSuite= unittest.TestSuite()
    testSuite.addTest(FlightsTestCases('test_test1'))

    FlightsTestCases.www_address='http://testpage.pl/'
    FlightsTestCases.flight_template=FlightTemplate.Test

    #FlightsTestCases.www_address='http://productionpage.pl/'
    #FlightsTestCases.flight_template=FlightTemplate.Production

    return testSuite

if __name__ == "__main__":
    result = unittest.TextTestRunner(verbosity=2).run(suite())
    sys.exit(not result.wasSuccessful())

change set_up to something like:

class FlightsTestCases(unittest.TestCase):
    www_address = None
    flight_template = None
    xml_report_generator = None

def setUp(self):
    self.verificationErrors = []
    if self.www_address == None:
        self.selenium = selenium("localhost", 5555, "*chrome", "http://testpage.pl/")
    else:
        self.selenium = selenium("localhost", 5555, "*chrome", self.www_address)


问:
How can I select a date in a DatePicker with selenium using python
I want to select a date from this DatePicker :

So far, I have been able to select today's date only. But I don't know how to select a specific date. From this I need to select yesterday's date. Here what I've done so far:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(chromedriver)
driver.get('https://www.ut.com.sv/reportes?p_auth=vUIS4sqn&p_p_id=MenuReportesEstadisticos_WAR_CompletePublicReports&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_MenuReportesEstadisticos_WAR_CompletePublicReports_reportName=25cargosdelsistema')

elm = driver.find_element_by_link_text('Cargos del Sistema')
driver.implicitly_wait(5)
elm.click()

#TIPO
drpmedicion=driver.find_element_by_id('tipo')
drpmed=Select(drpmedicion)
driver.implicitly_wait(2)

drpmed.select_by_visible_text('Indicativo')
driver.implicitly_wait(2)

#SALIDA
drpsalida=driver.find_element_by_id('outType')
drpsal=Select(drpsalida)
driver.implicitly_wait(2)
drpsal.select_by_visible_text('csv')

#FECHAS INICIO
date1=driver.find_element(By.NAME,'fecha_desde')
date1.click()
driver.implicitly_wait(2)
date1.click()
driver.implicitly_wait(2)

date2=driver.find_element(By.CLASS_NAME,'picker__button--today')
date2.click()

driver.implicitly_wait(5)

#FECHAS FIN
date3=driver.find_element(By.NAME,'fecha_hasta')
driver.implicitly_wait(2)
date3.click()
driver.implicitly_wait(2)
date3.click()

driver.implicitly_wait(5)

date4=driver.find_elements(By.CLASS_NAME,'picker__button--today')
date4[1].click()

driver.implicitly_wait(5)

#CLICK FINAL
btn=driver.find_element(By.XPATH, '//*[@id="portlet_FormularioReportesEstadisticos_WAR_CompletePublicReports"]/div/div/div/input')
btn.click()
</code>```

答:
You can approach this a couple of ways, the easiest would be to get the element based on the attribute data-pick that the linked website uses:

1

```

<p>The value is the day's epoch equivalent in milliseconds which you can get like so (change it to whatever date format you use)</p>

<pre class="lang-py prettyprint-override"><code>import time
import datetime

selectedDate = "01/06/2020"
epoch = int(time.mktime(datetime.datetime.strptime(selectedDate, "%d/%m/%Y").timetuple()))*1000
</code>```

Add the epoch value into your selector, get the parent element from there and click it.

The other way to click it would be to execute 'raw' Javascript via Selenium's execute_script. include/js/pickadate/picker.js handles when you click on the date with an on('click'... event. You could invoke that by using a querySelector and then using the .click() method.

Body:
I want to select a date from this DatePicker :

So far, I have been able to select today's date only. But I don't know how to select a specific date. From this I need to select yesterday's date. Here what I've done so far:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(chromedriver)
driver.get('https://www.ut.com.sv/reportes?p_auth=vUIS4sqn&p_p_id=MenuReportesEstadisticos_WAR_CompletePublicReports&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_MenuReportesEstadisticos_WAR_CompletePublicReports_reportName=25cargosdelsistema')

elm = driver.find_element_by_link_text('Cargos del Sistema')
driver.implicitly_wait(5)
elm.click()

#TIPO
drpmedicion=driver.find_element_by_id('tipo')
drpmed=Select(drpmedicion)
driver.implicitly_wait(2)

drpmed.select_by_visible_text('Indicativo')
driver.implicitly_wait(2)

#SALIDA
drpsalida=driver.find_element_by_id('outType')
drpsal=Select(drpsalida)
driver.implicitly_wait(2)
drpsal.select_by_visible_text('csv')

#FECHAS INICIO
date1=driver.find_element(By.NAME,'fecha_desde')
date1.click()
driver.implicitly_wait(2)
date1.click()
driver.implicitly_wait(2)

date2=driver.find_element(By.CLASS_NAME,'picker__button--today')
date2.click()

driver.implicitly_wait(5)

#FECHAS FIN
date3=driver.find_element(By.NAME,'fecha_hasta')
driver.implicitly_wait(2)
date3.click()
driver.implicitly_wait(2)
date3.click()

driver.implicitly_wait(5)

date4=driver.find_elements(By.CLASS_NAME,'picker__button--today')
date4[1].click()

driver.implicitly_wait(5)

#CLICK FINAL
btn=driver.find_element(By.XPATH, '//*[@id="portlet_FormularioReportesEstadisticos_WAR_CompletePublicReports"]/div/div/div/input')
btn.click()

Body:
You can approach this a couple of ways, the easiest would be to get the element based on the attribute data-pick that the linked website uses:

<td role="presentation">
    <div class="picker__day picker__day--infocus" data-pick="1590966000000" role="gridcell">1</div>
</td>

The value is the day's epoch equivalent in milliseconds which you can get like so (change it to whatever date format you use)

import time
import datetime

selectedDate = "01/06/2020"
epoch = int(time.mktime(datetime.datetime.strptime(selectedDate, "%d/%m/%Y").timetuple()))*1000

Add the epoch value into your selector, get the parent element from there and click it.

The other way to click it would be to execute 'raw' Javascript via Selenium's execute_script. include/js/pickadate/picker.js handles when you click on the date with an on('click'... event. You could invoke that by using a querySelector and then using the .click() method.


问:
Programmatically create azure Service Bus queue and Azure Service Bus trigger for Azure Functions
I am working on a scenario where when I need to create a new servicebus queue and an azure function that is triggered whenever a message is dropped in the said queue. Is there a way to call an API pass in some parameters and have the queue and function created ?

Any inputs will be much appreciated

答:
Technically, You can achieve both as far as i know.

You can create a new function with the CLI command , i do not think there is an API to do the same.

To create a Service Bus queue you can do it with the Nuget package and here is an answer already.


问:
FFMPEG - Can't add watermark in JS file
Here's the part of my file which's about the FFMPEG string.

```<code>    if (transcoderType === 'ffmpeg') {
            // https://www.ffmpeg.org/ffmpeg-formats.html#segment
            var tsOutputFormat = 'stream%05d.ts';
            var args = [
                    '-i', file, '-sn',
                    '-async', '1', '-acodec', 'libmp3lame', '-b:a', audioBitrate + 'k', '-ar', '44100', '-ac', '2',
                    '-vf', 'scale=min(' + targetWidth + '\\, iw):-1', '-b:v', videoBitrate + 'k', '-vcodec', 'libx264', '-profile:v', 'baseline', '-preset:v' ,'superfast',
                    '-x264opts', 'level=3.0',
                    '-threads', '0', '-flags', '-global_header', '-map', '0',
                    // '-map', '0:v:0', '-map', '0:a:1'
                    '-f', 'segment',
                    '-segment_list', playlistFileName, '-segment_format', 'mpegts', '-segment_list_flags', 'live', tsOutputFormat
                    //'-segment_time', '10', '-force_key_frames', 'expr:gte(t,n_forced*10)',
                    //'-f', 'hls', '-hls_time', '10', '-hls_list_size', '0', '-hls_allow_cache', '0', '-hls_segment_filename', tsOutputFormat, playlistFileName
</code>```

I added this line to add watermark after '-i', file, '-sn',

```<code>-i', '/home/logo.png', '-filter_complex', "overlay=10:102",
</code>```

Any help would be appreciated.

答:
ffmpeg -i file -i logo.png -filter_complex "[0]scale[bg];[bg][1]overlay=10:102[v]" -map "[v]" -map 0:a? … output
```

Don't use both -vf and -filter_complex. Combine them into one -filter_complex.

Remove -map 0 and instead -map the output from the -filter_complex.

Title: FFMPEG - Can't add watermark in JS file

Body:
Here's the part of my file which's about the FFMPEG string.

    if (transcoderType === 'ffmpeg') {
            // https://www.ffmpeg.org/ffmpeg-formats.html#segment
            var tsOutputFormat = 'stream%05d.ts';
            var args = [
                    '-i', file, '-sn',
                    '-async', '1', '-acodec', 'libmp3lame', '-b:a', audioBitrate + 'k', '-ar', '44100', '-ac', '2',
                    '-vf', 'scale=min(' + targetWidth + '\\, iw):-1', '-b:v', videoBitrate + 'k', '-vcodec', 'libx264', '-profile:v', 'baseline', '-preset:v' ,'superfast',
                    '-x264opts', 'level=3.0',
                    '-threads', '0', '-flags', '-global_header', '-map', '0',
                    // '-map', '0:v:0', '-map', '0:a:1'
                    '-f', 'segment',
                    '-segment_list', playlistFileName, '-segment_format', 'mpegts', '-segment_list_flags', 'live', tsOutputFormat
                    //'-segment_time', '10', '-force_key_frames', 'expr:gte(t,n_forced*10)',
                    //'-f', 'hls', '-hls_time', '10', '-hls_list_size', '0', '-hls_allow_cache', '0', '-hls_segment_filename', tsOutputFormat, playlistFileName

I added this line to add watermark after '-i', file, '-sn',

-i', '/home/logo.png', '-filter_complex', "overlay=10:102",

Any help would be appreciated.

Body:
ffmpeg -i file -i logo.png -filter_complex "[0]scale[bg];[bg][1]overlay=10:102[v]" -map "[v]" -map 0:a? … output

Don't use both -vf and -filter_complex. Combine them into one -filter_complex.

Remove -map 0 and instead -map the output from the -filter_complex.


问:
Vue on event selects first value only
I am using vue-draggable to drag my items. I am trying to print out the moved id using :move="onDrop" event and it prints out using console.log(this.teamByTime2[0].id); first value only. Lets take an example from my DATA, there is person called KIM CHAN, if i drag Kim then its suppose to print "5" not "4". Is there a way to solve that?

View

```<code><div id="app">
    <draggable :list="dataList3" class="list-group" draggable=".item" group="a">
      <div
        class="list-group-item item"
        v-for="element in dataList3"
        :key="element.name"
      >{{ element.last_name }}</div>
    </draggable>

    <br>

    <div v-for="reservation in teamByTime2" v-bind:key="reservation.id">
      <draggable
        :list="reservation.Reservation_people"
        class="list-group"
        draggable=".item"
        group="a"
        :move="onDrop" <!-- I am using move event here -->
      >
        <div
          class="list-group-item item"
          v-for="element in reservation.Reservation_people"
          :key="element.id"
        >{{ element.last_name }}</div>
      </draggable>
    </div>
  </div>
</code>```

Method

```<code>onDrop(e) {
  console.log("moving teamByTime");
  console.log(this.teamByTime2[0].id); <!-- this only prints out first value -->

  <!-- is there a way to get the id actual moving/dragging item ?
If I am moving Kim Chan from teamByTime, then the id is suppose to be 5 not 4 -->
}
</code>```

Data

```<code>data: () => ({
    selectedid: "",

    dataList3: [
      { id: "1", first_name: "Jay", last_name: "Leo" },
      { id: "2", first_name: "David", last_name: "Reu" },
      { id: "3", first_name: "John", last_name: "Jac" }
    ],

    teamByTime2: [
      {
        id: "4",
        Reservation_people: [{ id: "18", first_name: "San", last_name: "lee" }]
      },
      {
        id: "5",
        Reservation_people: [{ id: "19", first_name: "Kim", last_name: "Chan" }]
      },
      {
        id: "6",
        Reservation_people: [{ id: "20", first_name: "Sun", last_name: "leo" }]
      }
    ]
  })
</code>```

Here is my code below on CODE SANDBOX

https://codesandbox.io/s/serene-wildflower-sh4sk?file=/src/App.vue:874-1476

答:
:move="onDrop" is the short-form for v-bind:move="onDrop" which binds attribute move to a prop inside of the draggable component, or incase it doesnt exist as a prop inside of draggable it gets passed on to the root component that is the direct child of the <template> tag inside of draggable.

If you want to listen to the move event, you need to use the v-on directive, or its short form @move="onDrop"

Title: Vue on event selects first value only

Body:
I am using vue-draggable to drag my items. I am trying to print out the moved id using :move="onDrop" event and it prints out using console.log(this.teamByTime2[0].id); first value only. Lets take an example from my DATA, there is person called KIM CHAN, if i drag Kim then its suppose to print "5" not "4". Is there a way to solve that?

View

    <draggable :list="dataList3" class="list-group" draggable=".item" group="a">

{{ element.last_name }}

    </draggable>

      <draggable
        :list="reservation.Reservation_people"
        class="list-group"
        draggable=".item"
        group="a"
        :move="onDrop"
      >

{{ element.last_name }}

      </draggable>

Method

onDrop(e) {
  console.log("moving teamByTime");
  console.log(this.teamByTime2[0].id);

}

Data

data: () => ({
    selectedid: "",

    dataList3: [
      { id: "1", first_name: "Jay", last_name: "Leo" },
      { id: "2", first_name: "David", last_name: "Reu" },
      { id: "3", first_name: "John", last_name: "Jac" }
    ],

    teamByTime2: [
      {
        id: "4",
        Reservation_people: [{ id: "18", first_name: "San", last_name: "lee" }]
      },
      {
        id: "5",
        Reservation_people: [{ id: "19", first_name: "Kim", last_name: "Chan" }]
      },
      {
        id: "6",
        Reservation_people: [{ id: "20", first_name: "Sun", last_name: "leo" }]
      }
    ]
  })

Here is my code below on CODE SANDBOX

https://codesandbox.io/s/serene-wildflower-sh4sk?file=/src/App.vue:874-1476


问:
Max value of for each column for distinct rows of data frame in r
Let’s say there is an ordered df with an ID column, and other columns containing numeral data, ordered by the last column.

```<code>ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
#   ID  A  B  C  D Rating
#1 123 96 72 95 63     97
#2 142 83 69 94 88     95
#3  21 73 88 94 89     92
#4 562 47 75 94 88     87
#5  36 88 63 65 89     85
#6 721 65 89 81 79     83
#7 847 72 48 75 88     79
#8 321 67 80 75 79     77
</code>```

The aim is to get the max value for each group/column, with its ID, and each pair needs to be from a distinct row (unique ID). For two IDs with the same value for a column, pick the one with the better Rating.

What I did is use the apply() function to get the max from each column, extract the IDs that have that value, and join them all into a data frame. Because I was still missing an ID for the 4th column, I used an anti join to take out the previous IDs and repeated the process to get this data frame:

```<code>my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]
</code>```

To finally give me:

```<code>all
#   ID  A  B  D C.y
#1 123 96 NA NA  NA
#2 721 NA 89 NA  NA
#3  21 NA NA 89  NA
#4 142 NA NA NA  94
</code>```

Is there a more clean or concise/efficient way of doing this? Not necessarily the same way, perhaps just the ID and role like:

```<code>#   ID  Group
#1 123    A
#2 721    B
#3 142    C
#4 21     D
</code>```

答:
Another dplyr/purrr solution, less concise than Allan's.

```<code>find_max <- function(gg){
    tibble(
        group=gg,
        ID= df %>% select(all_of(c(gg,"Rating","ID"))) %>%
        arrange_all(desc) %>% slice(1) %>% pull(ID))
}

c("A","B","C","D") %>% map_dfr(find_max)
</code>```

The idea is to use dplyr::arrange to sort the data frame by the group and Rating (descending), and then keep the first line (the maximum)'s ID. Iteration is made using purrr::map_dfr which directly produces a tibble.

The output is:

```<code># A tibble: 4 x 2
  group    ID
  <chr> <dbl>
1 A       123
2 B       721
3 C       123
4 D        21
</code>```

Body:
Let’s say there is an ordered df with an ID column, and other columns containing numeral data, ordered by the last column.

ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
#   ID  A  B  C  D Rating
#1 123 96 72 95 63     97
#2 142 83 69 94 88     95
#3  21 73 88 94 89     92
#4 562 47 75 94 88     87
#5  36 88 63 65 89     85
#6 721 65 89 81 79     83
#7 847 72 48 75 88     79
#8 321 67 80 75 79     77

The aim is to get the max value for each group/column, with its ID, and each pair needs to be from a distinct row (unique ID). For two IDs with the same value for a column, pick the one with the better Rating.

What I did is use the apply() function to get the max from each column, extract the IDs that have that value, and join them all into a data frame. Because I was still missing an ID for the 4th column, I used an anti join to take out the previous IDs and repeated the process to get this data frame:

my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]

To finally give me:

all
#   ID  A  B  D C.y
#1 123 96 NA NA  NA
#2 721 NA 89 NA  NA
#3  21 NA NA 89  NA
#4 142 NA NA NA  94

Is there a more clean or concise/efficient way of doing this? Not necessarily the same way, perhaps just the ID and role like:

#   ID  Group
#1 123    A
#2 721    B
#3 142    C
#4 21     D

Body:
Another dplyr/purrr solution, less concise than Allan's.

find_max <- function(gg){
    tibble(
        group=gg,
        ID= df %>% select(all_of(c(gg,"Rating","ID"))) %>%
        arrange_all(desc) %>% slice(1) %>% pull(ID))
}

c("A","B","C","D") %>% map_dfr(find_max)

The idea is to use dplyr::arrange to sort the data frame by the group and Rating (descending), and then keep the first line (the maximum)'s ID. Iteration is made using purrr::map_dfr which directly produces a tibble.

The output is:

# A tibble: 4 x 2
  group    ID
  <chr> <dbl>
1 A       123
2 B       721
3 C       123
4 D        21


问:
React typescript with react-redux component requires all passed props
So I've just started to combine react, redux (react-redux) and typescript. But I can't seem to figure out something here, namely, why the child components inside of the App component require all of the props that I pass into the App component.

App component:

```<code>const App = ({contacts, user, activeUserId}: ApplicationState) => (
    <div className="App">
        <Sidebar contacts={contacts} />
        <Main user={user} activeUserId={activeUserId}/>
    </div>
);

const getContacts = ({contacts, user, activeUserId}: ApplicationState) => ({contacts, user, activeUserId});
export default connect(getContacts)(App);
</code>```

Sidebar component:

```<code>const Sidebar = ({contacts}: ApplicationState) => {
    let contactsValues: Array<Contacts> = contacts && Object.values(contacts);

    return (
        <aside className="Sidebar">
            {contactsValues && contactsValues.map((contact: Contacts) => <User user={contact} key={contact.user_id}/>)}
        </aside>
    )
}
</code>```

I don't think there's any reason to list the Main component here as well since its only an empty component but gives the same errors, so I will just go ahead an list the Interfaces:

```<code>export default interface Contacts {
    email: string,
    name: string,
    profile_pic: string,
    status: string,
    user_id: string
}

export default interface ApplicationState {
    contacts: Contacts,
    user: object,
    activeUserId: string | null
}
</code>```

Actual error code: "TS2739: Type '{ contacts: Contacts; }' is missing the following properties from type 'ApplicationState': user, activeUserId"

So, both components ask to have all the props injected into them, even though they are not required inside the component itself. If I supply the components the everything works and I get no errors.

I'm pretty sure there's something wrong with my syntax or 'wiring' of the types.

Can we also get a explanation or a decent link to docs/materials that help us understand why this is happening?

If there is anything else that I should be including please let me know and I will provide!

Edit:

I've actually realized that its important to show the Main component too because this one also causes problems and some of the fixes you guys have suggested only fix the Sidebar component but not the Main.

Main component:

```<code>import React from "react";
import "./Main.scss";

import ApplicationState from "../../models/ApplicationState";

const Main = ({user, activeUserId}: ApplicationState) => {
    return (
        <main className="Main">
            Main Stuff
        </main>
    )
}

</code>```

Edit:

From what I've experimented with all of these answers I think the best solution would be to make everything in the interfaces optional, but if I do this then the contactsValues variable inside the Sidebar component throws: TS2322: Type 'any[] | undefined' is not assignable to type 'Contacts[]'.   Type 'undefined' is not assignable to type 'Contacts[]'..

答:
The problem is with your Sidebar component where you just passed the contacts and defined its type to be ApplicationState... Change Sidebar parameter as:

```<code>const Sidebar = (contacts: Contacts) => {
let contactsValues: Array<Contacts> = contacts && Object.values(contacts);
return
 ( <aside className="Sidebar">
   {contactsValues && contactsValues.map((contact: Contacts) =>
   <User user={contact} key={contact.user_id}/>
   )}
  </aside> ) }
</code>```

Another way to resolve the error is to make interface attribute optional as:

Update

I think there is one more problem with the interfaces:

```<code>export default interface Contact {   //It's a single object, So Contact is OK
 email: string,
 name: string,
 profile_pic: string,
 status: string,
 user_id: string
}
export default interface ApplicationState {
 contacts: Contact[],   // I guess you need an array of Contacts
 user?: object,
 activeUserId?: string
}
</code>```

And I think you are getting error because of wrong initialization. Change to

```<code>let contactsValues: Array<Contacts> = contacts ? Object.values(contacts): [] as Contact[];
</code>```

Body:
So I've just started to combine react, redux (react-redux) and typescript. But I can't seem to figure out something here, namely, why the child components inside of the App component require all of the props that I pass into the App component.

App component:

const App = ({contacts, user, activeUserId}: ApplicationState) => (

        <Sidebar contacts={contacts} />

);

const getContacts = ({contacts, user, activeUserId}: ApplicationState) => ({contacts, user, activeUserId});
export default connect(getContacts)(App);

Sidebar component:

const Sidebar = ({contacts}: ApplicationState) => {
    let contactsValues: Array<Contacts> = contacts && Object.values(contacts);

    return (

            {contactsValues && contactsValues.map((contact: Contacts) => <User user={contact} key={contact.user_id}/>)}

    )
}

I don't think there's any reason to list the Main component here as well since its only an empty component but gives the same errors, so I will just go ahead an list the Interfaces:

export default interface Contacts {
    email: string,
    name: string,
    profile_pic: string,
    status: string,
    user_id: string
}

export default interface ApplicationState {
    contacts: Contacts,
    user: object,
    activeUserId: string | null
}

Actual error code: "TS2739: Type '{ contacts: Contacts; }' is missing the following properties from type 'ApplicationState': user, activeUserId"

So, both components ask to have all the props injected into them, even though they are not required inside the component itself. If I supply the components the everything works and I get no errors.

I'm pretty sure there's something wrong with my syntax or 'wiring' of the types.

Can we also get a explanation or a decent link to docs/materials that help us understand why this is happening?

If there is anything else that I should be including please let me know and I will provide!

Edit:

I've actually realized that its important to show the Main component too because this one also causes problems and some of the fixes you guys have suggested only fix the Sidebar component but not the Main.

Main component:

import React from "react";
import "./Main.scss";

import ApplicationState from "../../models/ApplicationState";

const Main = ({user, activeUserId}: ApplicationState) => {
    return (

            Main Stuff

    )
}

Edit:

From what I've experimented with all of these answers I think the best solution would be to make everything in the interfaces optional, but if I do this then the contactsValues variable inside the Sidebar component throws: TS2322: Type 'any[] | undefined' is not assignable to type 'Contacts[]'.   Type 'undefined' is not assignable to type 'Contacts[]'..

Body:
The problem is with your Sidebar component where you just passed the contacts and defined its type to be ApplicationState... Change Sidebar parameter as:

const Sidebar = (contacts: Contacts) => {
let contactsValues: Array<Contacts> = contacts && Object.values(contacts);
return
 ( <aside className="Sidebar">
   {contactsValues && contactsValues.map((contact: Contacts) =>
   <User user={contact} key={contact.user_id}/>
   )}
  </aside> ) }

Another way to resolve the error is to make interface attribute optional as:

Update

I think there is one more problem with the interfaces:

export default interface Contact {   //It's a single object, So Contact is OK
 email: string,
 name: string,
 profile_pic: string,
 status: string,
 user_id: string
}
export default interface ApplicationState {
 contacts: Contact[],   // I guess you need an array of Contacts
 user?: object,
 activeUserId?: string
}

And I think you are getting error because of wrong initialization. Change to

let contactsValues: Array<Contacts> = contacts ? Object.values(contacts): [] as Contact[];


问:
How can I convert FlowChart to PHP Code and vise versa in Enterprise Architect?
I'am new to Enterprise Architect, and I need to know if EA supports converting flowchart to php code and vise versa?, and if it doesn't are there any alternatives?</p>

答:
You can do that with PSeint, (you work with pseudocode that then translates to php), it's free but in spanish, unfortunately.

http://pseint.sourceforge.net/


问:
How to schedule Quartz Scheduler jobs for Ondemand trigger?

I dont want to schedule as OneTime job or Cron job.

I want to trigger it with Rest API, whenever I want

So far, didn't find any such Options.

Note: I have created custom Spring Quartz APIs for invoking Quartz jobs.

答: Quartz scheduler is a scheduling library that can run outside of web contexts and as such it does not provide any REST API. It provides a decent JMX and RMI APIs though that you can use to "manually" trigger your jobs as you wish.</p>


问:
Taking a list as input from user
While taking a list as an input from the user, the input is SUPPOSED to be enclosed within square brackets as opposed to just typing the numbers
This is my code for taking multiple inputs from the user for a list

```<code>a = list(map(int,input().strip().split(', ')))
</code>```

The default input is [1, 2, 3, 4].
When I run my code, I get an error as:

```<code>ValueError: invalid literal for int() with base 10: '[1'
</code>```

I know the reason it's happening is because '[1' is a an element that cannot be converted into int and it  (the square bracket and 1) is being regarded as the first element of the list at index 0.
Having the square bracket is absolutely essential for me, how can I resolve the error or just ignore the square brackets? Is there an ignore method or something similar that might work?
Cheers!

答:
In a simple way you can use strip() to remove extra whitespace and '[ ]'.</p>

```<code>a = list(map(int, input().strip(' []').split(',')))
</code>```

Title: Taking a list as input from user

Body:
While taking a list as an input from the user, the input is SUPPOSED to be enclosed within square brackets as opposed to just typing the numbers
This is my code for taking multiple inputs from the user for a list

a = list(map(int,input().strip().split(', ')))

The default input is [1, 2, 3, 4].
When I run my code, I get an error as:

ValueError: invalid literal for int() with base 10: '[1'

I know the reason it's happening is because '[1' is a an element that cannot be converted into int and it  (the square bracket and 1) is being regarded as the first element of the list at index 0.
Having the square bracket is absolutely essential for me, how can I resolve the error or just ignore the square brackets? Is there an ignore method or something similar that might work?
Cheers!

Body:
In a simple way you can use strip() to remove extra whitespace and '[ ]'.

a = list(map(int, input().strip(' []').split(',')))


问:
Extract nested microdata using xpath
I am trying to extract the recipe name from schema.org microdata using xpath

This is the xpath I came up with:

```<code>//*[@itemtype="http://schema.org/Recipe"]//*[@itemprop="name" and not(ancestor::*[@itemtype!="http://schema.org/Recipe"])]
</code>```

Select the node with itemprop="name" inside the node with itemtype="http://schema.org/Recipe", but ignore nodes with a non-recipe itemtype parent (within the scope of the itemtype="http://schema.org/Recipe" node).

Test cases:

Fails:

```<code><div itemtype="https://schema.org/Thing">
  <div itemtype="http://schema.org/Recipe">
    <div>
      <div itemtype="http://schema.org/BreadcrumbList">
          <div itemprop="name">test1</div>
          <div itemprop="name">test2</div>
      </div>
      <div itemprop="name">Recipe Name</div>
    </div>
  </div>
</div>
</code>```

Fails:

```<code><div itemtype="http://schema.org/Recipe">
  <div>
    <div itemtype="http://schema.org/BreadcrumbList">
      <div>
        <div itemprop="name">test1</div>
        <div>
            <div itemprop="name">test2</div>
        </div>
      </div>
    </div>
    <div>
      <div itemprop="name">Recipe Name</div>
    </div>
  </div>
</div>
</code>```

Passes:

```<code><div itemtype="http://schema.org/Recipe">
  <div>
    <div itemtype="http://schema.org/BreadcrumbList">
        <div itemprop="name">test1</div>
        <div itemprop="name">test2</div>
    </div>
    <div itemprop="name">Recipe Name</div>
  </div>
</div>
</code>```

Passes:

```<code><div itemtype="http://schema.org/Recipe">
  <div itemprop="name">Recipe Name</div>
</div>
</code>```

It appears that ancestor::*[@itemtype!="http://schema.org/Recipe"] is searching all ancestors instead of just ancestors within the Recipe node.

How can I extract the recipe name from Recipe microdata https://schema.org/Recipe when there are potentially nested itemtypes?

答:
If I understand your question correctly and you want to include all Recipe Name and exclude all testx, this expression

```<code>//*[@itemtype="http://schema.org/Recipe"]//*[@itemprop="name"][not(..[@itemtype!="http://schema.org/Recipe"])]
</code>```

or, simpler version:

```<code>//*[contains(@itemtype,"Recipe")]//*[@itemprop="name"][not(../@itemtype[not(contains(.,"Recipe"))])]
</code>```

should do it.

Edit:

Using the updated samples:

```<code>//*[contains(@itemtype,"Recipe")]//*[@itemprop="name"][not(ancestor::*[@itemtype][1]/@itemtype[not(contains(.,"Recipe"))])]
</code>```

That's xpath double negation for you...

Title: Extract nested microdata using xpath

Body:
I am trying to extract the recipe name from schema.org microdata using xpath

This is the xpath I came up with:

//*[@itemtype="http://schema.org/Recipe"]//*[@itemprop="name" and not(ancestor::*[@itemtype!="http://schema.org/Recipe"])]

Select the node with itemprop="name" inside the node with itemtype="http://schema.org/Recipe", but ignore nodes with a non-recipe itemtype parent (within the scope of the itemtype="http://schema.org/Recipe" node).

Test cases:

Fails:

test1

test2

Recipe Name

Fails:

test1

test2

Recipe Name

Passes:

test1

test2

Recipe Name

Passes:

Recipe Name

It appears that ancestor::*[@itemtype!="http://schema.org/Recipe"] is searching all ancestors instead of just ancestors within the Recipe node.

How can I extract the recipe name from Recipe microdata https://schema.org/Recipe when there are potentially nested itemtypes?

Body:
If I understand your question correctly and you want to include all Recipe Name and exclude all testx, this expression

//*[@itemtype="http://schema.org/Recipe"]//*[@itemprop="name"][not(..[@itemtype!="http://schema.org/Recipe"])]

or, simpler version:

//*[contains(@itemtype,"Recipe")]//*[@itemprop="name"][not(../@itemtype[not(contains(.,"Recipe"))])]

should do it.

Edit:

Using the updated samples:

//*[contains(@itemtype,"Recipe")]//*[@itemprop="name"][not(ancestor::*[@itemtype][1]/@itemtype[not(contains(.,"Recipe"))])]

That's xpath double negation for you...


问:
Git for Windows doesn't know %USERPROFILE%
I have the same issue like Git for Windows doesn't execute my .bashrc file and tried to make the same steps. But my Git Bash (2.5.0, 64bit on Windows 7, 64bit) doesn't know my %USERPROFILE%.

```<code>pitgrap@xxx MINGW64 /
$ pwd
/

pitgrap@xxx MINGW64 /
$ cd ~
bash: cd: /%USERPROFILE%: No such file or directory
</code>```

If I run Git Bash as Administror, it works. :(
But I don't want to run it everytime as Administrator. Any ideas?

答:
This just has to do with how each of those different languages handle variable expansion.

cmd:  C:\> echo %USERPROFILE%

bash: $ echo $USERPROFILE

ps:     PS> echo $env:USERPROFILE

In windows cmd prompt, variables should be surrounded by % on either side

Whereas Bash and PowerShell indicate a variables by prefixing with a $.

Git Bash gets all existing Windows environment variables at startup, while powershell tries to limit polluting the global namespace by including them under the $env object

If you want to confirm the shell has access to the environment variable, you can list all variables:

cmd (docs):  C:\> SET

bash (docs): $ printenv

ps (docs):     PS> Get-ChildItem env:

Body:
I have the same issue like Git for Windows doesn't execute my .bashrc file and tried to make the same steps. But my Git Bash (2.5.0, 64bit on Windows 7, 64bit) doesn't know my %USERPROFILE%.

pitgrap@xxx MINGW64 /
$ pwd
/

pitgrap@xxx MINGW64 /
$ cd ~
bash: cd: /%USERPROFILE%: No such file or directory

If I run Git Bash as Administror, it works. :(
But I don't want to run it everytime as Administrator. Any ideas?


问:
Temporary macro to store another macro and then reverting back
I want to have more control over macros such as assertions (and some logging macros that are not directly under my control). So I decided to do something like this, expecting it to work (in case somebody is wondering, the reason it does not work is that the last undef of MY_ASSERT_COPY invalidates MY_ASSERT right before it).

```<code>#ifndef ENABLE_FULL_ERROR_ASSERTS
#define MY_ASSERT_COPY MY_ASSERT
#undef MY_ASSERT
#define MY_ASSERT
#endif

// Code for my current class, which happens to be header only

#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#define MY_ASSERT MY_ASSERT_COPY
#undef MY_ASSERT_COPY
#endif
</code>```

Now I know a few ways around it, one being to define another macro for assertions just for that file, which I can then turn off without affecting assertions in any other part of the program. I initially thought this was a really elegant solution (before I found out it did not compile) that will allow me to use MY_ASSERT everywhere and then simply turn it off for particular files.

Since the above doesn't work, is there a workaround that will allow me to selectively kill the macro without affecting the surrounding code and without defining another substitute macro like #define MY_ASSERT_FOR_VECTORS MY_ASSERT

答:
This may not work in all situations, but maybe you could simply undef the macros, define them as you wish and then undef them again.

The next time your code uses some of these macros it should #include the header files where they were initially defined so it will define those macros again.

One safe option would be:

```<code>#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#define MY_ASSERT ....
#endif

// Code for my current class, which happens to be header only

#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#include "headers.h"  //etc
// line above should redefine the macros
#endif
</code>```

Body:
I want to have more control over macros such as assertions (and some logging macros that are not directly under my control). So I decided to do something like this, expecting it to work (in case somebody is wondering, the reason it does not work is that the last undef of MY_ASSERT_COPY invalidates MY_ASSERT right before it).

#ifndef ENABLE_FULL_ERROR_ASSERTS
#define MY_ASSERT_COPY MY_ASSERT
#undef MY_ASSERT
#define MY_ASSERT
#endif

// Code for my current class, which happens to be header only

#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#define MY_ASSERT MY_ASSERT_COPY
#undef MY_ASSERT_COPY
#endif

Now I know a few ways around it, one being to define another macro for assertions just for that file, which I can then turn off without affecting assertions in any other part of the program. I initially thought this was a really elegant solution (before I found out it did not compile) that will allow me to use MY_ASSERT everywhere and then simply turn it off for particular files.

Since the above doesn't work, is there a workaround that will allow me to selectively kill the macro without affecting the surrounding code and without defining another substitute macro like #define MY_ASSERT_FOR_VECTORS MY_ASSERT

Body:
This may not work in all situations, but maybe you could simply undef the macros, define them as you wish and then undef them again.

The next time your code uses some of these macros it should #include the header files where they were initially defined so it will define those macros again.

One safe option would be:

#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#define MY_ASSERT ....
#endif

// Code for my current class, which happens to be header only

#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#include "headers.h"  //etc
// line above should redefine the macros
#endif


问:
Visual Studio C++ Project and Referenced Project's References
I'm trying to setup a C++ solution that has multiple projects, for simplicity I'll call them ProjectA and ProjectB.

ProjectB is setup as a Static Library and uses an external library, I'll call it ExternalLib, that's been added to the Additional Includes in the properties of ProjectB. ProjectA has ProjectB added as a reference and has been added to the Additional Includes section of ProjectA. So far so good, I can reference classes in ProjectB from ProjectA but when I go to compile I get an error that one of the headers from ExternalLib can't be found. Not sure how to proceed I added ExternalLib to the Additional Includes section of ProjectA and built again. Now I get unresolved externals for classes in ExternalLib.

I'm sure I could fix the unresolved externals by adding ExternalLib to the Additional Dependencies for the Linker of PorjectA. However, I'm confused as to whether that's the right way to handle this. I'm a little new to C++ projects in VS, I'm more familiar with C#, so my question is:

Is it standard to have to include a referenced project's (ProjectB) dependencies (ExternalLib) in my main project (ProjectA)? Or have I configured PorjectB incorrectly?

答: Check your ProjectB header files, if header files included by ProjectA reference anything from ExternalLib then ProjectA will need to be told about ExternalLib. Usually I find the problem is that ProjectB is only supposed to use ExternalLib internally but that some part of ExternalLib has snuck into the public face of ProjectB. If something from ExternalLib is indeed supposed to be part of the public face of ProjectB then yes, anything that uses ProjectB will also need to be told about ExternalLib (ProjectB's knowledge of ExternalLib is not inherited by projects that reference ProjectB).</p>


问:
I need to pass a JSON file to MongoDB using Mongoose
I tried this, but it does not work:
The readFile works well, and it finishes before the connection to the DB had started.
My problem is when trying to use the parsed JSON obj (listingData) into MongoDB using Mongoose.

```<code> let listingData;
 fs.readFile('listings.json', 'utf8', (err, data) => {
   try {
     listingData = JSON.parse(data);
   } catch (err) {
     console.log('Error reading JSON file');
     throw err;
   }
   //console.log(listingData); // PRINTS DATA CORRECTLY!
 });

 async function loadListings() {
   try {
     await Listing.insertMany(listingData); // imported.insertMany(JSON Parsed)
     console.log("Listings inserted in the DB");
     //process.exit();
   } catch (error) {
     console.log("Error importing listings to DB");
     process.exit();
   }
 }
</code>```

SOLVED, thanks

答:
Both the readFile and loadListings is async so loadListing is not going to wait for readFile to finish and pass the data as by that time listingData isundefined.

You can solve this issue by using promise library of fs. Available after node 10.x version

```<code>  const fs= require(fs).promises

async function loadListings() {
   try {
     let listingData= await fs.readFile('listings.json','utf8')// Get data here, await will wait for execution to finish
     await Listing.insertMany(listingData);
     console.log("Listings inserted in the DB");
     //process.exit();
   } catch (error) {
     console.error(error) // Catch Error here
     console.log("Error importing listings to DB");
     process.exit();
   }
 }
</code>```

Body:
I tried this, but it does not work:
The readFile works well, and it finishes before the connection to the DB had started.
My problem is when trying to use the parsed JSON obj (listingData) into MongoDB using Mongoose.

 let listingData;
 fs.readFile('listings.json', 'utf8', (err, data) => {
   try {
     listingData = JSON.parse(data);
   } catch (err) {
     console.log('Error reading JSON file');
     throw err;
   }
   //console.log(listingData); // PRINTS DATA CORRECTLY!
 });

 async function loadListings() {
   try {
     await Listing.insertMany(listingData); // imported.insertMany(JSON Parsed)
     console.log("Listings inserted in the DB");
     //process.exit();
   } catch (error) {
     console.log("Error importing listings to DB");
     process.exit();
   }
 }

SOLVED, thanks

Body:
Both the readFile and loadListings is async so loadListing is not going to wait for readFile to finish and pass the data as by that time listingData isundefined.

You can solve this issue by using promise library of fs. Available after node 10.x version

  const fs= require(fs).promises

async function loadListings() {
   try {
     let listingData= await fs.readFile('listings.json','utf8')// Get data here, await will wait for execution to finish
     await Listing.insertMany(listingData);
     console.log("Listings inserted in the DB");
     //process.exit();
   } catch (error) {
     console.error(error) // Catch Error here
     console.log("Error importing listings to DB");
     process.exit();
   }
 }


问:
Receiving Nonetype error even though I am able to scrape the images of the website,
I am relatively new to python programming and have written this code to scrape images of website and save it on my computer, although this code seems to work but in the end I am getting a error

```<code>if len(nametemp)== 0 or nametemp== None:
TypeError: object of type 'NoneType' has no len()
</code>```

can someone please tell me what I am doing wrong?

答:
Change the order in the if condition, </p>

```<code>if nametemp == None or len(nametemp) == 0:
</code>```

Body:
I am relatively new to python programming and have written this code to scrape images of website and save it on my computer, although this code seems to work but in the end I am getting a error

if len(nametemp)== 0 or nametemp== None:
TypeError: object of type 'NoneType' has no len()

can someone please tell me what I am doing wrong?

Body:
Change the order in the if condition,

if nametemp == None or len(nametemp) == 0:


问:
xilinx vivado: read component.xml file into project from tcl
Let's suppose, I have one vivado project that I setup as follows:

Create a block design.

instantiated some IP cores, and wired them together

exported the IO's that I wanted from the block design

clicked on the block design in hierarchy browser and created an HDL wrapper

used IP packager to create a "component.xml" file representing the packaged IP core.  (Tool->Package IP->package current project)

Now I want to use this packaged IP core in another vivado project and have it show up under IP integrator under "user" library.  Is there a way to import this "component.xml" file from the other vivado project into the current project?  Preferablly using tcl?

Here's what my vivado block design looks like:

答:
The answer is that you  "set ip_repos_path property" of your current project to point to the directory that has the "component.xml" file from the other project,  then you issue the tcl command: update_ip_catalog.  This will cause the packaged core to show up in IP integrator under the "user" tab.

Here's a vivado tcl script that performs this task that assumes that you have previously used create_project or open_project commands:

```<code>proc tool_add_xact {file_component_xml} {
    puts "\n=> add_xact: $file_component_xml"

    global current_xml_name
    global current_xml_vlnv

    if {! [file exists $file_component_xml]} {
        puts "ERROR: file doesn't exist: $file_component_xml"
        exit 1;
    }

    if {! [regexp {component\.xml$} $file_component_xml tmp]} {
        puts "ERROR: wrong file name ($file). This proc only reads component.xml files created by IP Packager."
        exit 1;
    }

    set xml_dir  [file dirname $file_component_xml]
    set cfs      [current_fileset]
    set old_path [get_property ip_repo_paths $cfs]
    set new_path [concat $old_path $xml_dir]

    puts "    xml_dir: ($xml_dir)"
    puts "    add_repo:($new_path)"
    set_property ip_repo_paths $new_path $cfs

    puts "    update_ip_catalog"
    update_ip_catalog

    puts "    open_core"
    set core [ipx::open_core -set_current false $file_component_xml]

    set vlnv    [get_property vlnv $core]
    set tidbits [split $vlnv ":"]
    puts "    vlnv: $vlnv"

    puts "    close_core"
    ipx::unload_core $core

    set current_xml_name  [lindex $tidbits 2]
    set current_xml_vlnv  $vlnv
}

# Instantiate XACT IP
proc tool_add_core {args} {
    puts "\n=> add_core: $args"

    global current_xml_name
    global current_xml_vlnv

    #flag defaults
    set level 1
    set inst  ""

    # Parse Flags
    while {[llength $args]} {
        set flag [lindex $args 0]
        #puts "flag: ($flag)"
        #puts "args: ($args)"

        switch -glob $flag {
            -level  {
                # Instantion Generation Level
                set level [lindex $args 1]
                set args  [lrange $args 2 end]
                puts "level:($level) args($args)"

            } -inst {
                # Override default instantation name
                set autoname 0
                set inst  [lindex $args 1]
                set args  [lrange $args 2 end]
                puts "inst:($inst) args($args)"

            } -h* {
                #help
                puts "USAGE:"
                puts "    tool_add_core \[flags\] <component.xml>"
                puts ""
                puts "FLAGS:"
                puts "    -level 0      //Instantiate only"
                puts "    -level 1      //Instantiate + Generate Instantiation templates"
                puts "    -level 2      //Instantiate + Generate all"
                puts "    -level 3      //Instantiate + Synthesize"
                puts "    -inst <name>  //set name of instance, default: \${corename}_1"
                exit 1

            } -* {
                # unknown option
                error "unknown option [lindex $args 0]"

            } default break
        }
    }
    #puts "args: ($args)"

    # remaining argument is component.xml flag
    set file_component_xml "$args"
    puts "component_xml: $args"

    # Add Packaged IP core, aka. "component.xml", to "IP Integator Library"
    tool_add_xact $file_component_xml

    if {$inst == ""} {
       set module_ip "${current_xml_name}_1"
    } else {
       set module_ip "${inst}"
    }

    puts "-> level: $level"
    puts "-> inst:  $module_ip"

    # Create XCI by instantiating component just added to "IP Integrator Library"
    puts "-> create_ip -verbose -module_name $module_ip -vlnv $current_xml_vlnv"
    create_ip \
        -verbose \
        -module_name $module_ip \
        -vlnv $current_xml_vlnv

    set ip_obj [get_ips "${module_ip}"]

    # Instantate only
    if {$level == 0} {
        return
    }

    # Instantiate + Generate Instantiation template only
    if {$level == 1} {
        puts "\n-> generate_target {instantiation_template}"
        #generate_target {instantiation_template} [get_files "${module_ip}.xci"]
        generate_target {instantiation_template} $ip_obj
        return
    }

    # Instantiate + Generate all
    if {$level == 2} {
        puts "\n-> generate_target {all}"
        generate_target {all} $ip_obj
        return
    }

    # Instantiate + Generate all + Synthesize Core
    if {$level == 3} {
        puts "\n-> generate_target {all}"
        generate_target {all} $ip_obj

        set run_name "${module_ip}_synth_1"
        set run_jobs 8

        puts "\n-> synth_ip    name:${run_name}    jobs:${run_jobs}"

        create_ip_run $ip_obj
        launch_run -jobs $run_jobs $run_name
        wait_on_run $run_name

        return
    }

    error "unknown -level $level"
}
</code>```

Body:
The answer is that you  "set ip_repos_path property" of your current project to point to the directory that has the "component.xml" file from the other project,  then you issue the tcl command: update_ip_catalog.  This will cause the packaged core to show up in IP integrator under the "user" tab.

Here's a vivado tcl script that performs this task that assumes that you have previously used create_project or open_project commands:

proc tool_add_xact {file_component_xml} {
    puts "\n=> add_xact: $file_component_xml"

    global current_xml_name
    global current_xml_vlnv

    if {! [file exists $file_component_xml]} {
        puts "ERROR: file doesn't exist: $file_component_xml"
        exit 1;
    }

    if {! [regexp {component\.xml$} $file_component_xml tmp]} {
        puts "ERROR: wrong file name ($file). This proc only reads component.xml files created by IP Packager."
        exit 1;
    }

    set xml_dir  [file dirname $file_component_xml]
    set cfs      [current_fileset]
    set old_path [get_property ip_repo_paths $cfs]
    set new_path [concat $old_path $xml_dir]

    puts "    xml_dir: ($xml_dir)"
    puts "    add_repo:($new_path)"
    set_property ip_repo_paths $new_path $cfs

    puts "    update_ip_catalog"
    update_ip_catalog

    puts "    open_core"
    set core [ipx::open_core -set_current false $file_component_xml]

    set vlnv    [get_property vlnv $core]
    set tidbits [split $vlnv ":"]
    puts "    vlnv: $vlnv"

    puts "    close_core"
    ipx::unload_core $core

    set current_xml_name  [lindex $tidbits 2]
    set current_xml_vlnv  $vlnv
}

# Instantiate XACT IP
proc tool_add_core {args} {
    puts "\n=> add_core: $args"

    global current_xml_name
    global current_xml_vlnv

    #flag defaults
    set level 1
    set inst  ""

    # Parse Flags
    while {[llength $args]} {
        set flag [lindex $args 0]
        #puts "flag: ($flag)"
        #puts "args: ($args)"

        switch -glob $flag {
            -level  {
                # Instantion Generation Level
                set level [lindex $args 1]
                set args  [lrange $args 2 end]
                puts "level:($level) args($args)"

            } -inst {
                # Override default instantation name
                set autoname 0
                set inst  [lindex $args 1]
                set args  [lrange $args 2 end]
                puts "inst:($inst) args($args)"

            } -h* {
                #help
                puts "USAGE:"
                puts "    tool_add_core \[flags\] <component.xml>"
                puts ""
                puts "FLAGS:"
                puts "    -level 0      //Instantiate only"
                puts "    -level 1      //Instantiate + Generate Instantiation templates"
                puts "    -level 2      //Instantiate + Generate all"
                puts "    -level 3      //Instantiate + Synthesize"
                puts "    -inst <name>  //set name of instance, default: \${corename}_1"
                exit 1

            } -* {
                # unknown option
                error "unknown option [lindex $args 0]"

            } default break
        }
    }
    #puts "args: ($args)"

    # remaining argument is component.xml flag
    set file_component_xml "$args"
    puts "component_xml: $args"

    # Add Packaged IP core, aka. "component.xml", to "IP Integator Library"
    tool_add_xact $file_component_xml

    if {$inst == ""} {
       set module_ip "${current_xml_name}_1"
    } else {
       set module_ip "${inst}"
    }

    puts "-> level: $level"
    puts "-> inst:  $module_ip"

    # Create XCI by instantiating component just added to "IP Integrator Library"
    puts "-> create_ip -verbose -module_name $module_ip -vlnv $current_xml_vlnv"
    create_ip \
        -verbose \
        -module_name $module_ip \
        -vlnv $current_xml_vlnv

    set ip_obj [get_ips "${module_ip}"]

    # Instantate only
    if {$level == 0} {
        return
    }

    # Instantiate + Generate Instantiation template only
    if {$level == 1} {
        puts "\n-> generate_target {instantiation_template}"
        #generate_target {instantiation_template} [get_files "${module_ip}.xci"]
        generate_target {instantiation_template} $ip_obj
        return
    }

    # Instantiate + Generate all
    if {$level == 2} {
        puts "\n-> generate_target {all}"
        generate_target {all} $ip_obj
        return
    }

    # Instantiate + Generate all + Synthesize Core
    if {$level == 3} {
        puts "\n-> generate_target {all}"
        generate_target {all} $ip_obj

        set run_name "${module_ip}_synth_1"
        set run_jobs 8

        puts "\n-> synth_ip    name:${run_name}    jobs:${run_jobs}"

        create_ip_run $ip_obj
        launch_run -jobs $run_jobs $run_name
        wait_on_run $run_name

        return
    }

    error "unknown -level $level"
}


问:
Execute Pop, Discard and Remove commands on Sets
If someone can help to understand the following eval logic and how the particular method is applied in this scenario.

```<code>n = int(input())
s = set(map(int, input().split()))

for i in range(int(input())):
    eval('s.{0}({1})'.format(*input().split()+['']))

print(sum(s))
</code>```

The above code works absolutely fine and I'm trying to understand how the function works in details.

Here is the reference to the problem.

答:
Welcome to stackoverflow. If you're a begineer in Python, I recommend you to read the Python documentation, they provide a good resource to understand Python.

For this problem, you need to read https://docs.python.org/3/library/functions.html

Okay, let's break the code line by line.

```<code>n = int(input())
</code>```

Take an input string from stdin, then convert it to int data type. Then store it to variable n

```<code>s = set(map(int, input().split()))
</code>```

Take an input, and split it on every whitespace. e.g If the input is 1 2 3, it will  be a list of [1, 2, 3]. Then, convert every element of the list to an int data type. Then, convert the list to set. Then store it to variable s.

```<code>for i in range(int(input())):
</code>```

Iterate from 0 to a string from input and converted to int data type as i

```<code>    eval('s.{0}({1})'.format(*input().split()+['']))
</code>```

Okay, this will go a bit tricky.

First, try to understand the Python format, I recommend you to read https://pyformat.info/. In short, "string {0}, {2}, {1}".format("a", "b", "c") will give you string of "string a, c, b".

In this case, the format will take 2 argument, because there's {0} and {1} in the string 's.{0}({1})', which comes from *input().split()+[''] statement.

Python will execute input().split() first, take an input and split it to a list. Then merge the list with another list, which is ['']. After that, spread the list elements as the argument of the format.

e.g
If you have the input

```<code>remove 9
</code>```

It will call the format like this

```<code>'s.{0}({1})'.format("remove", "9", "")
# will be
's.remove(9)'
</code>```

```<code>"remove 9" -> ["remove", "9"] -> ["remove", "9", ""] -> "remove", "9", "" (as function argument)
</code>```

Okay, but what's the +[''] for? It's a trick for the formatter for input that only has one word.

e.g

```<code>'s.{0}({1})'.format("pop", "")
# will be
's.pop()'
</code>```

Eval function take one argument, which is string. And it will execute the string as a Python code. So, eval("print(1)") will print 1 to console.

```<code>print(sum(s))
</code>```

Print the sum of set s

I hope I explain it clear enough

Body:
If someone can help to understand the following eval logic and how the particular method is applied in this scenario.

n = int(input())
s = set(map(int, input().split()))

for i in range(int(input())):
    eval('s.{0}({1})'.format(*input().split()+['']))

print(sum(s))

The above code works absolutely fine and I'm trying to understand how the function works in details.

Here is the reference to the problem.

Body:
Welcome to stackoverflow. If you're a begineer in Python, I recommend you to read the Python documentation, they provide a good resource to understand Python.

For this problem, you need to read https://docs.python.org/3/library/functions.html

Okay, let's break the code line by line.

n = int(input())

Take an input string from stdin, then convert it to int data type. Then store it to variable n

s = set(map(int, input().split()))

Take an input, and split it on every whitespace. e.g If the input is 1 2 3, it will  be a list of [1, 2, 3]. Then, convert every element of the list to an int data type. Then, convert the list to set. Then store it to variable s.

for i in range(int(input())):

Iterate from 0 to a string from input and converted to int data type as i

    eval('s.{0}({1})'.format(*input().split()+['']))

Okay, this will go a bit tricky.

First, try to understand the Python format, I recommend you to read https://pyformat.info/. In short, "string {0}, {2}, {1}".format("a", "b", "c") will give you string of "string a, c, b".

In this case, the format will take 2 argument, because there's {0} and {1} in the string 's.{0}({1})', which comes from *input().split()+[''] statement.

Python will execute input().split() first, take an input and split it to a list. Then merge the list with another list, which is ['']. After that, spread the list elements as the argument of the format.

e.g
If you have the input

remove 9

It will call the format like this

's.{0}({1})'.format("remove", "9", "")
# will be
's.remove(9)'

"remove 9" -> ["remove", "9"] -> ["remove", "9", ""] -> "remove", "9", "" (as function argument)

Okay, but what's the +[''] for? It's a trick for the formatter for input that only has one word.

e.g

's.{0}({1})'.format("pop", "")
# will be
's.pop()'

Eval function take one argument, which is string. And it will execute the string as a Python code. So, eval("print(1)") will print 1 to console.

print(sum(s))

Print the sum of set s

I hope I explain it clear enough


问:
JQuery Two 'Select All' Checkboxes Across 2 Tables
I have two tables that are filled with a number of checkboxes (the number is variable based on a retrieval profile defined on a previous screen).  I've implemented a Select All check box at the top of each table with the following:

```<code>    $('#select_all').bind('click', function() {
    if(this.checked) {
        $(':checkbox').each(function() {
            this.checked = true;
        });
    } else {
        $(':checkbox').each(function() {
            this.checked = false;
        });
    }
 });
</code>```

But this function selects all checkboxes in both tables (as it is poorly written to do).    Is there an easy method of having the code select all checkboxes in each distinct tables.

Thanks.

答:
It is advisable you use class attribute for your table since Id's are supposed to be unique.

Create a variable to store value for table closest to checkbox current checkbox triggered and Concatenate the variable with Selector.

$('.selectAll').bind('click', function() {
  var thisTable = $(this).closest('.checkTable');//closest table of this checkbox triggered
  var checkedState = this.checked;//variable for checkbox checked.
  $(':checkbox', thisTable).each(function(){//concatenate 'thisTable' variable with css selector and iterate
    this.checked = checkedState;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="checkTable">
  <tr>
    <th> <input type="checkbox" class="selectAll"></th>
    <th>Select All</th>
  </tr>
  <tr>
    <td><input type="checkbox" id="1"></td>
    <td>Hello</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="2"></td>
    <td>Hi</td>
  </tr>

</table>
<table class="checkTable">
  <tr>
    <th><input type="checkbox" class="selectAll"></th>
    <th>Select All</th>
  </tr>
  <tr>
    <td><input type="checkbox" id="3"></td>
    <td>One</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="4"></td>
    <td>Two</td>
  </tr>

</table></code>```

Body:
I have two tables that are filled with a number of checkboxes (the number is variable based on a retrieval profile defined on a previous screen).  I've implemented a Select All check box at the top of each table with the following:

    $('#select_all').bind('click', function() {
    if(this.checked) {
        $(':checkbox').each(function() {
            this.checked = true;
        });
    } else {
        $(':checkbox').each(function() {
            this.checked = false;
        });
    }
 });

But this function selects all checkboxes in both tables (as it is poorly written to do).    Is there an easy method of having the code select all checkboxes in each distinct tables.

Thanks.

Body:
It is advisable you use class attribute for your table since Id's are supposed to be unique.

Create a variable to store value for table closest to checkbox current checkbox triggered and Concatenate the variable with Selector.

$('.selectAll').bind('click', function() {
  var thisTable = $(this).closest('.checkTable');//closest table of this checkbox triggered
  var checkedState = this.checked;//variable for checkbox checked.
  $(':checkbox', thisTable).each(function(){//concatenate 'thisTable' variable with css selector and iterate
    this.checked = checkedState;
  })
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="checkTable">
  <tr>
    <th> <input type="checkbox" class="selectAll"></th>
    <th>Select All</th>
  </tr>
  <tr>
    <td><input type="checkbox" id="1"></td>
    <td>Hello</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="2"></td>
    <td>Hi</td>
  </tr>

</table>
<table class="checkTable">
  <tr>
    <th><input type="checkbox" class="selectAll"></th>
    <th>Select All</th>
  </tr>
  <tr>
    <td><input type="checkbox" id="3"></td>
    <td>One</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="4"></td>
    <td>Two</td>
  </tr>

</table>


问:
Dynamically Change the Key Value based on Delimiter in Perl
I'm reading from a CSV file and populating a Hash based on Key-Value Pairs.
The First Column of the record is the key, and the rest of the record is the value. However, for some file I need to make first 2 columns as Key and the rest of the record is value. I have written it as below  based on if loop by checking the number of Key Columns, but I wanted to know if there is any better way to do this?

```<code>use strict;
use warnings;

open my $fh, '<:encoding(utf8)', 'Sample.csv'
      or die "Couldn't open Sample.csv";
my %hash;
my $KeyCols=2;
    while (<$fh>) {
        chomp;
        if ($KeyCols==1) {
        next unless /^(.*?),(.*)$/;
        $hash{$1} = $2;
        }
        elsif ($KeyCols==2) {
        next unless /^(.*?),(.*?),(.*)$/;
        $hash{$1.$2} = $3;
        }
    }
</code>```

答:
Here is one way to allow for any number of key columns (not just 1 or 2), but it uses split instead of a regex:

```<code>use warnings;
use strict;

my %hash;
my $KeyCols = 2;
while (<DATA>) {
    chomp;
    my @cols = split /,/, $_, $KeyCols+1;
    next unless @cols > $KeyCols;
    my $v = pop @cols;
    my $k = join '', @cols;
    $hash{$k} = $v;
}

__DATA__
a,b,c,d,e,f
q,w,e,r,t,y
</code>```

This is a self-contained code example.

A big assumption is that your CSV file does not contain commas in the data itself.  You should be using a CSV parser such as Text::CSV anyway.

Body:
I'm reading from a CSV file and populating a Hash based on Key-Value Pairs.
The First Column of the record is the key, and the rest of the record is the value. However, for some file I need to make first 2 columns as Key and the rest of the record is value. I have written it as below  based on if loop by checking the number of Key Columns, but I wanted to know if there is any better way to do this?

use strict;
use warnings;

open my $fh, '<:encoding(utf8)', 'Sample.csv'
      or die "Couldn't open Sample.csv";
my %hash;
my $KeyCols=2;
    while (<$fh>) {
        chomp;
        if ($KeyCols==1) {
        next unless /^(.*?),(.*)$/;
        $hash{$1} = $2;
        }
        elsif ($KeyCols==2) {
        next unless /^(.*?),(.*?),(.*)$/;
        $hash{$1.$2} = $3;
        }
    }

Body:
Here is one way to allow for any number of key columns (not just 1 or 2), but it uses split instead of a regex:

use warnings;
use strict;

my %hash;
my $KeyCols = 2;
while (<DATA>) {
    chomp;
    my @cols = split /,/, $_, $KeyCols+1;
    next unless @cols > $KeyCols;
    my $v = pop @cols;
    my $k = join '', @cols;
    $hash{$k} = $v;
}

__DATA__
a,b,c,d,e,f
q,w,e,r,t,y

This is a self-contained code example.

A big assumption is that your CSV file does not contain commas in the data itself.  You should be using a CSV parser such as Text::CSV anyway.


问:
Problem regarding the time of downloading and creating app in react
I have typed out these-

```<code>npm -v
6.14.4
node -v
v12.17.0
npm i -g create-react-app
added a few packages
create-react-app react-app
</code>```

Now in the directory created I have a file named react-app. This has a package.json file.
This is present in the following package.json file.

```<code>{
  "name": "react-app",
  "version": "0.1.0",
  "private": true
}
</code>```

It has been almost six hours. There hasn't been a single file (other than package.json) been added. What changes do I need to make?. These are the lines after I enter the create react statement in command line.

```<code>Creating a new React app in C:\Users\<Closed>\<Closed>\react-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...
</code>```

It has the cursor in the next line and shows nothing, it keeps blinking.

答:
The official documentation suggests that you use npx. Try this:

```<code>npx create-react-app my-app
cd my-app
npm start
</code>```

See here: https://reactjs.org/docs/create-a-new-react-app.html

There is no reason why you should install create-react-app globally. (-g).

Also, if it takes longer than like 10minutes depending on your internet connection, stop the command since something is not working. Don't wait six hours!

Body:
I have typed out these-

npm -v
6.14.4
node -v
v12.17.0
npm i -g create-react-app
added a few packages
create-react-app react-app

Now in the directory created I have a file named react-app. This has a package.json file.
This is present in the following package.json file.

{
  "name": "react-app",
  "version": "0.1.0",
  "private": true
}

It has been almost six hours. There hasn't been a single file (other than package.json) been added. What changes do I need to make?. These are the lines after I enter the create react statement in command line.

Creating a new React app in C:\Users\<Closed>\<Closed>\react-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

It has the cursor in the next line and shows nothing, it keeps blinking.

Body:
The official documentation suggests that you use npx. Try this:

npx create-react-app my-app
cd my-app
npm start

See here: https://reactjs.org/docs/create-a-new-react-app.html

There is no reason why you should install create-react-app globally. (-g).

Also, if it takes longer than like 10minutes depending on your internet connection, stop the command since something is not working. Don't wait six hours!


问:
Static variable across multiple, different subclasses - corrected
I was wondering what happened if I define a base Activity object with all my activities as subclasses of that. Then I declare a static variable in the base class, will all the subclasses use the SAME static or will there be one per subclass.

For example. My base class:

```<code>public class MyBaseActivity extends Activity{

   static int myStatic;

   ...
   ....

}
</code>```

Then:

```<code>public class MyActivity1 extends MyBaseActivity {

   private void someMethod1(){
         myStatic = 1;
    }

   ...
   ....

}
</code>```

and

```<code>public class MyActivity1 extends MyBaseActivity {

   private void someMethod2(){
          if (myStatic == 1)
            doSomething();
    }

   ...
   ....

}
</code>```

If I now start MyActivity1 and it sets a value in "myStatic". It then exits and then I start MyActivity2 - should I still have the value set by the first activity?
In the example above, would the "if" statement be true or false?

I know that if I instantiate Activity1 more than once then obviously I would get the same static variable. However, here I am instantiating a different subclass each time.

I am getting the impression that that is what is happening to me but want to be sure.

答: Static is static.  They will reference the same object.</p>

Body:
I was wondering what happened if I define a base Activity object with all my activities as subclasses of that. Then I declare a static variable in the base class, will all the subclasses use the SAME static or will there be one per subclass.

For example. My base class:

public class MyBaseActivity extends Activity{

   static int myStatic;

   ...
   ....

}

Then:

public class MyActivity1 extends MyBaseActivity {

   private void someMethod1(){
         myStatic = 1;
    }

   ...
   ....

}

and

public class MyActivity1 extends MyBaseActivity {

   private void someMethod2(){
          if (myStatic == 1)
            doSomething();
    }

   ...
   ....

}

If I now start MyActivity1 and it sets a value in "myStatic". It then exits and then I start MyActivity2 - should I still have the value set by the first activity?
In the example above, would the "if" statement be true or false?

I know that if I instantiate Activity1 more than once then obviously I would get the same static variable. However, here I am instantiating a different subclass each time.

I am getting the impression that that is what is happening to me but want to be sure.