问:
Start video call in Hangouts or Duo using intent?
I am looking for a way to start a video call in either Hangouts or Duo.
There seems to be 0 documentation regarding what intents should be used.
Does anyone have an idea?</p>

答:
A) HangoutUrlHandlerActivity, ShortlinkUrlHandlerActivity and ConversationUrlHandlerActivity are available for receiving Intent with an Uri.

What I have so far, which is actually working, but only for ongoing conversations & video calls:

a) opening an ongoing conversation:

```<code>void joinConversation(@NonNull String conversationId) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = new Uri.Builder().scheme("content").authority("hangouts.google.com").appendPath("chat").appendPath(conversationId).build();
    intent.setClassName("com.google.android.talk", "com.google.android.apps.hangouts.phone.ConversationUrlHandlerActivity");
    intent.setDataAndType(uri, "vnd.google.android.hangouts/vnd.google.android.hangout_whitelist");
    startActivity(intent);
}
</code>```

b) joining an ongoing video call (the ID comes from hangouts.google.com/hangouts/_/meet):

```<code>void joinHangout(@NonNull String callId) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = new Uri.Builder().scheme("content").authority("g.co").appendPath("hangout").appendPath(Uri.encode(callId)).build();
    intent.setClassName("com.google.android.talk", "com.google.android.apps.hangouts.phone.ShortlinkUrlHandlerActivity");
    intent.setDataAndType(uri, "vnd.google.android.hangouts/vnd.google.android.hangout_whitelist");
    startActivity(intent);
}
</code>```

If direct invites should not be possible - one could still schedule calls through the Calendar API, where one gets the callId from, so that one can join the Hangout once it is scheduled. Google Meet does not even support direct invites, but only through Google Calendar appointments.

Based upon the comment from @Mir Milad, I've managed to at least create a new text conversation; but still nothing that would ring someone up (it notifies as soon as the first message had been sent):

```<code>/** @param googleUserId that 21 digit Google user ID, aka Gaia ID  */
void createConversation(@NonNull String googleUserId) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = new Uri.Builder().scheme("content").authority("hangouts.google.com").appendPath("chat").appendPath("person").appendPath(googleUserId).build();
    intent.setClassName("com.google.android.talk", "com.google.android.apps.hangouts.phone.ConversationUrlHandlerActivity");
    intent.setDataAndType(uri, "vnd.google.android.hangouts/vnd.google.android.hangout_whitelist");
    startActivity(intent);
}
</code>```

As far as I can tell, there is no such thing as an explicit "call me" URL for Hangouts. And even web-based, the Hangout is being initiated with two Gaia ID, which then result in a room name to join. Even Google's own Hangouts Dialer seems to be broken, when looking at the recent comments.

B) For Google Duo, this was already answered here.

Body:
A) HangoutUrlHandlerActivity, ShortlinkUrlHandlerActivity and ConversationUrlHandlerActivity are available for receiving Intent with an Uri.

What I have so far, which is actually working, but only for ongoing conversations & video calls:

a) opening an ongoing conversation:

void joinConversation(@NonNull String conversationId) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = new Uri.Builder().scheme("content").authority("hangouts.google.com").appendPath("chat").appendPath(conversationId).build();
    intent.setClassName("com.google.android.talk", "com.google.android.apps.hangouts.phone.ConversationUrlHandlerActivity");
    intent.setDataAndType(uri, "vnd.google.android.hangouts/vnd.google.android.hangout_whitelist");
    startActivity(intent);
}

b) joining an ongoing video call (the ID comes from hangouts.google.com/hangouts/_/meet):

void joinHangout(@NonNull String callId) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = new Uri.Builder().scheme("content").authority("g.co").appendPath("hangout").appendPath(Uri.encode(callId)).build();
    intent.setClassName("com.google.android.talk", "com.google.android.apps.hangouts.phone.ShortlinkUrlHandlerActivity");
    intent.setDataAndType(uri, "vnd.google.android.hangouts/vnd.google.android.hangout_whitelist");
    startActivity(intent);
}

If direct invites should not be possible - one could still schedule calls through the Calendar API, where one gets the callId from, so that one can join the Hangout once it is scheduled. Google Meet does not even support direct invites, but only through Google Calendar appointments.

Based upon the comment from @Mir Milad, I've managed to at least create a new text conversation; but still nothing that would ring someone up (it notifies as soon as the first message had been sent):

/** @param googleUserId that 21 digit Google user ID, aka Gaia ID  */
void createConversation(@NonNull String googleUserId) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = new Uri.Builder().scheme("content").authority("hangouts.google.com").appendPath("chat").appendPath("person").appendPath(googleUserId).build();
    intent.setClassName("com.google.android.talk", "com.google.android.apps.hangouts.phone.ConversationUrlHandlerActivity");
    intent.setDataAndType(uri, "vnd.google.android.hangouts/vnd.google.android.hangout_whitelist");
    startActivity(intent);
}

As far as I can tell, there is no such thing as an explicit "call me" URL for Hangouts. And even web-based, the Hangout is being initiated with two Gaia ID, which then result in a room name to join. Even Google's own Hangouts Dialer seems to be broken, when looking at the recent comments.

B) For Google Duo, this was already answered here.


来源: stackexchange

问:
Best practice to record large amount of hits into MySQL database
Well, this is the thing. Let's say that my future PHP CMS need to drive 500k visitors daily and I need to record them all in MySQL database (referrer, ip address, time etc.). This way I need to insert 300-500 rows per minute and update 50 more. The main problem is that script would call database every time I want to insert new row, which is every time someone hits a page.

My question, is there any way to locally cache incoming hits first (and what is the best solution for that apc, csv...?) and periodically send them to database every 10 minutes for example? Is this good solution and what is the best practice for this situation?

答:
One way would be to use Apache access.log. You can get a quite fine logging by using cronolog utility with apache . Cronolog will handle the storage of a very big number of rows in files, and can rotate it based on volume day, year, etc. Using this utility will prevent your Apache from suffering of log writes.

Then as said by others, use a cron-based job to analyse these log and push whatever summarized or raw data you want in MySQL.

You may think of using a dedicated database (or even database server) for write-intensive jobs, with specific settings. For example you may not need InnoDB storage and keep a simple MyIsam. And you could even think of another database storage (as said by @Riccardo Galli)

ContentLicense: CC BY-SA 3.0


问:
PowerShell with a configuration script
Needs some help. We run PowerShell scripts using a configuration script.

e.g. .\folderA\TheConfigurationScript .\scriptThatDoesAllTheWork.ps1

The issue is that in the directory where scriptThatDoesAllTheWork.ps1 is located there are number of other scripts.

If I accidentally add a space before scriptThatDoesAllTheWork.ps1 all scripts located in that folder are executed

e.g. .\folderA\TheConfigurationScript
.\ scriptThatDoesAllTheWork.ps1

All variables therefore defined in folderA\TheConfigurationScript are available to scriptThatDoesAllTheWork.ps1 that does all the work

Is there any way to avoid this behaviour

Thanks in advance

答: Thanks to mclayton. I had a get-childitem that would return all the files in case of space. In case this helps anyone</p>

ContentLicense: CC BY-SA 4.0

Title: PowerShell with a configuration script


问:
Left alignment of last line of flex cells
I've made a table-like flex structure, that looks pretty nice and has adaptive number of cells, but when last row isn't full - it stretches remaining cells to full size, which looks unshapely.

https://jsfiddle.net/zzmaster/6uw4gm3t/3/
(you need to enlarge results area to maximum in order to see this)

Logically, justify-content: flex-start; should fix this, but it doesn't.

Is there any way to turn remained cells back to their's place?

答:
change your css like below!

ul.text {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
ul.text li {
  min-width: 300px;
  display: inline-flex;
  flex: 1 1 0px;
  justify-content: center;
  align-items: center;
  resize: both;
}```


问:
Could not drop database `symfony-project` for connection named default An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused
I accidentally created a database symfony-project successfully, but it's not appearing on my phpmyadmin page. I want to drop the database with

```<code>php bin/console doctrine:database:drop --force
</code>```

then this message comes out

Could not drop database symfony-project for connection named default
  An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused

When I try to create a new database, with php bin/console doctrine:database:create, an error message comes out:

In AbstractMySQLDriver.php line 93:

   An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused

In PDOConnection.php line 31:

   SQLSTATE[HY000] [2002] Connection refused

In PDOConnection.php line 27:

   SQLSTATE[HY000] [2002] Connection refused

Because the connection is refused, I can't create and drop any databases right now.

My database url on the .env file is

```<code>DATABASE_URL=mysql://root:@127.0.0.1:3306/symfony-project?serverVersion=5.7
</code>```

My password is empty.

I've tried to change the 127.0.0.1 to localhost and the error message is telling me that

there is no such file or directory.

I'm using symfony 4 and xampp on macOS

UPDATE

I've edited my config/packages/doctrine.yaml file. I commented the url: '%env(resolve:DATABASE_URL)%' and added this:

```<code>doctrine:
dbal:
    dbname: symfony-project
    charset: utf8
    host: 127.0.0.1
    port: 8080
    user: root
    password:
    driver: pdo_mysql
</code>```

and now this message comes out

In AbstractMySQLDriver.php line 106:

   An exception occurred in driver: SQLSTATE[HY000] [2006] MySQL server has gone away

In PDOConnection.php line 31:

   SQLSTATE[HY000] [2006] MySQL server has gone away

In PDOConnection.php line 27:

   SQLSTATE[HY000] [2006] MySQL server has gone away

In PDOConnection.php line 27:

   PDO::__construct(): MySQL server has gone away

答:
I think you can also try the connection by attempt to create a database:

```<code>php bin/console doctrine:database:create
</code>```

If you're using Symfony 2, you need to use:

```<code>php app/console doctrine:database:create
</code>```

I also see that in the string:

```<code>DATABASE_URL=mysql://root:@127.0.0.1:3306/symfony-project?serverVersion=5.7
</code>```

You didn't specify the password for root user. Although that might be not an issue if the password is unspecified at the beginning, it's better to re-check these credentials.

Body:
I accidentally created a database symfony-project successfully, but it's not appearing on my phpmyadmin page. I want to drop the database with

php bin/console doctrine:database:drop --force

then this message comes out

Could not drop database symfony-project for connection named default
  An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused

When I try to create a new database, with php bin/console doctrine:database:create, an error message comes out:

In AbstractMySQLDriver.php line 93:

   An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused

In PDOConnection.php line 31:

   SQLSTATE[HY000] [2002] Connection refused

In PDOConnection.php line 27:

   SQLSTATE[HY000] [2002] Connection refused

Because the connection is refused, I can't create and drop any databases right now.

My database url on the .env file is

DATABASE_URL=mysql://root:@127.0.0.1:3306/symfony-project?serverVersion=5.7

My password is empty.

I've tried to change the 127.0.0.1 to localhost and the error message is telling me that

there is no such file or directory.

I'm using symfony 4 and xampp on macOS

UPDATE

I've edited my config/packages/doctrine.yaml file. I commented the url: '%env(resolve:DATABASE_URL)%' and added this:

doctrine:
dbal:
    dbname: symfony-project
    charset: utf8
    host: 127.0.0.1
    port: 8080
    user: root
    password:
    driver: pdo_mysql

and now this message comes out

In AbstractMySQLDriver.php line 106:

   An exception occurred in driver: SQLSTATE[HY000] [2006] MySQL server has gone away

In PDOConnection.php line 31:

   SQLSTATE[HY000] [2006] MySQL server has gone away

In PDOConnection.php line 27:

   SQLSTATE[HY000] [2006] MySQL server has gone away

In PDOConnection.php line 27:

   PDO::__construct(): MySQL server has gone away

Body:
I think you can also try the connection by attempt to create a database:

php bin/console doctrine:database:create

If you're using Symfony 2, you need to use:

php app/console doctrine:database:create

I also see that in the string:

DATABASE_URL=mysql://root:@127.0.0.1:3306/symfony-project?serverVersion=5.7

You didn't specify the password for root user. Although that might be not an issue if the password is unspecified at the beginning, it's better to re-check these credentials.


问:
How to pass default value loaded into form input to the payload
I'm making an edit form which inside Modal. Form inputs has defaultValue that comes from props with an name, age and strength as default value. If I change all inputs value, everything works fine, but if I change only one input value when I console.log payload I got and empty strings, but only value that I changed goes to the payload.  How can I make that even I change only one input payload gets inputs default value from props?

My code is here:

```<code>import React, { Component } from 'react';
import './Form.scss';
import axios from 'axios';

class Form extends Component {
    constructor(props){
        super(props);
        this.state = {
            id: this.props.gnomeId,
            submitedName: '',
            submitedAge: '',
            submitedStrength: ''
        }
        this.onSubmit = this.onSubmit.bind(this);
    }

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value,
        });
    }

    onSubmit(event) {
        event.preventDefault();

        const gnome = {
                name: this.state.submitedName,
                age: this.state.submitedAge,
                strenght: this.state.submitedStrength,
              }
        console.log(gnome);

        axios.post(`${API}/${this.state.id}`, {gnome})
        .then( res => {
            console.log(res);
            console.log(res.data);
        });
    }

    render() {
        return(
            <form onSubmit={this.onSubmit}>
                <div>
                    <label htmlFor="name">Name</label>
                    <input type="text" name="submitedName" id="name" defaultValue={this.props.gnomeName} onChange={this.handleChange}/>
                </div>
                <div>
                    <label htmlFor="age">Age</label>
                    <input type="text" name="submitedAge" id="age" defaultValue={this.props.gnomeAge} onChange={this.handleChange}/>
                </div>
                <div>
                    <label htmlFor="strength">Strength</label>
                    <input type="text" name="submitedStrength" id="strength" defaultValue={this.props.gnomeStrength} onChange={this.handleChange}/>
                </div>
                <button type="submit" className="submit-btn">Submit</button>
            </form>
        )
    }
}

export default Form;
</code>```

答:
First remove the defaultProps.
add componentDidUpdate in class based component and useEffect in function based component

```<code>componentDidUpdate(props) {
  if(props){
    this.state = {
      id: this.props.gnomeId,
      submitedName: props.gnomeName,
      submitedAge: props.gnomeAge,
      submitedStrength: props.gnomeStrength
    }
  }
}
</code>```

it is necessary to put props in if because it has undefined initial so not to get error

Body:
I'm making an edit form which inside Modal. Form inputs has defaultValue that comes from props with an name, age and strength as default value. If I change all inputs value, everything works fine, but if I change only one input value when I console.log payload I got and empty strings, but only value that I changed goes to the payload.  How can I make that even I change only one input payload gets inputs default value from props?

My code is here:

import React, { Component } from 'react';
import './Form.scss';
import axios from 'axios';

class Form extends Component {
    constructor(props){
        super(props);
        this.state = {
            id: this.props.gnomeId,
            submitedName: '',
            submitedAge: '',
            submitedStrength: ''
        }
        this.onSubmit = this.onSubmit.bind(this);
    }

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value,
        });
    }

    onSubmit(event) {
        event.preventDefault();

        const gnome = {
                name: this.state.submitedName,
                age: this.state.submitedAge,
                strenght: this.state.submitedStrength,
              }
        console.log(gnome);

        axios.post(`${API}/${this.state.id}`, {gnome})
        .then( res => {
            console.log(res);
            console.log(res.data);
        });
    }

    render() {
        return(
            <form onSubmit={this.onSubmit}>

                    Name
                    <input type="text" name="submitedName" id="name" defaultValue={this.props.gnomeName} onChange={this.handleChange}/>

                    Age
                    <input type="text" name="submitedAge" id="age" defaultValue={this.props.gnomeAge} onChange={this.handleChange}/>

                    Strength
                    <input type="text" name="submitedStrength" id="strength" defaultValue={this.props.gnomeStrength} onChange={this.handleChange}/>

                <button type="submit" className="submit-btn">Submit</button>
            </form>
        )
    }
}

export default Form;

Body:
First remove the defaultProps.
add componentDidUpdate in class based component and useEffect in function based component

componentDidUpdate(props) {
  if(props){
    this.state = {
      id: this.props.gnomeId,
      submitedName: props.gnomeName,
      submitedAge: props.gnomeAge,
      submitedStrength: props.gnomeStrength
    }
  }
}

it is necessary to put props in if because it has undefined initial so not to get error


问:
Can we register PSSessionConfiguration on remote machine?
Is it possible to register a PS session configuration for machine A from machine B.
Cmdlet "Register-PSSessionConfiguration" works locally only??</p>

答:
First you need to enable PowerShell Remoting on the PC You Want to Access Remotely

In the PowerShell window, type the following command, and then hit Enter:

```<code>Enable-PSRemoting -SkipNetworkProfileCheck -Force
Set-Item WSMan:\localhost\Client\TrustedHosts  *
Restart-Service WinRM
Test-WsMan $env:computername
</code>```

If you’re on a home network where you want to go ahead and trust any PC to connect remotely, you can type the following cmdlet in PowerShell (again, you’ll need to run it as Administrator).

```<code>Set-Item wsman:\localhost\client\trustedhosts *
</code>```

Or

```<code>Set-Item wsman:\localhost\client\trustedhosts 10.0.0.22
</code>```

Or

```<code>Set-Item wsman:\localhost\client\trustedhosts '10.0.0.22,10.0.0.23'
</code>```

Register a PSSessionConfiguration

To connect 'Computer1' let us register a session configuration on the server using a domain account.
Just type the following cmdlet and then hit Enter:

```<code>Invoke-Command -ComputerName Computer1 -ScriptBlock {Register-PSSessionConfiguration -Name SessionName -RunAsCredential 'domain\mydomainaccount' -Force }
</code>```

Now I'll use this session configuration the next time I want to run a command on the remote computer.

```<code>Invoke-Command -ComputerName 'Computer1' -ScriptBlock { Get-ChildItem-Path \\Computer1\c$ } -ConfigurationName SessionName
</code>```

Body:
First you need to enable PowerShell Remoting on the PC You Want to Access Remotely

In the PowerShell window, type the following command, and then hit Enter:

Enable-PSRemoting -SkipNetworkProfileCheck -Force
Set-Item WSMan:\localhost\Client\TrustedHosts  *
Restart-Service WinRM
Test-WsMan $env:computername

If you’re on a home network where you want to go ahead and trust any PC to connect remotely, you can type the following cmdlet in PowerShell (again, you’ll need to run it as Administrator).

Set-Item wsman:\localhost\client\trustedhosts *

Or

Set-Item wsman:\localhost\client\trustedhosts 10.0.0.22

Or

Set-Item wsman:\localhost\client\trustedhosts '10.0.0.22,10.0.0.23'

Register a PSSessionConfiguration

To connect 'Computer1' let us register a session configuration on the server using a domain account.
Just type the following cmdlet and then hit Enter:

Invoke-Command -ComputerName Computer1 -ScriptBlock {Register-PSSessionConfiguration -Name SessionName -RunAsCredential 'domain\mydomainaccount' -Force }

Now I'll use this session configuration the next time I want to run a command on the remote computer.

Invoke-Command -ComputerName 'Computer1' -ScriptBlock { Get-ChildItem-Path \\Computer1\c$ } -ConfigurationName SessionName


问:
Is there a possibility to get a notification when a file on FTP server has been modified?
I'd like to build a service where a file from a FTP Server is downloaded as soon as it has been modified. It's always the same file name. I think of checking for the timestamp every few minutes but maybe there is a more elegant way to solve that?</p>

答:
Checking timestamp (or something very similar) is the only way you can do it with a generic the FTP protocol API.

Your particular FTP server may have better API for that, but we do not know anything about your FTP server.


问:
Find conflicted date intervals using SQL
Suppose I have following table in Sql Server 2008:

```<code>ItemId StartDate   EndDate
1      NULL        2011-01-15
2      2011-01-16  2011-01-25
3      2011-01-26  NULL
</code>```

As you can see, this table has StartDate and EndDate columns. I want to validate data in these columns. Intervals cannot conflict with each other. So, the table above is valid, but the next table is invalid, becase first row has End Date greater than StartDate in the second row.

```<code>ItemId StartDate   EndDate
1      NULL        2011-01-17
2      2011-01-16  2011-01-25
3      2011-01-26  NULL
</code>```

NULL means infinity here.

Could you help me to write a script for data validation?

[The second task]

Thanks for the answers.
I have a complication. Let's assume, I have such table:

```<code>ItemId  IntervalId StartDate   EndDate
1       1          NULL        2011-01-15
2       1          2011-01-16  2011-01-25
3       1          2011-01-26  NULL
4       2          NULL        2011-01-17
5       2          2011-01-16  2011-01-25
6       2          2011-01-26  NULL
</code>```

Here I want to validate intervals within a groups of IntervalId, but not within the whole table. So, Interval 1 will be valid, but Interval 2 will be invalid.

And also. Is it possible to add a constraint to the table in order to avoid such invalid records?

[Final Solution]

I created function to check if interval is conflicted:

```<code>CREATE FUNCTION [dbo].[fnIntervalConflict]
(
    @intervalId INT,
    @originalItemId INT,
    @startDate DATETIME,
    @endDate DATETIME
)
RETURNS BIT
AS
BEGIN

    SET @startDate = ISNULL(@startDate,'1/1/1753 12:00:00 AM')
    SET @endDate = ISNULL(@endDate,'12/31/9999 11:59:59 PM')

    DECLARE @conflict BIT = 0

    SELECT TOP 1 @conflict = 1
    FROM Items
    WHERE IntervalId = @intervalId
    AND ItemId <> @originalItemId
    AND (
    (ISNULL(StartDate,'1/1/1753 12:00:00 AM') >= @startDate
     AND ISNULL(StartDate,'1/1/1753 12:00:00 AM') <= @endDate)
     OR (ISNULL(EndDate,'12/31/9999 11:59:59 PM') >= @startDate
     AND ISNULL(EndDate,'12/31/9999 11:59:59 PM') <= @endDate)
    )

    RETURN @conflict
END
</code>```

And then I added 2 constraints to my table:

```<code>ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_Dates CHECK (StartDate IS NULL OR EndDate IS NULL OR StartDate <= EndDate)

GO
</code>```

and

```<code>ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_ValidInterval CHECK (([dbo].[fnIntervalConflict]([IntervalId], ItemId,[StartDate],[EndDate])=(0)))

GO
</code>```

I know, the second constraint slows insert and update operations, but it is not very important for my application.
And also, now I can call function fnIntervalConflict from my application code before inserts and updates of data in the table.

答:
Something like this should give you all overlaping periods

```<code>SELECT
*
FROM
mytable t1
JOIN mytable t2 ON t1.EndDate>t2.StartDate AND t1.StartDate < t2.StartDate
</code>```

Edited for Adrians comment bellow

Body:
Suppose I have following table in Sql Server 2008:

ItemId StartDate   EndDate
1      NULL        2011-01-15
2      2011-01-16  2011-01-25
3      2011-01-26  NULL

As you can see, this table has StartDate and EndDate columns. I want to validate data in these columns. Intervals cannot conflict with each other. So, the table above is valid, but the next table is invalid, becase first row has End Date greater than StartDate in the second row.

ItemId StartDate   EndDate
1      NULL        2011-01-17
2      2011-01-16  2011-01-25
3      2011-01-26  NULL

NULL means infinity here.

Could you help me to write a script for data validation?

[The second task]

Thanks for the answers.
I have a complication. Let's assume, I have such table:

ItemId  IntervalId StartDate   EndDate
1       1          NULL        2011-01-15
2       1          2011-01-16  2011-01-25
3       1          2011-01-26  NULL
4       2          NULL        2011-01-17
5       2          2011-01-16  2011-01-25
6       2          2011-01-26  NULL

Here I want to validate intervals within a groups of IntervalId, but not within the whole table. So, Interval 1 will be valid, but Interval 2 will be invalid.

And also. Is it possible to add a constraint to the table in order to avoid such invalid records?

[Final Solution]

I created function to check if interval is conflicted:

CREATE FUNCTION [dbo].[fnIntervalConflict]
(
    @intervalId INT,
    @originalItemId INT,
    @startDate DATETIME,
    @endDate DATETIME
)
RETURNS BIT
AS
BEGIN

    SET @startDate = ISNULL(@startDate,'1/1/1753 12:00:00 AM')
    SET @endDate = ISNULL(@endDate,'12/31/9999 11:59:59 PM')

    DECLARE @conflict BIT = 0

    SELECT TOP 1 @conflict = 1
    FROM Items
    WHERE IntervalId = @intervalId
    AND ItemId <> @originalItemId
    AND (
    (ISNULL(StartDate,'1/1/1753 12:00:00 AM') >= @startDate
     AND ISNULL(StartDate,'1/1/1753 12:00:00 AM') <= @endDate)
     OR (ISNULL(EndDate,'12/31/9999 11:59:59 PM') >= @startDate
     AND ISNULL(EndDate,'12/31/9999 11:59:59 PM') <= @endDate)
    )

    RETURN @conflict
END

And then I added 2 constraints to my table:

ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_Dates CHECK (StartDate IS NULL OR EndDate IS NULL OR StartDate <= EndDate)

GO

and

ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_ValidInterval CHECK (([dbo].[fnIntervalConflict]([IntervalId], ItemId,[StartDate],[EndDate])=(0)))

GO

I know, the second constraint slows insert and update operations, but it is not very important for my application.
And also, now I can call function fnIntervalConflict from my application code before inserts and updates of data in the table.

Body:
Something like this should give you all overlaping periods

SELECT
*
FROM
mytable t1
JOIN mytable t2 ON t1.EndDate>t2.StartDate AND t1.StartDate < t2.StartDate

Edited for Adrians comment bellow


问:
How to access input value in multiple component?
I have 2 components :  headerComponent and searchPageComponent.

    Whatever the value we enter on header component search bar, the search page component should get the value.

header.component.html

```<code><form class="form-inline md-form form-sm">
          <input class="form-control form-control-sm mr-3 w-75" id="searchString" type="text"
             placeholder="Search" [(ngModel)]="searchValue" name="searchString" (ngModelChange)="onChange($event)">
          <button class="headerSearchbarBtn" id="btnSearch" routerLink="/searchResult">
              <span class="headerSearchbarIcon"></span>
           </button>
       </form>
</code>```

header.component.ts

```<code>export class HeaderComponent implements OnInit {
        searchValue: string;
        constructor(private router: Router) { }
        ngOnInit() {
         }
         onChange($event) {
          this.searchValue = $event;
         }
       }
</code>```

Search.component.ts

```<code>export class SearchComponent implements  OnInit {
        ngOnInit() {
          console.log(this.searchValue); // 'this.searchValue' => value should come from header.compomnent.ts
        }
      }
</code>```

There is no parent child relation here, I want to know how the data is passed from one component to other,
    and Why cant we directly access the input field box value in different components in Angular?

答:
Service in add this code

```<code> setSearchValue = new Subject<any>();
  getSearchValue = this.setSearchValue.asObservable();
</code>```

First import your Service in Header component

```<code>constructor(private service: HeaderService)
</code>```

```<code>header.component.ts
</code>```

```<code>export class HeaderComponent implements OnInit {
        searchValue: string;
        constructor(private router: Router) { }
        ngOnInit() {
         }
         onChange($event) {
           this.service.setSearchValue.next(event);
           });
         }
       }
</code>```

```<code>Search.component.ts
</code>```

```<code>export class SearchComponent implements  OnInit {
        ngOnInit() {
         this.getSearchValue();
        }
      }

   getSearchValue(){
      this.service.getSearchValue.subscribe((value) => {
       this.searchValue = value;
      });
    }
</code>```

Body:
I have 2 components :  headerComponent and searchPageComponent.

    Whatever the value we enter on header component search bar, the search page component should get the value.

header.component.html

<form class="form-inline md-form form-sm">
          <input class="form-control form-control-sm mr-3 w-75" id="searchString" type="text"
             placeholder="Search" [(ngModel)]="searchValue" name="searchString" (ngModelChange)="onChange($event)">
          <button class="headerSearchbarBtn" id="btnSearch" routerLink="/searchResult">

           </button>
       </form>

header.component.ts

export class HeaderComponent implements OnInit {
        searchValue: string;
        constructor(private router: Router) { }
        ngOnInit() {
         }
         onChange($event) {
          this.searchValue = $event;
         }
       }

Search.component.ts

export class SearchComponent implements  OnInit {
        ngOnInit() {
          console.log(this.searchValue); // 'this.searchValue' => value should come from header.compomnent.ts
        }
      }

There is no parent child relation here, I want to know how the data is passed from one component to other,
    and Why cant we directly access the input field box value in different components in Angular?

Body:
Service in add this code

 setSearchValue = new Subject<any>();
  getSearchValue = this.setSearchValue.asObservable();

First import your Service in Header component

constructor(private service: HeaderService)

header.component.ts

export class HeaderComponent implements OnInit {
        searchValue: string;
        constructor(private router: Router) { }
        ngOnInit() {
         }
         onChange($event) {
           this.service.setSearchValue.next(event);
           });
         }
       }

Search.component.ts

export class SearchComponent implements  OnInit {
        ngOnInit() {
         this.getSearchValue();
        }
      }

   getSearchValue(){
      this.service.getSearchValue.subscribe((value) => {
       this.searchValue = value;
      });
    }


问:
Python doesn't see installed module entity.rfc3413.oneliner
thank you in advance for help.

Here is an issue, I use module pysnmp with pyasn1, I am using this example:
http://pysnmp.sourceforge.net/quickstart.html , and getting an error:

```<code># python snmp.py
Traceback (most recent call last):
File "snmp.py", line 1, in <module>
from pysnmp.entity.rfc3413.oneliner import cmdgen
File "/home/user_name/rrd_poller/pysnmp.py", line 5, in <module>
ImportError: No module named **entity.rfc3413.oneliner**
</code>```

Other question is why it refers to entity.rfc3413.oneliner but not to pysnmp.entity.rfc3413.oneliner . Also, I checked

```<code>/usr/local/lib/python2.7/site-packages/pysnmp/entity/rfc3413/oneliner/__init__.py
</code>```

These server has two versions of python installed one is in /usr/bin/ other in /opt, When I do:

```<code>which python
</code>```

I get:

```<code>/opt/python/python/Python-2.7.5/python # which is correct location
</code>```

Modules are installed:

```<code>#python -c "help ('modules')"
</code>```

Gives:

```<code>pysnmp and pyasn1
</code>```

答:
Use pysnmp

```<code>pip install -U pysnmp

[root@localhost]# python
Python 2.7.5

    >> from pysnmp.entity.rfc3413.oneliner import cmdgen
    >>
</code>```

Body:
thank you in advance for help.

Here is an issue, I use module pysnmp with pyasn1, I am using this example:
http://pysnmp.sourceforge.net/quickstart.html , and getting an error:

# python snmp.py
Traceback (most recent call last):
File "snmp.py", line 1, in <module>
from pysnmp.entity.rfc3413.oneliner import cmdgen
File "/home/user_name/rrd_poller/pysnmp.py", line 5, in <module>
ImportError: No module named **entity.rfc3413.oneliner**

Other question is why it refers to entity.rfc3413.oneliner but not to pysnmp.entity.rfc3413.oneliner . Also, I checked

/usr/local/lib/python2.7/site-packages/pysnmp/entity/rfc3413/oneliner/__init__.py

These server has two versions of python installed one is in /usr/bin/ other in /opt, When I do:

which python

I get:

/opt/python/python/Python-2.7.5/python # which is correct location

Modules are installed:

#python -c "help ('modules')"

Gives:

pysnmp and pyasn1

Body:
Use pysnmp

pip install -U pysnmp

[root@localhost]# python
Python 2.7.5

    >> from pysnmp.entity.rfc3413.oneliner import cmdgen
    >>


问:
End of the (next) month from a random date
I have a question what is the fastest way to get end of the month from a day. I have a really large table and I want my code to be fast. My current code looks as follows:

```<code>library(lubridate)

end_of_month <- function(date){
 day(date) <- days_in_month(date)
 date
}
</code>```

I have another question. Is it a fast way to get a last day of the next month from a random date?

```<code>"2019-05-15" %>% as.Date() %m+% months(1) %>% end_of_month  # 2019-06-30
</code>```

Can I do this in one step or do I need an extra function to handle this?

答:
Updated answer

Thanks to @Edward for pointing out the issue in the original answer.

You can use ceiling_date after adding 1 month to the original date

```<code>ceiling_date(as.Date('2019-05-15') + months(1), unit = "month") - 1
#[1] "2019-06-30"

ceiling_date(as.Date('2019-04-15') + months(1), unit = "month") - 1
#[1] "2019-05-31"
</code>```

Old Answer

We can use ceiling_date with unit as '2 months'

```<code>library(lubridate)
'2019-05-15' %>% as.Date() %>% ceiling_date(unit = '2 months') - 1
#[1] "2019-06-30"
</code>```

Body:
I have a question what is the fastest way to get end of the month from a day. I have a really large table and I want my code to be fast. My current code looks as follows:

library(lubridate)

end_of_month <- function(date){
 day(date) <- days_in_month(date)
 date
}

I have another question. Is it a fast way to get a last day of the next month from a random date?

"2019-05-15" %>% as.Date() %m+% months(1) %>% end_of_month  # 2019-06-30

Can I do this in one step or do I need an extra function to handle this?

Body:
Updated answer

Thanks to @Edward for pointing out the issue in the original answer.

You can use ceiling_date after adding 1 month to the original date

ceiling_date(as.Date('2019-05-15') + months(1), unit = "month") - 1
#[1] "2019-06-30"

ceiling_date(as.Date('2019-04-15') + months(1), unit = "month") - 1
#[1] "2019-05-31"

Old Answer

We can use ceiling_date with unit as '2 months'

library(lubridate)
'2019-05-15' %>% as.Date() %>% ceiling_date(unit = '2 months') - 1
#[1] "2019-06-30"


问:
I am getting 500 internal sever error (XDMP-CHILDNODEKIND) while processing ZIP
We have rest extension for which one of the parameter for post  method is zip that we want to process but I am getting error 500. following message displayed in response. ZIP consist of some json and images and pdf. is there any workaround to make it run.

here is situation i have reproduced what I have got same in PROD Environment:

extension code:

```<code>declare
%roxy:params("")
%rapi:transaction-mode("update")
function dmc:post(
    $context as map:map,
    $params  as map:map,
    $input   as document-node()*
) as document-node()*
{
  let $_ := xdmp:log("**********")
  let $_ := xdmp:log($context)
  let $_ := xdmp:log("**********")

  let $_ := xdmp:log("**********")
  let $_ := xdmp:log($params)
  let $_ := xdmp:log("**********")

  let $_ := xdmp:log("**********")
  let $_ := xdmp:log($input)
  let $_ := xdmp:log("**********")

  let $_ := xdmp:log("**********")
  let $_ := xdmp:log(xdmp:get-request-field-content-type("rs:file"))
  let $_ := xdmp:log("**********")

  let $_ := map:put($context, "output-types", "application/xml")
  let $_ := map:put($context, "output-status", (201, "Created"))
  let $name := map:get($params, "name")
  let $file := map:get($params, "file")
  return document{c:my-function($name, $file)}
};
</code>```

module code :

```<code>declare function c:my-function($name as xs:string, $file as binary()) as xs:string{

    let $my-name := $name
    let $my-file := $file
    return $my-name
};
</code>```

error log:

```<code>2020-02-20 20:57:04.530 Info: **********
2020-02-20 20:57:04.530 Info: {"input-types":"multipart/form-data"}
2020-02-20 20:57:04.530 Info: **********
2020-02-20 20:57:04.530 Info: **********
2020-02-20 20:57:04.531 Info: {"file":["", "504b0304140000000800339fa94a56184dfee3850000209000001a00000000a882994a20b6abbe41000000410000000a00000000000000010020000000a38e0000617373656c2e6a736f6e504b05060000000003000300b90000000c8f00000000"], "name":"shrikant"}
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.531 Info: application/x-zip-compressed
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.537 Notice: XDMP-AS: (err:XPTY0004) $file as binary() -- Invalid coercion: "" as binary()
2020-02-20 20:57:04.537 Notice:+in /config/config.xqy, at 21:60,
2020-02-20 20:57:04.537 Notice:+in xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy")(map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/lib/extensions-util.xqy, at 905:44,
2020-02-20 20:57:04.537 Notice:+in extut:call-service("MyExtension", "POST", xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy"), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $extension-name = "MyExtension"
2020-02-20 20:57:04.537 Notice:+  $method = "POST"
2020-02-20 20:57:04.537 Notice:+  $service = xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy")
2020-02-20 20:57:04.537 Notice:+  $context = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $service-params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $input = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/lib/extensions-util.xqy, at 858:20,
2020-02-20 20:57:04.537 Notice:+in function() as item()*() [1.0-ml]
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/lib/extensions-util.xqy,
2020-02-20 20:57:04.537 Notice:+in xdmp:invoke(function() as item()*, <options xmlns="xdmp:eval"><isolation>different-transaction</isolation>...</options>) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/lib/extensions-util.xqy, at 856:12,
2020-02-20 20:57:04.537 Notice:+in extut:invoke-service("MyExtension", "POST", "query", xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy"), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}, fn:false()) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $extension-name = "MyExtension"
2020-02-20 20:57:04.537 Notice:+  $method = "POST"
2020-02-20 20:57:04.537 Notice:+  $default-txn-mode = "query"
2020-02-20 20:57:04.537 Notice:+  $service = xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy")
2020-02-20 20:57:04.537 Notice:+  $context = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $service-params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $input = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+  $in-txn = fn:false()
2020-02-20 20:57:04.537 Notice:+  $txn-curr = "query"
2020-02-20 20:57:04.537 Notice:+  $txn-mode = "update"
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/models/resource-model-query.xqy, at 269:20,
2020-02-20 20:57:04.537 Notice:+in rsrcmodqry:resource-post("MyExtension", map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}, fn:false(), local:rsrcmod-callback#6) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $resource-name = "MyExtension"
2020-02-20 20:57:04.537 Notice:+  $context = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $resource-params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $input = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+  $in-txn = fn:false()
2020-02-20 20:57:04.537 Notice:+  $responder = local:rsrcmod-callback#6
2020-02-20 20:57:04.537 Notice:+  $service = xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy")
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/models/resource-model-query.xqy, at 236:4,
2020-02-20 20:57:04.537 Notice:+in rsrcmodqry:exec-post(map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}, local:rsrcmod-callback#6) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $headers = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $endpoint-params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $input = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+  $responder = local:rsrcmod-callback#6
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/endpoints/resource-service-query.xqy, at 78:8 [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $headers = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $method = "POST"
2020-02-20 20:57:04.537 Notice:+  $body = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+  $params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $extra-names = ()
2020-02-20 20:57:04.542 Info: Status 500: XDMP-AS: (err:XPTY0004) $file as binary() -- Invalid coercion: "" as binary()
</code>```

答:
The error message is pretty clear here - you can’t have child nodes with binary content i.e. can’t put an image as a child node of an XML document, for example

This has been already answered in more detail:

Query generate 'XDMP-CHILDNODEKIND: $final -- element nodes cannot have binary node children' error

Body:
We have rest extension for which one of the parameter for post  method is zip that we want to process but I am getting error 500. following message displayed in response. ZIP consist of some json and images and pdf. is there any workaround to make it run.

here is situation i have reproduced what I have got same in PROD Environment:

extension code:

declare
%roxy:params("")
%rapi:transaction-mode("update")
function dmc:post(
    $context as map:map,
    $params  as map:map,
    $input   as document-node()*
) as document-node()*
{
  let $_ := xdmp:log("**********")
  let $_ := xdmp:log($context)
  let $_ := xdmp:log("**********")

  let $_ := xdmp:log("**********")
  let $_ := xdmp:log($params)
  let $_ := xdmp:log("**********")

  let $_ := xdmp:log("**********")
  let $_ := xdmp:log($input)
  let $_ := xdmp:log("**********")

  let $_ := xdmp:log("**********")
  let $_ := xdmp:log(xdmp:get-request-field-content-type("rs:file"))
  let $_ := xdmp:log("**********")

  let $_ := map:put($context, "output-types", "application/xml")
  let $_ := map:put($context, "output-status", (201, "Created"))
  let $name := map:get($params, "name")
  let $file := map:get($params, "file")
  return document{c:my-function($name, $file)}
};

module code :

declare function c:my-function($name as xs:string, $file as binary()) as xs:string{

    let $my-name := $name
    let $my-file := $file
    return $my-name
};

error log:

2020-02-20 20:57:04.530 Info: **********
2020-02-20 20:57:04.530 Info: {"input-types":"multipart/form-data"}
2020-02-20 20:57:04.530 Info: **********
2020-02-20 20:57:04.530 Info: **********
2020-02-20 20:57:04.531 Info: {"file":["", "504b0304140000000800339fa94a56184dfee3850000209000001a00000000a882994a20b6abbe41000000410000000a00000000000000010020000000a38e0000617373656c2e6a736f6e504b05060000000003000300b90000000c8f00000000"], "name":"shrikant"}
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.531 Info: application/x-zip-compressed
2020-02-20 20:57:04.531 Info: **********
2020-02-20 20:57:04.537 Notice: XDMP-AS: (err:XPTY0004) $file as binary() -- Invalid coercion: "" as binary()
2020-02-20 20:57:04.537 Notice:+in /config/config.xqy, at 21:60,
2020-02-20 20:57:04.537 Notice:+in xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy")(map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/lib/extensions-util.xqy, at 905:44,
2020-02-20 20:57:04.537 Notice:+in extut:call-service("MyExtension", "POST", xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy"), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $extension-name = "MyExtension"
2020-02-20 20:57:04.537 Notice:+  $method = "POST"
2020-02-20 20:57:04.537 Notice:+  $service = xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy")
2020-02-20 20:57:04.537 Notice:+  $context = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $service-params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $input = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/lib/extensions-util.xqy, at 858:20,
2020-02-20 20:57:04.537 Notice:+in function() as item()*() [1.0-ml]
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/lib/extensions-util.xqy,
2020-02-20 20:57:04.537 Notice:+in xdmp:invoke(function() as item()*, <options xmlns="xdmp:eval"><isolation>different-transaction</isolation>...</options>) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/lib/extensions-util.xqy, at 856:12,
2020-02-20 20:57:04.537 Notice:+in extut:invoke-service("MyExtension", "POST", "query", xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy"), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}, fn:false()) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $extension-name = "MyExtension"
2020-02-20 20:57:04.537 Notice:+  $method = "POST"
2020-02-20 20:57:04.537 Notice:+  $default-txn-mode = "query"
2020-02-20 20:57:04.537 Notice:+  $service = xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy")
2020-02-20 20:57:04.537 Notice:+  $context = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $service-params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $input = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+  $in-txn = fn:false()
2020-02-20 20:57:04.537 Notice:+  $txn-curr = "query"
2020-02-20 20:57:04.537 Notice:+  $txn-mode = "update"
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/models/resource-model-query.xqy, at 269:20,
2020-02-20 20:57:04.537 Notice:+in rsrcmodqry:resource-post("MyExtension", map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}, fn:false(), local:rsrcmod-callback#6) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $resource-name = "MyExtension"
2020-02-20 20:57:04.537 Notice:+  $context = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $resource-params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $input = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+  $in-txn = fn:false()
2020-02-20 20:57:04.537 Notice:+  $responder = local:rsrcmod-callback#6
2020-02-20 20:57:04.537 Notice:+  $service = xdmp:function(fn:QName("http://marklogic.com/rest-api/resource/MyExtension","post"), "/marklogic.rest.resource/MyExtension/assets/resource.xqy")
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/models/resource-model-query.xqy, at 236:4,
2020-02-20 20:57:04.537 Notice:+in rsrcmodqry:exec-post(map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>), map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...), document{binary{""}}, local:rsrcmod-callback#6) [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $headers = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $endpoint-params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $input = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+  $responder = local:rsrcmod-callback#6
2020-02-20 20:57:04.537 Notice:+in /MarkLogic/rest-api/endpoints/resource-service-query.xqy, at 78:8 [1.0-ml]
2020-02-20 20:57:04.537 Notice:+  $headers = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>)
2020-02-20 20:57:04.537 Notice:+  $method = "POST"
2020-02-20 20:57:04.537 Notice:+  $body = document{binary{""}}
2020-02-20 20:57:04.537 Notice:+  $params = map:map(<map:map xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>...XDMP-CHILDNODEKIND: element nodes cannot have binary node children...)
2020-02-20 20:57:04.537 Notice:+  $extra-names = ()
2020-02-20 20:57:04.542 Info: Status 500: XDMP-AS: (err:XPTY0004) $file as binary() -- Invalid coercion: "" as binary()


问:
Problem outputting solution for a 2 digit BCD adder using Verilog
I am building a 2 digit BCD adder using only one module. I am rather new to verilog so i don't know if i made a mistake with some of the assignments, but the simulation wont output any answer it just give me the X error for my output. I dont know if i made a mistake in coding the module or coding the simulation but all the waveform output shows is the inputs but give me no outputs. I just want to know where i went wrong. I am kinda stuck here.

I am trying to create this:

The code for module is as follows:

```<code>   `timescale 1ns / 1ps

module two_digit_BCDAdder(input [7:0] X, input Load, input clk, output [8:0]R );

reg [7:0] Q=0;
always @(posedge clk)
begin
if (Load)
Q<=X;
else
Q<=Q;
end
// 8 bit register

wire sum1, sum3;

//wires for both upper  parallel adders sum1 left adder sum 3 right adder

 wire cout1, cout2, cout3, cout4;
// wires for cout,  being cout1 top left adder, cout 2 bottom left adder,
//  cout3 top right adder, cout 4 bottom right adder

 wire cin;
// wire for or gate connected to cin

 wire d1,d2;
// D1 connects or gate of the comparator and cout 1 to PA bottom left,
//  D2 connects or gate of the comparator and cout 1 to PA bottom right,

 wire C1,C2;
// C1 comparator on the left
// C2 comparator on the right

 assign cin = (cout1|cout2);
// Cin or gate

 assign d1 = (cout1|C1);
 assign d2 =(cout3|C2);
// Creation of or gates

 assign C1 = (sum1 > 4'b1001);
 assign C2= (sum3 > 4'b1001);
// Comparator sum hase tobe greater than 9 for BCD addition

 assign {cout3, sum3}= {Q[0],Q[1],Q[2],Q[3]}+{X[0],X[1],X[2],X[3]};
// Top right Parallel Adder
 assign {cout4,{R[0],R[1],R[2],R[3]}} = sum3+{1'b0,d2,d2,1'b0};
// Bottom left Comparator

 assign {cout1,sum1} = {Q[4],Q[5],Q[6],Q[7]}+{X[4],X[5],X[6],X[7]}+cin;
 // Top left Parallel Adder

 assign {cout2,{R[4],R[5],R[6],R[7]}} = sum1 +{1'b0,d1,d1,1'b0};
 // bottom left Parallel Adder

 assign R[8]=(d1|cout2);
//or gate for final carry led

endmodule

</code>```

This is the simulation code i am working with:

```<code>    `timescale 1ns / 1ps

module BCD_sim();
reg [7:0]x;
reg b;
reg clk;
wire[8:0]r;

two_digit_BCDAdder uut(x,b,clk,r);

initial
begin
clk =0;

 forever #1 clk=~clk;
end

initial
 begin

x=0; b=0;
//Values for test
#2 x=55; b=1;
#2 x=55; b=0;
#4;
#2 x=99; b=1;
#2 x=99; b=0;
#4;
#2 x=87; b=1;
#2 x=78; b=0;
#4;
#2 x=25; b=1;
#2 x=75; b=0;
#4;
#2 x=33; b=1;
#2 x=66; b=0;
#4;
#2 x=69; b=1;
#2 x=96; b=0;

$finish;
end
endmodule

</code>```

答:
I have updated the code to make it modular.. and picture with inked modular names is added

```<code>     `timescale 1ns / 1ps

module two_digit_BCDAdder(
    input           clk,
    input [7:0]     X,
    input           Load,
    output [8:0]    R
);

reg [7:0] Q = 0;

// 8 bit register
always @(posedge clk)begin
    if (Load) Q <= #10 X;
    else      Q <= #10 Q;
 end

 wire [3:0] AM,AL,BL,BM;
 wire [3:0] sum_PA1,sum_PA2,sum_PA3,sum_PA4;
 wire       cin_PA1,cin_PA2,cin_PA3,cin_PA4;
 wire       cout_PA1,cout_PA2,cout_PA3,cout_PA4;
 wire       or_gate1_out,or_gate2_out,or_gate3_out,or_gate4_out;
 wire       c1_ag9,c2_ag9;

 assign AL = Q[3:0] ;
 assign AM = Q[7:4] ;
 assign BL = X[3:0] ;
 assign BM = X[7:4] ;

adder PA1(
    .a     (AM)
   ,.b     (BM)
   ,.c_in  (or_gate3_out)
   ,.sum   (sum_PA1)
   ,.c_out (cout_PA1)
);

adder PA2(
    .a     (AL)
   ,.b     (BL)
   ,.c_in  (1'b0)
   ,.sum   (sum_PA2)
   ,.c_out (cout_PA2)
);

adder PA3(
    .a     ({1'b0,{2{or_gate1_out}},1'b0})
   ,.b     (sum_PA1)
   ,.c_in  (1'b0)
   ,.sum   (sum_PA3)
   ,.c_out (cout_PA3)
);

adder PA4(
    .a     ({1'b0,{2{or_gate4_out}},1'b0})
   ,.b     (sum_PA2)
   ,.c_in  (1'b0)
   ,.sum   (sum_PA4)
   ,.c_out (cout_PA4)
);

comp C1(
    .a   (sum_PA1)
   ,.ag9 (c1_ag9)
);

comp C2(
    .a   (sum_PA2)
   ,.ag9 (c2_ag9)
);

or_gate or_gate1 (
  .a   (cout_PA1)
 ,.b   (c1_ag9)
 ,.out (or_gate1_out)
);

or_gate or_gate2 (
  .a   (or_gate1_out)
 ,.b   (cout_PA3)
 ,.out (or_gate2_out)
);

or_gate or_gate3 (
  .a   (cout_PA2)
 ,.b   (cout_PA4)
 ,.out (or_gate3_out)
);

or_gate or_gate4 (
  .a   (c2_ag9)
 ,.b   (cout_PA2)
 ,.out (or_gate4_out)
);

 assign R[3:0]  = sum_PA4;
 assign R[7:4]  = sum_PA3;
 assign R[8]    = or_gate2_out;

endmodule

 module adder (input  [3:0] a,b,
               input        c_in,
               output [3:0] sum,
               output       c_out
);
    assign {c_out,sum} = a+b+c_in;
endmodule

module comp (input [3:0] a,
             output      ag9
);
   assign ag9 = a > 4'h9;
endmodule

module or_gate(input  a,b,
               output out
);
    assign out = a||b;
endmodule
</code>```

and new tb file with named port connections to dut

```<code>     `timescale 1ns / 1ps

module BCD_sim();
reg [7:0]x;
reg b;
reg clk;
wire[8:0]r;

two_digit_BCDAdder dut(
     .clk    (clk)
    ,.X      (x)
    ,.Load   (b)
    ,.R      (r)
);

initial
begin
clk =0;
 forever #1 clk=~clk;
end

initial
 begin

x=0; b=0;
//Values for test
#2 x=55; b=1;
#2 x=55; b=0;
#4;
#2 x=99; b=1;
#2 x=99; b=0;
#4;
#2 x=87; b=1;
#2 x=78; b=0;
#4;
#2 x=25; b=1;
#2 x=75; b=0;
#4;
#2 x=33; b=1;
#2 x=66; b=0;
#4;
#2 x=69; b=1;
#2 x=96; b=0;

$finish;
end
endmodule
</code>```

with the above files vivdo simulator is showing the results..

simple code instead of modular

```<code>    module two_digit_BCDAdder(
    input           clk,
    input [7:0]     X,
    input           Load,
    output [8:0]    R
);

reg [7:0] Q = 0;

// 8 bit register
always @(posedge clk)begin
    if (Load) Q <= #10 X;
    else      Q <= #10 Q;
 end

 wire [3:0] AM,AL,BL,BM;
 wire [3:0] sum_PA1,sum_PA2,sum_PA3,sum_PA4;
 wire       cin_PA1,cin_PA2,cin_PA3,cin_PA4;
 wire       cout_PA1,cout_PA2,cout_PA3,cout_PA4;
 wire       or_gate1_out,or_gate2_out,or_gate3_out,or_gate4_out;
 wire       c1_ag9,c2_ag9;

 assign AL = Q[3:0] ;
 assign AM = Q[7:4] ;
 assign BL = X[3:0] ;
 assign BM = X[7:4] ;

 //4 Adders
 assign {cout_PA1,sum_PA1} = AM[3:0] + BM[3:0] + or_gate3_out;
 assign {cout_PA2,sum_PA2} = AL[3:0] + BL[3:0] + 1'b0        ;
 assign {cout_PA3,sum_PA3} = sum_PA1[3:0] + {1'b0,{2{or_gate1_out}},1'b0} + 1'b0;
 assign {cout_PA4,sum_PA4} = sum_PA2[3:0] + {1'b0,{2{or_gate4_out}},1'b0} + 1'b0;

 // 2 Comparators
 assign c1_ag9 = sum_PA1 > 4'h9 ;
 assign c2_ag9 = sum_PA2 > 4'h9 ;

// 4 OR gates
assign or_gate1_out = cout_PA1     || c1_ag9   ;
assign or_gate2_out = or_gate1_out || cout_PA3 ;
assign or_gate3_out = cout_PA2     || cout_PA4 ;
assign or_gate4_out = cout_PA2     || c2_ag9   ;

// Assigning outputs
 assign R[3:0]  = sum_PA4;
 assign R[7:4]  = sum_PA3;
 assign R[8]    = or_gate2_out;

endmodule
</code>```

Body:
I am building a 2 digit BCD adder using only one module. I am rather new to verilog so i don't know if i made a mistake with some of the assignments, but the simulation wont output any answer it just give me the X error for my output. I dont know if i made a mistake in coding the module or coding the simulation but all the waveform output shows is the inputs but give me no outputs. I just want to know where i went wrong. I am kinda stuck here.

I am trying to create this:

The code for module is as follows:

   `timescale 1ns / 1ps

module two_digit_BCDAdder(input [7:0] X, input Load, input clk, output [8:0]R );

reg [7:0] Q=0;
always @(posedge clk)
begin
if (Load)
Q<=X;
else
Q<=Q;
end
// 8 bit register

wire sum1, sum3;

//wires for both upper  parallel adders sum1 left adder sum 3 right adder

 wire cout1, cout2, cout3, cout4;
// wires for cout,  being cout1 top left adder, cout 2 bottom left adder,
//  cout3 top right adder, cout 4 bottom right adder

 wire cin;
// wire for or gate connected to cin

 wire d1,d2;
// D1 connects or gate of the comparator and cout 1 to PA bottom left,
//  D2 connects or gate of the comparator and cout 1 to PA bottom right,

 wire C1,C2;
// C1 comparator on the left
// C2 comparator on the right

 assign cin = (cout1|cout2);
// Cin or gate

 assign d1 = (cout1|C1);
 assign d2 =(cout3|C2);
// Creation of or gates

 assign C1 = (sum1 > 4'b1001);
 assign C2= (sum3 > 4'b1001);
// Comparator sum hase tobe greater than 9 for BCD addition

 assign {cout3, sum3}= {Q[0],Q[1],Q[2],Q[3]}+{X[0],X[1],X[2],X[3]};
// Top right Parallel Adder
 assign {cout4,{R[0],R[1],R[2],R[3]}} = sum3+{1'b0,d2,d2,1'b0};
// Bottom left Comparator

 assign {cout1,sum1} = {Q[4],Q[5],Q[6],Q[7]}+{X[4],X[5],X[6],X[7]}+cin;
 // Top left Parallel Adder

 assign {cout2,{R[4],R[5],R[6],R[7]}} = sum1 +{1'b0,d1,d1,1'b0};
 // bottom left Parallel Adder

 assign R[8]=(d1|cout2);
//or gate for final carry led

endmodule

This is the simulation code i am working with:

    `timescale 1ns / 1ps

module BCD_sim();
reg [7:0]x;
reg b;
reg clk;
wire[8:0]r;

two_digit_BCDAdder uut(x,b,clk,r);

initial
begin
clk =0;

 forever #1 clk=~clk;
end

initial
 begin

x=0; b=0;
//Values for test
#2 x=55; b=1;
#2 x=55; b=0;
#4;
#2 x=99; b=1;
#2 x=99; b=0;
#4;
#2 x=87; b=1;
#2 x=78; b=0;
#4;
#2 x=25; b=1;
#2 x=75; b=0;
#4;
#2 x=33; b=1;
#2 x=66; b=0;
#4;
#2 x=69; b=1;
#2 x=96; b=0;

$finish;
end
endmodule

Body:
I have updated the code to make it modular.. and picture with inked modular names is added

     `timescale 1ns / 1ps

module two_digit_BCDAdder(
    input           clk,
    input [7:0]     X,
    input           Load,
    output [8:0]    R
);

reg [7:0] Q = 0;

// 8 bit register
always @(posedge clk)begin
    if (Load) Q <= #10 X;
    else      Q <= #10 Q;
 end

 wire [3:0] AM,AL,BL,BM;
 wire [3:0] sum_PA1,sum_PA2,sum_PA3,sum_PA4;
 wire       cin_PA1,cin_PA2,cin_PA3,cin_PA4;
 wire       cout_PA1,cout_PA2,cout_PA3,cout_PA4;
 wire       or_gate1_out,or_gate2_out,or_gate3_out,or_gate4_out;
 wire       c1_ag9,c2_ag9;

 assign AL = Q[3:0] ;
 assign AM = Q[7:4] ;
 assign BL = X[3:0] ;
 assign BM = X[7:4] ;

adder PA1(
    .a     (AM)
   ,.b     (BM)
   ,.c_in  (or_gate3_out)
   ,.sum   (sum_PA1)
   ,.c_out (cout_PA1)
);

adder PA2(
    .a     (AL)
   ,.b     (BL)
   ,.c_in  (1'b0)
   ,.sum   (sum_PA2)
   ,.c_out (cout_PA2)
);

adder PA3(
    .a     ({1'b0,{2{or_gate1_out}},1'b0})
   ,.b     (sum_PA1)
   ,.c_in  (1'b0)
   ,.sum   (sum_PA3)
   ,.c_out (cout_PA3)
);

adder PA4(
    .a     ({1'b0,{2{or_gate4_out}},1'b0})
   ,.b     (sum_PA2)
   ,.c_in  (1'b0)
   ,.sum   (sum_PA4)
   ,.c_out (cout_PA4)
);

comp C1(
    .a   (sum_PA1)
   ,.ag9 (c1_ag9)
);

comp C2(
    .a   (sum_PA2)
   ,.ag9 (c2_ag9)
);

or_gate or_gate1 (
  .a   (cout_PA1)
 ,.b   (c1_ag9)
 ,.out (or_gate1_out)
);

or_gate or_gate2 (
  .a   (or_gate1_out)
 ,.b   (cout_PA3)
 ,.out (or_gate2_out)
);

or_gate or_gate3 (
  .a   (cout_PA2)
 ,.b   (cout_PA4)
 ,.out (or_gate3_out)
);

or_gate or_gate4 (
  .a   (c2_ag9)
 ,.b   (cout_PA2)
 ,.out (or_gate4_out)
);

 assign R[3:0]  = sum_PA4;
 assign R[7:4]  = sum_PA3;
 assign R[8]    = or_gate2_out;

endmodule

 module adder (input  [3:0] a,b,
               input        c_in,
               output [3:0] sum,
               output       c_out
);
    assign {c_out,sum} = a+b+c_in;
endmodule

module comp (input [3:0] a,
             output      ag9
);
   assign ag9 = a > 4'h9;
endmodule

module or_gate(input  a,b,
               output out
);
    assign out = a||b;
endmodule

and new tb file with named port connections to dut

     `timescale 1ns / 1ps

module BCD_sim();
reg [7:0]x;
reg b;
reg clk;
wire[8:0]r;

two_digit_BCDAdder dut(
     .clk    (clk)
    ,.X      (x)
    ,.Load   (b)
    ,.R      (r)
);

initial
begin
clk =0;
 forever #1 clk=~clk;
end

initial
 begin

x=0; b=0;
//Values for test
#2 x=55; b=1;
#2 x=55; b=0;
#4;
#2 x=99; b=1;
#2 x=99; b=0;
#4;
#2 x=87; b=1;
#2 x=78; b=0;
#4;
#2 x=25; b=1;
#2 x=75; b=0;
#4;
#2 x=33; b=1;
#2 x=66; b=0;
#4;
#2 x=69; b=1;
#2 x=96; b=0;

$finish;
end
endmodule

with the above files vivdo simulator is showing the results..

simple code instead of modular

    module two_digit_BCDAdder(
    input           clk,
    input [7:0]     X,
    input           Load,
    output [8:0]    R
);

reg [7:0] Q = 0;

// 8 bit register
always @(posedge clk)begin
    if (Load) Q <= #10 X;
    else      Q <= #10 Q;
 end

 wire [3:0] AM,AL,BL,BM;
 wire [3:0] sum_PA1,sum_PA2,sum_PA3,sum_PA4;
 wire       cin_PA1,cin_PA2,cin_PA3,cin_PA4;
 wire       cout_PA1,cout_PA2,cout_PA3,cout_PA4;
 wire       or_gate1_out,or_gate2_out,or_gate3_out,or_gate4_out;
 wire       c1_ag9,c2_ag9;

 assign AL = Q[3:0] ;
 assign AM = Q[7:4] ;
 assign BL = X[3:0] ;
 assign BM = X[7:4] ;

 //4 Adders
 assign {cout_PA1,sum_PA1} = AM[3:0] + BM[3:0] + or_gate3_out;
 assign {cout_PA2,sum_PA2} = AL[3:0] + BL[3:0] + 1'b0        ;
 assign {cout_PA3,sum_PA3} = sum_PA1[3:0] + {1'b0,{2{or_gate1_out}},1'b0} + 1'b0;
 assign {cout_PA4,sum_PA4} = sum_PA2[3:0] + {1'b0,{2{or_gate4_out}},1'b0} + 1'b0;

 // 2 Comparators
 assign c1_ag9 = sum_PA1 > 4'h9 ;
 assign c2_ag9 = sum_PA2 > 4'h9 ;

// 4 OR gates
assign or_gate1_out = cout_PA1     || c1_ag9   ;
assign or_gate2_out = or_gate1_out || cout_PA3 ;
assign or_gate3_out = cout_PA2     || cout_PA4 ;
assign or_gate4_out = cout_PA2     || c2_ag9   ;

// Assigning outputs
 assign R[3:0]  = sum_PA4;
 assign R[7:4]  = sum_PA3;
 assign R[8]    = or_gate2_out;

endmodule


问:
Validate a certain column in a csv file data using textfieldparser in c#
I have a button in my webform that uploads a csv file with data, inserts the data in a database, and displays the content of the database in a gridview. I am using a TextFieldParser to read the csv file. However, I cannot seem to figure out how to add a validation in it.

I want to validate the first column (which is the SKU in my database) of the uploaded csv file data. If the data has a duplicate in the database, it will prompt a message that the action cannot be completed. If not, it will continue to insert the data in the database.

This is what the data in the csv file that will be uploaded looks like

For reference, This is my code:

```<code>protected void AddButton_Click(object sender, EventArgs e)
    {

        string path = @"C:\Users\hac9289\Downloads\";
        //Creating object of datatable
        DataTable tblcsv = new DataTable();
        //creating columns
        tblcsv.Columns.Add("Stock Keeping Unit");
        tblcsv.Columns.Add("Universal Product Code");
        tblcsv.Columns.Add("Vendor Name");
        tblcsv.Columns.Add("Product Name");
        tblcsv.Columns.Add("Product Description");
        tblcsv.Columns.Add("Retail Price");
        //getting full file path of Uploaded file
        string CSVFilePath = Path.GetFullPath(path + AddFile.PostedFile.FileName);

        if (!AddFile.HasFile)
        {
            ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('File Upload Empty');", true);
        }

        else
        {
            //parse records in csv file
            using (TextFieldParser parser = new TextFieldParser(CSVFilePath))
            {
                parser.HasFieldsEnclosedInQuotes = true;
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                bool invalid = false;

                while (!parser.EndOfData)
                {
                    //Processing row
                    tblcsv.Rows.Add();
                    int count = 0;
                    string[] fields = parser.ReadFields();

                    /*I am trying these code for validation but it doesnt work hahaha
                    foreach (DataRow row in tblcsv.Rows)
                    {
                        // Check some other column is not equal to some value
                        if (row["StockKeepingUnit"] == fields)
                        {
                            ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Action not completed due to duplicate SKU');", true);
                        }
                    }*/

                    foreach (string field in fields)
                    {
                        tblcsv.Rows[tblcsv.Rows.Count - 1][count] = field;

                        count++;
                    }
                }
            }
            InsertCSVRecords(tblcsv);
            PopulateGridView();
        }

    }

    private void InsertCSVRecords(DataTable csvdt)
    {

        using (SqlConnection connect = new SqlConnection(connectionString))
        {
            connect.Open();

            //creating object of SqlBulkCopy
            using (SqlBulkCopy objbulk = new SqlBulkCopy(connect))
            {
                //assigning Destination table name
                objbulk.DestinationTableName = "RetailInfo";
                //Mapping Table column
                objbulk.ColumnMappings.Add(0, "StockKeepingUnit");
                objbulk.ColumnMappings.Add(1, "UniversalProductCode");
                objbulk.ColumnMappings.Add(2, "VendorName");
                objbulk.ColumnMappings.Add(3, "ProductName");
                objbulk.ColumnMappings.Add(4, "ProductDesc");
                objbulk.ColumnMappings.Add(5, "RetailPrice");

                //inserting Datatable Records to DataBase
                objbulk.WriteToServer(csvdt);
            }
        }

        ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('CSV Data added');", true);

    }
</code>```

Any ideas? Any help will be appreciated. Thank you.

答:
You can use the select method of data table which returns an array of rows that matches the filter criteria.

```<code>     //Instead of 0 in fileds[0] you have to provide an index of stock-keeping unit index position in array
     if (tblcsv.Select($"StockKeepingUnit={fields[0]}").Length > 0)
     {
            //Display Message Record already exists
            //Skip to add in datatable and continue
            //or display message
     }
</code>```

Body:
I have a button in my webform that uploads a csv file with data, inserts the data in a database, and displays the content of the database in a gridview. I am using a TextFieldParser to read the csv file. However, I cannot seem to figure out how to add a validation in it.

I want to validate the first column (which is the SKU in my database) of the uploaded csv file data. If the data has a duplicate in the database, it will prompt a message that the action cannot be completed. If not, it will continue to insert the data in the database.

This is what the data in the csv file that will be uploaded looks like

For reference, This is my code:

protected void AddButton_Click(object sender, EventArgs e)
    {

        string path = @"C:\Users\hac9289\Downloads\";
        //Creating object of datatable
        DataTable tblcsv = new DataTable();
        //creating columns
        tblcsv.Columns.Add("Stock Keeping Unit");
        tblcsv.Columns.Add("Universal Product Code");
        tblcsv.Columns.Add("Vendor Name");
        tblcsv.Columns.Add("Product Name");
        tblcsv.Columns.Add("Product Description");
        tblcsv.Columns.Add("Retail Price");
        //getting full file path of Uploaded file
        string CSVFilePath = Path.GetFullPath(path + AddFile.PostedFile.FileName);

        if (!AddFile.HasFile)
        {
            ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('File Upload Empty');", true);
        }

        else
        {
            //parse records in csv file
            using (TextFieldParser parser = new TextFieldParser(CSVFilePath))
            {
                parser.HasFieldsEnclosedInQuotes = true;
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                bool invalid = false;

                while (!parser.EndOfData)
                {
                    //Processing row
                    tblcsv.Rows.Add();
                    int count = 0;
                    string[] fields = parser.ReadFields();

                    /*I am trying these code for validation but it doesnt work hahaha
                    foreach (DataRow row in tblcsv.Rows)
                    {
                        // Check some other column is not equal to some value
                        if (row["StockKeepingUnit"] == fields)
                        {
                            ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Action not completed due to duplicate SKU');", true);
                        }
                    }*/

                    foreach (string field in fields)
                    {
                        tblcsv.Rows[tblcsv.Rows.Count - 1][count] = field;

                        count++;
                    }
                }
            }
            InsertCSVRecords(tblcsv);
            PopulateGridView();
        }

    }

    private void InsertCSVRecords(DataTable csvdt)
    {

        using (SqlConnection connect = new SqlConnection(connectionString))
        {
            connect.Open();

            //creating object of SqlBulkCopy
            using (SqlBulkCopy objbulk = new SqlBulkCopy(connect))
            {
                //assigning Destination table name
                objbulk.DestinationTableName = "RetailInfo";
                //Mapping Table column
                objbulk.ColumnMappings.Add(0, "StockKeepingUnit");
                objbulk.ColumnMappings.Add(1, "UniversalProductCode");
                objbulk.ColumnMappings.Add(2, "VendorName");
                objbulk.ColumnMappings.Add(3, "ProductName");
                objbulk.ColumnMappings.Add(4, "ProductDesc");
                objbulk.ColumnMappings.Add(5, "RetailPrice");

                //inserting Datatable Records to DataBase
                objbulk.WriteToServer(csvdt);
            }
        }

        ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('CSV Data added');", true);

    }

Any ideas? Any help will be appreciated. Thank you.

Body:
You can use the select method of data table which returns an array of rows that matches the filter criteria.

     //Instead of 0 in fileds[0] you have to provide an index of stock-keeping unit index position in array
     if (tblcsv.Select($"StockKeepingUnit={fields[0]}").Length > 0)
     {
            //Display Message Record already exists
            //Skip to add in datatable and continue
            //or display message
     }


问:
Update table based on another table
I'm trying to update a column in a table based on another column in another table.

```<code>UPDATE eval e
   SET rank = (SELECT p.desc
                 FROM Position p
                WHERE p.id = e.faculty
                  AND p.date >= '2011-05-20'
              )
</code>```

p.id and e.faculty correspond. I want to update rank with p.desc if the id's are the same. (e.faculty and p.id)

Any help will be great! :)

答:
You need a restriction in the form of a WHERE clause; if you use EXISTS you can based it on you scalar subquery e.g.

```<code>UPDATE eval
   SET rank = (
               SELECT p.desc
                 FROM Position p
                WHERE p.id = eval.faculty
                      AND p.date >= '2011-05-20'
              )
 WHERE EXISTS (
               SELECT *
                 FROM Position p
                WHERE p.id = eval.faculty
                      AND p.date >= '2011-05-20'
              );
</code>```

Note the above targets the UPDATE on the base table eval rather than the correlation name e. This makes a lot more sense when you think of an SQL UPDATE in terms of relational assignment i.e. you don't want to assign to e because it (unlike the base table) will go out of scope!

Title: Update table based on another table

Body:
I'm trying to update a column in a table based on another column in another table.

UPDATE eval e
   SET rank = (SELECT p.desc
                 FROM Position p
                WHERE p.id = e.faculty
                  AND p.date >= '2011-05-20'
              )

p.id and e.faculty correspond. I want to update rank with p.desc if the id's are the same. (e.faculty and p.id)

Any help will be great! :)

Body:
You need a restriction in the form of a WHERE clause; if you use EXISTS you can based it on you scalar subquery e.g.

UPDATE eval
   SET rank = (
               SELECT p.desc
                 FROM Position p
                WHERE p.id = eval.faculty
                      AND p.date >= '2011-05-20'
              )
 WHERE EXISTS (
               SELECT *
                 FROM Position p
                WHERE p.id = eval.faculty
                      AND p.date >= '2011-05-20'
              );

Note the above targets the UPDATE on the base table eval rather than the correlation name e. This makes a lot more sense when you think of an SQL UPDATE in terms of relational assignment i.e. you don't want to assign to e because it (unlike the base table) will go out of scope!


问:
us WHERE statement and ARRAY for AthenaQuery
I have an SQL query like this (written for PostgreSQL):

```<code>SELECT *
FROM users
WHERE users.company_id = ANY(ARRAY[945387, 969109, 1460013, 1460044]) AND
 users.profession_id = ANY(ARRAY[2738, 6388])
GROUP BY users.company_id
</code>```

but I can't run it like this for AthenaQuery (getting SYNTAX_ERROR: Function any not registered).
How can I convert it?

答:
You can rewrite the array operator to a standard IN condition.

Your query is equivalent to:

```<code>SELECT *
FROM users
WHERE users.company_id IN (945387, 969109, 1460013, 1460044)
  AND users.profession_id IN (2738, 6388)
GROUP BY users.company_id
</code>```

Body:
I have an SQL query like this (written for PostgreSQL):

SELECT *
FROM users
WHERE users.company_id = ANY(ARRAY[945387, 969109, 1460013, 1460044]) AND
 users.profession_id = ANY(ARRAY[2738, 6388])
GROUP BY users.company_id

but I can't run it like this for AthenaQuery (getting SYNTAX_ERROR: Function any not registered).
How can I convert it?

Body:
You can rewrite the array operator to a standard IN condition.

Your query is equivalent to:

SELECT *
FROM users
WHERE users.company_id IN (945387, 969109, 1460013, 1460044)
  AND users.profession_id IN (2738, 6388)
GROUP BY users.company_id


问:
How can I import bulk data from a CSV file into DynamoDB?
I am trying to import a CSV file data into AWS DynamoDB.

Here's what my CSV file looks like:

```<code>first_name  last_name
sri ram
Rahul   Dravid
JetPay  Underwriter
Anil Kumar  Gurram
</code>```

答:
Here's a simpler solution. And with this solution, you don't have to remove empty string attributes.</p>

```<code>require('./env'); //contains aws secret/access key
const parse = require('csvtojson');
const AWS = require('aws-sdk');

// --- start user config ---

const CSV_FILENAME = __dirname + "/002_subscribers_copy_from_db.csv";
const DYNAMODB_TABLENAME = '002-Subscribers';

// --- end user config ---

//You could add your credentials here or you could
//store it in process.env like I have done aws-sdk
//would detect the keys in the environment

AWS.config.update({
    region: process.env.AWS_REGION
});

const db = new AWS.DynamoDB.DocumentClient({
    convertEmptyValues: true
});

(async ()=>{
    const json = await parse().fromFile(CSV_FILENAME);

    //this is efficient enough if you're processing small
    //amounts of data. If your data set is large then I
    //suggest using dynamodb method .batchWrite() and send
    //in data in chunks of 25 (the limit) and find yourself
    //a more efficient loop if there is one
    for(var i=0; i<json.length; i++){
        console.log(`processing item number ${i+1}`);
        let query = {
            TableName: DYNAMODB_TABLENAME,
            Item: json[i]
        };

        await db.put(query).promise();

        /**
         * Note: If "json" contains other nested objects, you would have to
         *       loop through the json and parse all child objects.
         *       likewise, you would have to convert all children into their
         *       native primitive types because everything would be represented
         *       as a string.
         */
    }
    console.log('\nDone.');
})();
</code>```

Body:
I am trying to import a CSV file data into AWS DynamoDB.

Here's what my CSV file looks like:

first_name  last_name
sri ram
Rahul   Dravid
JetPay  Underwriter
Anil Kumar  Gurram

Body:
Here's a simpler solution. And with this solution, you don't have to remove empty string attributes.

require('./env'); //contains aws secret/access key
const parse = require('csvtojson');
const AWS = require('aws-sdk');

// --- start user config ---

const CSV_FILENAME = __dirname + "/002_subscribers_copy_from_db.csv";
const DYNAMODB_TABLENAME = '002-Subscribers';

// --- end user config ---

//You could add your credentials here or you could
//store it in process.env like I have done aws-sdk
//would detect the keys in the environment

AWS.config.update({
    region: process.env.AWS_REGION
});

const db = new AWS.DynamoDB.DocumentClient({
    convertEmptyValues: true
});

(async ()=>{
    const json = await parse().fromFile(CSV_FILENAME);

    //this is efficient enough if you're processing small
    //amounts of data. If your data set is large then I
    //suggest using dynamodb method .batchWrite() and send
    //in data in chunks of 25 (the limit) and find yourself
    //a more efficient loop if there is one
    for(var i=0; i<json.length; i++){
        console.log(`processing item number ${i+1}`);
        let query = {
            TableName: DYNAMODB_TABLENAME,
            Item: json[i]
        };

        await db.put(query).promise();

        /**
         * Note: If "json" contains other nested objects, you would have to
         *       loop through the json and parse all child objects.
         *       likewise, you would have to convert all children into their
         *       native primitive types because everything would be represented
         *       as a string.
         */
    }
    console.log('\nDone.');
})();