问:
EF4 : horizontal splitting or complex types?
I need your help to implement horizontal table splitting but not for inherited class(es). I need just to "move" some attributes to new entity, separate them. This new entity should have an association (1 <-> 1..0)

But I catch the "...Their primary keys may collide" error. Where is the secret? (OK, I know it now: The secret is "only 1<->1")

But there is still one open question: what to use horizontal classes or derived entities?

I have table Records (with PK RecordID) where there are several attributes with "duplicated information" that means this information can be "accessed" also by using/joining other referenced table (let say Dictionary) and is just "backuped" information from it.

Referred information could differ from "backuped/duplicated" and this have sense in my domain model, so in general I need both, but most of select and update statements do not involve those "duplicated attributes", so I want to support this fact somehow in the conceptual model. Is this the normal desire or the direct way to get "overdesigned" model ?

OK. This is the scheme. On the left what I have, on the right what I want to have.

答:
OK I found the reason for the error.

I've tried to use assocaition with multiplicity 1<->1..0 . This not works with "horizontal table splitting". Only 1<->1 work!

But I still do not decide - what is better: move "duplicated fields" to separate entyty (overdesign?) or just create complex type for them.


来源: stackexchange

问:
how do i fix this, x not in list
this is the code for this sub routine

```<code>def elimination():
    global name
    global contestants
    global tempContestants
    global lipsync_songs
    global bottom_two
    bottom = tempContestants[0:len(tempContestants)-1]
    tempContestants.remove(bottom)
    bottom1 = tempContestants[0:len(tempContestants)-1]
    tempContestants.remove(bottom1)
    bottom_two = [bottom, bottom1]
    print(bottom_two[0], "and", bottom_two[1], "I'm sorry my dears but you are up for elimination")
    lipsync()
    eliminated = bottom_two[random.randint(0,len(bottom_two)-1)]
    bottom_two.remove(eliminated)
    safe = str(bottom_two)
    print("Ladies, I have made my decision")
    print(safe+", shantay you stay!")
    print(eliminated+", sashay away!")
    contestants.remove(eliminated)
    if eliminated == name:
        print("You have been eliminated!")
        quit()
</code>```

and here is the error message

```<code>    tempContestants.remove(bottom)
ValueError: list.remove(x): x not in list
</code>```

what does this mean and how do i fix it?

答:
This reproduces your error:

```<code>In [644]: [1,2,3].remove(4)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-644-181ce8c0fac7> in <module>
----> 1 [1,2,3].remove(4)

ValueError: list.remove(x): x not in list
In [645]: [1,2,3].remove(3)
</code>```

Looks like bottom is a list of elements of array;

```<code>In [689]: [1,2,3].remove([1,2])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-689-9c95562dca44> in <module>
----> 1 [1,2,3].remove([1,2])

ValueError: list.remove(x): x not in list
</code>```

===

```<code>bottom = tempContestants[0:len(tempContestants)-1]
tempContestants.remove(bottom)

In [691]: x = [1,2,3,4]
In [692]: bottom = x[0:len(x)-1]
In [693]: bottom
Out[693]: [1, 2, 3]
</code>```

You could remove the items iteratively:

```<code>In [694]: for i in bottom: x.remove(i)
In [695]: x
Out[695]: [4]
</code>```

or just select the slice that you want to keep:

```<code>In [696]: x = [1,2,3,4]
In [698]: x[-1:]
Out[698]: [4]
</code>```

ContentLicense: CC BY-SA 4.0

Title: how do i fix this, x not in list

Body:
this is the code for this sub routine

def elimination():
    global name
    global contestants
    global tempContestants
    global lipsync_songs
    global bottom_two
    bottom = tempContestants[0:len(tempContestants)-1]
    tempContestants.remove(bottom)
    bottom1 = tempContestants[0:len(tempContestants)-1]
    tempContestants.remove(bottom1)
    bottom_two = [bottom, bottom1]
    print(bottom_two[0], "and", bottom_two[1], "I'm sorry my dears but you are up for elimination")
    lipsync()
    eliminated = bottom_two[random.randint(0,len(bottom_two)-1)]
    bottom_two.remove(eliminated)
    safe = str(bottom_two)
    print("Ladies, I have made my decision")
    print(safe+", shantay you stay!")
    print(eliminated+", sashay away!")
    contestants.remove(eliminated)
    if eliminated == name:
        print("You have been eliminated!")
        quit()

and here is the error message

    tempContestants.remove(bottom)
ValueError: list.remove(x): x not in list

what does this mean and how do i fix it?

Body:
This reproduces your error:

In [644]: [1,2,3].remove(4)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-644-181ce8c0fac7> in <module>
----> 1 [1,2,3].remove(4)

ValueError: list.remove(x): x not in list
In [645]: [1,2,3].remove(3)

Looks like bottom is a list of elements of array;

In [689]: [1,2,3].remove([1,2])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-689-9c95562dca44> in <module>
----> 1 [1,2,3].remove([1,2])

ValueError: list.remove(x): x not in list

===

bottom = tempContestants[0:len(tempContestants)-1]
tempContestants.remove(bottom)

In [691]: x = [1,2,3,4]
In [692]: bottom = x[0:len(x)-1]
In [693]: bottom
Out[693]: [1, 2, 3]

You could remove the items iteratively:

In [694]: for i in bottom: x.remove(i)
In [695]: x
Out[695]: [4]

or just select the slice that you want to keep:

In [696]: x = [1,2,3,4]
In [698]: x[-1:]
Out[698]: [4]


问:
How to build a vector of strings in python flatbuffer?
It appears that the python documentation (also this) for flatbuffer is currently spotty and mixed up with c++ api on occasions. I tried to create a vector of strings in the following manner:

```<code>builder, builder2, builder3 = flatbuffers.Builder(1024), flatbuffers.Builder(1024), flatbuffers.Builder(1024)
Feature.FeatureStart(builder)
Feature.FeatureStartStringValuesVector(builder2, 1)
builder2.PrependSOffsetTRelative(builder3.CreateString('a'.encode()))
Feature.AddStringValues(builder, builder2.EndVector(1))
Feature.FeatureEnd(builder)
</code>```

At the line that has PrependSOffsetTRelative I get an error:

flatbuffers.builder.OffsetArithmeticError: flatbuffers: Offset
  arithmetic error.

I tried replacing builder3 with builder2, or replacing builder2/builder3 with builder, or removing .encode(), they all resulted in various errors.

I checked that the CreateString always returns 8 whereas PrependSOffsetTRelative seems to want only 0 as an input. What am I missing here? Thanks.

Here is my fbs schema file:

```<code>table Feature {
  string_values:[string];
}
root_type Feature;
</code>```

答:
OK. I figured it out. There should not be multiple builders, instead the entire flatbuffer is constructed byte by byte directly in a sequence, from bottom to top, all using the same builder. So the order of calling Start, End etc methods matters a lot. The following works:</p>

```<code>builder = flatbuffers.Builder(1024)
s = builder.CreateString('a')
Feature.FeatureStartStringValuesVector(builder, 1)
builder.PrependSOffsetTRelative(s)
x = builder.EndVector(1)
Feature.FeatureStart(builder)
Feature.FeatureAddStringValues(builder, x)
ret = Feature.FeatureEnd(builder)
</code>```

Body:
It appears that the python documentation (also this) for flatbuffer is currently spotty and mixed up with c++ api on occasions. I tried to create a vector of strings in the following manner:

builder, builder2, builder3 = flatbuffers.Builder(1024), flatbuffers.Builder(1024), flatbuffers.Builder(1024)
Feature.FeatureStart(builder)
Feature.FeatureStartStringValuesVector(builder2, 1)
builder2.PrependSOffsetTRelative(builder3.CreateString('a'.encode()))
Feature.AddStringValues(builder, builder2.EndVector(1))
Feature.FeatureEnd(builder)

At the line that has PrependSOffsetTRelative I get an error:

flatbuffers.builder.OffsetArithmeticError: flatbuffers: Offset
  arithmetic error.

I tried replacing builder3 with builder2, or replacing builder2/builder3 with builder, or removing .encode(), they all resulted in various errors.

I checked that the CreateString always returns 8 whereas PrependSOffsetTRelative seems to want only 0 as an input. What am I missing here? Thanks.

Here is my fbs schema file:

table Feature {
  string_values:[string];
}
root_type Feature;

Body:
OK. I figured it out. There should not be multiple builders, instead the entire flatbuffer is constructed byte by byte directly in a sequence, from bottom to top, all using the same builder. So the order of calling Start, End etc methods matters a lot. The following works:

builder = flatbuffers.Builder(1024)
s = builder.CreateString('a')
Feature.FeatureStartStringValuesVector(builder, 1)
builder.PrependSOffsetTRelative(s)
x = builder.EndVector(1)
Feature.FeatureStart(builder)
Feature.FeatureAddStringValues(builder, x)
ret = Feature.FeatureEnd(builder)


问:
How to display matching description of an object nested in an array?
I have a function, whose purpose is to display specific description of a particular object that is nested within an array. The idea is that once the function (findSettings()) receives a particular array(systemSettings) and some key(tab12) that is in the objects, it should run through the switch statement and provide its matching description.

In other words, if the function's argument is 'tab12', then it should return the description, 'Description for tab12'.

I have tried to find a matching object using the find method, and that works well, although if I try to run the switch statement, it returns an error: 'Obejct is possibly undefined'.

```<code>const systemSettings = [
  {key: 'tab1', value: 'Main Tab'},
  {key: 'tab12', value: 'Tab 12'},
  {key: 'tab13', value: 'Tab 13'},
  {key: 'tab4', value: 'Tab 4'}
]

type sampObj = {
  key: string;
  value: string;
}

let info: string = '';

function findSetting(arr: sampObj[], settingKey: string) {

  const selectedObjs = arr.find(obj => obj.key === settingKey);

  switch(selectedObjs.key) {
    case 'tab1':
      info += 'Description for tab1';
      break;
    case 'tab12':
      info += 'Description for tab12';
      break;
    case 'tab13':
      info += 'Description for tab13';
      break;
    case 'tab4':
      info += 'Description for tab4';
      break;
    default:
      info += 'No description available'
  }

}

findSetting(systemSettings, 'tab12')```

Any assistance would be highly appreciated.
Thanks.
```

答:
const selectedObjs = arr.find(obj => obj.key === settingKey); could return undefined if an object with the specified key is not in the array.

You can check to see if the object is not undefined before executing your switch statement:

```<code>if(selectedObjs) {
   switch(selectedObjs.key) {
       case 'tab1':
          info += 'Description for tab1';
          break;
        case 'tab12':
          info += 'Description for tab12';
          break;
        case 'tab13':
          info += 'Description for tab13';
          break;
        case 'tab4':
          info += 'Description for tab4';
          break;
        default:
          info += 'No description available'
  }
}
else {
   // Handle invalid settingKey case
}
</code>```

Body:
I have a function, whose purpose is to display specific description of a particular object that is nested within an array. The idea is that once the function (findSettings()) receives a particular array(systemSettings) and some key(tab12) that is in the objects, it should run through the switch statement and provide its matching description.

In other words, if the function's argument is 'tab12', then it should return the description, 'Description for tab12'.

I have tried to find a matching object using the find method, and that works well, although if I try to run the switch statement, it returns an error: 'Obejct is possibly undefined'.

const systemSettings = [
  {key: 'tab1', value: 'Main Tab'},
  {key: 'tab12', value: 'Tab 12'},
  {key: 'tab13', value: 'Tab 13'},
  {key: 'tab4', value: 'Tab 4'}
]

type sampObj = {
  key: string;
  value: string;
}

let info: string = '';

function findSetting(arr: sampObj[], settingKey: string) {

  const selectedObjs = arr.find(obj => obj.key === settingKey);

  switch(selectedObjs.key) {
    case 'tab1':
      info += 'Description for tab1';
      break;
    case 'tab12':
      info += 'Description for tab12';
      break;
    case 'tab13':
      info += 'Description for tab13';
      break;
    case 'tab4':
      info += 'Description for tab4';
      break;
    default:
      info += 'No description available'
  }

}

findSetting(systemSettings, 'tab12')```

Any assistance would be highly appreciated.
Thanks.

Body:
const selectedObjs = arr.find(obj => obj.key === settingKey); could return undefined if an object with the specified key is not in the array.

You can check to see if the object is not undefined before executing your switch statement:

if(selectedObjs) {
   switch(selectedObjs.key) {
       case 'tab1':
          info += 'Description for tab1';
          break;
        case 'tab12':
          info += 'Description for tab12';
          break;
        case 'tab13':
          info += 'Description for tab13';
          break;
        case 'tab4':
          info += 'Description for tab4';
          break;
        default:
          info += 'No description available'
  }
}
else {
   // Handle invalid settingKey case
}


问:
android, when read the file from res/raw, context.getAssets().open(fileName), the content read in are corrupted
on Android, using com.google.gson:gson:2.8.5,

when passing a josnString and when the json is large (noticed for example when string length is  669304), it got

```<code>com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException:
Unterminated string at line 2902 column 564904 path $.items.result[10].quoted_status.full_text

</code>```

or different errors:

the json has array of sub json strings, structured like,

```<code>{
      "items": {
        "result": [
          {subJsonString...},
          {subJsonString...},
          ...
        ]
     }
}
</code>```

and the json string is stored in the res/raw/jsonstring.txt, and read in at runtime before give to Gson fro deserialization.

if reduce the sub json elements in the array (i.e. 10 items or less in the array) it works fine, and the individual json elements string all working fine. But when the array has more items it starts to throw.

update: it seems is problem from reading the json string from res/raw
after further look,
the log shows the output json string read from the res/raw/jsonString.txt are corrupted, when there are more items. Here after adding the 11th sub item into the json string array, it shows 000000000... at certain point (the 11th item who encountered issue are just a copy from the 1st item, so the string should be fine)

here is the code how the raw string is read, how it logs it

```<code>val jsonStr = getJsonFromFile(context, "res/raw/jsoninraw.txt")
returnedModel = gson.fromJson<T>(jsonStr, dataClassType)

......

fun getJsonFromFile(context: Context?, fileName: String): String? {
        val json: String
        try {
            val inputStream: InputStream = context.getAssets().open(fileName)
            val size = inputStream.available()
            val buffer = ByteArray(size)
            inputStream.use { it.read(buffer) }
            json = String(buffer)
        } catch (ioException: IOException) {
            ioException.printStackTrace()
            return null
        }
        return json
            .also {
                logString(it)
            }
    }

fun logString(jsonStr: String) {
    val chunkSize = 512
    var i = 0
    while (i < jsonStr.length) {
        Log.e("+++", jsonStr.substring(i, Math.min(jsonStr.length, i + chunkSize)))
        i += chunkSize
    }
}
</code>```

what are the better way to deserialize the json string into model?

答:
Found the problem that the ByteArray has 64k limit, so anything beyond is corrupted.

the updated the getJsonFromFile() works.

```<code>fun getJsonFromFile(context: Context?, fileName: String?): String? {
        val returnString = StringBuilder()
        var inputStream: InputStream? = null
        var isr: InputStreamReader? = null
        var input: BufferedReader? = null
        try {

            inputStream = if (context == null) {
                val cLoader = this.javaClass.classLoader
                cLoader.getResourceAsStream(fileName)
            } else {
                context.getAssets().open(fileName)
            }

          // either #1:
          // returnString.append(inputStream?.readBytes()?.toString(Charsets.UTF_8))

         // or #2:
            inputStream?.let {
                val inputString = inputStream.bufferedReader().use { it.readText() }
                returnString.append(inputString)
            }

// or #3:
//            isr = InputStreamReader(inputStream)
//            input = BufferedReader(isr)
//            var line: String? = ""
//            while (input.readLine().also { line = it } != null) {
//                returnString.append(line)
//            }
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        } finally {
            try {
                isr?.close()
                inputStream?.close()
                input?.close()
            } catch (e2: Exception) {
                e2.message
            }
        }
        return returnString.toString()
    }
</code>```

Body:
on Android, using com.google.gson:gson:2.8.5,

when passing a josnString and when the json is large (noticed for example when string length is  669304), it got

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException:
Unterminated string at line 2902 column 564904 path $.items.result[10].quoted_status.full_text

or different errors:

the json has array of sub json strings, structured like,

{
      "items": {
        "result": [
          {subJsonString...},
          {subJsonString...},
          ...
        ]
     }
}

and the json string is stored in the res/raw/jsonstring.txt, and read in at runtime before give to Gson fro deserialization.

if reduce the sub json elements in the array (i.e. 10 items or less in the array) it works fine, and the individual json elements string all working fine. But when the array has more items it starts to throw.

update: it seems is problem from reading the json string from res/raw
after further look,
the log shows the output json string read from the res/raw/jsonString.txt are corrupted, when there are more items. Here after adding the 11th sub item into the json string array, it shows 000000000... at certain point (the 11th item who encountered issue are just a copy from the 1st item, so the string should be fine)

here is the code how the raw string is read, how it logs it

val jsonStr = getJsonFromFile(context, "res/raw/jsoninraw.txt")
returnedModel = gson.fromJson<T>(jsonStr, dataClassType)

......

fun getJsonFromFile(context: Context?, fileName: String): String? {
        val json: String
        try {
            val inputStream: InputStream = context.getAssets().open(fileName)
            val size = inputStream.available()
            val buffer = ByteArray(size)
            inputStream.use { it.read(buffer) }
            json = String(buffer)
        } catch (ioException: IOException) {
            ioException.printStackTrace()
            return null
        }
        return json
            .also {
                logString(it)
            }
    }

fun logString(jsonStr: String) {
    val chunkSize = 512
    var i = 0
    while (i < jsonStr.length) {
        Log.e("+++", jsonStr.substring(i, Math.min(jsonStr.length, i + chunkSize)))
        i += chunkSize
    }
}

what are the better way to deserialize the json string into model?

Body:
Found the problem that the ByteArray has 64k limit, so anything beyond is corrupted.

the updated the getJsonFromFile() works.

fun getJsonFromFile(context: Context?, fileName: String?): String? {
        val returnString = StringBuilder()
        var inputStream: InputStream? = null
        var isr: InputStreamReader? = null
        var input: BufferedReader? = null
        try {

            inputStream = if (context == null) {
                val cLoader = this.javaClass.classLoader
                cLoader.getResourceAsStream(fileName)
            } else {
                context.getAssets().open(fileName)
            }

          // either #1:
          // returnString.append(inputStream?.readBytes()?.toString(Charsets.UTF_8))

         // or #2:
            inputStream?.let {
                val inputString = inputStream.bufferedReader().use { it.readText() }
                returnString.append(inputString)
            }

// or #3:
//            isr = InputStreamReader(inputStream)
//            input = BufferedReader(isr)
//            var line: String? = ""
//            while (input.readLine().also { line = it } != null) {
//                returnString.append(line)
//            }
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        } finally {
            try {
                isr?.close()
                inputStream?.close()
                input?.close()
            } catch (e2: Exception) {
                e2.message
            }
        }
        return returnString.toString()
    }


问:
Is it possible to create PHP extensions in Haskell?
Is it possible to create PHP extensions with Haskell?

Usually PHP extensions are written using C. Is using Haskell FFI to provide functionality for a stub C extension possible (or even a good idea)?

What are the caveats to such an approach? Does Zend perform some magic in the background that would disrupt such a scheme?

答: Yes, its possible. Just make sure you wrap everything and translate arguments between php -> c -> haskell and the way back correctly.</p>

ContentLicense: CC BY-SA 3.0


问:
VueJS - How to check an array on matching values?
I'm working on a couponcode VueJS app, in which I want to check an array with different discountcodes on matching values. Below I have an array with two discountcodes. If the button is clicked, I want to check the array for any matches. I am not sure what would be the best solution for this..

```<code><template>
    <div class="container">

        <input placeholder='type discount' v-model="discountInput">
        <button @click="checkDiscount">check for discount</button>

        <span class="alert" v-if="discountValid">
            Code juist
        </span>

        <span class="alert" v-if="discountInvalid">
            Code onjuist
        </span>

    </div>
</template>

<script>

  export default {

    props: {

    },

    data: () => {
        return {
            discountInput: '',
            discountValid: false,
            discountInvalid: false,
            discountCodes: [
                { code: 'discount-code-1', message: '10% discount' },
                { code: 'discount-code-2', message: '5 dollar discount' }
            ]

        }
    },
    components: {

    },
    methods: {

        checkDiscount() {
            if (this.discountInput === this.discountCode) {
                return true;
            } else {
                return false;
            }
        }

    },
    watch: {

    }
}
</script>
</code>```

答:
A find should work.

```<code>  checkDiscount() {
    if (this.discountCodes.find(x => x.code === this.discountInput)) {
      return true;
    } else {
      return false;
    }
  }
</code>```

or as comments pointed out could be reduced to:

```<code>  checkDiscount() {
    return !!this.discountCodes.find(x => x.code === this.discountInput);
  }

</code>```

Body:
I'm working on a couponcode VueJS app, in which I want to check an array with different discountcodes on matching values. Below I have an array with two discountcodes. If the button is clicked, I want to check the array for any matches. I am not sure what would be the best solution for this..

<template>

        <input placeholder='type discount' v-model="discountInput">
        <button @click="checkDiscount">check for discount</button>

            Code juist

            Code onjuist

</template>

Body:
A find should work.

  checkDiscount() {
    if (this.discountCodes.find(x => x.code === this.discountInput)) {
      return true;
    } else {
      return false;
    }
  }

or as comments pointed out could be reduced to:

  checkDiscount() {
    return !!this.discountCodes.find(x => x.code === this.discountInput);
  }


问:
AWS : how to archive files from S3 to Glacier using only command line
I can't find a command example for archiving a set of files from a given prefix in  S3 into a given vault in Glacier using ONLY COMMAND LINE, i.e. no Lifecycles, no python+boto. Thanks.

This doc has a lot of examples but none fit my request:
https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html

答:
You're looking for this:

https://aws.amazon.com/premiumsupport/knowledge-center/restore-s3-object-glacier-storage-class/

```<code>aws s3 cp s3://bucketname/key/file s3://bucketname/key/file --storage-class GLACIER
</code>```

optionally use --recursive instead of a specific file name.

Body:
You're looking for this:

https://aws.amazon.com/premiumsupport/knowledge-center/restore-s3-object-glacier-storage-class/

aws s3 cp s3://bucketname/key/file s3://bucketname/key/file --storage-class GLACIER

optionally use --recursive instead of a specific file name.


问:
Uncaught TypeError: windowWidth is not a function
I keep getting the error: Uncaught TypeError: windowWidth is not a function - how do i fix, please see below code - i trying to screate about us page that is responsive with two images?</p>

```<code>import React, { useState, useEffect } from 'react';
import classes from './styles.module.scss';
import chair from './chair.png';
import chairmob from './chairmob.png';

const About = () => {
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  const imageUrl = windowWidth() >= 600 ? chair : chairmob;

  const handleWindowResize = () => {
    setWindowWidth(window.innerWidth);
  };

  useEffect(() => {
    window.addEventListener('resize', handleWindowResize);

    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  });

  return (
    // <div className={classes.About}>
    <div className="About" style={{ backgroundImage: `url(${imageUrl})` }}>
      <div className="About-content">
        <h1>oh hello</h1>
        <p>
          We're Homewa,<br></br> the first property <br></br>
          search platform that <br></br>actually puts the <br></br>you first.{' '}
        </p>
      </div>
    </div>
    // </div>
  );
};

export default About;
</code>```

答:
You got a typo: windowWidth is not a function:

```<code>//                not windowWidth()
const imageUrl = windowWidth >= 600 ? chair : chairmob;
</code>```

Also, you should set the event listener only on a mount instead on every render as it is currently set:

```<code>useEffect(() => {
  const handleWindowResize = () => {
    setWindowWidth(window.innerWidth);
  };

  window.addEventListener('resize', handleWindowResize);

  return () => {
    window.removeEventListener('resize', handleWindowResize);
  };
}, []);
</code>```

Body:
I keep getting the error: Uncaught TypeError: windowWidth is not a function - how do i fix, please see below code - i trying to screate about us page that is responsive with two images?

import React, { useState, useEffect } from 'react';
import classes from './styles.module.scss';
import chair from './chair.png';
import chairmob from './chairmob.png';

const About = () => {
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  const imageUrl = windowWidth() >= 600 ? chair : chairmob;

  const handleWindowResize = () => {
    setWindowWidth(window.innerWidth);
  };

  useEffect(() => {
    window.addEventListener('resize', handleWindowResize);

    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  });

  return (
    //

    <div className="About" style={{ backgroundImage: `url(${imageUrl})` }}>

oh hello

          We're Homewa,

 the first property

          search platform that

actually puts the

you first.{' '}

    //

  );
};

export default About;

Body:
You got a typo: windowWidth is not a function:

//                not windowWidth()
const imageUrl = windowWidth >= 600 ? chair : chairmob;

Also, you should set the event listener only on a mount instead on every render as it is currently set:

useEffect(() => {
  const handleWindowResize = () => {
    setWindowWidth(window.innerWidth);
  };

  window.addEventListener('resize', handleWindowResize);

  return () => {
    window.removeEventListener('resize', handleWindowResize);
  };
}, []);


问:
Dereference Operator Before an Array Element?
What does the notation in something like int y = *x[0] do, i.e. when you have a dereference operator right before an array element?

答:
*expr is like expr[0] with the [0] at the very end of expr.
[subscript] binds tighter than unary *.

That makes *x[1] equivalent to x[1][0], and if it evaluates to an int,
then x could have been either an array of pointers or a two-dimensional int array.

Example:

```<code>#include <stdio.h>
int main()
{
    {
        //two dimensional int-array
        int x[2][2]={
            {1,2},
            {3,4},
        };
        printf("%d\n", *x[1]); //3
        printf("%d\n", x[1][0 /*the star*/]); //3
    }
    {
        //array of pointers to int
        int *x[2] = { &(int){1}, &(int){2} };
        printf("%d\n", *x[1]); //2
        printf("%d\n", x[1][0 /*the star*/]); //2
    }

}
</code>```

Body:
*expr is like expr[0] with the [0] at the very end of expr.
[subscript] binds tighter than unary *.

That makes *x[1] equivalent to x[1][0], and if it evaluates to an int,
then x could have been either an array of pointers or a two-dimensional int array.

Example:

#include <stdio.h>
int main()
{
    {
        //two dimensional int-array
        int x[2][2]={
            {1,2},
            {3,4},
        };
        printf("%d\n", *x[1]); //3
        printf("%d\n", x[1][0 /*the star*/]); //3
    }
    {
        //array of pointers to int
        int *x[2] = { &(int){1}, &(int){2} };
        printf("%d\n", *x[1]); //2
        printf("%d\n", x[1][0 /*the star*/]); //2
    }

}


问:
How can I implement joi-password-complexity in Joi validation?
I want to enforce password complexity by using the joi-password-complexity package when users register.

https://github.com/kamronbatman/joi-password-complexity

I tried but I got the following error:

(node:14872) UnhandledPromiseRejectionWarning: AssertionError
  [ERR_ASSERTION]: Invalid schema content:
  (password.$_root.alternatives)

This is the code I'm using:

```<code>const mongoose = require("mongoose");
const Joi = require("joi");
const passwordComplexity = require("joi-password-complexity");

const complexityOptions = {
  min: 5,
  max: 250,
  lowerCase: 1,
  upperCase: 1,
  numeric: 1,
  symbol: 1,
  requirementCount: 2,
};

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    minlenght: 1,
    maxlength: 55,
    required: true
  },
  email: {
    type: String,
    minlength: 5,
    maxlength: 255,
    unique: true,
    required: true
  },
  password: {
    type: String,
    minlength: 5,
    maxlength: 1024,
    required: true
  }
})

const User = mongoose.model("User", userSchema);

function validateUser(user) {
  const schema = {
    name: Joi.string().min(1).max(55).required(),
    email: Joi.string().min(5).max(255).required().email(),
    password: passwordComplexity(complexityOptions) // This is not working
  }
  return Joi.validate(user, schema);
}

exports.User = User;
exports.validate = validateUser;
</code>```

I also tried to follow this example: https://forum.codewithmosh.com/d/215-joi-password-complexity-problem but it seems outdated since the "new" keyword will throw another error (not a constructor).

Any help is appreciated!

答:
Here is how i solved the issue:
if You are using joi@14.3.1 or older then install joi-password-complexity@2.0.1 then try this code:

```<code>User.js model

const mongoose = require("mongoose");
const Joi = require("joi");
const PasswordComplexity = require("joi-password-complexity");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

const User = mongoose.model("User", userSchema);

function validateUser(user) {
  const schema = {
    name: Joi.string()
      .min(3)
      .max(50)
      .required(),
    email: Joi.string()
      .email()
      .max(255)
      .required(),
    password:  new PasswordComplexity({
    min: 8,
    max: 25,
    lowerCase: 1,
    upperCase: 1,
    numeric: 1,
    symbol: 1,
    requirementCount: 4
  });
  };
  return Joi.validate(user, schema);
}

module.exports.validate = validateUser;
module.exports.User = User;
</code>```

This will validate password complexity but for making password REQUIRED you have to validate it in your route...

```<code>Users.js route

const _ = require("lodash");
const express = require("express");
const { User, validate } = require("../models/user");

const router = express.Router();

//POST
router.post("/", async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error.details[0].message);
  //
  if (!req.body.password) return res.status(400).send("Password is required..");

  let user = await User.findOne({ email: req.body.email });
  if (user) return res.status(400).send("User already registered..");

  user = new User(_.pick(req.body, ["name", "email", "password"]));
  await user.save();
  res.send(_.pick(user, ["_id", "name", "email"]));
});

module.exports = router;
</code>```

Body:
I want to enforce password complexity by using the joi-password-complexity package when users register.

https://github.com/kamronbatman/joi-password-complexity

I tried but I got the following error:

(node:14872) UnhandledPromiseRejectionWarning: AssertionError
  [ERR_ASSERTION]: Invalid schema content:
  (password.$_root.alternatives)

This is the code I'm using:

const mongoose = require("mongoose");
const Joi = require("joi");
const passwordComplexity = require("joi-password-complexity");

const complexityOptions = {
  min: 5,
  max: 250,
  lowerCase: 1,
  upperCase: 1,
  numeric: 1,
  symbol: 1,
  requirementCount: 2,
};

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    minlenght: 1,
    maxlength: 55,
    required: true
  },
  email: {
    type: String,
    minlength: 5,
    maxlength: 255,
    unique: true,
    required: true
  },
  password: {
    type: String,
    minlength: 5,
    maxlength: 1024,
    required: true
  }
})

const User = mongoose.model("User", userSchema);

function validateUser(user) {
  const schema = {
    name: Joi.string().min(1).max(55).required(),
    email: Joi.string().min(5).max(255).required().email(),
    password: passwordComplexity(complexityOptions) // This is not working
  }
  return Joi.validate(user, schema);
}

exports.User = User;
exports.validate = validateUser;

I also tried to follow this example: https://forum.codewithmosh.com/d/215-joi-password-complexity-problem but it seems outdated since the "new" keyword will throw another error (not a constructor).

Any help is appreciated!

Body:
Here is how i solved the issue:
if You are using joi@14.3.1 or older then install joi-password-complexity@2.0.1 then try this code:

User.js model

const mongoose = require("mongoose");
const Joi = require("joi");
const PasswordComplexity = require("joi-password-complexity");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

const User = mongoose.model("User", userSchema);

function validateUser(user) {
  const schema = {
    name: Joi.string()
      .min(3)
      .max(50)
      .required(),
    email: Joi.string()
      .email()
      .max(255)
      .required(),
    password:  new PasswordComplexity({
    min: 8,
    max: 25,
    lowerCase: 1,
    upperCase: 1,
    numeric: 1,
    symbol: 1,
    requirementCount: 4
  });
  };
  return Joi.validate(user, schema);
}

module.exports.validate = validateUser;
module.exports.User = User;

This will validate password complexity but for making password REQUIRED you have to validate it in your route...

Users.js route

const _ = require("lodash");
const express = require("express");
const { User, validate } = require("../models/user");

const router = express.Router();

//POST
router.post("/", async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error.details[0].message);
  //
  if (!req.body.password) return res.status(400).send("Password is required..");

  let user = await User.findOne({ email: req.body.email });
  if (user) return res.status(400).send("User already registered..");

  user = new User(_.pick(req.body, ["name", "email", "password"]));
  await user.save();
  res.send(_.pick(user, ["_id", "name", "email"]));
});

module.exports = router;


问:
A problem with trying to import "from flask_ask import..."?
On repl.it, I'm trying to import certain things from a specific library however, it brings back an error "No module named 'flask_ask' ". I've posted this before and the solution worked a little bit but caused more errors. Any help would be much appreciated.

```<code>from array import *
from flask import Flask
from flask_ask import Ask, statement, question, session
import json
</code>```

If you would like the rest of the code, I will post it in the comment section.

答:
Just to make sure have you ran pip install flask-ask ? Are you working on a virtual environment by any chance? Please post the rest of the code.

It looks like you can install it by doing this

Body:
On repl.it, I'm trying to import certain things from a specific library however, it brings back an error "No module named 'flask_ask' ". I've posted this before and the solution worked a little bit but caused more errors. Any help would be much appreciated.

from array import *
from flask import Flask
from flask_ask import Ask, statement, question, session
import json

If you would like the rest of the code, I will post it in the comment section.


问:
React navigation crashing when clicking anywhere on screen
Android Emulator Environment: Pixel_3_XL_API_29

Whenever I use any react-navigation component such as stack or drawer in my expo-based app, and click anywhere on the screen with a mouse, it crashes.
If I remove

```<code><AppContainer />
</code>```

in the below example, and replace it with

```<code><LoginScreen/>
</code>```

, everything works fine. Note: LoginScreen is just a blank screen with no logic of its own.

I can see the below error in adb logs

```<code>02-13 15:52:32.562   751   751 E MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
02-13 15:52:32.562   751   751 E MessageQueue-JNI: java.lang.IllegalStateException: Already prepared or hasn't been reset
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler.prepare(GestureHandler.java:7)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.recordHandlerIfNotPresent(GestureHandlerOrchestrator.java:8)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.recordViewHandlersForPointer(GestureHandlerOrchestrator.java:5)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.traverseWithPointerEvents(GestureHandlerOrchestrator.java:12)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.extractGestureHandlers(GestureHandlerOrchestrator.java:5)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.onTouchEvent(GestureHandlerOrchestrator.java:4)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerRootHelper.dispatchTouchEvent(RNGestureHandlerRootHelper.java:2)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerRootView.dispatchTouchEvent(RNGestureHandlerRootView.java:1)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
</code>```

package.json

```<code>{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start -c",
    "doctor": "expo doctor",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-native-community/masked-view": "0.1.5",
    "react-navigation-stack": "2.1.1",
    "react-navigation": "4.1.1",
    "axios": "0.19.2",
    "debounce": "1.2.0",
    "expo": "~36.0.0",
    "expo-secure-store": "~8.0.0",
    "native-base": "^2.13.8",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "^0.61.5",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-reanimated": "~1.4.0",
    "react-native-safe-area-context": "0.6.0",
    "react-native-screens": "2.0.0-alpha.12",
    "uuid": "3.4.0"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.0.0",
    "@babel/core": "^7.0.0"
  },
  "private": true
}
</code>```

App.js

```<code>import 'react-native-gesture-handler';
import React from "react";
import { AppLoading } from "expo";
import * as Font from "expo-font";
import { Ionicons } from "@expo/vector-icons";
import MainMenu from './MainMenu'
import LoginScreen from './LoginScreen'
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

 const navi = createStackNavigator({
 Login: {
    screen: LoginScreen,
  },
  Menu: {
    screen: MainMenu,
  }
}, {
    initialRouteName: 'Login',
  });

const AppContainer = createAppContainer(navi);

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isReady: false
    };
  }
  async componentDidMount() {
    await Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      Ionicons: require("native-base/Fonts/Ionicons.ttf")
    });
    this.setState({ isReady: true });
  }
  render() {
    if (!this.state.isReady) {
      return <AppLoading />;
    }
    return (<AppContainer />);
  }
}
</code>```

Login Screen

```<code>import React from "react";
import { Container, Header, Body, Title, List, ListItem, Content, Text } from "native-base";
export default class MainMenu extends React.Component {
  constructor(props)
  {
    super(props);
  }
  render() {
    return (
      <Container>
              <Header>
          <Body>
            <Title>Test</Title>
          </Body>
        </Header>
       <Content>
        </Content>
      </Container>
  );
  }
}
</code>```

Note: I get the same error with react-navigation 4 and 5

答:
I had the same error. The problem is somewhere in react-native-gesture-handler package and as I see, it is not fixed yet.

Downgrade to version 1.4.0 or try this solution:

import 'react-native-gesture-handler';
...
if (Platform.OS === 'android') {
  const { UIManager } = NativeModules;
  if (UIManager) {
    // Add gesture specific events to genericDirectEventTypes object
    // exported from UIManager native module.
    // Once new event types are registered with react it is possible
    // to dispatch these events to all kind of native views.
    UIManager.genericDirectEventTypes = {
      ...UIManager.genericDirectEventTypes,
      onGestureHandlerEvent: { registrationName: 'onGestureHandlerEvent' },
      onGestureHandlerStateChange: {
        registrationName: 'onGestureHandlerStateChange',
      },
    };
  }
}
```

Body:
Android Emulator Environment: Pixel_3_XL_API_29

Whenever I use any react-navigation component such as stack or drawer in my expo-based app, and click anywhere on the screen with a mouse, it crashes.
If I remove

<AppContainer />

in the below example, and replace it with

<LoginScreen/>

, everything works fine. Note: LoginScreen is just a blank screen with no logic of its own.

I can see the below error in adb logs

02-13 15:52:32.562   751   751 E MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
02-13 15:52:32.562   751   751 E MessageQueue-JNI: java.lang.IllegalStateException: Already prepared or hasn't been reset
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler.prepare(GestureHandler.java:7)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.recordHandlerIfNotPresent(GestureHandlerOrchestrator.java:8)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.recordViewHandlersForPointer(GestureHandlerOrchestrator.java:5)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.traverseWithPointerEvents(GestureHandlerOrchestrator.java:12)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.extractGestureHandlers(GestureHandlerOrchestrator.java:5)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator.onTouchEvent(GestureHandlerOrchestrator.java:4)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerRootHelper.dispatchTouchEvent(RNGestureHandlerRootHelper.java:2)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at abi36_0_0.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerRootView.dispatchTouchEvent(RNGestureHandlerRootView.java:1)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
02-13 15:52:32.562   751   751 E MessageQueue-JNI:      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start -c",
    "doctor": "expo doctor",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-native-community/masked-view": "0.1.5",
    "react-navigation-stack": "2.1.1",
    "react-navigation": "4.1.1",
    "axios": "0.19.2",
    "debounce": "1.2.0",
    "expo": "~36.0.0",
    "expo-secure-store": "~8.0.0",
    "native-base": "^2.13.8",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "^0.61.5",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-reanimated": "~1.4.0",
    "react-native-safe-area-context": "0.6.0",
    "react-native-screens": "2.0.0-alpha.12",
    "uuid": "3.4.0"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.0.0",
    "@babel/core": "^7.0.0"
  },
  "private": true
}

App.js

import 'react-native-gesture-handler';
import React from "react";
import { AppLoading } from "expo";
import * as Font from "expo-font";
import { Ionicons } from "@expo/vector-icons";
import MainMenu from './MainMenu'
import LoginScreen from './LoginScreen'
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

 const navi = createStackNavigator({
 Login: {
    screen: LoginScreen,
  },
  Menu: {
    screen: MainMenu,
  }
}, {
    initialRouteName: 'Login',
  });

const AppContainer = createAppContainer(navi);

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isReady: false
    };
  }
  async componentDidMount() {
    await Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      Ionicons: require("native-base/Fonts/Ionicons.ttf")
    });
    this.setState({ isReady: true });
  }
  render() {
    if (!this.state.isReady) {
      return <AppLoading />;
    }
    return (<AppContainer />);
  }
}

Login Screen

import React from "react";
import { Container, Header, Body, Title, List, ListItem, Content, Text } from "native-base";
export default class MainMenu extends React.Component {
  constructor(props)
  {
    super(props);
  }
  render() {
    return (
      <Container>

            <Title>Test</Title>

       <Content>
        </Content>
      </Container>
  );
  }
}

Note: I get the same error with react-navigation 4 and 5


问:
Count number of ways to reach a score
I am working on a task where I have a number now I want to know how many ways to reach to this number using 2,3,6 using additions and I can use a number as many number of times as possible.

1st Example:

```<code>Given number is 6
There are 3 ways to reach to this number:
2 +2 + 2 = 2*3
3 + 3 = 3*2
6
</code>```

2nd Example:

```<code>Given number is 5
There are 2 ways to reach to this number:
2+3
3+2 (order matters here)
</code>```

I have come up with below code with help of this link:

```<code>static int count(int n) {
    // table[i] will store count of solutions for
    // value i.
    int table[] = new int[n + 1], i;

    // Base case (If given value is 0)
    table[0] = 1;

    // One by one consider given 3
    // moves and update the table[]
    // values after the index greater
    // than or equal to the value of
    // the picked move
    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];

    return table[n];
}
</code>```

This code is working only for 1st example, but not working for 2nd example because the program is returning 1 instead of 2.

How to fix this issue?

答:
The problem is that you miss combinations such as 2+6+2 (where a lesser number comes after a greater number), because you run (for example) table[10] += table[10-2] before  table[8] += table[8-6], so the former doesn't take into account the result of the latter.

To fix that, change this:

```<code>    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];
</code>```

to this:

```<code>    for (i = 1; i <= n; i++) {
        if (i >= 2) {
            table[i] += table[i - 2];
        }
        if (i >= 3) {
            table[i] += table[i - 3];
        }
        if (i >= 6) {
            table[i] += table[i - 6];
        }
    }
</code>```

so that you handle e.g. table[10] only after you've fully processed e.g. table[8].

Title: Count number of ways to reach a score

Body:
I am working on a task where I have a number now I want to know how many ways to reach to this number using 2,3,6 using additions and I can use a number as many number of times as possible.

1st Example:

Given number is 6
There are 3 ways to reach to this number:
2 +2 + 2 = 2*3
3 + 3 = 3*2
6

2nd Example:

Given number is 5
There are 2 ways to reach to this number:
2+3
3+2 (order matters here)

I have come up with below code with help of this link:

static int count(int n) {
    // table[i] will store count of solutions for
    // value i.
    int table[] = new int[n + 1], i;

    // Base case (If given value is 0)
    table[0] = 1;

    // One by one consider given 3
    // moves and update the table[]
    // values after the index greater
    // than or equal to the value of
    // the picked move
    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];

    return table[n];
}

This code is working only for 1st example, but not working for 2nd example because the program is returning 1 instead of 2.

How to fix this issue?

Body:
The problem is that you miss combinations such as 2+6+2 (where a lesser number comes after a greater number), because you run (for example) table[10] += table[10-2] before  table[8] += table[8-6], so the former doesn't take into account the result of the latter.

To fix that, change this:

    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];

to this:

    for (i = 1; i <= n; i++) {
        if (i >= 2) {
            table[i] += table[i - 2];
        }
        if (i >= 3) {
            table[i] += table[i - 3];
        }
        if (i >= 6) {
            table[i] += table[i - 6];
        }
    }

so that you handle e.g. table[10] only after you've fully processed e.g. table[8].


问:
send current date to Api using typescript in format (DateTime)
how can I send current date to API using typescript in a specific format (DateTime)
when I send date to API, it's sent in this format so I got the error.

my ts code:

```<code>date: Date;
constructor( private dataStorageService: DataStorageService) {
    this.date = new Date();
}
onSubmit(Message , form : FormGroup){
    let newMsg = {
        username: Message.username,
        header: Message.header,
        content: Message.content,
        file: Message.file
    }
  this.dataStorageService.postMessage(newMsg, this.Id , this.date).subscribe(data => {
      console.log('done');
      console.log(this.date);
      }, error => {
          console.error("Error saving jobs!");
      })
}
</code>```

http://api.azharcouncil.com/api/notification/PostNotification?user_id=15&Header=hj&Content=hjh&File_Path=null&date=Wed%20Nov%2015%202017%2010:44:56%20GMT+0200%20(Egypt%20Standard%20Time)

So my request is invalid because of the date format...

答:
we can achieve this by using moment.js

Sample coding

```<code>import * as moment from 'moment-timezone'

export enum dateFormats {
    'DMY'= 'DD/MM/YYYY',
    'MDY'= 'MM/DD/YYYY'
}

// converts datestring to date
export const ToDate = (dateString: string, format: string) => new Date(moment(dateString, format))

// converts date to datestring
export const ToDateString = (date: Date, format: string) => moment(date).format(format)
</code>```

Usage (in component)

```<code>const dateValue = new Date() // Date = Tue Feb 19 2020 12:05:22 GMT+0530 (IST)
const dateString = ToDateString(dateValue, dateFormats.DMY) // dateString = '19/02/2020'
</code>```

Body:
how can I send current date to API using typescript in a specific format (DateTime)
when I send date to API, it's sent in this format so I got the error.

my ts code:

date: Date;
constructor( private dataStorageService: DataStorageService) {
    this.date = new Date();
}
onSubmit(Message , form : FormGroup){
    let newMsg = {
        username: Message.username,
        header: Message.header,
        content: Message.content,
        file: Message.file
    }
  this.dataStorageService.postMessage(newMsg, this.Id , this.date).subscribe(data => {
      console.log('done');
      console.log(this.date);
      }, error => {
          console.error("Error saving jobs!");
      })
}

http://api.azharcouncil.com/api/notification/PostNotification?user_id=15&Header=hj&Content=hjh&File_Path=null&date=Wed%20Nov%2015%202017%2010:44:56%20GMT+0200%20(Egypt%20Standard%20Time)

So my request is invalid because of the date format...

Body:
we can achieve this by using moment.js

Sample coding

import * as moment from 'moment-timezone'

export enum dateFormats {
    'DMY'= 'DD/MM/YYYY',
    'MDY'= 'MM/DD/YYYY'
}

// converts datestring to date
export const ToDate = (dateString: string, format: string) => new Date(moment(dateString, format))

// converts date to datestring
export const ToDateString = (date: Date, format: string) => moment(date).format(format)

Usage (in component)

const dateValue = new Date() // Date = Tue Feb 19 2020 12:05:22 GMT+0530 (IST)
const dateString = ToDateString(dateValue, dateFormats.DMY) // dateString = '19/02/2020'


问:
What does "{} = {}" do when used in Angular constructor?
I found this snippet of code in Angular dynamic forms tutorial and I'm not sure what {} = {} in the constructor does.

Full snippet:

```<code>export class QuestionBase<T> {
  value: T;
  key: string;
  label: string;
  required: boolean;
  order: number;
  controlType: string;
  type: string;
  options: {key: string, value: string}[];

  constructor(options: {
      value?: T,
      key?: string,
      label?: string,
      required?: boolean,
      order?: number,
      controlType?: string,
      type?: string
    } = {}) {
    this.value = options.value;
    this.key = options.key || '';
    this.label = options.label || '';
    this.required = !!options.required;
    this.order = options.order === undefined ? 1 : options.order;
    this.controlType = options.controlType || '';
    this.type = options.type || '';
  }
}
</code>```

Thanks in advance!

答:
Variable name:

```<code>options:
</code>```

Type signature (note that all properties are optional):

```<code>{
  value?: T,
  key?: string,
  label?: string,
  required?: boolean,
  order?: number,
  controlType?: string,
  type?: string
}
</code>```

Default value (object with no properties):

```<code>= {}
</code>```

Body:
I found this snippet of code in Angular dynamic forms tutorial and I'm not sure what {} = {} in the constructor does.

Full snippet:

export class QuestionBase<T> {
  value: T;
  key: string;
  label: string;
  required: boolean;
  order: number;
  controlType: string;
  type: string;
  options: {key: string, value: string}[];

  constructor(options: {
      value?: T,
      key?: string,
      label?: string,
      required?: boolean,
      order?: number,
      controlType?: string,
      type?: string
    } = {}) {
    this.value = options.value;
    this.key = options.key || '';
    this.label = options.label || '';
    this.required = !!options.required;
    this.order = options.order === undefined ? 1 : options.order;
    this.controlType = options.controlType || '';
    this.type = options.type || '';
  }
}

Thanks in advance!

Body:
Variable name:

options:

Type signature (note that all properties are optional):

{
  value?: T,
  key?: string,
  label?: string,
  required?: boolean,
  order?: number,
  controlType?: string,
  type?: string
}

Default value (object with no properties):

= {}


答:
Try to use array some  method as follows :

```<code> checkDiscount() {

            return this.discountCodes.some(dis => dis.code === this.discountInput)

        }
</code>```

Title: VueJS - How to check an array on matching values?

Body:
Try to use array some  method as follows :

 checkDiscount() {

            return this.discountCodes.some(dis => dis.code === this.discountInput)

        }


问:
Oracle comparing day to second interval to an integer
I am wondering what is going on under the hood of oracle when I am trying to compare day to second interval with a integer.

Example below.

```<code>SET SERVEROUTPUT ON;
DECLARE
    v_date1 TIMESTAMP := current_timestamp ;
    v_date2 TIMESTAMP := current_timestamp - 150;
BEGIN
    -- Wrong way. But what is happening here?
    IF v_date1 - v_date2 < 2 THEN
        DBMS_OUTPUT.PUT_LINE('YES - why?');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO');
    END IF;
    -- Correct way
    IF v_date1 < v_date2 + 2 THEN
        DBMS_OUTPUT.PUT_LINE('YES');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO - works as expected');
    END IF;
    -- Another correct way
    IF v_date1 - v_date2 < INTERVAL '2' DAY THEN
        DBMS_OUTPUT.PUT_LINE('YES');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO - works as expected as well');
    END IF;
END;
</code>```

Can somebody explain to me why first IF is evaluated to true?

答:
I guess this is not a bug, but wrong source code.

You should treat intervals as INTERVAL

```<code>DECLARE
    v_date1 TIMESTAMP := CURRENT_TIMESTAMP ;
    v_date2 TIMESTAMP := v_date1 - INTERVAL '150' DAY;
BEGIN
    DBMS_OUTPUT.PUT_LINE(v_date1 - v_date2);
    -- Right way.
    IF v_date1 - v_date2 < INTERVAL '2' DAY THEN
        DBMS_OUTPUT.PUT_LINE('YES - why?');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO');
    END IF;
    -- Right way
    IF v_date1 < v_date2 + INTERVAL '2' DAY THEN
        DBMS_OUTPUT.PUT_LINE('YES');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO - works as expected');
    END IF;
    -- Right correct way
    IF v_date1 - v_date2 < INTERVAL '2' DAY THEN
        DBMS_OUTPUT.PUT_LINE('YES');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO - works as expected as well');
    END IF;
END;

+000000150 00:00:00.000000000
NO
NO - works as expected
NO - works as expected as well
</code>```

Body:
I am wondering what is going on under the hood of oracle when I am trying to compare day to second interval with a integer.

Example below.

SET SERVEROUTPUT ON;
DECLARE
    v_date1 TIMESTAMP := current_timestamp ;
    v_date2 TIMESTAMP := current_timestamp - 150;
BEGIN
    -- Wrong way. But what is happening here?
    IF v_date1 - v_date2 < 2 THEN
        DBMS_OUTPUT.PUT_LINE('YES - why?');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO');
    END IF;
    -- Correct way
    IF v_date1 < v_date2 + 2 THEN
        DBMS_OUTPUT.PUT_LINE('YES');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO - works as expected');
    END IF;
    -- Another correct way
    IF v_date1 - v_date2 < INTERVAL '2' DAY THEN
        DBMS_OUTPUT.PUT_LINE('YES');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO - works as expected as well');
    END IF;
END;

Can somebody explain to me why first IF is evaluated to true?

Body:
I guess this is not a bug, but wrong source code.

You should treat intervals as INTERVAL

DECLARE
    v_date1 TIMESTAMP := CURRENT_TIMESTAMP ;
    v_date2 TIMESTAMP := v_date1 - INTERVAL '150' DAY;
BEGIN
    DBMS_OUTPUT.PUT_LINE(v_date1 - v_date2);
    -- Right way.
    IF v_date1 - v_date2 < INTERVAL '2' DAY THEN
        DBMS_OUTPUT.PUT_LINE('YES - why?');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO');
    END IF;
    -- Right way
    IF v_date1 < v_date2 + INTERVAL '2' DAY THEN
        DBMS_OUTPUT.PUT_LINE('YES');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO - works as expected');
    END IF;
    -- Right correct way
    IF v_date1 - v_date2 < INTERVAL '2' DAY THEN
        DBMS_OUTPUT.PUT_LINE('YES');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NO - works as expected as well');
    END IF;
END;

+000000150 00:00:00.000000000
NO
NO - works as expected
NO - works as expected as well


问:
How should I create a linked list with a generic amount of items per node in C
I need to expand a linked list in C that is able to take a generic number of (same type) values.

Here is the generic linked list:

```<code>struct Node {
int item;
struct Node* next;
};

struct List {
    struct Node* head;
    struct Node* tail;
};

struct List SLL_new() {
    /* construct an empty list */
    struct List list;
    list.head = NULL;
    list.tail = NULL;
    return list;
}
</code>```

I need to modify SLL_new() to take an integer parameter that represents the number of items that will be stored in a single node.

I could do something like:

```<code>struct Node {
int item1;
int item2;
int item3;
int item4;
int item5;
struct Node* next;
};
</code>```

but this probably isn't feasible, as there's no limit on the number of items that can be stored in a node. Is there an easier way to do this?

答:
I need to modify SLL_new() to take an integer parameter that represents the number of items that will be stored in a single node.

So do that. You're not asked how the eventual Node allocation will work yet, you just need

```<code>struct List {
    int node_elements;
    struct Node* head;
    struct Node* tail;
};

struct List SLL_new(int nelem) {
    /* construct an empty list */
    struct List list;
    list.node_elements = nelem;
    list.head = NULL;
    list.tail = NULL;
    return list;
}
</code>```

Once you've done that, the other answer's flexible array is how you'll actually use node_elements every time you allocate a new node in this list.

Body:
I need to expand a linked list in C that is able to take a generic number of (same type) values.

Here is the generic linked list:

struct Node {
int item;
struct Node* next;
};

struct List {
    struct Node* head;
    struct Node* tail;
};

struct List SLL_new() {
    /* construct an empty list */
    struct List list;
    list.head = NULL;
    list.tail = NULL;
    return list;
}

I need to modify SLL_new() to take an integer parameter that represents the number of items that will be stored in a single node.

I could do something like:

struct Node {
int item1;
int item2;
int item3;
int item4;
int item5;
struct Node* next;
};

but this probably isn't feasible, as there's no limit on the number of items that can be stored in a node. Is there an easier way to do this?

Body:
I need to modify SLL_new() to take an integer parameter that represents the number of items that will be stored in a single node.

So do that. You're not asked how the eventual Node allocation will work yet, you just need

struct List {
    int node_elements;
    struct Node* head;
    struct Node* tail;
};

struct List SLL_new(int nelem) {
    /* construct an empty list */
    struct List list;
    list.node_elements = nelem;
    list.head = NULL;
    list.tail = NULL;
    return list;
}

Once you've done that, the other answer's flexible array is how you'll actually use node_elements every time you allocate a new node in this list.


问:
How to handle errors in Express 4 from within the Node.Js app?
I upgraded to Express 4 and have the following problem with error handling.

Before I used to have the code in app.js — after all the possible routes I had

```<code>var routes = require('./routes')
app.use(routes.notfound)
app.use(routes.error)
app.use(routes.badrequest)
</code>```

And then inside the /routes/index.js I had:

```<code>exports.notfound = function(req, res) {
    res.status(404).format({
        html: function() {
            res.render('404')
        },
        json: function() {
            res.send({
                message: 'We did not find what you were looking for :(',
            })
        },
        xml: function() {
            res.write('<error>\n')
            res.write(
                ' <message>We did not find what you were looking for :(</message>\n'
            )
            res.end('</error>\n')
        },
        text: function() {
            res.send('We did not find what you were looking for :(\n')
        },
    })
}
</code>```

Now when I call for 404 elsewhere in the app (not in app.js) using res.send(404) I get the right 404 code response but I don't get to the part where it selects whether it shows html or json or text.

How do I do that?

答:
You need to handle error catching differently, here is one way to do so:

Create a middleware after all of your routes that will catch errors you pass to it, the callback would take in an extra parameter containing details about the error:

```<code>app.use((err, req, res, next) => {
  // Handle the error here
});
</code>```

Whenever you want to render an error, you can use next in your routes to pass it to this middleware, and pass extra information you can use to decide how to handle the error. There is a module called http-errors that can create objects like that for you. Here is an example route:

```<code>const createError = require('http-errors');

app.get('/posts', (req, res, next) => {
  // Logic...
  if(/* some condition */) {
    next(createError(404));
  }
});
</code>```

This will pass the error object created to your error handling middleware, and from there you can choose how to handle it.

To extend this, and to make it work better with asynchronous code, you can wrap your router's callbacks with a function that will make sure exceptions that get thrown are passed over to the error handling middleware, this comes in handy when working with async and await:

```<code>// Wrapper function to forward errors from async scopes
const wrap = fn => (...args) => fn(...args).catch(args[2]);

app.get('/posts', wrap(async (req, res) => {
  // Logic...
  await controller.get('posts'); // Promise rejections will get forwarded to middleware
}));
</code>```

This also lets you just throw the error object instead of calling next.

Body:
I upgraded to Express 4 and have the following problem with error handling.

Before I used to have the code in app.js — after all the possible routes I had

var routes = require('./routes')
app.use(routes.notfound)
app.use(routes.error)
app.use(routes.badrequest)

And then inside the /routes/index.js I had:

exports.notfound = function(req, res) {
    res.status(404).format({
        html: function() {
            res.render('404')
        },
        json: function() {
            res.send({
                message: 'We did not find what you were looking for :(',
            })
        },
        xml: function() {
            res.write('<error>\n')
            res.write(
                ' <message>We did not find what you were looking for :(</message>\n'
            )
            res.end('</error>\n')
        },
        text: function() {
            res.send('We did not find what you were looking for :(\n')
        },
    })
}

Now when I call for 404 elsewhere in the app (not in app.js) using res.send(404) I get the right 404 code response but I don't get to the part where it selects whether it shows html or json or text.

How do I do that?

Body:
You need to handle error catching differently, here is one way to do so:

Create a middleware after all of your routes that will catch errors you pass to it, the callback would take in an extra parameter containing details about the error:

app.use((err, req, res, next) => {
  // Handle the error here
});

Whenever you want to render an error, you can use next in your routes to pass it to this middleware, and pass extra information you can use to decide how to handle the error. There is a module called http-errors that can create objects like that for you. Here is an example route:

const createError = require('http-errors');

app.get('/posts', (req, res, next) => {
  // Logic...
  if(/* some condition */) {
    next(createError(404));
  }
});

This will pass the error object created to your error handling middleware, and from there you can choose how to handle it.

To extend this, and to make it work better with asynchronous code, you can wrap your router's callbacks with a function that will make sure exceptions that get thrown are passed over to the error handling middleware, this comes in handy when working with async and await:

// Wrapper function to forward errors from async scopes
const wrap = fn => (...args) => fn(...args).catch(args[2]);

app.get('/posts', wrap(async (req, res) => {
  // Logic...
  await controller.get('posts'); // Promise rejections will get forwarded to middleware
}));

This also lets you just throw the error object instead of calling next.


问:
Why am I getting a result opposite from what I expected?
I wrote a code to figure out whether a small binary tree t1 is a subtree of t2.
I am supposed to get true as the result but I am getting the opposite.

Here is my code:

```<code>class Node {
    int val;
    Node left, right;
    public Node(int v) {
        val = v;
        left = right = null;
    }
}
public class BT {
    Node root;
    public BT() {
        root = null;
    }
    public boolean containsTree(Node t1, Node t2) {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        getOrderString(t1, s1);
        getOrderString(t2, s2);
        return s1.indexOf(s2.toString()) != -1;
    }
    public void getOrderString(Node t, StringBuilder s) {
        if (t == null) {
            s.append("X");
            return;
        }
        s.append(t.val);
        getOrderString(t.left, s);
        getOrderString(t.right, s);
    }
    public static void main(String[] args) {
        BT bt = new BT();
        bt.root = new Node(10);
        bt.root.left = new Node(12);
        bt.root.right = new Node(15);
        bt.root.left.left = new Node(25);
        bt.root.left.right = new Node(30);
        bt.root.right.left = new Node(36);
        BT bt2 = new BT();
        bt2.root = new Node(10);
        bt2.root.left = new Node(12);
        bt2.root.right = new Node(15);
        bt2.root.left.left = new Node(25);
        System.out.println(bt.containsTree(bt.root, bt2.root));
    }
}
</code>```

Could anyone explain to me why i am getting false?

答:
Your API for constructing the tree is hard to read. If you defined a constructor:

```<code>public Node(int v, Node left, Node right)
</code>```

Then you could declare your trees as:

```<code>bt.root = new Node(
    10,
    new Node(
        12,
        new Node(25, null, null),
        new Node(30, null, null)),
    new Node(
        25,
        new Node(36, null, null),
        null));

bt2.root = new Node(
    10,
    new Node(
        12,
        new Node(25, null, null),
        null)),
    new Node(15, null, null));
</code>```

Like this, I think it is easy to see that the second isn't a subtree of the first:

the node with value 10 in the first has a right node with value 25; in the second it has a right value 15;

the node with value 12 in the first has a non-null right value, whereas it is null in the second.

Body:
I wrote a code to figure out whether a small binary tree t1 is a subtree of t2.
I am supposed to get true as the result but I am getting the opposite.

Here is my code:

class Node {
    int val;
    Node left, right;
    public Node(int v) {
        val = v;
        left = right = null;
    }
}
public class BT {
    Node root;
    public BT() {
        root = null;
    }
    public boolean containsTree(Node t1, Node t2) {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        getOrderString(t1, s1);
        getOrderString(t2, s2);
        return s1.indexOf(s2.toString()) != -1;
    }
    public void getOrderString(Node t, StringBuilder s) {
        if (t == null) {
            s.append("X");
            return;
        }
        s.append(t.val);
        getOrderString(t.left, s);
        getOrderString(t.right, s);
    }
    public static void main(String[] args) {
        BT bt = new BT();
        bt.root = new Node(10);
        bt.root.left = new Node(12);
        bt.root.right = new Node(15);
        bt.root.left.left = new Node(25);
        bt.root.left.right = new Node(30);
        bt.root.right.left = new Node(36);
        BT bt2 = new BT();
        bt2.root = new Node(10);
        bt2.root.left = new Node(12);
        bt2.root.right = new Node(15);
        bt2.root.left.left = new Node(25);
        System.out.println(bt.containsTree(bt.root, bt2.root));
    }
}

Could anyone explain to me why i am getting false?

Body:
Your API for constructing the tree is hard to read. If you defined a constructor:

public Node(int v, Node left, Node right)

Then you could declare your trees as:

bt.root = new Node(
    10,
    new Node(
        12,
        new Node(25, null, null),
        new Node(30, null, null)),
    new Node(
        25,
        new Node(36, null, null),
        null));

bt2.root = new Node(
    10,
    new Node(
        12,
        new Node(25, null, null),
        null)),
    new Node(15, null, null));

Like this, I think it is easy to see that the second isn't a subtree of the first:

the node with value 10 in the first has a right node with value 25; in the second it has a right value 15;

the node with value 12 in the first has a non-null right value, whereas it is null in the second.


问:
Adonis JS - Access Model's custom method
I've added a custom method called customMethod to a model, like so:

```<code>class Prize extends Model {

  customMethod(){

    return 'test'

  }

}
</code>```

When I use find to get a prize by primary key I can call this method no problem

```<code>    const prize = await Prize.find(1);

    return prize.customMethod();
    //returns 'test'
</code>```

but when if I get a prize any other way, through a relationship or by querying by a field, I can't access this method.

```<code>   const countrysPrizes = await country.prizes().fetch();

    for (const key in countrysPrizes) {
      if (countrysPrizes.hasOwnProperty(key)) {
        const prize = countrysPrizes[key];

        return prize.customMethod();
        //returns 500 - prize.customMethod is not a function
      }
    }
</code>```

How can I access this method while iterating through multiple of the object?

答:
You need to use <fetched_object>.rows because of VanillaSerializer

Example code :

  const user = await User.find(1);
  const posts = await user.posts().fetch();

  posts.rows.forEach(post=> { // use .rows
    console.info(post.customMethod()); // Your custom method
  });
```

I've had trouble using the basic foreach loop. So I used .foreach()

An output example with fetch() :

Body:
I've added a custom method called customMethod to a model, like so:

class Prize extends Model {

  customMethod(){

    return 'test'

  }

}

When I use find to get a prize by primary key I can call this method no problem

    const prize = await Prize.find(1);

    return prize.customMethod();
    //returns 'test'

but when if I get a prize any other way, through a relationship or by querying by a field, I can't access this method.

   const countrysPrizes = await country.prizes().fetch();

    for (const key in countrysPrizes) {
      if (countrysPrizes.hasOwnProperty(key)) {
        const prize = countrysPrizes[key];

        return prize.customMethod();
        //returns 500 - prize.customMethod is not a function
      }
    }

How can I access this method while iterating through multiple of the object?

Body:
You need to use <fetched_object>.rows because of VanillaSerializer

Example code :

  const user = await User.find(1);
  const posts = await user.posts().fetch();

  posts.rows.forEach(post=> { // use .rows
    console.info(post.customMethod()); // Your custom method
  });

I've had trouble using the basic foreach loop. So I used .foreach()

An output example with fetch() :


问:
Alternative for CREATE VIRTUAL TABLE IF NOT EXISTS
According to CREATE VIRTUAL TABLE syntax, IF NOT EXISTS clause is not available.

How should I handle the case when the virtual table already exists without using DROP TABLE IF EXISTS?

I want to use rtree and fts module.

答:
This is now supported since sqlite 3.7.11.

changelog


问:
Where is Location of Microsoft Edge Extension Folder that are installed from Microsoft Store?
Where is the location of Microsoft Edge extensions folder when they are installed from Microsoft Store, in Windows 10?</p>

答: In your edge browser go to edge://version/ page and locate the Profile Path there that would look something like C:\Users\%username%\AppData\Local\Microsoft\Edge\User Data\Default\Extensions


问:
How to keep div x to the right of img its currently overlayed on using position absolute?
I am trying to create this (Black represents the div in my current code):

Currently the div is not consistent in its placement, like I would like it to be (I would like it to be constantly ini the same place like the image above).

How can I make the div stay in the same place like in the image?

Here is what I currently have:

.content {
  display: grid;
  grid-template-columns: repeat( auto-fit, minmax(400px, 1fr) );
  height: 100%;
  padding: 5px;
  margin-top: 95px;
  /* 25 */
  margin-right: 25px;
  margin-left: 215px;
  margin-bottom: 170px;

  text-align: center;
}

#example {
   position: absolute;
   top: 10px;
   left: 130px;

   padding: 5px;
   background-color: white;
   border: 2px solid red;
   color: darkgreen;
}

.grid-item:active {
  box-shadow: 0 0 5px 0px rgba(0,0,0,1);
}

.grid-item:hover {

background-color: #262626;
}

.grid-item {
  position: relative;

padding: 0px;

  border-radius: 10px;

  transition: 0.2s background-color;
}

.thumbnail {
  /* background-color: black; */
  /* object-fit: cover;
  background-repeat: no-repeat;
  background-size: cover; */

  margin-right: 5px;
  /* width: 95%; */
  width: 430px;
  height: 240px;
  /* height: 70%; */
  border-radius: 11px;
  border: 1px solid #282828;
  cursor: pointer;
  object-fit: cover;
}
/* object-fit: cover; */

.details {
  display: inline-flex;
  /* text-align: center; */
  /* display:block; */
  /* display:table-cell;
  vertical-align:middle; */

  /* background-color: grey; */
  margin-right: 5px;
  /* width: 95%; */
  width: 430px;
  height: 75px;
  cursor: pointer;
}
.portalTitle {
  margin-top: 25px;
  margin-left: 10px;
  /* margin: auto; */
  /* line-height: 70px; */
  font: Arial;
  font-family: sans-serif;
  font-size: 16px;
  font-weight:500;
}
.profileImg {
  cursor: pointer;
  width: 45px;
  height: 45px;
  border-radius: 25px;
  margin-top: 10px;
  object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="content">
      <div class="grid-item">
        <img class="thumbnail" src="https://firebasestorage.googleapis.com/v0/b/soundscapeportals.appspot.com/o/9SUaEJqwrbYHv0kyGmAhglyY1eI2%2F8a53b262101685.5a84bec504f01.jpg?alt=media&token=ea80efb6-a7e7-41d6-9c2d-cdc5ef8cc731">
        <div id="example">This is my div</div>
        <div class="details">
          <img class="profileImg" src="https://firebasestorage.googleapis.com/v0/b/soundscapeportals.appspot.com/o/9SUaEJqwrbYHv0kyGmAhglyY1eI2%2F8a53b262101685.5a84bec504f01.jpg?alt=media&token=ea80efb6-a7e7-41d6-9c2d-cdc5ef8cc731">
          <span class="portalTitle"> Shanghai, China night sounds</span>
        </div>
      </div>
      <div class="grid-item">
        <img class="thumbnail" src="images/testImg.png">
        <div id="example">This is my div</div>
        <div class="details">
          <img class="profileImg" src="images/testImg.png">
          <span class="portalTitle"> Shanghai, China night sounds</span>
        </div>
      </div>
    </div></code>```

答:
Put your image inside a container div and make your example be positioned absolute to that div, not the griditem div. Also, DO NOT use multiple elements with the same ID. Here is an example where I made the first item be like you want it to be and your second one is how you originally had it so you can see the difference.

.content {
  display: grid;
  grid-template-columns: repeat( auto-fit, minmax(400px, 1fr) );
  height: 100%;
  padding: 5px;
  margin-top: 95px;
  /* 25 */
  margin-right: 25px;
  margin-left: 215px;
  margin-bottom: 170px;
  text-align: center;
}

.example {
   position: absolute;
   top: 10px;
   left: 130px;
   padding: 5px;
   background-color: white;
   border: 2px solid red;
   color: darkgreen;
}

.grid-item:active {
  box-shadow: 0 0 5px 0px rgba(0,0,0,1);
}

.grid-item:hover {
  background-color: #262626;
}

.grid-item {
  position: relative;
  padding: 0px;
  border-radius: 10px;
  transition: 0.2s background-color;
}

.thumbnail {
  /* background-color: black; */
  /* object-fit: cover;
  background-repeat: no-repeat;
  background-size: cover; */
  margin-right: 5px;
  /* width: 95%; */
  width: 430px;
  height: 240px;
  /* height: 70%; */
  border-radius: 11px;
  border: 1px solid #282828;
  cursor: pointer;
  object-fit: cover;
}
/* object-fit: cover; */

.details {
  display: inline-flex;
  /* text-align: center; */
  /* display:block; */
  /* display:table-cell;
  vertical-align:middle; */
  /* background-color: grey; */
  margin-right: 5px;
  /* width: 95%; */
  width: 430px;
  height: 75px;
  cursor: pointer;
}
.portalTitle {
  margin-top: 25px;
  margin-left: 10px;
  /* margin: auto; */
  /* line-height: 70px; */
  font: Arial;
  font-family: sans-serif;
  font-size: 16px;
  font-weight:500;
}
.profileImg {
  cursor: pointer;
  width: 45px;
  height: 45px;
  border-radius: 25px;
  margin-top: 10px;
  object-fit: cover;
}

.imgcontainer {
  display: inline-block;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div class="grid-item">
    <div class="imgcontainer">
      <img class="thumbnail" src="https://firebasestorage.googleapis.com/v0/b/soundscapeportals.appspot.com/o/9SUaEJqwrbYHv0kyGmAhglyY1eI2%2F8a53b262101685.5a84bec504f01.jpg?alt=media&token=ea80efb6-a7e7-41d6-9c2d-cdc5ef8cc731" />
      <div class="example">This is my div</div>
    </div>
    <div class="details">
      <img class="profileImg" src="https://firebasestorage.googleapis.com/v0/b/soundscapeportals.appspot.com/o/9SUaEJqwrbYHv0kyGmAhglyY1eI2%2F8a53b262101685.5a84bec504f01.jpg?alt=media&token=ea80efb6-a7e7-41d6-9c2d-cdc5ef8cc731" />
      <span class="portalTitle"> Shanghai, China night sounds</span>
    </div>
  </div>
  <div class="grid-item">
    <img class="thumbnail" src="images/testImg.png" />
    <div class="example">This is my div</div>
    <div class="details">
      <img class="profileImg" src="images/testImg.png" />
      <span class="portalTitle"> Shanghai, China night sounds</span>
    </div>
  </div>
</div></code>```

Body:
I am trying to create this (Black represents the div in my current code):

Currently the div is not consistent in its placement, like I would like it to be (I would like it to be constantly ini the same place like the image above).

How can I make the div stay in the same place like in the image?

Here is what I currently have:

.content {
  display: grid;
  grid-template-columns: repeat( auto-fit, minmax(400px, 1fr) );
  height: 100%;
  padding: 5px;
  margin-top: 95px;
  /* 25 */
  margin-right: 25px;
  margin-left: 215px;
  margin-bottom: 170px;

  text-align: center;
}

#example {
   position: absolute;
   top: 10px;
   left: 130px;

   padding: 5px;
   background-color: white;
   border: 2px solid red;
   color: darkgreen;
}

.grid-item:active {
  box-shadow: 0 0 5px 0px rgba(0,0,0,1);
}

.grid-item:hover {

background-color: #262626;
}

.grid-item {
  position: relative;

padding: 0px;

  border-radius: 10px;

  transition: 0.2s background-color;
}

.thumbnail {
  /* background-color: black; */
  /* object-fit: cover;
  background-repeat: no-repeat;
  background-size: cover; */

  margin-right: 5px;
  /* width: 95%; */
  width: 430px;
  height: 240px;
  /* height: 70%; */
  border-radius: 11px;
  border: 1px solid #282828;
  cursor: pointer;
  object-fit: cover;
}
/* object-fit: cover; */

.details {
  display: inline-flex;
  /* text-align: center; */
  /* display:block; */
  /* display:table-cell;
  vertical-align:middle; */

  /* background-color: grey; */
  margin-right: 5px;
  /* width: 95%; */
  width: 430px;
  height: 75px;
  cursor: pointer;
}
.portalTitle {
  margin-top: 25px;
  margin-left: 10px;
  /* margin: auto; */
  /* line-height: 70px; */
  font: Arial;
  font-family: sans-serif;
  font-size: 16px;
  font-weight:500;
}
.profileImg {
  cursor: pointer;
  width: 45px;
  height: 45px;
  border-radius: 25px;
  margin-top: 10px;
  object-fit: cover;
}

This is my div

           Shanghai, China night sounds

This is my div

           Shanghai, China night sounds

Body:
Put your image inside a container div and make your example be positioned absolute to that div, not the griditem div. Also, DO NOT use multiple elements with the same ID. Here is an example where I made the first item be like you want it to be and your second one is how you originally had it so you can see the difference.

.content {
  display: grid;
  grid-template-columns: repeat( auto-fit, minmax(400px, 1fr) );
  height: 100%;
  padding: 5px;
  margin-top: 95px;
  /* 25 */
  margin-right: 25px;
  margin-left: 215px;
  margin-bottom: 170px;
  text-align: center;
}

.example {
   position: absolute;
   top: 10px;
   left: 130px;
   padding: 5px;
   background-color: white;
   border: 2px solid red;
   color: darkgreen;
}

.grid-item:active {
  box-shadow: 0 0 5px 0px rgba(0,0,0,1);
}

.grid-item:hover {
  background-color: #262626;
}

.grid-item {
  position: relative;
  padding: 0px;
  border-radius: 10px;
  transition: 0.2s background-color;
}

.thumbnail {
  /* background-color: black; */
  /* object-fit: cover;
  background-repeat: no-repeat;
  background-size: cover; */
  margin-right: 5px;
  /* width: 95%; */
  width: 430px;
  height: 240px;
  /* height: 70%; */
  border-radius: 11px;
  border: 1px solid #282828;
  cursor: pointer;
  object-fit: cover;
}
/* object-fit: cover; */

.details {
  display: inline-flex;
  /* text-align: center; */
  /* display:block; */
  /* display:table-cell;
  vertical-align:middle; */
  /* background-color: grey; */
  margin-right: 5px;
  /* width: 95%; */
  width: 430px;
  height: 75px;
  cursor: pointer;
}
.portalTitle {
  margin-top: 25px;
  margin-left: 10px;
  /* margin: auto; */
  /* line-height: 70px; */
  font: Arial;
  font-family: sans-serif;
  font-size: 16px;
  font-weight:500;
}
.profileImg {
  cursor: pointer;
  width: 45px;
  height: 45px;
  border-radius: 25px;
  margin-top: 10px;
  object-fit: cover;
}

.imgcontainer {
  display: inline-block;
  position: relative;
}

<div class="content">
  <div class="grid-item">
    <div class="imgcontainer">
      <img class="thumbnail" src="https://firebasestorage.googleapis.com/v0/b/soundscapeportals.appspot.com/o/9SUaEJqwrbYHv0kyGmAhglyY1eI2%2F8a53b262101685.5a84bec504f01.jpg?alt=media&token=ea80efb6-a7e7-41d6-9c2d-cdc5ef8cc731" />
      <div class="example">This is my div</div>
    </div>
    <div class="details">
      <img class="profileImg" src="https://firebasestorage.googleapis.com/v0/b/soundscapeportals.appspot.com/o/9SUaEJqwrbYHv0kyGmAhglyY1eI2%2F8a53b262101685.5a84bec504f01.jpg?alt=media&token=ea80efb6-a7e7-41d6-9c2d-cdc5ef8cc731" />
      <span class="portalTitle"> Shanghai, China night sounds</span>
    </div>
  </div>
  <div class="grid-item">
    <img class="thumbnail" src="images/testImg.png" />
    <div class="example">This is my div</div>
    <div class="details">
      <img class="profileImg" src="images/testImg.png" />
      <span class="portalTitle"> Shanghai, China night sounds</span>
    </div>
  </div>
</div>


答:
First, you could form rolling 120 second blocs of data.
You could then apply;

block and evaluate using duplicated:
df = df[df.duplicated(subset=['val1','val2',’val3’], keep=False)]

Or groupby:
df.groupby(['val1','val2',’val3’]).count()

Or even a SQL distinct.
https://www.w3schools.com/sql/sql_distinct.asp

Please post what you have tried. The above methods work for strings, floats, datetimes and integer data types.

Title: How to find duplicate based upon multiple columns in a rolling window in pandas?

Body:
Sample Data

{"transaction": {"merchant": "merchantA", "amount": 20, "time": "2019-02-13T10:00:00.000Z"}}
{"transaction": {"merchant": "merchantB", "amount": 90, "time": "2019-02-13T11:00:01.000Z"}}
{"transaction": {"merchant": "merchantC", "amount": 90, "time": "2019-02-13T11:00:10.000Z"}}
{"transaction": {"merchant": "merchantD", "amount": 90, "time": "2019-02-13T11:00:20.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 90, "time": "2019-02-13T11:01:30.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 90, "time": "2019-02-13T11:02:30.000Z"}}
.
.

I have some code like this

    df = pd.DataFrame()
for line in sys.stdin:
    data = json.loads(line)
    # df1 = pd.DataFrame(data["transaction"], index=[len(df.index)])
    df1 = pd.DataFrame(data["transaction"], index=[data['transaction']['time']])
    df1['time'] = pd.to_datetime(df1['time'])
    df = df.append(df1)
    # df['count'] = df.rolling('2min', on='time', min_periods=1)['amount'].count()

print(df)
print(len(df[df.merchant.eq(data['transaction']['merchant']) & df.amount.eq(data['transaction']['amount'])].index))

Current output

2019-02-13T10:00:00.000Z  merchantA      20 2019-02-13 10:00:00
2019-02-13T11:00:01.000Z  merchantB      90 2019-02-13 11:00:01
2019-02-13T11:00:10.000Z  merchantC      90 2019-02-13 11:00:10
2019-02-13T11:00:20.000Z  merchantD      90 2019-02-13 11:00:20
2019-02-13T11:01:30.000Z  merchantE      90 2019-02-13 11:01:30
2019-02-13T11:02:30.000Z  merchantE      90 2019-02-13 11:02:30

2

Expected output

2019-02-13T10:00:00.000Z  merchantA      20 2019-02-13 10:00:00
2019-02-13T11:00:01.000Z  merchantB      90 2019-02-13 11:00:01
2019-02-13T11:00:10.000Z  merchantC      90 2019-02-13 11:00:10
2019-02-13T11:00:20.000Z  merchantD      90 2019-02-13 11:00:20
2019-02-13T11:01:30.000Z  merchantE      90 2019-02-13 11:01:30

As the data is streaming. I want to check if a duplicate record(whose merchant and amount value are same) arrives withing two minutes so I discard it as and do no processing on it. print it as a duplicate.

Do I have to do something with index zipping or groupby? but then how to equate of multiple columns.
Or some rolling condition on two columns but can't find anything how to do it.

What am I missing here?

Thanks

EDIT

#dup = df[df.duplicated(subset=['merchant', 'amount'], keep=False)]
     res = df.loc[(df.merchant == data['transaction']['merchant']) & (df.amount == data['transaction']['amount'])]
        # res['timediff'] = pd.to_timedelta((data['transaction']['time'] - res['time']), unit='T')
        res['timediff'] = (data['transaction']['time'] - res['time'])
        if len(res.index) >1:
           print(res)

so im trying something like this and if the result is less than 120 seconds i can process it.
But the resulting df in currently in the form of

                      merchant  amount                time       concat          timediff
2019-02-13 11:03:00  merchantF      10 2019-02-13 11:03:00  merchantF10 -1 days +23:59:20
2019-02-13 11:02:20  merchantF      10 2019-02-13 11:02:20  merchantF10          00:00:00

2019-02-13 11:01:30  merchantE      10 2019-02-13 11:01:30  merchantE10 00:01:00
2019-02-13 11:02:00  merchantE      10 2019-02-13 11:02:00  merchantE10 00:00:30
2019-02-13 11:02:30  merchantE      10 2019-02-13 11:02:30  merchantE10 00:00:00

-1 days +23:59:20 this format I think can be delt with taking Absolute value?

how can I convert the time in a format that I can compare it with 120 seconds? pd.to_deltatime() didn't work for me or maybe I'm using it wrong.