qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,443,939 | <p>There is a list from the user:</p>
<pre><code>user_list = [1, 3.5, "xx", "gg", 6, "2"].
new_list = []
</code></pre>
<p>How to make it so that with the help of "list comprehension" from user_list to new_list moved:</p>
<ol>
<li>Value with type (float)</li>
<li>Even number with type(int)</li>
<li>All elements that have type (str) turned into -2 and were sent to a new_list</li>
</ol>
| [
{
"answer_id": 74444243,
"author": "sahasrara62",
"author_id": 5086255,
"author_profile": "https://Stackoverflow.com/users/5086255",
"pm_score": 1,
"selected": false,
"text": "list comprehension"
},
{
"answer_id": 74458549,
"author": "bjdev",
"author_id": 19834372,
"author_profile": "https://Stackoverflow.com/users/19834372",
"pm_score": 0,
"selected": false,
"text": "new_list"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74443939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20377891/"
] |
74,443,942 | <p>I have my original web scraped HTML text as this</p>
<pre><code>> {"overview":"\\u003cp\\u003e\\u003cspan style=\\"font-size:
> 10.5pt;\\"\\u003e\\u003cspan class=\\"TextRun SCXW87260372 BCX0\\" style=\\"margin: 0px; padding: 0px; -webkit-user-drag: none;
> -webkit-tap-highlight-color: transparent; color: #000000; font-family: \'Meiryo UI\', \'Meiryo UI_MSFontService\', sans-serif; font-kerning:
> none; line-height: 15.1083px; font-variant-ligatures: none
> !important;\\"\\u003e\\u003cspan class=\\"NormalTextRun SCXW87260372
> BCX0\\" style=\\"margin: 0px; padding: 0px; -webkit-user-drag: none;
> -webkit-tap-highlight-color: transparent; background-color: inherit;\\"\\u003eFioriアプリの動作確認で、2通りのトラブルシューティングをする\\u003c/span\\u003e\\u003c/span\\u003e\\u003cspan
> class=\\"EOP SCXW87260372 BCX0\\" style=\\"margin: 0px;.....
</code></pre>
<p>I used the BeautifulSoup to eliminate all the HTML tags using the below code</p>
<pre><code>def beautify_full_text(content):
try:
soup = BeautifulSoup(content.encode('utf-8').decode('unicode-escape'), "html.parser")
for tag in soup():
for attribute in ["class", "id", "name", "style"]:
del tag[attribute]
return os.linesep.join([s for s in soup.text.splitlines() if s])
except Exception as e:
print(e)
return
</code></pre>
<p>I now see that the returned text has no HTML Tags but has the below text</p>
<pre><code>{"overview":"Fioriã\x82¢ã\x83\x97ã\x83ªã\x81®å\x8b\x95ä½\x9c確èª\x8dã\x81§ã\x80\x81ï¼\x92é\x80\x9aã\x82\x8aã\x81®ã\x83\x88ã\x83©ã\x83\x96ã\x83«ã\x82·ã\x83¥ã\x83¼ã\x83\x86ã\x82£ã\x83³ã\x82°ã\x82\x92ã\x81\x99ã\x82\x8bÂ\xa0\nGatewayã\x81®ã\x82¨ã\x83©ã\x83¼ã\x83\xadã\x82°ã\x82\x92確èª\x8dÂ\xa0\nã\x83\x96ã\x83©ã\x82¦ã\x82¶ã\x81®ã\x82³ã\x83³ã\x82½ã\x83¼ã\x83«ã\x81§ICFã\x82µã\x83¼ã\x83\x93ã\x82¹ç\xad\x89ã\x81§403/403ã\x81\x8cå\x87ºã\x81¦ã\x81\x84ã\x81ªã\x81\x84ã\x81\x8b\nÂ\xa0â\x80¯Â\xa0[Gateway
Foundation] Which Tools Can Be Used for
Troubleshooting?Â\xa0\n極å\x8a\x9bã\x83\xadã\x82°ã\x82ªã\x83³è¨\x80èª\x9eï¼\x9dè\x8b±èª\x9eã\x81«ã\x81\x97ã\x81¦ã\x80\x81ã\x80\x8cggrksã\x80\x8dã\x82\x92ã\x82ªã\x83\x96ã\x83©ã\x83¼ã\x83\x88ã\x81«å\x8c\nã\x82\x93ã\x81§è¨\x80ã\x81\x86Â\xa0\n"}
</code></pre>
<p>Is there a way I can eliminate these unwanted characters as well?</p>
| [
{
"answer_id": 74449885,
"author": "Mark Tolonen",
"author_id": 235698,
"author_profile": "https://Stackoverflow.com/users/235698",
"pm_score": 1,
"selected": false,
"text": "unicode-escape"
},
{
"answer_id": 74463990,
"author": "Vishnukk",
"author_id": 3152686,
"author_profile": "https://Stackoverflow.com/users/3152686",
"pm_score": 0,
"selected": false,
"text": "def beautify_full_text(content):\n try:\n soup = BeautifulSoup(content.encode('utf-8').decode('unicode-escape'), \"html.parser\")\n for tag in soup():\n for attribute in [\"class\", \"id\", \"name\", \"style\"]:\n del tag[attribute]\n \n beau_text = os.linesep.join([s for s in soup.text.splitlines() if s])\n beau_text = beau_text.encode(\"ascii\", \"ignore\").decode()\n return beau_text\n except Exception as e:\n print(e)\n return\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74443942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3152686/"
] |
74,443,983 | <p>I have an UICollectionView built programatically that doesn't allow me to scroll to the last item in it.</p>
<p><a href="https://i.stack.imgur.com/g4Ybt.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g4Ybt.gif" alt="" /></a></p>
<p>Here is how I set it up</p>
<pre><code>private let collectionView: UICollectionView = UICollectionView(
frame: .zero,
collectionViewLayout: UICollectionViewCompositionalLayout { sectionIndex, _ -> NSCollectionLayoutSection? in
return WorkoutListViewController.createSectionLayout(section: sectionIndex)
})
</code></pre>
<pre><code>private static func createSectionLayout(section: Int) -> NSCollectionLayoutSection {
// item
let item = NSCollectionLayoutItem(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalHeight(1.0)
)
)
item.contentInsets = NSDirectionalEdgeInsets(top: 14, leading: 0, bottom: 14, trailing: 0)
// group
let verticalGroup = NSCollectionLayoutGroup.vertical(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(123)
),
repeatingSubitem: item,
count: 1
)
// section
let section = NSCollectionLayoutSection(group: verticalGroup)
return section
}
</code></pre>
<pre><code>private func configureCollectionView() {
view.addSubview(collectionView)
collectionView.register(
WorkoutListCollectionViewCell.self,
forCellWithReuseIdentifier: WorkoutListCollectionViewCell.identifier
)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .systemBackground
}
</code></pre>
<p>I tried modifying the height by giving it a very large number (e.g 2000) and nothing changed. I also tried adding the <code>UICollectionViewDelegateFlowLayout</code> protocol to add the</p>
<pre><code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
}
</code></pre>
<p>function and return the <code>CGSize</code> of my item.</p>
| [
{
"answer_id": 74444046,
"author": "Natarajan",
"author_id": 3420996,
"author_profile": "https://Stackoverflow.com/users/3420996",
"pm_score": 2,
"selected": true,
"text": "collectionView.contentInset = .init(top: 0.0, left: 0.0, bottom: bottomHeight, right: 0.0)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74443983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11488162/"
] |
74,443,990 | <p>So i try to loop an Array and push it into object within this code:</p>
<pre><code> const past7Days = [...Array(7).keys()].map(index => {
var date = new Date();
const local = new Date();
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
local.setDate(date.getDate() - index);
return local.toJSON().slice(0, 10);
});
let data={};
let arr=[]
for (var i = 0; i < past7Days.length; i++) {
console.log(past7Days[i]);
return arr.push(data["key"] = past7Days[i])
}
</code></pre>
<p>what i expected is :</p>
<pre><code>[{key:"date"},{key:"date2"}]
</code></pre>
<p>can somebody tellme where did i do wrong here</p>
| [
{
"answer_id": 74444156,
"author": "qrsngky",
"author_id": 4225384,
"author_profile": "https://Stackoverflow.com/users/4225384",
"pm_score": 1,
"selected": false,
"text": "<string representation of a date>"
},
{
"answer_id": 74444193,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 3,
"selected": true,
"text": "data"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74443990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16136595/"
] |
74,443,993 | <p>We have a lakehouse architecture with Hive metastore tables. I want to do processing on this data, so I select my data as Spark dataframe.</p>
<p>The specific processing step I wanted to achieve was parsing date columns in my Spark Dataframes that come in a rather strange format: <code>/Date(1582959943313)/</code>, where the number inside /Date(xx)/ is miliseconds since epoch. I thought I was being clever by converting my Spark DF <code>toPandas()</code> and then process the dates:</p>
<pre><code>df_accounts = spark.sql("SELECT * FROM database.accounts")
df_accounts_pandas = df_accounts.toPandas()
df_accounts_pandas['ControlledDate'] = df_accounts_pandas['ControlledDate'].str.slice(start=6, stop=-2)
df_accounts_pandas['Created'] = df_accounts_pandas['Created'].str.slice(start=6, stop=-2)
df_accounts_pandas['ControlledDate'] = pd.to_datetime(df_accounts_pandas['ControlledDate'], unit='ms', origin='unix')
df_accounts_pandas['Created'] = pd.to_datetime(df_accounts_pandas['Created'], unit='ms', origin='unix')
</code></pre>
<p>This works fine. Now the next step would be to convert the df <em>back</em> to a Spark Dataframe, and be done with it.</p>
<pre><code>df_accounts = spark.createDataframe(df_accounts_pandas)
</code></pre>
<p>This throws a <code>ValueError: Some of types cannot be determined after inferring</code></p>
<p><a href="https://stackoverflow.com/questions/40517553/pyspark-valueerror-some-of-types-cannot-be-determined-after-inferring">This SO Question</a> tells me to either manually define a schema or drop Null columns. But why do I have to make this choice? I don't understand why I was able to do the conversion the other way around, but now cannot convert back.</p>
<p>Are there any other workarounds? My tables have 100's of columns so I don't want to manually define a schema. I don't know if columns that are NULL now will be NULL in the future.</p>
<p>P.S. - Am rather new to spark ecosystem - Is it even a good idea to do processing in pandas like this? (I would like to since it has more options than regular PySpark) Or are there better ways to use pandas functionality on Spark dataframes?</p>
| [
{
"answer_id": 74444377,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 1,
"selected": false,
"text": "toPandas()"
},
{
"answer_id": 74529985,
"author": "Arjun",
"author_id": 4432720,
"author_profile": "https://Stackoverflow.com/users/4432720",
"pm_score": 0,
"selected": false,
"text": "from pyspark.sql.types import *\naccounts_new_schema = StructType([ StructField(\"col1\", LongType(), True)\\\n ,StructField(\"col2\", IntegerType(), True)\\\n ,StructField(\"col3\", IntegerType(), True)\\\n ,StructField(\"col4\", IntegerType(), True)\\\n ,StructField(\"col5\", StringType(), True)\\\n ,StructField(\"col6\", StringType(), True)\\\n ,StructField(\"col7\", IntegerType(), True)\\\n ,StructField(\"col8\", IntegerType(), True)\\])\n\nspdf = spark.createDataFrame(df_accounts_pandas,schema=accounts_new_schema)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74443993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7253901/"
] |
74,444,009 | <p>Is there a way to traverse through html elements in playwright like <code>cy.get("abc").find("div")</code> in cypress?</p>
<p>In other words, any <code>find()</code> equivalent method in playwright?</p>
<p><code>page.locator("abc").find()</code> is not a valid method in playwright though :(</p>
| [
{
"answer_id": 74447556,
"author": "agoff",
"author_id": 11625850,
"author_profile": "https://Stackoverflow.com/users/11625850",
"pm_score": 2,
"selected": false,
"text": "findBy*"
},
{
"answer_id": 74450820,
"author": "Kartoos",
"author_id": 7801965,
"author_profile": "https://Stackoverflow.com/users/7801965",
"pm_score": 1,
"selected": false,
"text": "<body style=\"\">\n <div>\n <h1>Example Domain</h1>\n <p>This domain is for use in illustrative examples in documents. You may use this\n domain in literature without prior coordination or asking for permission.</p>\n <p>\n <a href=\"https://www.iana.org/domains/example\">More information...</a>\n </p>\n </div>\n</body>\n"
},
{
"answer_id": 74451812,
"author": "Blunt",
"author_id": 20473079,
"author_profile": "https://Stackoverflow.com/users/20473079",
"pm_score": 3,
"selected": true,
"text": "div"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16391157/"
] |
74,444,011 | <p>I'm trying to implement normalized binary cross entropy for a classification task following this paper: <a href="https://arxiv.org/pdf/2006.13554.pdf" rel="nofollow noreferrer">Normalized Loss Functions for Deep Learning with Noisy Labels</a>.
The math is as follows:
<a href="https://i.stack.imgur.com/leXDb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/leXDb.png" alt="enter image description here" /></a></p>
<p>Here is my implementation:</p>
<pre><code>import tensorflow as tf
from keras.utils import losses_utils
class NormalizedBinaryCrossentropy(tf.keras.losses.Loss):
def __init__(
self,
from_logits=False,
label_smoothing=0.0,
axis=-1,
reduction=tf.keras.losses.Reduction.NONE,
name="normalized_binary_crossentropy",
**kwargs
):
super().__init__(
reduction=reduction, name=name
)
self.from_logits = from_logits
self._epsilon = tf.keras.backend.epsilon()
def call(self, target, logits):
if tf.is_tensor(logits) and tf.is_tensor(target):
logits, target = losses_utils.squeeze_or_expand_dimensions(
logits, target
)
logits = tf.convert_to_tensor(logits)
target = tf.cast(target, logits.dtype)
if self.from_logits:
logits = tf.math.sigmoid(logits)
logits = tf.clip_by_value(logits, self._epsilon, 1.0 - self._epsilon)
numer = target * tf.math.log(logits) + (1 - target) * tf.math.log(1 - logits)
denom = - (tf.math.log(logits) + tf.math.log(1 - logits))
return - numer / denom
def get_config(self):
config = super().get_config()
config.update({"from_logits": self._from_logits})
return config
</code></pre>
<p>I'm using this loss to train a binary classifier (CTR predictor), but loss of the model does not decrease and ROC-AUC remains at ~0.49-0.5. To verify the implementation of numerator, I tried training by removing the denominator and it's working fine.</p>
<pre><code># Example Usage
labels = np.array([[0], [1], [0], [0], [0]]).astype(np.int64)
logits = np.array([[-1.024], [2.506], [1.43], [0.004], [-2.0]]).astype(np.float64)
tf_nce = NormalizedBinaryCrossentropy(
reduction=tf.keras.losses.Reduction.NONE,
from_logits=True
)
tf_nce(labels, logits)
#<tf.Tensor: shape=(5, 1), dtype=float64, numpy=
# array([[0.18737159],
# [0.02945536],
# [0.88459308],
# [0.50144269],
# [0.05631594]])>
</code></pre>
<p>I checked manually with some extremes and that loss doesn't hit nans or 0s.</p>
<p>Can anyone help me in debugging why the model is not able to converge on this loss? Is there something wrong with my understanding of the loss function or implementation?</p>
<p>Edit 1: Model architecture is a Multi-Gate Mixture-of-Experts with 6 tasks. All 6 tasks are binary classification and losses from all tasks are added together to get final loss.</p>
| [
{
"answer_id": 74447556,
"author": "agoff",
"author_id": 11625850,
"author_profile": "https://Stackoverflow.com/users/11625850",
"pm_score": 2,
"selected": false,
"text": "findBy*"
},
{
"answer_id": 74450820,
"author": "Kartoos",
"author_id": 7801965,
"author_profile": "https://Stackoverflow.com/users/7801965",
"pm_score": 1,
"selected": false,
"text": "<body style=\"\">\n <div>\n <h1>Example Domain</h1>\n <p>This domain is for use in illustrative examples in documents. You may use this\n domain in literature without prior coordination or asking for permission.</p>\n <p>\n <a href=\"https://www.iana.org/domains/example\">More information...</a>\n </p>\n </div>\n</body>\n"
},
{
"answer_id": 74451812,
"author": "Blunt",
"author_id": 20473079,
"author_profile": "https://Stackoverflow.com/users/20473079",
"pm_score": 3,
"selected": true,
"text": "div"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7674869/"
] |
74,444,019 | <p>I have multiple documents with different index name that bulk saves in elasticsearch:</p>
<pre><code>public void bulkCreateOrUpdate(List personUpdateList, List addressUpdateList, List positionUpdateList) {
this.operations.bulkUpdate(personUpdateList,Person.class);
this.operations.bulkUpdate(addressUpdateList, Address.class);
this.operations.bulkUpdate(positionUpdateList, Position.class);
}
</code></pre>
<p>However, is this still possible to be optimized by calling just a single line, saving multiple list of different index types?</p>
| [
{
"answer_id": 74447556,
"author": "agoff",
"author_id": 11625850,
"author_profile": "https://Stackoverflow.com/users/11625850",
"pm_score": 2,
"selected": false,
"text": "findBy*"
},
{
"answer_id": 74450820,
"author": "Kartoos",
"author_id": 7801965,
"author_profile": "https://Stackoverflow.com/users/7801965",
"pm_score": 1,
"selected": false,
"text": "<body style=\"\">\n <div>\n <h1>Example Domain</h1>\n <p>This domain is for use in illustrative examples in documents. You may use this\n domain in literature without prior coordination or asking for permission.</p>\n <p>\n <a href=\"https://www.iana.org/domains/example\">More information...</a>\n </p>\n </div>\n</body>\n"
},
{
"answer_id": 74451812,
"author": "Blunt",
"author_id": 20473079,
"author_profile": "https://Stackoverflow.com/users/20473079",
"pm_score": 3,
"selected": true,
"text": "div"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20204076/"
] |
74,444,034 | <p>I'm running this transformation in PDI and it took me hours to load table that contains 18000 record .</p>
<p><a href="https://i.stack.imgur.com/FEbei.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FEbei.png" alt="enter image description here" /></a></p>
<p>SQL query in the iput table step :
<a href="https://i.stack.imgur.com/2DU7B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2DU7B.png" alt="enter image description here" /></a></p>
<p>Is it normal or should I try to optimize the SQL query or add more steps ??</p>
| [
{
"answer_id": 74447556,
"author": "agoff",
"author_id": 11625850,
"author_profile": "https://Stackoverflow.com/users/11625850",
"pm_score": 2,
"selected": false,
"text": "findBy*"
},
{
"answer_id": 74450820,
"author": "Kartoos",
"author_id": 7801965,
"author_profile": "https://Stackoverflow.com/users/7801965",
"pm_score": 1,
"selected": false,
"text": "<body style=\"\">\n <div>\n <h1>Example Domain</h1>\n <p>This domain is for use in illustrative examples in documents. You may use this\n domain in literature without prior coordination or asking for permission.</p>\n <p>\n <a href=\"https://www.iana.org/domains/example\">More information...</a>\n </p>\n </div>\n</body>\n"
},
{
"answer_id": 74451812,
"author": "Blunt",
"author_id": 20473079,
"author_profile": "https://Stackoverflow.com/users/20473079",
"pm_score": 3,
"selected": true,
"text": "div"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11101976/"
] |
74,444,078 | <p>I'm using react-hook-form to validate text input field.</p>
<pre><code> const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm({ mode: 'onBlur' });
<input
name='name'
type='text'
onInput={(e) => setValue(e.target.value)}
{...register('name',{ required: true })}
/>
</code></pre>
<p>My problem is that when I enter text 'name' in that input - text clears.
Also I have another input with name blog.</p>
<pre><code><input
name='blog'
type='text'
onInput={(e) => setValue(e.target.value)}
{...register('blog',{ required: true })}
/>
</code></pre>
<p>Now if I write blog - blog input clears.
Funny thing is that you can write name inside blog input and text in name input clears.
Same way If I write blog inside name input - blog input text clears.</p>
<p>I guess I'm making some dumb mistake, what am I doing wrong ? :)</p>
| [
{
"answer_id": 74444109,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "onInput={(e) => setValue(\"blog\", e.target.value)}\n"
},
{
"answer_id": 74444356,
"author": "Saqib Ali",
"author_id": 20508261,
"author_profile": "https://Stackoverflow.com/users/20508261",
"pm_score": 0,
"selected": false,
"text": "const [blogValue,setBlogValue] = useState(\"\");\n\n<input\n name='blog'\n type='text'\n value ={blogValue}\n onChange={(e) => setBlogValue(e.target.value)}\n/>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678855/"
] |
74,444,113 | <p>I am trying to calculate the % change by year in the following dataset, does anyone know if this is possible?</p>
<p>I have the difference but am unsure how we can change this into a percentage</p>
<p>C diff(economy_df_by_year$gdp_per_capita)</p>
<pre><code>df
year gdp
1998 8142.
1999 8248.
2000 8211.
2001 7926.
2002 8366.
2003 10122.
2004 11493.
2005 12443.
2006 13275.
2007 15284.
</code></pre>
| [
{
"answer_id": 74444109,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "onInput={(e) => setValue(\"blog\", e.target.value)}\n"
},
{
"answer_id": 74444356,
"author": "Saqib Ali",
"author_id": 20508261,
"author_profile": "https://Stackoverflow.com/users/20508261",
"pm_score": 0,
"selected": false,
"text": "const [blogValue,setBlogValue] = useState(\"\");\n\n<input\n name='blog'\n type='text'\n value ={blogValue}\n onChange={(e) => setBlogValue(e.target.value)}\n/>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18338223/"
] |
74,444,118 | <p>I'm trying to understand this auto-increment formula, that my colleague has written. I understand how <strong>arrayformula</strong> usually works and also <strong>countifs</strong>.</p>
<p>Formula from the screen: <code>=ARRAYFORMULA(COUNTIFS(ROW(B2:B), "<="&ROW(B2:B)))</code></p>
<p>I'm stacked about why ROW(B2:B) (1param in COUNTIFS) as a range works fine. It should be a range, not just a number that <strong>ROW</strong> function returns.</p>
<p>I have been trying to find an answer, read documentation, but nothing helped.</p>
<p>I think that, for example, for 4th line the formula would look like this (if we seperate from ARRAYFORMULA):</p>
<p>COUNTIFS(<strong>ROW(B4:B</strong>), "<="&ROW(B4:B)),</p>
<p>COUNTIFS(<strong>4</strong>, "<=4")</p>
<p>I need to understand this code, not other solutions.</p>
<p><a href="https://i.stack.imgur.com/gYvFl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gYvFl.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74444109,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "onInput={(e) => setValue(\"blog\", e.target.value)}\n"
},
{
"answer_id": 74444356,
"author": "Saqib Ali",
"author_id": 20508261,
"author_profile": "https://Stackoverflow.com/users/20508261",
"pm_score": 0,
"selected": false,
"text": "const [blogValue,setBlogValue] = useState(\"\");\n\n<input\n name='blog'\n type='text'\n value ={blogValue}\n onChange={(e) => setBlogValue(e.target.value)}\n/>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16260974/"
] |
74,444,184 | <p>I tried to run the image by index from my image folder but I don't know how to implement specific to text to each image see here <img src="https://i.stack.imgur.com/XbxGm.jpg" alt="my out put" /></p>
<p>But I am unsure now how I can add specific text to each images by index</p>
<pre><code> child: Container(
width: 160,
padding: EdgeInsets.only(left: 15),
margin: EdgeInsets.only(left: 15),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(15),
image: DecorationImage(
image: AssetImage("img/city${index + 1}.jpg"),
fit: BoxFit.cover,
opacity: 0.7,
),
),
Padding(
padding: EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: \[
Text(
"City name",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600),
),
</code></pre>
| [
{
"answer_id": 74444109,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "onInput={(e) => setValue(\"blog\", e.target.value)}\n"
},
{
"answer_id": 74444356,
"author": "Saqib Ali",
"author_id": 20508261,
"author_profile": "https://Stackoverflow.com/users/20508261",
"pm_score": 0,
"selected": false,
"text": "const [blogValue,setBlogValue] = useState(\"\");\n\n<input\n name='blog'\n type='text'\n value ={blogValue}\n onChange={(e) => setBlogValue(e.target.value)}\n/>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17958365/"
] |
74,444,185 | <p>I'm trying to use <code>apache_beam.dataframe.io.read_csv</code> function to read an online source with no success. Everything works if the file is hosted on google storage <code>'gs://bucket/source.csv'</code> but fails on getting the file from <code>'https://github.com/../source.csv'</code> like sources..</p>
<pre><code>from apache_beam.dataframe.io import read_csv
url = 'https://github.com/datablist/sample-csv-files/raw/main/files/people/people-100.csv'
with beam.Pipeline() as pipeline:
original_collection = pipeline | read_csv(path=url)
original_collection = original_collection[:5]
original_collection | beam.Map(print)
</code></pre>
<p>Giving me</p>
<pre><code>ValueError: Unable to get filesystem from specified path, please use the correct path or ensure the required dependency is installed, e.g., pip install apache-beam[gcp]. Path specified: https://github.com/datablist/sample-csv-files/raw/main/files/people/people-100.csv
</code></pre>
<p>Could anybody give me a hint?</p>
| [
{
"answer_id": 74449641,
"author": "Mazlum Tosun",
"author_id": 9261558,
"author_profile": "https://Stackoverflow.com/users/9261558",
"pm_score": 0,
"selected": false,
"text": "Beam"
},
{
"answer_id": 74453052,
"author": "robertwb",
"author_id": 582333,
"author_profile": "https://Stackoverflow.com/users/582333",
"pm_score": 2,
"selected": true,
"text": "def parse_csv(contents):\n [use pandas, the csv module, etc. to parse the contents string into rows]\n\nwith beam.Pipeline() as pipeline:\n urls = pipeline | beam.Create(['https://github.com/datablist/sample-csv-files/...'])\n contents = urls | beam.Map(lambda url: urllib.request.urlopen(url).read())\n rows = contents | beam.FlatMap(parse_csv)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6835888/"
] |
74,444,186 | <p>I am migrating d3 to newer version 7.6.1, now the version which i am using is 5.15 and it has one method which is <strong>d3.entries</strong> and in version 7.6.1 it is deprecated.</p>
<p>As far as i know this d3.entries is used to convert object to array of object for example -</p>
<pre><code>chart.data = function(value,newName,newColor,sorted) {
varColor=newColor;
varSorted=sorted;
displayData = d3.entries(value); //version 5.15
console.log("-----");
console.log(displayData);
assignedName = newName;
return chart;
}
</code></pre>
<pre><code>{Metrics: 404, Asset: 492, B7: 84} to [{'Metrics',404}, {'Asset': 492}, {'B7': 84}]
</code></pre>
<p>but when i upgrade my d3 version this d3.entries() function is not there so i used <strong>Object.entries()</strong> -</p>
<pre><code>chart.data = function(value,newName,newColor,sorted) {
varColor=newColor;
varSorted=sorted;
displayData = Object.entries(value); //version 7.6
console.log("-----");
console.log(displayData);
assignedName = newName;
return chart;
}
</code></pre>
<pre><code>My Output is -
[['Metrics',404], ['Asset': 492], ['B7': 84]]
</code></pre>
<p>but still i am not getting the desired output.</p>
| [
{
"answer_id": 74449641,
"author": "Mazlum Tosun",
"author_id": 9261558,
"author_profile": "https://Stackoverflow.com/users/9261558",
"pm_score": 0,
"selected": false,
"text": "Beam"
},
{
"answer_id": 74453052,
"author": "robertwb",
"author_id": 582333,
"author_profile": "https://Stackoverflow.com/users/582333",
"pm_score": 2,
"selected": true,
"text": "def parse_csv(contents):\n [use pandas, the csv module, etc. to parse the contents string into rows]\n\nwith beam.Pipeline() as pipeline:\n urls = pipeline | beam.Create(['https://github.com/datablist/sample-csv-files/...'])\n contents = urls | beam.Map(lambda url: urllib.request.urlopen(url).read())\n rows = contents | beam.FlatMap(parse_csv)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20300988/"
] |
74,444,195 | <p>I have a windows forms timer with an async callback that await a database operation, why the await is executed again even before the previous callback has not finished yet? How can I fix this?
Many people say that System.Windows.Forms.Timer wait that previous callback operation finishes before executing new one.</p>
<pre><code>Private Async Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' I have an array with 6 elements that i control
' for executing database operation
For i=1 To 6
If(some condition is true in array index)
Await SaveAsync()
'set to false the condition in array index after save
End If
Next
End Sub
</code></pre>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74444599,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 2,
"selected": true,
"text": "Interval"
},
{
"answer_id": 74493146,
"author": "Craig",
"author_id": 2659161,
"author_profile": "https://Stackoverflow.com/users/2659161",
"pm_score": 0,
"selected": false,
"text": "System.Windows.Forms.Timer"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20221290/"
] |
74,444,254 | <p>I have an multidimensional array like this:</p>
<pre><code>$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"],
"downloads2" => ["downloadnaam" => "eyetyy"],
];
</code></pre>
<p>I need to check if the value <code>eyetyy</code> exists in this array under the key <code>downloadnaam</code><br/>
Then I need to find the index of this value and remove it from the array.<br/><br/>
<strong>The expected result</strong>:</p>
<pre><code>$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"]
];
</code></pre>
<p>I tried this:</p>
<pre><code>$index = array_search($download->name, array_column($downloadArray, 'downloadnaam'));
if ($index !== null)
{
unset($downloadArray[$index]);
die("found index: " . $index);
}
</code></pre>
<p><code>$download->name</code> contains <code>'eyetyy'</code><br/>
<code>$downloadArray</code> is my array<br/>
But it always dies and doesn't show any index on screen.<br/>
Can anyone help me?</p>
| [
{
"answer_id": 74444433,
"author": "Yohann Daniel Carter",
"author_id": 4849739,
"author_profile": "https://Stackoverflow.com/users/4849739",
"pm_score": 0,
"selected": false,
"text": "$downloadArray = [\n \"downloads1\" => [\"downloadnaam\" => \"fdgssgsfg\"],\n \"downloads2\" => [\"downloadnaam\" => \"eyetyy\"],\n];\n\nforeach ($downloadArray as $subKey => $subArray) {\n if (\\in_array($subArray['downloadnaam'], ['eyetyy'], true)) {\n unset($downloadArray[$subKey]);\n }\n }\n\nvar_dump($downloadArray);\n"
},
{
"answer_id": 74444720,
"author": "SamYan",
"author_id": 2363860,
"author_profile": "https://Stackoverflow.com/users/2363860",
"pm_score": 1,
"selected": false,
"text": "$downloadArray = [\n \"downloads1\" => [\"downloadnaam\" => \"fdgssgsfg\"],\n \"downloads2\" => [\"downloadnaam\" => \"eyetyy\"],\n];\n\n$filter = \"eyetyy\";\n\n// Search for index\n$index = array_search($filter, array_column($downloadArray, \"downloadnaam\"));\n\nif ($index !== false) {\n // Delete\n array_splice($downloadArray, $index, 1);\n}\n\nprint_r($downloadArray);\ndie();\n"
},
{
"answer_id": 74444999,
"author": "Jbadminton",
"author_id": 5275959,
"author_profile": "https://Stackoverflow.com/users/5275959",
"pm_score": 2,
"selected": true,
"text": "$downloadArray = array_filter($downloadArray, function ($item) use ($download) {\n return $item['downloadnaam'] != $download->name;\n});\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5275959/"
] |
74,444,255 | <p>I tried to increment the count whenever i click the button. When click the button it is getting rendered twice. But it should be render only once.</p>
<p>Here is my code
<a href="https://codesandbox.io/s/async-pine-3z2ty3?file=/src/App.js" rel="nofollow noreferrer">https://codesandbox.io/s/async-pine-3z2ty3?file=/src/App.js</a></p>
<pre><code>import { useCallback, useMemo, useState } from "react";
import Button from "./Button";
export default function App() {
const [count, setCount] = useState(0);
const [count1, setCount1] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
const MyButton1 = useMemo(
() => <Button handleClick={handleClick} title="Increment Count" />,
[handleClick]
);
const MyButton2 = useMemo(
() => (
<Button handleClick={() => setCount1(count1 + 1)} title="Click here" />
),
[count1]
);
return (
<div className="App">
<div>count : {count}</div>
{MyButton1}
<div>count1 : {count1}</div>
{MyButton2}
</div>
);
}
</code></pre>
<pre><code>import React from "react";
const Button = React.memo(({ handleClick, title }) => {
console.log(title);
return <button onClick={handleClick}>{title}</button>;
});
export default Button;
</code></pre>
| [
{
"answer_id": 74444361,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 3,
"selected": true,
"text": "handleClick"
},
{
"answer_id": 74444901,
"author": "Faizan Ahmad",
"author_id": 6761008,
"author_profile": "https://Stackoverflow.com/users/6761008",
"pm_score": 0,
"selected": false,
"text": "<StrictMode></StrictMode>"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20228364/"
] |
74,444,269 | <p>Hei,</p>
<p>i have a question about the best practice here. I have a Golang Project which uses as Postgres Database and specific Migrations. The Database has many tables and some depend on each other (Table A has FK to Table B, Table B has FK to Table A). My "problem" is now that i have to import data from CSV files, which i do with the COPY ... FROM ... WITH Command. Each CSV file contains the Data for a specific table.</p>
<p>If i try to use the copy command i get the error: "insert or update on table "b" violates foreign key constraint". Thats right, because in table a is no data right now. And cause of the FKs the problem happens on both sides.</p>
<p>So what is the best way to import the data?</p>
<p>Thanks :)</p>
| [
{
"answer_id": 74444361,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 3,
"selected": true,
"text": "handleClick"
},
{
"answer_id": 74444901,
"author": "Faizan Ahmad",
"author_id": 6761008,
"author_profile": "https://Stackoverflow.com/users/6761008",
"pm_score": 0,
"selected": false,
"text": "<StrictMode></StrictMode>"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3087506/"
] |
74,444,290 | <p>I have an Angular Material Paginator which I am currently customizing the css of.</p>
<p>It looks like this:</p>
<p><a href="https://i.stack.imgur.com/peKB4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/peKB4.png" alt="enter image description here" /></a></p>
<p>I cant record my screen on my device so I will explain.</p>
<p>The two arrow buttons on the right side are Angular Material Icon Buttons.</p>
<p>When I click them, a ripple effect (gray circle) appears. I need to delete that ripple effect.</p>
<p>I couldn't inspect the element where it happens because it only appears on a click.</p>
<p>I checked SO already about this question and the most common answer, to use <code>[disableRipple]="true"</code> doesn't work here, since angular paginator does not have this property. I am working in a big project with several developers, so I would not like to touch global scss files.</p>
<p>This is my code btw:</p>
<pre><code><mat-paginator
#paginator
(page)="changePage($event)"
[length]="imagesAndFiles.length"
[pageIndex]="pageIndex"
[pageSize]="pageSize"
[pageSizeOptions]="[4, 8, 16, 24, 32]"
>
</mat-paginator>
</code></pre>
<p>How can I remove the ripple effect from the arrow buttons?</p>
| [
{
"answer_id": 74444361,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 3,
"selected": true,
"text": "handleClick"
},
{
"answer_id": 74444901,
"author": "Faizan Ahmad",
"author_id": 6761008,
"author_profile": "https://Stackoverflow.com/users/6761008",
"pm_score": 0,
"selected": false,
"text": "<StrictMode></StrictMode>"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14287016/"
] |
74,444,299 | <p>I would like to merge two dictionaries this way below:</p>
<pre><code>dict1={
'kl':'ngt',
'schemas':
[
{
'date':'14-12-2022',
'name':'kolo'
}
]
}
dict2={
'kl':'mlk',
'schemas':
[
{
'date':'14-12-2022',
'name':'maka'
}
],
}
</code></pre>
<p>then I create a variable that will group the two dictionaries in this way</p>
<pre><code>all_dict=[
'kl':'ngt',
'schemas':
[
{
'date':'14-12-2022',
'name':'kolo'
}
],
'kl':'mlk',
'schemas':
[
{
'date':'23-10-2022',
'name':'maka'
}
]
......
]
</code></pre>
<p>How to get this result. I'm stuck right now please help me if possible</p>
| [
{
"answer_id": 74444996,
"author": "ali jafarzadeh",
"author_id": 17230449,
"author_profile": "https://Stackoverflow.com/users/17230449",
"pm_score": 2,
"selected": true,
"text": "all_dict=[\n{\n 'kl':'ngt',\n 'schemas':\n [\n {\n 'date':'14-12-2022',\n 'name':'kolo'\n }\n ],\n},\n\n {\n\n 'kl':'mlk',\n 'schemas':\n [\n {\n 'date':'23-10-2022',\n 'name':'maka'\n }\n ]\n}\n ......\n ]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20339610/"
] |
74,444,319 | <p>I want to search for a string in a number of text files in a folder and its subfolders.</p>
<p>Then all files containing this string should be listed. How can this be made?</p>
<p>The string is just something like "Test". So no special chars. I thought of something like the following in a loop:</p>
<pre><code>open('*', 'r').read().find('Test')
</code></pre>
| [
{
"answer_id": 74444996,
"author": "ali jafarzadeh",
"author_id": 17230449,
"author_profile": "https://Stackoverflow.com/users/17230449",
"pm_score": 2,
"selected": true,
"text": "all_dict=[\n{\n 'kl':'ngt',\n 'schemas':\n [\n {\n 'date':'14-12-2022',\n 'name':'kolo'\n }\n ],\n},\n\n {\n\n 'kl':'mlk',\n 'schemas':\n [\n {\n 'date':'23-10-2022',\n 'name':'maka'\n }\n ]\n}\n ......\n ]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18172305/"
] |
74,444,369 | <p>the bellow component is for testing how to update a set with useState. The error occurs at <strong>state.has(num)</strong>
The state variable from useState is a set and has is a set build-in function. Why this error happens?</p>
<pre><code>import { useState } from "react";
function App() {
const [state, setState] = useState(new Set());
console.log(typeof state);
function clickHandler(num) {
if (!state.has(num)) {
setState(prevState => {
return setState(new Set(prevState).add(num))
})
} else {
setState((prevState) => {
return setState(new Set(prevState).delete(num));
});
}
}
return (
<>
<button onClick={() => clickHandler(1)}>1</button>
<button onClick={() => clickHandler(2)}>2</button>
<button onClick={() => clickHandler(3)}>3</button>
{ state}
</>
);
}
export default App;
</code></pre>
| [
{
"answer_id": 74444429,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 3,
"selected": true,
"text": "setState"
},
{
"answer_id": 74444607,
"author": "Saqib Ali",
"author_id": 20508261,
"author_profile": "https://Stackoverflow.com/users/20508261",
"pm_score": 0,
"selected": false,
"text": "import { useState, useRef, useEffect } from \"react\";\n\nfunction App() {\n const [stateValue, setStateValue] = useState(0);\n const previousValue = useRef(null);\n console.log(typeof stateValue);\n\n useEffect(() => {\n previousValue.current = stateValue;\n }, [stateValue]);\n\n function clickHandler(num) {\n setStateValue(num);\n }\n\n return (\n <>\n <button onClick={() => clickHandler(1)}>1</button>\n <button onClick={() => clickHandler(2)}>2</button>\n <button onClick={() => clickHandler(3)}>3</button>\n <br />\n <h5>number: {stateValue}</h5>\n <h5>previous number: {previousValue.current}</h5>\n </>\n );\n}\n\nexport default App;\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15428430/"
] |
74,444,370 | <p>looking for a way to remove open unpaired tags!
BS4 as well as lxml are good at removing unpaired closed tags.
But if they find an open tag, they try to close it, and close it at the very end :(</p>
<p>Example</p>
<pre><code>from bs4 import BeautifulSoup
import lxml.html
codeblock = '<strong>Good</strong> Some text and bad closed strong </strong> Some text and bad open strong PROBLEM HERE <strong> Some text <h2>Some</h2> or <h3>Some</h3> <p>Some Some text <strong>Good2</strong></p>'
soup = BeautifulSoup(codeblock, "html.parser").prettify()
print(soup)
root = lxml.html.fromstring(codeblock)
res = lxml.html.tostring(root)
print(res)
</code></pre>
<p>Output bs4:</p>
<pre><code><strong>
Good
</strong>
Some text and bad closed strong
Some text and bad open strong PROBLEM HERE
<strong>
Some text
<h2>
Some
</h2>
or
<h3>
Some
</h3>
<p>
Some Some text
<strong>
Good2
</strong>
</p>
</strong>
</code></pre>
<p>Output lxml:</p>
<pre><code>b'<div><strong>Good</strong> Some text and bad closed strong Some text and bad open strong PROBLEM HERE <strong> Some text <h2>Some</h2> or <h3>Some</h3> <p>Some Some text <strong>Good2</strong></p></strong></div>'
</code></pre>
<ol>
<li>I would be fine if the tag is closed before the first following tag, here in the example of H2</li>
</ol>
<pre><code>PROBLEM HERE <strong> Some text </strong><h2>Some</h2>
</code></pre>
<ol start="2">
<li>I would also be ok with removing this open tag <code><strong></code></li>
</ol>
<p>But the fact that it closes at the very end - this is a problem!</p>
<p><strong>In the real code the index (position) of the tag <code><strong></code> is not known!</strong></p>
<p>What are the solutions?</p>
<p>I tried to do it with BS4 and lxml but it didn't work!
If you know the solution, please help!</p>
| [
{
"answer_id": 74444537,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": ".unwrap()"
},
{
"answer_id": 74446208,
"author": "Sasha Kucher",
"author_id": 20509156,
"author_profile": "https://Stackoverflow.com/users/20509156",
"pm_score": 0,
"selected": false,
"text": "<strong>"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509156/"
] |
74,444,395 | <p>I have a log files that I read/stream into Python (it contains timestamp and data) using tail.</p>
<p>I need a way to see if, in the last 10 seconds, how many lines were seen/observed based on a filter (e.g. line contains "error")</p>
<p>I'll be checking every X seconds to see how many lines were present for "error" or "debug" etc... The count should only look at the last X seconds.</p>
<p>Example:</p>
<p>A log file which Python tails is</p>
<pre class="lang-none prettyprint-override"><code>2022-11-15 14:00:00,000 : Error 1923
2022-11-15 14:00:01,000 : Error 1456
2022-11-15 14:00:01,400 : Error 1001
2022-11-15 14:00:03,400 : Error 1124
2022-11-15 14:00:05,400 : Normal 0011
2022-11-15 14:00:06,400 : Error 1123
</code></pre>
<p>When I read the file, in Python; I want to answer the question</p>
<p><em>In the last X seconds, how many times have I seen Error or How many times have I seen Normal?</em></p>
<p>How would I accomplish this whilst I tail a file to check the last 10 seconds or 20 seconds etc.?</p>
| [
{
"answer_id": 74617097,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 1,
"selected": false,
"text": "datetime.datetime.now()"
},
{
"answer_id": 74664326,
"author": "kenjoe41",
"author_id": 4671205,
"author_profile": "https://Stackoverflow.com/users/4671205",
"pm_score": 0,
"selected": false,
"text": "# Import the necessary modules\nimport time\nfrom tail import tail\n\n# Set the number of seconds to look back\nnum_seconds = 10\n\n# Open the log file and stream the lines\nwith open('logfile.txt') as logfile:\n for line in tail(logfile):\n # Get the current time\n current_time = time.time()\n\n # Check if the line contains the desired string\n if \"error\" in line:\n # Check if the line was seen within the last X seconds\n if current_time - line_time <= num_seconds:\n # Increment the count\n count += 1\n"
},
{
"answer_id": 74672839,
"author": "Khaoz-07",
"author_id": 20171262,
"author_profile": "https://Stackoverflow.com/users/20171262",
"pm_score": 0,
"selected": false,
"text": "import time\n\nlog_lines = [\n (\"2022-11-15 14:00:00,000\", \"Error 1923\"),\n (\"2022-11-15 14:00:01,000\", \"Error 1456\"),\n (\"2022-11-15 14:00:01,400\", \"Error 1001\"),\n (\"2022-11-15 14:00:03,400\", \"Error 1124\"),\n (\"2022-11-15 14:00:05,400\", \"Normal 0011\"),\n (\"2022-11-15 14:00:06,400\", \"Error 1123\"),\n]\n\n# Get the current time and subtract 10 seconds from it\ntime_x_seconds_ago = time.time() - 10\n\n# Count the number of lines that occurred within the last X seconds\ncount = 0\nfor timestamp, line in log_lines:\n if time.strptime(timestamp, \"%Y-%m-%d %H:%M:%S,%f\") >= time_x_seconds_ago:\n count += 1\n\nprint(f\"Number of lines in the last 10 seconds: {count}\")\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370507/"
] |
74,444,435 | <p>I see the following step in noraUI sources</p>
<pre><code>@And("I expect to have {page-element} with the text {string}(\\?)")
public void expectText(Page.PageElement pageElement, String textOrKey, List<GherkinStepCondition> conditions) throws FailureException, TechnicalException {
this.expectText(pageElement, textOrKey, new Object[0]);
}
</code></pre>
<p>I would like to use this step but I can't pass {page-element} for this step. How it should look like?</p>
<p>According to doc I see that it should starts with $, but this step keeps undefined from feature file</p>
| [
{
"answer_id": 74617097,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 1,
"selected": false,
"text": "datetime.datetime.now()"
},
{
"answer_id": 74664326,
"author": "kenjoe41",
"author_id": 4671205,
"author_profile": "https://Stackoverflow.com/users/4671205",
"pm_score": 0,
"selected": false,
"text": "# Import the necessary modules\nimport time\nfrom tail import tail\n\n# Set the number of seconds to look back\nnum_seconds = 10\n\n# Open the log file and stream the lines\nwith open('logfile.txt') as logfile:\n for line in tail(logfile):\n # Get the current time\n current_time = time.time()\n\n # Check if the line contains the desired string\n if \"error\" in line:\n # Check if the line was seen within the last X seconds\n if current_time - line_time <= num_seconds:\n # Increment the count\n count += 1\n"
},
{
"answer_id": 74672839,
"author": "Khaoz-07",
"author_id": 20171262,
"author_profile": "https://Stackoverflow.com/users/20171262",
"pm_score": 0,
"selected": false,
"text": "import time\n\nlog_lines = [\n (\"2022-11-15 14:00:00,000\", \"Error 1923\"),\n (\"2022-11-15 14:00:01,000\", \"Error 1456\"),\n (\"2022-11-15 14:00:01,400\", \"Error 1001\"),\n (\"2022-11-15 14:00:03,400\", \"Error 1124\"),\n (\"2022-11-15 14:00:05,400\", \"Normal 0011\"),\n (\"2022-11-15 14:00:06,400\", \"Error 1123\"),\n]\n\n# Get the current time and subtract 10 seconds from it\ntime_x_seconds_ago = time.time() - 10\n\n# Count the number of lines that occurred within the last X seconds\ncount = 0\nfor timestamp, line in log_lines:\n if time.strptime(timestamp, \"%Y-%m-%d %H:%M:%S,%f\") >= time_x_seconds_ago:\n count += 1\n\nprint(f\"Number of lines in the last 10 seconds: {count}\")\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14137052/"
] |
74,444,460 | <p>My knowledge till now was that arrays in C and CPP/C++ have fixed sizes. However recently I encountered 2 pieces of code which seems to contradict this fact. I am attaching the pics here. Want to hear everyone's thoughts on how these are working. Also pasting the code and doubts here:</p>
<p>1.</p>
<pre><code>#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str1[]="Good"; //size of str1 should be 5
char str2[]="Afternoon"; //size of str2 should be 10
cout<<"\nSize of str1 before the copy: "<<sizeof(str1);
cout<<"\nstr1: "<<str1;
strcpy(str1,str2); //copying str1 into str2
cout<<"\nSize of str1 after the copy: "<<sizeof(str1);
cout<<"\nstr1: "<<str1;
return 0;
}
</code></pre>
<p><code>your text</code>
O/P:
Size of str1 before the copy: 5
str1: Good
Size of str1 after the copy: 5
str1: Afternoon</p>
<p>In first snippet I am using strcpy to copy char str2[] contents that is "Afternoon" into char str1[] whose size is 5 less than size of str2. So theoritically the line strcpy(str1,str2) should give error as size of str1 is less than size of str2 and fixed. But it executes, and more surprising is the fact that even after str1 contain the word "afternoon" the size is still the same.</p>
<p>2.</p>
<pre><code>#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char first_string[10]; // declaration of char array variable
char second_string[20]; // declaration of char array variable
int i; // integer variable declaration
cout<<"Enter the first string: ";
cin>>first_string;
cout<<"\nEnter the second string: ";
cin>>second_string;
for(i=0;first_string[i]!='\0';i++);
for(int j=0;second_string[j]!='\0';j++)
{
first_string[i]=second_string[j];
i++;
}
first_string[i]='\0';
cout<<"After concatenation, the string would look like: "<<first_string;
return 0;
}
</code></pre>
<p>O/P:
Enter the first string: good</p>
<p>Enter the second string: afternoon</p>
<p>After concatenation, the string would look like: goodafternoon</p>
<p>Here also even if I provide a string of length 20 as input to second_string[] it's still able to concatenate both the strings and put them in first_string[], even though the size of the concatenated string will be clearly greater than size of first_string[] which is 10.</p>
<p>I tried to assign a string of greater length to a string variable of smaller length. techincally it should not work but it worked anyway</p>
| [
{
"answer_id": 74444505,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 3,
"selected": false,
"text": "sizeof"
},
{
"answer_id": 74444597,
"author": "Marcus Müller",
"author_id": 4433386,
"author_profile": "https://Stackoverflow.com/users/4433386",
"pm_score": 1,
"selected": false,
"text": "char stringname[20] = \"string\";"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19732877/"
] |
74,444,467 | <p>I want to auto scroll to the first row after a given row number that has column A empty unloading the sheet (This Google Sheets)</p>
<p>the following formula works but scrolls past the last empty row as I assume if a row has formulas that add a blank in a cell it is counting them as not empty</p>
<pre><code> function onOpen(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = ss.getSheets()[0].getName();
// Logger.log("DEBUG: sheetname = "+sheetname)
var sheet = ss.getSheetByName(sheetname);
var lastRow = sheet.getLastRow();
var range = sheet.getRange(lastRow,1);
sheet.setActiveRange(range);
}
</code></pre>
<p>So I have tried modifying thus, but it doesn't scroll down</p>
<pre><code>function onOpen(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = ss.getSheets()[0].getName();
// Logger.log("DEBUG: sheetname = "+sheetname)
var sheet = ss.getSheetByName(sheetname);
var lastRow = sheet.getRange('A7:A').getLastRow() + 1;
var range = sheet.getRange(lastRow,1);
sheet.setActiveRange(range);
}
</code></pre>
<p>column A is empty at row 600 say but the sheet doesn't scroll on loading</p>
| [
{
"answer_id": 74444661,
"author": "Ping",
"author_id": 20288037,
"author_profile": "https://Stackoverflow.com/users/20288037",
"pm_score": 3,
"selected": true,
"text": ".lastRow()"
},
{
"answer_id": 74444952,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 1,
"selected": false,
"text": "getLastRow_()"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438299/"
] |
74,444,498 | <p>I'm in the process of learning python. I encountered a problem with json that I can't overcome.</p>
<p>I have this dataset from json in python:</p>
<pre><code>{
"Sophos": {
"detected": true,
"result": "phishing site"
},
"Phishtank": {
"detected": false,
"result": "clean site"
},
"CyberCrime": {
"detected": false,
"result": "clean site"
},
"Spam404": {
"detected": false,
"result": "clean site"
},
"SecureBrain": {
"detected": false,
"result": "clean site"
},
"Hoplite Industries": {
"detected": false,
"result": "clean site"
},
"CRDF": {
"detected": false,
"result": "clean site"
},
"Rising": {
"detected": false,
"result": "clean site"
},
"Fortinet": {
"detected": true,
"result": "phishing site"
},
"alphaMountain.ai": {
"detected": true,
"result": "phishing site"
},
"Lionic": {
"detected": false,
"result": "clean site"
},
"Cyble": {
"detected": false,
"result": "clean site"
}
}
</code></pre>
<p>I would like to filter these dictionaries in such a way as to print only those keys and values in which <strong>"detected": true</strong>.</p>
<p>For example I would like print only</p>
<pre><code>{
"Sophos": {
"detected": true,
"result": "phishing site"
},
"Fortinet": {
"detected": true,
"result": "phishing site"
}
}
</code></pre>
<p>I use VirusTotal apikey v2 <a href="https://developers.virustotal.com/v2.0/reference/domain-report" rel="nofollow noreferrer">https://developers.virustotal.com/v2.0/reference/domain-report</a>
My code in python:</p>
<pre><code>parameters = {'apikey': api_key, 'resource': domain}
response = requests.get(url, params=parameters)
python_response = json.loads(response.text)
scans = python_response["scans"]
example = json.dumps(python_response["scans"], indent=4)
print(example)
</code></pre>
<p>I'm looking for a simple and readable way to do it so that I understand it as best I can. I would like print result in Python. I searched and read various solutions for this (list comprehension or filter() with lambda), but it did not help me.</p>
<p>I'm still learning, thanks in advance for your understanding if it's a simple case.</p>
<p>Thank you in advance for your help and answers.</p>
| [
{
"answer_id": 74444637,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 3,
"selected": true,
"text": "true"
},
{
"answer_id": 74444658,
"author": "Faisal Nazik",
"author_id": 13959139,
"author_profile": "https://Stackoverflow.com/users/13959139",
"pm_score": 2,
"selected": false,
"text": "for key, value in example.items():\n if value[\"detected\"] == True:\n print(key, value)\n"
},
{
"answer_id": 74444702,
"author": "Himanshu Joshi",
"author_id": 10337294,
"author_profile": "https://Stackoverflow.com/users/10337294",
"pm_score": 1,
"selected": false,
"text": "for i in jsondump:\n if jsondump[i]['detected'] == True:\n print(jsondump[i])\n"
},
{
"answer_id": 74444792,
"author": "Umair Ali Khan",
"author_id": 15814754,
"author_profile": "https://Stackoverflow.com/users/15814754",
"pm_score": 1,
"selected": false,
"text": "new_dict = { key:val for (key,val) in example.items() if(value[\"detected\"] == True)}\n"
},
{
"answer_id": 74445044,
"author": "Oghli",
"author_id": 5169186,
"author_profile": "https://Stackoverflow.com/users/5169186",
"pm_score": 1,
"selected": false,
"text": "dataset = {\n \"Sophos\": {\n \"detected\": True,\n \"result\": \"phishing site\"\n },\n \"Phishtank\": {\n \"detected\": False,\n \"result\": \"clean site\"\n },\n \"CyberCrime\": {\n \"detected\": False,\n \"result\": \"clean site\"\n },\n \"Spam404\": {\n \"detected\": False,\n \"result\": \"clean site\"\n },\n \"SecureBrain\": {\n \"detected\": False,\n \"result\": \"clean site\"\n },\n \"Hoplite Industries\": {\n \"detected\": False,\n \"result\": \"clean site\"\n },\n \"CRDF\": {\n \"detected\": False,\n \"result\": \"clean site\"\n },\n \"Rising\": {\n \"detected\": False,\n \"result\": \"clean site\"\n },\n \"Fortinet\": {\n \"detected\": True,\n \"result\": \"phishing site\"\n },\n \"alphaMountain.ai\": {\n \"detected\": True,\n \"result\": \"phishing site\"\n },\n \"Lionic\": {\n \"detected\": False,\n \"result\": \"clean site\"\n },\n \"Cyble\": {\n \"detected\": False,\n \"result\": \"clean site\"\n }\n}\n\ndef filter_dict(d, f):\n ''' Filters dictionary d by function f. '''\n newDict = dict()\n # Iterate over all (k,v) pairs in dict\n for key, value in d.items():\n # Is condition satisfied?\n if f(key, value):\n newDict[key] = value\n return newDict\n\nprint(filter_dict(dataset, lambda k, v: v['detected'] == True))\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509308/"
] |
74,444,509 | <p>I have a dataframe like this:</p>
<pre><code>col1=[i for i in range(10)]
col2=[i**2 for i in range(10)]
df=pd.DataFrame(list(zip(col1,col2)),columns=['col1','col2'])
</code></pre>
<p>I want to create a new column using apply that adds the numbers in each row and then it adds then index. Something like</p>
<pre><code>df['col3']=df.apply(lambda x:x['col1']+x['col2']+index(x))
</code></pre>
<p>But of course index(x) does not work.</p>
<p>How can I do it in this setting?</p>
| [
{
"answer_id": 74444526,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "df['col3'] = df['col1']+df['col2']+df.index\n"
},
{
"answer_id": 74444527,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "axis=1"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18373361/"
] |
74,444,519 | <p>I'm trying to find an efficient way to merge two list of python objects (classes) with diferent structures and merge them into a new list of new object. The code:</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
class StructureOne(object):
def __init__(self, date_time: datetime, name: str):
self.date_time: datetime = date_time
self.name: str = name
self.value = None
def set_value(self,value:float):
self.value = value
class StructureTwo(object):
def __init__(self, date_time: datetime, value: float):
self.date_time = date_time
self.value: float = value
def merge_lists(list_one: list[StructureOne], list_two: list[StructureTwo]) -> list[StructureOne]:
for element_one in list_one:
i = 0
while i < len(list_two) and element_one.value is None:
if element_one.date_time == list_two[i].date_time:
element_one.set_value(value=list_two[i].value)
i += 1
return list_one
list_one: list[StructureOne] = [
StructureOne(date_time=datetime(2022, 1, 1, 0), name='zero'),
StructureOne(date_time=datetime(2022, 1, 1, 1), name='one'),
StructureOne(date_time=datetime(2022, 1, 1, 2), name='two'),
StructureOne(date_time=datetime(2022, 1, 1, 3), name='three'),
]
list_two: list[StructureTwo] = [
StructureTwo(date_time=datetime(2022, 1, 1, 0), value=0),
StructureTwo(date_time=datetime(2022, 1, 1, 1), value=1),
StructureTwo(date_time=datetime(2022, 1, 1, 2), value=2),
StructureTwo(date_time=datetime(2022, 1, 1, 3), value=3),
]
merged_list: list[StructureOne] = merge_lists(list_one=list_one, list_two=list_two)
</code></pre>
<p>The desired result is</p>
<pre class="lang-py prettyprint-override"><code>
list_one: list[StructureOne] = [
StructureOne(date_time=datetime(2022, 1, 1, 0), name='zero', value=0),
StructureOne(date_time=datetime(2022, 1, 1, 1), name='one', value=1),
StructureOne(date_time=datetime(2022, 1, 1, 2), name='two', value=2),
StructureOne(date_time=datetime(2022, 1, 1, 3), name='three', value=3),
]
</code></pre>
<p>We are trying to not use external libraries like <a href="https://github.com/viralogic/py-enumerable" rel="nofollow noreferrer">py-linq</a>.</p>
| [
{
"answer_id": 74444526,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "df['col3'] = df['col1']+df['col2']+df.index\n"
},
{
"answer_id": 74444527,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "axis=1"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16696915/"
] |
74,444,523 | <p>I want to make a floating widget but not floating all the time, when the widget is pulled up from the floating navigation bar it will appear like the picture in the middle</p>
<p>How to make a widget like this middle image?<a href="https://i.stack.imgur.com/Yi4uG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yi4uG.jpg" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74444526,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "df['col3'] = df['col1']+df['col2']+df.index\n"
},
{
"answer_id": 74444527,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "axis=1"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20259643/"
] |
74,444,534 | <p>I can't get this result: I need to have a date table (in YYYY-MM-DD format), where each date would contain requests.
Let me explain, basically I browse an already existing date table, which contains the dates of my requests.
And after this date array browsing, I build my new array which contains the date on which the array is positioned, as a key, and the associated request obtained by the call to my API.</p>
<p>So I have an array of the style (in the code snippet, dateArray[i] corresponds to the date on which the date array is positioned):</p>
<p>Here is the table daysRequests:</p>
<pre class="lang-js prettyprint-override"><code>[{
date: dateArray[i],
requests: [idRequestX]
},
{
date: dateArray[i],
requests: [idRequestX, idRequestY]
}]
</code></pre>
<p>And here is the push I do there:</p>
<pre class="lang-js prettyprint-override"><code>this.daysRequests.push({
day: dateArray[i],
requests: [idRequest]
});
</code></pre>
<p>Currently the push in the array creates duplicates for me, because if a date has several requests, it is not able to look for the record in the array corresponding to the already existing date and add in the requests sub-array, the new request.</p>
<p>I don't know how to check that the date already exists in the table and if it does, add the id of the new request in its sub table.</p>
<p>The complexity is that it is a key-value dictionary containing an array.</p>
<p>And that, I can't manage.</p>
<p>Does anyone have an idea?</p>
| [
{
"answer_id": 74444526,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "df['col3'] = df['col1']+df['col2']+df.index\n"
},
{
"answer_id": 74444527,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "axis=1"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20230231/"
] |
74,444,548 | <p>I wrote a lexical analyzer for cpp codes in python, but the problem is when I use input.split(" ") it won't recognize codes like x=2 or function() as three different tokens unless I add an space between them manually, like: x = 2 .
also it fails to recognize the tokens at the beginning of each line.
(if i add spaces between each two tokens and also at the beginning of each line, my code works correctly)</p>
<p>I tried splitting the code first by lines then by space but it got complicated and still I wasn't able to solve the first problem.
Also I thought about splitting it by operators, yet I couldn't actually implement it. plus I need the operators to be recognized as tokens as well, so this might not be a good idea.
I would appreciate it if anyone could give any solution or suggestion, Thank You.</p>
<pre><code>f=open("code.txt")
input=f.read()
input=input.split(" ")
</code></pre>
<pre><code>f=open("code.txt")
input=f.read()
input1=input.split("\n")
for var in input1:
var=var.split(" ")
</code></pre>
| [
{
"answer_id": 74448547,
"author": "Alex Vergara",
"author_id": 14075508,
"author_profile": "https://Stackoverflow.com/users/14075508",
"pm_score": 0,
"selected": false,
"text": "x=2"
},
{
"answer_id": 74449407,
"author": "rici",
"author_id": 1566221,
"author_profile": "https://Stackoverflow.com/users/1566221",
"pm_score": -1,
"selected": false,
"text": "re"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509154/"
] |
74,444,554 | <pre><code>#include <iostream>
using namespace std;
int main()
{
int d=4,r;
d=r+5;
cout<<d;
return 0;
}
</code></pre>
<p>The <code>r</code> variable has not a value .</p>
<p>How the compiler build this program?!</p>
<p>The output is : 21</p>
| [
{
"answer_id": 74444613,
"author": "Nikita Demodov",
"author_id": 11782808,
"author_profile": "https://Stackoverflow.com/users/11782808",
"pm_score": -1,
"selected": false,
"text": "r"
},
{
"answer_id": 74444629,
"author": "Hammad Ali",
"author_id": 12021448,
"author_profile": "https://Stackoverflow.com/users/12021448",
"pm_score": -1,
"selected": false,
"text": "r"
},
{
"answer_id": 74444638,
"author": "nvoigt",
"author_id": 2060725,
"author_profile": "https://Stackoverflow.com/users/2060725",
"pm_score": 1,
"selected": false,
"text": "r"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509496/"
] |
74,444,567 | <p>That same error appeared for many developers before, but none of them used Svelte, problem is I have it already initialized in main.js</p>
<pre class="lang-js prettyprint-override"><code>import Parse from 'parse/dist/parse.min.js';
const appID=import.meta.env['APP_ID'];
const PARSE_HOST_URL = 'https://parseapi.back4app.com/';
const jsKey = import.meta.env['JS_ID'];
Parse.initialize(appID, jsKey);
Parse.serverURL = PARSE_HOST_URL;
</code></pre>
<p>When I got that error I tried pasting this code again inside the component that should read the data but there was no difference. I also tried pasting the code from back4app documentation (where the DB is hosted).</p>
<pre class="lang-html prettyprint-override"><code><script context="module">
import Parse from 'parse/dist/parse.min.js';
export const Members = async function () {
// Reading parse objects is done by using Parse.Query
const parseQuery = new Parse.Query('members');
try {
let memberList = await parseQuery.find();
return memberList;
} catch (error) {
alert('Error! '+error.message);
};
};
</script>
</code></pre>
<p>the env file is located in the main root directory, did I put it in the wrong location or am I missing something?</p>
<p>Update: this is the previous version of the app written in vanilla js</p>
<pre><code>Parse.initialize([app_key], [js_key]);
Parse.serverURL = "https://parseapi.back4app.com/";
const membersDiv=document.querySelector('.memberlist');
const namesList=document.querySelector('.names');
let members = Parse.Object.extend("members");
let query = new Parse.Query(members).limit(1000);
query.find().then(function(results) {
results.forEach(function(member) {
let ul = document.createElement('ul');
let namesList = document.createElement('li');
namesList.classList.add('member');
namesList.innerHTML = ` <p class="name">${member.get('name')}</p><p class="memberid">${member.get('memberid')}</p><p><a href="tel:${member.get('phone')}">${member.get('phone')}</a></p>`;
if (member.get('phone')===undefined){
namesList.innerHTML = ` <p class="name">${member.get('name')}</p><p class="memberid">${member.get('memberid')}</p><p>${member.get('phone')}</p>`;
}
if (typeof member.get('phone')!="undefined"&& member.get('phone').substring(0,1)!='0'){
namesList.innerHTML = ` <p class="name">${member.get('name')}</p><p class="memberid">${member.get('memberid')}</p><p><a href="tel:${'0'+member.get('phone')}">${'0'+member.get('phone')}</a></p>`;
}
membersDiv.appendChild(namesList);
// create 5 checkboxes for each member
let checkboxes = document.createElement('div');
checkboxes.classList.add('checkboxes');
namesList.appendChild(checkboxes);
for (let i = 0; i < 5; i++) {
let checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.classList.add('w'+parseInt(i+1));
checkboxes.appendChild(checkbox);
if (member.get('w'+parseInt(i+1)) == true) {
// check the first checkbox
checkboxes.children[i].checked = true;
}
// when a checkbox is checked, update the member object
checkboxes.children[i].onclick = function() {
member.set('w'+parseInt(i+1), this.checked);
member.save();
if (member.save()){
console.log(members.name)
} else{
console.log('error')
}
}
}
});
});
</code></pre>
| [
{
"answer_id": 74444613,
"author": "Nikita Demodov",
"author_id": 11782808,
"author_profile": "https://Stackoverflow.com/users/11782808",
"pm_score": -1,
"selected": false,
"text": "r"
},
{
"answer_id": 74444629,
"author": "Hammad Ali",
"author_id": 12021448,
"author_profile": "https://Stackoverflow.com/users/12021448",
"pm_score": -1,
"selected": false,
"text": "r"
},
{
"answer_id": 74444638,
"author": "nvoigt",
"author_id": 2060725,
"author_profile": "https://Stackoverflow.com/users/2060725",
"pm_score": 1,
"selected": false,
"text": "r"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15059561/"
] |
74,444,585 | <p>I am writing a job filtering system in Vuejs and when the user enters a letter in the search bar, it only filters through the first letter instead of the whole word.</p>
<p>Imagine I have a list with item "Banana". If the user types "Banana" into the search bar, the item "Banana" is returned, since the search matches the list item. When the user just types a singular letter i.e. "B" it displays all items with the letter B. However when another letter is followed by that "Ba" it returns nothing.</p>
<p>Below is the code that is causing me problems:</p>
<pre><code><script>
export default {
data(){
return{
searchQuery:'',
selectedItem: null,
isVisible: false,
userArray: [],
};
},
computed: {
filteredUser() {
const query = this.searchQuery.toLowerCase();
if(this.searchQuery === "" ) {
return this.userArray;
}
return this.userArray.filter((user) => {
return Object.values(user).some((word) =>
String(word).toLowerCase().includes(query)
);
});
},
},
</code></pre>
<p>Other aspects of this filter function are working (i.e. the ability to click on jobs) except this search function.</p>
<p>Any help would be greatly appreciated.</p>
| [
{
"answer_id": 74444613,
"author": "Nikita Demodov",
"author_id": 11782808,
"author_profile": "https://Stackoverflow.com/users/11782808",
"pm_score": -1,
"selected": false,
"text": "r"
},
{
"answer_id": 74444629,
"author": "Hammad Ali",
"author_id": 12021448,
"author_profile": "https://Stackoverflow.com/users/12021448",
"pm_score": -1,
"selected": false,
"text": "r"
},
{
"answer_id": 74444638,
"author": "nvoigt",
"author_id": 2060725,
"author_profile": "https://Stackoverflow.com/users/2060725",
"pm_score": 1,
"selected": false,
"text": "r"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467279/"
] |
74,444,606 | <p>I wrote a definition to iterate over 200 files and calculate the number of transitions and transversions in a DNA sequence. Now I want to sum up the first column of the output of this for loop together and the second column together.</p>
<p>this is the output that I get repeated 200 times because I have 200 files, I want to get the sum of the first column (0+1+1+1+1+...)and the second column (1+0+0+0+....)</p>
<p><code>(0, 1) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (0, 1) (1, 0) (0, 1) (1, 0) (0, 1) (1, 0)</code></p>
<p>I tried to print the definition as a list and then sum up the lists, but those lists are not defined as they are just a for loop output, so I couldn't sum them up.</p>
<pre><code>print([dna_comparison(wild_type= f, mut_seq= h)])
</code></pre>
<p>Result:</p>
<pre><code>[(0, 1)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
</code></pre>
| [
{
"answer_id": 74444862,
"author": "Luca Clissa",
"author_id": 7678074,
"author_profile": "https://Stackoverflow.com/users/7678074",
"pm_score": 1,
"selected": false,
"text": "t"
},
{
"answer_id": 74444884,
"author": "Hobanator",
"author_id": 15324493,
"author_profile": "https://Stackoverflow.com/users/15324493",
"pm_score": 2,
"selected": false,
"text": "outputs = [(0, 1), (1, 0), (1, 0), ....]\n"
},
{
"answer_id": 74444886,
"author": "Himanshu Joshi",
"author_id": 10337294,
"author_profile": "https://Stackoverflow.com/users/10337294",
"pm_score": 2,
"selected": true,
"text": "arr = [[(0, 1)],\n[(1, 0)],\n[(1, 0)],\n[(1, 0)],\n[(1, 0)],\n[(1, 0)],\n[(1, 0)],\n[(1, 0)]]\nfirstcolumn = 0\nsecondcolumn = 0 \nfor i in arr:\n for v in i:\n print(v[0], ' ', v[1])\n firstcolumn = firstcolumn + v[0]\n secondcolumn = secondcolumn + v[1]\n \nprint(firstcolumn, secondcolumn)\n# 7 1\n"
},
{
"answer_id": 74444909,
"author": "Asi",
"author_id": 6544498,
"author_profile": "https://Stackoverflow.com/users/6544498",
"pm_score": 1,
"selected": false,
"text": "import random\n\ndata_number = 200 # Simulating n number of data in files\nwild_type: int = 0\nmut_seq: int = 0\nfor _ in range(data_number):\n data = (random.randint(0, 1), random.randint(0, 1)) # Simulating the tuple reading from a file\n wild_type += data[0]\n mut_seq += data[1]\n\nprint(f'wild_type {wild_type} times. mut_seq {mut_seq} times.')\n"
},
{
"answer_id": 74444940,
"author": "Christian Sloper",
"author_id": 8111755,
"author_profile": "https://Stackoverflow.com/users/8111755",
"pm_score": 2,
"selected": false,
"text": "accumulate"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509479/"
] |
74,444,608 | <p>I need to wrap first and last string that represent title and price of a product of a div with a span tag. This strings are taken from database and varies between products.
I trying to using wrap method on element but nothing change.</p>
<p>Is there any way to solve this issue.</p>
<p>HTML</p>
<pre><code><div class="product_desc">
Some Bracelet title
<p><span class=""> Material:</span> <span class=""> 926 Silver</span></p>
<p><span class=""> Chain length:</span> <span class=""> 21 cm</span></p>
<p><span class=""></span></p>
Price: €85.37
</div>
</code></pre>
<p>jQuery (to wrap first element)</p>
<p>Return the title for example</p>
<pre><code>$(".product_desc").text().trim().split('\n')[0])
</code></pre>
<p>Wrap not work</p>
<pre><code>$($(".product_desc").text().trim().split('\n')[0]).wrap("<span class='hello'></span>")
</code></pre>
| [
{
"answer_id": 74444925,
"author": "Pete",
"author_id": 1790982,
"author_profile": "https://Stackoverflow.com/users/1790982",
"pm_score": 2,
"selected": true,
"text": "$('.product_desc').contents() // get the contents\n .filter((index, element) => element.nodeType === 3 && element.data.trim().length > 0) // filter out text nodes\n .eq(0) // get the first text node - if you also want to wrap the last textnode, remove this line\n .wrap('<span class=\"hello\"></span>'); // wrap it"
},
{
"answer_id": 74445094,
"author": "Kairav Thakar",
"author_id": 20447312,
"author_profile": "https://Stackoverflow.com/users/20447312",
"pm_score": 0,
"selected": false,
"text": "$('.product_desc').each(function(i, v) {\n$(v).contents().eq(0).wrap('<span class=\"title\"/>');\n$(v).contents().eq(6).wrap('<span class=\"price\"/>');\n});\n"
},
{
"answer_id": 74445477,
"author": "Vivekanand Vishvkarma",
"author_id": 19443694,
"author_profile": "https://Stackoverflow.com/users/19443694",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n <script>\n $(document).ready(function () {\n let dv = document.getElementsByClassName(\"product_desc\")[0];\n $(dv.firstChild).wrap(\"<span class='title'></span>\");\n $(dv.lastChild).wrap(\"<span class='price'></span>\");\n console.log(dv)\n });\n </script>\n</head>\n\n<body>\n <div class=\"product_desc\">\n Some Bracelet title\n <p><span class=\"\"> Material:</span> <span class=\"\"> 926 Silver</span></p>\n <p><span class=\"\"> Chain length:</span> <span class=\"\"> 21 cm</span></p>\n <p><span class=\"\"></span></p>\n Price: €85.37\n </div>\n</body>\n</html>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533023/"
] |
74,444,640 | <p>I'm trying to set the <code>hosts</code> value in a ansible playbook dynamically. This means that in the <code>group_vars/all.yml</code> I have the correct IP for the host that ansible should use to connect. I have to do so, as I do not have the IP's beforehand. Prior to running the role described below, I run a role that creates the servers and only after that I have the IP's.</p>
<p>This is my <code>playbook.yml</code>:</p>
<pre><code>- name: do_something
hosts:
- "{{ NETWORK.IP }}"
roles:
- my_role
</code></pre>
<p>and the file<code>group_vars/all.yml</code> looks like this:</p>
<pre><code>NETWORK:
IP: 10.0.0.1
</code></pre>
<p>and when I execute I get:</p>
<pre><code>$ ansible-playbook playbook.yml
...
ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'NETWORK' is undefined
The error appears to be in 'playbook.yml': line X, column Y, but may
be elsewhere in the file depending on the exact syntax problem.
</code></pre>
<p><strong>I tried</strong> using different things such as</p>
<ul>
<li>in an earlier task on localhost using the set_facts module to set the variable</li>
<li>using the gather_facts in the playbook</li>
<li>using vars_file: group_vars/all.yml</li>
</ul>
<p><strong>Is it even possible to do like that? What am I doing wrong?</strong></p>
<hr />
<p>When I do something like this in the playbook:</p>
<pre><code>- name:
do_something2 hosts:
- LOCALHOST
tasks:
- set_fact:
MY_HOST: "{{ NETWORK.IP }}"
</code></pre>
<p>it is working. So I guess it has something to do with the 'all.yml' as the LOCALHOST is defined in a group. But <code>all.yml</code> should be possible to use even if the host is not defined in a group right?</p>
<hr />
<p><strong>Additional information</strong>:
This is the output of <code>ansible --version</code>:</p>
<pre><code>ansible [core 2.13.3]
config file = /etc/ansible/ansible.cfg
configured module search path = ['SOME_PATH', '/usr/share/ansible/plugins/modules']
ansible python module location = SOME_PATH
ansible collection location = SOME_PATH
executable location = SOME_PATH
python version = 3.10.8 (main, Oct 19 2022, 07:46:20) [GCC]
jinja version = 3.1.2
libyaml = True
</code></pre>
<p>and I'm running it on openSUSE Leap</p>
<p>edit: added the description as of why I need to have it set dynamically (because I create the servers in an earlier role).</p>
| [
{
"answer_id": 74444925,
"author": "Pete",
"author_id": 1790982,
"author_profile": "https://Stackoverflow.com/users/1790982",
"pm_score": 2,
"selected": true,
"text": "$('.product_desc').contents() // get the contents\n .filter((index, element) => element.nodeType === 3 && element.data.trim().length > 0) // filter out text nodes\n .eq(0) // get the first text node - if you also want to wrap the last textnode, remove this line\n .wrap('<span class=\"hello\"></span>'); // wrap it"
},
{
"answer_id": 74445094,
"author": "Kairav Thakar",
"author_id": 20447312,
"author_profile": "https://Stackoverflow.com/users/20447312",
"pm_score": 0,
"selected": false,
"text": "$('.product_desc').each(function(i, v) {\n$(v).contents().eq(0).wrap('<span class=\"title\"/>');\n$(v).contents().eq(6).wrap('<span class=\"price\"/>');\n});\n"
},
{
"answer_id": 74445477,
"author": "Vivekanand Vishvkarma",
"author_id": 19443694,
"author_profile": "https://Stackoverflow.com/users/19443694",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n <script>\n $(document).ready(function () {\n let dv = document.getElementsByClassName(\"product_desc\")[0];\n $(dv.firstChild).wrap(\"<span class='title'></span>\");\n $(dv.lastChild).wrap(\"<span class='price'></span>\");\n console.log(dv)\n });\n </script>\n</head>\n\n<body>\n <div class=\"product_desc\">\n Some Bracelet title\n <p><span class=\"\"> Material:</span> <span class=\"\"> 926 Silver</span></p>\n <p><span class=\"\"> Chain length:</span> <span class=\"\"> 21 cm</span></p>\n <p><span class=\"\"></span></p>\n Price: €85.37\n </div>\n</body>\n</html>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10065674/"
] |
74,444,665 | <p>I'm currently doing c++ with OpenCL, where a c-style struct is required to carry configuration information from the c++ host to the OpenCL kernel. Given that dynamically allocated arrays are not guaranteed to be supported by every OpenCL implementation, I must ensure every array accessible by the kernel code be static-sized. However, I run into weird errors when initializing static arrays within a c-style struct.</p>
<p>The error could be reproduced by the following PoC:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cstring>
#include <string>
#define ID_SIZE 16
struct conf_t {
const unsigned int a;
const unsigned int b;
const unsigned char id[ID_SIZE];
};
int main() {
const std::string raw_id("0123456789ABCDEF");
unsigned char id[ID_SIZE];
memcpy(id,raw_id.c_str(),ID_SIZE);
struct conf_t conf = {10,2048,id};
}
</code></pre>
<p>And the following error:</p>
<pre><code>poc.cc: In function ‘int main()’:
poc.cc:15:39: error: array must be initialized with a brace-enclosed initializer
15 | struct conf_t conf = {10,2048,id};
| ^~
</code></pre>
<p>It's true that I could remove the const keyword in the struct and get rid of the stack variable <code>id</code>, where <code>&(conf.id)</code> could be the first parameter of <code>memcpy</code>. However, I'd like to keep the immutability of fields in the conf struct, which enables the compilers to check undesired modifications.</p>
<p>For my understanding, structs in c should have the following memory layout:</p>
<pre><code> 0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| a |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| b |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ id +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</code></pre>
<p>Given the stack variable <code>id</code> is also with static size, I'm confused why the c++ compiler still looks for a brace-enclosed initializer even if <code>id</code> is already a static-sized array.</p>
| [
{
"answer_id": 74444948,
"author": "Alex Vergara",
"author_id": 14075508,
"author_profile": "https://Stackoverflow.com/users/14075508",
"pm_score": 0,
"selected": false,
"text": "const unsigned char"
},
{
"answer_id": 74444954,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 1,
"selected": false,
"text": "struct conf_t {\n const unsigned int a;\n const unsigned int b;\n const unsigned char id[ID_SIZE];\n};\n\nconf_t syntax_1 = { 10, 1, { 'a', 'b', 'c' }}; // an array needs its own {}\nconf_t syntax_2 = { 10, 1, \"hello\" }; // an array of char can be a string.\n // make sure you have room for the\n // null termination!\n"
},
{
"answer_id": 74445757,
"author": "Frodyne",
"author_id": 11829247,
"author_profile": "https://Stackoverflow.com/users/11829247",
"pm_score": 2,
"selected": true,
"text": "memcopy"
},
{
"answer_id": 74448914,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 0,
"selected": false,
"text": "struct conf_t { \n const unsigned int a;\n const unsigned int b;\n const unsigned char id[ID_SIZE];\n};\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5330938/"
] |
74,444,681 | <p>Existing Dataframe :</p>
<pre><code>Id Month Year scheduled completed
A Jan 2021 0 0
A Feb 2021 1 0
A mar 2021 0 0
B June 2021 0 1
B July 2021 0 1
B Aug 2021 0 1
B Sep 2021 0 1
C Nov 2021 1 0
C Dec 2021 1 0
C Jan 2022 1 0
C Feb 2022 1 0
</code></pre>
<p>Expected Dataframe :</p>
<pre><code> Id status
A defaulter
B non_defaulter
C defaulter
</code></pre>
<p>I am trying to create a status tag for each basis their activity. if for three consecutive Month if <strong>completed</strong> column remains 0 , that Id is to be tagged as "defaulter" else "non_defaulter"</p>
| [
{
"answer_id": 74444948,
"author": "Alex Vergara",
"author_id": 14075508,
"author_profile": "https://Stackoverflow.com/users/14075508",
"pm_score": 0,
"selected": false,
"text": "const unsigned char"
},
{
"answer_id": 74444954,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 1,
"selected": false,
"text": "struct conf_t {\n const unsigned int a;\n const unsigned int b;\n const unsigned char id[ID_SIZE];\n};\n\nconf_t syntax_1 = { 10, 1, { 'a', 'b', 'c' }}; // an array needs its own {}\nconf_t syntax_2 = { 10, 1, \"hello\" }; // an array of char can be a string.\n // make sure you have room for the\n // null termination!\n"
},
{
"answer_id": 74445757,
"author": "Frodyne",
"author_id": 11829247,
"author_profile": "https://Stackoverflow.com/users/11829247",
"pm_score": 2,
"selected": true,
"text": "memcopy"
},
{
"answer_id": 74448914,
"author": "Michaël Roy",
"author_id": 2430669,
"author_profile": "https://Stackoverflow.com/users/2430669",
"pm_score": 0,
"selected": false,
"text": "struct conf_t { \n const unsigned int a;\n const unsigned int b;\n const unsigned char id[ID_SIZE];\n};\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19303365/"
] |
74,444,688 | <p>I'm in the process of learning Python, and I'm trying to make a simple loop, for adding dirty prices, to my dataframe bond_df.</p>
<p>Days_left is a Series, bond_df is a pandas dataframe containing the closing prices used in the formula below.</p>
<p><em>If i run the command:</em></p>
<pre><code>days = days_left[1].days
</code></pre>
<p>I get an integer of size 1 with the value of 2, and this is exactly what I need. I need the value of days as integers, and without any other time-stamp on it (see the attached picture). So, I use ".days", so that I can extract the integer value of the days, and get rid of the time-stamp for hours and seconds etc.</p>
<p>Because of this, i figured I could then use this in a loop to construct my column of dirty-prices, in my df:</p>
<pre><code>for i, number in days_left:
days = days_left[i].days
bond_df['dirty_price'][i] = bond_df['closing_price'][i] + ((365 - days)/365)
</code></pre>
<p>However this does not work and returns the message:</p>
<p><em><strong>"TypeError: cannot unpack non-iterable Timedelta object"</strong></em></p>
<p>I then figured, that I could construct a loop using a range instead:</p>
<pre><code>for i in range(0, len(days_left)):
days = days_left[i].days
bond_df['dirty_price'][i] = bond_df['closing_price'][i] + ((365 - days)/365)
print(days, bond_df['dirty_price'])
</code></pre>
<p>This seem to work as intended.</p>
<p>But I would still like to find out, what I did wrong in the first instance.</p>
<p>Can somebody explain the difference between these two loops and why I cannot do as above?</p>
<p><em>All the best,</em>
Nic</p>
<p><a href="https://i.stack.imgur.com/ikxfz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ikxfz.png" alt="The value of days_left:" /></a></p>
| [
{
"answer_id": 74444781,
"author": "Iguananaut",
"author_id": 982257,
"author_profile": "https://Stackoverflow.com/users/982257",
"pm_score": 0,
"selected": false,
"text": "for i, number in days_left:\n"
},
{
"answer_id": 74444823,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\n\nDAYS_IN_YEAR = 365 # this actually isn't constant; adjust as needed\n\ndf = pd.DataFrame(\n {\n \"days_left\": [pd.Timedelta(days=1), pd.Timedelta(days=2), pd.Timedelta(days=3)],\n \"closing_price\": [1, 2, 3],\n }\n)\n\ndf[\"dirty_price\"] = df[\"closing_price\"] + (\n (DAYS_IN_YEAR - df[\"days_left\"].dt.total_seconds() / 86400)\n / DAYS_IN_YEAR\n # could also use df[\"days_left\"].dt.days here if hours minutes etc. don't matter\n)\n\ndf\n days_left closing_price dirty_price\n0 1 days 1 1.997260\n1 2 days 2 2.994521\n2 3 days 3 3.991781\n"
},
{
"answer_id": 74445095,
"author": "suvayu",
"author_id": 289784,
"author_profile": "https://Stackoverflow.com/users/289784",
"pm_score": 0,
"selected": false,
"text": "In [20]: dt = pd.timedelta_range(\"1 day\", \"5 day\", freq=\"1d\")\nIn [21]: type(dt)\nOut[21]: pandas.core.indexes.timedeltas.TimedeltaIndex\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10756363/"
] |
74,444,739 | <p><a href="https://i.stack.imgur.com/gRXvq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gRXvq.png" alt="[enter image description here](https://i.stack.imgur.com/M5896.png)." /></a></p>
<p>After successfully installed all of the aboves I was going to create react-native app using npx react-native init AwesomeProject comand and faced Your Ruby version is 2.6.8, but your Gemfile specified 2.7.5 error is also given in attached file. please check it and help me to suggest the way to solved.</p>
| [
{
"answer_id": 74444781,
"author": "Iguananaut",
"author_id": 982257,
"author_profile": "https://Stackoverflow.com/users/982257",
"pm_score": 0,
"selected": false,
"text": "for i, number in days_left:\n"
},
{
"answer_id": 74444823,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\n\nDAYS_IN_YEAR = 365 # this actually isn't constant; adjust as needed\n\ndf = pd.DataFrame(\n {\n \"days_left\": [pd.Timedelta(days=1), pd.Timedelta(days=2), pd.Timedelta(days=3)],\n \"closing_price\": [1, 2, 3],\n }\n)\n\ndf[\"dirty_price\"] = df[\"closing_price\"] + (\n (DAYS_IN_YEAR - df[\"days_left\"].dt.total_seconds() / 86400)\n / DAYS_IN_YEAR\n # could also use df[\"days_left\"].dt.days here if hours minutes etc. don't matter\n)\n\ndf\n days_left closing_price dirty_price\n0 1 days 1 1.997260\n1 2 days 2 2.994521\n2 3 days 3 3.991781\n"
},
{
"answer_id": 74445095,
"author": "suvayu",
"author_id": 289784,
"author_profile": "https://Stackoverflow.com/users/289784",
"pm_score": 0,
"selected": false,
"text": "In [20]: dt = pd.timedelta_range(\"1 day\", \"5 day\", freq=\"1d\")\nIn [21]: type(dt)\nOut[21]: pandas.core.indexes.timedeltas.TimedeltaIndex\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509618/"
] |
74,444,740 | <p>I would like the user to be able to select the start_date and automatically (without the user selecting anything) have the same value appear in the end date. Here is the code snippet I have extracted:</p>
<pre><code> <?php
$required = 'false';
$start_date_value = '';
if ( 'yes' == $settings['cwbf_start_date_required'] ) {
$required = 'true';
}
if ( isset( $_GET['start_date'] ) ) {
$start_date_value = sanitize_text_field( wp_unslash( $_GET['start_date'] ) );
}
$start_place_holder = __( 'Día de la reserva', 'codup-filters-for-woo-booking' );
?>
<input name="start_date" id="start_date" validate-required="<?php echo wp_kses_post( $required ); ?>" placeholder="<?php echo wp_kses_post( $start_place_holder ); ?>" autocomplete="off" min="<?php echo wp_kses_post( gmdate( 'Y-m-d' ) ); ?>" type="text" value="<?php echo wp_kses_post( $start_date_value ); ?>" />
</div>
<?php
if ( 'yes' == $settings['cwbf_end_date_enable'] ) {
?>
<div class="filter-row">
<label class="cwbf-fields-label">
<?php
if ( '' != $settings['cwbf_end_date_text'] ) {
echo wp_kses_post( $settings['cwbf_end_date_text'] );
} else {
esc_attr_e( 'End Date', 'codup-filters-for-woo-booking' );
}
?>
</label>
<?php
$required = 'false';
$end_date_value = '';
if ( 'yes' == $settings['cwbf_end_date_required'] ) {
$required = 'true';
}
if ( isset( $_GET['end_date'] ) ) {
$end_date_value = sanitize_text_field( wp_unslash( $_GET['end_date'] ) );
}
$end_place_holder = __( 'Place your End Date here', 'codup-filters-for-woo-booking' );
?>
<input name="end_date" id="end_date" validate-required="<?php echo wp_kses_post( $required ); ?>" placeholder="<?php echo wp_kses_post( $end_place_holder ); ?>" autocomplete="off" min="<?php echo wp_kses_post( gmdate( 'Y-m-d' ) ); ?>" type="text" value="<?php echo wp_kses_post( $end_date_value ); ?>" />
</div>
<?php
</code></pre>
<p>I am a newbie in html and php but I think this is a critical issue for my project, thank you very much :)</p>
| [
{
"answer_id": 74444781,
"author": "Iguananaut",
"author_id": 982257,
"author_profile": "https://Stackoverflow.com/users/982257",
"pm_score": 0,
"selected": false,
"text": "for i, number in days_left:\n"
},
{
"answer_id": 74444823,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\n\nDAYS_IN_YEAR = 365 # this actually isn't constant; adjust as needed\n\ndf = pd.DataFrame(\n {\n \"days_left\": [pd.Timedelta(days=1), pd.Timedelta(days=2), pd.Timedelta(days=3)],\n \"closing_price\": [1, 2, 3],\n }\n)\n\ndf[\"dirty_price\"] = df[\"closing_price\"] + (\n (DAYS_IN_YEAR - df[\"days_left\"].dt.total_seconds() / 86400)\n / DAYS_IN_YEAR\n # could also use df[\"days_left\"].dt.days here if hours minutes etc. don't matter\n)\n\ndf\n days_left closing_price dirty_price\n0 1 days 1 1.997260\n1 2 days 2 2.994521\n2 3 days 3 3.991781\n"
},
{
"answer_id": 74445095,
"author": "suvayu",
"author_id": 289784,
"author_profile": "https://Stackoverflow.com/users/289784",
"pm_score": 0,
"selected": false,
"text": "In [20]: dt = pd.timedelta_range(\"1 day\", \"5 day\", freq=\"1d\")\nIn [21]: type(dt)\nOut[21]: pandas.core.indexes.timedeltas.TimedeltaIndex\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509567/"
] |
74,444,758 | <p>I'm using styled components and have the following code</p>
<p><code>TopNav.tsx</code></p>
<pre><code>import {
Container,
SearchContainer,
SearchBox,
NotificationsContainer,
NotificationsDetails,
NotificationsSummary,
NotificationsCounter,
NotificationsItems,
NotificationsHeader,
NotificationsMarkReadText,
Notification,
NotificationTopper,
NotificationContent,
NotificationUnread,
NotificationUnreadDot,
NotificationsShowAll
} from '@/components/Layout/TopNav.style';
import Link from 'next/link';
import { MagnifyingGlassIcon, BellIcon } from '@heroicons/react/24/outline';
import { NOTIFICATIONS } from '@/constants/Notifications';
import { ThemeSwitch } from '@/components/ThemeSwitch/ThemeSwitch';
interface TopNavProps {
fullWidth: Boolean;
}
export const TopNav = ({ fullWidth }: TopNavProps) => {
return (
<Container>
<SearchContainer>
<SearchBox>
<form>
<button type="submit">
<MagnifyingGlassIcon />
</button>
<input type="text" placeholder="The everything search..." />
</form>
</SearchBox>
</SearchContainer>
<NotificationsContainer>
<NotificationsDetails>
<NotificationsSummary>
<BellIcon />
<NotificationsCounter>10</NotificationsCounter>
</NotificationsSummary>
<NotificationsItems>
<NotificationsHeader>
<NotificationsMarkReadText>
Mark all as read
</NotificationsMarkReadText>
<NotificationsShowAll>
<Link href="/notifications">Show all</Link>
</NotificationsShowAll>
</NotificationsHeader>
{NOTIFICATIONS.map(({ date, message, url }, index) => {
return (
<Notification key={`notify_${index}`}>
<NotificationContent>
<Link href={url} target="_blank">
<NotificationTopper>
<strong>{date}</strong>
<NotificationUnread>
<NotificationUnreadDot />
</NotificationUnread>
</NotificationTopper>
<p>{message}</p>
</Link>
</NotificationContent>
</Notification>
);
})}
</NotificationsItems>
</NotificationsDetails>
</NotificationsContainer>
<ThemeSwitch />
</Container>
);
};
</code></pre>
<p><code>TopNav.style.ts</code></p>
<pre><code>import styled from 'styled-components';
import mq from '@/styles/mq';
export const Container = styled.nav`
border-bottom: var(--border2px) solid var(--gray500);
background-color: var(--gray100);
width: ${(props) => props.fullWidth}? '100%' : calc(100% - 5rem);
padding: 1.06rem 0.5rem;
align-items: center;
position: fixed;
display: flex;
z-index: 999;
gap: 2rem;
right: 0;
top: 0;
@media screen and ${mq.minMedium} {
width: calc(100% - 15rem);
padding: 1.25rem 0.5rem;
}
`;
export const SearchContainer = styled.div`
flex: 12;
`;
...
</code></pre>
<p>As my styles are in a separate file to keep the code clean, how do I go about passing <code>fullWidth</code> into my style file? So I can dynamically set the width of my navigation.</p>
<p>I have took a look at the docs, and it seems all the examples are will all the code in the same file.</p>
| [
{
"answer_id": 74444833,
"author": "Haneen Mahdin",
"author_id": 17708926,
"author_profile": "https://Stackoverflow.com/users/17708926",
"pm_score": 0,
"selected": false,
"text": "<Container fullWidth={yourValue} />\n"
},
{
"answer_id": 74444841,
"author": "kind user",
"author_id": 6695924,
"author_profile": "https://Stackoverflow.com/users/6695924",
"pm_score": 2,
"selected": true,
"text": "fullWidth"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12370067/"
] |
74,444,773 | <pre><code>File_Name = "Invoice_Dmart"
Folder-Name = "c:\Documents\Scripts\Bills"
</code></pre>
<p>How to check if the specific filename exist in the "Folder-Name" with any extension, If Yes Get the full path in a variable.</p>
<p>Code i have been using:</p>
<pre><code>import os.path
if not os.path.Folder-Name(File_Name):
print("The File s% it's not created "%File_Name)
os.touch(File_Name)
print("The file s% has been Created ..."%File_Name)
</code></pre>
<p>Please Suggest the best possible way to solve it.</p>
| [
{
"answer_id": 74444906,
"author": "Abdul Niyas P M",
"author_id": 6699447,
"author_profile": "https://Stackoverflow.com/users/6699447",
"pm_score": 0,
"selected": false,
"text": "pathlib.Path"
},
{
"answer_id": 74445042,
"author": "PatrickCty",
"author_id": 7241805,
"author_profile": "https://Stackoverflow.com/users/7241805",
"pm_score": 0,
"selected": false,
"text": "import os\n\nfile_name = \"Invoice_Dmart\"\nfolder_name = \"c:\\Documents\\Scripts\\Bills\"\n\n# os.path.splitext() split filename and ext\n# os.listdir() list all files in the given dir\nfilenames_wo_ext = [os.path.splitext(elem)[0] for elem in os.listdir(folder_name)]\nif file_name not in filenames_wo_ext:\n print(\"The File %s it's not created \"% file_name)\n with open(file_name, 'w'):\n print(\"The file %s has been Created ...\"% file_name)\n\n"
},
{
"answer_id": 74445043,
"author": "Enrique Vilchez Campillejo",
"author_id": 12184303,
"author_profile": "https://Stackoverflow.com/users/12184303",
"pm_score": 2,
"selected": false,
"text": "Folder-Name"
},
{
"answer_id": 74514755,
"author": "JohnyCapo",
"author_id": 19335841,
"author_profile": "https://Stackoverflow.com/users/19335841",
"pm_score": 0,
"selected": false,
"text": "pathlib"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11050535/"
] |
74,444,850 | <p>I have a data-set of 3D points (x,y,z) projected onto a plane and i'd like to transform them into a simple 2D plot by looking at the points from an orthogonal direction to that plane. Any python explanation are much appreciated!</p>
<p><a href="https://i.stack.imgur.com/rCgWY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rCgWY.png" alt="Data-Set" /></a></p>
| [
{
"answer_id": 74444906,
"author": "Abdul Niyas P M",
"author_id": 6699447,
"author_profile": "https://Stackoverflow.com/users/6699447",
"pm_score": 0,
"selected": false,
"text": "pathlib.Path"
},
{
"answer_id": 74445042,
"author": "PatrickCty",
"author_id": 7241805,
"author_profile": "https://Stackoverflow.com/users/7241805",
"pm_score": 0,
"selected": false,
"text": "import os\n\nfile_name = \"Invoice_Dmart\"\nfolder_name = \"c:\\Documents\\Scripts\\Bills\"\n\n# os.path.splitext() split filename and ext\n# os.listdir() list all files in the given dir\nfilenames_wo_ext = [os.path.splitext(elem)[0] for elem in os.listdir(folder_name)]\nif file_name not in filenames_wo_ext:\n print(\"The File %s it's not created \"% file_name)\n with open(file_name, 'w'):\n print(\"The file %s has been Created ...\"% file_name)\n\n"
},
{
"answer_id": 74445043,
"author": "Enrique Vilchez Campillejo",
"author_id": 12184303,
"author_profile": "https://Stackoverflow.com/users/12184303",
"pm_score": 2,
"selected": false,
"text": "Folder-Name"
},
{
"answer_id": 74514755,
"author": "JohnyCapo",
"author_id": 19335841,
"author_profile": "https://Stackoverflow.com/users/19335841",
"pm_score": 0,
"selected": false,
"text": "pathlib"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11469965/"
] |
74,444,854 | <p>How to make an outer border around all cells in a row? Check the example in the bottom with the green border</p>
<p><a href="https://jsfiddle.net/Lgb91rhw/" rel="nofollow noreferrer">https://jsfiddle.net/Lgb91rhw/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background: red;
}
table {
table-layout: fixed;
border-collapse: separate;
border-spacing: 0 30px;
}
td {
padding: 15px 6px;
background: #fff;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
<td>some data row 1</td>
<td>some data row 1</td>
</tr>
<tr>
<td>some data row 2</td>
<td>some data row 2</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/kSJFU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kSJFU.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74445004,
"author": "Diego D",
"author_id": 1221208,
"author_profile": "https://Stackoverflow.com/users/1221208",
"pm_score": 0,
"selected": false,
"text": "border-collapse:separate;"
},
{
"answer_id": 74445011,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 3,
"selected": true,
"text": "body {\n background: red;\n}\n\ntable {\n table-layout: fixed;\n border-collapse: separate;\n border-spacing: 0 30px;\n}\n\ntd {\n padding: 15px 6px;\n background: #fff;\n}\n\ntr {\n outline: 2px solid #0f0;\n}"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/555222/"
] |
74,444,891 | <p>I'm writing C# code that runs Git commands via ProcessStartInfo.</p>
<p>I am aware in terms of syntax that I can run commands from the console in parallel by adding a single <code>&</code> character between them. For example:</p>
<p><code>echo "Hello world!" & echo "Goodbye world!"</code></p>
<p>Because these commands run in parallel they're asynchronous, meaning their output order is random.
The issue is that in my C# code I need to use the response from each command, and unfortunately there is no indicative output to tell me which output belongs to which command I ran.</p>
<p>Is there a way to tell which output came from which command?</p>
<p>For example, a way to echo specific text when the specific command has finished?</p>
| [
{
"answer_id": 74489131,
"author": "freedom2025",
"author_id": 10098858,
"author_profile": "https://Stackoverflow.com/users/10098858",
"pm_score": 0,
"selected": false,
"text": "echo \"Hello world!\" >1st.out 2>1st.err & \necho \"Goodbye world!\" >2nd.out 2>2nd.err &\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74444891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5547683/"
] |
74,445,008 | <p>How do I return more than one possible value? (Two sum problem: Determine if any two number inside an array sum to a number A)</p>
<p>I already figure out how to kind of solve the problem.</p>
<pre><code>def twoSum(arr, A):
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == A:
return(arr[i], arr[j])
print(twoSum([1,2,3,4],5))
</code></pre>
<p>However, I only manage to return the first possible value. Although (2, 3) is also correct.</p>
<pre><code>my output: (1, 4)
</code></pre>
<p>Is there a way to return multiple values such as</p>
<pre><code>intended output: [(1, 4), (2, 3)]
</code></pre>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74445055,
"author": "Szabolcs",
"author_id": 6337523,
"author_profile": "https://Stackoverflow.com/users/6337523",
"pm_score": 1,
"selected": true,
"text": "tuple"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12524160/"
] |
74,445,034 | <p>If I add a SingleChildScrollView in this Flutter screen, all my widgets disappear. I get a blank white screen. This is my code without scroll:</p>
<pre class="lang-dart prettyprint-override"><code>class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.only(top: 33),
child: Stack(
alignment: AlignmentDirectional.topEnd,
children: [
Positioned(
top: 0,
right: 0,
child: Image.asset("assets/images/top_right.png"), //Icon
),
Positioned(
top: -10,
right: 0,
child: Image.asset("assets/images/profile_picture.png"),
),
Container(
margin: const EdgeInsets.all(20),
child: Column(
children: [
Container(
margin: const EdgeInsets.all(15),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.only(),
child: const Text(
"Hi,",
style: TextStyle(
fontFamily: "poppin_regular",
fontSize: 27,
color: Colors.black),
)),
Container(
margin: const EdgeInsets.only(),
child: const Text(
"Jennifer",
style: TextStyle(
fontFamily: "poppin_semibold",
fontSize: 40,
color: Colors.black),
))
],
),
],
),
),
Flexible(
child: Container(
margin: const EdgeInsets.only(),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
margin: const EdgeInsets.only(top: 10),
elevation: 1,
shadowColor: Colors.black,
child: Row(
children: [
const SizedBox(
width: 305,
height: 50,
child: Padding(
padding:
EdgeInsets.only(left: 20, right: 20),
child: TextField(
keyboardType: TextInputType.multiline,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Search For Place",
hintStyle: TextStyle(
fontSize: 14,
color: Color.fromRGBO(
140, 140, 140, 100)),
),
),
), //Padding
),
Image.asset("assets/images/search.png")
],
),
),
const SizedBox(
width: double.infinity,
child: Text(
"What are you looking for",
style: TextStyle(
fontFamily: "poppin_semibold",
fontSize: 18),
)),
Container(
height: 133,
width: 345,
decoration: const BoxDecoration(
color: Color(0xffa3a3a3),
borderRadius: BorderRadius.all(
Radius.circular(10),
)),
child: InkWell(
onTap: () {},
child: Padding(
padding: const EdgeInsets.only(left: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.asset("assets/images/Group 509.png"),
const Text(
"Request a trip",
style: TextStyle(
color: Colors.black,
fontFamily: "poppin_semibold",
fontSize: 18),
),
Row(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: const [
Text(
"When new trip matches your travel ",
style: TextStyle(
color: Colors.black,
fontSize: 12,
fontFamily: "poppin_regular"),
),
Text(
"needs Get Notified",
style: TextStyle(
color: Colors.black,
fontSize: 12,
fontFamily: "poppin_regular"),
),
],
),
Container(
margin: const EdgeInsets.only(),
height: 71,
width: 90,
child: Image.asset(
"assets/images/Group 539.png"))
],
)
],
),
),
),
),
Container(
height: 133,
width: 345,
decoration: const BoxDecoration(
color: Color(0xffffdacb),
borderRadius: BorderRadius.all(
Radius.circular(10),
)),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PostYourTrip(),
));
},
child: Padding(
padding: const EdgeInsets.only(left: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.asset("assets/images/orangedots.png"),
const Text(
"Post your trip",
style: TextStyle(
color: Colors.black,
fontFamily: "poppin_semibold",
fontSize: 18),
),
Row(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Column(
children: const [
Text(
"Let others know about your plan so ",
style: TextStyle(
color: Colors.black,
fontSize: 12,
fontFamily: "poppin_regular"),
),
Text(
"they can join you on your journey ",
style: TextStyle(
color: Colors.black,
fontSize: 12,
fontFamily: "poppin_regular"),
),
],
),
Container(
margin: const EdgeInsets.only(),
height: 71,
width: 90,
child: Image.asset(
"assets/images/post_trip.png"))
],
)
],
),
),
),
),
Container(
height: 133,
width: 345,
decoration: const BoxDecoration(
color: Color(0xffbde4fe),
borderRadius: BorderRadius.all(
Radius.circular(10),
)),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FindTrip(),
));
},
child: Padding(
padding: const EdgeInsets.only(left: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.asset("assets/images/bluedot.png"),
const Text(
"Find your trip",
style: TextStyle(
color: Colors.black,
fontFamily: "poppin_semibold",
fontSize: 18),
),
Row(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: const [
Text(
"Find a ride and carpool anywhere in",
style: TextStyle(
color: Colors.black,
fontSize: 12,
fontFamily: "poppin_regular"),
),
Text(
"Pakistan",
style: TextStyle(
color: Colors.black,
fontSize: 12,
fontFamily: "poppin_regular"),
),
],
),
Container(
margin: const EdgeInsets.only(),
height: 71,
width: 90,
child: Image.asset(
"assets/images/postgroup.png"))
],
)
],
),
),
),
),
],
),
),
)
],
),
)
],
),
),
);
}
}
</code></pre>
<p>If I add a <code>SingleChildScrollView</code> in top after or before the padding widget, all the widgets disappear.</p>
<p>Please Check and provide me a solution. Thanks</p>
| [
{
"answer_id": 74445055,
"author": "Szabolcs",
"author_id": 6337523,
"author_profile": "https://Stackoverflow.com/users/6337523",
"pm_score": 1,
"selected": true,
"text": "tuple"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17863927/"
] |
74,445,052 | <p>I want to extract a list of lists from a <code>.txt</code> file. The data in the <code>.txt</code> file is given like this:</p>
<pre><code>[[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]],
[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]],
[[12,34.2,54.1,46.3,12.2],[9.2,63,23.7,42.6,15.2]]]
</code></pre>
<p>I want to store it in a list like:</p>
<pre><code>listA = [[[12,34.2,54.1,46.3,12.2], [9.2,63,23.7,42.6,15.2]], [[12,34.2,54.1,46.3,12.2], [9.2,63,23.7,42.6,15.2]],[[12,34.2,54.1,46.3,12.2], [9.2,63,23.7,42.6,15.2]]]
</code></pre>
<p>I tried using the <code>read()</code> function, but it reads as a <strong>string</strong>, and I can't seem to find out how to extract what I want.</p>
| [
{
"answer_id": 74445055,
"author": "Szabolcs",
"author_id": 6337523,
"author_profile": "https://Stackoverflow.com/users/6337523",
"pm_score": 1,
"selected": true,
"text": "tuple"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509747/"
] |
74,445,090 | <p>I'm trying rotate a div with a border.
The border has the same color as the background.
A very thin line appears between the border outline and the background.
Here is my code below.
I'm trying to get rid of the weird line.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: black;
}
div {
width: 50px;
height: 50px;
background-color: white;
border: 50px solid black;
transform: rotate(45deg);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code></pre>
</div>
</div>
</p>
<p>I tried multiple browsers.</p>
<p>I could fix this by using another div instead of a border, but I'm more interested in getting the border to work as expected.</p>
| [
{
"answer_id": 74445180,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 1,
"selected": false,
"text": "body {\n background-color: black;\n}\n\ndiv {\n width: 50px;\n height: 50px;\n background-color: white;\n border: 50px solid black;\n transform: rotate(45deg);\n outline-offset:-1px;\n outline: 2px solid black;\n}"
},
{
"answer_id": 74445273,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": "body {\n background-color: black;\n }\ndiv{\nwidth: 50px;\n height: 50px;\n background-color: white;\n transform: rotate(45deg);\n border: 0px;\n /* border: 50px solid black; */\n margin: 50px;\n}"
},
{
"answer_id": 74622354,
"author": "Rene van der Lende",
"author_id": 2015909,
"author_profile": "https://Stackoverflow.com/users/2015909",
"pm_score": 0,
"selected": false,
"text": "Z-axis"
},
{
"answer_id": 74622632,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 3,
"selected": true,
"text": "backface-visibility: hidden"
},
{
"answer_id": 74666819,
"author": "Yash Pathania",
"author_id": 20674315,
"author_profile": "https://Stackoverflow.com/users/20674315",
"pm_score": -1,
"selected": false,
"text": "body {\n background-color: black;\n }\ndiv{\nwidth: 50px;\n height: 50px;\n background-color: white;\n transform: rotate(45deg);\n border: 0px;\n /* border: 50px solid black; */\n margin: 50px;\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14861272/"
] |
74,445,098 | <p>Any Kong authentication plugin (key-auth, basic-auth) produces a response header "www-authenticate" with a realm="kong".
Is there a way to change the value of realm to something that doesn't indicate which API gateway I'm using?</p>
<p>I read the docs of the authentication plugins but there is no config value for that.</p>
| [
{
"answer_id": 74445180,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 1,
"selected": false,
"text": "body {\n background-color: black;\n}\n\ndiv {\n width: 50px;\n height: 50px;\n background-color: white;\n border: 50px solid black;\n transform: rotate(45deg);\n outline-offset:-1px;\n outline: 2px solid black;\n}"
},
{
"answer_id": 74445273,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": "body {\n background-color: black;\n }\ndiv{\nwidth: 50px;\n height: 50px;\n background-color: white;\n transform: rotate(45deg);\n border: 0px;\n /* border: 50px solid black; */\n margin: 50px;\n}"
},
{
"answer_id": 74622354,
"author": "Rene van der Lende",
"author_id": 2015909,
"author_profile": "https://Stackoverflow.com/users/2015909",
"pm_score": 0,
"selected": false,
"text": "Z-axis"
},
{
"answer_id": 74622632,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 3,
"selected": true,
"text": "backface-visibility: hidden"
},
{
"answer_id": 74666819,
"author": "Yash Pathania",
"author_id": 20674315,
"author_profile": "https://Stackoverflow.com/users/20674315",
"pm_score": -1,
"selected": false,
"text": "body {\n background-color: black;\n }\ndiv{\nwidth: 50px;\n height: 50px;\n background-color: white;\n transform: rotate(45deg);\n border: 0px;\n /* border: 50px solid black; */\n margin: 50px;\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2311578/"
] |
74,445,124 | <p><strong>1. Given A of size 4 × 3 and K = 1 with bird habitats at (0, 0), (2, 2) and (3, 1)
the function should return 3. Wind turbines can be built in three locations: (0, 2), (1, 1) and (2, 0).</strong>
In my code i have got an error of index out of range what should i can do to get my desired output.in the given case out put should be 3.</p>
<pre><code>def solution(Matrix, K):
row=len(Matrix)
col=len(Matrix[0])
K = K +1
for i in (row):
for j in (col):
if Matrix[i][j] == 1:
print(Matrix)
fun(Matrix,i,j, K),
res = 0,
for i in (row):
for j in (col):
if Matrix[i][j] == 0:
res += 1,
return res,
def fun(Matrix,i,j,k):
if k == 1:
if i-1 >= 0:
if Matrix[i-1][j]==0 or Matrix[i-1][j] >=2 and Matrix[i-1][j] <= k-1:
Matrix[i-1][j]=k,
fun(Matrix,i-1,j,k-1),
if i+1 < len(Matrix):
if Matrix[i+1][j] == 0 or Matrix[i+1][j] >=2 and Matrix[i+1][j] <= k-1:
Matrix[i+1][j]=k,
fun(Matrix,i+1,j,k-1)
if j-1 >= 0:
if Matrix[i][j-1]== 0 or Matrix[i][j+1] >= 2 and Matrix[i][j-1] <= k-1:
Matrix[i][j-1]=k,
fun(Matrix,i,j-1,k-1)
if j+1 < len(Matrix[0]):
if Matrix[i][j+1]== 0 or Matrix[i][j-1] >=2 and Matrix[i][j+1] <= k-1:
Matrix[i][j+1]=k,
fun(Matrix,i,j+1,k-1),
return
</code></pre>
| [
{
"answer_id": 74445254,
"author": "Noah",
"author_id": 14028308,
"author_profile": "https://Stackoverflow.com/users/14028308",
"pm_score": 1,
"selected": false,
"text": " row=len(Matrix),\n col=len(Matrix[0]),\n K = K +1;\n"
},
{
"answer_id": 74459586,
"author": "HASEEB UR REHMAN",
"author_id": 20509251,
"author_profile": "https://Stackoverflow.com/users/20509251",
"pm_score": 0,
"selected": false,
"text": " res = 0,\nfor i in range(len(Matrix)):\n for j in range(len(Matrix[0])):\n if Matrix[i][j] == 1:\n fun(Matrix,i,j, K),\n \nfor i in range(len(Matrix)): \n for j in range(len(Matrix[0])):\n if Matrix[i][j] == 0:\n res=res[0]+1,\n----------\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509251/"
] |
74,445,170 | <p>I'm trying to create an effect making the arrow icon visible incresing its height progressively on hover, and I'm trying to make a transition but I can't set this div not visible setting the div height to 0,</p>
<pre><code><div id="down-arrow-div" className="text-center down-arrow" >
<i className="fas fa-chevron-down"></i>
</div>
</code></pre>
<p>the css doesn't work</p>
<pre><code>.down-arrow-div{
height:0%;
}
</code></pre>
<p>I can hide the div with <code>visibility</code> but is a binary value and the effect is not the same</p>
| [
{
"answer_id": 74445246,
"author": "niorad",
"author_id": 5774727,
"author_profile": "https://Stackoverflow.com/users/5774727",
"pm_score": 1,
"selected": false,
"text": "overflow: hidden;"
},
{
"answer_id": 74445285,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 2,
"selected": true,
"text": "#down-arrow-div {\n width: 5rem;\n height: 5rem;\n border: 1px solid gray;\n display: grid;\n place-items: center;\n}\n\n#down-arrow-div>i {\n opacity: 0;\n font-size: 1rem;\n transition: all 0.5s;\n}\n\n#down-arrow-div:hover>i {\n opacity: 1;\n font-size: 2rem;\n}"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19939168/"
] |
74,445,184 | <p>I received 1 challenge through the interview test.
The requirement of the test is to build a search engine that source data from a txt file, and every time the user enters a word, it will return the results.</p>
<ul>
<li><p>The second requirement is:</p>
<p>Given a single word x, update the search corpus with x. The new word x should immediately be
queryable.</p>
</li>
<li><p>3rd requirement is:</p>
<p>Given a single word y, remove the most similar word to y in the corpus from further search results.</p>
</li>
</ul>
<p>I have never created a search engine before.</p>
<p>How can i create it with NodeJs and what is the meaning of the 2nd and 3rd requirements?</p>
<p>Thanks!</p>
| [
{
"answer_id": 74445246,
"author": "niorad",
"author_id": 5774727,
"author_profile": "https://Stackoverflow.com/users/5774727",
"pm_score": 1,
"selected": false,
"text": "overflow: hidden;"
},
{
"answer_id": 74445285,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 2,
"selected": true,
"text": "#down-arrow-div {\n width: 5rem;\n height: 5rem;\n border: 1px solid gray;\n display: grid;\n place-items: center;\n}\n\n#down-arrow-div>i {\n opacity: 0;\n font-size: 1rem;\n transition: all 0.5s;\n}\n\n#down-arrow-div:hover>i {\n opacity: 1;\n font-size: 2rem;\n}"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16864718/"
] |
74,445,188 | <p>I configured system and user pool on Azure AKS instances. I follow this guide:</p>
<p><a href="https://learn.microsoft.com/en-us/azure/aks/use-system-pools?tabs=azure-cli#system-and-user-node-pools" rel="nofollow noreferrer">Microrosft Guide</a></p>
<p>before the activity we only had system type pools for applications and system pods as well.</p>
<p>I did the following steps:</p>
<ul>
<li><p>creation of a system type pool and set of the following taint "CriticalAddonsOnly = true: NoSchedule" (to avoid deployment on the system pool for application microservices)</p>
</li>
<li><p>conversion of old pools from system to users</p>
</li>
<li><p>restart the following deployments:</p>
<p>gatekeeper-system:</p>
<ul>
<li>gatekeeper-audit</li>
<li>gatekeeper-controller</li>
</ul>
<p>kube-system:</p>
<ul>
<li>coredns</li>
<li>coredns-autoscaler</li>
<li>metrics-server</li>
<li>azure-policy</li>
<li>azure-policy-webhook</li>
<li>konnectivity-agent</li>
<li>ama-logs-rs</li>
</ul>
</li>
</ul>
<p>to allow the scheduling of system pods also on the pool system since they are not automatically scheduled after pool creation.</p>
<p>Now i'm noticing that the system pods have now been scheduled on the pool system as well but I keep seeing the same pods on all other nodes. Even if I brutally delete them from the user pools, they are immediately redeployed on them. Is the behavior correct? Logically if I have a pool system all pods should only be on that pool and none on the user pool?</p>
<p>Thanks</p>
| [
{
"answer_id": 74445246,
"author": "niorad",
"author_id": 5774727,
"author_profile": "https://Stackoverflow.com/users/5774727",
"pm_score": 1,
"selected": false,
"text": "overflow: hidden;"
},
{
"answer_id": 74445285,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 2,
"selected": true,
"text": "#down-arrow-div {\n width: 5rem;\n height: 5rem;\n border: 1px solid gray;\n display: grid;\n place-items: center;\n}\n\n#down-arrow-div>i {\n opacity: 0;\n font-size: 1rem;\n transition: all 0.5s;\n}\n\n#down-arrow-div:hover>i {\n opacity: 1;\n font-size: 2rem;\n}"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13222044/"
] |
74,445,207 | <p>I have a problem about getting jwt token from one service and use it in the test method of one service.</p>
<p>I tried to write <strong>JUnit Controller test</strong> in payment, product and order service in my spring boot microservice example. After I defined auth service to handle with creating user and login with <strong>jwt</strong> token and defined api gateway to use <strong>JWTFilter</strong>, it is required to define <strong>bearer token</strong> for each request of each test request method.</p>
<p>Normally, it works but I have to get jwt token and use it but I have no idea how to get it?</p>
<p>Here is an one test method of PaymentControllerTest shown below. As you can see, there is no defination of <strong>Authorization Bearer</strong>. How can I define it?</p>
<pre><code>@Test
@DisplayName("Place Order -- Success Scenario")
void test_When_placeOrder_DoPayment_Success() throws Exception {
OrderRequest orderRequest = getMockOrderRequest();
String jwt = getJWTTokenForRoleUser();
MvcResult mvcResult
= mockMvc.perform(MockMvcRequestBuilders.post("/order/placeorder")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.header("Authorization", "Bearer " + jwt)
.content(objectMapper.writeValueAsString(orderRequest)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String orderId = mvcResult.getResponse().getContentAsString();
Optional<Order> order = orderRepository.findById(Long.valueOf(orderId));
assertTrue(order.isPresent());
Order o = order.get();
assertEquals(Long.parseLong(orderId), o.getId());
assertEquals("PLACED", o.getOrderStatus());
assertEquals(orderRequest.getTotalAmount(), o.getAmount());
assertEquals(orderRequest.getQuantity(), o.getQuantity());
}
</code></pre>
<p>Here are methods regarding the jwt token process</p>
<pre><code>private String getJWTTokenForRoleUser(){
var loginRequest = new LoginRequest("User1","user1");
String jwt = jwtUtils.generateJwtToken(loginRequest.getUsername());
return jwt;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginRequest {
private String username;
private String password;
}
</code></pre>
<p>Here is the jwtutil class shown below</p>
<pre><code>@Component
public class JwtUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(JwtUtils.class);
@Value("${jwt.secret}")
private String jwtSecret;
@Value("${jwt.expireMs}")
private int jwtExpirationMs;
public String generateJwtToken(String username) {
return generateTokenFromUsername(username);
}
public String generateTokenFromUsername(String username) {
return Jwts.builder().setSubject(username).setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
.signWith(SignatureAlgorithm.HS512, jwtSecret).compact();
}
}
</code></pre>
<p>To run the app,
<strong>1 )</strong> Run Service Registery (Eureka Server)</p>
<p><strong>2 )</strong> Run config server</p>
<p><strong>3 )</strong> Run zipkin and redis through these commands shown below on docker</p>
<pre><code>docker run -d -p 9411:9411 openzipkin/zipkin
docker run -d --name redis -p 6379:6379 redis
</code></pre>
<p><strong>4 )</strong> Run api gateway</p>
<p><strong>5 )</strong> Run auth service,product service,order service and payment service</p>
<p><strong>Edited</strong> (I defined all properites in application-test.yaml but they couldn't be fetched from OrderControllerTest)</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'jwt.secret' in value "${jwt.secret}"
</code></pre>
<p>Here is the repo : <a href="https://github.com/Rapter1990/microservicecoursedailybuffer" rel="nofollow noreferrer">Link</a></p>
| [
{
"answer_id": 74445246,
"author": "niorad",
"author_id": 5774727,
"author_profile": "https://Stackoverflow.com/users/5774727",
"pm_score": 1,
"selected": false,
"text": "overflow: hidden;"
},
{
"answer_id": 74445285,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 2,
"selected": true,
"text": "#down-arrow-div {\n width: 5rem;\n height: 5rem;\n border: 1px solid gray;\n display: grid;\n place-items: center;\n}\n\n#down-arrow-div>i {\n opacity: 0;\n font-size: 1rem;\n transition: all 0.5s;\n}\n\n#down-arrow-div:hover>i {\n opacity: 1;\n font-size: 2rem;\n}"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19721745/"
] |
74,445,221 | <pre><code> "message": "Call to a member function find() on array",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
</code></pre>
<p>How do I get the id parameter from the array below: When i pass the parameter 1 i want to fetch only first element when id is 2 I fetch item 2 of array</p>
<pre><code> public function payments($id){
$data = [
['id' => 1, 'amount' => '22000', 'name' => 'ken'],
['id' => 2, 'amount' => '24000', 'name' => 'ken'],
['id' => 3, 'amount' => '26000', 'name' => 'ken'],
['id' => 4, 'amount' => '2000', 'name' => 'tom'],
];
return $data->find($id);
}
</code></pre>
| [
{
"answer_id": 74445311,
"author": "Matthew Bradley",
"author_id": 20320967,
"author_profile": "https://Stackoverflow.com/users/20320967",
"pm_score": 2,
"selected": false,
"text": "array_search"
},
{
"answer_id": 74447791,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 1,
"selected": false,
"text": "public function payments($id){\n $data = [\n ['id' => 1, 'amount' => '22000', 'name' => 'ken'],\n ['id' => 2, 'amount' => '24000', 'name' => 'ken'],\n ['id' => 3, 'amount' => '26000', 'name' => 'ken'],\n ['id' => 4, 'amount' => '2000', 'name' => 'tom'],\n ];\n $data = collect($data);\n return $data->where('id', $id)->first();\n}\n"
},
{
"answer_id": 74456717,
"author": "penina kinanu",
"author_id": 20295565,
"author_profile": "https://Stackoverflow.com/users/20295565",
"pm_score": 1,
"selected": true,
"text": "public function payments($id){\n $data = [\n ['id' => 1, 'amount' => '22000', 'name' => 'ken'],\n ['id' => 2, 'amount' => '24000', 'name' => 'ken'],\n ['id' => 3, 'amount' => '26000', 'name' => 'ken'],\n ['id' => 4, 'amount' => '2000', 'name' => 'tom'],\n ];\n $data = collect($data);\n return $data->where('id', $id)->all();\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20295565/"
] |
74,445,264 | <p>This example is from the documentation of HttpUrlConnection:</p>
<pre class="lang-java prettyprint-override"><code>URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
finally {
urlConnection.disconnect();
}
</code></pre>
<p>The documentation says:</p>
<blockquote>
<p>Once the response body has been read, the HttpURLConnection should be closed by calling disconnect().</p>
</blockquote>
<p>I tried use the Java class to load an image in a functional style:</p>
<pre class="lang-kotlin prettyprint-override"><code>fun fetch (url: String): ImageBitmap =
URL(url)
.openConnection()
.also { it.setRequestProperty (authorization.header, authorization.basicauth()) }
.getInputStream()
.buffered()
.use { BitmapFactory.decodeStream(it) }
.asImageBitmap()
</code></pre>
<p>Now I am wondering how to add the <code>disconnect</code> call?</p>
<p>I want to achieve this:</p>
<pre class="lang-kotlin prettyprint-override"><code>fun fetch (url: String): ImageBitmap {
var connection: HttpURLConnection? = null
return try {
URL(url)
.openConnection()
.also { it.setRequestProperty(authorization.header, authorization.basicauth()) }
.also { connection = it as HttpURLConnection }
.getInputStream()
.buffered()
.use { BitmapFactory.decodeStream(it) }
.asImageBitmap()
} finally {
connection?.disconnect()
}
}
</code></pre>
<p>But in a less ugly manner.</p>
| [
{
"answer_id": 74445311,
"author": "Matthew Bradley",
"author_id": 20320967,
"author_profile": "https://Stackoverflow.com/users/20320967",
"pm_score": 2,
"selected": false,
"text": "array_search"
},
{
"answer_id": 74447791,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 1,
"selected": false,
"text": "public function payments($id){\n $data = [\n ['id' => 1, 'amount' => '22000', 'name' => 'ken'],\n ['id' => 2, 'amount' => '24000', 'name' => 'ken'],\n ['id' => 3, 'amount' => '26000', 'name' => 'ken'],\n ['id' => 4, 'amount' => '2000', 'name' => 'tom'],\n ];\n $data = collect($data);\n return $data->where('id', $id)->first();\n}\n"
},
{
"answer_id": 74456717,
"author": "penina kinanu",
"author_id": 20295565,
"author_profile": "https://Stackoverflow.com/users/20295565",
"pm_score": 1,
"selected": true,
"text": "public function payments($id){\n $data = [\n ['id' => 1, 'amount' => '22000', 'name' => 'ken'],\n ['id' => 2, 'amount' => '24000', 'name' => 'ken'],\n ['id' => 3, 'amount' => '26000', 'name' => 'ken'],\n ['id' => 4, 'amount' => '2000', 'name' => 'tom'],\n ];\n $data = collect($data);\n return $data->where('id', $id)->all();\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402322/"
] |
74,445,287 | <p>I use numpy to do image processing, I wanted to switch the image to black and white and for that I did the calculation in each cell to see the luminosity, but if i want to show it i have to transform a 2d array into 2d array with 3 times the same value</p>
<p>for exemple i have this:</p>
<pre><code>a = np.array([[255,0][0,255]])
#into
b = np.array([[[255,255,255],[0,0,0]],[[0,0,0],[255,255,255]]])
</code></pre>
<p>I've been searching for a while but i don't find anything to help</p>
<p>PS: sorry if i have made some mistake with my English.</p>
| [
{
"answer_id": 74445311,
"author": "Matthew Bradley",
"author_id": 20320967,
"author_profile": "https://Stackoverflow.com/users/20320967",
"pm_score": 2,
"selected": false,
"text": "array_search"
},
{
"answer_id": 74447791,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 1,
"selected": false,
"text": "public function payments($id){\n $data = [\n ['id' => 1, 'amount' => '22000', 'name' => 'ken'],\n ['id' => 2, 'amount' => '24000', 'name' => 'ken'],\n ['id' => 3, 'amount' => '26000', 'name' => 'ken'],\n ['id' => 4, 'amount' => '2000', 'name' => 'tom'],\n ];\n $data = collect($data);\n return $data->where('id', $id)->first();\n}\n"
},
{
"answer_id": 74456717,
"author": "penina kinanu",
"author_id": 20295565,
"author_profile": "https://Stackoverflow.com/users/20295565",
"pm_score": 1,
"selected": true,
"text": "public function payments($id){\n $data = [\n ['id' => 1, 'amount' => '22000', 'name' => 'ken'],\n ['id' => 2, 'amount' => '24000', 'name' => 'ken'],\n ['id' => 3, 'amount' => '26000', 'name' => 'ken'],\n ['id' => 4, 'amount' => '2000', 'name' => 'tom'],\n ];\n $data = collect($data);\n return $data->where('id', $id)->all();\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17399120/"
] |
74,445,288 | <p>I'm working on understanding template parameter pack expansion in C++. For demo purposes, I wanted to write a function that prints human readable names of types used in a signature (any signature - that's where the variadic template comes in).</p>
<pre><code>#include <boost/type_index.hpp>
std::string SignatureToString()
{
return std::string();
}
template<typename Arg1, typename... Args>
std::string SignatureToString(const Arg1&, Args&&... args)
{
std::string strRetVal = boost::typeindex::type_id<Arg1>().pretty_name();
std::string strRemainingSignature = SignatureToString(args...); // expanding parameters works
if (!strRemainingSignature.empty())
{
strRetVal = strRetVal + ", " + strRemainingSignature;
}
return strRetVal;
}
class cDog {/* ... */};
int main(int /*argc*/, char* /*argv*/[])
{
int i(0);
std::string str;
//cDog someDog("Harry"); // don't want to construct this dummy object!
std::cout << "GetSignature(): '" << SignatureToString() << "'" << std::endl;
std::cout << "GetSignature(int): '" << SignatureToString(i) << "'" << std::endl;
std::cout << "GetSignature(std::string): '" << SignatureToString(str) << "'" << std::endl;
//std::cout << "GetSignature(cDog): '" << SignatureToString(someDog) << "'" << std::endl;
std::cout << "GetSignature(int, std::string): '" << SignatureToString(i, str) << "'" << std::endl;
//std::cout << "GetSignature(int, std::string, cDog): '" << SignatureToString(i, str, someDog) << "'" << std::endl;
}
</code></pre>
<p>The above example works. Since boost::typeindex::type_id does not really need the passed variable of type Arg1 (and some types - such as cDog - might not or not easily be dummy-constructable), I thought I could change the implementation to the one below (same template arguments, but no passed parameter pack of those types) and recursively call the template by expanding the pack of <strong>types</strong> instead of the pack of <strong>parameters</strong>. I read <a href="https://en.cppreference.com/w/cpp/language/parameter_pack" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/language/parameter_pack</a> section "Template argument lists" to mean that this should be possible, but my compiler (vc141) gives me error C2672 (no matching signature found).</p>
<p>edit: The error description apparently has to do with template resolution, but I don't see the applicability to my problem. <a href="https://learn.microsoft.com/en-gb/cpp/error-messages/compiler-errors-2/compiler-error-c2672?view=msvc-150" rel="nofollow noreferrer">https://learn.microsoft.com/en-gb/cpp/error-messages/compiler-errors-2/compiler-error-c2672?view=msvc-150</a></p>
<pre><code>template<typename Arg1, typename... Args>
std::string SignatureToString()
{
std::string strRetVal = boost::typeindex::type_id<Arg1>().pretty_name(); // this line apparently still works (makes sense)
std::string strRemainingSignature = SignatureToString<Args...>(); // expanding type pack does not work (...?)
if (!strRemainingSignature.empty())
{
strRetVal = strRetVal + ", " + strRemainingSignature;
}
return strRetVal;
}
int main(int /*argc*/, char* /*argv*/[])
{
std::cout << "GetSignature(): '" << SignatureToString() << "'" << std::endl;
std::cout << "GetSignature(int): '" << SignatureToString<int>() << "'" << std::endl;
std::cout << "GetSignature(std::string): '" << SignatureToString<std::string>() << "'" << std::endl;
return 0;
}
</code></pre>
<p>What am I doing wrong here?</p>
| [
{
"answer_id": 74445350,
"author": "Daniel",
"author_id": 362589,
"author_profile": "https://Stackoverflow.com/users/362589",
"pm_score": 3,
"selected": false,
"text": "std::string SignatureToString()\n"
},
{
"answer_id": 74445438,
"author": "Daniel",
"author_id": 2424669,
"author_profile": "https://Stackoverflow.com/users/2424669",
"pm_score": 0,
"selected": false,
"text": "// Catch call with zero args\nstd::string SignatureToString()\n{\n return std::string();\n}\n\n// Catch call with exactly one arg\ntemplate <typename Arg1>\nstd::string SignatureToString()\n{\n return boost::typeindex::type_id<Arg1>().pretty_name();\n}\n\n// Catch all other cases\ntemplate<typename Arg1, typename Arg2, typename... Args>\nstd::string SignatureToString()\n{\n std::string strRetVal = boost::typeindex::type_id<Arg1>().pretty_name();\n std::string strRemainingSignature = SignatureToString<Arg2, Args...>();\n if (!strRemainingSignature.empty())\n {\n strRetVal = strRetVal + \", \" + strRemainingSignature;\n }\n return strRetVal;\n}\n"
},
{
"answer_id": 74445603,
"author": "joergbrech",
"author_id": 12173376,
"author_profile": "https://Stackoverflow.com/users/12173376",
"pm_score": 1,
"selected": false,
"text": "if constexpr"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2424669/"
] |
74,445,333 | <p>I use a timer to count down. I feed seconds into the timer and the countdown begins. The timer works, but the problem is that when I change the page, I get an error that the timer will continue to work. Although I'm already on another page. I can't figure out how to disable it when changing the page.
My code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>class _OutfitsMasterNewWidgetState extends State<OutfitsMasterNewWidget> {
late FocusNode _searchFocus;
late TextEditingController _searchController;
final String? errorText = '';
final interval = const Duration(seconds: 1);
int currentSeconds = 0;
String setStatus(int time) {
if (time == 0) {
return '0';
} else {
int timerMaxSeconds = time;
if (timerMaxSeconds - currentSeconds < 0) {
return '0';
} else {
return '${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')}: '
'${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')}';
}
}
}
void startTimeout() {
var duration = interval;
Timer.periodic(duration, (timer) {
setState(() {
currentSeconds = timer.tick;
});
});
}
@override
void initState() {
_searchFocus = FocusNode();
_searchController = TextEditingController();
super.initState();
startTimeout();
BlocProvider.of<OutfitsNewBloc>(context).add(
OutfitsNewInitialEvent(
startInitial: true,
),
);
}
@override
void dispose() {
_searchFocus.dispose();
_searchController.dispose();
startTimeout();
super.dispose();
}</code></pre>
</div>
</div>
</p>
<p>My Errore
<a href="https://i.stack.imgur.com/FJpSb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FJpSb.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74445410,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": false,
"text": "mounted"
},
{
"answer_id": 74445500,
"author": "Dev",
"author_id": 1834941,
"author_profile": "https://Stackoverflow.com/users/1834941",
"pm_score": 1,
"selected": false,
"text": "Timer? periodicTimer;\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11202504/"
] |
74,445,354 | <p>I have two dataframes, <code>df_1</code> and <code>df_2</code>. Both of them have <code>datetimeindex</code>, starting in <code>2022-01-01</code> and goes until <code>2022-08-14</code>. The first one, <code>df_1</code>, has hourly measurements, and the second one, <code>df_2</code>, has daily measurements.</p>
<pre><code>df_1 = pd.DataFrame(np.random.rand(5424, 1),
columns=["Random"],
index=pd.date_range(start="20220101000000", end="20220814230000", freq='H'))
df_2 = pd.DataFrame(np.random.randint(0, 3, size=226),
columns=["Random"],
index=pd.date_range(start="20220101", end="20220814", freq='D'))
</code></pre>
<p>How could I drop all rows from <code>df_1</code> in which the same day of <code>df_2</code> has a measurement different from zero? For example, if the first two days of January have 6 and 7 as measurements, I would need to drop all 48 hours of those days in <code>df_1</code>.</p>
| [
{
"answer_id": 74445377,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "merge_asof"
},
{
"answer_id": 74457691,
"author": "Marble_gold",
"author_id": 15423701,
"author_profile": "https://Stackoverflow.com/users/15423701",
"pm_score": 0,
"selected": false,
"text": "df_1"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12297666/"
] |
74,445,359 | <p>I have a Qml Canvas Item where in, the height of canvas item keeps varying based on the input dynamically. Below is my code</p>
<pre><code>Item {
id: barGraph
property int highestRange: 200
property int rangeVal: (RangeModel.rangeValue === "---") ? highestRange : RangeModel.rangeValue
property int totalHeight: 450
property int canvasHeight: (rangeVal * totalHeight) / highestRange
height: 700
width: 500
x: 120
y: 145
Canvas {
id: mycanvas
height: canvasHeight
width: 16
onPaint: {
var context = getContext("2d");
var startX = mycanvas.x;
var startY = mycanvas.y;
context.lineWidth = 0.5;
context.strokeStyle = "white";
context.beginPath();
context.moveTo(startX, startY);
context.lineTo(startX,(mycanvas.height - 10));
context.lineTo(mycanvas.width, mycanvas.height);
context.lineTo(mycanvas.width, startY + 10);
context.lineTo(mycanvas.width / 2, startY);
context.closePath(); // base drawn automatically
context.fill();
context.stroke();
}
}}
</code></pre>
<p>The output of this code look like this :</p>
<p><a href="https://i.stack.imgur.com/pJDOm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pJDOm.png" alt="canvas with full height" /></a></p>
<p>The problem with this code is, whenever the height of the canvas changes dynamically it actually resizes from the below position as shown in the image</p>
<p><a href="https://i.stack.imgur.com/U07QB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U07QB.jpg" alt="resized canvas image" /></a>.</p>
<p>I actually need this to be resized from the Y top position and keeping the below position unmovable which I am unable to achieve through this code.</p>
<p>Any support is much appreciated here.</p>
| [
{
"answer_id": 74445377,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "merge_asof"
},
{
"answer_id": 74457691,
"author": "Marble_gold",
"author_id": 15423701,
"author_profile": "https://Stackoverflow.com/users/15423701",
"pm_score": 0,
"selected": false,
"text": "df_1"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3098361/"
] |
74,445,365 | <p>The problem is exactly the same as listed <a href="https://stackoverflow.com/questions/58480179/identify-discrete-events-based-on-a-time-difference-of-30-minutes-or-more-in-r">here </a> albeit in python not R. What is the best solution to handle this in python?</p>
<p>Unclear what to proceed with next. It seems there is some way to get tidyverse in python but I am wondering if there is a way to do this with standard python packages?</p>
<p>Thanks</p>
<p><strong>See issue from other question described here:</strong></p>
<p>I have a dataframe of timestamps when an individual animal (ID) is detected in specific locations. Here is an example of the data:</p>
<pre><code>
timestampUTC location ID
2017-10-02 19:23:27 JB12 A69-1601-47272
2017-10-02 19:26:48 JB12 A69-1601-47272
2017-10-02 19:27:23 JB12 A69-1601-47272
2017-10-02 19:31:46 JB12 A69-1601-47272
2017-10-02 23:52:15 JB12 A69-1601-47272
2017-10-02 23:53:26 JB12 A69-1601-47272
2017-10-02 23:55:13 JB12 A69-1601-47272
2017-10-03 19:53:50 JB13 A69-1601-47272
2017-10-03 19:55:23 JB13 A69-1601-47272
2017-10-03 19:58:26 JB13 A69-1601-47272
2017-10-04 13:15:13 JB12 A69-1601-47280
2017-10-04 13:16:42 JB12 A69-1601-47280
2017-10-04 13:21:39 JB12 A69-1601-47280
2017-10-04 19:34:54 JB12 A69-1601-47280
2017-10-04 19:55:28 JB12 A69-1601-47280
2017-10-04 20:08:23 JB12 A69-1601-47280
2017-10-04 20:21:43 JB12 A69-1601-47280
2017-10-05 04:55:48 JB13 A69-1601-47280
2017-10-05 04:57:04 JB13 A69-1601-47280
2017-10-05 05:18:40 JB13 A69-1601-47280
2017-10-07 21:24:19 JB13 A69-1601-47280
2017-10-07 21:25:36 JB13 A69-1601-47280
2017-10-07 21:29:25 JB13 A69-1601-47280
</code></pre>
<p>My real dataframe is almost 200,000 lines long and has 4 different locations and 13 different IDs.</p>
<p>I want to sort these into discrete events (ID at location) with start and end times based on the timestampUTC column, with the events ending at the timestampUTC when the next detection for that ID in that location is more than half an hour later. The next event begins at the next datetime.</p>
<p>Using the example data above, I would want to generate another dataframe that looks something like this:</p>
<pre><code>
ID location event start event end
A69-1601-47272 JB12 2017-10-02 19:23:27 2017-10-02 19:31:46
A69-1601-47272 JB12 2017-10-02 23:52:15 2017-10-02 23:55:13
A69-1601-47272 JB13 2017-10-03 19:53:50 2017-10-03 19:58:26
A69-1601-47280 JB12 2017-10-04 13:15:13 2017-10-04 13:21:39
A69-1601-47280 JB12 2017-10-04 19:34:54 2017-10-04 20:21:43
A69-1601-47280 JB13 2017-10-05 04:55:48 2017-10-05 05:18:40
A69-1601-47280 JB13 2017-10-07 21:24:19 2017-10-07 21:29:25
</code></pre>
<p>If an ID was detected at a location it gives the ID, location, and the start and end of its time there.</p>
<p>For example, you can see that there are 2 discrete events for ID 47272 at location JB12 that occur on the same day (2017-10-02) but the difference between the end of the first event and the start of the second is >30 min (~4 hrs and 20 mins) so they're separate events.</p>
<p>I would add what code I have tried but I don't know where to start with tidyverse and would prefer to do this in python.</p>
<p>Thanks in advance!</p>
<p><strong>And see solution in R here:</strong></p>
<p>Here is an option</p>
<pre><code>
library(tidyverse)
df %>%
mutate(
timestampUTC = as.POSIXct(timestampUTC),
diff = c(0, diff(timestampUTC) / 60),
grp = cumsum(diff > 30)) %>%
group_by(grp) %>%
summarise(
ID = first(ID),
location = first(location),
`event start` = first(timestampUTC),
`event end` = last(timestampUTC))
## A tibble: 7 x 5
# grp ID location `event start` `event end`
# <int> <fct> <fct> <dttm> <dttm>
#1 0 A69-1601-47272 JB12 2017-10-02 19:23:27 2017-10-02 19:31:46
#2 1 A69-1601-47272 JB12 2017-10-02 23:52:15 2017-10-02 23:55:13
#3 2 A69-1601-47272 JB13 2017-10-03 19:53:50 2017-10-03 19:58:26
#4 3 A69-1601-47280 JB12 2017-10-04 13:15:13 2017-10-04 13:21:39
#5 4 A69-1601-47280 JB12 2017-10-04 19:34:54 2017-10-04 20:21:43
#6 5 A69-1601-47280 JB13 2017-10-05 04:55:48 2017-10-05 05:18:40
#7 6 A69-1601-47280 JB13 2017-10-07 21:24:19 2017-10-07 21:29:25
</code></pre>
<p>I've kept some some of the intermediate steps (columns) to help with readability and understanding. In short, we convert timestamps to POSIXct, then calculate time differences in minutes between successive timestamps with diff, create groups of observations based on whether the next timestamp is > 30 minutes away. The rest is grouping by grp and summarising entries from relevant columns.</p>
<p>The same, more succinct (perhaps at the expense of readability)</p>
<pre><code>df %>%
group_by(grp = cumsum(c(0, diff(as.POSIXct(timestampUTC)) / 60) > 30)) %>%
summarise(
ID = first(ID),
location = first(location),
`event start` = first(timestampUTC),
`event end` = last(timestampUTC)) %>%
select(-grp)
</code></pre>
<p><strong>Sample data</strong></p>
<pre><code>df <- read.table(text =
"timestampUTC location ID
'2017-10-02 19:23:27' JB12 A69-1601-47272
'2017-10-02 19:26:48' JB12 A69-1601-47272
'2017-10-02 19:27:23' JB12 A69-1601-47272
'2017-10-02 19:31:46' JB12 A69-1601-47272
'2017-10-02 23:52:15' JB12 A69-1601-47272
'2017-10-02 23:53:26' JB12 A69-1601-47272
'2017-10-02 23:55:13' JB12 A69-1601-47272
'2017-10-03 19:53:50' JB13 A69-1601-47272
'2017-10-03 19:55:23' JB13 A69-1601-47272
'2017-10-03 19:58:26' JB13 A69-1601-47272
'2017-10-04 13:15:13' JB12 A69-1601-47280
'2017-10-04 13:16:42' JB12 A69-1601-47280
'2017-10-04 13:21:39' JB12 A69-1601-47280
'2017-10-04 19:34:54' JB12 A69-1601-47280
'2017-10-04 19:55:28' JB12 A69-1601-47280
'2017-10-04 20:08:23' JB12 A69-1601-47280
'2017-10-04 20:21:43' JB12 A69-1601-47280
'2017-10-05 04:55:48' JB13 A69-1601-47280
'2017-10-05 04:57:04' JB13 A69-1601-47280
'2017-10-05 05:18:40' JB13 A69-1601-47280
'2017-10-07 21:24:19' JB13 A69-1601-47280
'2017-10-07 21:25:36' JB13 A69-1601-47280
'2017-10-07 21:29:25' JB13 A69-1601-47280", header = T)
</code></pre>
| [
{
"answer_id": 74445377,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "merge_asof"
},
{
"answer_id": 74457691,
"author": "Marble_gold",
"author_id": 15423701,
"author_profile": "https://Stackoverflow.com/users/15423701",
"pm_score": 0,
"selected": false,
"text": "df_1"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10270397/"
] |
74,445,391 | <p><a href="https://i.stack.imgur.com/uqcyJ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uqcyJ.gif" alt="enter image description here" /></a></p>
<p>I am trying to filter array of objects (courses) with array of unique data (tag) using radio button using react hooks. I am able to achieve the functionality but checking of radio button is not working. please help me to add checked inside <input type="radio" checked={ } /></p>
<pre><code>import React, { useState } from "react";
const courses = [
{ id: "1", course: "React Tutorial", tag: "react" },
{ id: "2", course: "Object-oriented programming (OOP)", tag: "oop" },
{ id: "3", course: "Java Programming", tag: "java" },
{ id: "4", course: "JavaScript Course", tag: "javascript" },
{ id: "5", course: "Spring Boot Tutorial", tag: "spring" },
{ id: "6", course: "Python Bootcamp", tag: "python" },
{ id: "7", course: "Spring Framework Course", tag: "spring" },
{ id: "8", course: "React with Redux", tag: "react" },
{ id: "9", course: "C#: Classes and OOP", tag: "oop" },
{ id: "10", course: "Java Masterclass", tag: "java" },
{ id: "11", course: "ES6 JavaScript Training", tag: "javascript" },
{ id: "12", course: "Learn Python Programming", tag: "python" },
];
const uniqueTags = [...new Set(courses.map((item: any) => item.tag))];
const App = () => {
const [filterData, setFilterData] = useState(courses);
const handleFilterItems = (tag: any) => {
setFilterData(courses);
const filteredItems = courses?.filter((item: any) => item.tag === tag);
setFilterData(filteredItems);
};
return (
<>
<input type="radio" onChange={() => setFilterData(courses)} /> All
{uniqueTags.map((tag, index) => (
<div key={index}>
<input
type="radio"
key={index}
// checked={tag}
value={tag}
onChange={() => handleFilterItems(tag)}
/>
{tag}
</div>
))}
{filterData.map((course: any) => (
<li key={course.id}>
{course.id}-{course.course}-{course.tag}
</li>
))}
</>
);
};
export default App;
</code></pre>
| [
{
"answer_id": 74445377,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "merge_asof"
},
{
"answer_id": 74457691,
"author": "Marble_gold",
"author_id": 15423701,
"author_profile": "https://Stackoverflow.com/users/15423701",
"pm_score": 0,
"selected": false,
"text": "df_1"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14495095/"
] |
74,445,408 | <p>i am trying to store form email/password registration with next.js but it is giving error</p>
<pre><code>import {useState} from 'react'
type Props = {
label: string
placeholder?: string
onChange: () => void
name?: string
value?: any
}
export const TextField = ({ label, onChange, placeholder, name, value }: Props) => {
const [inputs, setInputs] = useState({})
const handleChange = (event: any) => {
const name = event.target.name
const value = event.target.value
setInputs(values => ({...values, [name]: value}))
}
const handleSubmit = (event: any) => {
event.preventDefault()
console.log(inputs)
}
return (
<div style={{width:'100%'}}>
<div className='text-sm my-2'>{label}</div>
<input
className='border-blue-200 border-2 rounded focus:ring-blue-200 focus:border-blue-200 focus:outline-none px-2'
style={{ height: '45px', maxWidth: '280px', width: '100%', backgroundColor: '#0D0D0D' }}
placeholder={placeholder}
onChange={onChange}
name={name}
value={name}
/>
</div>
)
}
</code></pre>
<p>and i have this in register file</p>
<pre><code><form action="" method="post">
<div className='flex flex-col flex-wrap gap-y-5'>
<TextField name="email" value={inputs.email || ""} label='Enter Your email address:' onChange={() => {handleChange}} />
<TextField name="password" value={inputs.password || ""} label='Enter Your Password:' onChange={() => {handleChange}} />
</div>
<div className='mt-7 flex items-center gap-x-2'>
<PrimaryButton text='Register' onClick={() => {handleSubmit}} />
<div className='text-sm'>
Already Registered? <a onClick={() => push('/login')}>Login</a>
</div>
</div>
</form>
</code></pre>
<p>it keeps saying 'Cannot find name 'handleSubmit'.ts(2304)', it cannot read input, handleSubmit, or handleChange from the other file.</p>
| [
{
"answer_id": 74445629,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 2,
"selected": false,
"text": " onClick={handleSubmit}\n"
},
{
"answer_id": 74446039,
"author": "Camilo Gomez",
"author_id": 17717225,
"author_profile": "https://Stackoverflow.com/users/17717225",
"pm_score": 0,
"selected": false,
"text": "\ntype FormSignup = {\n email: string;\n password: string;\n}\n\ntype Props = {\n label: string\n placeholder?: string\n onChange: () => void\n name?: string\n value?: any\n}\n\nconst TextField = ({ label, onChange, placeholder, name, value }: Props) => {\n return (\n <div style={{width:'100%'}}>\n <div className='text-sm my-2'>{label}</div> \n <input\n className='border-blue-200 border-2 rounded focus:ring-blue-200 focus:border-blue-200 focus:outline-none px-2'\n style={{ height: '45px', maxWidth: '280px', width: '100%', backgroundColor: '#0D0D0D' }}\n placeholder={placeholder}\n onChange={onChange}\n name={name}\n value={name}\n />\n </div>\n )\n}\n\nconst Signup = () => {\n const [inputs, setInputs] = useState<FormSignup | null>(null);\n\n const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n const name = event.target.name\n const value = event.target.value\n setInputs(values => ({...values, [name]: value}))\n }\n\n const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault()\n console.log(inputs)\n }\n\n return(\n <form onSubmit={handleSubmit}>\n <div className='flex flex-col flex-wrap gap-y-5'>\n <TextField onChange={handleChange} name=\"email\" value={inputs?.email || \"\"} label='Enter Your email address:' />\n <TextField onChange={handleChange} name=\"password\" value={inputs?.password || \"\"} label='Enter Your Password:' />\n </div>\n <div className='mt-7 flex items-center gap-x-2'>\n <PrimaryButton text='Register' type=\"submit\" /> \n <div className='text-sm'>\n Already Registered? <a onClick={() => push('/login')}>Login</a>\n </div>\n </div>\n </form>\n );\n}\n\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19934976/"
] |
74,445,414 | <p>I'm trying to build a function where when a link is clicked (all have the same class), a class is toggled on another element.</p>
<p>Example: if I click on link 1 red should get the class active. If I click on link 2, pink should get the class active and not the others and so on. My javascript knowledge is limited and I managed to give the link an active class but not the respective elements that I want to focus.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".trigger").click(function(){
$('.trigger').removeClass('checked')
$(this).addClass('checked')
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main{
position: relative;
width: 500px;
height: 500px;
}
.basic{
width: 300px;
height: 300px;
position: absolute;
right: 0;
}
.red {
background-color: red;
}
.pink {
background-color: pink;
}
.blue{
background-color: blue;
}
.green {
background-color: green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="trigger">Link 1</a>
<a href="#" class="trigger">Link 2</a>
<a href="#" class="trigger">Link 3</a>
<a href="#" class="trigger">Link 4</a>
<div class="main">
<div class="red basic"></div>
<div class="pink basic"></div>
<div class="blue basic"></div>
<div class="green basic"></div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74445607,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": " $(document).ready(function(){\n $(\".trigger1\").click(function(){\n $('.basic:eq(0)').toggle();\n });\n $(\".trigger2\").click(function(){\n $('.basic:eq(1)').toggle();\n });\n $(\".trigger3\").click(function(){\n $('.basic:eq(2)').toggle();\n });\n $(\".trigger4\").click(function(){\n $('.basic:eq(3)').toggle();\n });\n })"
},
{
"answer_id": 74445691,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 3,
"selected": true,
"text": "position: absolute"
},
{
"answer_id": 74445968,
"author": "Vivekanand Vishvkarma",
"author_id": 19443694,
"author_profile": "https://Stackoverflow.com/users/19443694",
"pm_score": 0,
"selected": false,
"text": "<html>\n\n<head>\n <style>\n .main {\n position: relative;\n width: 500px;\n height: 500px;\n }\n\n .basic {\n width: 300px;\n height: 300px;\n position: absolute;\n right: 0;\n }\n\n .red {\n background-color: red;\n }\n\n .pink {\n background-color: pink;\n\n }\n\n .blue {\n background-color: blue;\n\n }\n\n .green {\n background-color: green;\n\n }\n </style>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n <script>\n $(document).ready(function () {\n $(\".trigger\").click(function () {\n $('.trigger').removeClass('checked')\n $(this).addClass('checked')\n let txt = $(this).text().trim();\n $(\".basic\").css(\"z-index\", \"0\")\n if (txt == \"Link 1\") {\n $(\".red\").eq(0).css(\"z-index\", \"10\");\n }\n else if (txt == \"Link 2\") {\n $(\".pink\").eq(0).css(\"z-index\", \"10\");\n }\n else if (txt == \"Link 3\") {\n $(\".blue\").eq(0).css(\"z-index\", \"10\");\n }\n else if (txt == \"Link 4\") {\n $(\".green\").eq(0).css(\"z-index\", \"10\");\n }\n })\n });\n </script>\n</head>\n\n<body>\n <a href=\"#\" class=\"trigger\">Link 1</a>\n <a href=\"#\" class=\"trigger\">Link 2</a>\n <a href=\"#\" class=\"trigger\">Link 3</a>\n <a href=\"#\" class=\"trigger\">Link 4</a>\n\n <div class=\"main\">\n <div class=\"red basic\"></div>\n <div class=\"pink basic\"></div>\n <div class=\"blue basic\"></div>\n <div class=\"green basic\"></div>\n </div>\n</body>\n\n</html>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5769648/"
] |
74,445,426 | <p>I recently started using Apps Script to automate some processes in Google Sheets.</p>
<p>I need to add "/" between numbers only while they are inside parentheses.</p>
<p>example "123(123)" to "123(1/2/3)"</p>
<p>I've played around with textFinder but no luck.</p>
| [
{
"answer_id": 74445607,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": " $(document).ready(function(){\n $(\".trigger1\").click(function(){\n $('.basic:eq(0)').toggle();\n });\n $(\".trigger2\").click(function(){\n $('.basic:eq(1)').toggle();\n });\n $(\".trigger3\").click(function(){\n $('.basic:eq(2)').toggle();\n });\n $(\".trigger4\").click(function(){\n $('.basic:eq(3)').toggle();\n });\n })"
},
{
"answer_id": 74445691,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 3,
"selected": true,
"text": "position: absolute"
},
{
"answer_id": 74445968,
"author": "Vivekanand Vishvkarma",
"author_id": 19443694,
"author_profile": "https://Stackoverflow.com/users/19443694",
"pm_score": 0,
"selected": false,
"text": "<html>\n\n<head>\n <style>\n .main {\n position: relative;\n width: 500px;\n height: 500px;\n }\n\n .basic {\n width: 300px;\n height: 300px;\n position: absolute;\n right: 0;\n }\n\n .red {\n background-color: red;\n }\n\n .pink {\n background-color: pink;\n\n }\n\n .blue {\n background-color: blue;\n\n }\n\n .green {\n background-color: green;\n\n }\n </style>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n <script>\n $(document).ready(function () {\n $(\".trigger\").click(function () {\n $('.trigger').removeClass('checked')\n $(this).addClass('checked')\n let txt = $(this).text().trim();\n $(\".basic\").css(\"z-index\", \"0\")\n if (txt == \"Link 1\") {\n $(\".red\").eq(0).css(\"z-index\", \"10\");\n }\n else if (txt == \"Link 2\") {\n $(\".pink\").eq(0).css(\"z-index\", \"10\");\n }\n else if (txt == \"Link 3\") {\n $(\".blue\").eq(0).css(\"z-index\", \"10\");\n }\n else if (txt == \"Link 4\") {\n $(\".green\").eq(0).css(\"z-index\", \"10\");\n }\n })\n });\n </script>\n</head>\n\n<body>\n <a href=\"#\" class=\"trigger\">Link 1</a>\n <a href=\"#\" class=\"trigger\">Link 2</a>\n <a href=\"#\" class=\"trigger\">Link 3</a>\n <a href=\"#\" class=\"trigger\">Link 4</a>\n\n <div class=\"main\">\n <div class=\"red basic\"></div>\n <div class=\"pink basic\"></div>\n <div class=\"blue basic\"></div>\n <div class=\"green basic\"></div>\n </div>\n</body>\n\n</html>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509995/"
] |
74,445,429 | <p>I have generated a bash script that activates virtaulenv and runs my custom management command in Django. I want to run the bash script every day at midnight.</p>
<p><strong>Bash Script</strong> :</p>
<pre><code>cd ~
cd path_to_virtualenv/
source virtualenv_name/bin/activate
cd path_to_project/
python manage.py custom_command
deactivate
</code></pre>
<p>When I run this script using <code>.</code> or <code>source</code> it runs perfectly. I have configured crontab to run this bash script (For testing, I have set execution time per minute). But I am not getting desired output.</p>
<p><strong>crontab -e</strong></p>
<pre><code>*/1 * * * * source /path_to_bash_script/bash_script_filename
</code></pre>
| [
{
"answer_id": 74445618,
"author": "Zkh",
"author_id": 19235697,
"author_profile": "https://Stackoverflow.com/users/19235697",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash"
},
{
"answer_id": 74455921,
"author": "Manoj Kamble",
"author_id": 18089995,
"author_profile": "https://Stackoverflow.com/users/18089995",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\nsource /path_to_virutalenv/bin/activate\npython /path_to_project/manage.py custom_command\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18089995/"
] |
74,445,430 | <p>First, I want to capture pose values by subscribing to teleop_key from a turtle. Then I want to change these captured values and publish to a second turtle. The problem is that I couldn't capture the pose values as a global variables. And due to this I couldn't change the variables and published the modified ones.</p>
<p>I think I have an almost finished code. That's why I'm going to throw them all out directly.</p>
<pre><code>#!/usr/bin/env python3
from turtlesim.msg import Pose
from geometry_msgs.msg import Twist
import rospy as rp
global pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z
def pose_callback(msg):
rp.loginfo("("+ str(msg.x) + "," + str(msg.y) + "," + str(msg.theta)+ ")")
pos_l_x = msg.x
pos_l_y = msg.y
pos_a_z = msg.theta
if __name__ == '__main__':
rp.init_node("turtle_inverse")
while not rp.is_shutdown():
sub = rp.Subscriber("/turtlesim1/turtle1/pose", Pose, callback= pose_callback)
rate = rp.Rate(1)
rp.loginfo("Node has been started")
cmd = Twist()
cmd.linear.x = -1*pos_l_x
cmd.linear.y = -1*pos_l_y
cmd.linear.z = 0
cmd.angular.x = 0
cmd.angular.y = 0
cmd.angular.z = -1*pos_a_z
pub = rp.Publisher("/turtlesim2/turtle1/cmd_vel", Twist, queue_size=10)
try:
pub.publish(cmd)
except rp.ServiceException as e:
rp.logwarn(e)
rate.sleep()
rp.spin()
</code></pre>
<p>And I did the connection between turtle1 and turtle2 in the lunch file below:</p>
<pre><code><?xml version="1.0"?>
<launch>
<group ns="turtlesim1">
<node pkg="turtlesim" type="turtlesim_node" name="turtle1">
<remap from="/turtle1/cmd_vel" to="vel_1"/>
</node>
<node pkg="turtlesim" type="turtle_teleop_key" name="Joyistic" output= "screen">
<remap from="/turtle1/cmd_vel" to="vel_1"/>
</node>
</group>
<group ns="turtlesim2">
<node pkg="turtlesim" type="turtlesim_node" name="turtle1">
</node>
</group>
<node pkg="turtlesim" type="mimic" name="mimic">
<remap from="input" to="turtlesim1/turtle1"/>
<remap from="output" to="turtlesim2/turtle1"/>
</node>
</launch>
</code></pre>
<p>And lastly here my package.xml code:</p>
<pre><code><?xml version="1.0"?>
<package format="2">
<name>my_robot_controller</name>
<version>0.0.0</version>
<description>The my_robot_controller package</description>
<!-- One maintainer tag required, multiple allowed, one person per tag -->
<!-- Example: -->
<!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
<maintainer email="(I delete it for sharing)">enes</maintainer>
<!-- One license tag required, multiple allowed, one license per tag -->
<!-- Commonly used license strings: -->
<!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
<license>TODO</license>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>rospy</build_depend>
<build_depend>turtlesim</build_depend>
<build_depend>geometry_msgs</build_depend>
<build_export_depend>rospy</build_export_depend>
<build_export_depend>turtlesim</build_export_depend>
<build_export_depend>geometry_msgs</build_export_depend>
<exec_depend>rospy</exec_depend>
<exec_depend>turtlesim</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<export>
<!-- Other tools can request additional information be placed here -->
</export>
</package>
</code></pre>
<p>Not: I work in catkin workspace the mistake couldn't be here because I run many different code without trouble</p>
| [
{
"answer_id": 74449318,
"author": "BTables",
"author_id": 11936229,
"author_profile": "https://Stackoverflow.com/users/11936229",
"pm_score": 2,
"selected": true,
"text": "pos"
},
{
"answer_id": 74451016,
"author": "Enes",
"author_id": 13659111,
"author_profile": "https://Stackoverflow.com/users/13659111",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\nfrom turtlesim.msg import Pose\nfrom geometry_msgs.msg import Twist\nimport rospy as rp\n\npos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0 \n\ndef pose_callback(msg):\n rp.loginfo(\"(\"+ str(msg.linear.x) + \",\" + str(msg.linear.y) + \",\" + str(msg.angular.z)+ \")\")\n global pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z \n pos_l_x = msg.linear.x\n pos_l_y = msg.linear.y\n pos_l_z = msg.linear.z\n pos_a_x = msg.angular.x\n pos_a_y = msg.angular.y\n pos_a_z = msg.angular.z\n\nif __name__ == '__main__':\n rp.init_node(\"turtle_inverse\")\n sub = rp.Subscriber(\"/turtlesim1/turtle1/cmd_vel\", Twist, callback= pose_callback)\n rate = rp.Rate(1)\n rp.loginfo(\"Node has been started\")\n\n while not rp.is_shutdown():\n cmd = Twist()\n\n cmd.linear.x = -1*pos_l_x\n cmd.linear.y = -1*pos_l_y\n cmd.linear.z = -1*pos_l_z\n cmd.angular.x = -1*pos_a_x\n cmd.angular.y = -1*pos_a_y\n cmd.angular.z = -1*pos_a_z\n \n pub = rp.Publisher(\"/turtlesim2/turtle1/cmd_vel\", Twist, queue_size=10)\n try:\n pub.publish(cmd)\n except rp.ServiceException as e:\n pass\n pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0\n rate.sleep()\nrp.spin()\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13659111/"
] |
74,445,476 | <p>image cant seem to fit in just one section and keep overflowing to another section.</p>
<p>tried putting tag in between but does not seems to work, img keep showing in two section.also tried the width and padding but i can't move the img to the left. can anyone help with only css and html? can't use js on this project.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#section1 {
height: 580px;
width: 1519px;
background-color: #0E2E3B;
padding: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<section id="section1">
</section>
<section class="main" id="section2" id="profil">
<h1>Lorem</h1>
<h2>Lorem</h2>
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<img src="pancasila.jpg">
</section>
<body></code></pre>
</div>
</div>
</p>
<p>the html code</p>
| [
{
"answer_id": 74449318,
"author": "BTables",
"author_id": 11936229,
"author_profile": "https://Stackoverflow.com/users/11936229",
"pm_score": 2,
"selected": true,
"text": "pos"
},
{
"answer_id": 74451016,
"author": "Enes",
"author_id": 13659111,
"author_profile": "https://Stackoverflow.com/users/13659111",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\nfrom turtlesim.msg import Pose\nfrom geometry_msgs.msg import Twist\nimport rospy as rp\n\npos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0 \n\ndef pose_callback(msg):\n rp.loginfo(\"(\"+ str(msg.linear.x) + \",\" + str(msg.linear.y) + \",\" + str(msg.angular.z)+ \")\")\n global pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z \n pos_l_x = msg.linear.x\n pos_l_y = msg.linear.y\n pos_l_z = msg.linear.z\n pos_a_x = msg.angular.x\n pos_a_y = msg.angular.y\n pos_a_z = msg.angular.z\n\nif __name__ == '__main__':\n rp.init_node(\"turtle_inverse\")\n sub = rp.Subscriber(\"/turtlesim1/turtle1/cmd_vel\", Twist, callback= pose_callback)\n rate = rp.Rate(1)\n rp.loginfo(\"Node has been started\")\n\n while not rp.is_shutdown():\n cmd = Twist()\n\n cmd.linear.x = -1*pos_l_x\n cmd.linear.y = -1*pos_l_y\n cmd.linear.z = -1*pos_l_z\n cmd.angular.x = -1*pos_a_x\n cmd.angular.y = -1*pos_a_y\n cmd.angular.z = -1*pos_a_z\n \n pub = rp.Publisher(\"/turtlesim2/turtle1/cmd_vel\", Twist, queue_size=10)\n try:\n pub.publish(cmd)\n except rp.ServiceException as e:\n pass\n pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0\n rate.sleep()\nrp.spin()\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20473729/"
] |
74,445,489 | <p>I am currently learning Laravel. I had a pre-built script and I need to do some changes in it to make it usable... But as much I learnt from the web, I understood that the routes are specified in the Routes/web.php file.
But in the application I'm working on, the routes are defined in Routes/api.php file.</p>
<p>I even tried to find out the HTML pages in the Views folder but it only has the code for the tables which are there on the User Interface. All the controllers also return some data (like... return $data) in the end but no php or blade.php file is mentioned in any controller.</p>
<p>I need to find out the HTML pages so that I can change some components or elements from that website.</p>
<p>Please help me with this. Thanks!</p>
| [
{
"answer_id": 74449318,
"author": "BTables",
"author_id": 11936229,
"author_profile": "https://Stackoverflow.com/users/11936229",
"pm_score": 2,
"selected": true,
"text": "pos"
},
{
"answer_id": 74451016,
"author": "Enes",
"author_id": 13659111,
"author_profile": "https://Stackoverflow.com/users/13659111",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\nfrom turtlesim.msg import Pose\nfrom geometry_msgs.msg import Twist\nimport rospy as rp\n\npos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0 \n\ndef pose_callback(msg):\n rp.loginfo(\"(\"+ str(msg.linear.x) + \",\" + str(msg.linear.y) + \",\" + str(msg.angular.z)+ \")\")\n global pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z \n pos_l_x = msg.linear.x\n pos_l_y = msg.linear.y\n pos_l_z = msg.linear.z\n pos_a_x = msg.angular.x\n pos_a_y = msg.angular.y\n pos_a_z = msg.angular.z\n\nif __name__ == '__main__':\n rp.init_node(\"turtle_inverse\")\n sub = rp.Subscriber(\"/turtlesim1/turtle1/cmd_vel\", Twist, callback= pose_callback)\n rate = rp.Rate(1)\n rp.loginfo(\"Node has been started\")\n\n while not rp.is_shutdown():\n cmd = Twist()\n\n cmd.linear.x = -1*pos_l_x\n cmd.linear.y = -1*pos_l_y\n cmd.linear.z = -1*pos_l_z\n cmd.angular.x = -1*pos_a_x\n cmd.angular.y = -1*pos_a_y\n cmd.angular.z = -1*pos_a_z\n \n pub = rp.Publisher(\"/turtlesim2/turtle1/cmd_vel\", Twist, queue_size=10)\n try:\n pub.publish(cmd)\n except rp.ServiceException as e:\n pass\n pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0\n rate.sleep()\nrp.spin()\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20507866/"
] |
74,445,504 | <p>I am adding payment and subscription to my application using stripe
I want to fee the user per the usage of my system , I tried to report usage as floating point number
but cant find a way to do that , the supported method allows you send integer usage only
any suggestion to do that?</p>
<p>I used UsageRecordCreateOptions.Quantity , but its integer field</p>
| [
{
"answer_id": 74449318,
"author": "BTables",
"author_id": 11936229,
"author_profile": "https://Stackoverflow.com/users/11936229",
"pm_score": 2,
"selected": true,
"text": "pos"
},
{
"answer_id": 74451016,
"author": "Enes",
"author_id": 13659111,
"author_profile": "https://Stackoverflow.com/users/13659111",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\nfrom turtlesim.msg import Pose\nfrom geometry_msgs.msg import Twist\nimport rospy as rp\n\npos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0 \n\ndef pose_callback(msg):\n rp.loginfo(\"(\"+ str(msg.linear.x) + \",\" + str(msg.linear.y) + \",\" + str(msg.angular.z)+ \")\")\n global pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z \n pos_l_x = msg.linear.x\n pos_l_y = msg.linear.y\n pos_l_z = msg.linear.z\n pos_a_x = msg.angular.x\n pos_a_y = msg.angular.y\n pos_a_z = msg.angular.z\n\nif __name__ == '__main__':\n rp.init_node(\"turtle_inverse\")\n sub = rp.Subscriber(\"/turtlesim1/turtle1/cmd_vel\", Twist, callback= pose_callback)\n rate = rp.Rate(1)\n rp.loginfo(\"Node has been started\")\n\n while not rp.is_shutdown():\n cmd = Twist()\n\n cmd.linear.x = -1*pos_l_x\n cmd.linear.y = -1*pos_l_y\n cmd.linear.z = -1*pos_l_z\n cmd.angular.x = -1*pos_a_x\n cmd.angular.y = -1*pos_a_y\n cmd.angular.z = -1*pos_a_z\n \n pub = rp.Publisher(\"/turtlesim2/turtle1/cmd_vel\", Twist, queue_size=10)\n try:\n pub.publish(cmd)\n except rp.ServiceException as e:\n pass\n pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0\n rate.sleep()\nrp.spin()\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510089/"
] |
74,445,505 | <p>Basically, it should be possible to copy html-code directly into a Quarto document (.qmd) and then render it to an html-website.</p>
<p>I tried to do that and copied the following code from the <a href="https://bootswatch.com/simplex/" rel="nofollow noreferrer">Simplex Theme</a> to a quarto website:</p>
<pre><code><div class="card border-primary mb-3" style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Primary card title</h4>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
<div class="card border-secondary mb-3" style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Secondary card title</h4>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</code></pre>
<p>However, the results only partially works:</p>
<p><a href="https://i.stack.imgur.com/NZMp2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NZMp2.png" alt="enter image description here" /></a></p>
<p>Do I make something wrong?</p>
| [
{
"answer_id": 74449318,
"author": "BTables",
"author_id": 11936229,
"author_profile": "https://Stackoverflow.com/users/11936229",
"pm_score": 2,
"selected": true,
"text": "pos"
},
{
"answer_id": 74451016,
"author": "Enes",
"author_id": 13659111,
"author_profile": "https://Stackoverflow.com/users/13659111",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\nfrom turtlesim.msg import Pose\nfrom geometry_msgs.msg import Twist\nimport rospy as rp\n\npos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0 \n\ndef pose_callback(msg):\n rp.loginfo(\"(\"+ str(msg.linear.x) + \",\" + str(msg.linear.y) + \",\" + str(msg.angular.z)+ \")\")\n global pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z \n pos_l_x = msg.linear.x\n pos_l_y = msg.linear.y\n pos_l_z = msg.linear.z\n pos_a_x = msg.angular.x\n pos_a_y = msg.angular.y\n pos_a_z = msg.angular.z\n\nif __name__ == '__main__':\n rp.init_node(\"turtle_inverse\")\n sub = rp.Subscriber(\"/turtlesim1/turtle1/cmd_vel\", Twist, callback= pose_callback)\n rate = rp.Rate(1)\n rp.loginfo(\"Node has been started\")\n\n while not rp.is_shutdown():\n cmd = Twist()\n\n cmd.linear.x = -1*pos_l_x\n cmd.linear.y = -1*pos_l_y\n cmd.linear.z = -1*pos_l_z\n cmd.angular.x = -1*pos_a_x\n cmd.angular.y = -1*pos_a_y\n cmd.angular.z = -1*pos_a_z\n \n pub = rp.Publisher(\"/turtlesim2/turtle1/cmd_vel\", Twist, queue_size=10)\n try:\n pub.publish(cmd)\n except rp.ServiceException as e:\n pass\n pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0\n rate.sleep()\nrp.spin()\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2459401/"
] |
74,445,527 | <p><strong>Problem</strong>
Compute a per-warp histogram of sorted sequence of numbers held by individual threads in a warp.</p>
<p>Example:</p>
<pre><code>lane: 0123456789... 31
val: 222244455777799999 ..
</code></pre>
<p>The result must be held by N lower threads in a warp (where N is the amount of unique numbers), e.g.:</p>
<pre><code>lane 0: val=2, num=4 (2 occurs 4 times)
lane 1: val=4, num=3 (4 occurs 3 times)
lane 2: val=5, num=2 ...
lane 3: val=7, num=4
lane 4: val=9, num=5
...
</code></pre>
<p>Note that, it is essentially not required for a sequence of 'val' to be sorted: it's only necessary for equal numbers to be grouped together, i.e.: 99955555773333333...</p>
<p><strong>Possible solution</strong>
This can be done quite efficiently with shuffle intrinsics,
though my question is whether it's possible to do this <em>without</em> using shared memory at all (I mean shared memory is a scarce resource, I need it somewhere else) ?</p>
<p>For simplicity, I execute this code for a single warp only (so that printf works fine):</p>
<pre><code>__device__ __inline__ void sorted_seq_histogram()
{
uint32_t tid = threadIdx.x, lane = tid % 32;
uint32_t val = (lane + 117)* 23 / 97; // sorted sequence of values to be reduced
printf("%d: val = %d\n", lane, val);
uint32_t num = 1;
uint32_t allmsk = 0xffffffffu, shfl_c = 31;
for(int i = 1; i <= 16; i *= 2) {
#if 1
uint32_t xval = __shfl_down_sync(allmsk, val, i),
xnum = __shfl_down_sync(allmsk, num, i);
if(lane + i < 32) {
if(val == xval)
num += xnum;
}
#else // this is a (hopefully) optimized version of the code above
asm(R"({
.reg .u32 r0,r1;
.reg .pred p;
shfl.sync.down.b32 r0|p, %1, %2, %3, %4;
shfl.sync.down.b32 r1|p, %0, %2, %3, %4;
@p setp.eq.s32 p, %1, r0;
@p add.u32 r1, r1, %0;
@p mov.u32 %0, r1;
})"
: "+r"(num) : "r"(val), "r"(i), "r"(shfl_c), "r"(allmsk));
#endif
}
// shfl.sync wraps around: so thread 0 gets the value of thread 31
bool leader = val != __shfl_sync(allmsk, val, lane - 1);
auto OK = __ballot_sync(allmsk, leader); // find delimiter threads
auto total = __popc(OK); // the total number of unique numbers found
auto lanelt = (1 << lane) - 1;
auto idx = __popc(OK & lanelt);
printf("%d: val = %d; num = %d; total: %d; idx = %d; leader: %d\n", lane, val, num, total, idx, leader);
__shared__ uint32_t sh[64];
if(leader) { // here we need shared memory :(
sh[idx] = val;
sh[idx + 32] = num;
}
__syncthreads();
if(lane < total) {
val = sh[lane], num = sh[lane + 32];
} else {
val = 0xDEADBABE, num = 0;
}
printf("%d: final val = %d; num = %d\n", lane, val, num);
}
</code></pre>
<p>Here is my GPU output:</p>
<pre><code>0: val = 27
1: val = 27
2: val = 28
3: val = 28
4: val = 28
5: val = 28
6: val = 29
7: val = 29
8: val = 29
9: val = 29
10: val = 30
11: val = 30
12: val = 30
13: val = 30
14: val = 31
15: val = 31
16: val = 31
17: val = 31
18: val = 32
19: val = 32
20: val = 32
21: val = 32
22: val = 32
23: val = 33
24: val = 33
25: val = 33
26: val = 33
27: val = 34
28: val = 34
29: val = 34
30: val = 34
31: val = 35
0: val = 27; num = 2; total: 9; idx = 0; leader: 1
1: val = 27; num = 1; total: 9; idx = 1; leader: 0
2: val = 28; num = 4; total: 9; idx = 1; leader: 1
3: val = 28; num = 3; total: 9; idx = 2; leader: 0
4: val = 28; num = 2; total: 9; idx = 2; leader: 0
5: val = 28; num = 1; total: 9; idx = 2; leader: 0
6: val = 29; num = 4; total: 9; idx = 2; leader: 1
7: val = 29; num = 3; total: 9; idx = 3; leader: 0
8: val = 29; num = 2; total: 9; idx = 3; leader: 0
9: val = 29; num = 1; total: 9; idx = 3; leader: 0
10: val = 30; num = 4; total: 9; idx = 3; leader: 1
11: val = 30; num = 3; total: 9; idx = 4; leader: 0
12: val = 30; num = 2; total: 9; idx = 4; leader: 0
13: val = 30; num = 1; total: 9; idx = 4; leader: 0
14: val = 31; num = 4; total: 9; idx = 4; leader: 1
15: val = 31; num = 3; total: 9; idx = 5; leader: 0
16: val = 31; num = 2; total: 9; idx = 5; leader: 0
17: val = 31; num = 1; total: 9; idx = 5; leader: 0
18: val = 32; num = 5; total: 9; idx = 5; leader: 1
19: val = 32; num = 4; total: 9; idx = 6; leader: 0
20: val = 32; num = 3; total: 9; idx = 6; leader: 0
21: val = 32; num = 2; total: 9; idx = 6; leader: 0
22: val = 32; num = 1; total: 9; idx = 6; leader: 0
23: val = 33; num = 4; total: 9; idx = 6; leader: 1
24: val = 33; num = 3; total: 9; idx = 7; leader: 0
25: val = 33; num = 2; total: 9; idx = 7; leader: 0
26: val = 33; num = 1; total: 9; idx = 7; leader: 0
27: val = 34; num = 4; total: 9; idx = 7; leader: 1
28: val = 34; num = 3; total: 9; idx = 8; leader: 0
29: val = 34; num = 2; total: 9; idx = 8; leader: 0
30: val = 34; num = 1; total: 9; idx = 8; leader: 0
31: val = 35; num = 1; total: 9; idx = 8; leader: 1
0: final val = 27; num = 2
1: final val = 28; num = 4
2: final val = 29; num = 4
3: final val = 30; num = 4
4: final val = 31; num = 4
5: final val = 32; num = 5
6: final val = 33; num = 4
7: final val = 34; num = 4
8: final val = 35; num = 1
9: final val = -559039810; num = 0
10: final val = -559039810; num = 0
11: final val = -559039810; num = 0
12: final val = -559039810; num = 0
13: final val = -559039810; num = 0
14: final val = -559039810; num = 0
15: final val = -559039810; num = 0
16: final val = -559039810; num = 0
17: final val = -559039810; num = 0
18: final val = -559039810; num = 0
19: final val = -559039810; num = 0
20: final val = -559039810; num = 0
21: final val = -559039810; num = 0
22: final val = -559039810; num = 0
23: final val = -559039810; num = 0
24: final val = -559039810; num = 0
25: final val = -559039810; num = 0
26: final val = -559039810; num = 0
27: final val = -559039810; num = 0
28: final val = -559039810; num = 0
29: final val = -559039810; num = 0
30: final val = -559039810; num = 0
31: final val = -559039810; num = 0
</code></pre>
<p><strong>Question</strong>
Is it possible to do this without using shared memory?
Somehow, I cannot figure it out with all these brain-twisting shuffle intrinsics..</p>
| [
{
"answer_id": 74449318,
"author": "BTables",
"author_id": 11936229,
"author_profile": "https://Stackoverflow.com/users/11936229",
"pm_score": 2,
"selected": true,
"text": "pos"
},
{
"answer_id": 74451016,
"author": "Enes",
"author_id": 13659111,
"author_profile": "https://Stackoverflow.com/users/13659111",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\nfrom turtlesim.msg import Pose\nfrom geometry_msgs.msg import Twist\nimport rospy as rp\n\npos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0 \n\ndef pose_callback(msg):\n rp.loginfo(\"(\"+ str(msg.linear.x) + \",\" + str(msg.linear.y) + \",\" + str(msg.angular.z)+ \")\")\n global pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z \n pos_l_x = msg.linear.x\n pos_l_y = msg.linear.y\n pos_l_z = msg.linear.z\n pos_a_x = msg.angular.x\n pos_a_y = msg.angular.y\n pos_a_z = msg.angular.z\n\nif __name__ == '__main__':\n rp.init_node(\"turtle_inverse\")\n sub = rp.Subscriber(\"/turtlesim1/turtle1/cmd_vel\", Twist, callback= pose_callback)\n rate = rp.Rate(1)\n rp.loginfo(\"Node has been started\")\n\n while not rp.is_shutdown():\n cmd = Twist()\n\n cmd.linear.x = -1*pos_l_x\n cmd.linear.y = -1*pos_l_y\n cmd.linear.z = -1*pos_l_z\n cmd.angular.x = -1*pos_a_x\n cmd.angular.y = -1*pos_a_y\n cmd.angular.z = -1*pos_a_z\n \n pub = rp.Publisher(\"/turtlesim2/turtle1/cmd_vel\", Twist, queue_size=10)\n try:\n pub.publish(cmd)\n except rp.ServiceException as e:\n pass\n pos_l_x,pos_l_y,pos_l_z,pos_a_x,pos_a_y,pos_a_z = 0,0,0,0,0,0\n rate.sleep()\nrp.spin()\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4349407/"
] |
74,445,537 | <p>I am following along with a tutorial, and I am building a simple regression model with tensorflow. I would expect tf to fit the model without any hiccups. Instead, I am getting a value error.</p>
<p>The model and compile steps look identical to the tutorial.</p>
<p>The data is similar (two numpy arrays). I used different numbers in the arrays, but I do not think that is the issue. Any two arrays of equal length should be valid, right?</p>
<pre><code>X = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
y = tf.constant(np.array([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]))
model = tf.keras.Sequential([
tf.keras.layers.Dense(1)
])
model.compile(
loss=tf.keras.losses.mae,
optimizer=tf.keras.optimizers.SGD(),
metrics=["mae"]
)
model.fit(X, y, epochs=10)
</code></pre>
<pre><code>---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-41-2da4b2bd3c5c> in <module>
12 )
13
---> 14 model.fit(X, y, epochs=10)
~/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
59 def error_handler(*args, **kwargs):
60 if not tf.debugging.is_traceback_filtering_enabled():
---> 61 return fn(*args, **kwargs)
62
63 filtered_tb = None
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
1562 ):
1563 callbacks.on_train_batch_begin(step)
-> 1564 tmp_logs = self.train_function(iterator)
1565 if data_handler.should_sync:
1566 context.async_wait()
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py in error_handler(*args, **kwargs)
139 try:
140 if not is_traceback_filtering_enabled():
--> 141 return fn(*args, **kwargs)
142 except NameError:
143 # In some very rare cases,
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
913
914 with OptionalXlaContext(self._jit_compile):
--> 915 result = self._call(*args, **kwds)
916
917 new_tracing_count = self.experimental_get_tracing_count()
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
961 # This is the first call of __call__, so we have to initialize.
962 initializers = []
--> 963 self._initialize(args, kwds, add_initializers_to=initializers)
964 finally:
965 # At this point we know that the initialization is complete (or less
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
783 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)
784 self._concrete_stateful_fn = (
--> 785 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access
786 *args, **kwds))
787
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
2521 args, kwargs = None, None
2522 with self._lock:
-> 2523 graph_function, _ = self._maybe_define_function(args, kwargs)
2524 return graph_function
2525
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
2758 # Only get placeholders for arguments, not captures
2759 args, kwargs = placeholder_dict["args"]
-> 2760 graph_function = self._create_graph_function(args, kwargs)
2761
2762 graph_capture_container = graph_function.graph._capture_func_lib # pylint: disable=protected-access
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs)
2668 arg_names = base_arg_names + missing_arg_names
2669 graph_function = ConcreteFunction(
-> 2670 func_graph_module.func_graph_from_py_func(
2671 self._name,
2672 self._python_function,
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, acd_record_initial_resource_uses)
1245 _, original_func = tf_decorator.unwrap(python_func)
1246
-> 1247 func_outputs = python_func(*func_args, **func_kwargs)
1248
1249 # invariant: `func_outputs` contains only Tensors, CompositeTensors,
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
675 # the function a weak reference to itself to avoid a reference cycle.
676 with OptionalXlaContext(compile_with_xla):
--> 677 out = weak_wrapped_fn().__wrapped__(*args, **kwds)
678 return out
679
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
1231 except Exception as e: # pylint:disable=broad-except
1232 if hasattr(e, "ag_error_metadata"):
-> 1233 raise e.ag_error_metadata.to_exception(e)
1234 else:
1235 raise
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
1220 # TODO(mdan): Push this block higher in tf.function's call stack.
1221 try:
-> 1222 return autograph.converted_call(
1223 original_func,
1224 args,
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py in converted_call(f, args, kwargs, caller_fn_scope, options)
437 try:
438 if kwargs is not None:
--> 439 result = converted_f(*effective_args, **kwargs)
440 else:
441 result = converted_f(*effective_args)
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py in tf__train_function(iterator)
13 try:
14 do_return = True
---> 15 retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
16 except:
17 do_return = False
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py in converted_call(f, args, kwargs, caller_fn_scope, options)
375
376 if not options.user_requested and conversion.is_allowlisted(f):
--> 377 return _call_unconverted(f, args, kwargs, options)
378
379 # internal_convert_user_code is for example turned off when issuing a dynamic
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py in _call_unconverted(f, args, kwargs, options, update_cache)
457 if kwargs is not None:
458 return f(*args, **kwargs)
--> 459 return f(*args)
460
461
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py in step_function(model, iterator)
1144 )
1145 data = next(iterator)
-> 1146 outputs = model.distribute_strategy.run(run_step, args=(data,))
1147 outputs = reduce_per_replica(
1148 outputs, self.distribute_strategy, reduction="first"
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py in run(***failed resolving arguments***)
1313 fn = autograph.tf_convert(
1314 fn, autograph_ctx.control_status_ctx(), convert_by_default=False)
-> 1315 return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
1316
1317 def reduce(self, reduce_op, value, axis):
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py in call_for_each_replica(self, fn, args, kwargs)
2889 kwargs = {}
2890 with self._container_strategy().scope():
-> 2891 return self._call_for_each_replica(fn, args, kwargs)
2892
2893 def _call_for_each_replica(self, fn, args, kwargs):
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py in _call_for_each_replica(self, fn, args, kwargs)
3690 def _call_for_each_replica(self, fn, args, kwargs):
3691 with ReplicaContext(self._container_strategy(), replica_id_in_sync_group=0):
-> 3692 return fn(*args, **kwargs)
3693
3694 def _reduce_to(self, reduce_op, value, destinations, options):
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
687 try:
688 with conversion_ctx:
--> 689 return converted_call(f, args, kwargs, options=options)
690 except Exception as e: # pylint:disable=broad-except
691 if hasattr(e, 'ag_error_metadata'):
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py in converted_call(f, args, kwargs, caller_fn_scope, options)
375
376 if not options.user_requested and conversion.is_allowlisted(f):
--> 377 return _call_unconverted(f, args, kwargs, options)
378
379 # internal_convert_user_code is for example turned off when issuing a dynamic
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py in _call_unconverted(f, args, kwargs, options, update_cache)
456
457 if kwargs is not None:
--> 458 return f(*args, **kwargs)
459 return f(*args)
460
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py in run_step(data)
1133
1134 def run_step(data):
-> 1135 outputs = model.train_step(data)
1136 # Ensure counter is updated only if `train_step` succeeds.
1137 with tf.control_dependencies(_minimum_control_deps(outputs)):
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py in train_step(self, data)
991 # Run forward pass.
992 with tf.GradientTape() as tape:
--> 993 y_pred = self(x, training=True)
994 loss = self.compute_loss(x, y, y_pred, sample_weight)
995 self._validate_target_and_loss(y, loss)
~/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
59 def error_handler(*args, **kwargs):
60 if not tf.debugging.is_traceback_filtering_enabled():
---> 61 return fn(*args, **kwargs)
62
63 filtered_tb = None
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py in __call__(self, *args, **kwargs)
555 layout_map_lib._map_subclass_model_variable(self, self._layout_map)
556
--> 557 return super().__call__(*args, **kwargs)
558
559 @doc_controls.doc_in_current_and_subclasses
~/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
59 def error_handler(*args, **kwargs):
60 if not tf.debugging.is_traceback_filtering_enabled():
---> 61 return fn(*args, **kwargs)
62
63 filtered_tb = None
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/base_layer.py in __call__(self, *args, **kwargs)
1095 self._compute_dtype_object
1096 ):
-> 1097 outputs = call_fn(inputs, *args, **kwargs)
1098
1099 if self._activity_regularizer:
~/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
153 else:
154 new_e = e
--> 155 raise new_e.with_traceback(e.__traceback__) from None
156 finally:
157 del signature
~/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
94 bound_signature = None
95 try:
---> 96 return fn(*args, **kwargs)
97 except Exception as e:
98 if hasattr(e, "_keras_call_info_injected"):
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/sequential.py in call(self, inputs, training, mask)
423 kwargs["training"] = training
424
--> 425 outputs = layer(inputs, **kwargs)
426
427 if len(tf.nest.flatten(outputs)) != 1:
~/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
59 def error_handler(*args, **kwargs):
60 if not tf.debugging.is_traceback_filtering_enabled():
---> 61 return fn(*args, **kwargs)
62
63 filtered_tb = None
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/base_layer.py in __call__(self, *args, **kwargs)
1063 ):
1064
-> 1065 input_spec.assert_input_compatibility(
1066 self.input_spec, inputs, self.name
1067 )
~/opt/anaconda3/lib/python3.8/site-packages/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name)
248 ndim = x.shape.rank
249 if ndim is not None and ndim < spec.min_ndim:
--> 250 raise ValueError(
251 f'Input {input_index} of layer "{layer_name}" '
252 "is incompatible with the layer: "
ValueError: in user code:
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py", line 1160, in train_function *
return step_function(self, iterator)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py", line 1146, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py", line 1315, in run
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py", line 2891, in call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py", line 3692, in _call_for_each_replica
return fn(*args, **kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py", line 1135, in run_step **
outputs = model.train_step(data)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py", line 993, in train_step
y_pred = self(x, training=True)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 61, in error_handler
return fn(*args, **kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/training.py", line 557, in __call__
return super().__call__(*args, **kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 61, in error_handler
return fn(*args, **kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/base_layer.py", line 1097, in __call__
outputs = call_fn(inputs, *args, **kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 155, in error_handler
raise new_e.with_traceback(e.__traceback__) from None
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 96, in error_handler
return fn(*args, **kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/sequential.py", line 425, in call
outputs = layer(inputs, **kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 61, in error_handler
return fn(*args, **kwargs)
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/base_layer.py", line 1065, in __call__
input_spec.assert_input_compatibility(
File "/Users/mcm66103/opt/anaconda3/lib/python3.8/site-packages/keras/engine/input_spec.py", line 250, in assert_input_compatibility
raise ValueError(
ValueError: Exception encountered when calling layer "sequential_24" " f"(type Sequential).
Input 0 of layer "dense_25" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)
Call arguments received by layer "sequential_24" " f"(type Sequential):
• inputs=tf.Tensor(shape=(None,), dtype=int64)
• training=True
• mask=None
</code></pre>
| [
{
"answer_id": 74445578,
"author": "AloneTogether",
"author_id": 9657861,
"author_profile": "https://Stackoverflow.com/users/9657861",
"pm_score": 2,
"selected": true,
"text": "Dense"
},
{
"answer_id": 74445602,
"author": "Andi R",
"author_id": 19768538,
"author_profile": "https://Stackoverflow.com/users/19768538",
"pm_score": 0,
"selected": false,
"text": "X = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\ny = tf.constant(np.array([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]))\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.InputLayer(input_shape=(1,)), # This will take care of dimensions\n tf.keras.layers.Dense(1)\n])\n\nmodel.compile(\n loss=tf.keras.losses.mae,\n optimizer=tf.keras.optimizers.SGD(),\n metrics=[\"mae\"]\n)\n\nmodel.fit(X, y, epochs=10)\n"
},
{
"answer_id": 74446499,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "X = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\ny = tf.constant(np.array([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]))\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Dense(1)\n])\n\nmodel.compile(\n loss=tf.keras.losses.mae,\n optimizer=tf.keras.optimizers.SGD(),\n metrics=[\"mae\"]\n)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13066430/"
] |
74,445,564 | <pre><code>from tkinter import *
window2 = Tk()
Var = ' '
store = ['a', 'b', 'c', 'd']
count = 3
for i in store:
if i != None:
chs_store = Button(window2, text = i).grid(row = count , column = 4)
count += 1
</code></pre>
<p>I made buttons and placed them on the frame like this. In order to place buttons as same as the order of the list. And now I want to put the different commands into each buttons.</p>
<p>ex) If I click the Button that says 'a', I want <code>Var = 'one'</code>, and if I click the Button 'b', I want <code>Var = 'two'</code>.</p>
<p>How should I solve this</p>
| [
{
"answer_id": 74445578,
"author": "AloneTogether",
"author_id": 9657861,
"author_profile": "https://Stackoverflow.com/users/9657861",
"pm_score": 2,
"selected": true,
"text": "Dense"
},
{
"answer_id": 74445602,
"author": "Andi R",
"author_id": 19768538,
"author_profile": "https://Stackoverflow.com/users/19768538",
"pm_score": 0,
"selected": false,
"text": "X = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\ny = tf.constant(np.array([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]))\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.InputLayer(input_shape=(1,)), # This will take care of dimensions\n tf.keras.layers.Dense(1)\n])\n\nmodel.compile(\n loss=tf.keras.losses.mae,\n optimizer=tf.keras.optimizers.SGD(),\n metrics=[\"mae\"]\n)\n\nmodel.fit(X, y, epochs=10)\n"
},
{
"answer_id": 74446499,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "X = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\ny = tf.constant(np.array([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]))\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Dense(1)\n])\n\nmodel.compile(\n loss=tf.keras.losses.mae,\n optimizer=tf.keras.optimizers.SGD(),\n metrics=[\"mae\"]\n)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509836/"
] |
74,445,567 | <p>I am working in Reactjs and i am using "nextjs" framework,Right now i am getting data(blog detail) according to slug([slug.js]) but on the right side of page (sidebar) i want to get data of all other
blogs with same category(cat_name),how can i do this ? Here is my current code</p>
<pre><code>import Axios from "axios";
import {useRouter} from "next/router";
//import LatestBlogs from "../../components/LatestBlogs/LatestBlogs";
import Link from 'next/link'
import { useEffect } from 'react'
//import Header from '../../components/Layout/Header'
const Post = ({ post }) => {
const router = useRouter();
// const htmlString = {post.description_front};
const htmlString = post?.description_front
// console.log({post.});
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<>
<header className="inner-header">
<div className="container">
<nav className='navbar navbar-expand-lg main-header' >
<Link href="/">
<a classNameName="navbar-brand" href=''> <img src="/img/logo1.png" /> </a></Link>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
<span className="navbar-toggler-icon"><img src="/img/list.svg" /></span>
</button>
</nav>
</div>
</header>
<div className="alfa-img">
<div className="container">
<div className="row">
<div className="col-md-7">
<div className="release-time">
<img className="mask-img" src={post.image} />
</div>
<div className="game-re">
<h2>{post.title} !</h2>
{post.description}
</div>
</div>
<div className="col-md-5">
<div className="pined">
<h3>Pinned</h3>
//Following div should be dynamic
<div className="img-content">
<div className="img-pined">
<img className="mask-on" src="/img/Mask Group 11.png" />
</div>
<div className="alfa-lp">
<h4>Alpha Release Time !</h4>
<p>With the launch of our social media and publications, the only question is, &apos; When will the game be released?&apos;
MBG plans to release the game in stages and versions such as alpha - first release, beta - second release, release and versions - which will be the final release and then MBG will release the latest updates through release versions.
Regarding the debut of MBG, the full steps of the game&apos;s release will be announced when the roadmap is released</p>
<h6 className="post-date post">Posted: 14 oct 22</h6>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</>
);
};
export default Post;
export const getStaticProps = async ({ params }) => {
const { data } = await Axios.get(`xxxxxxxxxxxxxxxxxxxxxxxxx/${params.slug}`);
const post = data;
return {
props: {
post,
},
};
};
export const getStaticPaths = async () => {
const { data } = await Axios.get("http://xxxxxxxxxxx.com/xxxxxxxxxxxxxxxx/blogs");
const posts = data.slice(0, 10);
const paths = posts.map((post) => ({ params: { slug: post.slug.toString() } }));
return {
paths,
fallback: true,
};
};
</code></pre>
| [
{
"answer_id": 74445578,
"author": "AloneTogether",
"author_id": 9657861,
"author_profile": "https://Stackoverflow.com/users/9657861",
"pm_score": 2,
"selected": true,
"text": "Dense"
},
{
"answer_id": 74445602,
"author": "Andi R",
"author_id": 19768538,
"author_profile": "https://Stackoverflow.com/users/19768538",
"pm_score": 0,
"selected": false,
"text": "X = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\ny = tf.constant(np.array([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]))\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.InputLayer(input_shape=(1,)), # This will take care of dimensions\n tf.keras.layers.Dense(1)\n])\n\nmodel.compile(\n loss=tf.keras.losses.mae,\n optimizer=tf.keras.optimizers.SGD(),\n metrics=[\"mae\"]\n)\n\nmodel.fit(X, y, epochs=10)\n"
},
{
"answer_id": 74446499,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "X = tf.constant(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\ny = tf.constant(np.array([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]))\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Dense(1)\n])\n\nmodel.compile(\n loss=tf.keras.losses.mae,\n optimizer=tf.keras.optimizers.SGD(),\n metrics=[\"mae\"]\n)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5308126/"
] |
74,445,571 | <p>Im trying to setup a planning for 20 employees and 2 years.
In here I want to hide the weeks that already passed in the input.</p>
<p>Down below is how far I got. After testing it seems to work till the "All" part but can't figure the last part out. With the inputbox I want that the person is able to enter the value based on the first row, 2023 week 1 (20231) till 2024 week 52 (202452).</p>
<p>My goal is that if someone enters the value of 202336 it should show 2023 week 36 and later and it hides the previous weeks.</p>
<p>Is someone able to help me? Thanks in advance!</p>
<pre><code>Sub Hidepastweeks()
Dim myValue As Variant
myValue = InputBox("Weeks visible from week:", "Visable weeks")
Dim c As Range
Range("A2").Value = myValue
With Range("G1:DF1")
Application.ScreenUpdating = False
.EntireColumn.Hidden = (myValue <> "All")
If myValue <> "All" Then
For Each c In Range("G1:DF1").Cells
If c.Value < "myValue" Then
c.EntireColumn.Hidden = True
End If
Next
End If
Application.ScreenUpdating = True
End With
End Sub
</code></pre>
<p>I Tried different sites but they all seem to have an equal to formula instead of lesser then.</p>
| [
{
"answer_id": 74446058,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 2,
"selected": true,
"text": "Application.Match"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509771/"
] |
74,445,588 | <p>I use LayoutBuilder to control the view when the orientation changes, but it rebuilds the view with every change like when a keyboard is up. How can I control when to re-build the widget only when orientation changes?</p>
<pre><code>class ExampleScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
double screenHeight = constraints.maxHeight;
double screenWidth = constraints.maxWidth;
///this function checks the orientation of the device, and it's used
///for the rebuild of the LayoutBuilder to fit both portrait and
///landscape orientations
Get.find<ViewController>().setOrientation(context);
return Scaffold(
backgroundColor: Colors.green,
body: SafeArea(
child: Container(),
),
);
});
}
}
</code></pre>
| [
{
"answer_id": 74446058,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 2,
"selected": true,
"text": "Application.Match"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10412586/"
] |
74,445,620 | <p>I am working on a legacy application with a class named <code>Point3D</code> as shown below...</p>
<pre><code>template <class T>
class Point3D final
{
T values[3];
public:
Point3D();
Point3D(T x, T y, T z);
explicit Point3D(const T value);
Point3D(const Point3D& point);
explicit Point3D(const Point2D<T>& point);
~Point3D();
};
</code></pre>
<p>This class is getting used in many places as <code>vector<Point3D<double>></code>. The size of the vector is > <code>10^5</code>.
Also, the legacy code passes this vector as a value and returns by value. This is making the application very slow.
Also in many places, we have similar codes as shown below...</p>
<pre><code>for(auto i: n){ // This loop runs for 10^4 times
Point3D<double> vpos;
vpos[X_COORDINATE] = /*Some calculation*/;
vpos[Y_COORDINATE] = /*Some calculation*/;
vpos[Z_COORDINATE] = /*Some calculation*/;
Positions.push_back(vpos);
}
</code></pre>
<p>To improve the performance, I plan to modify the <code>Point3D</code> class to use <code>move semantics</code> as shown below...</p>
<pre><code>template <class T>
class Point3D final {
T* values;
public:
Point3D() {
values = new T[3];
}
Point3D(T x, T y, T z) {
values = new T[3];
}
explicit Point3D(const T value) {
values = new T[3];
}
Point3D(const Point3D& point) {
values = new T[3];
}
~Point3D() {
delete[] values;
}
T operator [] (qint64 coordinate) const { return values[coordinate]; }
T& operator [] (qint64 coordinate) { return values[coordinate]; }
Point3D& operator = (const Point3D& point) {
...
return *this;
}
Point3D(Point3D&& other) noexcept : values(other.values)
{
other.values = nullptr;
}
Point3D& operator=(Point3D&& other) noexcept
{
using std::swap;
swap(*this, other);
return *this;
}
};
</code></pre>
<p>I am new to <code>move semantics</code>, please let me know any other ways to improve the performance.
Thanks</p>
| [
{
"answer_id": 74445787,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 2,
"selected": false,
"text": "std::vector"
},
{
"answer_id": 74446144,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 4,
"selected": true,
"text": "Point3D"
},
{
"answer_id": 74446352,
"author": "Hein Breukers",
"author_id": 16860716,
"author_profile": "https://Stackoverflow.com/users/16860716",
"pm_score": 1,
"selected": false,
"text": "Positions.reserve(10000);\nfor(auto i : n)\n{ // This loop runs for 10^4 times\n auto x_coord = /*Some calculation*/;\n auto y_coord = /*Some calculation*/;\n auto z_coord = /*Some calculation*/;\n\n Positions.emplace_back(x_coord,y_coord,z_coord);\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747770/"
] |
74,445,627 | <pre><code>public int userID;
//global variable
public Index()
{
userID = 10;
return userID;
}
public TaskCompleted()
{
Console.WriteLine(Index())
}
</code></pre>
<p>i want the userID to be accessed in each and every method and can we updated anywhere</p>
| [
{
"answer_id": 74445696,
"author": "Cristian Rusanu",
"author_id": 2065371,
"author_profile": "https://Stackoverflow.com/users/2065371",
"pm_score": 0,
"selected": false,
"text": "public static class Globals\n{\n public static int UserID {get; set;}\n}\n"
},
{
"answer_id": 74445803,
"author": "Olivier Jacot-Descombes",
"author_id": 880990,
"author_profile": "https://Stackoverflow.com/users/880990",
"pm_score": 1,
"selected": false,
"text": "Index"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510051/"
] |
74,445,635 | <p>I've recently inherited some code. It has a class called <code>SystemConfig</code> that acts as a grab-bag of constants that are used across the code base. But while a few of the constants are defined directly on that class, a big pile of them are defined as properties of a metaclass of that class. Like this:</p>
<pre><code>class _MetaSystemConfig(type):
@property
define CONSTANT_1(cls):
return "value 1"
@property
define CONSTANT_2(cls):
return "value 2"
...
class SystemConfig(metaclass=_MetaSystemConfig):
CONSTANT_3 = "value 3"
...
</code></pre>
<p>The class is never instantiated; the values are just used as <code>SystemConfig.CONSTANT_1</code> and so on.</p>
<p>No-one who is still involved in the project seems to have any idea why it was done this way, except that someone seems to think the guy who did it thought it made unit testing easier.</p>
<p>Can someone explain to me any advantages of doing it this way and why I shouldn't just move all the properties to the <code>SystemConfig</code> class and delete the metaclass?</p>
<p>Edit to add: The metaclass definition doesn't contain anything other than properties.</p>
| [
{
"answer_id": 74450088,
"author": "Tom",
"author_id": 274460,
"author_profile": "https://Stackoverflow.com/users/274460",
"pm_score": 1,
"selected": false,
"text": "@property"
},
{
"answer_id": 74461814,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "def add_constants(cls):\n cls.CONSTANT_1 = \"value 1\"\n cls.CONSTANT_2 = \"value 2\"\n\n\n@add_constants\nclass SystemConfig:\n CONSTANT_3 = \"value 3\"\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274460/"
] |
74,445,638 | <p>I need to solve a maze using backtracking method.
My maze has 0 listed as a wall, 1 listed as an empty cell, 2 is for visited, 3 for dragon.
Dragons are basically obstacles that I can go through BUT I need to choose the path with the LEAST dragons.
So far I can solve the maze and mark a path, but I can't seem to think of a relatively simple way of finding the path with the least dragons.
Do note we just started coding with C in my uni (so far I've only done java/bash/a bit of python), so I'm really new to C and algorithms in general.</p>
<p>Code is below.</p>
<pre><code>#include <stdio.h>
#define IMPOSSIBLE (N*N+1)
int counter=0;
enum {WALL,EMPTY,VISITED,DRAGON,N};
int printMaze(int maze[N][N])
{
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
printf("%d ",maze[i][j]);
}
printf("\n");
}
}
int solveMaze(int maze[N][N], int i, int j)
{
if (maze[i][j] == WALL){ return 0; } // If [i][j] are currently a wall (0).
if (maze[i][j] == VISITED) { return 0; } // If [i][j] are currently a mark (2).
if (maze[i][j] == DRAGON) { counter++; }
maze[i][j] = VISITED; // Mark current spot with (2).
if (i==N-1 && j==N-1) { return 1; } // reached the end (N-1,N-1) - (3,3) incase N is 4.
if ( ((i < N-1) && solveMaze(maze,i+1,j)) || ((i > 0) && solveMaze(maze,i-1,j)) || ((j < N-1) && solveMaze(maze,i,j+1)) || ((j > 0) && solveMaze(maze,i,j-1)) ) { // checking index-out-bounds + recursively going around the maze
return 1;
}
maze[i][j] = EMPTY;
return 0;
}
int main() {
int maze[N][N] = { {1,1,3,3},
{3,0,1,1},
{3,0,0,1},
{1,3,3,1} };
int solved = solveMaze(maze, 0, 0);
if (solved)
{
printMaze(maze);
printf("Amount of dragons passed through in the maze: %d\n",counter);
}
else
{
printf("No solution, %d\n",IMPOSSIBLE);
}
}
</code></pre>
<p>I tried creating a counter that counts the amount of dragons on the way, but I guess I'm not fluent enough in recursions to make it go in every available path and choose the best one.</p>
| [
{
"answer_id": 74450088,
"author": "Tom",
"author_id": 274460,
"author_profile": "https://Stackoverflow.com/users/274460",
"pm_score": 1,
"selected": false,
"text": "@property"
},
{
"answer_id": 74461814,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "def add_constants(cls):\n cls.CONSTANT_1 = \"value 1\"\n cls.CONSTANT_2 = \"value 2\"\n\n\n@add_constants\nclass SystemConfig:\n CONSTANT_3 = \"value 3\"\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17321893/"
] |
74,445,667 | <p>I have a <code>Set</code> of <code>Integer</code>:</p>
<pre class="lang-java prettyprint-override"><code>Set<Integer> itemSet = new HashSet<Integer>();
itemSet.add(1);
itemSet.add(3);
itemSet.add(5);
</code></pre>
<p>I want to convert it into an array of <code>Integer</code> where the value of each element in the array is double the value of the corresponding element in original <code>Set</code>. According to the above example, the array elements should be:</p>
<pre><code>2, 6, 10
</code></pre>
<p>I tried:</p>
<pre class="lang-java prettyprint-override"><code>
Integer[] itemArr1 = itemSet.toArray((val) -> {
Integer[] it = new Integer[]{val*2};
return it;
}
);
</code></pre>
<p>but the values are not getting doubled.</p>
| [
{
"answer_id": 74446049,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 1,
"selected": false,
"text": "toArray()"
},
{
"answer_id": 74450229,
"author": "oleg.cherednik",
"author_id": 3461397,
"author_profile": "https://Stackoverflow.com/users/3461397",
"pm_score": 2,
"selected": false,
"text": "IntStream"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14907157/"
] |
74,445,728 | <p>I want to search for files with .2fa extension on remote computers. I can find the files I want, but it takes a long time to get to the second computer because it scans all windows files.</p>
<p>I tried the -exclude and where arguments but they do not work.</p>
<p>Could you please help me? Thanks.</p>
<pre><code>$ServerList = Import-Csv 'C:\PC.CSV'
$result = foreach ($pc in $ServerList.barkod) {
$exclude = '*ProgramData*','*Program Files*','*Program Files (x86)*','*Windows*'.'*winupdate*'
$sourcepath = 'c$'
Get-ChildItem -Path \\$pc\$sourcepath -Recurse | Where-Object { $_.Name -like "*.2fa" } |
where {$_.name -notin $Exclude}
}
$result
</code></pre>
<p>I tried</p>
<p>-Exclude $exclude
-where {$_.name -notin $Exclude}</p>
| [
{
"answer_id": 74446049,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 1,
"selected": false,
"text": "toArray()"
},
{
"answer_id": 74450229,
"author": "oleg.cherednik",
"author_id": 3461397,
"author_profile": "https://Stackoverflow.com/users/3461397",
"pm_score": 2,
"selected": false,
"text": "IntStream"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19896510/"
] |
74,445,744 | <p>Can I use a batch for temporal calculation, but eventually not include it in the results?</p>
<p>For example, I want to use 'temporal' tabular for calculation of other queries, but I do not want to get it later in the results (because it's too large). I.e. the results should contain <em>only Tables X and Y</em>.</p>
<pre><code>requests
| take 1000
| as temporal;
temporal | summarize count() | as X;
temporal | summarize avg(duration) | as Y;
</code></pre>
<p>P.s. using 'let' is impossible in my scenario</p>
| [
{
"answer_id": 74446049,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 1,
"selected": false,
"text": "toArray()"
},
{
"answer_id": 74450229,
"author": "oleg.cherednik",
"author_id": 3461397,
"author_profile": "https://Stackoverflow.com/users/3461397",
"pm_score": 2,
"selected": false,
"text": "IntStream"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9652134/"
] |
74,445,750 | <pre><code>import time
i = 1
def sendData(x):
time.sleep(5)
print("delayed data: ", x)
while (1):
print(i)
sendData(i)
i += 1
time.sleep(0.5)
</code></pre>
<p>What I want is to print a value every 5 seconds while the infinite loop runs.
so I can see the values printing very .5 seconds and another value being printed every 5 seconds.
At the moment, the loop still gets delayed because of the time.sleep(5) in the helper function. Any help is appreciated. Thank you.</p>
| [
{
"answer_id": 74445881,
"author": "TomerG",
"author_id": 1885248,
"author_profile": "https://Stackoverflow.com/users/1885248",
"pm_score": 3,
"selected": false,
"text": "threading"
},
{
"answer_id": 74445986,
"author": "Eugene Yalansky",
"author_id": 6808501,
"author_profile": "https://Stackoverflow.com/users/6808501",
"pm_score": 1,
"selected": false,
"text": "import asyncio\n\n\nasync def send_data(x):\n await asyncio.sleep(5) # Could be network request as well\n print(\"delayed data: \", x)\n\n\nasync def main():\n i = 1\n while True:\n print(i)\n # Create non blocking task (run in background)\n asyncio.create_task(send_data(i)) \n i += 1\n await asyncio.sleep(0.5)\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n\n"
},
{
"answer_id": 74454592,
"author": "Nindi",
"author_id": 20505208,
"author_profile": "https://Stackoverflow.com/users/20505208",
"pm_score": 0,
"selected": false,
"text": "# importing module\nimport time\n \n \n# running loop from 0 to 4\nfor i in range(0,5):\n \n # printing numbers\n print(\"delayed data: \", i)\n \n # adding 0.5 seconds time delay\n time.sleep(0.5)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383052/"
] |
74,445,805 | <p>I have a pyspark dataframe <code>df</code> :-</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>status</th>
<th style="text-align: center;">Flag</th>
</tr>
</thead>
<tbody>
<tr>
<td>present</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>present</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td>na</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>Void</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td>present</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>notpresent</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td>present</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td>present</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td>ok</td>
<td style="text-align: center;">1</td>
</tr>
</tbody>
</table>
</div>
<p>I want to update the <code>Flag</code> as 1 wherever we have status is <code>present</code> or <code>ok</code> :-</p>
<p>Expected :-</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>status</th>
<th style="text-align: center;">Flag</th>
</tr>
</thead>
<tbody>
<tr>
<td>present</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>present</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>na</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>Void</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td>present</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>notpresent</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td>present</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>present</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td>ok</td>
<td style="text-align: center;">1</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74445933,
"author": "ScootCork",
"author_id": 4700327,
"author_profile": "https://Stackoverflow.com/users/4700327",
"pm_score": 2,
"selected": true,
"text": "withColumn"
},
{
"answer_id": 74446408,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "df.withColumn('Flag', col('status').isin(['ok', 'present']).astype('int')).show()\n\n+----------+----+\n| status|Flag|\n+----------+----+\n| present| 1|\n| ok| 1|\n| present| 1|\n| void| 0|\n| na| 1|\n|notpresent| 0|\n+----------+----+\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14353779/"
] |
74,445,827 | <p>I am making a video player using pygame, it takes numpy arrays of frames from a video file and streams them to a pygame window using a buffer.</p>
<p>I'm getting a weird issue where CPU usage is increasing <em>(program is slowing down)</em> over time, then CPU usage is sharply decreasing <em>(program is speeding up)</em>. Memory usage stays pretty much constant, so I don't think it's a memory leak. This affects the program as I'm trying to stream a video, and long processing times turn it into a slideshow.</p>
<p>I would expect fluctuations, but not that steep. I cannot seem to figure what is going on here, I would really appreciate some help in debugging this!</p>
<hr />
<p>Source code to replicate the issue at the end of the question. You can use any
.mp4 file, but the exact one I used is <a href="https://drive.google.com/file/d/1_tfTVHmaoTEYxkLrjVS8NiAvdes3Gd77/view?usp=share_link" rel="nofollow noreferrer">here to download</a>. This
also outputs a log.txt file which I am using to debug the issue. My findings are below...</p>
<hr />
<p><strong>In the first few seconds, process time is relatively fast:</strong></p>
<pre><code>[12:13:31] (Variable: current_frame) 1
[12:13:31] (Variable: len(frame_buffer)) 3
[12:13:31] (Process time) 0.08 seconds
</code></pre>
<p><strong>It steadily slows over the duration of about 30 seconds, until it hits peak slowness at ~0.5 seconds of process time:</strong></p>
<pre><code>[12:14:07] (Variable: current_frame) 154
[12:14:07] (Variable: len(frame_buffer)) 3
[12:14:07] (Process time) 0.53 seconds
</code></pre>
<p><strong>Then it dips down to previous levels:</strong></p>
<pre><code>[12:14:11] (Variable: current_frame) 164
[12:14:11] (Variable: len(frame_buffer)) 3
[12:14:11] (Process time) 0.1 seconds
</code></pre>
<p>Here is a graph I made using matplotlib to identify the trend over ~1000 frames:
<a href="https://i.stack.imgur.com/kQomW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kQomW.png" alt="enter image description here" /></a></p>
<pre><code>import cv2
import time
import pygame
import gc
from datetime import datetime
#Debug code
runtime_start = str(datetime.now().strftime("%H-%M-%S"))
def log(prefix, message):
string = "[" + str(datetime.now().strftime("%H:%M:%S")) + "] " + "(" + str(prefix) + ") " + str(message)
print(string)
with open(file="log" + runtime_start + ".txt", mode="a", encoding="utf-8") as file:
file.write(string + "\n")
### ### ###
#Globals
buffer_size = 3
frame_buffer = []
### ### ###
#Functions
def loadVideoFileToMemory(file):
"""
Load file to memory.
"""
global capture
capture = cv2.VideoCapture(file)
def getFrameFromVideo(file, frame_number):
"""
Captures a frame from the loaded file, returns a numpy image array.
"""
#capture = cv2.VideoCapture(file)
capture.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
ret, frame = capture.read()
#image = ImageTk.PhotoImage(image=Image.fromarray(frame))
image = cv2.resize(frame, (90*6, 160*6))
del frame
gc.collect()
return image
def setBuffer(start_frame):
"""
Fills the buffer at a set starting frame before playing the video.
"""
frame_buffer.clear()
for i in range(buffer_size):
frame_buffer.append(getFrameFromVideo("test_video1.mp4", start_frame + i))
def updateBuffer(frame):
"""
Updates frame_buffer, deals with garabge collection.
"""
del frame_buffer[0]
gc.collect()
if len(frame_buffer) < buffer_size: #Limits to buffer size
frame_array = getFrameFromVideo("test_video1.mp4", frame + buffer_size)
frame_buffer.append(frame_array)
del frame_array
gc.collect()
def displayImageToPygame(image, window):
"""
Converts a numpy image array to a pygame surface and blits to screen.
"""
window.blit(pygame.surfarray.make_surface(image), (0,0))
def createPygameWindow():
"""
Creates a pygame window, sets the frame_buffer and starts the main thread.
"""
window = pygame.display.set_mode((160*6, 90*6))
pygame.display.flip()
#Starting frame
current_frame = 0
setBuffer(current_frame) #Set from this position
displayImageToPygame(frame_buffer[0], window) #Show starting frame
pygameThread(window, current_frame)
def pygameThread(window, current_frame):
"""
Main thread. Plays the video.
"""
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
timer_start = time.time() #DEBUG: PROCESSING TIME
current_frame += 1
displayImageToPygame(frame_buffer[1], window)
updateBuffer(current_frame)
pygame.display.flip()
#DEBUG: POST TO LOG.TXT
log("Variable: current_frame", current_frame)
log("Variable: len(frame_buffer)", len(frame_buffer))
timer_end = time.time() #DEBUG: PROCESSING TIME
log("Process time", str(round(timer_end - timer_start, 2)) + " seconds")
###
### ### ###
video_file = "test_video1.mp4" #Replace this with a path to an .mp4 file. You can download the exact file I'm using here: https://drive.google.com/file/d/1_tfTVHmaoTEYxkLrjVS8NiAvdes3Gd77/view?usp=share_link
loadVideoFileToMemory(video_file)
createPygameWindow()
</code></pre>
| [
{
"answer_id": 74445933,
"author": "ScootCork",
"author_id": 4700327,
"author_profile": "https://Stackoverflow.com/users/4700327",
"pm_score": 2,
"selected": true,
"text": "withColumn"
},
{
"answer_id": 74446408,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "df.withColumn('Flag', col('status').isin(['ok', 'present']).astype('int')).show()\n\n+----------+----+\n| status|Flag|\n+----------+----+\n| present| 1|\n| ok| 1|\n| present| 1|\n| void| 0|\n| na| 1|\n|notpresent| 0|\n+----------+----+\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9888447/"
] |
74,445,879 | <p>I have the following sample dataframe called df (<code>dput</code> below):</p>
<pre><code> group date indicator
1 A 2022-11-01 01:00:00 FALSE
2 A 2022-11-01 03:00:00 FALSE
3 A 2022-11-01 04:00:00 TRUE
4 A 2022-11-01 05:00:00 FALSE
5 A 2022-11-01 06:00:00 TRUE
6 A 2022-11-01 07:00:00 FALSE
7 A 2022-11-01 10:00:00 FALSE
8 A 2022-11-01 12:00:00 FALSE
9 B 2022-11-01 01:00:00 FALSE
10 B 2022-11-01 02:00:00 FALSE
11 B 2022-11-01 03:00:00 FALSE
12 B 2022-11-01 06:00:00 TRUE
13 B 2022-11-01 07:00:00 FALSE
14 B 2022-11-01 08:00:00 FALSE
15 B 2022-11-01 11:00:00 TRUE
16 B 2022-11-01 13:00:00 FALSE
</code></pre>
<p>I would like to calculate the difference in hours between dates with their nearest conditioned rows which have <code>indicator == TRUE</code> per group. Also, the rows with TRUE should return 0 as output. Here you can see the desired output called df_desired:</p>
<pre><code> group date indicator diff_hours
1 A 2022-11-01 01:00:00 FALSE 3
2 A 2022-11-01 03:00:00 FALSE 1
3 A 2022-11-01 04:00:00 TRUE 0
4 A 2022-11-01 05:00:00 FALSE 1
5 A 2022-11-01 06:00:00 TRUE 0
6 A 2022-11-01 07:00:00 FALSE 1
7 A 2022-11-01 10:00:00 FALSE 4
8 A 2022-11-01 12:00:00 FALSE 6
9 B 2022-11-01 01:00:00 FALSE 5
10 B 2022-11-01 02:00:00 FALSE 4
11 B 2022-11-01 03:00:00 FALSE 3
12 B 2022-11-01 06:00:00 TRUE 0
13 B 2022-11-01 07:00:00 FALSE 1
14 B 2022-11-01 08:00:00 FALSE 2
15 B 2022-11-01 11:00:00 TRUE 0
16 B 2022-11-01 13:00:00 FALSE 2
</code></pre>
<p>So I was wondering if anyone knows how to calculate the difference between dates in hours with respect to their nearest conditioned row per group?</p>
<hr />
<p>Here <code>dput</code> of df and df_desired:</p>
<pre><code>df <- structure(list(group = c("A", "A", "A", "A", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B"), date = structure(c(1667260800,
1667268000, 1667271600, 1667275200, 1667278800, 1667282400, 1667293200,
1667300400, 1667260800, 1667264400, 1667268000, 1667278800, 1667282400,
1667286000, 1667296800, 1667304000), class = c("POSIXct", "POSIXt"
), tzone = ""), indicator = c(FALSE, FALSE, TRUE, FALSE, TRUE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE,
TRUE, FALSE)), class = "data.frame", row.names = c(NA, -16L))
df_desired <- structure(list(group = c("A", "A", "A", "A", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B"), date = structure(c(1667260800,
1667268000, 1667271600, 1667275200, 1667278800, 1667282400, 1667293200,
1667300400, 1667260800, 1667264400, 1667268000, 1667278800, 1667282400,
1667286000, 1667296800, 1667304000), class = c("POSIXct", "POSIXt"
), tzone = ""), indicator = c(FALSE, FALSE, TRUE, FALSE, TRUE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE,
TRUE, FALSE), diff_hours = c(3, 1, 0, 1, 0, 1, 4, 6, 5, 4, 3,
0, 1, 2, 0, 2)), class = "data.frame", row.names = c(NA, -16L
))
</code></pre>
| [
{
"answer_id": 74446061,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": false,
"text": "data.table"
},
{
"answer_id": 74446151,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 4,
"selected": true,
"text": "map_dbl"
},
{
"answer_id": 74446198,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "tidyr::fill()"
},
{
"answer_id": 74446692,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": false,
"text": "#Maël answer in base R\nby(df, df$group, \\(d) transform(\n d, diff_hours = sapply(d$date, \\(x) min(abs(x - d$date[d[[\"indicator\"]]])))\n )) |>\n do.call(what = rbind.data.frame)\n#> group date indicator diff_hours\n#> A.1 A 2022-10-31 20:00:00 FALSE 3\n#> A.2 A 2022-10-31 22:00:00 FALSE 1\n#> A.3 A 2022-10-31 23:00:00 TRUE 0\n#> A.4 A 2022-11-01 00:00:00 FALSE 1\n#> A.5 A 2022-11-01 01:00:00 TRUE 0\n#> A.6 A 2022-11-01 02:00:00 FALSE 1\n#> A.7 A 2022-11-01 05:00:00 FALSE 4\n#> A.8 A 2022-11-01 07:00:00 FALSE 6\n#> B.9 B 2022-10-31 20:00:00 FALSE 5\n#> B.10 B 2022-10-31 21:00:00 FALSE 4\n#> B.11 B 2022-10-31 22:00:00 FALSE 3\n#> B.12 B 2022-11-01 01:00:00 TRUE 0\n#> B.13 B 2022-11-01 02:00:00 FALSE 1\n#> B.14 B 2022-11-01 03:00:00 FALSE 2\n#> B.15 B 2022-11-01 06:00:00 TRUE 0\n#> B.16 B 2022-11-01 08:00:00 FALSE 2\n\n#ThomasIsCoding answer in base\ntransform(df, diff_hours = apply(abs(outer(df$date, df$date[df$indicator], `-`))/3600, 1, min))\n#> group date indicator diff_hours\n#> 1 A 2022-10-31 20:00:00 FALSE 3\n#> 2 A 2022-10-31 22:00:00 FALSE 1\n#> 3 A 2022-10-31 23:00:00 TRUE 0\n#> 4 A 2022-11-01 00:00:00 FALSE 1\n#> 5 A 2022-11-01 01:00:00 TRUE 0\n#> 6 A 2022-11-01 02:00:00 FALSE 1\n#> 7 A 2022-11-01 05:00:00 FALSE 1\n#> 8 A 2022-11-01 07:00:00 FALSE 1\n#> 9 B 2022-10-31 20:00:00 FALSE 3\n#> 10 B 2022-10-31 21:00:00 FALSE 2\n#> 11 B 2022-10-31 22:00:00 FALSE 1\n#> 12 B 2022-11-01 01:00:00 TRUE 0\n#> 13 B 2022-11-01 02:00:00 FALSE 1\n#> 14 B 2022-11-01 03:00:00 FALSE 2\n#> 15 B 2022-11-01 06:00:00 TRUE 0\n#> 16 B 2022-11-01 08:00:00 FALSE 2\n"
},
{
"answer_id": 74447076,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "apply"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14282714/"
] |
74,445,921 | <p>For this vectorial function I want to evaluate the jacobian:</p>
<pre><code>import jax
import jax.numpy as jnp
def myf(arr, phi_0, phi_1, phi_2, lambda_0, R):
arr = jnp.deg2rad(arr)
phi_0 = jnp.deg2rad(phi_0)
phi_1 = jnp.deg2rad(phi_1)
phi_2 = jnp.deg2rad(phi_2)
lambda_0 = jnp.deg2rad(lambda_0)
n = jnp.sin(phi_1)
F = 2.0
rho_0 = 1.0
rho = R*F*(1/jnp.tan(jnp.pi/4 + arr[1]/2))**n
x_L = rho*jnp.sin(n*(arr[0] - lambda_0))
y_L = rho_0 - rho*jnp.cos(n*(arr[0] - lambda_0))
return jnp.array([x_L,y_L])
arr = jnp.array([-18.1, 29.9])
jax.jacobian(myf)(arr, 29.5, 29.5, 29.5, -17.0, R=1)
</code></pre>
<p>I obtain</p>
<pre><code>[[ 0.01312758 0.00014317]
[-0.00012411 0.01514319]]
</code></pre>
<p>I'm in shock with these values. Take for instance the element <code>[0][0], 0.01312758</code>. We know it's the partial of <code>x_L</code> with respect to the variable <code>arr[0]</code>. Whether by hand or using sympy that derivative is ~0.75.</p>
<pre><code>from sympy import *
x, y = symbols('x y')
x_L = (2.0*(1/tan(3.141592/4 + y/2))**0.492)*sin(0.492*(x + 0.2967))
deriv = Derivative(x_L, x)
deriv.doit()
deriv.doit().evalf(subs={x: -0.3159, y: 0.52})
0.752473089673695
</code></pre>
<p>(inserting <code>x, y</code>, that are <code>arr[0]</code> and <code>arr[1]</code> already in radians). This is also the result I obtain by hand. What is happening with Jax results? I can't see what I'm doing bad.</p>
| [
{
"answer_id": 74447755,
"author": "David",
"author_id": 6010635,
"author_profile": "https://Stackoverflow.com/users/6010635",
"pm_score": 1,
"selected": false,
"text": "jax.jacobian(myf)"
},
{
"answer_id": 74450205,
"author": "jakevdp",
"author_id": 2937831,
"author_profile": "https://Stackoverflow.com/users/2937831",
"pm_score": 3,
"selected": true,
"text": "result = jax.jacobian(myf)(arr, 29.5, 29.5, 29.5, -17.0, R=1)\nprint(result * 180 / jnp.pi)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6010635/"
] |
74,445,936 | <p>I am running a Kafka Cluster Docker Compose on an AWS EC2 instance.
I want to receive all the tweets of a specific keyword and push them to Kafka. This works fine.
But I also want to count the most used words of those tweets.</p>
<p>This is the WordCount code:</p>
<pre><code>import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.StreamsBuilder;
import java.util.Arrays;
import java.util.Properties;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import java.util.concurrent.CountDownLatch;
import static org.apache.kafka.streams.StreamsConfig.APPLICATION_ID_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG;
public class WordCount {
public static void main(String[] args) {
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, String> textLines = builder
.stream("test-topic");
textLines
.flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
.groupBy((key, value) -> value)
.count(Materialized.as("WordCount"))
.toStream()
.to("test-output", Produced.with(Serdes.String(), Serdes.Long()));
final Topology topology = builder.build();
Properties props = new Properties();
props.put(APPLICATION_ID_CONFIG, "streams-word-count");
props.put(BOOTSTRAP_SERVERS_CONFIG, "ec2-ip:9092");
props.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
final KafkaStreams streams = new KafkaStreams(topology, props);
final CountDownLatch latch = new CountDownLatch(1);
Runtime.getRuntime().addShutdownHook(
new Thread("streams-shutdown-hook") {
@Override
public void run() {
streams.close();
latch.countDown();
}
});
try {
streams.start();
latch.await();
} catch (Throwable e) {
System.exit(1);
}
System.exit(0);
}
}
</code></pre>
<p>When I check the output topic in the Control Center, it looks like this:</p>
<p><a href="https://i.stack.imgur.com/1Z2l5.png" rel="nofollow noreferrer">Key</a></p>
<p><a href="https://i.stack.imgur.com/9co4b.png" rel="nofollow noreferrer">Value</a></p>
<p>Looks like it's working as far as splitting the tweets into single words. But the count value isn't in Long format, although it is specified in the code.</p>
<p>When I use the kafka-console-consumer to consume from this topic, it says:</p>
<p>"Size of data received by LongDeserializer is not 8"</p>
| [
{
"answer_id": 74446413,
"author": "leccionesonline",
"author_id": 1370047,
"author_profile": "https://Stackoverflow.com/users/1370047",
"pm_score": -1,
"selected": false,
"text": "KStream<String, String> textLines = builder.stream(\"test-topic\", Consumed.with(stringSerde, stringSerde));\n\nKTable<String, Long> wordCounts = textLines \n .flatMapValues(value -> Arrays.asList(value.toLowerCase().split(\"\\\\W+\")))\n .groupBy((key, value) -> value) \n .count()\n .toStream()\n .to(\"test-output\", Produced.with(Serdes.String(), Serdes.Long()));\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510283/"
] |
74,445,959 | <p>I'm having a child component that get some data from a form. And passes that to a parent component via the @Output decorator. Pressing a button triggers getDataFromForm()</p>
<pre><code>export class FormChildComponent {
@Output() doSomethingWithData: EventEmitter<any> = new EventEmitter<any>()
...
getDataFromForm(){
...
this.doSomethingWithData.emit(form.values);
}
renderSomething(?data){
//This needs to be called in anther child after the event got
triggered and the data got processed in the parent
}
}
</code></pre>
<p>In the parent component I'm doing some processing with the data, on the button press event in the child. After that I have to render something based on the processed data in another child, which is the same child component type as above.</p>
<p>parent.component.html</p>
<pre><code><FormChildComponent (doSomethingWithData)="processData($event)">
</code></pre>
<p>parent.component.ts</p>
<pre><code>processData($event: object){
doSomething($event);
}
</code></pre>
<p>What's the best practice to pass events and data between children and their parent?</p>
| [
{
"answer_id": 74446019,
"author": "Fabian Strathaus",
"author_id": 17298437,
"author_profile": "https://Stackoverflow.com/users/17298437",
"pm_score": 0,
"selected": false,
"text": "@Input()"
},
{
"answer_id": 74446248,
"author": "Chris Hamilton",
"author_id": 12914833,
"author_profile": "https://Stackoverflow.com/users/12914833",
"pm_score": 1,
"selected": false,
"text": "export type DataType = { name: string };\n\n@Injectable({ providedIn: 'root' })\nexport class MyService {\n dataSubject = new Subject<DataType>();\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14525017/"
] |
74,445,979 | <p>I need to find a file with a .gz extension among files in a loop and extract some data from it and print it.</p>
<p>i have folders like d091,d092,.....,d150 and under these folders there are different files with .gz extension. I need to print some data from these .gz files. the location of the data in the file as I specified.</p>
<p>this is the code i try to use but it didn't work. how can i specify the path in for loop?</p>
<pre><code>shopt -s nullglob
shopt -s failglob
for k in {091..099}; do
for file in $(ls *.gz)
do
echo ${file:0:4} | tee -a receiver_ids
echo ${file:16:17} | tee -a doy
echo ${file:0:100} | tee -a data_record
done
done
</code></pre>
| [
{
"answer_id": 74446448,
"author": "Martian",
"author_id": 2068539,
"author_profile": "https://Stackoverflow.com/users/2068539",
"pm_score": -1,
"selected": false,
"text": "for file in $(find . -name \"*.gz\"); do \n file=$(basename ${file})\n echo ${file:0:4} | tee -a receiver_ids\n echo ${file:16:17} | tee -a doy\n echo ${file:0:100} | tee -a data_record \ndone\n"
},
{
"answer_id": 74447298,
"author": "Bruno",
"author_id": 3079831,
"author_profile": "https://Stackoverflow.com/users/3079831",
"pm_score": 0,
"selected": false,
"text": "echo | tee"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510244/"
] |
74,445,988 | <p>I have a simple layout with image on Left and Title of blog on right with light grey background for large screen or were width is minimum 800px. for smaller screens it should show image on top and Title below image. It is working fine except two thing</p>
<ol>
<li>It show extra space under image which is shown as yellow background in this case.</li>
<li>I want Title Item to be same height as Image element with light grey background, in this case which is represented as red.</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-container {
display: flex;
align-items: stretch;
flex-direction: row;
border: 1px solid blue;
height: 100%;
}
.flex-container>div {
background-color: yellow;
color: #555;
width: 50%;
height: 100%;
margin: 0px;
text-align: center;
align-self: center;
font-size: 30px;
}
.title-wrapper {
background-color: #f00 !important;
}
.imgx {
width: 100%;
}
@media (max-width: 800px) {
.flex-container {
flex-direction: column;
}
.flex-container>div {
width: 100%;
margin: 0px;
}
.imgx {
width: 100%;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
<div class="image-wrapper"><img class="imgx" src="https://dummyimage.com/600x400/000/add413&text=IMAGE"></div>
<div class="title-wrapper">This is the title</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74446143,
"author": "c.m.",
"author_id": 19850943,
"author_profile": "https://Stackoverflow.com/users/19850943",
"pm_score": -1,
"selected": false,
"text": ".flex-container > div {\n background-color: yellow;\n color: #555;\n width: 50%;\n margin: 0px;\n text-align: center;\n font-size: 30px;\n}\n"
},
{
"answer_id": 74446287,
"author": "Pete",
"author_id": 1790982,
"author_profile": "https://Stackoverflow.com/users/1790982",
"pm_score": 1,
"selected": false,
"text": "display: block"
},
{
"answer_id": 74446295,
"author": "G-Cyrillus",
"author_id": 2442099,
"author_profile": "https://Stackoverflow.com/users/2442099",
"pm_score": 3,
"selected": true,
"text": "vertical-align:"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74445988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122748/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.