instruction stringlengths 0 30k ⌀ |
|---|
The most efficient approach is to sort both lists by time then concurrent run through both lists. Complexity is 2 sorts plus O(n), where "n = min(runEvents.Count, heartBeats.Count)". But, most probable, both lists are already time-ordered, thus only O(n) remains. |
How can I reshape a 3D NumPy array into a 2D array, while utilizing the data along axis 2 to upscale?e.g. 3D array with shape 2*2*4:
```
array_3d = [[[ 1 2 3 4]
[ 5 6 7 8]]
[[ 9 10 11 12]
[13 14 15 16]]]
reshape to 2D array with shape 4*4:
reshaped_array = [[ 1 2 5 6]
[ 3 4 7 8]
[ 9 10 13 14]
[11 12 15 16]]
```
I've attempted this approach:
```
reshaped_array = array_3d.swapaxes(1, 2).reshape(-1, array_3d.shape[1])
```
But I got:
```
[[ 1 5]
[ 2 6]
[ 3 7]
[ 4 8]
[ 9 13]
[10 14]
[11 15]
[12 16]]
``` |
Reshape a 3D NumPy array to a 2D array, using the data along axis 2 to upscale |
|numpy|numpy-ndarray| |
null |
I have a project to monitorize some parameters with ESP32 (Arduino IDE sketch) and I save result into a gsheets. Every new day gerenate new sheet to save dates. After new sheet creation, I want to insert into sheet a line chart with 3 series using requests addChart. With one serie is ok, but is more explicit evolution of 3 parameters so when I define 3 series in json I receive next error.
"error": {
"code": 400,
"message": "Invalid requests[0].addChart: If specifying more than one sourceRange within a domain or series, each sourceRange across the domain & series must be in order and contiguous.",
"status": "INVALID_ARGUMENT"
Succint what I try:
domain sources: A1:A1000 (time of event) on axis x
series1 sources: B1:B1000 (values of parameter A)
series2 sources: C1:C1000 (values of parameter B)
series2 sources: D1:D1000 (values of parameter C)
Using [https://developers.google.com/sheets/api/samples/charts](https://developers.google.com/sheets/api/samples/charts) this is result.
```
`
{
"requests": [
{
"addChart": {
"chart": {
"spec": {
"basicChart": {
"chartType": "LINE",
"domains": {
"domain": {
"sourceRange": {
"sources": [
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 0,
"endColumnIndex": 1,
"sheetId": 1439439696
},
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 0,
"endColumnIndex": 1,
"sheetId": 1439439696
},
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 0,
"endColumnIndex": 1,
"sheetId": 1439439696
}
]
}
}
},
"series": {
"series": {
"sourceRange": {
"sources": [
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 5,
"endColumnIndex": 6,
"sheetId": 1439439696
},
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 6,
"endColumnIndex": 7,
"sheetId": 1439439696
},
{
"startRowIndex": 1,
"endRowIndex": 1000,
"startColumnIndex": 7,
"endColumnIndex": 8,
"sheetId": 1439439696
}
]
}
}
}
}
},
"position": {
"overlayPosition": {
"anchorCell": {
"sheetId": 1439439696,
"rowIndex": 2,
"columnIndex": 2
}
}
}
}
}
}
}`
```
What I'm wrong?
[What I expected:][1]
[1]: https://i.stack.imgur.com/j4m8Q.jpg |
**html**:
```html
<div class="text-stroke" data-text="Your text">Your text</div>
```
**css**:
```css
.text-stroke {
position: relative;
color: white;
&:after {
content: attr(data-text);
position: absolute;
left: 0;
top: 0;
-webkit-text-stroke: 2px #000;
-webkit-text-fill-color: transparent;
z-index: -1;
}
}
``` |
null |
|azure|azure-powershell|azure-analysis-services| |
null |
I have this carousel that needs a simple operation: appear infinite. The problem is that the animation cuts off and leaves a blank space at the end of the last element. I leave the code below and hope someone can help me.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.slider {
padding-top: 28px;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
overflow: hidden;
}
.slider-items {
display: flex;
justify-content: center;
align-items: center;
gap: 40px;
animation: scroll 30s linear infinite;
}
@keyframes scroll {
0% {
transform: translateX(0%);
}
100% {
transform: translateX(-50%);
}
}
.slider-items img {
width: 12%;
margin: 40px;
filter: grayscale(100%);
}
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div className="slider pb-12">
<div className="slider-items">
<img src="https://picsum.photos/id/237/200/300" alt="" />
<img src="https://picsum.photos/seed/picsum/200/300" alt="" />
<img src="https://picsum.photos/200/300?grayscale" alt="" />
<img src="https://picsum.photos/200/300/?blur" alt="" />
<img src="https://picsum.photos/200/300.jpg" alt="" />
<img src="https://picsum.photos/id/237/200/300" alt="" />
<img src="https://picsum.photos/seed/picsum/200/300" alt="" />
<img src="https://picsum.photos/200/300?grayscale" alt="" />
<img src="https://picsum.photos/seed/picsum/200/300" alt="" />
<img src="https://picsum.photos/200/300?grayscale" alt="" />
<img src="https://picsum.photos/200/300.jpg" alt="" />
<img src="https://picsum.photos/id/237/200/300" alt="" />
</div>
</div>
<!-- end snippet -->
I tried cloning the content, using sass, changing the seconds the animation lasts, the width of all the containers, changing the HTML structure and nothing works for me. |
null |
If you have an infinite `Stream` like a `NetworkStream`, replacing string tokens on-the-fly would make a lot of sense. But because you are processing a finite stream of which you need the *complete* content, such a filtering doesn't make sense because of the performance impact.
My argument is that you would have to use buffering. The size of the buffer is of course restricting the amount of characters you can process. Assuming you use a ring buffer or kind of a queue, you would have to remove one character to append a new. This leads to a lot of drawbacks when compared to processing the complete content.
Pros & Cons
| Full-content search & replace | Buffered (real-time) search & replace |
| -------- | -------------- |
| Single pass over the full range | multiple passes over the same range |
| Advanced search (e.g. backtracking, look-ahead etc.) | Because characters get dropped at the start of the buffer, the search engine loses context |
| Because we have the full context available, we won't ever miss a match | Because characters get dropped at the start of the buffer, there will be edge cases where the searched token does not fit into the buffer. Of course, we can resize the buffer to a length = n * token_length. However, this limitation impacts performance as the optimal buffer size is now constrained by the token size. The worst case is that the token length equals the length of the stream. Based on the search algorithm we would have to keep input in the buffer until we match all key words and then discard the matched part. If there is no match the buffer size would equal the size of the stream. It makes sense to evaluate the expected input and search keys for the worst-case scenarios and switch to a full-context search to get rid of the buffer management overhead. Just to highlight that the efficiency of a real-time search is very much limited by the input and the search keys (expected scenario). It can't be faster than full-context search. It potentially consumes less memory under optimal circumstances. |
| Don't have to worry about an optimal buffer size to maximize efficiency | Buffer size becomes more and more important the longer the source content is. Too small buffers result in too many buffer shifts and too many passes over the same range. Note, the key cost for the original search & replace task is the string search and the replace/modification, so it makes sense to reduce the number of comparisons to an absolute minimum. |
| Consumes more memory. However, this is not relevant in this case as we will store the complete response in (client) memory anyways. And if we use the appropriate text search technique, we avoid all the extra `string` allocations that occur during the search & replace. | Only the size of the buffers are allocated. However, this is not relevant in this case as we will store the complete response in (client) memory anyways.
| Does not allow to filter the stream in real-time (not relevant in this case)). However, a hybrid solution is possible where we would filter certain parts in real-time (e.g. a preamble) | Allows to filter the stream in real-time so that we can make decisions based on content e.g. abort the reading (not relevant in this case).|
I stop here as the most relevant performance costs search & replace are better for the full-content solution. For the real-time search & replace we basically would have to implement our own algorithm that has to compete against the .NET search and replace algorithms. No problem, but considering the effort and the final use case I would not waste any time on that.
An efficient solution could implement a custom `TextReader`, an advanced `StreamReader` that operates on a `StringBuilder` to search and replace characters. While `StringBuilder` offers a significant performance advantage over the string search & replace it does not allow complex search patterns like word boundaries. For example, word boundaries are only possible if the patter explicitly includes the bounding characters.
For example, replacing "int" in the input "internal int " with "pat" produces "paternal pat". If we want to replace only "int" in "internal int " we would have to use regular expression. Because regular expression only operates on `string` we have to pay with efficiency.
The following example implements a `StringReplaceStreamReader` that extends `TextReader` to act as a specialized `StreamReader`. For best performance, tokens are replaced *after* the complete stream has been read.
For brevity it only supports `ReadToEndAsync`, `Read` and `Peak` methods.
It supports simple search where the search pattern is simply matched against the input (called simple-search).
Then it also supports two variants of regular expression search and replace for more advanced search and replace scenarios.
The first variant is based on a set of key-value pairs while the second variant uses a regex pattern provided by the caller.
Because simple-search involves iteration of the source dictionary entries + multiple passes (one for each entry) this search mode is expected to be the slowest algorithm, although the replace using a `StringBuilder` itself is actually faster. Under these circumstances, the `Regex` search & replace is expected to be significantly faster than the simple search and replace using the `StringBuilder` as it can process the input in a single pass.
The `StringReplaceStreamReader` search behavior is configurable via constructor.
Usage example
------------------
```c#
private Dictionary<string, string> replacementTable;
private async Task ReplaceInStream(Stream sourceStream)
{
this.replacementTable = new Dictionary<string, string>
{
{ "private", "internal" },
{ "int", "BUTTON" },
{ "Read", "Not-To-Read" }
};
// Search and replace using simple search
// (slowest).
await using var streamReader = new StringReplaceStreamReader(sourceStream, Encoding.Default, this.replacementTable, StringComparison.OrdinalIgnoreCase);
string text = await streamReader.ReadToEndAsync();
// Search and replace variant #1 using regex with key-value pairs instead of a regular expression pattern
// for advanced scenarios (fast)
await using var streamReader2 = new StringReplaceStreamReader(sourceStream, Encoding.Default, this.replacementTable, SearchMode.Regex);
string text2 = await streamReader2.ReadToEndAsync();
// Search and replace variant #2 using regex and regular expression pattern
// for advanced scenarios (fast).
// The matchEvaluator callback actually provides the replcement value for each match.
// Creates the following regular expression:
// "\bprivate\b|\bint\b|\bRead\b"
string searchPattern = this.replacementTable.Keys
.Select(key => $@"\b{key}\b")
.Aggregate((current, newValue) => $"{current}|{newValue}");
await using var streamReader3 = new StringReplaceStreamReader(sourceStream, Encoding.Default, searchPattern, Replace);
string text3 = await streamReader.ReadToEndAsync();
}
private string Replace(Match match)
=> this.replacementTable.TryGetValue(match.Value, out string replacement)
? replacement
: match.Value;
```
Implementation
-------------------
**SearchMode**
```c#
public enum SearchMode
{
Default = 0,
Simple,
Regex
}
```
**StringReplaceStreamReader.cs**
```c#
public class StringReplaceStreamReader : TextReader, IDisposable, IAsyncDisposable
{
public Stream BaseStream { get; }
public long Length => this.BaseStream.Length;
public bool EndOfStream => this.BaseStream.Position == this.BaseStream.Length;
public SearchMode SearchMode { get; }
private const int DefaultCapacity = 4096;
private readonly IDictionary<string, string> stringReplaceTable;
private readonly StringComparison stringComparison;
private readonly Encoding encoding;
private readonly Decoder decoder;
private readonly MatchEvaluator? matchEvaluator;
private readonly Regex? regularExpression;
private readonly byte[] byteBuffer;
private readonly char[] charBuffer;
public StringReplaceStreamReader(Stream stream, Encoding encoding, IDictionary<string, string> stringReplaceTable)
: this(stream, encoding, stringReplaceTable, StringComparison.OrdinalIgnoreCase, SearchMode.Simple)
{
}
public StringReplaceStreamReader(Stream stream, Encoding encoding, IDictionary<string, string> stringReplaceTable, SearchMode searchMode)
: this(stream, encoding, stringReplaceTable, StringComparison.OrdinalIgnoreCase, searchMode)
{
}
public StringReplaceStreamReader(Stream stream, Encoding encoding, IDictionary<string, string> stringReplaceTable, StringComparison stringComparison)
: this(stream, encoding, stringReplaceTable, stringComparison, SearchMode.Simple)
{
}
public StringReplaceStreamReader(Stream stream, Encoding encoding, IDictionary<string, string> stringReplaceTable, StringComparison stringComparison, SearchMode searchMode)
{
ArgumentNullException.ThrowIfNull(stream, nameof(stream));
ArgumentNullException.ThrowIfNull(stringReplaceTable, nameof(stringReplaceTable));
this.BaseStream = stream;
this.encoding = encoding ?? Encoding.Default;
this.decoder = this.encoding.GetDecoder();
this.stringReplaceTable = stringReplaceTable;
this.stringComparison = stringComparison;
this.SearchMode = searchMode;
this.regularExpression = null;
this.matchEvaluator = ReplaceMatch;
if (searchMode is SearchMode.Regex)
{
RegexOptions regexOptions = CreateDefaultRegexOptions(stringComparison);
var searchPatternBuilder = new StringBuilder();
foreach (KeyValuePair<string, string> entry in stringReplaceTable)
{
// Creates the following regular expression:
// "\b[search_key]\b|\b[search_key]\b"
string pattern = @$"\b{entry.Key}\b";
searchPatternBuilder.Append(pattern);
searchPatternBuilder.Append('|');
}
string searchPattern = searchPatternBuilder.ToString().TrimEnd('|');
this.regularExpression = new Regex(searchPattern, regexOptions);
}
this.byteBuffer = new byte[StringReplaceStreamReader.DefaultCapacity];
int charBufferSize = this.encoding.GetMaxCharCount(this.byteBuffer.Length);
this.charBuffer = new char[charBufferSize];
}
public StringReplaceStreamReader(Stream stream, Encoding encoding, string searchAndReplacePattern, MatchEvaluator matchEvaluator)
: this(stream, encoding, searchAndReplacePattern, matchEvaluator, RegexOptions.None)
{
}
public StringReplaceStreamReader(Stream stream, Encoding encoding, string searchAndReplacePattern, MatchEvaluator matchEvaluator, RegexOptions regexOptions)
{
ArgumentNullException.ThrowIfNull(stream, nameof(stream));
ArgumentNullException.ThrowIfNullOrWhiteSpace(searchAndReplacePattern, nameof(searchAndReplacePattern));
ArgumentNullException.ThrowIfNull(matchEvaluator, nameof(matchEvaluator));
this.BaseStream = stream;
this.encoding = encoding ?? Encoding.Default;
this.decoder = this.encoding.GetDecoder();
this.matchEvaluator = matchEvaluator;
this.SearchMode = SearchMode.Regex;
this.stringReplaceTable = new Dictionary<string, string>();
this.stringComparison = StringComparison.OrdinalIgnoreCase;
if (regexOptions is RegexOptions.None)
{
regexOptions = CreateDefaultRegexOptions(stringComparison);
}
else if ((regexOptions & RegexOptions.Compiled) == 0)
{
regexOptions |= RegexOptions.Compiled;
}
this.regularExpression = new Regex(searchAndReplacePattern, regexOptions);
this.byteBuffer = new byte[StringReplaceStreamReader.DefaultCapacity];
int charBufferSize = this.encoding.GetMaxCharCount(this.byteBuffer.Length);
this.charBuffer = new char[charBufferSize];
}
public override int Peek()
{
int value = Read();
this.BaseStream.Seek(this.BaseStream.Position - 1, SeekOrigin.Begin);
return value;
}
public override int Read()
=> this.BaseStream.ReadByte();
public override Task<string> ReadToEndAsync()
=> ReadToEndAsync(CancellationToken.None);
public override async Task<string> ReadToEndAsync(CancellationToken cancellationToken)
{
if (!this.BaseStream.CanRead)
{
throw new InvalidOperationException("Source stream is not readable.");
}
var textBuilder = new StringBuilder(StringReplaceStreamReader.DefaultCapacity);
int bytesRead = 0;
int charsRead = 0;
while (!this.EndOfStream)
{
cancellationToken.ThrowIfCancellationRequested();
bytesRead = await this.BaseStream.ReadAsync(buffer, 0, buffer.Length);
bool flush = this.EndOfStream;
charsRead = this.decoder.GetChars(this.byteBuffer, 0, bytesRead, this.charBuffer, 0, flush);
textBuilder.Append(charBuffer, 0, charsRead);
}
cancellationToken.ThrowIfCancellationRequested();
SearchAndReplace(textBuilder, cancellationToken, out string result);
return result;
}
public ValueTask DisposeAsync()
=> ((IAsyncDisposable)this.BaseStream).DisposeAsync();
private void SearchAndReplace(StringBuilder textBuilder, CancellationToken cancellationToken, out string result)
{
cancellationToken.ThrowIfCancellationRequested();
if (this.SearchMode is SearchMode.Simple or SearchMode.Default)
{
foreach (KeyValuePair<string, string> entry in this.stringReplaceTable)
{
cancellationToken.ThrowIfCancellationRequested();
textBuilder.Replace(entry.Key, entry.Value);
}
result = textBuilder.ToString();
}
else if (this.SearchMode is SearchMode.Regex)
{
string input = textBuilder.ToString();
result = this.regularExpression!.Replace(input, this.matchEvaluator!);
}
else
{
throw new NotImplementedException($"Search mode {this.SearchMode} is not implemented.");
}
}
private string ReplaceMatch(Match match)
=> this.stringReplaceTable.TryGetValue(match.Value, out string replacement)
? replacement
: match.Value;
private RegexOptions CreateDefaultRegexOptions(StringComparison stringComparison)
{
RegexOptions regexOptions = RegexOptions.Multiline | RegexOptions.Compiled;
if (stringComparison is StringComparison.CurrentCultureIgnoreCase or StringComparison.InvariantCultureIgnoreCase or StringComparison.OrdinalIgnoreCase)
{
regexOptions |= RegexOptions.IgnoreCase;
}
return regexOptions;
}
}
``` |
I'm running Arch on WSL2 and using ZSH as my shell with Windows Terminal as my terminal emulator. Is there any way to make it so that when you select any text, and type something, the selected text gets replaced like all modern text editors and Windows Powershell? Currently, when I select something and type, the text gets deselected and what i typed just goes before or after the selected text depending on which side I selected the text from (I have enabled selection through ctrl+shift+arrowkey just like modern editors). |
def set_dict_keys():
my_dict = {1: 'VDD', 2: 'VDD', 7: 'VDD', 0: 0, 3: 0, 4: 0, 6: 9, 13: 9, 'GND': 'GND', 15: 'GND', 12: 12}
print(my_dict)
output = {}
mappings = {}
current_value = 1
for key, value in my_dict.items():
if value not in ['VDD', 'GND']:
if value not in mappings:
mappings[value] = current_value
current_value += 1
output[key] = mappings[value]
else:
output[key] = value
print(output)
set_dict_keys()
The idea is to keep a mapping of values to IDs, then loop through all `my_dict` items and update the `output` dict. |
I want to tune a model using a custom class probability metric "pg", which stands for partial gini coefficient. I use it on data that exists of numerical predictors and a binary factor as class label (after preprocessing with the recipe). This is the tuning code:
```
xgb_folds <- train %>% vfold_cv(v=5)
xgb_model <- parsnip::boost_tree(
mode = "classification",
trees = tune(),
tree_depth = tune(),
learn_rate = tune(),
loss_reduction = tune()
) %>%
set_engine("xgboost")
xgb_wf <- workflow() %>%
add_recipe(TREE_recipe) %>%
add_model(xgb_model)
xgboost_tuned <- tune::tune_grid(
object = xgb_wf,
resamples = xgb_folds,
grid = hyperparameters_XGB_tidy,
metrics = metric_set(pg),
control = tune::control_grid(verbose = TRUE)
```
The code above worked when I set the metric in tune_grid to roc_auc. When using pg however I get this warning: `Warning message:
All models failed. Run 'show_notes(.Last.tune.result)' for more information.`
The .Last.tune.result contains this error:
```
unique notes:
────────────────────────────────────────────────────────────────────────────────────────────────────
Error in `metric_set()`:
! Failed to compute `pg()`.
Caused by error in `UseMethod()`:
! no applicable method for 'pg' applied to an object of class "c('grouped_df', 'tbl_df', 'tbl', 'data.frame')"
```
This is the yardstick implementation for pg I tried:
(running pg_vec on class probabilities and label vectors worked as expected)
```
# partialGini for tidymodels
library(tidymodels, rlang)
pg_impl <- function(truth, estimate, case_weights = NULL) {
sorted_indices <- order(estimate, decreasing = TRUE)
sorted_probs <- estimate[sorted_indices]
sorted_actuals <- truth[sorted_indices]
# Select subset with PD < 0.4
subset_indices <- which(sorted_probs < 0.4)
subset_probs <- sorted_probs[subset_indices]
subset_actuals <- sorted_actuals[subset_indices]
# Check if there are both positive and negative cases in the subset
if (length(unique(subset_actuals)) > 1) {
# Calculate ROC curve for the subset
roc_subset <- pROC::roc(subset_actuals, subset_probs,
direction = "<", quiet = TRUE)
# Calculate AUC for the subset
partial_auc <- pROC::auc(roc_subset)
# Calculate partial Gini coefficient
(2 * partial_auc - 1)
} else return(NA)
}
pg_vec <- function(truth, estimate, estimator = NULL, na_rm = TRUE, case_weights = NULL, ...) {
abort_if_class_pred(truth)
estimator <- finalize_estimator(truth, estimator)
check_prob_metric(truth, estimate, case_weights, estimator)
if (na_rm) {
result <- yardstick_remove_missing(truth, estimate, case_weights)
truth <- result$truth
estimate <- result$estimate
case_weights <- result$case_weights
} else if (yardstick_any_missing(truth, estimate, case_weights)) {
return(NA_real_)
}
pg_impl(truth, estimate, case_weights = case_weights)
}
pg <- function(data, ...) {
UseMethod("pg")
}
pg <- new_prob_metric(pg, direction = "maximize")
pg.data.frame <- function(data, truth, ..., na_rm = TRUE) {
prob_metric_summarizer(
name = "pg",
fn = pg_vec,
data = data,
truth = !! enquo(truth),
...,
na_rm = na_rm)
}
``` |
How to do transaction on concurrency situation in nestjs, prisma |
|mysql|concurrency|parallel-processing|nestjs|prisma| |
null |
Try doing:
pip install -U datasets
>This error stems from a breaking change in fsspec. It has been fixed in the latest datasets release (2.14.6). Updating the installation with pip install -U datasets should fix the issue.
git link : https://github.com/huggingface/datasets/issues/6352
************
If you are using `fsspec`, then do:
pip install fsspec==2023.9.2
There is a problem with `fsspec==2023.10.0`
git link : https://github.com/huggingface/datasets/issues/6330
****
***
**Edit**: Looks like it broken again in `2.17` and `2.18` downgrading to `2.16` should work. |
JS, the problem of not detecting the overlap status of the cards |
```py
interval_ranges = [df['A'].iloc[0]] + df['B'].tolist()
(
df2.assign(interval=pd.cut(df2['Point'], interval_ranges))
.merge(
df.assign(interval=pd.cut(df['B'], interval_ranges))
)
.assign(Returned_Data=lambda x: x['A'] + x['B'])
)
Point interval A B Returned_Data
0 11.5 (10, 20] 11 20 31
1 18.3 (10, 20] 11 20 31
2 31.3 (30, 40] 31 40 71
3 41.2 (40, 50] 41 50 91
4 51.5 (50, 60] 51 60 111
5 66.6 (60, 70] 61 70 131
6 34.7 (30, 40] 31 40 71
7 12.1 (10, 20] 11 20 31
8 14.4 (10, 20] 11 20 31
9 56.8 (50, 60] 51 60 111
10 54.3 (50, 60] 51 60 111
```
```py
In [5]: interval_ranges = [df['A'].iloc[0]] + df['B'].tolist()
In [6]: df.assign(interval=pd.cut(df['B'], interval_ranges))
Out[6]:
A B interval
0 0 10 (0, 10]
1 11 20 (10, 20]
2 21 30 (20, 30]
3 31 40 (30, 40]
4 41 50 (40, 50]
5 51 60 (50, 60]
6 61 70 (60, 70]
In [7]: df2.assign(interval=pd.cut(df2['Point'], interval_ranges))
Out[7]:
Point interval
0 11.5 (10, 20]
1 18.3 (10, 20]
2 31.3 (30, 40]
3 41.2 (40, 50]
4 51.5 (50, 60]
5 66.6 (60, 70]
6 34.7 (30, 40]
7 12.1 (10, 20]
8 14.4 (10, 20]
9 56.8 (50, 60]
10 54.3 (50, 60]
In [8]: df2.assign(interval=pd.cut(df2['Point'], interval_ranges)).merge(df.assign(interval=pd.cut(df['B'], interval_r
...: anges)))
Out[183]:
Point interval A B
0 11.5 (10, 20] 11 20
1 18.3 (10, 20] 11 20
2 31.3 (30, 40] 31 40
3 41.2 (40, 50] 41 50
4 51.5 (50, 60] 51 60
5 66.6 (60, 70] 61 70
6 34.7 (30, 40] 31 40
7 12.1 (10, 20] 11 20
8 14.4 (10, 20] 11 20
9 56.8 (50, 60] 51 60
10 54.3 (50, 60] 51 60
In [9]: df2.assign(interval=pd.cut(df2['Point'], interval_ranges)).merge(df.assign(interval=pd.cut(df['B'], interval_r
...: anges))).assign(Returned_Data=lambda x: x['A'] + x['B'])
Out[184]:
Point interval A B Returned_Data
0 11.5 (10, 20] 11 20 31
1 18.3 (10, 20] 11 20 31
2 31.3 (30, 40] 31 40 71
3 41.2 (40, 50] 41 50 91
4 51.5 (50, 60] 51 60 111
5 66.6 (60, 70] 61 70 131
6 34.7 (30, 40] 31 40 71
7 12.1 (10, 20] 11 20 31
8 14.4 (10, 20] 11 20 31
9 56.8 (50, 60] 51 60 111
10 54.3 (50, 60] 51 60 111
```
1. create the bins - `interval_ranges = [df['A'].iloc[0]] + df['B'].tolist()`
2. create your join column in both dfs using `pd.cut(df['B'], interval_ranges)` and `pd.cut(df2['Point'], interval_ranges)`
3. merge both dfs on this join column
4. create your `Returned_Data` column by adding the `A` and `B` columns |
I own a vps. There we have three minecraft servers and one discord bot. we also have a local mongoDB running on the vps. I have connected to it using node.js mongoose library. I am talking about the discord bot in this case. When I create documents in the mongodb, it works, and the code reads everything. Suddenly, after about 2-3 hours, every single document i created, is deleted. Its really annoying, and makes the bot completely useless. There are no errors, no logs, it just deletes them. When hosting the mongodb publicly, everything works, and nothing is getting deleted, so its not the code. There are no TTL indexes as far as I know, but I couldn't find any reliable documentation on how to check using mongoose.
I am just trying to host my bot on a VPS, its my first time doing so. Because we want to avoid dataleaks, we decided to host the mongoDB locally on the VPS, we need the mongoDB to communicate over all the servers (minecraft and discord). Since everything works, and nothing is being deleted when hosting the mongoDB using atlas, I would think hosting it on the VPS would work. When we tried contacting the support team on the VPS service, they said they couldn't do anything as this is a problem with mongoDB |
It may be related to how you handle the initial render after refreshing.
useEffect(() => {
const getProduct = async () => {
if (params?.slug) {
try {
const { data } = await axios.get(
`/api/pp/product/get-product/${params.slug}`
);
setProduct(data?.product);
} catch (error) {
console.log(error);
}
}
};
getProduct();
}, [params?.slug]);
Try fetching the product details on every render. The usage of async/await may cause the `undefined` error.
----------
Always render the product only when it has been fetched and updated in the `state`.
{product && (
<>
<div className="col-md-6">
<img
src={`/api/pp/product/productPhoto/${product._id}`}
width={"300"}
height={"250"}
/>
</div>
<div className="col-md-6">
<h1>product details</h1>
</div>
</>
)} |
I use VSCode Server as a Home Assistant integration, but I think, as it is based on VSCode Web, there should be no difference. I have just installed it, and right from the beginning, the context menu looks transparent. I can't imagine this would be helpful for someone. Is this a weird setting or extension, like in this thread?:
https://stackoverflow.com/questions/76857254/how-to-fix-vs-code-displaying-as-see-through-or-transparent
Or do you think it is a Home Assistant-related bug?
[enter image description here](https://i.stack.imgur.com/ajOC5.png)
I looked up the GlassIt-VSC extension but it is uninstalled. |
How to fix transparent VSCode context menu in Home Assistant? |
|visual-studio-code|home-assistant|vs-code-settings| |
null |
I create a file using `nano file.txt` . I typed in `Hello` hit enter and then typed `mate`.
How do I replace the linefeed character in this file with `\\n` so that I can substitute this value later when I build valid json data.
Right now this is my bash script
```
#!/bin/bash
expected_output=$(<file.txt)
expected_output=${expected_output//\\/\\\\}
JSON_FMT='{"output":"%s"}'
printf "%s" "$expected_output" >> aaa.txt
```
the file `aaa.txt` is being read by a different programming language where I decode the json. |
export const GET = async () => {
console.log('Request Made on Get Posts...');
try {
await connect();
const posts = await Post.find().sort({ createdAt: -1 }).limit(20);
if (posts.length === 0) {
return Response.status(404).json({ error: "Posts not found" });
}
return Response.status(200).json({ posts });
} catch (e) {
console.error(e);
return Response.status(500).json({ error: "Database error" });
}
} |
here is my code
**this code not work on safari.**
```
function ScrollToActiveTab(item, id, useraction) {
if (item !== null && item !== undefined && useraction) {
dispatch(addCurrentMenu(item));
}
requestAnimationFrame(() => {
// Ensure this runs after any pending layout changes
var scrollableDiv = document.getElementById('scrollableDiv');
let tempId = 'targetId-' + id;
var targetElement = document.getElementById(tempId);
if (targetElement) {
var targetPosition = targetElement.offsetLeft + targetElement.clientWidth / 2 - window.innerWidth / 2;
// Perform the scroll
scrollableDiv.scrollLeft = targetPosition;
}
});
}
```
Please guide my why ° scrollableDiv.scrollLeft = targetPosition;° not work on safari. Thanks
i want work scrollableDiv.scrollLeft = targetPosition , in safari also |
|python|pandas| |
Yep figured it out I actually refiened the schema. Now I have a Master collection and API rule
@reauest.auth.id = user.id
to view and list the records. Here user is the assigned user to a record. When user creates a record it automatically assigns it. |
after running commands
./gradlew clean
./gradlew assembleRelease
it gives error
Task :@react-native-camera-roll_camera-roll:compileReleaseJavaWithJavac
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Users\aksha\Desktop\Akshay\node_modules@react-native-camera-roll\camera-roll\android\src\main\java\com\reactnativecommunity\cameraroll\CameraRollPackage.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Task :react-native-camera-roll_camera-roll:copyReleaseJniLibsProjectAndLocalJars FAILED
FAILURE: Build failed with an exception.
What went wrong:
A problem was found with the configuration of task ':react-native-camera-roll_camera-roll:copyReleaseJniLibsProjectAndLocalJars' (type 'LibraryJniLibsTask').
Gradle detected a problem with the following location: 'C:\Users\aksha\Desktop\Akshay\node_modules@react-native-camera-roll\camera-roll\android\build\intermediates\stripped_native_libs\release\out'.
Reason: Task ':react-native-camera-roll_camera-roll:copyReleaseJniLibsProjectAndLocalJars' uses this output of task ':@react-native-camera-roll_camera-roll:stripReleaseDebugSymbols' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed.
Possible solutions:
Declare task ':@react-native-camera-roll_camera-roll:stripReleaseDebugSymbols' as an input of ':react-native-camera-roll_camera-roll:copyReleaseJniLibsProjectAndLocalJars'.
Declare an explicit dependency on ':@react-native-camera-roll_camera-roll:stripReleaseDebugSymbols' from ':react-native-camera-roll_camera-roll:copyReleaseJniLibsProjectAndLocalJars' using Task#dependsOn.
Declare an explicit dependency on ':@react-native-camera-roll_camera-roll:stripReleaseDebugSymbols' from ':react-native-camera-roll_camera-roll:copyReleaseJniLibsProjectAndLocalJars' using Task#mustRunAfter.
For more information, please refer to https://docs.gradle.org/8.3/userguide/validation_problems.html#implicit_dependency in the Gradle documentation.
Try:
Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.
Get more help at https://help.gradle.org.
Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.
You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
For more on this, please refer to https://docs.gradle.org/8.3/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.
BUILD FAILED in 29s
how to solve this problem |
You can use the following script to Remotely and Locally modify the Security Policy, with my script you can run against multiple machines, users, and user rights:
[Link to my Get / Set User Rights Blog Post][1].
You can copy and paste the script to the Powershell ISE, just **edit line 437** *(near bottom of script)* to include the required parameters `-UserRight` and `-Add` *or* `-Remove`. The other parameters are optional `-ComputerName`, `-UserName`:
```powershell
<#
.Synopsis
Add and Remove User Right(s) for defined user(s) and computer(s).
.DESCRIPTION
Add and Remove User Rights via Powershell.
.PARAMETER AddRight
You want to Add a user right.
.Parameter ComputerName
Defines the name of the computer where the user right should be granted. This can be multiple values, comma seperated.
Default is the local computer on which the script is run.
.PARAMETER RemoveRight
You want to Remove a user right.
.Parameter Username
Defines the Username under which the service should run. This can be multiple values, comma seperated.
Use the form: domain\Username.
Default is the user under which the script is run.
.PARAMETER UserRight
Defines the User Right you want to set. This can be multiple values, comma seperated.
Name of the right you want to add to: SeServiceLogonRight
There is no default for this argument
All of the Options you can use:
Replace a process level token (SeAssignPrimaryTokenPrivilege)
Generate security audits (SeAuditPrivilege)
Back up files and directories (SeBackupPrivilege)
Log on as a batch job (SeBatchLogonRight)
Bypass traverse checking (SeChangeNotifyPrivilege)
Create global objects (SeCreateGlobalPrivilege)
Create a pagefile (SeCreatePagefilePrivilege)
Create permanent shared objects (SeCreatePermanentPrivilege)
Create symbolic links (SeCreateSymbolicLinkPrivilege)
Create a token object (SeCreateTokenPrivilege)
Debug programs (SeDebugPrivilege)
Obtain an impersonation token for another user in the same session (SeDelegateSessionUserImpersonatePrivilege)
Deny log on as a batch job (SeDenyBatchLogonRight)
Deny log on locally (SeDenyInteractiveLogonRight)
Deny access to this computer from the network (SeDenyNetworkLogonRight)
Deny log on through Remote Desktop Services (SeDenyRemoteInteractiveLogonRight)
Deny log on as a service (SeDenyServiceLogonRight)
Enable computer and user accounts to be trusted for delegation (SeEnableDelegationPrivilege)
Impersonate a client after authentication (SeImpersonatePrivilege)
Increase scheduling priority (SeIncreaseBasePriorityPrivilege)
Adjust memory quotas for a process (SeIncreaseQuotaPrivilege)
Increase a process working set (SeIncreaseWorkingSetPrivilege)
Allow log on locally (SeInteractiveLogonRight)
Load and unload device drivers (SeLoadDriverPrivilege)
Lock pages in memory (SeLockMemoryPrivilege)
Add workstations to domain (SeMachineAccountPrivilege)
Perform volume maintenance tasks (SeManageVolumePrivilege)
Access this computer from the network (SeNetworkLogonRight)
Profile single process (SeProfileSingleProcessPrivilege)
Modify an object label (SeRelabelPrivilege)
Allow log on through Remote Desktop Services (SeRemoteInteractiveLogonRight)
Force shutdown from a remote system (SeRemoteShutdownPrivilege)
Restore files and directories (SeRestorePrivilege)
Manage auditing and security log (SeSecurityPrivilege)
Log on as a service (SeServiceLogonRight)
Shut down the system (SeShutdownPrivilege)
Synchronize directory service data (SeSyncAgentPrivilege)
Modify firmware environment values (SeSystemEnvironmentPrivilege)
Profile system performance (SeSystemProfilePrivilege)
Change the system time (SeSystemtimePrivilege)
Take ownership of files or other objects (SeTakeOwnershipPrivilege)
Act as part of the operating system (SeTcbPrivilege)
Change the time zone (SeTimeZonePrivilege)
Access Credential Manager as a trusted caller (SeTrustedCredManAccessPrivilege)
Remove computer from docking station (SeUndockPrivilege)
.Example
Usage:
Single Users
Add User Right "Log on as a service" for CONTOSO\User:
.\Set-UserRights.ps1 -AddRight -Username CONTOSO\User -UserRight SeServiceLogonRight
Add User Right "Log on as a batch job" for CONTOSO\User:
.\Set-UserRights.ps1 -AddRight -Username CONTOSO\User -UserRight SeBatchLogonRight
Remove User Right "Log on as a batch job" for CONTOSO\User:
.\Set-UserRights.ps1 -RemoveRight -Username CONTOSO\User -UserRight SeBatchLogonRight
Add User Right "Allow log on locally" for current user:
.\Set-UserRights.ps1 -AddRight -UserRight SeInteractiveLogonRight
Remove User Right "Allow log on locally" for current user:
.\Set-UserRights.ps1 -RemoveRight -UserRight SeInteractiveLogonRight
Multiple Users / Services / Computers
Add User Right "Log on as a service" and "Log on as a batch job" for CONTOSO\User and run on, local machine and SQL.contoso.com:
.\Set-UserRights.ps1 -AddRight -UserRight SeServiceLogonRight, SeBatchLogonRight -ComputerName $env:COMPUTERNAME, SQL.contoso.com -UserName CONTOSO\User1, CONTOSO\User2
.Notes
Original Creator: Bill Loytty (weloytty)
Based on this script found here: https://github.com/weloytty/QuirkyPSFunctions/blob/main/Source/Users/Grant-LogOnAsService.ps1
I modified to my own needs: https://github.com/blakedrumm/SCOM-Scripts-and-SQL/blob/master/Powershell/General%20Functions/Set-UserRights.ps1
My blog post: https://blakedrumm.com/blog/set-and-check-user-rights-assignment/
Author: Blake Drumm (blakedrumm@microsoft.com)
First Created on: January 5th, 2022
Last Modified on: October 12th, 2022
#>
param
(
[Parameter(Position = 0,
HelpMessage = 'You want to Add a user right.')]
[Alias('add')]
[switch]$AddRight,
[Parameter(Position = 1)]
[Alias('computer')]
[array]$ComputerName,
[Parameter(Position = 2,
HelpMessage = 'You want to Remove a user right.')]
[switch]$RemoveRight,
[Parameter(Position = 3)]
[Alias('user')]
[array]$Username,
[Parameter(Mandatory = $false,
Position = 4)]
[ValidateSet('SeNetworkLogonRight', 'SeBackupPrivilege', 'SeChangeNotifyPrivilege', 'SeSystemtimePrivilege', 'SeCreatePagefilePrivilege', 'SeDebugPrivilege', 'SeRemoteShutdownPrivilege', 'SeAuditPrivilege', 'SeIncreaseQuotaPrivilege', 'SeIncreaseBasePriorityPrivilege', 'SeLoadDriverPrivilege', 'SeBatchLogonRight', 'SeServiceLogonRight', 'SeInteractiveLogonRight', 'SeSecurityPrivilege', 'SeSystemEnvironmentPrivilege', 'SeProfileSingleProcessPrivilege', 'SeSystemProfilePrivilege', 'SeAssignPrimaryTokenPrivilege', 'SeRestorePrivilege', 'SeShutdownPrivilege', 'SeTakeOwnershipPrivilege', 'SeDenyNetworkLogonRight', 'SeDenyInteractiveLogonRight', 'SeUndockPrivilege', 'SeManageVolumePrivilege', 'SeRemoteInteractiveLogonRight', 'SeImpersonatePrivilege', 'SeCreateGlobalPrivilege', 'SeIncreaseWorkingSetPrivilege', 'SeTimeZonePrivilege', 'SeCreateSymbolicLinkPrivilege', 'SeDelegateSessionUserImpersonatePrivilege', 'SeMachineAccountPrivilege', 'SeTrustedCredManAccessPrivilege', 'SeTcbPrivilege', 'SeCreateTokenPrivilege', 'SeCreatePermanentPrivilege', 'SeDenyBatchLogonRight', 'SeDenyServiceLogonRight', 'SeDenyRemoteInteractiveLogonRight', 'SeEnableDelegationPrivilege', 'SeLockMemoryPrivilege', 'SeRelabelPrivilege', 'SeSyncAgentPrivilege', IgnoreCase = $true)]
[Alias('right')]
[array]$UserRight
)
BEGIN
{
Write-Output '==================================================================='
Write-Output '========================== Start of Script ======================='
Write-Output '==================================================================='
$checkingpermission = "Checking for elevated permissions..."
$scriptout += $checkingpermission
Write-Output $checkingpermission
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$currentPath = $myinvocation.mycommand.definition
$nopermission = "Insufficient permissions to run this script. Attempting to open the PowerShell script ($currentPath) as administrator."
$scriptout += $nopermission
Write-Warning $nopermission
# We are not running "as Administrator" - so relaunch as administrator
# ($MyInvocation.Line -split '\.ps1[\s\''\"]\s*', 2)[-1]
Start-Process powershell.exe "-File", ('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
break
}
else
{
$permissiongranted = " Currently running as administrator - proceeding with script execution..."
Write-Output $permissiongranted
}
Function Time-Stamp
{
$TimeStamp = Get-Date -UFormat "%B %d, %Y @ %r"
return "$TimeStamp - "
}
}
PROCESS
{
function Inner-SetUserRights
{
param
(
[Parameter(Position = 0,
HelpMessage = 'You want to Add a user right.')]
[Alias('add')]
[switch]$AddRight,
[Parameter(Position = 1)]
[Alias('computer')]
[array]$ComputerName,
[Parameter(Position = 2,
HelpMessage = 'You want to Remove a user right.')]
[switch]$RemoveRight,
[Parameter(Position = 3)]
[Alias('user')]
[array]$Username,
[Parameter(Mandatory = $false,
Position = 4)]
[Alias('right')]
[array]$UserRight
)
if (!$UserRight)
{
Write-Warning "Inner Function: Unable to continue because you did not supply the '-UserRight' parameter."
break
}
if (!$AddRight -and !$RemoveRight)
{
Write-Warning "Inner Function: Unable to continue because you did not supply the '-AddRight' or '-RemoveRight' switches."
break
}
elseif ($AddRight -and $RemoveRight)
{
Write-Warning "Inner Function: Unable to continue because you used both the '-AddRight' and '-RemoveRight' switches. Run again with just one of these present, either Add or Remove."
break
}
elseif ($AddRight)
{
Write-Verbose "Inner Function: Detected -AddRight switch in execution."
$ActionType = 'Adding'
}
elseif ($RemoveRight)
{
Write-Verbose "Inner Function: Detected -RemoveRight switch in execution."
$ActionType = 'Removing'
}
else
{
Write-Warning "Something is wrong, detected logic is broken before executing main function. Exiting."
break
}
Function Time-Stamp
{
$TimeStamp = Get-Date -UFormat "%B %d, %Y @ %r"
return "$TimeStamp - "
}
$tempPath = [System.IO.Path]::GetTempPath()
$import = Join-Path -Path $tempPath -ChildPath "import.inf"
if (Test-Path $import) { Remove-Item -Path $import -Force }
$export = Join-Path -Path $tempPath -ChildPath "export.inf"
if (Test-Path $export) { Remove-Item -Path $export -Force }
$secedt = Join-Path -Path $tempPath -ChildPath "secedt.sdb"
if (Test-Path $secedt) { Remove-Item -Path $secedt -Force }
$Error.Clear()
try
{
foreach ($right in $UserRight)
{
$UserLogonRight = switch ($right)
{
"SeBatchLogonRight" { "Log on as a batch job (SeBatchLogonRight)" }
"SeDenyBatchLogonRight" { "Deny log on as a batch job (SeDenyBatchLogonRight)" }
"SeDenyInteractiveLogonRight" { "Deny log on locally (SeDenyInteractiveLogonRight)" }
"SeDenyNetworkLogonRight" { "Deny access to this computer from the network (SeDenyNetworkLogonRight)" }
"SeDenyRemoteInteractiveLogonRight" { "Deny log on through Remote Desktop Services (SeDenyRemoteInteractiveLogonRight)" }
"SeDenyServiceLogonRight" { "Deny log on as a service (SeDenyServiceLogonRight)" }
"SeInteractiveLogonRight" { "Allow log on locally (SeInteractiveLogonRight)" }
"SeNetworkLogonRight" { "Access this computer from the network (SeNetworkLogonRight)" }
"SeRemoteInteractiveLogonRight" { "Allow log on through Remote Desktop Services (SeRemoteInteractiveLogonRight)" }
"SeServiceLogonRight" { "Log on as a service (SeServiceLogonRight)" }
Default { "($right)" }
}
Write-Output ("$(Time-Stamp)$ActionType `"$UserLogonRight`" right for user account: '$Username' on host: '$env:COMPUTERNAME'")
if ($Username -match "^S-.*-.*-.*$|^S-.*-.*-.*-.*-.*-.*$|^S-.*-.*-.*-.*-.*$|^S-.*-.*-.*-.*$")
{
$sid = $Username
}
else
{
$sid = ((New-Object System.Security.Principal.NTAccount($Username)).Translate([System.Security.Principal.SecurityIdentifier])).Value
}
secedit /export /cfg $export | Out-Null
#Change the below to any right you would like
$sids = (Select-String $export -Pattern "$right").Line
if ($ActionType -eq 'Adding')
{
# If right has no value it needs to be added
if ($sids -eq $null)
{
$sids = "$right = *$sid"
$sidList = $sids
}
else
{
$sidList = "$sids,*$sid"
}
}
elseif ($ActionType -eq 'Removing')
{
$sidList = "$($sids.Replace("*$sid", '').Replace("$Username", '').Replace(",,", ',').Replace("= ,", '= '))"
}
Write-Verbose $sidlist
foreach ($line in @("[Unicode]", "Unicode=yes", "[System Access]", "[Event Audit]", "[Registry Values]", "[Version]", "signature=`"`$CHICAGO$`"", "Revision=1", "[Profile Description]", "Description=$ActionType `"$UserLogonRight`" right for user account: $Username", "[Privilege Rights]", "$sidList"))
{
Add-Content $import $line
}
}
secedit /import /db $secedt /cfg $import | Out-Null
secedit /configure /db $secedt | Out-Null
gpupdate /force | Out-Null
Write-Verbose "The script will not delete the following paths due to running in verbose mode, please remove these files manually if needed:"
Write-Verbose "`$import : $import"
Write-Verbose "`$export : $export"
Write-Verbose "`$secedt : $secedt"
if ($VerbosePreference.value__ -eq 0)
{
Remove-Item -Path $import -Force | Out-Null
Remove-Item -Path $export -Force | Out-Null
Remove-Item -Path $secedt -Force | Out-Null
}
}
catch
{
Write-Output ("$(Time-Stamp)Failure occurred while granting `"$right`" to user account: '$Username' on host: '$env:COMPUTERNAME'")
Write-Output "Error Details: $error"
}
}
$InnerSetUserRightFunctionScript = "function Inner-SetUserRights { ${function:Inner-SetUserRights} }"
function Set-UserRights
{
param
(
[Parameter(Position = 0,
HelpMessage = 'You want to Add a user right.')]
[Alias('add')]
[switch]$AddRight,
[Parameter(Position = 1)]
[Alias('computer')]
[array]$ComputerName,
[Parameter(Position = 2,
HelpMessage = 'You want to Remove a user right.')]
[switch]$RemoveRight,
[Parameter(Position = 3)]
[Alias('user')]
[array]$Username,
[Parameter(Mandatory = $false,
Position = 4)]
[ValidateSet('SeNetworkLogonRight', 'SeBackupPrivilege', 'SeChangeNotifyPrivilege', 'SeSystemtimePrivilege', 'SeCreatePagefilePrivilege', 'SeDebugPrivilege', 'SeRemoteShutdownPrivilege', 'SeAuditPrivilege', 'SeIncreaseQuotaPrivilege', 'SeIncreaseBasePriorityPrivilege', 'SeLoadDriverPrivilege', 'SeBatchLogonRight', 'SeServiceLogonRight', 'SeInteractiveLogonRight', 'SeSecurityPrivilege', 'SeSystemEnvironmentPrivilege', 'SeProfileSingleProcessPrivilege', 'SeSystemProfilePrivilege', 'SeAssignPrimaryTokenPrivilege', 'SeRestorePrivilege', 'SeShutdownPrivilege', 'SeTakeOwnershipPrivilege', 'SeDenyNetworkLogonRight', 'SeDenyInteractiveLogonRight', 'SeUndockPrivilege', 'SeManageVolumePrivilege', 'SeRemoteInteractiveLogonRight', 'SeImpersonatePrivilege', 'SeCreateGlobalPrivilege', 'SeIncreaseWorkingSetPrivilege', 'SeTimeZonePrivilege', 'SeCreateSymbolicLinkPrivilege', 'SeDelegateSessionUserImpersonatePrivilege', 'SeMachineAccountPrivilege', 'SeTrustedCredManAccessPrivilege', 'SeTcbPrivilege', 'SeCreateTokenPrivilege', 'SeCreatePermanentPrivilege', 'SeDenyBatchLogonRight', 'SeDenyServiceLogonRight', 'SeDenyRemoteInteractiveLogonRight', 'SeEnableDelegationPrivilege', 'SeLockMemoryPrivilege', 'SeRelabelPrivilege', 'SeSyncAgentPrivilege', IgnoreCase = $true)]
[Alias('right')]
[array]$UserRight
)
if (!$Username)
{
$Username = "$env:USERDOMAIN`\$env:USERNAME"
}
if (!$UserRight)
{
Write-Warning "Main Function: Unable to continue because you did not supply the '-UserRight' parameter."
break
}
if (!$AddRight -and !$RemoveRight)
{
Write-Warning "Main Function: Unable to continue because you did not supply the '-AddRight' or '-RemoveRight' switches."
break
}
elseif ($AddRight -and $RemoveRight)
{
Write-Warning "Main Function: Unable to continue because you used both the '-AddRight' and '-RemoveRight' switches. Run again with just one of these present, either Add or Remove."
break
}
elseif ($AddRight)
{
Write-Verbose "Main Function: Detected -AddRight switch in execution."
$ActionType = 'Adding'
}
elseif ($RemoveRight)
{
Write-Verbose "Main Function: Detected -RemoveRight switch in execution."
$ActionType = 'Removing'
}
if (!$ComputerName)
{
$ComputerName = $env:ComputerName
}
foreach ($user in $Username)
{
foreach ($right in $UserRight)
{
foreach ($computer in $ComputerName)
{
if ($computer -match $env:COMPUTERNAME)
{
Inner-SetUserRights -UserRight $right -Username $user -AddRight:$AddRight -RemoveRight:$RemoveRight
}
else
{
Invoke-Command -ComputerName $Computer -Script {
param ($script,
[string]$Username,
[Parameter(Mandatory = $true)]
[array]$UserRight,
$AddRight,
$RemoveRight,
$VerbosePreference)
. ([ScriptBlock]::Create($script))
$VerbosePreference = $VerbosePreference
$Error.Clear()
try
{
if ($VerbosePreference -eq 0)
{
Inner-SetUserRights -Username $Username -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight
}
else
{
Inner-SetUserRights -Username $Username -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight -Verbose
}
}
catch
{
$info = [PSCustomObject]@{
Exception = $Error.Exception.Message
Reason = $Error.CategoryInfo.Reason
Target = $Error.CategoryInfo.TargetName
Script = $Error.InvocationInfo.ScriptName
Line = $Error.InvocationInfo.ScriptLineNumber
Column = $Error.InvocationInfo.OffsetInLine
Date = Get-Date
User = $env:username
}
Write-Warning "$info"
}
} -ArgumentList $InnerSetUserRightFunctionScript, $user, $right, $AddRight, $RemoveRight, $VerbosePreference
}
}
}
}
}
if ($ComputerName -or $Username -or $UserRight -or $RemoveRight)
{
foreach ($user in $Username)
{
Set-UserRights -ComputerName $ComputerName -Username $user -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight
}
}
else
{
<# Edit line 437 to modify the default command run when this script is executed.
Example:
Set-UserRights -AddRight -UserRight SeServiceLogonRight, SeBatchLogonRight -ComputerName $env:COMPUTERNAME, SQL.contoso.com -UserName CONTOSO\User1, CONTOSO\User2
or
Set-UserRights -AddRight -UserRight SeBatchLogonRight -Username S-1-5-11
or
Set-UserRights -RemoveRight -UserRight SeBatchLogonRight -Username CONTOSO\User2
or
Set-UserRights -RemoveRight -UserRight SeServiceLogonRight, SeBatchLogonRight -Username CONTOSO\User1
#>
Set-UserRights
}
}
END
{
Write-Output "$(Time-Stamp)Script Completed!"
}
```
[1]: https://blakedrumm.com/blog/set-and-check-user-rights-assignment/ |
I have the following code snippet.
```
template<typename T>
void test3(const T& x)
{
std::cout << std::is_const_v<T> << std::endl;
std::cout << std::is_reference_v<decltype(x)> << std::endl;
std::cout << std::is_const_v<decltype(x)> << std::endl;
std::cout << std::endl;
}
int main() {
int x = 5;
int& rx = x;
const int cx = 5;
const int& crx = 5;
std::cout << std::boolalpha;
{
test3(x);
test3(rx);
test3(cx);
test3(crx);
}
return 0;
}
```
The statement `std::is_const_v<decltype(x)>` yields false for all calls of the test3(const T& x) function. My understanding was since the const qualifier is specified as part of the function argument, this statement would yield true, but it prints false every time. Wanted to ask why this is the case and/or if I am missing something? |
C++ - constness of template type deduction |
|c++|templates|type-deduction| |
null |
I have the following code snippet.
```
template<typename T>
void test3(const T& x)
{
std::cout << std::is_const_v<T> << std::endl;
std::cout << std::is_reference_v<decltype(x)> << std::endl;
std::cout << std::is_const_v<decltype(x)> << std::endl;
std::cout << std::endl;
}
int main() {
int x = 5;
int& rx = x;
const int cx = 5;
const int& crx = 5;
std::cout << std::boolalpha;
{
test3(x);
test3(rx);
test3(cx);
test3(crx);
}
return 0;
}
```
The statement `std::is_const_v<decltype(x)>` yields false for all calls of the `test3(const T& x)` function. My understanding was since the const qualifier is specified as part of the function argument, this statement would yield true, but it prints false every time. Wanted to ask why this is the case and/or if I am missing something? |
`GestureDetector` requires a child Widget to execute, the Gesture behaviour will execute on the child widget. |
```
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<title>Game Cards App</title>
<link rel="icon" type="image/png" href="https://cdn1.iconfinder.com/data/icons/entertainment-events-hobbies/24/card-game-cards-hold-512.png">
<style>
.card-partially-visible {
pointer-events: none;
}
#main-content {
display: none;
}
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-flow: column wrap;
background: radial-gradient(circle, rgba(7, 50, 22, 255) 0%, rgba(0, 0, 0, 255) 100%);
animation: shine 4s linear infinite;
color: white;
font-family: "Lato";
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
ul {
margin: 0;
padding: 0;
list-style-type: none;
max-width: 800px;
width: 100%;
margin: 0 auto;
padding: 15px;
text-align: center;
overflow-x: hidden;
}
.card {
float: left;
position: relative;
width: calc(33.33% - 30px + 9.999px);
height: 340px;
margin: 0 30px 30px 0;
perspective: 1000;
}
.card:first-child .card__front {
background:#5271C2;
}
.card__front img {
width: 100%;
height: 100%;
object-fit: cover;
}
.card:first-child .card__num {
text-shadow: 1px 1px rgba(52, 78, 147, 0.8)
}
.card:nth-child(2) .card__front {
background:#35a541;
}
.card:nth-child(2) .card__num {
text-shadow: 1px 1px rgba(34, 107, 42, 0.8);
}
.card:nth-child(3) {
margin-right: 0;
}
.card:nth-child(3) .card__front {
background: #bdb235;
}
.card:nth-child(3) .card__num {
text-shadow: 1px 1px rgba(129, 122, 36, 0.8);
}
.card:nth-child(4) .card__front {
background: #db6623;
}
.card:nth-child(4) .card__num {
text-shadow: 1px 1px rgba(153, 71, 24, 0.8);
}
.card:nth-child(5) .card__front {
background: #3e5eb3;
}
.card:nth-child(5) .card__num {
text-shadow: 1px 1px rgba(42, 64, 122, 0.8);
}
.card:nth-child(6) .card__front {
background: #aa9e5c;
}
.card:nth-child(6) .card__num {
text-shadow: 1px 1px rgba(122, 113, 64, 0.8);
}
.card:last-child {
margin-right: 0;
}
.card__flipper {
cursor: pointer;
transform-style: preserve-3d;
transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1);
border: 3.5px solid rgba(255, 215, 0, 0.6);
background-image: linear-gradient(45deg, rgba(255, 215, 0, 0.5), transparent, rgba(255, 215, 0, 0.5));
}
.card__front, .card__back {
position: absolute;
backface-visibility: hidden;
top: 0;
left: 0;
width: 100%;
height: 340px;
}
.card__front {
transform: rotateY(0);
z-index: 2;
overflow: hidden;
}
.card__back {
transform: rotateY(180deg) scale(1.1);
background: linear-gradient(45deg, #483D8B, #301934, #483D8B, #301934);
display: flex;
flex-flow: column wrap;
align-items: center;
justify-content: center;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.card__back span {
font-weight: bold; /* Metni kalın yap */
color: white; /* Beyaz renk */
font-size: 16px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.card__name {
font-size: 32px;
line-height: 0.9;
font-weight: 700;
}
.card__name span {
font-size: 14px;
}
.card__num {
font-size: 100px;
margin: 0 8px 0 0;
font-weight: 700;
}
@media (max-width: 700px) {
.card__num {
font-size: 70px;
}
}
@media (max-width: 700px) {
.card {
width: 100%;
height: 290px;
margin-right: 0;
float: none;
}
.card .card__front,
.card .card__back {
height: 290px;
overflow: hidden;
}
}
/* Demo */
main {
text-align: center;
}
main h1, main p {
margin: 0 0 12px 0;
}
main h1 {
margin-top: 12px;
font-weight: 300;
}
.fa-github {
color: white;
font-size: 50px;
margin-top: 8px;
}
.tm-container {
display: flex;
justify-content: center;
align-items: center;
}
.tm-letter {
display:inline-block;
font-size:30px;
margin: 0 5px;
margin-top: 10px;
opacity: 0;
transform: translateY(0);
animation: letter-animation 6s ease-in-out infinite;
}
@keyframes letter-animation {
0%, 100% {
opacity: 1;
transform: translateY(0);
}
10%, 40%, 60%, 90% {
opacity: 1;
transform: translateY(-10px);
}
20%, 80% {
opacity: 1;
transform: translateY(0);
}
}
#m-letter {
animation-delay: 1.5s;
}
a {
position: relative;
display: inline-block;
padding: 0px;
}
a::before {
content: '';
position: absolute;
top: 50%; /* Orta konumu */
left: 50%; /* Orta konumu */
transform: translate(-50%, -50%);
width: 50px;
height: 45px;
border-radius: 50%; /* Eğer bir daire şeklinde efekt isteniyorsa */
box-shadow: 0 0 8px 4px rgba(110, 110, 110, 0.8);
filter: blur(4px) brightness(1.5); /
opacity: 0;
transition: opacity 0.3s ease, transform 0.3s ease;
z-index: -1;
}
a:hover::before {
opacity: 1;
}
body.hoverEffect {
background: radial-gradient(circle at center, #000000, #000033, #000066, #1a1a1a);
}
#gameCard {
width: 300px;
height: 450px;
margin: 50px auto;
padding: 20px;
border-radius: 15px;
box-shadow:
0 0 50px 10px #FFD700,
0 0 100px 20px #0000FF,
0 0 150px 30px #000033;
background: rgba(0,0,0,0.7);
color:#FFD700;
text-align: center;
border: 3px solid #FFD700;
}
#gameCardLink span {
font-size: 18px;
margin-right: 5px;
font-weight: bold;
}
#gameCardLink span:last-child {
font-size: 0.79em;
vertical-align: super;
opacity: 0.9;
font-weight: bold;
text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
}
#loading-animation {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image:url('data:image/jpeg;base64,/);
background-repeat: no-repeat;
background-size: cover ;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
}
.loader {
border-top: 9px solid #00a2ed;
border-radius: 80%;
width: 12vw;
height: 12vw;
animation: spin 2s linear infinite;
position: absolute;
left: 44%;
top: 46%; /
transform: translate(-50%, -50%) rotate(0deg); /* Yuvarlak halkanın tam ortasında olması için bu dönüşümü kullanın. */
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div id="loading-animation">
<div class="loader"></div>
</div>
<div id="main-content">
<div class="tm-container">
<div class="tm-letter" id="t-letter">T</div>
<div class="tm-letter" id="m-letter">M</div>
</div>
<audio id="flipSound" preload="auto">
<source src="https://cdn.freesound.org/previews/321/321114_2776777-lq.ogg" type="audio/wav">
</audio>
<main>
<div id="gameCardLink">
<span>G</span>
<span>a</span>
<span>m</span>
<span>e</span>
<span> </span> <!-- Boşluk eklemek için span ekledik -->
<span> </span>
<span>C</span>
<span> </span>
<span>a</span>
<span> </span>
<span>r</span>
<span> </span>
<span>d</span>
<span> </span>
<span>s</span>
<span>®</span>
</div>
<p><a href="https://github.com/murattasci06"><i class="fab fa-github"></i></a></p>
</main>
<ul>
<li class="card" >
<div class="card__flipper">
<div class="card__front">
<img src="https://gecbunlari.com/wp-content/uploads/2021/12/Spiderman-No-Way-Home.jpg" alt="Spiderman">
<p class="card__name"><span>Marvel</span><br>Spiderman</p>
<p class="card__num">1</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/JfVOs4VSpmA?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#514d9b" stroke-width="35" />
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>1.89 Bil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src="https://i.pinimg.com/736x/1e/f1/3d/1ef13dfa4b7b8c131302e242d1ec48d7.jpg" alt="Batman">
<p class="card__name"><span>DC</span><br>Batman</p>
<p class="card__num">2</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/mqqft2x_Aa4?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#35a541" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>771 Mil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src="https://wallpapercave.com/wp/wp12279011.jpg" alt="Guardians_of_the_Galaxy_Vol_3">
<p class="card__name"><span>Marvel</span><br>Guardians_of_the_Galaxy_Vol_3</p>
<p class="card__num">3</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/u3V5KDHRQvk?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#bdb235" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>845.4 Mil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src="https://wallpaperaccess.com/full/8940499.jpg" alt="Shazam">
<p class="card__name"><span>DC</span><br>Shazam2</p>
<p class="card__num">4</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/AIc671o9yCI?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#db6623" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>462.5 Mil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src="https://images2.alphacoders.com/131/1316679.jpeg" alt="Flash">
<p class="card__name"><span>DC</span><br>Flash</p>
<p class="card__num">5</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/hebWYacbdvc?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#3e5eb3" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>560.2 Mil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src=" https://images3.alphacoders.com/121/1213553.jpg" alt="Dr_Strange_2">
<p class="card__name"><span>Marvel</span><br>Dr_Strange_2</p>
<p class="card__num">6</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/aWzlQ2N6qqg?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#aa9e5c" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>955.8 Mil. $</span>
</div>
</div>
</li>
</ul>
</div>
</body>
<script>
var Flipper = (function() {
var card = $('.card');
var flipper = card.find('.card__flipper');
var win = $(window);
var flip = function() {
var thisCard = $(this);
var thisFlipper = thisCard.find('.card__flipper');
var offset = thisCard.offset();
var xc = win.width() / 2;
var yc = win.height() / 2;
var docScroll = $(document).scrollTop();
var cardW = thisCard.outerWidth() / 2;
var cardH = thisCard.height() / 2;
var transX = xc - offset.left - cardW;
var transY = docScroll + yc - offset.top - cardH;
// if (offset.top > card.height()) transY = docScroll - offset.top + cardH;
if (win.width() <= 700) transY = 0;
if (card.hasClass('active')) unflip();
thisCard.css({'z-index': '3'}).addClass('active');
thisFlipper.css({
'transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)',
'-webkit-transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)',
'-ms-transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)'
}).addClass('active');
return false;
};
var unflip = function(e) {
card.css({'z-index': '1'}).removeClass('active');
flipper.css({
'transform': 'none',
'-webkit-transform': 'none',
'-ms-transform': 'none'
}).removeClass('active');
};
var bindActions = function() {
card.on('click', flip);
win.on('click', unflip);
}
var init = function() {
bindActions();
};
return {
init: init
};
}());
Flipper.init();
</script>
<script>
<!-- HOOVER FOR TRAILER -->
let hoverTimeout;
$('.card').hover(function() {
const currentCard = $(this); // Store the current card element in a variable
hoverTimeout = setTimeout(() => {
currentCard.find('.card__front').hide();
currentCard.find('.iframe').show();
var src = currentCard.find('.iframe').attr("src");
currentCard.find('.iframe').attr("src", src);
// Add fullscreen functionality
currentCard.find('.iframe').on('click', function() {
$(this).requestFullscreen();
});
}, 5000); // 5000 milliseconds (5 seconds)
}, function() {
clearTimeout(hoverTimeout); // Clear the timeout to prevent actions if the user moves away before 5 seconds
$(this).find('.card__front').show();
$(this).find('.iframe').hide();
var src = $(this).find('.iframe').attr("src");
if (src) {
$(this).find('.iframe').attr("src", src.replace('?autoplay=1', ''));
}
});
</script>
<script>
var cardFlags = {};
$(document).ready(function() {
var flipSound = document.getElementById("flipSound");
// Sesin yalnızca kartın ön yüzüne tıklandığında çalmasını sağlayın.
$(".card__front").click(function() {
console.log('Kart önüne tıklandı', event.target);
flipSound.currentTime = 0;
flipSound.play();
console.log('dönüş sesi çalındı', event.target);
});
$(".card").click(function() {
var card = $(this);
var cardId = card.find(".card__num").text();
console.log(cardId);
// Check if the card is not already flipping to avoid multiple flips
if (!card.hasClass('flipping')) {
card.addClass('flipping');
// Check if the front side is facing the viewer
if (!card.hasClass("flipped")) {
console.log("is card flag true or false", cardId);
if (!cardFlags[cardId]) {
startAnimation(div);
console.log("started");
cardFlags[cardId] = true;
card.addClass("flipped");
}
// Adding canvas to back-side
var div = document.querySelector('.flipped .card__flipper.active .card__back');
var canvas = document.getElementsByClassName('p5Canvas')[0];
if (div && canvas) {
div.appendChild(canvas);
canvas.style.position = 'absolute';
}
} else {
console.log("stopped");
card.removeClass("flipped");
}
setTimeout(function() {
card.removeClass('flipping');
}, 1000);
}
});
// Prevent sound on back side click
$(".card__back").click(function(e) {
e.stopPropagation();
});
});
</script>
<script>
// Body's hoover effect
document.getElementById("gameCardLink").addEventListener("mouseover", function() {
document.body.classList.add("hoverEffect");
});
document.getElementById("gameCardLink").addEventListener("mouseout", function() {
document.body.classList.remove("hoverEffect");
});
</script>
<script>
// Portal effect
var p5Instance;
function startAnimation(div) {
// adding canvas to back-side
var canvas = document.getElementsByClassName('p5Canvas')[0];
if (div && canvas) {
div.appendChild(canvas);
canvas.style.position = 'absolute';
}
const sketch = (p) => {
const createParticleSystem = (location) => {
const origin = location.copy();
const particles = [];
const addParticle = velocity => {
const rand = p.random(0, 1);
if (rand <= .3) {
particles.push(createSparkParticle(origin, velocity.copy()));
} else {
particles.push(createParticle(origin, velocity.copy()));
}
};
const applyForce = force => {
particles.forEach(particle => {
particle.applyForce(force);
});
};
const run = () => {
particles.forEach((particle, index) => {
particle.move();
particle.draw();
if (particle.isDead()) {
particles.splice(index, 1);
}
});
};
return {
origin,
addParticle,
run,
applyForce
};
};
const createSparkParticle = (locationP, velocity) => {
const particle = createParticle(locationP, velocity);
let fade = 255;
const draw = () => {
p.colorMode(p.HSB);
p.stroke(16, 62, 100, fade);
const arrow = velocity.copy().normalize().mult(p.random(2, 4));
const direction = p5.Vector.add(particle.location, arrow);
p.line(particle.location.x, particle.location.y, direction.x, direction.y);
};
const move = () => {
particle.applyForce(p.createVector(p.random(-.2, .2), p.random(-0.1, -0.4)));
particle.velocity.add(particle.acc);
particle.location.add(particle.velocity.copy().normalize().mult(p.random(2, 4)));
particle.acc.mult(0);
fade -= 5;
};
return {
...particle,
draw,
move
}
}
const createParticle = (locationP, velocity) => {
const acc = p.createVector(0, 0);
const location = locationP.copy();
let fade = 255;
const fadeMinus = p.randomGaussian(15, 2);
let ligther = 100;
let situate = 62;
const draw = () => {
p.colorMode(p.HSB)
p.stroke(16, p.constrain(situate, 62, 92), p.constrain(ligther, 60, 100), fade);
const arrow = velocity.copy().mult(2);
const direction = p5.Vector.add(location, arrow);
p.line(location.x, location.y, direction.x, direction.y);
};
const move = () => {
velocity.add(acc);
location.add(velocity.copy().div(p.map(velocity.mag(), 18, 0, 5, 1)));
acc.mult(0);
fade -= fadeMinus;
ligther -= 8;
situate += 8;
};
const applyForce = force => {
acc.add(force);
};
const isDead = () => {
if (fade < 0 || location.x < 0 || location.x > p.width || location.y > p.height) {
return true;
} else {
return false;
}
};
return {
draw,
move,
applyForce,
isDead,
velocity,
location,
acc
};
};
const createMover = () => {
const location = p.createVector(p.width / 2, p.height / 2);
const velocity = p.createVector(0, 0);
const acc = p.createVector(0, 0);
const mass = 10;
let angle = 0;
let angleVelocity = 0;
let angleAcc = 0;
let len = 100;
const particleSystems = [
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location)
];
const getGotoVector = angle => {
const radius = p.map(angleVelocity, 0, 0.3, 0, 80);
const goToVector = p.createVector(
location.x + radius * p.cos(angle),
location.y + radius * p.sin(angle)
);
return goToVector;
};
const draw = () => {
const goToVector = getGotoVector(angle);
particleSystems.forEach(particleSystem => {
particleSystem.run();
});
};
const renderParticleSystem = () => {
particleSystems.forEach(particleSystem => {
const goToVector = getGotoVector(angle - p.random(0, p.TWO_PI));
const prepencular = p.createVector(
(goToVector.y - location.y)*-1,
(goToVector.x - location.x)
);
prepencular.normalize();
prepencular.mult(angleVelocity * 70);
particleSystem.origin.set(goToVector);
particleSystem.addParticle(prepencular);
const gravity = p.createVector(0, 0.3);
particleSystem.applyForce(gravity);
});
};
const move = () => {
angleAcc = 0.005;
angleVelocity = p.constrain(angleVelocity + angleAcc, 0, 0.32);
angle += angleVelocity;
angleAcc = 0;
renderParticleSystem();
};
return {
draw,
move
};
};
let mover;
p.setup = function() {
p.createCanvas(230, 320);
p.clear();
mover = createMover();
}
p.draw = function() {
p.clear();
mover.move();
mover.draw();
}
};
p5Instance = new p5(sketch);
}
</script>
<script>
// hiding and showing loading animation
function hideLoadingAnimation() {
console.log("Yükleme animasyonu gizleniyor, ana içerik gösteriliyor");
var loadingAnimation = document.getElementById("loading-animation");
var mainContent = document.getElementById("main-content");
loadingAnimation.style.display = "none";
mainContent.style.display = "block";
}
window.onload = function() {
console.log("Sayfa tamamen yüklendi");
hideLoadingAnimation();
};
</script>
</html>
```
In the picture on the issue, there is a purple card turned upside down in the middle. There are 2 cards above and below that overlap with this card. While the cards overlap each other front and back, how can I easily ensure that the bottom side of the cards, whose front side is half visible, does not play trailers with hoover (**mouse events will not work in this case**)? with css? I am trying to solve this problem with very simple approaches.
card-partially-visible {
pointer-events: none;
}
Does something like this make sense? If so, how should you determine if it is partially visible?
Could there be a ready-made function that will detect it automatically?
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/6kFhI.png |
```
Flutter (Channel beta, 3.21.0-1.0.pre.2, on Microsoft Windows [Version 10.0.19045.4170], locale en-US)
• Flutter version 3.21.0-1.0.pre.2 on channel beta at C:\Users\wzalz\flutter_windows_3.19.3-stable\flutter
! Warning: `dart` on your path resolves to C:\Program Files\Dart\dart-sdk\bin\dart.exe, which is not inside your
current Flutter SDK checkout at C:\Users\wzalz\flutter_windows_3.19.3-stable\flutter. Consider adding
C:\Users\wzalz\flutter_windows_3.19.3-stable\flutter\bin to the front of your path.
```
What do I do
I tried again and again |
I want to use this scene in my HTML, but I need to change some of the scene settings - like background, disable zoom etc.
How do I duplicate published scene to my draft?
https://my.spline.design/interactivespherescopy-d9d1c8bb2f660546855bd1b02c7063f8/
I tried to apply this scene as it is but I can't change background or zoom settings via JavaScript |
In query resolver can i extract the raw query or list of fields/sub-objects which are getting returned in response? I need to apply some logic based on the attributes being returned in response. |
In graphql java kickstart how to extract raw query being fired |
|java|graphql|graphql-java|graphql-java-tools| |
I setup the Rails project on VScode but it does not produce the expected outcome. It just profile 6 single files and does not have any folders.
I followed all the step in: https://guides.rubyonrails.org/getting_started.html and also install extension for Ruby and Rails on VScode but cannot set the expected Rails setup |
Rails project setup problems on VScode |
|ruby-on-rails|ruby| |
null |
In my case I am having html content inside foreignObject tag, and my html text was not scaling in all the browsers of iPhone.
I fixed this text scaling issue by prefixing all the html tags by xlink as shown in the sample code below.
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 900 900"
width="900" height="900">
<image xlink:href="img/chart.png" height="100%" width="100%" />
<foreignObject x="18%" y="1%" width="15%" height="20%">
<xlink:body xmlns="http://www.w3.org/1999/xhtml">
<xlink:table width="100%" height="100%">
<xlink:tr>
<xlink:td id="PlanetH3" align="center" valign="middle">
<text>Your text which is to be scaled.</text>
</xlink:td>
</xlink:tr>
</xlink:table>
</xlink:body>
</foreignObject>
</svg>
Please note that second line is most important in above code sample, where you have to define xlink namespace and viewBox attribute on svg open tag.
Thanks. |
I am using Emulator. Each and every time when I run app for test, its shows "System not responding".
How can I resolve this error that requires clicking "Wait" around 100 times before being able to work on the emulator?
Clearing ram and cache. |
I have a handful of data objects floating around my code which have a large number of fields of the same type:
```
struct AsStruct{
mass: i32,
height: i32,
energy: i32,
age: i32,
radioactivity: i32,
}
```
(actual examples would have more fields - like 20+).
Sometimes but not always, I'm dealing with these fields in a collective way, and it would be better to have something like a `Map<String, i32>`
```
pub const ALL_STATS: [&str; 5] = ["mass", "height", "energy", "age", "radioactivity"];
struct AsMap{
data : HashMap<String, i32>,
}
```
This latter model lets me treat some things in a neat programmatic way. For instance, below are functions to generate random versions of each:
```
pub fn generate_map() -> AsMap {
let mut map = HashMap::new();
for s in ALL_STATS.iter() {
map.insert(s.to_string(), rand::random::<i32>() % 10);
}
AsMap{data: map}
}
pub fn generate_struct() -> AsStruct {
AsStruct{
mass: rand::random::<i32>() % 10,
height: rand::random::<i32>() % 10,
energy: rand::random::<i32>() % 10,
age: rand::random::<i32>() % 10,
radioactivity: rand::random::<i32>() % 10,
}
}
```
Obviously, the "Map" version will scale much more easily, and require less refactoring as stats change. On the other hand, there's also times when it's preferable to have the stricter `AsStruct` definition, which can be accessed by more concise syntax and doesn't need extra code to handle missing keys, etc.
I can write translations between the two, or put some set of getters and setters on the `AsStruct` one to allow fields to be treated as keys. This would involve a great deal of boiler plate, however, and feels like a worthy use case for something like a `derive` macro. I can also imagine a lot of additional nice-to-have features that could be added to such a solution, such as typed keys, support for structs with fields of different types, etc.
So my question is : Has this already been solved? Is there a crate with such a derive macro floating out there that I don't know about? Is there a standard pattern for having my cake and eating it too in such situations?
|
react-native-camera-roll_camera-roll:copyReleaseJniLibsProjectAndLocalJars FAILED |
|reactjs|react-native|camera-roll| |
null |
How can I reshape a 3D NumPy array into a 2D array, while utilizing the data along axis 2 to upscale?
e.g. 3D array with shape [2,2,4]:
```
array_3d = [[[ 1 2 3 4]
[ 5 6 7 8]]
[[ 9 10 11 12]
[13 14 15 16]]]
```
reshape to 2D array with shape [4, 4]:
```
reshaped_array = [[ 1 2 5 6]
[ 3 4 7 8]
[ 9 10 13 14]
[11 12 15 16]]
```
I've attempted this approach:
```
reshaped_array = array_3d.swapaxes(1, 2).reshape(-1, array_3d.shape[1])
```
But I got:
```
[[ 1 5]
[ 2 6]
[ 3 7]
[ 4 8]
[ 9 13]
[10 14]
[11 15]
[12 16]]
``` |
I'm working on an NX project where I've organized different repositories for components, alongside incorporating a third-party Tailwind component library. Currently, I'm facing issues with duplicate classNames being generated in the CSS bundle. Despite following the instructions outlined here, the problem persists. Can someone advise on how to configure the third-party Tailwind component library in NX to prevent the generation of duplicate classNames?
[1]: https://tailwindcss.com/docs/content-configuration#working-with-third-party-libraries |
NX is not able to purge tailwind third-party library's classNames |
|tailwind-css|monorepo|nrwl-nx|nx-monorepo| |
I have installed Firebase version 8.6.5 using `npm install firebase`. But I wish to downgrade Firebase to version 7.16.1 due to some code compatibility.
|
How can I downgrade Firebase version? |
i think, the codesample in c given below should output: 10,15,10. But it gives output: 15,15,15. my question is how this result comes?
#include <stdio.h>
int main() {
int a=10;
printf("%d %d %d",a,a=a+5,a);
return 0;
} |
how printf() function behaves in printf("%d %d %d",a,a=a+5,a);? |
|c|printf| |
```
id column1
1 ['A']
2 ['A', 'B', 'C']
3 [null]
```
I'd like to select row 3, but trying
```SELECT * FROM table WHERE CONTAINS(column1, null)```
returns empty result. I'm lost as to why that's not selecting row 3. Help? |
How to select array with null values in sql? |
|sql| |
I've found the problem, I think! In validationSchemaCalcolo I set:
'**':{
trim:true,
escape:true
},
... and so each float becomes a string. |
I met the same issue:
It was because of gradle version, ```compile``` command is expired and was replaced by ```api/implementation```, and In gradle 7.0+, it was removed.
I still want to use ```compile```, so I downgrade gradle version to gradle 4.10.
In file ```gradle-wrapper.properties```, use ```distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-all.zip``` |
Text selection replacement in ZSH |
|zsh|windows-subsystem-for-linux| |
null |
**Description:**
I recently completed my first JavaScript project, a Pomodoro clock, without relying on tutorials. I'd like feedback on my code to improve my skills further. Here's a detailed overview of how I implemented it:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pomodoro Clock</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="app-title">
<div class="double-line"></div>
<p>Pomodoro Clock</p>
<div class="double-line"></div>
</div>
<div class="adjustment-div">
<div class="break-length-div">
<p class="heading">Break Length</p>
<div class="value-adjustment">
<button class="minus">-</button>
<div class="minutes"></div>
<button class="plus">+</button>
</div>
</div>
<div class="session-length-div">
<p class="heading">Session Length</p>
<div class="value-adjustment">
<button class="minus">-</button>
<div class="minutes"></div>
<button class="plus">+</button>
</div>
</div>
</div>
<div class="session">
<div class="heading">
Start
</div>
<div class="time">
00:00
</div>
</div>
<div class="controls">
<div class="reset-button">
<button>Reset</button>
</div>
<div class="start-button">
<button>Start</button>
</div>
</div>
<div class="remarks">
Designed based on a pen by <u>Edd Yerburgh</u> and code by <u>Crying Wolfe</u>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
```
The CSS of the clock
```
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-color: #0e9aa7;
font-family: sans-serif;
height: 100%;
margin: 0;
padding-top: 40px;
display: flex;
justify-content: center;
}
.container {
width: 100vh;
height: 90vh;
display: flex;
flex-direction: column;
align-items: center;
}
.app-title {
display: flex;
align-items: center;
}
.double-line {
height: 5px;
width: 200px;
border-top: 2px solid white;
border-bottom: 2px solid white;
}
.app-title p {
color: white;
font-size: 26px;
font-weight: bold;
padding: 0 15px 0 15px;
}
.adjustment-div {
display: flex;
justify-content: space-between;
width: 80%;
}
.break-length-div,
.session-length-div {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 40px;
width: 130px;
}
.break-length-div .heading,
.session-length-div .heading {
color: white;
font-size: 15px;
font-weight: 600;
}
.value-adjustment {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 8px;
width: 90%;
}
.minus,
.plus {
background: transparent;
height: 30px;
width: 30px;
color: #3db9c5;
border: 1px #3db9c5 solid;
border-radius: 3px;
cursor: pointer;
}
.minus:hover,
.plus:hover {
color: #2dd6e6;
border-color: #2dd6e6;
}
.value-adjustment .minutes {
background-color: white;
height: 38px;
width: 38px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.session {
margin-top: 30px;
height: 280px;
width: 280px;
border-radius: 50%;
border: 5px solid #3db9c5;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: white;
position: relative;
}
.session .heading {
font-size: 26px;
font-weight: bold;
position: absolute;
top: 60px;
}
.session .time {
font-size: 76px;
font-weight: bolder;
margin-top: 40px;
}
.controls {
display: flex;
justify-content: space-between;
padding: 0 10px;
margin-top: 30px;
width: 200px;
}
.start-button button,
.reset-button button {
width: 80px;
height: 30px;
background: transparent;
color: white;
border: 2px solid #3db9c5;
border-radius: 5px;
font-size: 18px;
cursor: pointer;
}
.start-button button:hover,
.reset-button button:hover {
border-color: #2dd6e6;
}
.remarks {
margin-top: 40px;
color: #80e4eb;
}
```
This is my JavaScript
```
console.log("Happy Coding, with Pomodoro Timer!");
const break_time_adjustments = () => {
// Getting all elements to set the length of Break
const increase_break_time_button = document.querySelector(
".break-length-div .value-adjustment .plus"
),
decrease_break_time_button = document.querySelector(
".break-length-div .value-adjustment .minus"
),
break_time_value = document.querySelector(
".break-length-div .value-adjustment .minutes"
);
// Performing Operations on the elements
let break_time = 5;
break_time_value.innerHTML = break_time;
// Getter function to retrieve the current brake time
const get_break_time = () => break_time;
// Setter funtion to set the update the break time and display it
const set_break_time = (new_time) => {
break_time = new_time;
break_time_value.innerHTML = break_time;
};
// Increasing the length of Break
function increase_break_time() {
set_break_time(break_time + 5); // Increasing the break time by 5
}
increase_break_time_button.addEventListener("click", increase_break_time);
// Decreasing the length of Break
function decrease_break_time() {
if (break_time <= 0) {
break_time = 0;
} else {
set_break_time(break_time - 5); // Decreasing the break time by 5
}
}
decrease_break_time_button.addEventListener("click", decrease_break_time);
return { get_break_time, set_break_time };
};
const { get_break_time, set_break_time } = break_time_adjustments();
break_time_adjustments();
const session_time_adjustments = () => {
// Getting all elements to set the length of a session
const increase_session_time_button = document.querySelector(
".session-length-div .value-adjustment .plus"
),
decrease_session_time_button = document.querySelector(
".session-length-div .value-adjustment .minus"
),
session_time_value = document.querySelector(
".session-length-div .value-adjustment .minutes"
);
// Performing Operations on the elements
let session_time = 25;
session_time_value.innerHTML = session_time;
// Getter function to retrieve the current session time
const get_session_time = () => session_time;
// Setter function to update the session time and display it
const set_session_time = (newTime) => {
session_time = newTime;
session_time_value.innerHTML = session_time;
};
// Increasing the length of Session
function increase_session_time() {
set_session_time(session_time + 5); // Increasing length of Session time by 5
}
increase_session_time_button.addEventListener("click", increase_session_time);
// Decreasing the length of Session
function decrease_session_time() {
if (session_time <= 0) {
session_time = 0;
} else {
set_session_time(session_time - 5); // Decreasing length of Session time by 5
}
}
decrease_session_time_button.addEventListener("click", decrease_session_time);
// Return getter and setter functions
return { get_session_time, set_session_time };
};
const { get_session_time, set_session_time } = session_time_adjustments();
// Initializing a variable to store session interval id
let session_interval_id;
const update_time = (session_duration) => {
// Getting elements to update the Time
const Time = document.querySelector(".time");
const heading = document.querySelector(".session .heading");
heading.innerHTML = "Session";
let minutes = session_duration;
let seconds = 0;
// Updating Time
const timer = setInterval(() => {
if (minutes === 0 && seconds === 0) {
clearInterval(timer); // Stop the timer when it reaches 0
break_time(get_break_time()); // Start the break
// break_time(1); // For testing
return;
}
if (seconds === 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
Time.innerHTML = `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
}, 1000);
session_interval_id = timer;
return timer;
};
// Initializing a varibale to store break time interval id
let break_interval_id;
const break_time = (break_duration_time) => {
//Getting elements to start break time
const Time = document.querySelector(".time");
const heading = document.querySelector(".session .heading");
heading.innerHTML = "Break";
// Starting Break time
let break_duration = break_duration_time;
let minutes = break_duration;
let seconds = 0;
const break_timer = setInterval(() => {
if (minutes === 0 && seconds === 0) {
clearInterval(break_timer); // Stop the timer when it reaches 0
update_time(get_session_time());
// update_time(1); // For Testing
return;
}
if (seconds === 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
Time.innerHTML = `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
}, 1000);
break_interval_id = break_timer;
return break_timer;
};
const start = () => {
// Getting elements to start the clock
const start_button = document.querySelector(".controls .start-button button");
// Flag to check if previous session is already running
let is_session_running = false;
// Starting the clock
function start_clock() {
if (is_session_running) {
clearInterval(session_interval_id); // Clearing previous session
clearInterval(break_interval_id); // Clearing previous break
}
update_time(get_session_time());
// update_time(1); // For Testing
is_session_running = true;
}
start_button.addEventListener("click", start_clock);
};
start();
const stop = () => {
// Getting Elements to stop the clock
const reset_button = document.querySelector(".controls .reset-button button");
const heading = document.querySelector(".session .heading");
const Timer = document.querySelector(".session .time");
// Adding funcionality to stop button
function reset_the_timer() {
clearInterval(session_interval_id);
clearInterval(break_interval_id);
heading.innerHTML = "Start";
Timer.innerHTML = "00:00";
}
reset_button.addEventListener("click", reset_the_timer);
};
stop();
```
**Key Features:**
**Modularization:** I modularized my code by breaking it down into functions for adjusting break and session times, updating the time display, starting the session, and stopping/resetting the clock. This approach promotes code reuse and maintainability.
**Event Handling:** Event listeners are used to handle user interactions, such as increasing/decreasing break and session times, starting the clock, and resetting it, making the application interactive and user-friendly.
**Error Handling:** I implemented basic error handling to ensure that session and break times do not become negative and are capped at a minimum of 0.
**Functionality:** The Pomodoro clock alternates between session and break periods based on user-defined times, providing a functional and intuitive experience.
**Request for Feedback:**
I would appreciate feedback on the overall structure and readability of my code, as well as suggestions for optimization and improvement. Additionally, any advice on best practices or alternative approaches would be valuable for my learning journey.
Thank you for your time and assistance! |
I have create my first project using JavaScript, It's a Pomodoro Clock, I am learning JavaScript, is it a good code or not |
|javascript| |
null |
It is most likely caused by your `hash_password` method, check its return type and make sure it returns a User instance. Also no need to use a custom made hashing method as the built in method `set_password` provides the same functionality.
Example of how it would look like using `set_password`:
user.set_password(request.data["password"])
user.save() |
We want to exclude specific property of an javascript object.
**Sample Input:**
> const foo={
> "bar":"sangram",
> "baz":"sagar",
> "mux":"sachin",
> "fch":"swapnil"
>
> }
we want to omit a 'bar' property of this object foo.
**Sample Output:**
> const foo={
> "baz":"sagar",
> "mux":"sachin",
> "fch":"swapnil"
> }
**Solution:**
> const foo={
> "bar":"sangram",
> "baz":"sagar",
> "mux":"sachin",
> "fch":"swapnil"
>
> }
> const { bar, ...qux } = foo
> console.log(qux)
**Output:**
> { baz: 'sagar', mux: 'sachin', fch: 'swapnil' } |
I am quite definitely not an expert either, but I have had the same issue. I resolved the issue by using a slightly older version of tf using:
!pip install -U "tensorflow-text==2.15.*"
and
!pip install -U "tf-models-official==2.15.*"
For reference, I am running scripts on Google Colab (I know this sometimes has it's own little ways..). |
[example:](https://i.stack.imgur.com/GvSoN.png)
I need calendar in flutter like above image. the monthly calendar starts from previous month 25th to current month 24th. for example: April month calendar: Mar25-Apr24th. develop this calendar using syncfusion flutter calendar or tablecalendar |
in flutter calendar, i need monthly calendar to be start from previous month 25th to current month 24th. example: mar month calendar: 25th feb - 24mar |
|ios|flutter|mobile|frontend| |
null |
IN MbedTls with RSA in a C-programm encryption/decryption works when using separate buffers (for plainText, cipherText, and decryptedText, i.e. the content of plainText and decryptedText is the same), but not when using just one buffer to perform in-place encryption/decryption as i get gibberish/not correctly encrypted data.
Is that just a general limitation or is my code wrong?
Background:
I'm trying to use in-place encryption and decryption with RSA in MbedTls in a C-programm. [Here](https://forums.mbed.com/t/in-place-encryption-decryption-with-aes/4531) it says that "In place cipher is allowed in Mbed TLS, unless specified otherwise.", although I'm not sure if they are also talking about AES. From my understanding i didn't see any specification saying otherwise (should work) for mbedtls_rsa_rsaes_oaep_decrypt in the Mbed TLS API documentation.
Code:
```
size_t sizeDecrypted;
unsigned char plainText[15000] = "yxcvbnm";
unsigned char cipherText[15000];
unsigned char decryptedText[15000];
rtn = mbedtls_rsa_rsaes_oaep_encrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, sizeof("yxcvbnm"), &plainText, &cipherText);
rtn = mbedtls_rsa_rsaes_oaep_decrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, &sizeDecrypted, &cipherText, &decryptedText, 15000);
//decryptedText afterwards contains the correctly decrypted text just like plainText
//sizeDecrypted is 8 (because of the binary zero at the end of the string)
unsigned char text[15000] = "yxcvbnm";
rtn = mbedtls_rsa_rsaes_oaep_encrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, sizeof("yxcvbnm"), &text, &text);
rtn = mbedtls_rsa_rsaes_oaep_decrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, &sizeDecrypted, &text, &text, 15000);
//someText afterwards doesn't contain the correctly decrypted text/has a different content than plainText
//rtn is always 0, i.e. no error is returned
//sizeDecrypted is 8
``` |
Easy translation between struct and map format? |
|rust| |
Creating this question since https://repost.aws/knowledge-center/sagemaker-lifecycle-script-timeout didnt work for me.
It was a version issue. So I want the on-stop and custom conda environment in my sage maker.
I tried to add sage maker conda environment and auto-stop sage maker after one hour but I saw errors in cloudwatch logs. |
custom environment in sage maker |
|amazon-sagemaker| |
null |
{"OriginalQuestionIds":[686439],"Voters":[{"Id":7328782,"DisplayName":"Cris Luengo","BindingReason":{"GoldTagBadge":"matlab"}}]} |
Check value of ${RR_LIB_FILES}.
Errors say that this line `target_link_libraries(myrrlib PUBLIC ${RR_LIB_FILES})` links against two libcrypto.a libraries. This is ofcourse illegal.
Print it out and check for duplicates.
I suspect that with switch from SHARED to STATIC for myrrlib also dependencies are built and/or imported (linked) as STATIC, which results (likely) with keeping libcrypto.a internally to sub-library. |
When I'm going to update the SEO as admin from the frontend it shows me the error
> Attempt to read property "id" on null
[![enter image description here][1]][1]
This is my controller code
public function updateSEO(Request $request)
{
// first, get the language info from db
$language = Language::where('code', $request->language)->first();
$langId = $language->id;
// then, get the seo info of that language from db
$seo = SEO::where('language_id', $langId)->first();
// else update the existing seo info of that language
$seo->update($request->all());
$request->session()->flash('success', __('Updated successfully!'));
return redirect()->back();
}
This is my view code
<div class="form-group">
<label>{{ __('Meta Description For Home Page') }}</label>
<textarea class="form-control" name="home_meta_description" rows="5"
placeholder="{{ __('Enter Meta Description') }}">{{ $data->home_meta_description }}</textarea>
</div>
[1]: https://i.stack.imgur.com/O8Wew.png |
i have string:
const text = 'A Jack# Jack#aNyWord Jack, Jack';
i want search word "Jack" only, but if Jack contain # character, its say true mean match.
i try like:
const text = 'A Jack# Jack#aNyWord Jack, Jack';
const regexpWords = /Jack(?=,|#)/g;
console.log(text.match(regexpWords));
result say: `Array ["Jack", "Jack", "Jack"]`
My expected output is: `Array ["Jack#", "Jack#aNyWord", "Jack"]`
except word "Jack,"
how can i do with this |
How to except coma in search word in RegExp javascript |
|javascript|regex| |
|azure|microsoft-graph-api|botframework|microsoft-teams| |
null |