问:
What is the most useful script you've written for everyday life?
Just wondering what little scripts/programs people here have written that helps one with his or her everyday life (aka not work related).

Anything goes, groundbreaking or not. For me right now, it's a small python script to calculate running pace given distance and time elapsed.

答:
Running WinXP and I never seem to have time to kick off a defrag and wait for it to finish. So I wrote my own script to fire off XP's builtin defrag.exe and scheduled it to run nitely. The results are saved to a log file in C:\Temp for later review.</p>

```<code>@echo off

GOTO :MAIN
###########################################################
#
#  Reason:
#     This script runs the defrag utility.
#
#  Suggestion:
#     Schedule this script to run daily (via schtasks)
#
#     Example:
#        SCHTASKS /Create /SC DAILY /ST 03:00:00
#                 /TR \"C:\path\to\DAILY_DEFRAG.BAT" /TN "Daily Defrag of C Drive\"
#
#     Example:
#        AT 03:00 /every:Su,M,T,W,Th,F,Sa C:\path\to\DAILY_DEFRAG.BAT
#
#  Required OS:
#     Windows XP or Windows Server 2003
#
#  Required files:
#     DEFRAG.EXE
#
#
###########################################################

:MAIN

   :: Output a listing of scheduled tasks
   SCHTASKS /QUERY /V > C:\temp\schtasks.out

   :: *****************************************************
   :: * SITE SPECIFIC Program Parameters                  *
   :: *****************************************************
   :: * Drive to defrag
        SET TARGET=C:

   :: * Log file
        SET LOGFILE=C:\temp\defrag.log

   :: *****************************************************
   :: * No editable parameters below this line            *
   :: *****************************************************

   SETLOCAL

   :: Announce intentions
   echo.
   echo Beginning defragmentation of disk %TARGET%
   echo ----------------------------------------------

   echo.
   for /f "tokens=1 delims=_" %%a in ('date /t') do set NOW=%%a
   for /f "tokens=1 delims=_" %%a in ('time /t') do set NOW=%NOW% %%a
   echo  Start time: %NOW%

   :: Run the defrag utility
   C:\WINNT\SYSTEM32\defrag.exe %TARGET% -f -v > %LOGFILE%

   echo.
   for /f "tokens=1 delims=_" %%a in ('date /t') do set NOW=%%a
   for /f "tokens=1 delims=_" %%a in ('time /t') do set NOW=%NOW% %%a
   echo    End time: %NOW%

   echo.
   echo ----------------------------------------------
   echo Defrag complete.
   echo.

:END
</code>```

OwnerDisplayName: Kyle Walsh

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kyle Walsh

Body:
Running WinXP and I never seem to have time to kick off a defrag and wait for it to finish. So I wrote my own script to fire off XP's builtin defrag.exe and scheduled it to run nitely. The results are saved to a log file in C:\Temp for later review.

@echo off

GOTO :MAIN
###########################################################
#
#  Reason:
#     This script runs the defrag utility.
#
#  Suggestion:
#     Schedule this script to run daily (via schtasks)
#
#     Example:
#        SCHTASKS /Create /SC DAILY /ST 03:00:00
#                 /TR \"C:\path\to\DAILY_DEFRAG.BAT" /TN "Daily Defrag of C Drive\"
#
#     Example:
#        AT 03:00 /every:Su,M,T,W,Th,F,Sa C:\path\to\DAILY_DEFRAG.BAT
#
#  Required OS:
#     Windows XP or Windows Server 2003
#
#  Required files:
#     DEFRAG.EXE
#
#
###########################################################

:MAIN

   :: Output a listing of scheduled tasks
   SCHTASKS /QUERY /V > C:\temp\schtasks.out

   :: *****************************************************
   :: * SITE SPECIFIC Program Parameters                  *
   :: *****************************************************
   :: * Drive to defrag
        SET TARGET=C:

   :: * Log file
        SET LOGFILE=C:\temp\defrag.log

   :: *****************************************************
   :: * No editable parameters below this line            *
   :: *****************************************************

   SETLOCAL

   :: Announce intentions
   echo.
   echo Beginning defragmentation of disk %TARGET%
   echo ----------------------------------------------

   echo.
   for /f "tokens=1 delims=_" %%a in ('date /t') do set NOW=%%a
   for /f "tokens=1 delims=_" %%a in ('time /t') do set NOW=%NOW% %%a
   echo  Start time: %NOW%

   :: Run the defrag utility
   C:\WINNT\SYSTEM32\defrag.exe %TARGET% -f -v > %LOGFILE%

   echo.
   for /f "tokens=1 delims=_" %%a in ('date /t') do set NOW=%%a
   for /f "tokens=1 delims=_" %%a in ('time /t') do set NOW=%NOW% %%a
   echo    End time: %NOW%

   echo.
   echo ----------------------------------------------
   echo Defrag complete.
   echo.

:END

OwnerDisplayName: robmandu


来源: stackexchange

问:
Swing - how to handle multiple cross-dependent components?
This is a more general question:
I have a quite complicated files table in swing (the data model is not trivial) , and when when the user clicks on an entry , two other view components need to change - File statistics view , and the file content view - both on the same screen.

One options is to have all these components class definitions in the same file , and then have the reference each other - But this will make a very messy code.

The other option I could think of is to pass the statistics and content components to the table object , and have him use it - but that will render the table not - reusable anywhere else.

I'm sure there's a better way to do it - what would you recommend to do?

Option 1:

```<code>class MyPanel extends JPanel{

private MyTable table;
private MyFileViewer fv;
private MyFileStats stats;

class MyTable {
   addMouseListener({ ... fv.update(); stats.update(); })
}
class MyFileViewer{...}
class MyFileStats{...}
}
</code>```

Options 2:

```<code>class MyTable {

   MyTable(MyFileViewer fv, MyFileStats stats) { ...
       addMouseListener({fv.update, stats.update ... }
   }
}
</code>```

答: Option 3: The Model–View–Controller pattern, as discussed here and in this outline. MVC hinges on the observer pattern. Instead of having each view update the others, arrange for each view to register itself as a listener to your data model. When the model changes, each view updates itself accordingly.</p>

ContentLicense: CC BY-SA 3.0

Body:
This is a more general question:
I have a quite complicated files table in swing (the data model is not trivial) , and when when the user clicks on an entry , two other view components need to change - File statistics view , and the file content view - both on the same screen.

One options is to have all these components class definitions in the same file , and then have the reference each other - But this will make a very messy code.

The other option I could think of is to pass the statistics and content components to the table object , and have him use it - but that will render the table not - reusable anywhere else.

I'm sure there's a better way to do it - what would you recommend to do?

Option 1:

class MyPanel extends JPanel{

private MyTable table;
private MyFileViewer fv;
private MyFileStats stats;

class MyTable {
   addMouseListener({ ... fv.update(); stats.update(); })
}
class MyFileViewer{...}
class MyFileStats{...}
}

Options 2:

class MyTable {

   MyTable(MyFileViewer fv, MyFileStats stats) { ...
       addMouseListener({fv.update, stats.update ... }
   }
}


问:
Vlookup Search Issue using *
I'm having a problem with the Vlookup function and I can not think of a way to fix it. For certain reasons, I could not add columns so I would have to be able to solve it in the formula.

Basically, I have two strings in the same column, CEP * and CEPCP and on the right I have other columns with information belonging to those two strings. The problem is that if I do a Vlookup from another sheet, when I search for the string CEP * it brings me the CEPCP information because excel interprets that I'm looking for anything that starts with CEP.

Is there any way to solve it with formulas?

Thanks!

EDIT: The Vlookup is the following:

VLOOKUP(A2;Users!A:P;4;FALSE)

Being A2 the CEP *

答:
You need to append the * with ~* to let Excel know that you want the actual string not the wildcard.

```<code>SUBSTITUTE(A2;"*";"~*")
</code>```

SUBSTITUTE does not use wildcards.

```<code>VLOOKUP(SUBSTITUTE(A2;"*";"~*");Users!A:P;4;FALSE)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Vlookup Search Issue using *

Body:
You need to append the * with ~* to let Excel know that you want the actual string not the wildcard.

SUBSTITUTE(A2;"*";"~*")

SUBSTITUTE does not use wildcards.

VLOOKUP(SUBSTITUTE(A2;"*";"~*");Users!A:P;4;FALSE)


问:
reformat dataset from long to wide dataset
Hopefully, you can help my question.

I have dataset looks like this. There are 1500 rows.

```<code>+-------+---------+---------+--------+
| index |   item  |  taste  |  price |
+-------+---------+---------+--------+
|     1 |  orange |  low    |      3 |
|     1 | banana  |  medium |      4 |
|     1 |  pier   |  high   |      2 |
|     2 | apple   | medium  |      4 |
|     2 |  orange |  medium |      4 |
|     2 |  banana |  medium |      3 |
|   ... | ...     | ...     |    ... |
|  1500 | 1500    |  1500   |   1500 |
+-------+---------+---------+--------+
</code>```

I use this code but got an error message:

```<code>library(data.table)

dcast(setDT(df), index ~ item, value.var = c("taste", "price"))
</code>```

the error massage:

Error in .subset2(x, i, exact = exact) : subscript out of bounds
  In addition: Warning message:
  In if (!(value.var %in% names(data))) { :
    the condition has length > 1 and only the first element will be used

this is the expected result that I want to get.

```<code>index, item, taste_orange,taste.banana, taste.pier, taste.apple, price_orange,price.banana, price.pier, price.apple,
1, low,medium,high,0,3,4,2,0
2, medium,medium,0,medium,4,3,0,4
...,...,...,...,...,...,...,....,...
1500,1500, 1500,1500,1500,1500,1500,1500,1500
</code>```

Thanks in advance!

答:
If you don't mind a tidyverse approach you could do something like:

```<code>library(tidyverse)
test <- read_delim(file=clipboard(),
  col_names=TRUE, delim=",", trim_ws=TRUE) ## copied your 6 lines of data into the clipboard
test %>%
  gather(key, value, -item, -index) %>%
  unite("names", item, key) %>%
  spread(names, value) %>%
  mutate_at(vars(ends_with("_price")), as.numeric)
# A tibble: 2 x 9
  index apple_price apple_taste banana_price banana_taste orange_price
  <dbl>       <dbl> <chr>              <dbl> <chr>               <dbl>
1     1          NA NA                     4 medium                  3
2     2           4 medium                 3 medium                  4
# … with 3 more variables: orange_taste <chr>, pier_price <dbl>,
#   pier_taste <chr>
</code>```

The "gather" command creates a "long" dataframe in which the "key" variable contains the type of information stored (i.e., taste and price), and the "value" variable contains the actual values; since the values are of different type, the numeric values are coerced into character. "unite" merges into a new column "names" the item description and the type of information. "spread" creates a new column for each value of the "names" column, with the corresponding values. The last bit (mutate_at) converts back prices to numeric format.

Body:
Hopefully, you can help my question.

I have dataset looks like this. There are 1500 rows.

+-------+---------+---------+--------+
| index |   item  |  taste  |  price |
+-------+---------+---------+--------+
|     1 |  orange |  low    |      3 |
|     1 | banana  |  medium |      4 |
|     1 |  pier   |  high   |      2 |
|     2 | apple   | medium  |      4 |
|     2 |  orange |  medium |      4 |
|     2 |  banana |  medium |      3 |
|   ... | ...     | ...     |    ... |
|  1500 | 1500    |  1500   |   1500 |
+-------+---------+---------+--------+

I use this code but got an error message:

library(data.table)

dcast(setDT(df), index ~ item, value.var = c("taste", "price"))

the error massage:

Error in .subset2(x, i, exact = exact) : subscript out of bounds
  In addition: Warning message:
  In if (!(value.var %in% names(data))) { :
    the condition has length > 1 and only the first element will be used

this is the expected result that I want to get.

index, item, taste_orange,taste.banana, taste.pier, taste.apple, price_orange,price.banana, price.pier, price.apple,
1, low,medium,high,0,3,4,2,0
2, medium,medium,0,medium,4,3,0,4
...,...,...,...,...,...,...,....,...
1500,1500, 1500,1500,1500,1500,1500,1500,1500

Thanks in advance!

Body:
If you don't mind a tidyverse approach you could do something like:

library(tidyverse)
test <- read_delim(file=clipboard(),
  col_names=TRUE, delim=",", trim_ws=TRUE) ## copied your 6 lines of data into the clipboard
test %>%
  gather(key, value, -item, -index) %>%
  unite("names", item, key) %>%
  spread(names, value) %>%
  mutate_at(vars(ends_with("_price")), as.numeric)
# A tibble: 2 x 9
  index apple_price apple_taste banana_price banana_taste orange_price
  <dbl>       <dbl> <chr>              <dbl> <chr>               <dbl>
1     1          NA NA                     4 medium                  3
2     2           4 medium                 3 medium                  4
# … with 3 more variables: orange_taste <chr>, pier_price <dbl>,
#   pier_taste <chr>

The "gather" command creates a "long" dataframe in which the "key" variable contains the type of information stored (i.e., taste and price), and the "value" variable contains the actual values; since the values are of different type, the numeric values are coerced into character. "unite" merges into a new column "names" the item description and the type of information. "spread" creates a new column for each value of the "names" column, with the corresponding values. The last bit (mutate_at) converts back prices to numeric format.


问:
How to Access Different Google Sheets From Python?
So I have Python basically connected to google sheets at the moment. It can access the first sheet and read and write data:

sheet = client.open("Remake").sheet1
```

<p>I can access sheet 1 inside the overarching spreadsheet, but I cannot access the second sheet (sheet2) by just changing it to:</p>

<pre class="lang-py prettyprint-override"><code>sheet = client.open("Remake").sheet2
</code>```

答:
To explain this, it is because Google Spreadsheet only implemented sheet1 to let you retrieve the first sheet in your spreadsheet as a shortcut. So if you want to retrieve other sheets, you need to use other methods like:

```<code>wks = gc.open("doc_name").get_worksheet(index)
</code>```

or

```<code>wks = gc.open("doc_name").worksheet(title)
</code>```

Related infos:

repo

SO post

Body:
So I have Python basically connected to google sheets at the moment. It can access the first sheet and read and write data:

sheet = client.open("Remake").sheet1

I can access sheet 1 inside the overarching spreadsheet, but I cannot access the second sheet (sheet2) by just changing it to:

sheet = client.open("Remake").sheet2

Body:
To explain this, it is because Google Spreadsheet only implemented sheet1 to let you retrieve the first sheet in your spreadsheet as a shortcut. So if you want to retrieve other sheets, you need to use other methods like:

wks = gc.open("doc_name").get_worksheet(index)

or

wks = gc.open("doc_name").worksheet(title)

Related infos:

repo

SO post


问:
React Bootstrap table not formatting
I am very new to react and am attempting to follow a basic table tutorial.

I have installed react-bootstrap-table

```<code>npm install react-bootstrap-table --save
</code>```

I have imported bootstrap-table

```<code>import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
</code>```

I have imported the css file:

```<code>import '../../node_modules/react-bootstrap-table/dist/react-bootstrap-table-all.min.css';
</code>```

With the above I am expecting a table to display as below:

However what I am seeing with my code is:

Why isn't the table appearing as in the example?

```<code>import React, { Component } from "react";
import './MenuButton.css';
import './MenuContainer.css';
import MenuButton from './MenuButton';
import Menu from './Menu';
import serverCall from "../api/ServerCall";
import {BootstrapTable,TableHeaderColumn} from 'react-bootstrap-table';
import '../../node_modules/react-bootstrap-table/css/react-bootstrap-table.css'

class MenuContainer extends Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            visible: false
        };
        this.handleMouseDown = this.handleMouseDown.bind(this);
        this.toggleMenu = this.toggleMenu.bind(this);

        this.getCustomers();
    }

    handleMouseDown(e) {
        this.toggleMenu();
        e.stopPropagation();
    }

    toggleMenu() {
        this.setState({
            visible: !this.state.visible
        });
    }

     getCustomers(){
              console.log("Getting Customers");
        serverCall(function(error, response) {
            if (error) {
                alert("Authorization Failed.")
            } else {
                console.log(response);

            }
        },"","customers.php");
    }

    render() {

        let products = [{
            id: 1,
            name: "Item name 1",
            price: 100
        },{
            id: 2,
            name: "Item name 2",
            price: 100
        }];

        return (

            <div>
                <div className="menu-container">
                    <div className="grid-item-hamburger-menu">
                        <MenuButton handleMouseDown={this.handleMouseDown}/>
                        <Menu handleMouseDown={this.handleMouseDown} menuVisibility={this.state.visible}/>
                    </div>

                    <div className="grid-item-dashboard-title">
                        Dashboard | Customers
                    </div>

                    <div className="grid-item-search">
                    </div>

                    <div className="grid-item-table">

                        <BootstrapTable data={ products }>
                            <TableHeaderColumn dataField='id' isKey>Product ID</TableHeaderColumn>
                            <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
                            <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
                        </BootstrapTable>
                </div>
                </div>
            </div>
        );
    }
}

export default MenuContainer;
</code>```

答:
For future reference, you should only need to import from the base of the app and not the node_modules path. I use the following and it works fine:

import 'react-bootstrap-table/dist/react-bootstrap-table-all.min.css'

Title: React Bootstrap table not formatting

Body:
I am very new to react and am attempting to follow a basic table tutorial.

I have installed react-bootstrap-table

npm install react-bootstrap-table --save

I have imported bootstrap-table

import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';

I have imported the css file:

import '../../node_modules/react-bootstrap-table/dist/react-bootstrap-table-all.min.css';

With the above I am expecting a table to display as below:

However what I am seeing with my code is:

Why isn't the table appearing as in the example?

import React, { Component } from "react";
import './MenuButton.css';
import './MenuContainer.css';
import MenuButton from './MenuButton';
import Menu from './Menu';
import serverCall from "../api/ServerCall";
import {BootstrapTable,TableHeaderColumn} from 'react-bootstrap-table';
import '../../node_modules/react-bootstrap-table/css/react-bootstrap-table.css'

class MenuContainer extends Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            visible: false
        };
        this.handleMouseDown = this.handleMouseDown.bind(this);
        this.toggleMenu = this.toggleMenu.bind(this);

        this.getCustomers();
    }

    handleMouseDown(e) {
        this.toggleMenu();
        e.stopPropagation();
    }

    toggleMenu() {
        this.setState({
            visible: !this.state.visible
        });
    }

     getCustomers(){
              console.log("Getting Customers");
        serverCall(function(error, response) {
            if (error) {
                alert("Authorization Failed.")
            } else {
                console.log(response);

            }
        },"","customers.php");
    }

    render() {

        let products = [{
            id: 1,
            name: "Item name 1",
            price: 100
        },{
            id: 2,
            name: "Item name 2",
            price: 100
        }];

        return (

                        <MenuButton handleMouseDown={this.handleMouseDown}/>
                        <Menu handleMouseDown={this.handleMouseDown} menuVisibility={this.state.visible}/>

                        Dashboard | Customers

                        <BootstrapTable data={ products }>
                            <TableHeaderColumn dataField='id' isKey>Product ID</TableHeaderColumn>
                            <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
                            <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
                        </BootstrapTable>

        );
    }
}

export default MenuContainer;


问:
How do I keep appending contents of a cell to a different sheet?
I have two columns of data. One is the a column named notes and the other is notes history. I update the notes section everyday, adding in today's note, a single or a double liner. My intention is to keep a record of everything I typed in this column which is similar to appending the notes to the history table</p>

答:
You could try sheet events :</p>

```<code>Option Explicit

Public Old_value As String

Private Sub Worksheet_Change(ByVal Target As Range)

    MsgBox "Old Value is: " & Old_value & vbNewLine & "New Value is: " & Target.Value

End Sub

Public Sub Worksheet_SelectionChange(ByVal Target As Range)

    'Let us assume that Notes appear in column A
    If Not Intersect(Target, Range("A:A")) Is Nothing Then
        Old_value = Target.Value
    End If

End Sub
</code>```

Body:
You could try sheet events :

Option Explicit

Public Old_value As String

Private Sub Worksheet_Change(ByVal Target As Range)

    MsgBox "Old Value is: " & Old_value & vbNewLine & "New Value is: " & Target.Value

End Sub

Public Sub Worksheet_SelectionChange(ByVal Target As Range)

    'Let us assume that Notes appear in column A
    If Not Intersect(Target, Range("A:A")) Is Nothing Then
        Old_value = Target.Value
    End If

End Sub


问:
Basic movie database interacting with external API
In job offers I often see the word "REST-API". So, I'd like to learn what REST-API actually is. I have some experience in Django. Well, I'm a beginner actually.

I found on GitHub a simple task: https://github.com/netguru/python-recruitment-task The only thing I don't understand is how to do this:

```<code>POST /movies:
    Request body should contain only movie title, and its presence should be validated.
    Based on passed title, other movie details should be fetched from http://www.omdbapi.com/ (or other similar, public movie database) - and saved to application database.
    Request response should include full movie object, along with all data fetched from external API.
</code>```

How should it looks like?

How to validate the "presence"?

How to download data from public databases?

答:
How should it looks like?

Maybe you'll be using Django to make this task, but you should understand the concept with the following and, probably, might adapt:

import sys

import requests

API_KEY = '<API_KEY>'

def insert_to_db():
    raise NotImplementedError("Implement this function by yourself.")

if __name__ == "__main__":
    title = '+'.join([arg for arg in sys.argv[1:]])

    # Check if title is found in argument list. It's a validation.
    if not title:
        raise IndexError("No title entered!")

    # The request itself.
    response = requests.get(f"http://www.omdbapi.com/?t={title}&apikey={API_KEY}").json()
    if response:
        print(response)
```

<p>This is a simple program, it reads your input (the movie title) through any terminal you're using, makes a simple request (using requests module) to your API and fetches a response in JSON. This is it's output:</p>

<pre class="lang-sh prettyprint-override"><code>$ python api.py city of god
{'Title': 'City of God', 'Year': '2002', 'Rated': 'R', 'Released': '13 Feb 2004', 'Runtime': '130 min', 'Genre': 'Crime, Drama', 'Director': 'Fernando Meirelles, Kátia Lund(co-director)', 'Writer': 'Paulo Lins (novel), Bráulio Mantovani (screenplay)', 'Actors': 'Alexandre Rodrigues, Leandro Firmino, Phellipe Haagensen, Douglas Silva', 'Plot': "In the slums of Rio, two kids' paths diverge as one struggles to become a photographer and the other a kingpin.", 'Language': 'Portuguese', 'Country': 'Brazil, France, Germany', 'Awards': 'Nominated for 4 Oscars. Another 66 wins & 38 nominations.', 'Poster': 'https://m.media-amazon.com/images/M/MV5BMGU5OWEwZDItNmNkMC00NzZmLTk1YTctNzVhZTJjM2NlZTVmXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg', 'Ratings': [{'Source': 'Internet Movie Database', 'Value': '8.6/10'}, {'Source': 'Rotten Tomatoes', 'Value': '91%'}, {'Source': 'Metacritic', 'Value': '79/100'}], 'Metascore': '79', 'imdbRating': '8.6', 'imdbVotes': '639,695', 'imdbID': 'tt0317248', 'Type': 'movie', 'DVD': '08 Jun 2004', 'BoxOffice': 'N/A', 'Production': 'Miramax Films', 'Website': 'http://www.miramax.com/movie/city-of-god', 'Response': 'True'}
</code>```

How to validate the "presence"?

Analyzing the program should clear your doubts.

    title = '+'.join([arg for arg in sys.argv[1:]])

    # Check if title is found in argument list. It's a validation.
    if not title:
        raise IndexError("No title entered!")
```

<p>This part of the code checks if a title is passed to your request. This is called <em>validation</em> and when you're dealing with APIs, it's important to clean the user input data before interacting with it, otherwise, it can mess up your API with unexpected behavior.</p>

<blockquote>
  <p><em>How to download data from public databases?</em></p>
</blockquote>

<p>This is a general question, you might need to explain further what you're trying to download. Databases varies, and APIs interface the communication with the DB by executing queries on your behalf. You might need to elaborate on that.</p>

<p>But downloading a JSON file with the API in question is really simple. If you're using Linux and you're kind of familiar with curl, just make a request with it and redirect it's output to a file:</p>

<pre class="lang-sh prettyprint-override"><code>curl "http://www.omdbapi.com/?t=the+professional&apikey=<API_KEY>" >> out.json
</code>```

With this example, you might relate an example of how to deal with external APIs, then it's up to you.

Body:
In job offers I often see the word "REST-API". So, I'd like to learn what REST-API actually is. I have some experience in Django. Well, I'm a beginner actually.

I found on GitHub a simple task: https://github.com/netguru/python-recruitment-task The only thing I don't understand is how to do this:

POST /movies:
    Request body should contain only movie title, and its presence should be validated.
    Based on passed title, other movie details should be fetched from http://www.omdbapi.com/ (or other similar, public movie database) - and saved to application database.
    Request response should include full movie object, along with all data fetched from external API.

How should it looks like?

How to validate the "presence"?

How to download data from public databases?

Body:
How should it looks like?

Maybe you'll be using Django to make this task, but you should understand the concept with the following and, probably, might adapt:

import sys

import requests

API_KEY = '<API_KEY>'

def insert_to_db():
    raise NotImplementedError("Implement this function by yourself.")

if __name__ == "__main__":
    title = '+'.join([arg for arg in sys.argv[1:]])

    # Check if title is found in argument list. It's a validation.
    if not title:
        raise IndexError("No title entered!")

    # The request itself.
    response = requests.get(f"http://www.omdbapi.com/?t={title}&apikey={API_KEY}").json()
    if response:
        print(response)

This is a simple program, it reads your input (the movie title) through any terminal you're using, makes a simple request (using requests module) to your API and fetches a response in JSON. This is it's output:

$ python api.py city of god
{'Title': 'City of God', 'Year': '2002', 'Rated': 'R', 'Released': '13 Feb 2004', 'Runtime': '130 min', 'Genre': 'Crime, Drama', 'Director': 'Fernando Meirelles, Kátia Lund(co-director)', 'Writer': 'Paulo Lins (novel), Bráulio Mantovani (screenplay)', 'Actors': 'Alexandre Rodrigues, Leandro Firmino, Phellipe Haagensen, Douglas Silva', 'Plot': "In the slums of Rio, two kids' paths diverge as one struggles to become a photographer and the other a kingpin.", 'Language': 'Portuguese', 'Country': 'Brazil, France, Germany', 'Awards': 'Nominated for 4 Oscars. Another 66 wins & 38 nominations.', 'Poster': 'https://m.media-amazon.com/images/M/MV5BMGU5OWEwZDItNmNkMC00NzZmLTk1YTctNzVhZTJjM2NlZTVmXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg', 'Ratings': [{'Source': 'Internet Movie Database', 'Value': '8.6/10'}, {'Source': 'Rotten Tomatoes', 'Value': '91%'}, {'Source': 'Metacritic', 'Value': '79/100'}], 'Metascore': '79', 'imdbRating': '8.6', 'imdbVotes': '639,695', 'imdbID': 'tt0317248', 'Type': 'movie', 'DVD': '08 Jun 2004', 'BoxOffice': 'N/A', 'Production': 'Miramax Films', 'Website': 'http://www.miramax.com/movie/city-of-god', 'Response': 'True'}

How to validate the "presence"?

Analyzing the program should clear your doubts.

    title = '+'.join([arg for arg in sys.argv[1:]])

    # Check if title is found in argument list. It's a validation.
    if not title:
        raise IndexError("No title entered!")

This part of the code checks if a title is passed to your request. This is called validation and when you're dealing with APIs, it's important to clean the user input data before interacting with it, otherwise, it can mess up your API with unexpected behavior.

How to download data from public databases?

This is a general question, you might need to explain further what you're trying to download. Databases varies, and APIs interface the communication with the DB by executing queries on your behalf. You might need to elaborate on that.

But downloading a JSON file with the API in question is really simple. If you're using Linux and you're kind of familiar with curl, just make a request with it and redirect it's output to a file:

curl "http://www.omdbapi.com/?t=the+professional&apikey=<API_KEY>" >> out.json

With this example, you might relate an example of how to deal with external APIs, then it's up to you.


问:
ActiveMQ test connection
I am trying to test ActiveMQ connection and return a value. it crashes on line:

httpResponse  = client.execute(theHttpGet);
```

<p>It is not my code I am trying to debug it. Can anyone help me to understand why the code is using <code>HttpGet</code>?</p>

<pre class="lang-java prettyprint-override"><code>  public ActivemqBrokerInfo(String serverAddress, int port, String apiUrl, int timeout) {

    // Default Activemq location
    this.serverAddress = String.format("http://%s:%s/%s", serverAddress, port, apiUrl);

    int timeoutInMs = timeout;

    HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutInMs).build();
    builder.setDefaultRequestConfig(requestConfig);

    client = builder.build();
  }

  public ActivemqBrokerInfo(String serverAddress) {

    this(serverAddress, DEFAULT_PORT, DEFAULT_API_URL, DEFAULT_TIMEOUT);
  }

  @Override
  public boolean testConnection() {

    HttpGet theHttpGet = new HttpGet(serverAddress);
    theHttpGet.addHeader("test-header-name", "test-header-value");
    HttpResponse httpResponse = null;

    try{
      httpResponse  = client.execute(theHttpGet);// Code is crashing on this line
    } catch (IOException ex){
      LOGGER.error("Broker down: ", ex);
    }

    return httpResponse != null;
  }
</code>```

答:
When ActiveMQ runs is normally starts an embedded web server. This web server is used to host the web admin console as well as the Jolokia endpoint which acts as an HTTP facade in front of the broker's MBeans. In other words, any client can send HTTP requests to specially formed URLs on the broker to get results from the underlying management beans. This is exactly what your bit of code appears to be doing. It appears to be sending an HTTP request to the Jolokia endpoint (i.e. api/jolokia) in order to determine if the broker is alive or not.

Based on the information provided it is impossible to determine why testConnection() is not returning successfully since you've included no information about the configuration or state of the broker.

I recommend you add additional logging to see what may be happening and also catch Exception rather than just IOException.

Title: ActiveMQ test connection

Body:
I am trying to test ActiveMQ connection and return a value. it crashes on line:

httpResponse  = client.execute(theHttpGet);

It is not my code I am trying to debug it. Can anyone help me to understand why the code is using HttpGet?

  public ActivemqBrokerInfo(String serverAddress, int port, String apiUrl, int timeout) {

    // Default Activemq location
    this.serverAddress = String.format("http://%s:%s/%s", serverAddress, port, apiUrl);

    int timeoutInMs = timeout;

    HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutInMs).build();
    builder.setDefaultRequestConfig(requestConfig);

    client = builder.build();
  }

  public ActivemqBrokerInfo(String serverAddress) {

    this(serverAddress, DEFAULT_PORT, DEFAULT_API_URL, DEFAULT_TIMEOUT);
  }

  @Override
  public boolean testConnection() {

    HttpGet theHttpGet = new HttpGet(serverAddress);
    theHttpGet.addHeader("test-header-name", "test-header-value");
    HttpResponse httpResponse = null;

    try{
      httpResponse  = client.execute(theHttpGet);// Code is crashing on this line
    } catch (IOException ex){
      LOGGER.error("Broker down: ", ex);
    }

    return httpResponse != null;
  }


答:
Demo, assuming Name is unique in the first table </p>

```<code>create table tab1 (
  id int identity
 ,TranslationId int null
 ,Name nvarchar(max) null
 );
 insert tab1 (Name)
     values
     ('Image1.jpg')
    ,('Image7.jpg')
    ,('Picture_Test.png')
    ,(null)

create table tab2 (
  id int identity (100,1)
 ,De nvarchar(max) null
 ,Fr nvarchar(max) null
 ,En nvarchar(max) null
 );

-- Update them

declare @map table(
  name nvarchar(max)
 ,ref int
  );

insert tab2 (de)
output inserted.De, inserted.id
into @map(Name, ref)
select Name
from tab1 src
where Name is not null and not exists (select 1 from tab2 t2 where t2.De = src.Name);

update t1 set TranslationId = ref, Name = null
from tab1 t1
join @map m on t1.Name = m.Name;

select * from tab1;
select * from tab2;
</code>```

Title: Insert on a child table and update FK on parent

Body:
I have a parent table with the following structure and data:

---------------------------------------------
|  Id | TranslationId |                Name |
---------------------------------------------
|   1 |          NULL |          Image1.jpg |
|   2 |          NULL |          Image7.jpg |
|   3 |          NULL |    Picture_Test.png |
---------------------------------------------

And the empty child table which holds the translated images:

-------------------------------------------------------------------------
|  Id |                  De |                  Fr |                  En |
-------------------------------------------------------------------------
|     |                     |                     |                     |
-------------------------------------------------------------------------

Now I'm looking for a single query statement or at least few queries which I can run without any further programming. Doing this job with scripting or programming would be easy but I have often situations where I need this kind of insert / update. And developing each time a small console app is not feasible.

At the end the two tables should look like this:

---------------------------------------------
|  Id | TranslationId |                Name |
---------------------------------------------
|   1 |            28 |                NULL |
|   2 |            29 |                NULL |
|   3 |            30 |                NULL |
---------------------------------------------

-------------------------------------------------------------------------
|  Id |                  De |                  Fr |                  En |
-------------------------------------------------------------------------
|  28 |          Image1.jpg |                NULL |               NULL  |
|  29 |          Image7.jpg |                NULL |               NULL  |
|  30 |    Picture_Test.png |                NULL |               NULL  |
-------------------------------------------------------------------------

Thank you for any advice.

Body:
Demo, assuming Name is unique in the first table

create table tab1 (
  id int identity
 ,TranslationId int null
 ,Name nvarchar(max) null
 );
 insert tab1 (Name)
     values
     ('Image1.jpg')
    ,('Image7.jpg')
    ,('Picture_Test.png')
    ,(null)

create table tab2 (
  id int identity (100,1)
 ,De nvarchar(max) null
 ,Fr nvarchar(max) null
 ,En nvarchar(max) null
 );

-- Update them

declare @map table(
  name nvarchar(max)
 ,ref int
  );

insert tab2 (de)
output inserted.De, inserted.id
into @map(Name, ref)
select Name
from tab1 src
where Name is not null and not exists (select 1 from tab2 t2 where t2.De = src.Name);

update t1 set TranslationId = ref, Name = null
from tab1 t1
join @map m on t1.Name = m.Name;

select * from tab1;
select * from tab2;


问:
Is there any way to make Visual Studio C++ error output useful?
I find VS19 output quite useless when working on C++ project. Consider running the example code on freshly installed VS19:

```<code>#include <iostream>

using namespace std;
class My
{
    public:
    void f() noexcept
    {
        throw exception{"A problem sir!"};
    }
};

int main()
{
    try
    {
        My m;
        m.f();
    }
    catch (exception& ex)
    {
        cout << "exception caught! " << ex.what() << endl;
    }
    return 0;
}
</code>```

What I would like to receive is: "Function throws an exception while marked as noexcept", and the cursor set on the problematic line. What I get is a new window with some general text, none of which mentions the problem, or where the problem is.

答:
Your verbosity parameter of MSBuild is may be too high. Go to menu: Tools -> Options. Then on the left pane select: Projects and Solutions -> Build and Run.
There you can select the appropriate verbosity of MSBuild (from Quiet to Diagnostic)</p>

Body:
I find VS19 output quite useless when working on C++ project. Consider running the example code on freshly installed VS19:

#include <iostream>

using namespace std;
class My
{
    public:
    void f() noexcept
    {
        throw exception{"A problem sir!"};
    }
};

int main()
{
    try
    {
        My m;
        m.f();
    }
    catch (exception& ex)
    {
        cout << "exception caught! " << ex.what() << endl;
    }
    return 0;
}

What I would like to receive is: "Function throws an exception while marked as noexcept", and the cursor set on the problematic line. What I get is a new window with some general text, none of which mentions the problem, or where the problem is.


问:
Remove a users reaction from fetchMessage? - Discord JS
I have a question for Discord.js.
How would I remove a specific user's reaction from a message?

I have tried to do so with this code:

```<code>// Now known as 'messages.fetch'.
message.channel.fetchMessage(MessageID).then(m => {
   m.reactions.remove(UserID);
});
</code>```

But it doesn't remove the user's reaction at all. Am I doing something wrong?

Any help would be appreciated.

答:
If you look at the documentation for reactions you can see it is a Collection, and it mentions that they are mapped by reaction ID's , and not the user ID's. The way you could remove them is get the reaction, filter the users and then maybe do something with that? I'm not sure how to remove those specifically, but that should get you the users, then filter that to the ID you want.

message.channel.fetchMessage(messageID).then(msg = m.reactions.get(reactionID).users); // Gets the users that reacted to a certain emote, I think.
```

Body:
I have a question for Discord.js.
How would I remove a specific user's reaction from a message?

I have tried to do so with this code:

// Now known as 'messages.fetch'.
message.channel.fetchMessage(MessageID).then(m => {
   m.reactions.remove(UserID);
});

But it doesn't remove the user's reaction at all. Am I doing something wrong?

Any help would be appreciated.


问:
Cannot connect to iTunes Store error while trying to send SKProductRequest
I have called "start" method of the "SKProductsRequest" class after creating and initializing object for the same.The delegate of this object is defining productsRequest:didReceiveResponse: method and request:didFailWithError: method. After the method     request:didFailWithError: is called i'm getting an error saying "Cannot connect to iTunes Store".
.My code is as follows:

```<code>-(IBAction)sendProductInfoRequest{
NSLog(@"sendProductInfoRequest");
NSSet *identifiersSet=[NSSet setWithObject:[NSString stringWithFormat:@"%@",@"com.hurix.Kitaboo.07APRIL201101"]];
SKProductsRequest *productRequest=[[SKProductsRequest alloc] initWithProductIdentifiers:identifiersSet];
productRequest.delegate=self;
[productRequest start];
NSLog(@"completing sendProductInfoRequest");
</code>```

}

```<code>- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
NSLog(@"request didFailWithError");
NSLog(@"The product request didFailWithError: %@",[error localizedDescription]);
</code>```

}

```<code>- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
NSLog(@"yoooo!");
NSLog(@"The product request didReceiveResponse :%@",[response description]);
</code>```

}

答: Usually it's really fast, couple of seconds at most. I'm guessing you're doing this on the sandbox environment, which I found really unreliable and unresponsive at times. I wouldn't worry too much about it and try again in a few hours.</p>

Body:
I have called "start" method of the "SKProductsRequest" class after creating and initializing object for the same.The delegate of this object is defining productsRequest:didReceiveResponse: method and request:didFailWithError: method. After the method     request:didFailWithError: is called i'm getting an error saying "Cannot connect to iTunes Store".
.My code is as follows:

-(IBAction)sendProductInfoRequest{
NSLog(@"sendProductInfoRequest");
NSSet *identifiersSet=[NSSet setWithObject:[NSString stringWithFormat:@"%@",@"com.hurix.Kitaboo.07APRIL201101"]];
SKProductsRequest *productRequest=[[SKProductsRequest alloc] initWithProductIdentifiers:identifiersSet];
productRequest.delegate=self;
[productRequest start];
NSLog(@"completing sendProductInfoRequest");

}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
NSLog(@"request didFailWithError");
NSLog(@"The product request didFailWithError: %@",[error localizedDescription]);

}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
NSLog(@"yoooo!");
NSLog(@"The product request didReceiveResponse :%@",[response description]);

}


问:
jpa containing query with list
I have a table Called Media that has a column "tagList" of type List. I want to search media based on list of input tag.
I need a method like this.

```<code>List<Media> findByTagListContaining(<List> inputTagList);
</code>```

This gives error but

```<code>    List<Media> findByTagListContaining(String inputTag);
</code>```

works fine. How to make first one works. I need partial matching as well for example if any row has tagList ["mentos","bollywood","comedy"]
and inputTagList is ["men","boll"] that row should come in result.

答:
Hello, You can try this.

```<code>{
 List<String> inputTagList = new ArrayList<String>();
 inputTagList.add("men");
 inputTagList.add("boll");
 findByTagListContaining(inputTagList);
}
</code>```

call your find By Tag List method

```<code>List<Media> findByTagListContaining(List<String> inputTagList){

 String inputTagString = "[";

 for(String strTemp : inputTagList){
  //here create you own pattern matching code. Ex:
  inputTagString+= "'" + strTemp + "%'" + ",";
 }

 inputTagString+="%]";
 //And your inputTagString is ready to match you element ["mentos","bollywood","comedy"]

}
</code>```

Title: jpa containing query with list

Body:
I have a table Called Media that has a column "tagList" of type List. I want to search media based on list of input tag.
I need a method like this.

List<Media> findByTagListContaining(<List> inputTagList);

This gives error but

    List<Media> findByTagListContaining(String inputTag);

works fine. How to make first one works. I need partial matching as well for example if any row has tagList ["mentos","bollywood","comedy"]
and inputTagList is ["men","boll"] that row should come in result.

Body:
Hello, You can try this.

{
 List<String> inputTagList = new ArrayList<String>();
 inputTagList.add("men");
 inputTagList.add("boll");
 findByTagListContaining(inputTagList);
}

call your find By Tag List method

List<Media> findByTagListContaining(List<String> inputTagList){

 String inputTagString = "[";

 for(String strTemp : inputTagList){
  //here create you own pattern matching code. Ex:
  inputTagString+= "'" + strTemp + "%'" + ",";
 }

 inputTagString+="%]";
 //And your inputTagString is ready to match you element ["mentos","bollywood","comedy"]

}


问:
Python Multiprocessing Queue when set to infinite is capped at 32768 (2^15)
I have a list with about 800000 elements (small strings) that are loaded into a Queue which is then consumed by different worker processes from a multiprocessing pool. I've found out that both in PyPy and in Python (2.7 and 3.6 respectively), even though I've set the Queue's maxsize explicitly to 0, the Queue in both cases is capped at 32768 elements at any given time, and therefore blocks on the 32768th element.

Why is this happening? I thought they were supposed to be infinite if maxsize is <= 0? I've gone over this StackOverflow question Python Queue raising Full even when infinite but it's the only one of such nature. Is there something else I may be missing?

I've tried the implementations of a multiprocessing Queue where I load a million integers and the queue.put(val) method always blocks on the 32768th value.

from multiprocessing import Queue
q = Queue(maxsize=0)
for i in range(int(1e7)):
    q.put(i)
    print(i)
```

<p>I was expecting to be able to insert all 1 million integers into the Queue, but as it turns out, it's unable to hold them all as it blocks on the 32768th integer. I'd love to have some light shed on the specifics of why this may be happening, which may already have been answered in the other StackOverflow question linked above, but it seems that the user that made the answer asked whether we were using a 32bit Python distribution, which is not my case, as I am using a 64bit Python distribution in both cases, as can be seen here (for PyPy with 2.7.13, which is what I'm using in my project):</p>

<pre class="lang-py prettyprint-override"><code>Python 2.7.13 (990cef41fe11, Mar 21 2019, 12:15:10)
[PyPy 7.1.0 with GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>> import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)
('7fffffffffffffff', True)
</code>```

UPDATE:

I've noticed something very interesting. This happened while running the Queue on MacOS, but I ran the code in a docker container with Linux and the queue was effectively loaded in full with all 800000 elements at once! It seems that this has something to do with MacOS.

答:
Multiprocessing Queue hanging means you're most likely exceeding the maximum semaphore count; i.e. OSX can't count that high and implicitly restricts you to 2^15 - 1.

I'm not sure how reliable/up-to-date the source is, but this is aligned with seemingly what's the max value for osx (https://github.com/st3fan/osx-10.9/blob/master/xnu-2422.1.72/bsd/sys/semaphore.h)

Edit/proof:

Explicitly trying to use a greater limit than 2^15 - 1 fails:

```<code>>>> Queue(maxsize=2**15)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py", line 102, in Queue
    return Queue(maxsize, ctx=self.get_context())
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/queues.py", line 48, in __init__
    self._sem = ctx.BoundedSemaphore(maxsize)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py", line 87, in BoundedSemaphore
    return BoundedSemaphore(value, ctx=self.get_context())
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/synchronize.py", line 145, in __init__
    SemLock.__init__(self, SEMAPHORE, value, value, ctx=ctx)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/synchronize.py", line 59, in __init__
    unlink_now)
OSError: [Errno 22] Invalid argument
</code>```

In your case, you've tried to implicitly create a queue of infinite size (<=0), however that's not what actually happens and OSX limits are applied: https://github.com/python/cpython/blob/master/Lib/multiprocessing/queues.py#L37

Body:
I have a list with about 800000 elements (small strings) that are loaded into a Queue which is then consumed by different worker processes from a multiprocessing pool. I've found out that both in PyPy and in Python (2.7 and 3.6 respectively), even though I've set the Queue's maxsize explicitly to 0, the Queue in both cases is capped at 32768 elements at any given time, and therefore blocks on the 32768th element.

Why is this happening? I thought they were supposed to be infinite if maxsize is <= 0? I've gone over this StackOverflow question Python Queue raising Full even when infinite but it's the only one of such nature. Is there something else I may be missing?

I've tried the implementations of a multiprocessing Queue where I load a million integers and the queue.put(val) method always blocks on the 32768th value.

from multiprocessing import Queue
q = Queue(maxsize=0)
for i in range(int(1e7)):
    q.put(i)
    print(i)

I was expecting to be able to insert all 1 million integers into the Queue, but as it turns out, it's unable to hold them all as it blocks on the 32768th integer. I'd love to have some light shed on the specifics of why this may be happening, which may already have been answered in the other StackOverflow question linked above, but it seems that the user that made the answer asked whether we were using a 32bit Python distribution, which is not my case, as I am using a 64bit Python distribution in both cases, as can be seen here (for PyPy with 2.7.13, which is what I'm using in my project):

Python 2.7.13 (990cef41fe11, Mar 21 2019, 12:15:10)
[PyPy 7.1.0 with GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>> import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)
('7fffffffffffffff', True)

UPDATE:

I've noticed something very interesting. This happened while running the Queue on MacOS, but I ran the code in a docker container with Linux and the queue was effectively loaded in full with all 800000 elements at once! It seems that this has something to do with MacOS.

Body:
Multiprocessing Queue hanging means you're most likely exceeding the maximum semaphore count; i.e. OSX can't count that high and implicitly restricts you to 2^15 - 1.

I'm not sure how reliable/up-to-date the source is, but this is aligned with seemingly what's the max value for osx (https://github.com/st3fan/osx-10.9/blob/master/xnu-2422.1.72/bsd/sys/semaphore.h)

Edit/proof:

Explicitly trying to use a greater limit than 2^15 - 1 fails:

>>> Queue(maxsize=2**15)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py", line 102, in Queue
    return Queue(maxsize, ctx=self.get_context())
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/queues.py", line 48, in __init__
    self._sem = ctx.BoundedSemaphore(maxsize)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py", line 87, in BoundedSemaphore
    return BoundedSemaphore(value, ctx=self.get_context())
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/synchronize.py", line 145, in __init__
    SemLock.__init__(self, SEMAPHORE, value, value, ctx=ctx)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/synchronize.py", line 59, in __init__
    unlink_now)
OSError: [Errno 22] Invalid argument

In your case, you've tried to implicitly create a queue of infinite size (<=0), however that's not what actually happens and OSX limits are applied: https://github.com/python/cpython/blob/master/Lib/multiprocessing/queues.py#L37


问:
What is the problem in my javascript code - delete an HTML element based on a condition (presence of another element) - beginner
I am trying to delete an element when that element contains another element on https://medium.com/

Sorry, all the pictures are here: https://imgur.com/a/uxG3cPz - did not have the reputation to embed them :)

Medium homepage - without code. Nothing changes when I inject my .js code

If the
 contains this element, then the
 should be deleted

the
 that should be deleted if it contains the  with a star SVG icon

Expected final result (I can't get this to work yet)

Can you please help me?

```<code>function removeElement(id) {
    var elem = document.getElementById(id);
    var dad = elem.parentNode.parentNode.prentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
    dad.removeChild(dad.firstChild);
}

function destroyLoop() {
    var i = O;
    while (i < 100) {
        removeElement("svgIcon svgIcon--star svgIcon--15px");
        i++;
    }
}

destroyLoop();
</code>```

I expect the code to actually delete the element but nothing seems to happen

A million thanks

答:
You are passing class name as id here. Use this piece of code. This will get the first element of the class and delete it.</p>

```<code>function removeElement(id) {
    var elem = document.getElementsByClassName(id)[0].closest("article");
    var dad = elem.parentNode;
    dad.removeChild(elem);
}

function destroyLoop() {
    var i = 0;
    while (i < 100) {
        removeElement("svgIcon svgIcon--star svgIcon--15px");
        i++;
    }
}

destroyLoop();
</code>```

Body:
I am trying to delete an element when that element contains another element on https://medium.com/

Sorry, all the pictures are here: https://imgur.com/a/uxG3cPz - did not have the reputation to embed them :)

Medium homepage - without code. Nothing changes when I inject my .js code

If the
 contains this element, then the
 should be deleted

the
 that should be deleted if it contains the  with a star SVG icon

Expected final result (I can't get this to work yet)

Can you please help me?

function removeElement(id) {
    var elem = document.getElementById(id);
    var dad = elem.parentNode.parentNode.prentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
    dad.removeChild(dad.firstChild);
}

function destroyLoop() {
    var i = O;
    while (i < 100) {
        removeElement("svgIcon svgIcon--star svgIcon--15px");
        i++;
    }
}

destroyLoop();

I expect the code to actually delete the element but nothing seems to happen

A million thanks

Body:
You are passing class name as id here. Use this piece of code. This will get the first element of the class and delete it.

function removeElement(id) {
    var elem = document.getElementsByClassName(id)[0].closest("article");
    var dad = elem.parentNode;
    dad.removeChild(elem);
}

function destroyLoop() {
    var i = 0;
    while (i < 100) {
        removeElement("svgIcon svgIcon--star svgIcon--15px");
        i++;
    }
}

destroyLoop();


问:
Send mass email with Gmail API
I want to send mass email with GMail API.
Currently I add all the addresses at the To section.
But every recipient should receive the mail and see only his address and not the other ones. Is there a method/API that I can use for this?</p>

答:
As far as I know, Gmail was not created for sending bulk emails as it restricts the number of recipients and has tons of other limitations. You should try to use third-party service for this.

Here you can find Gmail API limitation. It says

100 Recipients per message sent via SMTP (by POP or IMAP users) or the Gmail API

Title: Send mass email with Gmail API


问:
Kotlin interface with generics and Dagger
I have an interface defined where I have a generic type with the following

```<code>interface ActivityService<T> {
  fun getActivities(context: Context, listener: GetActivitiesListener<T>)
  fun addActivity(activity: T, context: Context, listener: AddActivityListener)
}
</code>```

And is implemented with

```<code>class AwsActivityService : ActivityService<Activity> {

override fun addActivity(activity: Activity, context: Context, listener: AddActivityListener) {
    AddActivityAsyncTask(activity, context, object : AddActivityAsyncTask.ActivityTaskListener {
        override fun onTaskComplete(result: Boolean) {
            listener.onTaskComplete(result)
        }
    }).execute()
}

override fun getActivities(context: Context, listener: GetActivitiesListener<Activity>) {
    GetActivitiesAsyncTask(context, object : GetActivitiesAsyncTask.ActivityTaskListener {
        override fun onTaskComplete(activityList: List<Activity>) {
            return listener.onTaskComplete(activityList)
        }
    }).execute()
}
</code>```

}

How do you then define the generics for the module within Dagger when instantiating AwsActivityService?

```<code>@Module
class ActivitiesModule() {

    @Provides
    @Inject
    @Singleton
    internal fun provideActivitiesModule(): ActivityService {
        return AwsActivityService()
    }
}
</code>```

答:
You could parhaps use a factory pattern to provide multiple classes based on type.

```<code>@Module
class ActivitiesModuleFactory() {

    @Provides
    @Inject
    @Singleton
    internal fun provideActivitiesModuleFactory(): ActivityServiceFactory {
        return ActivityServiceFactory()
    }
}
</code>```

```<code>
class ActivityServiceFactory {

  inline fun <reified T: Any> getActivities(context: Context, listener: GetActivitiesListener<T>) =
    when(T::class) {
      GoogleActivity::class -> google.getActivities(context, listener as GetActivitiesListener<GoogleActivity>)
      AwsActivity::class -> aws.getActivities(context, listener as GetActivitiesListener<AwsActivity>)
      else -> //throw error or use default listener here
    }

  fun addActivity(activity: any, context: Context, listener: AddActivityListener)=
    when(activity) {
      is GoogleActivity -> google.addActivity(activity, context, listener)
      is AwsActivity -> aws.addActivity(activity, context, listener)
      else -> //throw error or use default listener here
    }

  companion object {
    val aws = AwsActivityService()
    val google = GoogleActivityService()
  }
}
</code>```

```<code>GoogleActivityService : ActivityService<GoogleActivity> {
    override fun addActivity(activity: GoogleActivity, context: Context, listener: AddActivityListener) {
      AddActivityAsyncTask(activity, context, object : AddActivityAsyncTask.ActivityTaskListener {
        override fun onTaskComplete(result: Boolean) {
          listener.onTaskComplete(result)
        }
    }).execute()
    }

    override fun getActivities(context: Context, listener: GetActivitiesListener<GoogleActivity>) {
      GetActivitiesAsyncTask(context, object : GetActivitiesAsyncTask.ActivityTaskListener {
        override fun onTaskComplete(activityList: List<GoogleActivity>) {
          return listener.onTaskComplete(activityList)
        }
    }).execute()
 }
</code>```

The basic idea it to create a factory with a companion object containing instances of each type you need. This factory has an interface that accepts any type and then uses a when statement with type checking to call the correct activity service. Since companion objects are bound to the class there is only one of each ActivityService.

Body:
I have an interface defined where I have a generic type with the following

interface ActivityService<T> {
  fun getActivities(context: Context, listener: GetActivitiesListener<T>)
  fun addActivity(activity: T, context: Context, listener: AddActivityListener)
}

And is implemented with

class AwsActivityService : ActivityService<Activity> {

override fun addActivity(activity: Activity, context: Context, listener: AddActivityListener) {
    AddActivityAsyncTask(activity, context, object : AddActivityAsyncTask.ActivityTaskListener {
        override fun onTaskComplete(result: Boolean) {
            listener.onTaskComplete(result)
        }
    }).execute()
}

override fun getActivities(context: Context, listener: GetActivitiesListener<Activity>) {
    GetActivitiesAsyncTask(context, object : GetActivitiesAsyncTask.ActivityTaskListener {
        override fun onTaskComplete(activityList: List<Activity>) {
            return listener.onTaskComplete(activityList)
        }
    }).execute()
}

}

How do you then define the generics for the module within Dagger when instantiating AwsActivityService?

@Module
class ActivitiesModule() {

    @Provides
    @Inject
    @Singleton
    internal fun provideActivitiesModule(): ActivityService {
        return AwsActivityService()
    }
}

Body:
You could parhaps use a factory pattern to provide multiple classes based on type.

@Module
class ActivitiesModuleFactory() {

    @Provides
    @Inject
    @Singleton
    internal fun provideActivitiesModuleFactory(): ActivityServiceFactory {
        return ActivityServiceFactory()
    }
}

class ActivityServiceFactory {

  inline fun <reified T: Any> getActivities(context: Context, listener: GetActivitiesListener<T>) =
    when(T::class) {
      GoogleActivity::class -> google.getActivities(context, listener as GetActivitiesListener<GoogleActivity>)
      AwsActivity::class -> aws.getActivities(context, listener as GetActivitiesListener<AwsActivity>)
      else -> //throw error or use default listener here
    }

  fun addActivity(activity: any, context: Context, listener: AddActivityListener)=
    when(activity) {
      is GoogleActivity -> google.addActivity(activity, context, listener)
      is AwsActivity -> aws.addActivity(activity, context, listener)
      else -> //throw error or use default listener here
    }

  companion object {
    val aws = AwsActivityService()
    val google = GoogleActivityService()
  }
}

GoogleActivityService : ActivityService<GoogleActivity> {
    override fun addActivity(activity: GoogleActivity, context: Context, listener: AddActivityListener) {
      AddActivityAsyncTask(activity, context, object : AddActivityAsyncTask.ActivityTaskListener {
        override fun onTaskComplete(result: Boolean) {
          listener.onTaskComplete(result)
        }
    }).execute()
    }

    override fun getActivities(context: Context, listener: GetActivitiesListener<GoogleActivity>) {
      GetActivitiesAsyncTask(context, object : GetActivitiesAsyncTask.ActivityTaskListener {
        override fun onTaskComplete(activityList: List<GoogleActivity>) {
          return listener.onTaskComplete(activityList)
        }
    }).execute()
 }

The basic idea it to create a factory with a companion object containing instances of each type you need. This factory has an interface that accepts any type and then uses a when statement with type checking to call the correct activity service. Since companion objects are bound to the class there is only one of each ActivityService.


问:
Why am I getting the count value as zero of the counting class I am expecting it to be 20?
I am expecting the output as 20 since there are two threads and the "counting" class method "counter" is also synchronized.

```<code> class Counting{
     public int count ;
     public synchronized void counter(){
        count = count + 1;
    }
}

class mulA implements Runnable{
    public void run() {
        Counting obj = new Counting();
        for(int i = 0;i<10;i++) {
            obj.counter();
        }
    }
}

class mulB implements Runnable{
    public void run() {
        Counting obj1 = new Counting();
        for(int i = 0;i<10;i++) {
            obj1.counter();
        }
    }
}

public class MulTi {

    public static void main(String[] args) throws Exception {

        mulA obj2 = new mulA();
        mulB obj3 = new mulB();

        Thread t1 = new Thread(obj2);
        Thread t2 = new Thread(obj3);

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        Counting obj4 = new Counting();

        System.out.println(obj4.count);

    }

}
</code>```

How will i get the output as 20.Please tell me about my error.

答: Each instance of class Counting has its own count variable, you could make it static if you want all instances to increment the same value.

Body:
I am expecting the output as 20 since there are two threads and the "counting" class method "counter" is also synchronized.

 class Counting{
     public int count ;
     public synchronized void counter(){
        count = count + 1;
    }
}

class mulA implements Runnable{
    public void run() {
        Counting obj = new Counting();
        for(int i = 0;i<10;i++) {
            obj.counter();
        }
    }
}

class mulB implements Runnable{
    public void run() {
        Counting obj1 = new Counting();
        for(int i = 0;i<10;i++) {
            obj1.counter();
        }
    }
}

public class MulTi {

    public static void main(String[] args) throws Exception {

        mulA obj2 = new mulA();
        mulB obj3 = new mulB();

        Thread t1 = new Thread(obj2);
        Thread t2 = new Thread(obj3);

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        Counting obj4 = new Counting();

        System.out.println(obj4.count);

    }

}

How will i get the output as 20.Please tell me about my error.


问:
Joining tables without relation using JPA criteria
I have two tables with no modeled relation:

Table comm with columns:

```<code>name
date
code
</code>```

Table persondesc with columns:

```<code>code
description
</code>```

Relationship between the two tables is many to one (many comm to one persondesc):

com.code = persondesc.code

These two tables are mapped with annotations but I have no relation declared.

What I'm trying to is to select comm table ordered by persondesc.description.

How can I do this JPA and Hibernate?

答:
In case you need to sort by column which is in another table, you can create "fake" dependency with disabled insertable and updatable attributes. Domain model would looks like this:

Primary entity:

```<code>@Entity
public class Comm {

    @Id
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "date")
    private Date date;

    @Column(name = "code")
    private String code;

    @OneToOne(fetch = FetchType.LAZY) // @ManyToOne is also possible
    @JoinColumn(name = "code", referencedColumnName = "code", insertable = false, updatable = false)
    private PersonDesc personDesc;

}
</code>```

Entity with required data for sorting:

```<code>@Entity
public class PersonDesc {

    @Id
    private String code;

    @Column(name = "description")
    private String description;

}
</code>```

After you define your domain model, it possible to create criteria query:

```<code>CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<Comm> cq = cb.createQuery(Comm.class);
Root<Comm> root = cq.from(Comm.class);
Join<Comm, PersonDesc> leftJoin = root.join("personDesc", JoinType.LEFT);
cq.select(root);
cq.orderBy(cb.asc(root.get("personDesc.description")));
</code>```

Body:
I have two tables with no modeled relation:

Table comm with columns:

name
date
code

Table persondesc with columns:

code
description

Relationship between the two tables is many to one (many comm to one persondesc):

com.code = persondesc.code

These two tables are mapped with annotations but I have no relation declared.

What I'm trying to is to select comm table ordered by persondesc.description.

How can I do this JPA and Hibernate?

Body:
In case you need to sort by column which is in another table, you can create "fake" dependency with disabled insertable and updatable attributes. Domain model would looks like this:

Primary entity:

@Entity
public class Comm {

    @Id
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "date")
    private Date date;

    @Column(name = "code")
    private String code;

    @OneToOne(fetch = FetchType.LAZY) // @ManyToOne is also possible
    @JoinColumn(name = "code", referencedColumnName = "code", insertable = false, updatable = false)
    private PersonDesc personDesc;

}

Entity with required data for sorting:

@Entity
public class PersonDesc {

    @Id
    private String code;

    @Column(name = "description")
    private String description;

}

After you define your domain model, it possible to create criteria query:

CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<Comm> cq = cb.createQuery(Comm.class);
Root<Comm> root = cq.from(Comm.class);
Join<Comm, PersonDesc> leftJoin = root.join("personDesc", JoinType.LEFT);
cq.select(root);
cq.orderBy(cb.asc(root.get("personDesc.description")));


问:
failed to run Angular application getting error : Schema validation failed
I am using Angular 7 for my Application and I am getting error while running it on development server .

I did ng serve

but I got error below

```<code>      D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1>ng lint -fix Your
     global Angular CLI version (7.3.9) is greater than your local version
     (7.1.4). The local Angular CLI version is used.

     To disable this warning use "ng config -g cli.warnings.versionMismatch
     false".

 Schema validation failed with the following errors:
 Data path ".builders['app-shell']" should have required property 'class'.
     Error: Schema validation failed with the following errors:
Data path ".builders['app-shell']" should have required property 'class'.
         at MergeMapSubscriber.project (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\@angular-devkit\core\src\workspace\workspace.js:215:42)
         at MergeMapSubscriber._tryNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:69:27)
        at MergeMapSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:59:18)
         at MergeMapSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
         at MergeMapSubscriber.notifyNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:92:26)
        at InnerSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\InnerSubscriber.js:28:21)
        at InnerSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
         at MapSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\map.js:55:26)
        at MapSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
        at SwitchMapSubscriber.notifyNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\switchMap.js:86:26)
</code>```

Details OF my Angular Application

Angular.json - >

```<code>  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ftoss": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "styleext": "scss"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ftoss",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ],
            "styles": [
              "node_modules/font-awesome/scss/font-awesome.scss",
              "node_modules/angular-bootstrap-md/scss/bootstrap/bootstrap.scss",
              "node_modules/angular-bootstrap-md/scss/mdb-free.scss",
              "src/fonts/styles.css",
              "src/fonts/stylesheet.css",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/chart.js/dist/Chart.js",
              "node_modules/hammerjs/hammer.min.js"

            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "4mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angularev-server",
          "options": {
            "browserTarget": "ftoss:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ftoss:buildroduction"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ftoss:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.scss"
            ],
            "scripts": ["/src/firebase-messaging-sw.js"],
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ftoss-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angularrotractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "ftosserve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ftosserveroduction"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "ftoss"
}
</code>```

What I tried -  >

I uninstalled npm from my project and again installed it , again I got same issue

I did npm  cache clear again I got same issue

List item

答:
OK I did some testing and on my side (check out my comment in the question) it seems that the npm audit fix breaks the dependencies and causes ng serve to yield on that error.
It seems to have to do with a dependency and I hope they'll fix it soon...

Body:
I am using Angular 7 for my Application and I am getting error while running it on development server .

I did ng serve

but I got error below

      D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1>ng lint -fix Your
     global Angular CLI version (7.3.9) is greater than your local version
     (7.1.4). The local Angular CLI version is used.

     To disable this warning use "ng config -g cli.warnings.versionMismatch
     false".

 Schema validation failed with the following errors:
 Data path ".builders['app-shell']" should have required property 'class'.
     Error: Schema validation failed with the following errors:
Data path ".builders['app-shell']" should have required property 'class'.
         at MergeMapSubscriber.project (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\@angular-devkit\core\src\workspace\workspace.js:215:42)
         at MergeMapSubscriber._tryNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:69:27)
        at MergeMapSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:59:18)
         at MergeMapSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
         at MergeMapSubscriber.notifyNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:92:26)
        at InnerSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\InnerSubscriber.js:28:21)
        at InnerSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
         at MapSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\map.js:55:26)
        at MapSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
        at SwitchMapSubscriber.notifyNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\switchMap.js:86:26)

Details OF my Angular Application

Angular.json - >

  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ftoss": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "styleext": "scss"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ftoss",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ],
            "styles": [
              "node_modules/font-awesome/scss/font-awesome.scss",
              "node_modules/angular-bootstrap-md/scss/bootstrap/bootstrap.scss",
              "node_modules/angular-bootstrap-md/scss/mdb-free.scss",
              "src/fonts/styles.css",
              "src/fonts/stylesheet.css",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/chart.js/dist/Chart.js",
              "node_modules/hammerjs/hammer.min.js"

            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "4mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angularev-server",
          "options": {
            "browserTarget": "ftoss:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ftoss:buildroduction"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ftoss:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.scss"
            ],
            "scripts": ["/src/firebase-messaging-sw.js"],
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ftoss-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angularrotractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "ftosserve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ftosserveroduction"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "ftoss"
}

What I tried -  >

I uninstalled npm from my project and again installed it , again I got same issue

I did npm  cache clear again I got same issue

List item


问:
UICollectionViewController with dynamic header (like Reddit App)
I am looking for a way to implement a header view that automatically hides once you start scrolling down and immediately shows itself once the user starts scrolling up.
Usually, I always post some code, but now I am a little bit lost on how to implement such behaviour.

My view layout:

UICollectionViewController with paging enabled for horizontal
scrolling (has two items)

The UICollectionViewCell fills the entire vertical space. Each UICollectionViewCell hosts a UITableView for vertical scrolling. I assume that I have to use the UITableView vertical scrolling position to adjust the frame of the menu bar.

Video: https://imgur.com/a/Rdu3wko

What would be the best way to implement such a behaviour?

答: This functionality is possible in UITableView  set parallax header otherwise UIScrollView parallax animation.


问:
Angular Multiple subscriptions then perform action
I have a function that request data from an API using subscriptions. I am trying to re-write it so that it returns a boolean when all API calls have finished. Is there a better way to write this?

My current code:

```<code>public res1=null;
public res2=null;

getData(){
 this.svc.getData1().subscribe(x={this.res1=x;})
 this.svc.getData2().subscribe(x={this.res2=x;})
}
</code>```

I was thinking of trying to create an Observable that listens for changes to the nested subscriptions: (not tested code!)

```<code>getData(): Observable<boolean>{
 this.svc.getData1().subscribe(x=>{
   this.res1=x;
   this.svc.getData2().subscribe(x=>{this.res2=x;
     return true;
   })
 })
)
</code>```

}

答:
One way of doing it would be to use combineLatest. Combine latest emits a value when all the observables have emitted one value.

```<code>combineLatest(observeable1$, observable2$).subscribe(
  // when both have submitted a value. return what you like.
);
</code>```

If your observable are only going to resolve once. You can use forkJoin as well. Which is similar to promise.All

Body:
I have a function that request data from an API using subscriptions. I am trying to re-write it so that it returns a boolean when all API calls have finished. Is there a better way to write this?

My current code:

public res1=null;
public res2=null;

getData(){
 this.svc.getData1().subscribe(x={this.res1=x;})
 this.svc.getData2().subscribe(x={this.res2=x;})
}

I was thinking of trying to create an Observable that listens for changes to the nested subscriptions: (not tested code!)

getData(): Observable<boolean>{
 this.svc.getData1().subscribe(x=>{
   this.res1=x;
   this.svc.getData2().subscribe(x=>{this.res2=x;
     return true;
   })
 })
)

}

Body:
One way of doing it would be to use combineLatest. Combine latest emits a value when all the observables have emitted one value.

combineLatest(observeable1$, observable2$).subscribe(
  // when both have submitted a value. return what you like.
);

If your observable are only going to resolve once. You can use forkJoin as well. Which is similar to promise.All


问:
Why is wire variable causing illegal left-hand side in continuous assignment?
I have read through all similar posts, but none address the issue I'm having, namely that line 41 assign Y[b]=~Y[b]; causes error "Illegal left-hand side in continuous assignment."

I haven't assigned any regs so I don't see what the issue is. If I replace b with an actual number (say, 3) it works fine. But I need b as a variable here.

```<code>// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  wire b;        // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  assign b=(S[1]!=P[1])? b:b+1; // if parity of 2^0 not the same, add 1 to b
  assign b=(S[2]!=P[2])? b:b+2; // if parity of 2^1 not the same, add 2 to b
  assign b=(S[3]!=P[3])? b:b+4; // if parity of 2^2 not the same, add 4 to b

  assign Y[b]=~Y[b]; // correct the incorrect bit
  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule
</code>```

答:
The lines between module and endmodule are executed concurently. (It seems like you think they are executed sequentially.) Therefore, you are driving all the bits of Y in these lines

```<code>  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];
</code>```

and then are driving one of the bits of Y again in this line:

```<code>  assign Y[b]=~Y[b]; // correct the incorrect bit
</code>```

So (a) you have a short circuit and (b) which bit has the short circuit? That depends on b. So, the position of the short circuit depends on the state of one of the internal wires. You have described a circuit that can reconfigure itself depending on its inputs. Verilog won't let you do that. Verilog is a hardware description language. Conventional digital hardware can't reconfigure itself depending on the state of its inputs.

Body:
I have read through all similar posts, but none address the issue I'm having, namely that line 41 assign Y[b]=~Y[b]; causes error "Illegal left-hand side in continuous assignment."

I haven't assigned any regs so I don't see what the issue is. If I replace b with an actual number (say, 3) it works fine. But I need b as a variable here.

// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  wire b;        // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  assign b=(S[1]!=P[1])? b:b+1; // if parity of 2^0 not the same, add 1 to b
  assign b=(S[2]!=P[2])? b:b+2; // if parity of 2^1 not the same, add 2 to b
  assign b=(S[3]!=P[3])? b:b+4; // if parity of 2^2 not the same, add 4 to b

  assign Y[b]=~Y[b]; // correct the incorrect bit
  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule

Body:
The lines between module and endmodule are executed concurently. (It seems like you think they are executed sequentially.) Therefore, you are driving all the bits of Y in these lines

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

and then are driving one of the bits of Y again in this line:

  assign Y[b]=~Y[b]; // correct the incorrect bit

So (a) you have a short circuit and (b) which bit has the short circuit? That depends on b. So, the position of the short circuit depends on the state of one of the internal wires. You have described a circuit that can reconfigure itself depending on its inputs. Verilog won't let you do that. Verilog is a hardware description language. Conventional digital hardware can't reconfigure itself depending on the state of its inputs.