qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,441,895
<p>I'm trying to use fixtures to hold data for different tests, specifically user credentials. This is an example of the code. I'm getting 'Cannot read properties of undefined (reading 'data')'. I tried to google search , I found <a href="https://stackoverflow.com/questions/70929268/cypress-fixtures-cannot-read-properties-of-undefined-reading-data">Cypress fixtures - Cannot read properties of undefined (reading &#39;data&#39;)</a></p> <p>I used closure variable technique as reccomended in that post , yet I got reference error of unable to reference data.Please help me.I know cypress.config can be used but I want to keep that for global configs</p> <p>Json(credentials.json):</p> <pre><code>{ &quot;username&quot;:&quot;*****&quot;, &quot;password&quot;:&quot;*****&quot; } </code></pre> <p>Code:</p> <pre><code>import { LoginPage } from &quot;./pageobject/login_page&quot; describe('Test Scenario', () =&gt; { before(function () { cy .fixture('credentials').then(function (data) { this.data = data }) }) it('Simple login', () =&gt; { cy.visit(Cypress.env('url')) var loginpage = new LoginPage() loginpage.EnterUsername(this.data.username) loginpage.clickonSubmit() loginpage.EnterPassword(this.data.password) loginpage.clickonSubmit() Cypress .on('uncaught:exception', (err, runnable) =&gt; { return false; }); cy. wait(10000) cy. get('span[id=&quot;user&quot;]').should('have.text', this.data.username , 'User Login Unsuccessfully') }); }); </code></pre>
[ { "answer_id": 74442205, "author": "Amit Kahlon", "author_id": 13508689, "author_profile": "https://Stackoverflow.com/users/13508689", "pm_score": 0, "selected": false, "text": "this" }, { "answer_id": 74442364, "author": "Blunt", "author_id": 20473079, "author_profile": "https://Stackoverflow.com/users/20473079", "pm_score": 2, "selected": false, "text": "function () {}" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74441895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13180353/" ]
74,441,902
<p>This is my query:</p> <pre class="lang-php prettyprint-override"><code>$data = Collections::select(DB:raw(&quot;REGEXP_REPLACE(tour_id,'(,2|2,|2)','') as `new_tour_id&quot;))-&gt;get(); </code></pre> <p>I want to convert this query to update all my records in the database. This is my database table shows: <img src="https://i.stack.imgur.com/LDzVw.png" alt="" /></p> <p>I want this result: <img src="https://i.stack.imgur.com/WFBNH.png" alt="enter image description here" /></p>
[ { "answer_id": 74442205, "author": "Amit Kahlon", "author_id": 13508689, "author_profile": "https://Stackoverflow.com/users/13508689", "pm_score": 0, "selected": false, "text": "this" }, { "answer_id": 74442364, "author": "Blunt", "author_id": 20473079, "author_profile": "https://Stackoverflow.com/users/20473079", "pm_score": 2, "selected": false, "text": "function () {}" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74441902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11759266/" ]
74,441,907
<p>This is my code -</p> <pre><code>type LoginState = { loading: 'idle' | 'pending' | 'succeeded' | 'failed'; role: string; error: string; }; const initialState: LoginState = { loading: 'idle', role: '', error: '', }; const userSlice = createSlice({ name: 'user', initialState, reducers: {}, extraReducers: builder =&gt; { builder .addCase(authUser.pending, (state: LoginState) =&gt; { state.loading = 'pending'; }) .addCase(authUser.rejected, (state, action) =&gt; { state.loading = 'failed'; console.log('action', action); }); }, }); </code></pre> <p>And I am getting this error on TS -</p> <p><a href="https://i.stack.imgur.com/C8g41.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C8g41.png" alt="enter image description here" /></a></p> <p>I am not really sure, how I can resolve this. I have already added interfaces but seems I am missing something.</p> <p>Can you guys help.</p>
[ { "answer_id": 74441948, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 1, "selected": false, "text": "state" }, { "answer_id": 74441956, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": ".eslintrc" }, { "answer_id": 74442982, "author": "Rashomon", "author_id": 6546440, "author_profile": "https://Stackoverflow.com/users/6546440", "pm_score": 0, "selected": false, "text": "WritableDraft<LoginState>" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74441907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19290397/" ]
74,441,915
<p>I have this field</p> <pre><code>graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False) </code></pre> <p>and <code>GraduationYear</code> class is.</p> <pre><code>class GraduationYear(BaseModel): label = m.CharField(max_length=255) year = m.CharField(max_length=255,unique=True) def __str__(self): return self.label </code></pre> <p>Now I want to set the <code>GraduationYear</code> object where year=2022 as the default value of <code>graduation_year</code></p> <p>So, I am guessing I should embed sql to here below.</p> <pre><code>graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False,default='select GraduationYear where year=2022') </code></pre> <p>Is it possible?</p>
[ { "answer_id": 74442002, "author": "İlyas Sarı", "author_id": 20060726, "author_profile": "https://Stackoverflow.com/users/20060726", "pm_score": 0, "selected": false, "text": "default=lambda: GraduationYear.objects.get_or_create(year=2022)[0]\n" }, { "answer_id": 74442577, "author": "ybl", "author_id": 1991117, "author_profile": "https://Stackoverflow.com/users/1991117", "pm_score": 2, "selected": true, "text": "save" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74441915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942868/" ]
74,442,026
<p>I have future function and I want show this in the listview.seprator, but the listview do not get the future value. how can i fix this? this is my code: my hive class:</p> <pre><code>@HiveType(typeId: 3) class TaskCat extends HiveObject{ @HiveField(0) String catName; @HiveField(1) int userId; @HiveField(2) User? user; TaskCat(this.catName,this.user,this.userId); } </code></pre> <p>This is my function:</p> <pre><code>Future&lt;List&gt; showCategoryInHome() async { SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); var taskCatBox = await Hive.openBox('taskCat'); var filtertaskCat = taskCatBox.values .where( (TaskCat) =&gt; TaskCat.userId == sharedPreferences.getInt('key')) .toList(); return filtertaskCat; } </code></pre> <p>and this is my listview code:</p> <pre><code>FutureBuilder( future: controller.showCategoryInHome(), builder: (context, snapshot) { Future&lt;List&gt; test = controller.showCategoryInHome(); return ListView.separated( scrollDirection: Axis.horizontal, shrinkWrap: true, itemCount: 11 , // here currently I set the fix value but I want the length of my list itemBuilder: (context, index) { return TextButton( onPressed: () { }, child: Text( test[index].[catName], // and here not working too bucouse the list is future style: normalTextForCategory, ), ); }, separatorBuilder: (BuildContext context, int index) { return const VerticalDivider( width: 15, color: Colors.transparent, ); }, ); }, ) </code></pre>
[ { "answer_id": 74442075, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "FutureBuilder<List>(\n future: controller.showCategoryInHome(),\n builder: (context, snapshot) {\n switch (snapshot.connectionState) {\n case ConnectionState.waiting:\n return Text('Loading....');\n default:\n if (snapshot.hasError) {\n return Text('Error: ${snapshot.error}');\n } else {\n List data = snapshot.data ?? [];\n\n return ListView.separated(\n scrollDirection: Axis.horizontal,\n shrinkWrap: true,\n itemCount:data.length,\n itemBuilder: (context, index) {\n return TextButton(\n onPressed: () {},\n child: Text(\n data[index]['catName'],\n style: normalTextForCategory,\n ),\n );\n },\n separatorBuilder: (BuildContext context, int index) {\n return const VerticalDivider(\n width: 15,\n color: Colors.transparent,\n );\n },\n );\n }\n }\n },\n ),\n" }, { "answer_id": 74442119, "author": "quoci", "author_id": 9936384, "author_profile": "https://Stackoverflow.com/users/9936384", "pm_score": 0, "selected": false, "text": "Future" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20492111/" ]
74,442,038
<p>I have an error when inject IRequestHandler</p> <p><em>System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler<code>2[TabpediaFin.Handler.UnitMeasures.UnitMeasureList+Query,System.Collections.Generic.IEnumerable</code>1[TabpediaFin.Dto.UnitMeasureDto]] Lifetime: Transient ImplementationType: TabpediaFin.Handler.UnitMeasures.UnitMeasureList+QueryHandler': Unable to resolve service for type 'System.Data.IDbConnection' while attempting to activate 'TabpediaFin.Handler.UnitMeasures.UnitMeasureList+QueryHandler'.)'</em></p> <p><em>DbManager.cs</em></p> <pre><code>using Npgsql; namespace TabpediaFin.Infrastructure.Data; public class DbManager { private readonly string _connectionString; public DbManager(IConfiguration config) { _connectionString = config.GetConnectionString(&quot;DefaultConnection&quot;) ?? string.Empty; } public string ConnectionString =&gt; _connectionString; public IDbConnection CreateConnection() { IDbConnection cn = new NpgsqlConnection(_connectionString); DefaultTypeMap.MatchNamesWithUnderscores = true; // SimpleCRUD.SetDialect(SimpleCRUD.Dialect.PostgreSQL); return cn; } } </code></pre> <p><em>Program.cs</em></p> <pre><code>using FluentValidation.AspNetCore; using Serilog; using Serilog.Sinks.SystemConsole.Themes; using System.Reflection; using TabpediaFin.Infrastructure.Data; using MediatR; using TabpediaFin.Infrastructure.Validation; using TabpediaFin.Infrastructure; using Microsoft.AspNetCore.Builder; using TabpediaFin.Infrastructure.OpenApi; using Microsoft.EntityFrameworkCore.Migrations.Internal; using TabpediaFin.Infrastructure.Migrator; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Npgsql; Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.FromLogContext() .WriteTo.Console( outputTemplate: &quot;[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}&quot;, theme: AnsiConsoleTheme.Code) .CreateBootstrapLogger(); var builder = WebApplication.CreateBuilder(args); builder.Host.UseSerilog(); builder.Services.AddMediatR(Assembly.GetExecutingAssembly()); builder.Services.AddTransient(typeof(IPipelineBehavior&lt;,&gt;), typeof(ValidationPipelineBehavior&lt;,&gt;)); builder.Services.AddDbMigrator(); builder.Services.AddDbContext&lt;FinContext&gt;(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.RegisterSwagger(&quot;Tabpedia Finance&quot;, &quot;v1&quot;); builder.Services.AddControllers(options =&gt; { options.Filters.Add&lt;ValidateModelFilter&gt;(); }) .ConfigureApiBehaviorOptions(options =&gt; { options.SuppressModelStateInvalidFilter = true; }) .AddNewtonsoftJson(options =&gt; { options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }); builder.Services.AddFluentValidationAutoValidation(); builder.Services.AddCors(); builder.Services.RegisterSettings(builder.Configuration); builder.Services.RegisterServices(); builder.Services.RegisterRepositories(); //builder.Services.AddScoped&lt;IDbConnection&gt;(db =&gt; new NpgsqlConnection(Configuration.GetConnectionString(&quot;AppConnectionString&quot;))); builder.Services.AddJwt(); var app = builder.Build(); app.UseMiddlewares(); // Configure the HTTP request pipeline. // if (app.Environment.IsDevelopment()) // { app.UseSwagger(); app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;Tabpedia Finance v1&quot;)); // } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors( builder =&gt; builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .WithExposedHeaders(&quot;Token-Expired&quot;)); app.UseAuthorization(); app.UseEndpoints(endpoints =&gt; { endpoints.MapControllers(); }); app.MapControllers(); using (var scope = app.Services.CreateScope()) { TabpediaFin.Infrastructure.Migrator.Startup.UpdateDatabase(scope.ServiceProvider); } app.Run(); </code></pre> <p><em>UnitMeasureList.cs</em></p> <pre><code>using Microsoft.EntityFrameworkCore; namespace TabpediaFin.Handler.UnitMeasures { public class UnitMeasureList { public class Query : IRequest&lt;IEnumerable&lt;UnitMeasureDto&gt;&gt; { } public class QueryHandler : IRequestHandler&lt;Query, IEnumerable&lt;UnitMeasureDto&gt;&gt; { private readonly IDbConnection _dbConnection; private readonly ICurrentUser _currentUser; public QueryHandler( IDbConnection connection, ICurrentUser currentUser) { _dbConnection = connection; _currentUser = currentUser; } public async Task&lt;IEnumerable&lt;UnitMeasureDto&gt;&gt; Handle(Query req, CancellationToken cancellationToken) { string sql = $@&quot;SELECT um.*, at.Id, au.Id FROM UnitMeasure um INNER JOIN AppTenant at ON at.Id = um.Id INNER JOIN AppUser au ON au.Id = um.Id &quot;; var unitMeasure = await _dbConnection.QueryAsync&lt;UnitMeasureDto&gt;(sql, new { userName = _currentUser.Username }); return unitMeasure.ToList(); } } } } </code></pre> <p><em>UnitMeasureDto.cs</em></p> <pre><code>namespace TabpediaFin.Dto { public class UnitMeasureDto { protected UnitMeasureDto( int id ,int tenantId ,string name ,string description ,int createdUid ,DateTime createdUtc ,int updatedUid ,DateTime updatedUtc ) { Id = id; TenantId = tenantId; Name = name; Description = description; CreatedUid = createdUid; CreatedUtc = createdUtc; UpdatedUid = updatedUid; UpdatedUtc = updatedUtc; } public int Id { get; set; } public int TenantId { get; set; } public string Name { get; set; } public string Description { get; set; } public int CreatedUid { get; set; } public DateTime CreatedUtc { get; set; } public int UpdatedUid { get; set; } public DateTime UpdatedUtc { get; set; } } } </code></pre> <p><em>UnitMeasuresController.cs</em></p> <pre><code>namespace TabpediaFin.Handler.UnitMeasures { [Route(&quot;api/[controller]&quot;)] [ApiController] public class UnitMeasuresController : ControllerBase { private readonly IMediator _mediator; public UnitMeasuresController( IMediator mediator) { _mediator = mediator; } [HttpGet] public async Task&lt;IEnumerable&lt;UnitMeasureDto&gt;&gt; Get() =&gt; await _mediator.Send(new UnitMeasureList.Query()); } } </code></pre>
[ { "answer_id": 74442075, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "FutureBuilder<List>(\n future: controller.showCategoryInHome(),\n builder: (context, snapshot) {\n switch (snapshot.connectionState) {\n case ConnectionState.waiting:\n return Text('Loading....');\n default:\n if (snapshot.hasError) {\n return Text('Error: ${snapshot.error}');\n } else {\n List data = snapshot.data ?? [];\n\n return ListView.separated(\n scrollDirection: Axis.horizontal,\n shrinkWrap: true,\n itemCount:data.length,\n itemBuilder: (context, index) {\n return TextButton(\n onPressed: () {},\n child: Text(\n data[index]['catName'],\n style: normalTextForCategory,\n ),\n );\n },\n separatorBuilder: (BuildContext context, int index) {\n return const VerticalDivider(\n width: 15,\n color: Colors.transparent,\n );\n },\n );\n }\n }\n },\n ),\n" }, { "answer_id": 74442119, "author": "quoci", "author_id": 9936384, "author_profile": "https://Stackoverflow.com/users/9936384", "pm_score": 0, "selected": false, "text": "Future" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14028599/" ]
74,442,048
<p>I have following Code with ngModel, which is working. HTML:</p> <pre><code>&lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;search-name&quot;&gt; &lt;input class=&quot;form-control&quot; type=&quot;text&quot; name=&quot;search&quot; [(ngModel)]=&quot;searchText&quot; autocomplete=&quot;on&quot; placeholder=&quot; SEARCH &quot;&gt; &lt;/div&gt; &lt;ul *ngFor=&quot;let name of names | filter:searchText&quot;&gt; &lt;li&gt; &lt;span&gt;{{name.country}}&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>TypeScript:</p> <pre><code>import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'search-filter-angular'; searchText: any; names = [ { country: 'Adil'}, { country: 'John'}, { country: 'Jinku'}, { country: 'Steve'}, { country: 'Sam'}, { country: 'Zeed'}, { country: 'Abraham'}, { country: 'Heldon'} ]; } </code></pre> <p>How can I write this code with angular forms? I read there is also a two way data binding.</p> <p>Can please someone help?</p>
[ { "answer_id": 74442289, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 3, "selected": true, "text": "<div class=\"container\">\n <div class=\"search-name\">\n <input class=\"form-control\" type=\"text\" name=\"search\" [formControl]=\"searchText\" autocomplete=\"on\" placeholder=\" SEARCH \">\n </div>\n <ul *ngFor=\"let name of names | filter: (searchText.valueChanges | async)\">\n <li>\n <span>{{name.country}}</span>\n </li>\n </ul>\n</div>\n" }, { "answer_id": 74442335, "author": "MoxxiManagarm", "author_id": 11011793, "author_profile": "https://Stackoverflow.com/users/11011793", "pm_score": 1, "selected": false, "text": "<div class=\"container\">\n <div class=\"search-name\">\n <input\n class=\"form-control\"\n type=\"text\"\n name=\"search\"\n [formControl]=\"searchText\"\n autocomplete=\"on\"\n placeholder=\" SEARCH \"\n />\n </div>\n <ul *ngFor=\"let name of filteredNames$ | async\">\n <li>\n <span>{{ name.country }}</span>\n </li>\n </ul>\n</div>\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18203720/" ]
74,442,073
<p><img src="https://i.stack.imgur.com/TGhbI.png" alt="temp2 DataFrame" /></p> <p>When I use <code>s.iteritems()</code> in using <code>.iloc</code> I see the below warning:</p> <pre><code>FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead. for item in s.iteritems() </code></pre> <p>While I'm using this function:</p> <pre class="lang-py prettyprint-override"><code>temp3 = temp2.iloc[:, 0] </code></pre> <p>I am using python 3.8 and don't know why I'm getting this warning.</p> <p>I also tried the following:</p> <pre class="lang-py prettyprint-override"><code>temp3 = temp2.iloc[:, 0].copy() temp3 = temp2.loc[:, 0].copy() temp3 = temp2[0].copy() </code></pre> <p>But it's the same.</p>
[ { "answer_id": 74442190, "author": "Ilgım Akalay", "author_id": 12079456, "author_profile": "https://Stackoverflow.com/users/12079456", "pm_score": 1, "selected": false, "text": "temp3 = temp2[0].values\n" }, { "answer_id": 74605321, "author": "user20626534", "author_id": 20626534, "author_profile": "https://Stackoverflow.com/users/20626534", "pm_score": 0, "selected": false, "text": "def _series_to_str(s, max_items):\n res = []\n s = s[:max_items]\n for item in s.items():\n #for item in s.iteritems(): #bugged on panda 1.5 FutureWarning \n # item: (index, value)\n res.append(str(item))\n return ' '.join(res)\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12079456/" ]
74,442,082
<p>I have to take input from the user then the operator has to print what number is before the input and after the input like:</p> <p>input= 3<br /> has to print 2 and 4</p> <p>I used range, did I do it wrong? I am just a beginner in Python.</p> <pre><code>number=int(input) for num in range(number ,+ 1, -1): print(num) </code></pre>
[ { "answer_id": 74442115, "author": "Antoine Delia", "author_id": 4141606, "author_profile": "https://Stackoverflow.com/users/4141606", "pm_score": 2, "selected": true, "text": "input()" }, { "answer_id": 74442117, "author": "Amir Hossein Shahdaei", "author_id": 3017626, "author_profile": "https://Stackoverflow.com/users/3017626", "pm_score": 0, "selected": false, "text": "num = int(input())\n\nprint(num-1, num+1)\n" }, { "answer_id": 74442194, "author": "Fra93", "author_id": 4952549, "author_profile": "https://Stackoverflow.com/users/4952549", "pm_score": 0, "selected": false, "text": "R = 5 #range\nN = int(input(\"Enter your number. \"))\n\nnumbers = [ i for i in range(N-R,N+R+1) if i != N]\n\nprint(numbers)\n\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19535733/" ]
74,442,142
<p>I have these values in dataset in a pandas dataframe column</p> <pre><code>col1 [[1,2],[1,2]] [[3,4],[3,4]] [[5,6],[5,6]] </code></pre> <p>I want to get a new column of two elements as list in new columns as rows.</p> <p>This is the columns that I want to get.</p> <pre><code>col1 col2 [1,1] [2,2] [3,3] [4,4] [5,5] [6,6] </code></pre>
[ { "answer_id": 74442115, "author": "Antoine Delia", "author_id": 4141606, "author_profile": "https://Stackoverflow.com/users/4141606", "pm_score": 2, "selected": true, "text": "input()" }, { "answer_id": 74442117, "author": "Amir Hossein Shahdaei", "author_id": 3017626, "author_profile": "https://Stackoverflow.com/users/3017626", "pm_score": 0, "selected": false, "text": "num = int(input())\n\nprint(num-1, num+1)\n" }, { "answer_id": 74442194, "author": "Fra93", "author_id": 4952549, "author_profile": "https://Stackoverflow.com/users/4952549", "pm_score": 0, "selected": false, "text": "R = 5 #range\nN = int(input(\"Enter your number. \"))\n\nnumbers = [ i for i in range(N-R,N+R+1) if i != N]\n\nprint(numbers)\n\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5506647/" ]
74,442,164
<p>I understand NUnit runs tests in parallel, which isn't what this question is about exactly. In a single test, I can have two local socket connections open using TcpClient on different ports, which can communicate with one another in the same unit test. The problem is the address space is of course shared by the thread executing the unit test, so it doesn't simulate communication through a network how I want.</p> <p>If I have a test called Test1 with one TcpClient, and whilst it's running, I run Test2 with the other TcpClient, in these two tests I can have both the unit tests talking to one another and communicating - testing the protocol I've designed with separate address spaces, which does give me the simulation of a network I desire, and allows me to do the proper test assertions.</p> <p>Now the question is, is there any way to do this automatically? I'd like to have a single test that can run Test1 &amp; Test2, where both these tests communicate via their respective sockets, instead of starting them both up manually in parallel.</p>
[ { "answer_id": 74489108, "author": "PMF", "author_id": 2905768, "author_profile": "https://Stackoverflow.com/users/2905768", "pm_score": 3, "selected": true, "text": "dotnet test ServerUnitTests.dll\ndotnet test ClientUnitTests.dll\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5695300/" ]
74,442,178
<p>I do have this sample array of JSON, and I do not know how to loop through them and use it in creating a table row.</p> <p><strong>Sample code:</strong></p> <pre><code> var data = [ {foo1:&quot;a&quot;,foo2:&quot;b&quot;,foo3:&quot;c&quot;}, {foo1:&quot;d&quot;,foo2:&quot;e&quot;,foo3:&quot;f&quot;}, {foo1:&quot;g&quot;,foo2:&quot;h&quot;,foo3:&quot;i&quot;} ] </code></pre> <p><strong>I did use this method:</strong></p> <pre><code> $.each(data, function (key, value) { rows += &quot;&lt;tr id=&quot; + key + &quot;&gt;&lt;td&gt;&quot; + value.foo1+ &quot;&lt;/td&gt;&lt;td&gt;&quot; + value.foo2+ &quot;&lt;/td&gt;&lt;td&gt;&quot; + value.foo3+ &quot;&lt;/td&gt;&lt;td&gt;&quot;&lt;/tr&gt;&quot;; }); </code></pre> <p>//But I want to make it more flexible, so that I can reuse it in making another rows from another array of JSON, like this scenario:</p> <pre><code>var dataNew = [ {lorem1:&quot;j&quot;,lorem2:&quot;k&quot;,lorem3:&quot;l&quot;}, {lorem1:&quot;m&quot;,lorem2:&quot;n&quot;,lorem3:&quot;o&quot;}, {lorem1:&quot;p&quot;,lorem2:&quot;q&quot;,lorem3:&quot;r&quot;}, {lorem1:&quot;x&quot;,lorem2:&quot;s&quot;,lorem3:&quot;t&quot;}, {lorem1:&quot;w&quot;,lorem2:&quot;y&quot;,lorem3:&quot;z&quot;} ] </code></pre> <p>//Now I cannot use the method above</p>
[ { "answer_id": 74442242, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 1, "selected": false, "text": "var data = [\n {foo1:\"a\",foo2:\"b\",foo3:\"c\"},\n {foo1:\"d\",foo2:\"e\",foo3:\"f\"},\n {foo1:\"g\",foo2:\"h\",foo3:\"i\"}\n]\n\nvar dataNew = [\n {lorem1:\"j\",lorem2:\"k\",lorem3:\"l\"},\n {lorem1:\"m\",lorem2:\"n\",lorem3:\"o\"},\n {lorem1:\"p\",lorem2:\"q\",lorem3:\"r\"},\n {lorem1:\"x\",lorem2:\"s\",lorem3:\"t\"},\n {lorem1:\"w\",lorem2:\"y\",lorem3:\"z\"}\n]\n\nconst parseData = (data,table) => {\n let rows = \"\";\n data.forEach(d1 =>{\n rows += \"<tr>\"\n Object.entries(d1).forEach(d2 => {\n rows += \"<td id='\" + d2[0] + \"'>\" + d2[1] + \"</td>\" \n })\n rows +=\"</tr>\"\n })\n\n table.innerHTML = rows\n}\n\nparseData(data,document.querySelector(\"#table1\"))\nparseData(dataNew,document.querySelector(\"#table2\"))" }, { "answer_id": 74442728, "author": "Vadim", "author_id": 1580941, "author_profile": "https://Stackoverflow.com/users/1580941", "pm_score": 1, "selected": true, "text": ".textContent" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18492863/" ]
74,442,188
<p>I'm working on a springboot application which has security.xml used by AuthFilter[Org level authentication filter]. This xml looks in passwords.properties for username, password, etc. Sharing sample ex below.</p> <p>security.xml -</p> <pre><code>&lt;api-username&gt;${api.username}&lt;/api-username&gt; </code></pre> <p>passwords.properties -</p> <pre><code>api.username=abc </code></pre> <p>This works fine if the values are hardcoded in passwords.properties. But if I have to pass the values from env vars, property substitution isn't happening.</p> <p>passwords.properties :</p> <pre><code>api.username=$${api.username} </code></pre> <p>env vars :</p> <pre><code>api.username=abc </code></pre> <p>I'm stuck here. Could someone let me know a way to achieve this.</p> <p>I added below in my application.properties to make spring understand that the passwords.properties is a config file.</p> <pre><code>spring.config.import=classpath:passwords.properties </code></pre> <p>making this change too didn't help</p> <p>=================</p> <p>Update</p> <p>Looks like this XML is read during servlet initialization. Will property substitution work in this case?</p> <p>=================</p>
[ { "answer_id": 74442242, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 1, "selected": false, "text": "var data = [\n {foo1:\"a\",foo2:\"b\",foo3:\"c\"},\n {foo1:\"d\",foo2:\"e\",foo3:\"f\"},\n {foo1:\"g\",foo2:\"h\",foo3:\"i\"}\n]\n\nvar dataNew = [\n {lorem1:\"j\",lorem2:\"k\",lorem3:\"l\"},\n {lorem1:\"m\",lorem2:\"n\",lorem3:\"o\"},\n {lorem1:\"p\",lorem2:\"q\",lorem3:\"r\"},\n {lorem1:\"x\",lorem2:\"s\",lorem3:\"t\"},\n {lorem1:\"w\",lorem2:\"y\",lorem3:\"z\"}\n]\n\nconst parseData = (data,table) => {\n let rows = \"\";\n data.forEach(d1 =>{\n rows += \"<tr>\"\n Object.entries(d1).forEach(d2 => {\n rows += \"<td id='\" + d2[0] + \"'>\" + d2[1] + \"</td>\" \n })\n rows +=\"</tr>\"\n })\n\n table.innerHTML = rows\n}\n\nparseData(data,document.querySelector(\"#table1\"))\nparseData(dataNew,document.querySelector(\"#table2\"))" }, { "answer_id": 74442728, "author": "Vadim", "author_id": 1580941, "author_profile": "https://Stackoverflow.com/users/1580941", "pm_score": 1, "selected": true, "text": ".textContent" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19608343/" ]
74,442,193
<p>I was recently working on a WordPress project when I came across the underlined text in the picture below. It remains underlined until I hover over it, then the underline disappears.</p> <p>Button BEFORE hovering over it</p> <p><img src="https://i.stack.imgur.com/l14Wg.png" alt="Button BEFORE hovering over it" /></p> <p>Button AFTER hovering over it</p> <p><img src="https://i.stack.imgur.com/EKaz5.png" alt="Button AFTER hovering over it" /></p> <p>I tried to change basically all settings regarding both the general buttons look and the specific design of the one in the website header.</p> <p>I'm using the latest version of WordPress running the latest version of the Astra theme.</p> <p>This is the first time I have encountered this problem, although I've worked on many other websites before and it always worked as expected.</p> <p>Any Ideas?</p>
[ { "answer_id": 74442242, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 1, "selected": false, "text": "var data = [\n {foo1:\"a\",foo2:\"b\",foo3:\"c\"},\n {foo1:\"d\",foo2:\"e\",foo3:\"f\"},\n {foo1:\"g\",foo2:\"h\",foo3:\"i\"}\n]\n\nvar dataNew = [\n {lorem1:\"j\",lorem2:\"k\",lorem3:\"l\"},\n {lorem1:\"m\",lorem2:\"n\",lorem3:\"o\"},\n {lorem1:\"p\",lorem2:\"q\",lorem3:\"r\"},\n {lorem1:\"x\",lorem2:\"s\",lorem3:\"t\"},\n {lorem1:\"w\",lorem2:\"y\",lorem3:\"z\"}\n]\n\nconst parseData = (data,table) => {\n let rows = \"\";\n data.forEach(d1 =>{\n rows += \"<tr>\"\n Object.entries(d1).forEach(d2 => {\n rows += \"<td id='\" + d2[0] + \"'>\" + d2[1] + \"</td>\" \n })\n rows +=\"</tr>\"\n })\n\n table.innerHTML = rows\n}\n\nparseData(data,document.querySelector(\"#table1\"))\nparseData(dataNew,document.querySelector(\"#table2\"))" }, { "answer_id": 74442728, "author": "Vadim", "author_id": 1580941, "author_profile": "https://Stackoverflow.com/users/1580941", "pm_score": 1, "selected": true, "text": ".textContent" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14594459/" ]
74,442,204
<p>I wonder if it is possible to achieve uniqueness in an array of objects, only using one field of the object as the determinant if the object is unique or not with jsonb.</p> <p>An example of what I mean:</p> <p>I want to ensure that if the field of type jsonb looks like this:</p> <pre><code>&quot;[{&quot;x&quot;:&quot;a&quot;, &quot;timestamp&quot;: &quot;2016-12-26T12:09:43.901Z&quot;}]&quot; </code></pre> <p>then I want to have a constraint that forbids me to put another entry with &quot;x&quot;:&quot;a&quot; regardless of what the timestamp(or any other field for that matter) is on the new object I'm trying to enter</p>
[ { "answer_id": 74442542, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": true, "text": "create table the_table\n(\n id int primary key, \n data jsonb,\n constraint check_single_xa \n check (jsonb_array_length(jsonb_path_query_array(data, '$[*] ? (@.x == \"a\").x')) <= 1)\n);\n" }, { "answer_id": 74442663, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 1, "selected": false, "text": "CHECK" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5390751/" ]
74,442,231
<p>I declared an interface as below</p> <pre><code>interface Interface1 { property1: string; property2: string; } </code></pre> <p>I have another interface <code>Interface2</code> which needs to be the same as Interface1. I could have used Interface1 where ever Interface2 is used.</p> <p>But I wanted to know if there is a way to clone <code>Interface1</code> and assign it to <code>Interface2</code></p> <p>The way we do it for type declaration is as below.</p> <pre><code>type T1 = { property: 1 }; type T2 = T1; </code></pre> <p>I tried the below code.</p> <pre><code>interface Inteface2 extends Inteface1 </code></pre> <p>The above line throws an error at the end of the line.</p> <pre><code>Parsing error: '{' expected .eslint </code></pre> <p>Is there a way to clone an interface and assign it to another interface?</p>
[ { "answer_id": 74442306, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 1, "selected": false, "text": "{}" }, { "answer_id": 74442321, "author": "Anjan Talatam", "author_id": 14853666, "author_profile": "https://Stackoverflow.com/users/14853666", "pm_score": 3, "selected": true, "text": "{}" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20002028/" ]
74,442,235
<p>I would like to ask for help as I'm struggling to understand this issue.</p> <p>I have two databases main and backup. Both have same data and views. Main is inside VM on QNAP NAS (v10.5.5) and backup is on same NAS but installed natively (v10.5.8). I know this is bad idea but this is only a test setup I'm working on.</p> <p>Issue I have is with stored views. On the VM they would return result in less then 1s, but directly on NAS it takes up to 70s for exactly the same data set and view. It doesn't matter what view I use they are all slow on the backup DB. I tried to adjust settings in the mariadb.conf on NAS to increase buffers but no change made any difference at all. Only one function reduced the wait by 10s, skip-name-resolve. I have tried to run it via phpMyAdmin, MySQL Workbench and terminal directly on the NAS, result is always the same ~70s or sometimes even slower. Again on main DB inside VM they take less than 1s. That fact makes me think this is a config issue more than views themself.</p> <p>Here is my config file for mariaDB:</p> <pre><code>[mysqld] tmpdir = /share/CACHEDEV1_DATA/.mariadb10/tmp #skip-networking user=admin skip-external-locking socket = /var/run/mariadb10.sock key_buffer_size = 16M max_allowed_packet = 16M table_open_cache = 64 sort_buffer_size = 2M net_buffer_length = 16K read_buffer_size = 256K read_rnd_buffer_size = 512K myisam_sort_buffer_size = 128M #default-storage-engine = MyISAM default-storage-engine = InnoDB pid-file = /var/lock/mariadb10.pid log-error = /var/log/mariadb10/mariadb.err skip-name-resolve </code></pre> <p>I have compared output of SHOW VARIABLES; on both and the only big difference is that main DB uses rocksdb where backup is not.</p> <p>Does anyone have any idea what is wrong or what I'm missing? Please let me know if you need any extra information.</p> <p>Kind Regards</p> <p>UPDATE:</p> <p>Main explain output: <a href="https://i.stack.imgur.com/MHVqK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MHVqK.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/UqCjd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UqCjd.png" alt="enter image description here" /></a></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>select_type</th> <th>table</th> <th>type</th> <th>possible_keys</th> <th>key</th> <th>key_len</th> <th>ref</th> <th>rows</th> <th>r_rows</th> <th>filtered</th> <th>r_filtered</th> <th>Extra</th> </tr> </thead> <tbody> <tr> <td>'1'</td> <td>'PRIMARY'</td> <td>''</td> <td>'ALL'</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>'44803765561'</td> <td>'0.00'</td> <td>'100.00'</td> <td>'100.00'</td> <td>'Using where'</td> </tr> <tr> <td>'2'</td> <td>'DERIVED'</td> <td>'q1'</td> <td>'ALL'</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>'211669'</td> <td>'227012.00'</td> <td>'100.00'</td> <td>'0.00'</td> <td>'Using where; Using temporary; Using filesort'</td> </tr> <tr> <td>'2'</td> <td>'DERIVED'</td> <td>''</td> <td>'ALL'</td> <td>'distinct_key'</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>'211669'</td> <td>NULL</td> <td>'100.00'</td> <td>NULL</td> <td>'Using join buffer (flat</td> </tr> <tr> <td>'2'</td> <td>'DERIVED'</td> <td>'sic_report'</td> <td>'eq_ref'</td> <td>'PRIMARY'</td> <td>'PRIMARY'</td> <td>'4'</td> <td>'.max(<code>SOME_DB</code>.<code>sic_report</code>.<code>id</code>)'</td> <td>'1'</td> <td>NULL</td> <td>'100.00'</td> <td>NULL</td> <td>'Using where'</td> </tr> <tr> <td>'4'</td> <td>'MATERIALIZED'</td> <td>'sic_report'</td> <td>'ALL'</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>'211669'</td> <td>NULL</td> <td>'100.00'</td> <td>NULL</td> <td>'Using temporary'</td> </tr> </tbody> </table> </div> <p>Backup explain output: <a href="https://i.stack.imgur.com/GSdUX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GSdUX.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/JTuNR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JTuNR.png" alt="enter image description here" /></a></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>select_type</th> <th>table</th> <th>type</th> <th>possible_keys</th> <th>key</th> <th>key_len</th> <th>ref</th> <th>rows</th> <th>r_rows</th> <th>filtered</th> <th>r_filtered</th> <th>Extra</th> </tr> </thead> <tbody> <tr> <td>'1'</td> <td>'PRIMARY'</td> <td>''</td> <td>'ALL'</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>'230068224'</td> <td>'1.00'</td> <td>'100.00'</td> <td>'100.00'</td> <td>'Using where'</td> </tr> <tr> <td>'2'</td> <td>'DERIVED'</td> <td>'q1'</td> <td>'ALL'</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>'15168'</td> <td>'15586.00'</td> <td>'100.00'</td> <td>'100.00'</td> <td>'Using temporary; Using filesort'</td> </tr> <tr> <td>'2'</td> <td>'DERIVED'</td> <td>'sic_report'</td> <td>'ALL'</td> <td>'PRIMARY'</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>'15168'</td> <td>'15586.00'</td> <td>'100.00'</td> <td>'0.19'</td> <td>'Using where; Using join buffer (flat</td> </tr> <tr> <td>'2'</td> <td>'DERIVED'</td> <td>''</td> <td>'eq_ref'</td> <td>'distinct_key'</td> <td>'distinct_key'</td> <td>'4'</td> <td>'SOME_DB.sic_report.id'</td> <td>'1'</td> <td>'0.03'</td> <td>'100.00'</td> <td>'100.00'</td> <td>''</td> </tr> <tr> <td>'4'</td> <td>'MATERIALIZED'</td> <td>'sic_report'</td> <td>'ALL'</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>NULL</td> <td>'15168'</td> <td>'15586.00'</td> <td>'100.00'</td> <td>'100.00'</td> <td>'Using temporary'</td> </tr> </tbody> </table> </div> <p>Example view:</p> <pre><code>CREATE ALGORITHM = UNDEFINED DEFINER = `root`@`localhost` SQL SECURITY DEFINER VIEW `v_sic_stats` AS SELECT `q1`.`date_time` AS `date_time`, IFNULL(`q2`.`lines_`, 0) AS `lines_`, IFNULL(`q2`.`stations`, 0) AS `stations_avg`, IFNULL(ROUND(AVG(NULLIF(`q1`.`spol`, 0)), 1), 0) AS `spol_avg`, IFNULL(`q2`.`actual_pick`, 0) AS `actual_pick`, IFNULL(ROUND(NULLIF(`q2`.`lines_`, 0) / NULLIF(`q2`.`stations`, 0), 0), 0) AS `delivery_rate`, IFNULL(ROUND(AVG(NULLIF(`q1`.`src_order_pool`, 0)), 0), 0) AS `src_pool`, IFNULL(ROUND(AVG(NULLIF(`q1`.`wms_order_pool`, 0)), 0), 0) AS `wms_pool`, IFNULL(ROUND(`q2`.`avg_pick_time` / `q2`.`lines_`, 1), 0) AS `avg_pick_time`, IFNULL(`q2`.`sort_ff_c`, 0) AS `sort_ff_c`, IFNULL(`q2`.`sort_ff_dt`, '00:00:00') AS `sort_ff_dt`, IFNULL(`q2`.`sort_gf_c`, 0) AS `sort_gf_c`, IFNULL(`q2`.`sort_gf_dt`, '00:00:00') AS `sort_gf_dt`, IFNULL(MAX(CAST(`q1`.`sort_check_gf` AS DECIMAL (10 , 0 ))), 0) AS `sort_check_gf`, IFNULL(MAX(CAST(`q1`.`sort_check_ff` AS DECIMAL (10 , 0 ))), 0) AS `sort_check_ff`, IFNULL(`q2`.`tk01_sort_occupation`, 0) AS `tk01_sort_occupation`, IFNULL(`q2`.`tk02_sort_occupation`, 0) AS `tk02_sort_occupation`, IFNULL(`q2`.`tk01_sort_reloops`, 0) AS `tk01_sort_reloops`, IFNULL(`q2`.`tk02_sort_reloops`, 0) AS `tk02_sort_reloops`, IFNULL(`q2`.`tk01_emp_occ`, 0) AS `tk01_emp_occ`, IFNULL(`q2`.`tk01_emp_relop`, 0) AS `tk01_emp_relop`, IFNULL(`q2`.`tk02_emp_occ`, 0) AS `tk02_emp_occ`, IFNULL(`q2`.`tk02_emp_relop`, 0) AS `tk02_emp_relop`, IFNULL(`q2`.`pick_order_lead_time`, 0) AS `pick_order_lead_time`, IFNULL(ROUND(AVG(`q1`.`pick_order_postp_count`), 0), 0) AS `pick_order_postp_count`, IFNULL(`q2`.`tk01_err_occ`, 0) AS `tk01_err_occ`, IFNULL(`q2`.`tk01_err_relop`, 0) AS `tk01_err_relop`, IFNULL(`q2`.`tk02_err_occ`, 0) AS `tk02_err_occ`, IFNULL(`q2`.`tk02_err_relop`, 0) AS `tk02_err_relop`, IFNULL(`q2`.`stations_tk01`, 0) AS `stations_tk01`, IFNULL(`q2`.`stations_tk02`, 0) AS `stations_tk02`, IFNULL(`q2`.`tk01_sf_sorter`, 0) AS `tk01_sf_sorter`, IFNULL(`q2`.`tk01_sf_prezone`, 0) AS `tk01_sf_prezone`, IFNULL(`q2`.`tk02_sf_sorter`, 0) AS `tk02_sf_sorter`, IFNULL(`q2`.`tk02_sf_prezone`, 0) AS `tk02_sf_prezone` FROM (`SOME_DB`.`sic_report` `q1` JOIN (SELECT `SOME_DB`.`sic_report`.`id` AS `id`, `SOME_DB`.`sic_report`.`date_time` AS `date_time`, `SOME_DB`.`sic_report`.`lines_` AS `lines_`, `SOME_DB`.`sic_report`.`stations` AS `stations`, `SOME_DB`.`sic_report`.`spol` AS `spol`, `SOME_DB`.`sic_report`.`actual_pick` AS `actual_pick`, `SOME_DB`.`sic_report`.`created_at` AS `created_at`, `SOME_DB`.`sic_report`.`delivery_rate` AS `delivery_rate`, `SOME_DB`.`sic_report`.`src_order_pool` AS `src_order_pool`, `SOME_DB`.`sic_report`.`src_order_pool_qty` AS `src_order_pool_qty`, `SOME_DB`.`sic_report`.`wms_order_pool` AS `wms_order_pool`, `SOME_DB`.`sic_report`.`wms_order_pool_qty` AS `wms_order_pool_qty`, `SOME_DB`.`sic_report`.`avg_pick_time` AS `avg_pick_time`, `SOME_DB`.`sic_report`.`sort_ff_c` AS `sort_ff_c`, `SOME_DB`.`sic_report`.`sort_ff_dt` AS `sort_ff_dt`, `SOME_DB`.`sic_report`.`sort_gf_c` AS `sort_gf_c`, `SOME_DB`.`sic_report`.`sort_gf_dt` AS `sort_gf_dt`, `SOME_DB`.`sic_report`.`sort_check_gf` AS `sort_check_gf`, `SOME_DB`.`sic_report`.`sort_check_ff` AS `sort_check_ff`, `SOME_DB`.`sic_report`.`tk01_sort_occupation` AS `tk01_sort_occupation`, `SOME_DB`.`sic_report`.`tk02_sort_occupation` AS `tk02_sort_occupation`, `SOME_DB`.`sic_report`.`tk01_sort_reloops` AS `tk01_sort_reloops`, `SOME_DB`.`sic_report`.`tk02_sort_reloops` AS `tk02_sort_reloops`, `SOME_DB`.`sic_report`.`tk01_emp_occ` AS `tk01_emp_occ`, `SOME_DB`.`sic_report`.`tk01_emp_relop` AS `tk01_emp_relop`, `SOME_DB`.`sic_report`.`tk02_emp_occ` AS `tk02_emp_occ`, `SOME_DB`.`sic_report`.`tk02_emp_relop` AS `tk02_emp_relop`, `SOME_DB`.`sic_report`.`pick_order_lead_time` AS `pick_order_lead_time`, `SOME_DB`.`sic_report`.`pick_order_postp_count` AS `pick_order_postp_count`, `SOME_DB`.`sic_report`.`tk01_err_occ` AS `tk01_err_occ`, `SOME_DB`.`sic_report`.`tk01_err_relop` AS `tk01_err_relop`, `SOME_DB`.`sic_report`.`tk02_err_occ` AS `tk02_err_occ`, `SOME_DB`.`sic_report`.`tk02_err_relop` AS `tk02_err_relop`, `SOME_DB`.`sic_report`.`stations_tk01` AS `stations_tk01`, `SOME_DB`.`sic_report`.`stations_tk02` AS `stations_tk02`, `SOME_DB`.`sic_report`.`tk01_sf_sorter` AS `tk01_sf_sorter`, `SOME_DB`.`sic_report`.`tk01_sf_prezone` AS `tk01_sf_prezone`, `SOME_DB`.`sic_report`.`tk02_sf_sorter` AS `tk02_sf_sorter`, `SOME_DB`.`sic_report`.`tk02_sf_prezone` AS `tk02_sf_prezone` FROM `SOME_DB`.`sic_report` WHERE `SOME_DB`.`sic_report`.`id` IN (SELECT MAX(`SOME_DB`.`sic_report`.`id`) FROM `SOME_DB`.`sic_report` GROUP BY `SOME_DB`.`sic_report`.`date_time`)) `q2` ON (`q1`.`date_time` = `q2`.`date_time`)) WHERE `q1`.`date_time` &gt; SYSDATE() - INTERVAL 2 DAY GROUP BY `q1`.`date_time` </code></pre> <p>UPDATE2:</p> <p>Main innodb_buffer:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>'innodb_buffer_pool_chunk_size'</th> <th>'134217728'</th> </tr> </thead> <tbody> <tr> <td>'innodb_buffer_pool_dump_at_shutdown'</td> <td>'ON'</td> </tr> <tr> <td>'innodb_buffer_pool_dump_now'</td> <td>'OFF'</td> </tr> <tr> <td>'innodb_buffer_pool_dump_pct'</td> <td>'25'</td> </tr> <tr> <td>'innodb_buffer_pool_filename'</td> <td>'ib_buffer_pool'</td> </tr> <tr> <td>'innodb_buffer_pool_instances'</td> <td>'1'</td> </tr> <tr> <td>'innodb_buffer_pool_load_abort'</td> <td>'OFF'</td> </tr> <tr> <td>'innodb_buffer_pool_load_at_startup'</td> <td>'ON'</td> </tr> <tr> <td>'innodb_buffer_pool_load_now'</td> <td>'OFF'</td> </tr> <tr> <td>'innodb_buffer_pool_populate'</td> <td>'OFF'</td> </tr> <tr> <td>'innodb_buffer_pool_size'</td> <td>'805306368'</td> </tr> </tbody> </table> </div> <p>Backup innodb_buffer:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>'innodb_buffer_pool_chunk_size'</th> <th>'134217728'</th> </tr> </thead> <tbody> <tr> <td>'innodb_buffer_pool_dump_at_shutdown'</td> <td>'ON'</td> </tr> <tr> <td>'innodb_buffer_pool_dump_now'</td> <td>'OFF'</td> </tr> <tr> <td>'innodb_buffer_pool_dump_pct'</td> <td>'25'</td> </tr> <tr> <td>'innodb_buffer_pool_filename'</td> <td>'ib_buffer_pool'</td> </tr> <tr> <td>'innodb_buffer_pool_instances'</td> <td>'1'</td> </tr> <tr> <td>'innodb_buffer_pool_load_abort'</td> <td>'OFF'</td> </tr> <tr> <td>'innodb_buffer_pool_load_at_startup'</td> <td>'ON'</td> </tr> <tr> <td>'innodb_buffer_pool_load_now'</td> <td>'OFF'</td> </tr> <tr> <td>'innodb_buffer_pool_size'</td> <td>'1073741824'</td> </tr> </tbody> </table> </div> <p>Create Statement:</p> <pre><code>CREATE TABLE `sic_report` ( `id` int(11) NOT NULL AUTO_INCREMENT, `date_time` timestamp NOT NULL DEFAULT current_timestamp(), `lines_` text DEFAULT NULL, `stations` text DEFAULT NULL, `spol` text DEFAULT NULL, `actual_pick` text DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `delivery_rate` text DEFAULT NULL, `src_order_pool` text DEFAULT NULL, `src_order_pool_qty` text DEFAULT NULL, `wms_order_pool` text DEFAULT NULL, `wms_order_pool_qty` text DEFAULT NULL, `avg_pick_time` text DEFAULT NULL, `sort_ff_c` text DEFAULT NULL, `sort_ff_dt` text DEFAULT NULL, `sort_gf_c` text DEFAULT NULL, `sort_gf_dt` text DEFAULT NULL, `sort_check_gf` text DEFAULT NULL, `sort_check_ff` text DEFAULT NULL, `tk01_sort_occupation` text DEFAULT NULL, `tk02_sort_occupation` text DEFAULT NULL, `tk01_sort_reloops` text DEFAULT NULL, `tk02_sort_reloops` text DEFAULT NULL, `tk01_emp_occ` text DEFAULT NULL, `tk01_emp_relop` text DEFAULT NULL, `tk02_emp_occ` text DEFAULT NULL, `tk02_emp_relop` text DEFAULT NULL, `pick_order_lead_time` text DEFAULT NULL, `pick_order_postp_count` text DEFAULT NULL, `tk01_err_occ` text DEFAULT NULL, `tk01_err_relop` text DEFAULT NULL, `tk02_err_occ` text DEFAULT NULL, `tk02_err_relop` text DEFAULT NULL, `stations_tk01` text DEFAULT NULL, `stations_tk02` text DEFAULT NULL, `tk01_sf_sorter` text DEFAULT NULL, `tk01_sf_prezone` text DEFAULT NULL, `tk02_sf_sorter` text DEFAULT NULL, `tk02_sf_prezone` text DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=329266 DEFAULT CHARSET=latin1; </code></pre> <p>Main DB:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>TABLE_NAME</th> <th>ENGINE</th> <th>TABLE_ROWS</th> <th>AVG_ROW_LENGTH</th> <th>DATA_LENGTH</th> <th>INDEX_LENGTH</th> </tr> </thead> <tbody> <tr> <td>'sic_report'</td> <td>'InnoDB'</td> <td>'15644'</td> <td>'235'</td> <td>'3686400'</td> <td>'0'</td> </tr> </tbody> </table> </div> <p>Backup DB :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>TABLE_NAME</th> <th>ENGINE</th> <th>TABLE_ROWS</th> <th>AVG_ROW_LENGTH</th> <th>DATA_LENGTH</th> <th>INDEX_LENGTH</th> </tr> </thead> <tbody> <tr> <td>'sic_report'</td> <td>'InnoDB'</td> <td>'16266'</td> <td>'226'</td> <td>'3686400'</td> <td>'0'</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74444045, "author": "nnichols", "author_id": 1191247, "author_profile": "https://Stackoverflow.com/users/1191247", "pm_score": 2, "selected": true, "text": "ANALYZE TABLE table_name_1, table_name_2;\n" }, { "answer_id": 74453892, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 0, "selected": false, "text": "innodb_buffer_pool_size = 134217728\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048283/" ]
74,442,280
<p>I have 3 collections User, Attendance, Detection</p> <p>User collection Document</p> <pre class="lang-js prettyprint-override"><code>{ &quot;_id&quot;: &quot;60dd781d4524e6c116e234d2&quot;, &quot;workerFirstName&quot;: &quot;AMIT&quot;, &quot;workerSurname&quot;: &quot;SHAH&quot;, &quot;workerId&quot;: &quot;1001&quot;, &quot;locationName&quot;: &quot;HEAD OFFICE&quot;, &quot;workerDesignation&quot;: &quot;IT&quot;, &quot;workerDepartment&quot;: &quot;IT&quot;, }, </code></pre> <p>Attendance Document</p> <pre class="lang-js prettyprint-override"><code>{ &quot;_id&quot;: &quot;61307cee85b5055a15cf01b7&quot;, &quot;employeeId&quot;:&quot;60dd781d4524e6c116e234d2&quot;, &quot;Date&quot;: &quot;2022-11-01T00:00:00.000Z&quot;, &quot;duration&quot;: null, &quot;createdAs&quot;: &quot;FULL-DAY&quot;, &quot;detections&quot;: [ &quot;636095dc00d9abc953d8fd57&quot;, &quot;636132e6bf6fe52c582853b3&quot; ] } </code></pre> <p>Detection Document</p> <pre><code>{ &quot;_id&quot;: &quot;636095dc00d9abc953d8fd57&quot;, &quot;AttendanceId&quot;: &quot;61307cee85b5055a15cf01b7&quot; }, { &quot;_id&quot;: &quot;636132e6bf6fe52c582853b3&quot;, &quot;AttendanceId&quot;: &quot;61307cee85b5055a15cf01b7&quot; } </code></pre> <p>Getting all User $lookup to attendance and getting all the attendance related to a user.</p> <p>And also there is a detection array inside the attendance object. I want to also populate that detection array which is inside the attendance object.</p> <p>The query I Tried</p> <pre class="lang-js prettyprint-override"><code> const dailyAttendance = await User.aggregate([ { $sort: { workerId: 1 } }, { $match: { lastLocationId: Mongoose.Types.ObjectId(locationId), workerType: workerType, isActive: true, workerId: { $nin: [ &quot;8080&quot;, &quot;9999&quot;, &quot;9998&quot;, &quot;9997&quot;, &quot;9996&quot;, &quot;9995&quot;, &quot;9994&quot;, ], }, }, }, { $project: { _id: 1, workerId: 1, workerFirstName: 1, workerSurname: 1, workerDepartment: 1, workerDesignation: 1, locationName: 1, }, }, { $lookup: { from: &quot;attendances&quot;, localField: &quot;_id&quot;, foreignField: &quot;employeeId&quot;, pipeline: [ { $match: { Date: new Date(date), }, }, { $project: typesOfData, }, ], as: &quot;attendances&quot;, }, }, { $unwind: { path: &quot;$attendances&quot;, preserveNullAndEmptyArrays: true, }, }, ]) </code></pre> <p><strong>Output I got</strong></p> <pre class="lang-js prettyprint-override"><code>{ &quot;dailyAttendance&quot;: [ { &quot;_id&quot;: &quot;60dd781d4524e6c116e234d2&quot;, &quot;workerFirstName&quot;: &quot;AMIT&quot;, &quot;workerSurname&quot;: &quot;SHAH&quot;, &quot;workerId&quot;: &quot;1001&quot;, &quot;locationName&quot;: &quot;HEAD OFFICE&quot;, &quot;workerDesignation&quot;: &quot;IT&quot;, &quot;workerDepartment&quot;: &quot;IT&quot;, &quot;attendances&quot;: { &quot;_id&quot;: &quot;61307cee85b5055a15cf01b7&quot;, &quot;Date&quot;: &quot;2022-11-01T00:00:00.000Z&quot;, &quot;duration&quot;: null, &quot;createdAs&quot;: &quot;FULL-DAY&quot;, &quot;detections&quot;: [ &quot;636095dc00d9abc953d8fd57&quot;, &quot;636132e6bf6fe52c582853b3&quot; ] } }, { &quot;_id&quot;: &quot;60dd781c4524e6c116e2336c&quot;, &quot;workerFirstName&quot;: &quot;MADASWAMY&quot;, &quot;workerSurname&quot;: &quot;KARUPPASWAMY&quot;, &quot;workerId&quot;: &quot;1002&quot;, &quot;locationName&quot;: &quot;HEAD OFFICE&quot;, &quot;workerDesignation&quot;: &quot;IT&quot;, &quot;workerDepartment&quot;: &quot;IT&quot;, &quot;attendances&quot;: { &quot;_id&quot;: &quot;61307ce485b5055a15ceec02&quot;, &quot;Date&quot;: &quot;2022-11-01T00:00:00.000Z&quot;, &quot;duration&quot;: null, &quot;createdAs&quot;: &quot;FULL-DAY&quot;, &quot;detections&quot;: [ &quot;636095dc00d9abc953d8fd57&quot;, &quot;636132e6bf6fe52c582853b3&quot; ] } } ] } </code></pre>
[ { "answer_id": 74445120, "author": "Charchit Kapoor", "author_id": 12368154, "author_profile": "https://Stackoverflow.com/users/12368154", "pm_score": 0, "selected": false, "text": "db.user.aggregate([\n {\n \"$lookup\": {\n \"from\": \"attendance\",\n \"let\": {\n userId: \"$_id\"\n },\n \"pipeline\": [\n {\n \"$match\": {\n $expr: {\n \"$eq\": [\n \"$$userId\",\n \"$employeeId\"\n ]\n }\n }\n },\n {\n \"$unwind\": {\n path: \"$detections\",\n preserveNullAndEmptyArrays: true\n }\n },\n {\n \"$lookup\": {\n \"from\": \"detection\",\n \"localField\": \"detections\",\n \"foreignField\": \"_id\",\n \"as\": \"detections\"\n }\n },\n {\n \"$unwind\": {\n path: \"$detections\",\n preserveNullAndEmptyArrays: true\n }\n },\n {\n \"$group\": {\n \"_id\": {\n \"Date\": \"$Date\",\n \"_id\": \"$_id\",\n \"createdAs\": \"$createdAs\",\n \"duration\": \"$duration\",\n \"employeeId\": \"$employeeId\"\n },\n \"detections\": {\n \"$push\": \"$detections\"\n }\n }\n },\n {\n \"$replaceRoot\": {\n \"newRoot\": {\n \"$mergeObjects\": [\n \"$_id\",\n {\n detections: \"$detections\"\n }\n ]\n }\n }\n }\n ],\n \"as\": \"attendance\"\n }\n }\n])\n" }, { "answer_id": 74445353, "author": "Ali Iqbal", "author_id": 20321054, "author_profile": "https://Stackoverflow.com/users/20321054", "pm_score": 1, "selected": false, "text": "const dailyAttendance = await User.aggregate([\n { $sort: { workerId: 1 } },\n {\n $match: {\n lastLocationId: Mongoose.Types.ObjectId(locationId),\n workerType: workerType,\n isActive: true,\n workerId: {\n $nin: [\n \"8080\",\n \"9999\",\n \"9998\",\n \"9997\",\n \"9996\",\n \"9995\",\n \"9994\",\n ],\n },\n },\n },\n {\n $project: {\n _id: 1,\n workerId: 1,\n workerFirstName: 1,\n workerSurname: 1,\n workerDepartment: 1,\n workerDesignation: 1,\n locationName: 1,\n },\n },\n {\n $lookup: {\n from: \"attendances\",\n localField: \"_id\",\n foreignField: \"employeeId\",\n pipeline: [\n {\n $match: {\n Date: new Date(date),\n },\n },\n {\n $project: typesOfData,\n },\n ],\n as: \"attendances\",\n },\n },\n {\n $unwind: {\n path: \"$attendances\",\n preserveNullAndEmptyArrays: true,\n },\n },\n {\n '$unwind': {\n path: '$attandances.detections', \n preserveNullAndEmptyArrays: true\n }\n },\n {\n $lookup: {\n from: \"detections\",\n localField: \"attandances.detections\",\n foreignField: \"_id\",\n as: \"occurances\",\n },\n },\n ])\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9468615/" ]
74,442,296
<p>how can I get desired result. I want to calculate the cumulative sum of negative numbers first and then add this cumulative sum with positive numbers.</p> <pre><code>CREATE TABLE dbo.tb( [group_name] [nvarchar](255) ,[value] [float] ) INSERT INTO [dbo].[tb] ([group_name] ,[value]) VALUES ('A',-3),('A',-2),('A',-1),('A',1),('A',3),('B',-2) </code></pre> <p>By writing the following code, the result column will be displayed</p> <pre><code>SELECT [group_name] ,[value] ,sum(value) OVER (PARTITION BY group_name ORDER BY value asc ) result FROM [dbo].[tb] </code></pre> <p>How can I achieve the desired column?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>group_name</th> <th>value</th> <th>result</th> <th>desired</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>-3</td> <td>-3</td> <td>-6</td> </tr> <tr> <td>A</td> <td>-2</td> <td>-5</td> <td>-3</td> </tr> <tr> <td>A</td> <td>-1</td> <td>-6</td> <td>-1</td> </tr> <tr> <td>A</td> <td>1</td> <td>-5</td> <td>0</td> </tr> <tr> <td>A</td> <td>3</td> <td>2</td> <td>3</td> </tr> <tr> <td>B</td> <td>-2</td> <td>-2</td> <td>-2</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74463156, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 3, "selected": true, "text": "SELECT group_name, value,\n CASE \n WHEN \n value<0 THEN\n SUM(CASE WHEN value<0 THEN value END) OVER \n (PARTITION BY group_name ORDER BY value DESC)\n ELSE\n SUM(CASE WHEN value>=0 THEN value END) OVER \n (PARTITION BY group_name ORDER BY value) + \n MAX(CASE WHEN value<0 THEN value END) OVER \n (PARTITION BY group_name)\n END AS desired\nFROM tb\nORDER BY group_name, value\n" }, { "answer_id": 74463251, "author": "Rajat", "author_id": 9947159, "author_profile": "https://Stackoverflow.com/users/9947159", "pm_score": 1, "selected": false, "text": "cte" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15572273/" ]
74,442,303
<p>I would like to migrate to Jetpack Compose, but I don't know where to begin. My app uses single Activity / multiple Fragments, and there at least 100 Fragments. The app's navigation graph is in XML, which I understand does not support Composables.</p> <p>Please let me know if this sounds like the correct path.</p> <ol> <li>Modify each Fragment so that it hosts a single ComposeView that will contain the screen's UI</li> <li>Once completed, convert each Fragment to a Composable</li> <li>Replace the navigation graph with Jetpack Compose navigation</li> </ol> <p>Once this is done, there will be no Fragments in the app. Not sure what to do with my Activity. Should that be replaced as well?</p> <p>This will take forever, but I just wanted to make sure there is no other alternative. Thanks!</p>
[ { "answer_id": 74467150, "author": "Chris Arriola", "author_id": 450243, "author_profile": "https://Stackoverflow.com/users/450243", "pm_score": 1, "selected": false, "text": "FragmentActivity" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183356/" ]
74,442,322
<p>Code :</p> <pre><code>public class MyRepository { public TeamContext _teamContext; public MyRepository(TeamContext teamContext) { _teamContext = teamContext; } public void AddTeam(Team team) { team.Id = Guid.NewGuid(); _teamContext.Team.Add(team); } } </code></pre> <p>Team names should be unique. Using Entity Framework how to validate that?</p>
[ { "answer_id": 74442465, "author": "masoud rafiee", "author_id": 4256602, "author_profile": "https://Stackoverflow.com/users/4256602", "pm_score": 1, "selected": false, "text": "UNIQUE" }, { "answer_id": 74442533, "author": "Mihai Alexandru-Ionut", "author_id": 6583140, "author_profile": "https://Stackoverflow.com/users/6583140", "pm_score": 3, "selected": true, "text": "public void AddTeam(Team team)\n{ \n if(_textContext.Team.Any(t => t.Name == team.Name))\n {\n throw new TeamAlreadyExists(team.Name);\n }\n team.Id = Guid.NewGuid();\n _teamContext.Team.Add(team);\n}\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19799746/" ]
74,442,357
<p>Part of my tool allows a user to enter a string into a textfield, check if any words entered match with a preset array.</p> <p>If the user's string contains a name object in the array then I want it to be replaced with a link.</p> <p>I've created the function and onClick it should get the user's content, loop through the array to see if any names match the user's content and then replace that name with a link.</p> <p>Currently, it's only doing it per array object where as I need it to replace all and only return one string.</p> <pre><code> const generateContent = () =&gt; { var arr1 = [{ link: 'https://www.link1.com/', name: 'Link1' }, { link: 'https://www.link2.com/', name: 'Link2' }]; const findArrayItem = arr1.find(obj =&gt; content.includes(obj.name)) const final = content.replaceAll(findArrayItem.name, &quot;&lt;a href=&quot; + findArrayItem.link + &quot;&gt;&quot; + findArrayItem.name + &quot;&lt;/a&gt;&quot;) setFinalContent(final) } </code></pre>
[ { "answer_id": 74442525, "author": "nakzyu", "author_id": 12890173, "author_profile": "https://Stackoverflow.com/users/12890173", "pm_score": 2, "selected": true, "text": "const content = 'Link1Link2';\nconst generateContent = (content) => {\n var arr1 = [\n {\n link: 'https://www.link1.com/',\n name: 'Link1',\n },\n {\n link: 'https://www.link2.com/',\n name: 'Link2',\n },\n ];\n\n const final = arr1.reduce((a, b) => {\n return a.replaceAll(b.name, '<a href=' + b.link + '>' + b.name + '</a>');\n }, content);\n\n return final;\n};\n\ngenerateContent(content);" }, { "answer_id": 74442761, "author": "gazdagergo", "author_id": 5506730, "author_profile": "https://Stackoverflow.com/users/5506730", "pm_score": 0, "selected": false, "text": "const { useState } = React // for inline use\n// import { useState } from 'react' // for normal use\n\nconst linkMapping = [\n {\n link: 'https://www.link1.com/',\n name: 'Link1'\n },\n {\n link: 'https://www.link2.com/',\n name: 'Link2'\n }\n]\n\nconst replaceToLink = (text, linkMapping) => {\n return linkMapping.reduce((acc, { name, link }) => {\n return acc.replaceAll(`${name} `, `<a href=\"${link}\">${name}</a> `)\n }, text)\n}\n\nconst App = () => {\n const [value, setValue] = useState('')\n \n const handleChange = ({ target }) => {\n setValue(target.value)\n }\n \n return (\n <div>\n <textarea value={value} onChange={handleChange} />\n <div dangerouslySetInnerHTML={{ __html: replaceToLink(value, linkMapping) }} />\n </div>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'))" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16034511/" ]
74,442,375
<p>I want to develop a qml application that starts with the main window and three buttons are available in the main window. By pressing each button a new page(Layout) should show up, but after returning to the main window, the state of the previous page should not change. I have tried ListView but it did not work, because it destroys the Item after pop(). Here is my Code(PagesOne.qml is a sample for three pages that I want to open):</p> <blockquote> <p>main.qml</p> </blockquote> <pre class="lang-js prettyprint-override"><code> ApplicationWindow { id: root visible: true width: 8 * Screen.width / 10 height: 8 * Screen.height / 10 color: &quot;#154c79&quot; // Keep the window on the given x,y on starting Component.onCompleted: { x: Screen.width / 10 y: Screen.height / 10 } minimumWidth: 700 minimumHeight: 400 // Current Working Layout Component { id: pageOne PageOne{} } // Empty Layout Component { id: pageTwo PageTwo{} } // Empty Layout Component { id: pageThree PageThree{} } property variant items: [pageOne.createObject(), pageTwo.createObject(), pageThree.createObject()] StackView { id: stack anchors.fill: parent // initialItem: pageOne Component.onCompleted: { stack.push(items[2], {&quot;destroyOnPop&quot;: false}) stack.push(items[1], {&quot;destroyOnPop&quot;: false}) stack.push(items[0], {&quot;destroyOnPop&quot;: false}) } } // change layout on call function load_layout(layout){ console.log(&quot;#############&quot;, stack.depth, &quot;#############&quot;) switch (layout){ case 'one': stack.pop(0, {&quot;destroyOnPop&quot;: false}) break; case 'two': stack.pop(1, {&quot;destroyOnPop&quot;: false}) break; case 'three': stack.pop(2, {&quot;destroyOnPop&quot;: false}) break; default: stack.pop(0, {&quot;destroyOnPop&quot;: false}) } } } </code></pre> <blockquote> <p>PageOne.qml:</p> </blockquote> <pre class="lang-js prettyprint-override"><code> Item{ id: root // anchors.fill: parent // Empty rect Rectangle{ color: &quot;#03fc88&quot; anchors.fill: parent TextField { anchors.right: parent.right anchors.top: parent.top width: 120 height: 60 placeholderText: qsTr(&quot;Enter: &quot;) } Label{ anchors.centerIn: parent text: &quot;Page two&quot; } // return button RoundButton { id: btnBack text: &quot;\u003C&quot; onClicked: { if(text === &quot;\u003C&quot;){ load_layout('one') } } } } } </code></pre> <p>Is there any suggestion that helps me?</p>
[ { "answer_id": 74442525, "author": "nakzyu", "author_id": 12890173, "author_profile": "https://Stackoverflow.com/users/12890173", "pm_score": 2, "selected": true, "text": "const content = 'Link1Link2';\nconst generateContent = (content) => {\n var arr1 = [\n {\n link: 'https://www.link1.com/',\n name: 'Link1',\n },\n {\n link: 'https://www.link2.com/',\n name: 'Link2',\n },\n ];\n\n const final = arr1.reduce((a, b) => {\n return a.replaceAll(b.name, '<a href=' + b.link + '>' + b.name + '</a>');\n }, content);\n\n return final;\n};\n\ngenerateContent(content);" }, { "answer_id": 74442761, "author": "gazdagergo", "author_id": 5506730, "author_profile": "https://Stackoverflow.com/users/5506730", "pm_score": 0, "selected": false, "text": "const { useState } = React // for inline use\n// import { useState } from 'react' // for normal use\n\nconst linkMapping = [\n {\n link: 'https://www.link1.com/',\n name: 'Link1'\n },\n {\n link: 'https://www.link2.com/',\n name: 'Link2'\n }\n]\n\nconst replaceToLink = (text, linkMapping) => {\n return linkMapping.reduce((acc, { name, link }) => {\n return acc.replaceAll(`${name} `, `<a href=\"${link}\">${name}</a> `)\n }, text)\n}\n\nconst App = () => {\n const [value, setValue] = useState('')\n \n const handleChange = ({ target }) => {\n setValue(target.value)\n }\n \n return (\n <div>\n <textarea value={value} onChange={handleChange} />\n <div dangerouslySetInnerHTML={{ __html: replaceToLink(value, linkMapping) }} />\n </div>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'))" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13058878/" ]
74,442,407
<p>I have 32GB of managed memory and 8 task slots. As <code>state.backend.rocksdb.memory.managed</code> is set to true, each rockdb in each task slot uses 4GB of memory. Some of my tasks do not require a rocksdb backend so I want to increase this 4GB to 6GB by setting <code>state.backend.rocksdb.memory.fixed-per-slot: 6000m</code></p> <p>The problem when I set <code>state.backend.rocksdb.memory.fixed-per-slot: 6000m</code> is on Flink UI, in task manager page, I cant see the allocated managed memory anymore.</p> <p>As you can see when <code>state.backend.rocksdb.memory.fixed-per-slot</code> is not set and <code>state.backend.rocksdb.memory.managed: true</code>, 4GB usage appears on managed memory for each running task which uses rocksdb backend.</p> <p><a href="https://i.stack.imgur.com/CDBvf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CDBvf.png" alt="enter image description here" /></a></p> <p>But after setting <code>state.backend.rocksdb.memory.fixed-per-slot: 6000m</code> , Managed Memory always shows zero!</p> <p>1- How can I watch the managed memory allocation after setting <code>state.backend.rocksdb.memory.fixed-per-slot: 6000m</code></p> <p>2- Should <code>state.backend.rocksdb.memory.managed</code> be set to true even I set fixed-per-slot.</p>
[ { "answer_id": 74442525, "author": "nakzyu", "author_id": 12890173, "author_profile": "https://Stackoverflow.com/users/12890173", "pm_score": 2, "selected": true, "text": "const content = 'Link1Link2';\nconst generateContent = (content) => {\n var arr1 = [\n {\n link: 'https://www.link1.com/',\n name: 'Link1',\n },\n {\n link: 'https://www.link2.com/',\n name: 'Link2',\n },\n ];\n\n const final = arr1.reduce((a, b) => {\n return a.replaceAll(b.name, '<a href=' + b.link + '>' + b.name + '</a>');\n }, content);\n\n return final;\n};\n\ngenerateContent(content);" }, { "answer_id": 74442761, "author": "gazdagergo", "author_id": 5506730, "author_profile": "https://Stackoverflow.com/users/5506730", "pm_score": 0, "selected": false, "text": "const { useState } = React // for inline use\n// import { useState } from 'react' // for normal use\n\nconst linkMapping = [\n {\n link: 'https://www.link1.com/',\n name: 'Link1'\n },\n {\n link: 'https://www.link2.com/',\n name: 'Link2'\n }\n]\n\nconst replaceToLink = (text, linkMapping) => {\n return linkMapping.reduce((acc, { name, link }) => {\n return acc.replaceAll(`${name} `, `<a href=\"${link}\">${name}</a> `)\n }, text)\n}\n\nconst App = () => {\n const [value, setValue] = useState('')\n \n const handleChange = ({ target }) => {\n setValue(target.value)\n }\n \n return (\n <div>\n <textarea value={value} onChange={handleChange} />\n <div dangerouslySetInnerHTML={{ __html: replaceToLink(value, linkMapping) }} />\n </div>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'))" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1867205/" ]
74,442,409
<p>I'm trying to make a book where if the user press the pages it <code>SetActive(false)</code> every <code>GameObject</code> except the selected <code>GameObject</code>.</p> <pre class="lang-cs prettyprint-override"><code>public GameObject[] bookPages; int currentPage; public void whatPage ( ) { int pages = 0; while ( pages &lt; bookPages.Length ) { if ( pages == currentPage ) { Debug.Log ( &quot;CURRENT PAGE&quot; + currentPage ); bookPages [ currentPage ].SetActive ( true ); pages++; continue; } bookPages [ pages ].SetActive ( false ); Debug.Log ( pages ); pages++; } } public void pageFlu ( ) { currentPage = 1; whatPage ( ); bookPages [ currentPage ].SetActive ( true ); } </code></pre> <p>I have tried the <code>continue</code> method.</p>
[ { "answer_id": 74442513, "author": "Kroepniek", "author_id": 19699903, "author_profile": "https://Stackoverflow.com/users/19699903", "pm_score": 3, "selected": true, "text": "public GameObject[] bookPages;\nint currentPage;\n\npublic void DeactivateAllPages()\n{\n foreach (GameObject page in bookPages)\n {\n page.SetActive(false);\n }\n}\n\npublic void SelectPage(int pageIndex)\n{\n bookPages[currangePage].SetActive(false);\n\n currangePage = pageIndex;\n\n bookPages[currangePage].SetActive(true);\n}\n" }, { "answer_id": 74442557, "author": "Milan Egon Votrubec", "author_id": 8051819, "author_profile": "https://Stackoverflow.com/users/8051819", "pm_score": 0, "selected": false, "text": "currentPage " } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20449786/" ]
74,442,415
<p>I want if is possible the <code>Link</code> component from <code>react-router-dom</code> to not work until validations are made correct. If I remove the link, validation works as I want.</p> <p>I saw something with <code>ifValidate</code> but I don't understand exactly how to apply it.</p> <pre><code>import { Link } from &quot;react-router-dom&quot;; const AgentProfile = () =&gt; { const [firstName, setFirstName] = useState(&quot;&quot;); const [lastName, setLastName] = useState(&quot;&quot;); const [phone, setPhone] = useState(&quot;&quot;); const [proficiency, setProficiency] = useState(&quot;&quot;); const [address, setAddress] = useState(&quot;&quot;); const [city, setCity] = useState(&quot;&quot;); const [firstNameError, setFirstNameError] = useState(false); const [lastNameError, setLastNameError] = useState(false); const [phoneError, setPhoneError] = useState(false); const [proficiencyError, setProficiencyError] = useState(false); const [addressError, setAddressError] = useState(false); const [cityError, setCityError] = useState(false); const handleSubmit = (e) =&gt; { e.preventDefault(); setFirstNameError(false); setLastNameError(false); setPhoneError(false); setProficiencyError(false); setAddressError(false); setCityError(false); if (firstName === &quot;&quot;) { setFirstNameError(true); } if (lastName === &quot;&quot;) { setLastNameError(true); } if (phone === &quot;&quot;) { setPhoneError(true); } if (proficiency === &quot;&quot;) { setProficiencyError(true); } if (address === &quot;&quot;) { setAddressError(true); } if (city === &quot;&quot;) { setCityError(true); } if (firstName &amp;&amp; lastName &amp;&amp; phone &amp;&amp; proficiency &amp;&amp; address &amp;&amp; city) { console.log(firstName, lastName, phone, proficiency, address, city); } }; return ( &lt;&gt; &lt;Box sx={{ display: &quot;flex&quot;, flexDirection: &quot;column&quot;, width: &quot;65%&quot; }}&gt; &lt;Box ml={10} pt={6}&gt; &lt;Typography variant=&quot;h3&quot; color=&quot;GrayText&quot;&gt; Hello! Please tell us a little bit about yourself. &lt;/Typography&gt; &lt;/Box&gt; &lt;form noValidate autoComplete=&quot;off&quot; onSubmit={handleSubmit}&gt; &lt;Box sx={{ display: &quot;flex&quot; }} ml={10} mt={2}&gt; &lt;Box sx={{ width: &quot;50%&quot; }}&gt; {/* &lt;Typography variant=&quot;body2&quot;&gt;First Name&lt;/Typography&gt; */} &lt;TextField onChange={(e) =&gt; setFirstName(e.target.value)} label=&quot;First Name&quot; type=&quot;text&quot; required variant=&quot;outlined&quot; size=&quot;small&quot; error={firstNameError} /&gt; &lt;/Box&gt; &lt;Box&gt; {/* &lt;Typography variant=&quot;body2&quot;&gt;Last Name&lt;/Typography&gt; */} &lt;TextField onChange={(e) =&gt; setLastName(e.target.value)} label=&quot;Last Name&quot; type=&quot;text&quot; required variant=&quot;outlined&quot; size=&quot;small&quot; error={lastNameError} /&gt; &lt;/Box&gt; &lt;/Box&gt; &lt;Box sx={{ display: &quot;flex&quot; }} ml={10} mt={4}&gt; &lt;Box sx={{ width: &quot;50%&quot; }}&gt; {/* &lt;Typography variant=&quot;body2&quot;&gt;Phone&lt;/Typography&gt; */} &lt;TextField onChange={(e) =&gt; setPhone(e.target.value)} label=&quot;Phone&quot; type=&quot;text&quot; required variant=&quot;outlined&quot; size=&quot;small&quot; error={phoneError} /&gt; &lt;/Box&gt; &lt;Box sx={{ width: &quot;30%&quot; }}&gt; {/* &lt;Typography variant=&quot;body2&quot;&gt;Work Proficiency&lt;/Typography&gt; */} &lt;FormControl fullWidth size=&quot;small&quot; required&gt; &lt;InputLabel id=&quot;demo-simple-select-label&quot;&gt; Work Proficiency &lt;/InputLabel&gt; &lt;Select onChange={(e) =&gt; setProficiency(e.target.value)} labelId=&quot;demo-simple-select-label&quot; id=&quot;demo-simple-select&quot; value={proficiency} label=&quot;Work Proficiency&quot; error={proficiencyError} &gt; &lt;MenuItem value={2}&gt;Two years&lt;/MenuItem&gt; &lt;MenuItem value={5}&gt;Five years&lt;/MenuItem&gt; &lt;MenuItem value={10}&gt;Ten years&lt;/MenuItem&gt; &lt;/Select&gt; &lt;/FormControl&gt; &lt;/Box&gt; &lt;/Box&gt; &lt;Box ml={10} mt={6}&gt; {/* &lt;Typography variant=&quot;body2&quot;&gt;Street Address&lt;/Typography&gt; */} &lt;TextField onChange={(e) =&gt; setAddress(e.target.value)} label=&quot;Street Address&quot; type=&quot;text&quot; required variant=&quot;outlined&quot; size=&quot;small&quot; sx={{ width: &quot;80%&quot; }} error={addressError} /&gt; &lt;/Box&gt; &lt;Box ml={10} mt={6}&gt; {/* &lt;Typography variant=&quot;body2&quot;&gt;City&lt;/Typography&gt; */} &lt;TextField onChange={(e) =&gt; setCity(e.target.value)} label=&quot;City&quot; type=&quot;text&quot; required variant=&quot;outlined&quot; size=&quot;small&quot; sx={{ width: &quot;40%&quot; }} error={cityError} /&gt; &lt;/Box&gt; &lt;Box mt={8} sx={{ display: &quot;flex&quot;, justifyContent: &quot;space-between&quot; }}&gt; &lt;Box ml={8}&gt; &lt;Button variant=&quot;outlined&quot; sx={{ borderRadius: &quot;20px&quot; }}&gt; Back &lt;/Button&gt; &lt;/Box&gt; &lt;Box mr={18}&gt; &lt;Button type=&quot;submit&quot; variant=&quot;contained&quot; sx={{ borderRadius: &quot;20px&quot; }} &gt; &lt;Link to=&quot;/experienceconfirm&quot;&gt;Next&lt;/Link&gt; &lt;/Button&gt; &lt;/Box&gt; &lt;/Box&gt; &lt;/form&gt; &lt;/Box&gt; &lt;/&gt; ); }; export default AgentProfile; </code></pre> <p>Something like if validation is not correct link component to be disabled, and when user completes every field to become active.</p>
[ { "answer_id": 74442652, "author": "Bikas Lin", "author_id": 17582798, "author_profile": "https://Stackoverflow.com/users/17582798", "pm_score": 0, "selected": false, "text": "import { useEffect, useMemo } from \"react\";\nimport { Link } from \"react-router-dom\";\n\nconst AgentProfile = () => {\n const [firstName, setFirstName] = useState(\"\");\n const [lastName, setLastName] = useState(\"\");\n const [phone, setPhone] = useState(\"\");\n const [proficiency, setProficiency] = useState(\"\");\n const [address, setAddress] = useState(\"\");\n const [city, setCity] = useState(\"\");\n\n const [firstNameError, setFirstNameError] = useState(false);\n const [lastNameError, setLastNameError] = useState(false);\n const [phoneError, setPhoneError] = useState(false);\n const [proficiencyError, setProficiencyError] = useState(false);\n const [addressError, setAddressError] = useState(false);\n const [cityError, setCityError] = useState(false);\n\n useEffect(() => {\n if (firstName === \"\") {\n setFirstNameError(true);\n }\n\n if (lastName === \"\") {\n setLastNameError(true);\n }\n\n if (phone === \"\") {\n setPhoneError(true);\n }\n\n if (proficiency === \"\") {\n setProficiencyError(true);\n }\n\n if (address === \"\") {\n setAddressError(true);\n }\n\n if (city === \"\") {\n setCityError(true);\n }\n }, [firstName, lastName, phone, proficiency, address, city])\n\n const hasError = useMemo(\n () => firstNameError || lastNameError || phoneError || proficiencyError || addressError || cityError\n , [firstNameError, lastNameError, phoneError, proficiencyError, addressError, cityError]\n )\n\n return (\n <>\n <Box sx={{ display: \"flex\", flexDirection: \"column\", width: \"65%\" }}>\n <Box ml={10} pt={6}>\n <Typography variant=\"h3\" color=\"GrayText\">\n Hello! Please tell us a little bit about yourself.\n </Typography>\n </Box>\n <form noValidate autoComplete=\"off\" onSubmit={handleSubmit}>\n <Box sx={{ display: \"flex\" }} ml={10} mt={2}>\n <Box sx={{ width: \"50%\" }}>\n {/* <Typography variant=\"body2\">First Name</Typography> */}\n <TextField\n onChange={(e) => setFirstName(e.target.value)}\n label=\"First Name\"\n type=\"text\"\n required\n variant=\"outlined\"\n size=\"small\"\n error={firstNameError}\n />\n </Box>\n <Box>\n {/* <Typography variant=\"body2\">Last Name</Typography> */}\n <TextField\n onChange={(e) => setLastName(e.target.value)}\n label=\"Last Name\"\n type=\"text\"\n required\n variant=\"outlined\"\n size=\"small\"\n error={lastNameError}\n />\n </Box>\n </Box>\n <Box sx={{ display: \"flex\" }} ml={10} mt={4}>\n <Box sx={{ width: \"50%\" }}>\n {/* <Typography variant=\"body2\">Phone</Typography> */}\n <TextField\n onChange={(e) => setPhone(e.target.value)}\n label=\"Phone\"\n type=\"text\"\n required\n variant=\"outlined\"\n size=\"small\"\n error={phoneError}\n />\n </Box>\n <Box sx={{ width: \"30%\" }}>\n {/* <Typography variant=\"body2\">Work Proficiency</Typography> */}\n <FormControl fullWidth size=\"small\" required>\n <InputLabel id=\"demo-simple-select-label\">\n Work Proficiency\n </InputLabel>\n <Select\n onChange={(e) => setProficiency(e.target.value)}\n labelId=\"demo-simple-select-label\"\n id=\"demo-simple-select\"\n value={proficiency}\n label=\"Work Proficiency\"\n error={proficiencyError}\n >\n <MenuItem value={2}>Two years</MenuItem>\n <MenuItem value={5}>Five years</MenuItem>\n <MenuItem value={10}>Ten years</MenuItem>\n </Select>\n </FormControl>\n </Box>\n </Box>\n <Box ml={10} mt={6}>\n {/* <Typography variant=\"body2\">Street Address</Typography> */}\n <TextField\n onChange={(e) => setAddress(e.target.value)}\n label=\"Street Address\"\n type=\"text\"\n required\n variant=\"outlined\"\n size=\"small\"\n sx={{ width: \"80%\" }}\n error={addressError}\n />\n </Box>\n <Box ml={10} mt={6}>\n {/* <Typography variant=\"body2\">City</Typography> */}\n <TextField\n onChange={(e) => setCity(e.target.value)}\n label=\"City\"\n type=\"text\"\n required\n variant=\"outlined\"\n size=\"small\"\n sx={{ width: \"40%\" }}\n error={cityError}\n />\n </Box>\n <Box mt={8} sx={{ display: \"flex\", justifyContent: \"space-between\" }}>\n <Box ml={8}>\n <Button variant=\"outlined\" sx={{ borderRadius: \"20px\" }}>\n Back\n </Button>\n </Box>\n <Box mr={18}>\n <Button\n type=\"submit\"\n variant=\"contained\"\n sx={{ borderRadius: \"20px\" }}\n >\n {hasError? \"Next\" : <Link to=\"/experienceconfirm\">Next</Link>}\n </Button>\n </Box>\n </Box>\n </form>\n </Box>\n </>\n );\n};\n\nexport default AgentProfile;\n" }, { "answer_id": 74442774, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 1, "selected": false, "text": "import { Link, useNavigate } from 'react-router-dom';\n\nconst AgentProfile = () => {\n const navigate = useNavigate();\n\n ...\n\n const handleSubmit = (e) => {\n e.preventDefault();\n setFirstNameError(false);\n setLastNameError(false);\n setPhoneError(false);\n setProficiencyError(false);\n setAddressError(false);\n setCityError(false);\n\n let isError = false;\n\n if (!firstName) {\n setFirstNameError(true);\n isError = true;\n }\n\n if (!lastName) {\n setLastNameError(true);\n isError = true;\n }\n\n if (!phone) {\n setPhoneError(true);\n isError = true;\n }\n\n if (!proficiency) {\n setProficiencyError(true);\n isError = true;\n }\n\n if (!address) {\n setAddressError(true);\n isError = true;\n }\n\n if (!city) {\n setCityError(true);\n isError = true;\n }\n\n if (!isError) {\n navigate(\"/experienceconfirm\"); // <-- navigate on no error\n }\n };\n\n return (\n <>\n <Box sx={{ display: \"flex\", flexDirection: \"column\", width: \"65%\" }}>\n ...\n <form noValidate autoComplete=\"off\" onSubmit={handleSubmit}>\n ...\n <Box mt={8} sx={{ display: \"flex\", justifyContent: \"space-between\" }}>\n <Box ml={8}>\n <Button variant=\"outlined\" sx={{ borderRadius: \"20px\" }}>\n Back\n </Button>\n </Box>\n <Box mr={18}>\n <Button\n type=\"submit\"\n variant=\"contained\"\n sx={{ borderRadius: \"20px\" }}\n disabled={!(firstName && lastName && phone && proficiency && address && city)}\n >\n <Link\n to=\"/experienceconfirm\"\n onClick={e => e.preventDefault()} // <-- prevent immediate navigation\n >\n Next\n </Link>\n </Button>\n </Box>\n </Box>\n </form>\n </Box>\n </>\n );\n};\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20507963/" ]
74,442,450
<p>I want to overwrite some variables in my playbook file from the inventory file for a host that are defined as &quot;vars_prompt&quot;. If I understand it correctly, Ansible shouldn't prompt for the variables if they were already set before, however, it still prompts for the variables when I try to execute the playbook.</p> <p>How can I overwrite the &quot;vars_prompt&quot; variables from the inventory or is this not possible because of the variable precedence definition of Ansible?</p> <p><strong>Example:</strong><br /> playbook.yml</p> <pre><code>--- - name: Install Gateway hosts: all become: yes vars_prompt: - name: &quot;hostname&quot; prompt: &quot;Hostname&quot; private: no ... </code></pre> <p>inventory.yml</p> <pre><code>--- all: children: gateways: hosts: gateway: ansible_host: 192.168.1.10 ansible_user: user hostname: &quot;gateway-name&quot; ... </code></pre>
[ { "answer_id": 74443563, "author": "Matteo Capuano", "author_id": 20449210, "author_profile": "https://Stackoverflow.com/users/20449210", "pm_score": 0, "selected": false, "text": " vars_prompt:\n - name: \"hostname\"\n prompt: \"Hostname\"\n private: no\n default: \"gateway-name\"\n" }, { "answer_id": 74443603, "author": "Vladimir Botka", "author_id": 6482561, "author_profile": "https://Stackoverflow.com/users/6482561", "pm_score": 3, "selected": true, "text": "--extra-vars" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/843165/" ]
74,442,460
<p>I want the difference between two date columns in the number of days. <br> In pandas dataframe difference in two &quot;datetime64&quot; type columns returns number of days <br> but in pyspark.pandas dataframe the difference is returned in the &quot;int&quot; type.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import pyspark.pandas as ps data = { &quot;d1&quot;: [ &quot;2019-05-18&quot;, &quot;2019-06-21&quot;, &quot;2019-05-08&quot;, &quot;2019-05-22&quot;, &quot;2019-11-20&quot;, &quot;2019-05-29&quot;, ], &quot;d2&quot;: [ &quot;2019-05-21&quot;, &quot;2019-06-21&quot;, &quot;2019-05-09&quot;, &quot;2019-05-23&quot;, &quot;2019-11-21&quot;, &quot;2019-05-30&quot;, ], } df = pd.DataFrame(data) df[[&quot;d1&quot;, &quot;d2&quot;]] = df[[&quot;d1&quot;, &quot;d2&quot;]].astype(&quot;datetime64&quot;) pdf = ps.from_pandas(df) df[&quot;diff&quot;] = (df[&quot;d1&quot;] - df[&quot;d2&quot;]).dt.days pdf[&quot;diff&quot;] = pdf[&quot;d1&quot;] - pdf[&quot;d2&quot;] </code></pre> <p>Pandas difference Output: [-3, 0, -1, -1, -1, -1] <br> PySpark difference Output: [-259200, 0, -86400, -86400, -86400, -86400] <br></p> <p>Expected Op: PySpark difference should return in days format and be accessible using dt.days <br></p> <p>Tried:<br></p> <ol> <li>Converting int column to DateTime</li> </ol> <pre><code>pdf['diff'].astype('datetime64') &gt;&gt;&gt;['1969-12-29 00:00:00', '1970-01-01 00:00:00', '1969-12-31 00:00:00', '1969-12-31 00:00:00', '1969-12-31 00:00:00', '1969-12-31 00:00:00'] </code></pre> <ol start="2"> <li>The current sol that I am working with is</li> </ol> <pre><code>temp = pdf[[&quot;d1&quot;, &quot;d2&quot;]].to_pandas() pdf[&quot;diff2&quot;] = ps.Series((temp[&quot;d1&quot;] - temp[&quot;d2&quot;]).dt.days) &gt;&gt;&gt; [-3, 0, -1, -1, -1, -1] </code></pre> <p>This sol works, but for large datasets converting to pandas and doing operation on the two columns adds overhead and increases the runtime. So any concise way to get difference in two datetime columns in pyspark.pandas dataframe??</p>
[ { "answer_id": 74443563, "author": "Matteo Capuano", "author_id": 20449210, "author_profile": "https://Stackoverflow.com/users/20449210", "pm_score": 0, "selected": false, "text": " vars_prompt:\n - name: \"hostname\"\n prompt: \"Hostname\"\n private: no\n default: \"gateway-name\"\n" }, { "answer_id": 74443603, "author": "Vladimir Botka", "author_id": 6482561, "author_profile": "https://Stackoverflow.com/users/6482561", "pm_score": 3, "selected": true, "text": "--extra-vars" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14055137/" ]
74,442,495
<p>does anyone know if it is possible to use the na.approx function to interpolate depending on a varying timeframe ?</p> <p>Let's suggest we have a df like (the real df has over 5'000 rows):</p> <pre><code>Date, Value 2022-05-01, 6 2022-05-02, 5 2022-05-03, NA 2022-05-06, NA 2022-05-07, 14 2022-05-08, 15 2022-05-09, NA 2022-05-10, 67 </code></pre> <p>I want to conduct an linear interpolation depending on the date range. For example the two NA's at beginning: 1) 14-5 = 9, 2) Counting the days from 2022-05-02 until 2022-05-06 = 5 days, so we divide 3) 9/5 = 1.8. Value for NA at 2022-05-03 is 6.8 and for 2022-05-06 is 8.6.</p> <p>Second example at 2022-05-09: 1) 67-15 = 52, 2) 2022-05-08 until 2022-05-10 = 3 days, 3) 52/3 = 17.33333. Value for NA at 2022-05-09 is 32.33333 (= 15 + 17.33333)</p> <p>Is this possible to conduct it with the na.approx function? If not, how can I approach this?</p>
[ { "answer_id": 74444242, "author": "Jonny Phelps", "author_id": 5990938, "author_profile": "https://Stackoverflow.com/users/5990938", "pm_score": 0, "selected": false, "text": "# get data into required shape, and using data.table package\ndf <- read.table(text=\"\nDate, Value\n2022-05-01, 6\n2022-05-02, 5\n2022-05-03, NA\n2022-05-06, NA\n2022-05-07, 14\n2022-05-08, 15\n2022-05-09, NA\n2022-05-10, 67\n\", header=T)\nlibrary(data.table)\nlibrary(zoo)\nlibrary(lubridate)\ndt <- as.data.table(df)\ndt[, Date := lubridate::ymd(gsub(\",\",\"\",`Date.`))]\nsetorder(dt, Date)\n\n# first step, fill in to get the starting value\ndt[, Value2 := zoo::na.locf0(Value)]\n\n# group together the rows, only really interested in the NA ones, \n# ensuring they are grouped together. rleid makes a group where it finds new values\ndt[, Group := rleid(is.na(Value))]\n# find the value after the NA\ndt[, ValueNext := shift(Value2, n=1, type=\"lead\")]\n# find the dates before and after the NA period\ndt[, DatePre := shift(Date, n=1, type=\"lag\")]\ndt[, DateNext := shift(Date, n=1, type=\"lead\")]\n# find the differences in the values & dates\ndt[, ValueDiff := ValueNext[.N]-Value2[1], by=Group]\ndt[, DateDiff := as.integer(DateNext[.N]-DatePre[1]), by=Group]\n# divide through to get the addition\ndt[, ValueAdd := ValueDiff/DateDiff]\n# by group, use cumulative sum to add to the starting value\ndt[, ValueOut := Value2+cumsum(ValueAdd), by=Group]\n# we only care about NA groups, so revert back to original value for other\n# cases\ndt[!is.na(Value), ValueOut := Value]\n\n# check the NA rows\n# ! only difference is I get 2 as the date diff for 2022-05-09, not 3\ndt[is.na(Value),]\n\n# Final output\ndt[, .(Date, Value, ValueOut)]\n" }, { "answer_id": 74444816, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 3, "selected": true, "text": "DF" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16371833/" ]
74,442,506
<p>in my post requests to OrderProduct model, i want to only have to pass order.id and product.id and it works... untill i add a serializer to retrieve product.name. It might be because i didnt understand documentation about nested requests, but im unable to advance further into my project :(</p> <pre><code>[ { &quot;id&quot;: 2, &quot;order&quot;: 1, &quot;product&quot;: 1, } ] </code></pre> <p>^ here's how it looks without nested serializer, and thats the data that i wanna have to input</p> <pre><code>[ { &quot;id&quot;: 2, &quot;order&quot;: 1, &quot;product&quot;: { &quot;id&quot;: 1, &quot;name&quot;: &quot;gloomhaven&quot;, }, }, </code></pre> <p>^ here's how it looks after i add an additional serializer. I pretty much want these nested fields to be read only, with me still being able to send simple post requests</p> <p>here are my serializers</p> <pre><code>class OrderProductSerializer(serializers.ModelSerializer): product = Product() class Meta: model = OrderProduct fields = [ &quot;id&quot;, &quot;order&quot;, &quot;product&quot;] </code></pre> <pre><code>class Product(serializers.ModelSerializer): class Meta: model = Product fields = ( &quot;id&quot;, &quot;name&quot;) </code></pre> <p>Is there any way for me to accomplish this? Thank you for trying to help!</p>
[ { "answer_id": 74442940, "author": "lord stock", "author_id": 14689289, "author_profile": "https://Stackoverflow.com/users/14689289", "pm_score": 0, "selected": false, "text": "class OrderProductSerializer(serializers.ModelSerializer): \n product = Product(many=True)\n class Meta:\n model = OrderProduct\n fields = [\n \"id\",\n \"order\",\n \"product\"]\n" }, { "answer_id": 74449999, "author": "Harshil shrivastava", "author_id": 12590983, "author_profile": "https://Stackoverflow.com/users/12590983", "pm_score": 2, "selected": true, "text": "def to_representation(self, instance):\n response = super().to_representation(instance)\n response['other_field'] = instance.id# also response['other_field'] = otherSerializer(instance.model) \n return response\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18071522/" ]
74,442,511
<p>Need to update potentiometer values all time not only once, try different ways but nothing works :(</p> <p>I think that main problem is that this function while(digitalRead(gotoPositionAPin)); blocks</p> <p>Now it's read value and save speed</p> <p>workflow of code</p> <p>press button right save position a press button left save position b update pot speed (set speed) update pot acceleration (set accel) press button go to position A (its going with previous set of speed and acceleration) press button go to position B (its going with previous set of speed and acceleration)</p> <pre><code>#include &lt;AccelStepper.h&gt; // Define some steppers and the pins the will use AccelStepper stepper1(1, 12, 11); #define stepsPerRev 1600 #define stepPin 12 #define dirPin 11 #define ledPin 13 #define rotateLeftPin 7 #define rotateRightPin 6 #define savePositionAPin 5 #define savePositionBPin 4 #define gotoPositionAPin 3 #define gotoPositionBPin 2 #define maxSpeedPin 0 #define accelPin 1 // Set this to zero if you don't want debug messages printed #define printDebug 0 // These are the constants that define the speed associated with the MaxSpeed pot #define MAX_STEPS_PER_SECOND 1000 // At 200 s/r and 1/8th microstepping, this will be 333 rev/minute #define MIN_STEPS_PER_SECOND 27 // At 200 steps/rev and 1/8th microstepping, this will be 1 rev/minute // Change this value to scale the acceleration pot's scaling factor #define ACCEL_RATIO 1 int buttonState = 0; int stepNumber = 0; int curSpeed = 100; int dir = 0; int maxSpeed = 0; int accel = 0; long savedPosA = 0; long savedPosB = 0; int loopCtr = 0; float fMaxSpeed = 0.0; float fStepsPerSecond = 0.0; void setup() { pinMode(stepPin, OUTPUT); pinMode(dirPin, OUTPUT); pinMode(ledPin, OUTPUT); pinMode(rotateLeftPin, INPUT); pinMode(rotateRightPin, INPUT); pinMode(savePositionAPin, INPUT); pinMode(savePositionBPin, INPUT); pinMode(gotoPositionAPin, INPUT); pinMode(gotoPositionBPin, INPUT); if (printDebug) { // Initialize the Serial port Serial.begin(9600); } // blink the LED: blink(2); stepper1.setMaxSpeed(800.0); stepper1.setAcceleration(600.0); // Grab both speed and accel before we start maxSpeed = analogRead(maxSpeedPin); // Do the math to scale the 0-1023 value (maxSpeed) to // a range of MIN_STEPS_PER_SECOND to MAX_STEPS_PER_SECOND fMaxSpeed = maxSpeed / 1023.0; fStepsPerSecond = MIN_STEPS_PER_SECOND + (fMaxSpeed * (MAX_STEPS_PER_SECOND - MIN_STEPS_PER_SECOND)); if (fStepsPerSecond &gt; 1000) { fStepsPerSecond = 1000; } accel = analogRead(accelPin)/ACCEL_RATIO; } void loop() { // First, we need to see if either rotate button is down. They always take precidence. if(digitalRead(rotateLeftPin)) { stepper1.setSpeed(-fStepsPerSecond); while(digitalRead(rotateLeftPin)) { CheckPots(); stepper1.runSpeed(); stepper1.setSpeed(-fStepsPerSecond); } } else if (digitalRead(rotateRightPin)) { stepper1.setSpeed(fStepsPerSecond); while(digitalRead(rotateRightPin)) { CheckPots(); stepper1.runSpeed(); stepper1.setSpeed(fStepsPerSecond); } } // Go see if we need to update our analog conversions CheckPots(); // Check to see if user is trying to save position A or B if(digitalRead(savePositionAPin)) { savedPosA = stepper1.currentPosition(); if (printDebug) { Serial.print(&quot;Saved A at :&quot;); Serial.println(savedPosA); } while(digitalRead(savePositionAPin)); } if(digitalRead(savePositionBPin)) { savedPosB = stepper1.currentPosition(); if (printDebug) { Serial.print(&quot;Saved B at :&quot;); Serial.println(savedPosB); } while(digitalRead(savePositionBPin)); } // Check to see if the user wants to go to position A or B if (digitalRead(gotoPositionAPin)) { if (printDebug) { // Yup, let's go to position A Serial.print(&quot;cur pos = &quot;); Serial.println(stepper1.currentPosition()); Serial.print(&quot;Going to A = &quot;); Serial.println(savedPosA); Serial.print(&quot;Speed = &quot;); Serial.println(fStepsPerSecond); Serial.print(&quot;Accel = &quot;); Serial.println(accel); } stepper1.setAcceleration(0); stepper1.runToNewPosition(stepper1.currentPosition()); stepper1.setMaxSpeed(fStepsPerSecond); stepper1.setAcceleration(accel); stepper1.runToNewPosition(savedPosA); if (printDebug) { Serial.print(&quot;new pos = &quot;); Serial.println(stepper1.currentPosition()); } while(digitalRead(gotoPositionAPin)); } else if (digitalRead(gotoPositionBPin)) { // Yup, let's go to position B if (printDebug) { Serial.print(&quot;cur pos = &quot;); Serial.println(stepper1.currentPosition()); Serial.print(&quot;Going to B = &quot;); Serial.println(savedPosB); Serial.print(&quot;Speed = &quot;); Serial.println(fStepsPerSecond); Serial.print(&quot;Accel = &quot;); Serial.println(accel); } stepper1.setAcceleration(0); stepper1.runToNewPosition(stepper1.currentPosition()); stepper1.setMaxSpeed(fStepsPerSecond); stepper1.setAcceleration(accel); stepper1.runToNewPosition(savedPosB); if (printDebug) { Serial.print(&quot;new pos = &quot;); Serial.println(stepper1.currentPosition()); } while(digitalRead(gotoPositionBPin)); } } // Blink the reset LED: void blink(int howManyTimes) { int i; for (i=0; i &lt; howManyTimes; i++) { digitalWrite(ledPin, HIGH); delay(200); digitalWrite(ledPin, LOW); delay(200); } } void CheckPots(void) { loopCtr++; // Only read these once in a while because they take a LONG time if (loopCtr == 100) { maxSpeed = analogRead(maxSpeedPin); // Do the math to scale the 0-1023 value (maxSpeed) to // a range of MIN_STEPS_PER_SECOND to MAX_STEPS_PER_SECOND fMaxSpeed = maxSpeed / 1023.0; fStepsPerSecond = MIN_STEPS_PER_SECOND + (fMaxSpeed * (MAX_STEPS_PER_SECOND - MIN_STEPS_PER_SECOND)); if (fStepsPerSecond &gt; 1000) { fStepsPerSecond = 1000; } } // Read in the acceleration analog value // This needs to be scaled too, but to what? if (loopCtr &gt;= 200) { accel = analogRead(accelPin)/ACCEL_RATIO; loopCtr = 0; } } </code></pre>
[ { "answer_id": 74460858, "author": "mmixLinus", "author_id": 2115408, "author_profile": "https://Stackoverflow.com/users/2115408", "pm_score": 0, "selected": false, "text": "while(digitalRead(savePositionAPin));" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13914743/" ]
74,442,516
<p>I have an element in my Web Page <code>&lt;div class=&quot;col-md-12&quot;&gt;&lt;/div&gt;</code>. Currently it is maintaining width of parent element. But if I apply <code>position: fixed;</code> on <code>&lt;div class=&quot;col-md-12&quot;&gt;&lt;/div&gt;</code> it's width increases.</p> <p>How to keep previous width with <code>position: fixed;</code> ?</p>
[ { "answer_id": 74443072, "author": "c.m.", "author_id": 19850943, "author_profile": "https://Stackoverflow.com/users/19850943", "pm_score": 2, "selected": false, "text": "width: inherit;\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5043301/" ]
74,442,519
<p>I have to make a mass histogram of animals with a dataframe on pandas. The goal is that on my x-axis, I have the different masses of my CSV file, and on my y-axis, I have the number of animals that have that mass. I am a beginner in this field and I need to make a simple and understandable code</p> <p>Here is my current code :</p> <p>`</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns df = pd.read_csv(&quot;S:\Annee1\ISD\TP3\PanTHERIA_1-0_WR05_Aug2008.txt&quot;, sep='\t') ax = (df .loc[:, ['5-1_AdultBodyMass_g', 'MSW05_Binomial']] .groupby('MSW05_Binomial') .count('MSW05_Binomial') .plot.bar(rot=45, figsize=(16, 8)) ) ax.set_title('Masses corporelles de tous les animaux', fontsize=14) ax.set_xlabel('Animaux', fontsize=12) ax.set_ylabel('Masse corporelle', fontsize=12) </code></pre> <p>`</p> <p><a href="https://i.stack.imgur.com/BKtgY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BKtgY.png" alt="CSV File" /></a></p> <p>Thanks a lot</p> <p>PS: If you have any questions about my project, don't hesitate</p>
[ { "answer_id": 74444367, "author": "Clement Piat", "author_id": 16016505, "author_profile": "https://Stackoverflow.com/users/16016505", "pm_score": 3, "selected": true, "text": "pandas.DataFrame.hist" }, { "answer_id": 74445339, "author": "Marble_gold", "author_id": 15423701, "author_profile": "https://Stackoverflow.com/users/15423701", "pm_score": 0, "selected": false, "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# select the data\nmass = df[\"5-1_AdultBodyMass_g\"]\n\n# make bins\n# for instance:\nbins = [500, 1000, 1500, 2000, 2500, 3000]\n\n# or \n\nbins = np.arange(0,100000,10000)\n\n# make a plot\nplt.hist(mass,bins=bins)\nplt.title(\"Masses corporelles de tous les animaux\")\nplt.xlabel(\"Masses d'animaux\")\nplt.ylabel(\"Compter\")\nplt.show();\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20341363/" ]
74,442,528
<p>I have this xml:</p> <pre><code>&lt;NewDataSet xmlns=&quot;http://anonymous_link_here&quot;&gt; &lt;Table&gt; &lt;Name&gt;Example&lt;/Name&gt; &lt;/Table&gt; &lt;Table&gt; &lt;Name&gt;Example&lt;/Name&gt; &lt;/Table&gt; &lt;Table&gt; &lt;Name&gt;Example&lt;/Name&gt; &lt;/Table&gt; &lt;Table&gt; &lt;Name&gt;Example&lt;/Name&gt; &lt;/Table&gt; &lt;/NewDataSet&gt; </code></pre> <p>I'm trying to parse this xml to a <code>List&lt;myClass&gt;</code>:</p> <pre><code> public static List&lt;myClass&gt; ConvertToList(string xml) { var objects= XDocument.Parse(xml); var objectsList= (from o in objects.Root.Elements() select new myClass() { Name = (string)o.Element(&quot;Name&quot;), }).ToList(); return objectsList; } </code></pre> <p>myClass class:</p> <pre><code>[Serializable] [XmlRoot(&quot;Table&quot;), Namespace=&quot;http://anonymous_link_here&quot;] public class myClass{ [XmlElement(ElementName=&quot;Name&quot;), Namespace=&quot;http://anonymous_link_here&quot;] public string Name { get; set; } } </code></pre> <p>I don't know why I get the right count of elements in the <code>objectsList</code>, but the <code>Name</code> properties are null. I think there is something wrong with: <code>Name = (string)o.Element(&quot;Name&quot;)</code>. Any help would be appreciated.</p>
[ { "answer_id": 74443260, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": "public static List<myClass> ConvertToList(string xml)\n{\n var objects = XDocument.Parse(xml);\n var objectsList = (from o in objects.Root.Elements()\n select new myClass()\n {\n Name = o.Value,\n }).ToList();\n return objectsList;\n }\n" }, { "answer_id": 74443766, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": true, "text": "o.Element(\"Name\")" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19342899/" ]
74,442,555
<p>How can I do the deletion of the entities that I just persisted?</p> <pre><code>@Bean public Job job() { return this.jobBuilderFactory.get(&quot;job&quot;) .start(this.syncStep()) .build(); } @Bean public Step syncStep() { // read RepositoryItemReader&lt;Element1&gt; reader = new RepositoryItemReader&lt;&gt;(); reader.setRepository(repository); reader.setMethodName(&quot;findElements&quot;); reader.setArguments(new ArrayList&lt;&gt;(Arrays.asList(ZonedDateTime.now()))); final HashMap&lt;String, Sort.Direction&gt; sorts = new HashMap&lt;&gt;(); sorts.put(&quot;uid&quot;, Sort.Direction.ASC); reader.setSort(sorts); // write RepositoryItemWriter&lt;Element1&gt; writer = new RepositoryItemWriter&lt;&gt;(); writer.setRepository(otherrepository); writer.setMethodName(&quot;save&quot;); return stepBuilderFactory.get(&quot;syncStep&quot;) .&lt;Element1, Element2&gt; chunk(10) .reader(reader) .processor(processor) .writer(writer) .build(); } </code></pre> <p>It is a process of dumping elements. We pass the elements from one table to another.</p>
[ { "answer_id": 74442789, "author": "g00glen00b", "author_id": 1915448, "author_profile": "https://Stackoverflow.com/users/1915448", "pm_score": 0, "selected": false, "text": "CompositeItemWriter" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19939028/" ]
74,442,570
<p>I have an array of objects which I pull in via an Axios request called 'uniquecolors'. It looks like this:</p> <pre><code> mycolors color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color: [GREEN, RED, BLUE ] color: [YELLOW, ORANGE] color: [GREEN, GREEN,GREEN,RED] color: [ORANGE,GREEN,ORANGE,GREEN,RED]` </code></pre> <ol> <li><p>I would like to remove all colors apart from 'RED' and 'GREEN' for each object</p> </li> <li><p>I would like to replace 'RED' with 'Crimson'</p> </li> <li><p>I would like to replace 'GREEN' with 'Sage'</p> <pre><code>`methods: .... const uniquecolorscationwithduplicates = uniquecolors .toString() .replace(&quot;RED&quot;, &quot;Crimson&quot;) .replace(&quot;GREEN&quot;, &quot;Sage&quot;) .replace(&quot;YELLOW,&quot;, &quot;&quot;) .split(&quot;|&quot;);`` </code></pre> </li> </ol> <p>This actually keeps all the colors but adds on Crimson and Sage. So it displays 'GREEN,Sage,RED,Crimson,BLUE, YELLOW, ORANGE' instead of replacing.</p> <p>Why would that be?</p> <p>To remove I have been replacing with a blank string. I know this is a bad way to code it but Im not sure how else to do this.</p> <p>Ideally I'd like to change all instances of the colors when the page renders so any pointers would be helpful.</p> <p>Thanks in advance</p>
[ { "answer_id": 74446510, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 1, "selected": true, "text": "Array.map()" }, { "answer_id": 74447869, "author": "Build For Dev", "author_id": 20477335, "author_profile": "https://Stackoverflow.com/users/20477335", "pm_score": 1, "selected": false, "text": "const mycolors = [\n {color: ['GREEN', 'RED', 'BLUE', 'YELLOW', 'ORANGE', 'ORANGE', 'GREEN']},\n {color: ['GREEN', 'RED', 'BLUE', 'YELLOW', 'ORANGE', 'ORANGE', 'GREEN']},\n {color: ['GREEN', 'RED', 'BLUE']},\n {color: ['YELLOW', 'ORANGE']},\n {color: ['GREEN', 'GREEN', 'GREEN', 'RED']},\n {color: ['ORANGE', 'GREEN', 'ORANGE', 'GREEN', 'RED']}\n];\n\nconst colored = mycolors.map(({color}) => {\n let filtered = color.filter(col => col === 'RED' || col === 'GREEN')\n .map(el => {\n return el === 'RED' ? 'Crimson' : 'Sage';\n });\n return {color: filtered};\n});\n\nconsole.log(colored)\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20340686/" ]
74,442,594
<p>in an arry of objects i want to remove object which have same id (duplicated data) using javascript.</p> <p>below is the input array</p> <pre><code>const input = [ { id: '1', name: 'first', }, { id: '1', name: 'first', }, { id: '2', name: 'second', }, { id: '2', name: 'second', }, ] </code></pre> <p>so as you see from above array there are duplicating data with id '1' and '2'. if there is similar id i want include only one</p> <p>so the expected output is like below,</p> <pre><code>const output = [ { id: '1', name: 'first', }, { id: '2', name: 'second', }, ] </code></pre> <p>how can i do this. could someone help me with this. i am new to programming thanks.</p>
[ { "answer_id": 74442645, "author": "Gaurav Punjabi", "author_id": 11592137, "author_profile": "https://Stackoverflow.com/users/11592137", "pm_score": 0, "selected": false, "text": "const" }, { "answer_id": 74442647, "author": "Yves Kipondo", "author_id": 6108283, "author_profile": "https://Stackoverflow.com/users/6108283", "pm_score": 1, "selected": true, "text": "const input = [\n {\n id: '1',\n name: 'first',\n },\n { \n id: '1',\n name: 'first',\n },\n { \n id: '2',\n name: 'second',\n },\n {\n id: '2',\n name: 'second',\n }, \n]\n\nconst result = input.reduce((accumulator, current) => {\n let exists = accumulator.find(item => {\n return item.id === current.id;\n });\n if(!exists) { \n accumulator = accumulator.concat(current);\n }\n return accumulator;\n}, []);\n\nconsole.log(result);" }, { "answer_id": 74442691, "author": "R4ncid", "author_id": 14326899, "author_profile": "https://Stackoverflow.com/users/14326899", "pm_score": -1, "selected": false, "text": "Set" }, { "answer_id": 74442810, "author": "Amaarockz", "author_id": 11281152, "author_profile": "https://Stackoverflow.com/users/11281152", "pm_score": -1, "selected": false, "text": "const input = [\n{\n id: '1',\n name: 'first',\n},\n{ \n id: '1',\n name: 'first',\n},\n{ \n id: '2',\n name: 'second',\n},\n{\n id: '2',\n name: 'second',\n}, \n];\nconst uniqueIds = new Set();\nconst uniqueList = input.filter(element => {\nconst isDuplicate = uniqueIds.has(element.id);\n uniqueIds.add(element.id);\n return !isDuplicate;\n});\nconsole.log(uniqueList);" }, { "answer_id": 74573775, "author": "Bobnini", "author_id": 15496710, "author_profile": "https://Stackoverflow.com/users/15496710", "pm_score": 0, "selected": false, "text": "let id = \"601985b485d9281d64056953\"\n let contacts = [{\n ...,\n parent: \"601985b485d9281d64056953\",\n ...,\n },\n {\n ...,\n parent: \"601985b485d9281d64065128\",\n ...,\n }\n ]\n function findAndRemoveObjectFromArray(array, internalProperty, externalProperty, convertType = \"string\", returnObject = false) {\n let objIndex = -1\n if (convertType === \"string\") objIndex = array.findIndex((obj) => String(obj[`${internalProperty}`]) === String(externalProperty));\n if (convertType === \"number\") objIndex = array.findIndex((obj) => Number(obj[`${internalProperty}`]) === Number(externalProperty));\n\n if (objIndex > -1) {\n const object = array.splice(objIndex, 1);\n if (returnObject) return object.shift()\n return object\n }\n return [];\n }\n let currentContact = findAndRemoveObjectFromArray(contacts, \"parent\", id, 'string', true)\n// Results:{..., parent: \"601985b485d9281d64056953\",...}\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,442,604
<p><strong>My Problem</strong> I want search record page</p> <p><strong>i want funtion</strong></p> <p>I made a search bar with TextField,</p> <p>I hope the ontap function in the TextField works as well as the launcher TextButton.</p> <p><strong>Code</strong></p> <pre><code>TextField( onTap: () {}, decoration: InputDecoration( hintText: &quot;Please Input Data&quot;, hintStyle: TextStyle( fontFamily: 'Source Han Sans KR', fontSize: 14, color: const Color(0xffbcbcbc), letterSpacing: -0.35000000000000003, fontWeight: FontWeight.w300, ), border: InputBorder.none, prefixIcon: Icon(Icons.search)), ), TextButton( onPressed: () { }, child: Text( 'Activate', style: TextStyle( fontFamily: 'Source Han Sans KR', fontSize: 16, color: const Color(0xff191919), letterSpacing: -0.4, ), softWrap: false, )) </code></pre>
[ { "answer_id": 74442644, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "CupertinoSearchTextField()" }, { "answer_id": 74442752, "author": "K K Muhammed Fazil", "author_id": 11922179, "author_profile": "https://Stackoverflow.com/users/11922179", "pm_score": 2, "selected": true, "text": "class MyHomePage extends StatefulWidget {\n const MyHomePage({Key? key}) : super(key: key);\n\n @override\n State<MyHomePage> createState() => _MyHomePageState();\n}\n\nclass _MyHomePageState extends State<MyHomePage> {\n final textController = TextEditingController();\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: Row(\n children: [\n Expanded(\n child: TextField(\n onChanged: (value) {\n setState(() {});\n },\n controller: textController,\n decoration: InputDecoration(\n hintText: \"Please Input Data\",\n hintStyle: TextStyle(\n fontFamily: 'Source Han Sans KR',\n fontSize: 14,\n color: Color(0xffbcbcbc),\n letterSpacing: -0.35000000000000003,\n fontWeight: FontWeight.w300,\n ),\n border: InputBorder.none,\n prefixIcon: Icon(Icons.search)),\n ),\n ),\n TextButton(\n onPressed: textController.text.isEmpty\n ? null\n : () {\n // your code here\n },\n child: Text(\n 'Activate',\n style: TextStyle(\n fontFamily: 'Source Han Sans KR',\n fontSize: 16,\n color: textController.text.isEmpty ? Colors.grey : Color(0xff191919),\n letterSpacing: -0.4,\n ),\n softWrap: false,\n ),\n ),\n ],\n ),\n ),\n );\n }\n}\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18790182/" ]
74,442,642
<p>I want to do something like this:</p> <p><a href="https://i.stack.imgur.com/ArFw5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ArFw5.png" alt="enter image description here" /></a></p> <p>I want a <code>border-radius</code>, <code>transparency</code> (to see the background), and the possibility to fill from 0% to 100% the <code>border</code>.</p> <p>For the moment, I have this code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body{ background: lightgrey; } .avatar{ padding: 10px; display: inline-block; position: relative; z-index: 0; } .avatar:before{ width: 180px; aspect-ratio: 1; content: ""; position: absolute; z-index: -1; inset: 0; padding: 8px; border-radius: 100%; background: linear-gradient(to top, transparent 25%, blue 25%, blue); -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); -webkit-mask-composite: clear; mask-composite: clear; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;body&gt; &lt;div class="avatar"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>How is it possible to fill X% of the border?</p> <p>Thank you!</p>
[ { "answer_id": 74443023, "author": "MAYUR SANCHETI", "author_id": 12238257, "author_profile": "https://Stackoverflow.com/users/12238257", "pm_score": 0, "selected": false, "text": " body{\n background: lightgrey;\n }\n \n .avatar{\n padding: 10px;\n display: inline-block;\n position: relative;\n z-index: 0;\n }\n \n .avatar:before{\n width: 180px;\n aspect-ratio: 1;\n content: \"\";\n position: absolute;\n z-index: -1;\n inset: 0;\n padding: 8px;\n border-radius: 100%;\n background: linear-gradient(to top, transparent 25%, blue 25%, blue);\n -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);\n mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);\n -webkit-mask-composite: clear;\n mask-composite: clear;\n }\n .mainside{\n \n display: inline-block;\n position: relative;\n z-index: 0;\n }\n \n .mainside:before{\n width: 180px;\n aspect-ratio: 1;\n content: \"\";\n position: absolute;\n z-index: 9;\n inset: 0;\n padding: 8px;\n border-radius: 100%;\n background: linear-gradient(to right, transparent 90%, #878789 25%, #adadad);\n -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);\n mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);\n -webkit-mask-composite: clear;\n mask-composite: clear;\n }" }, { "answer_id": 74443050, "author": "Coolis", "author_id": 9399014, "author_profile": "https://Stackoverflow.com/users/9399014", "pm_score": 1, "selected": false, "text": "div {\n display: flex;\n width: 100px;\n height: 100px;\n border-radius: 50%;\n background: conic-gradient(red var(--progress), gray 0deg);\n font-size: 0;\n}\n\ndiv::after {\n content: attr(data-progress) '%';\n display: flex;\n justify-content: center;\n flex-direction: column;\n width: 100%;\n margin: 10px;\n border-radius: 50%;\n background: white;\n font-size: 1rem;\n text-align: center;\n}" }, { "answer_id": 74448461, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 2, "selected": true, "text": ".box {\n width: 100px;\n aspect-ratio: 1;\n display:inline-block;\n border-radius :50%;\n padding: 10px;\n background: conic-gradient(from -136deg, blue calc(var(--p)*.76),#f3f3f3 0);\n -webkit-mask:\n linear-gradient(#fff 0 0) content-box,\n linear-gradient(#fff 0 0);\n -webkit-mask-composite:destination-out;\n mask-composite:exclude;\n clip-path:polygon(0 0,100% 0,100% 100%, 50% 50%,0 100%);\n}\n\nbody {\n background:linear-gradient(to right,red,yellow);\n}" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4671933/" ]
74,442,667
<p>I need to call a function when a tab is pressed in the tabbar, but the tab does not reac anymore, even with an Inkwell. I also wrapped the position an the tab widget itself in an Gesturedetector or an inkwell, what iam doing wrong?</p> <pre><code>TabBar( indicatorColor: Colors.white, tabs: [ GestureDetector(//That does not work even with an InWell onTap: ()async{ await _dbLogin.function(); }, child: Stack( children: [ Positioned( left: 40, child: const Tab(icon: Icon(Icons.person_outline,color: Colors.lightGreen,size: 30,)) ), currentUser?.priceAlert==true? Positioned( bottom: 20, left: 40, child: const CircleAvatar( radius: 4.0, backgroundColor: Colors.red, ), ):Container() ], ), ), Stack( children: [ Positioned( left: 40, child: const Tab(icon: Icon(Icons.people_alt_outlined,color: Colors.lightGreen,size: 30,)), ), currentUser?.productAlert==true?Positioned( bottom: 20, left: 40, child: const CircleAvatar( radius: 4.0, backgroundColor: Colors.red, ), ):Container() ], ), Stack( children: [ Positioned( left: 40, child: Tab(icon: currentUser?.profilVerified==true?const Icon(Icons.account_circle_outlined,color:Colors.lightGreen,size: 30,):const Icon(Icons.account_circle_outlined,color:Colors.red,size: 30,)) ) ], ) ], ), </code></pre> <p>Any ideas? Thank you</p>
[ { "answer_id": 74442727, "author": "Ivo", "author_id": 1514861, "author_profile": "https://Stackoverflow.com/users/1514861", "pm_score": 2, "selected": false, "text": "TabBar" }, { "answer_id": 74442770, "author": "manhtuan21", "author_id": 8921450, "author_profile": "https://Stackoverflow.com/users/8921450", "pm_score": 1, "selected": false, "text": "TabBar(\n indicatorColor: Colors.white,\n onTap: (index) async {\n if (index == 0) {\n await _dbLogin.function();\n }\n },\n tabs: [\n Stack(\n children: [\n Positioned(\n left: 40,\n child: const Tab(\n icon: Icon(\n Icons.person_outline,\n color: Colors.lightGreen,\n size: 30,\n ))),\n currentUser?.priceAlert == true\n ? Positioned(\n bottom: 20,\n left: 40,\n child: const CircleAvatar(\n radius: 4.0,\n backgroundColor: Colors.red,\n ),\n )\n : Container()\n ],\n ),\n Stack(\n children: [\n Positioned(\n left: 40,\n child: const Tab(\n icon: Icon(\n Icons.people_alt_outlined,\n color: Colors.lightGreen,\n size: 30,\n )),\n ),\n currentUser?.productAlert == true\n ? Positioned(\n bottom: 20,\n left: 40,\n child: const CircleAvatar(\n radius: 4.0,\n backgroundColor: Colors.red,\n ),\n )\n : Container()\n ],\n ),\n Stack(\n children: [\n Positioned(\n left: 40,\n child: Tab(\n icon: currentUser?.profilVerified == true\n ? const Icon(\n Icons.account_circle_outlined,\n color: Colors.lightGreen,\n size: 30,\n )\n : const Icon(\n Icons.account_circle_outlined,\n color: Colors.red,\n size: 30,\n )))\n ],\n )\n ],\n )\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19767292/" ]
74,442,672
<p>When starting a neo4j server (version: 5.1.0) from the CLI, how to specify a <code>neo4j.conf</code> file, instead of having neo4j looking for configuration files in the default locations? (<a href="https://neo4j.com/docs/operations-manual/current/configuration/file-locations/#table-file-locations" rel="nofollow noreferrer">Default file locations</a>).</p> <p><code>neo4j start [relative_path]/neo4j.conf</code> resulted in: <code>Unmatched argument at index 1: '../../../config/neo4j.conf'</code>, while the expectation is that the specific neo4j.conf file is used.</p>
[ { "answer_id": 74443845, "author": "Christophe Willemsen", "author_id": 2662355, "author_profile": "https://Stackoverflow.com/users/2662355", "pm_score": 2, "selected": true, "text": "--help" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14062576/" ]
74,442,708
<p>In a given dataframe: <a href="https://i.stack.imgur.com/mKqT7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mKqT7.png" alt="enter image description here" /></a></p> <p>I would like to filter those columns where values are 0 for index <code>std</code>.</p>
[ { "answer_id": 74442723, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "DataFrame.loc" }, { "answer_id": 74442743, "author": "JohnyCapo", "author_id": 19335841, "author_profile": "https://Stackoverflow.com/users/19335841", "pm_score": -1, "selected": false, "text": "std" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17277677/" ]
74,442,713
<p>Problem: I want to use a subset of a VBA array using variables to steer the subset</p> <p>My test program is</p> <pre><code>Sub test2() Dim MyArray() As Double Dim c As Double Dim d As Double ReDim MyArray(5, 2) c = 3 d = 5 MyArray(0, 0) = 1 MyArray(1, 0) = 2 MyArray(2, 0) = 3 MyArray(3, 0) = 4 MyArray(4, 0) = 5 MyArray(0, 1) = 10 MyArray(1, 1) = 20 MyArray(2, 1) = 30 MyArray(3, 1) = 40 MyArray(4, 1) = 50 a = Application.Average(Application.Index(MyArray, [ROW(3:5)], 2)) b = Application.Average(Application.Index(MyArray, [ROW(c:d)], 2)) End Sub </code></pre> <p>I want to calc the average of cells 3-5 in row two. For the variable a the result is correct. Since I want to have the boundaries of the array defiend dynamically with two variables (c=3 and d=5) I tried to simply replace them. The result for variable b is &quot;Error 2023&quot; .</p> <p>How can this be solved?</p> <p>I already tried to use &quot;&quot; like (ROW(&quot;c&quot;:&quot;d&quot;) or Row(&quot;c:d&quot;). Result: only the Error type changes</p>
[ { "answer_id": 74443654, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 1, "selected": false, "text": "b = Application.Average(MyArray(c - 1, 1), MyArray(d - 1, 1))\n" }, { "answer_id": 74444084, "author": "T.M.", "author_id": 6460297, "author_profile": "https://Stackoverflow.com/users/6460297", "pm_score": 1, "selected": false, "text": "Evaluate" }, { "answer_id": 74445895, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 0, "selected": false, "text": "Sub test3()\nDim MyArray() As Double\nDim a As Integer, b As Double, c As Integer, d As Integer\nc = 3: d = 5\nReDim MyArray(5, 2)\nMyArray(1, 1) = 1\nMyArray(2, 1) = 2\nMyArray(3, 1) = 3\nMyArray(4, 1) = 4\nMyArray(5, 1) = 5\nMyArray(1, 2) = 10\nMyArray(2, 2) = 20\nMyArray(3, 2) = 20\nMyArray(4, 2) = 40\nMyArray(5, 2) = 50\nSum = 0: a = c\nDo Until a > d\nSum = Sum + Application.Sum(MyArray(a, 2))\na = a + 1\nLoop\nMsgBox \"Average = \" & Round(Sum / (d - c + 1), 2)\nEnd Sub\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508123/" ]
74,442,756
<p>I have a .txt file that says &quot;NAMES,&quot; &quot;POINTS&quot; and &quot;SUMMARY&quot; in capital letters, each followed by lines containing data. Each of these three groups is separated by an empty line:</p> <pre><code>NAMES John Cena Sam Smith Selena Gomez POINTS sixteen forty thirty SUMMARY eighth place sixth place first place </code></pre> <p>My goal is to create three separate sets of names, points and summary.</p> <p>I already created a set of names using the following code (which outputs a set of all names as intended):</p> <pre><code>names = set() for line in open('handout_example.txt'): line = line.strip() if not line: break names.add(line) names.remove('NAMES') print(names) #this outputs a set of all names </code></pre> <p>However, I am unsure on how to create a set of points and a set of summary given they're after an empty line and not at the start of the code unlike names. Any help would be greatly appreciated!! Thank you in advance &lt;3</p>
[ { "answer_id": 74443654, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 1, "selected": false, "text": "b = Application.Average(MyArray(c - 1, 1), MyArray(d - 1, 1))\n" }, { "answer_id": 74444084, "author": "T.M.", "author_id": 6460297, "author_profile": "https://Stackoverflow.com/users/6460297", "pm_score": 1, "selected": false, "text": "Evaluate" }, { "answer_id": 74445895, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 0, "selected": false, "text": "Sub test3()\nDim MyArray() As Double\nDim a As Integer, b As Double, c As Integer, d As Integer\nc = 3: d = 5\nReDim MyArray(5, 2)\nMyArray(1, 1) = 1\nMyArray(2, 1) = 2\nMyArray(3, 1) = 3\nMyArray(4, 1) = 4\nMyArray(5, 1) = 5\nMyArray(1, 2) = 10\nMyArray(2, 2) = 20\nMyArray(3, 2) = 20\nMyArray(4, 2) = 40\nMyArray(5, 2) = 50\nSum = 0: a = c\nDo Until a > d\nSum = Sum + Application.Sum(MyArray(a, 2))\na = a + 1\nLoop\nMsgBox \"Average = \" & Round(Sum / (d - c + 1), 2)\nEnd Sub\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508265/" ]
74,442,765
<p>My code:</p> <pre><code>V_max=15 H=1 n=1 C=c(0,0.01,0.1,1) fun &lt;- function( C, H, n ){ 2 / (3 + (C / H)^n) } for(i in 1:length(C)){ V_C &lt;- V_max*fun(C[i],H,n) x3 &lt;- rnorm(1000,V_C,1) } </code></pre> <p>I want my loop to iterate over all the values of vector C and calculate the means for each iteration successively and that the means are save as one data.frame. Since these are my beginnings in R, I am asking for help</p>
[ { "answer_id": 74443654, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 1, "selected": false, "text": "b = Application.Average(MyArray(c - 1, 1), MyArray(d - 1, 1))\n" }, { "answer_id": 74444084, "author": "T.M.", "author_id": 6460297, "author_profile": "https://Stackoverflow.com/users/6460297", "pm_score": 1, "selected": false, "text": "Evaluate" }, { "answer_id": 74445895, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 0, "selected": false, "text": "Sub test3()\nDim MyArray() As Double\nDim a As Integer, b As Double, c As Integer, d As Integer\nc = 3: d = 5\nReDim MyArray(5, 2)\nMyArray(1, 1) = 1\nMyArray(2, 1) = 2\nMyArray(3, 1) = 3\nMyArray(4, 1) = 4\nMyArray(5, 1) = 5\nMyArray(1, 2) = 10\nMyArray(2, 2) = 20\nMyArray(3, 2) = 20\nMyArray(4, 2) = 40\nMyArray(5, 2) = 50\nSum = 0: a = c\nDo Until a > d\nSum = Sum + Application.Sum(MyArray(a, 2))\na = a + 1\nLoop\nMsgBox \"Average = \" & Round(Sum / (d - c + 1), 2)\nEnd Sub\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508112/" ]
74,442,793
<p>I have a file that is stored with the following organizational format:</p> <pre><code>Dictionary List Object Attribute </code></pre> <p>Specifically looking like this:</p> <pre><code>dict = { '0': [TestObject(),TestObject(),TestObject(),TestObject(),TestObject()] '1': [TestObject(),TestObject(),TestObject(),TestObject(),TestObject()] '2': [TestObject(),TestObject(),TestObject(),TestObject(),TestObject()] '3': [TestObject(),TestObject(),TestObject(),TestObject(),TestObject()] } </code></pre> <p>With the TestObject object being defined as:</p> <pre><code>import random class TestObject: def __init__(self): self.id = random.randint() self.date = random.randint() self.size = random.randint() </code></pre> <p>The attributes in this example do not really matter and are just placeholders. What I am concerned with is converting this data format to be a dataframe. Specifically, I want to organize the data to resemble the following format:</p> <pre><code>|key| object | id | date | size | |-- | ------ | ---- | ---- | ---- | | 0 |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | 1 |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | 2 |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | 3 |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | | |TestObject| rand | rand | rand | </code></pre> <p>I found this method for converting a dictionary of lists to a dataframe:</p> <pre><code>pandas.DataFrame.from_dict(dictionary) </code></pre> <p>but in this case I am interested in extracting attributes from objects which are stored in the lists.</p>
[ { "answer_id": 74443654, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 1, "selected": false, "text": "b = Application.Average(MyArray(c - 1, 1), MyArray(d - 1, 1))\n" }, { "answer_id": 74444084, "author": "T.M.", "author_id": 6460297, "author_profile": "https://Stackoverflow.com/users/6460297", "pm_score": 1, "selected": false, "text": "Evaluate" }, { "answer_id": 74445895, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 0, "selected": false, "text": "Sub test3()\nDim MyArray() As Double\nDim a As Integer, b As Double, c As Integer, d As Integer\nc = 3: d = 5\nReDim MyArray(5, 2)\nMyArray(1, 1) = 1\nMyArray(2, 1) = 2\nMyArray(3, 1) = 3\nMyArray(4, 1) = 4\nMyArray(5, 1) = 5\nMyArray(1, 2) = 10\nMyArray(2, 2) = 20\nMyArray(3, 2) = 20\nMyArray(4, 2) = 40\nMyArray(5, 2) = 50\nSum = 0: a = c\nDo Until a > d\nSum = Sum + Application.Sum(MyArray(a, 2))\na = a + 1\nLoop\nMsgBox \"Average = \" & Round(Sum / (d - c + 1), 2)\nEnd Sub\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19678327/" ]
74,442,800
<p>I have recently switched from Visual Studio 2019 to 2022 and am working on a C# project that uses tab and indent size 3. I used <a href="https://i.stack.imgur.com/nfeLx.png" rel="nofollow noreferrer">the same tabs settings for both</a>.</p> <p>For some reason I can't figure out however, VS 2022 breaks indentation below any block of code that has been pasted or auto-completed. It looks like it is attempting to reformat with a size 4 indentation but I could be wrong on that (see here <a href="https://i.stack.imgur.com/Ueg17.png" rel="nofollow noreferrer">before</a> and <a href="https://i.stack.imgur.com/Oy1zL.png" rel="nofollow noreferrer">after</a> auto-complete).</p> <p>I have not used an <code>.editorconfig</code> file and could not find one anywhere in the folder structure. I have also tried disabling all my extensions and resetting my settings to no avail. Does anyone have an idea what might be the cause here?</p> <p><strong>EDIT</strong></p> <p>Since then I have tried the suggestions of <a href="https://stackoverflow.com/users/19849709/lei-zhang-msft">Lei Zhang-MSFT</a> but playing with the 'format on paste' and 'adaptive formatting' parameters did not change anything and creating an <code>.editorconfig</code> file from the 'Add item' menu doesn't seem to do anything (it didn't show an error but did not create the file). I have also attempted a repair and a full reinstall but that didn't change anything so it seems likely that this is somehow related to the project itself.</p> <p><strong>SOLUTION</strong></p> <p>I can now confirm that it was indeed a bug as <a href="https://stackoverflow.com/users/16764901/jiale-xue-msft">Jiale Xue - MSFT</a> suggested. Updating to VS2022 17.4.2 solved the issue.</p>
[ { "answer_id": 74443654, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 1, "selected": false, "text": "b = Application.Average(MyArray(c - 1, 1), MyArray(d - 1, 1))\n" }, { "answer_id": 74444084, "author": "T.M.", "author_id": 6460297, "author_profile": "https://Stackoverflow.com/users/6460297", "pm_score": 1, "selected": false, "text": "Evaluate" }, { "answer_id": 74445895, "author": "alpha", "author_id": 20508861, "author_profile": "https://Stackoverflow.com/users/20508861", "pm_score": 0, "selected": false, "text": "Sub test3()\nDim MyArray() As Double\nDim a As Integer, b As Double, c As Integer, d As Integer\nc = 3: d = 5\nReDim MyArray(5, 2)\nMyArray(1, 1) = 1\nMyArray(2, 1) = 2\nMyArray(3, 1) = 3\nMyArray(4, 1) = 4\nMyArray(5, 1) = 5\nMyArray(1, 2) = 10\nMyArray(2, 2) = 20\nMyArray(3, 2) = 20\nMyArray(4, 2) = 40\nMyArray(5, 2) = 50\nSum = 0: a = c\nDo Until a > d\nSum = Sum + Application.Sum(MyArray(a, 2))\na = a + 1\nLoop\nMsgBox \"Average = \" & Round(Sum / (d - c + 1), 2)\nEnd Sub\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9481715/" ]
74,442,807
<p>I want to compress the video from project directory using ffmpeg in python</p> <p>the video is saved from <code>cv2.VideoCapture(rtsp_url)</code></p> <p>Normally it run without problem in my local machine, but when I dockerize my app it seems docker container can't recognize ffmpeg or I missed something.</p> <pre><code>def compress(name): with open(name) as f: output = name[0:-4] + &quot;-f&quot;+ &quot;.mp4&quot; input = name subprocess.run('ffmpeg -i ' + input + ' -vcodec libx264 ' + output) video = cv2.VideoCapture(rtsp_url) # This is where the video comming from fileName = saveToProjDir(video) # Save the video to project directory and return the name compress(fileName) # Compress the video </code></pre> <p>It throws exception</p> <pre><code> Exception in thread Thread-8 (compress): Traceback (most recent call last): File &quot;/usr/local/lib/python3.11/threading.py&quot;, line 1038, in _bootstrap_inner self.run() File &quot;/usr/local/lib/python3.11/threading.py&quot;, line 975, in run self._target(*self._args, **self._kwargs) File &quot;/app/main.py&quot;, line 59, in compress subprocess.run('ffmpeg -i ' + input + ' -vcodec libx264 ' + output) File &quot;/usr/local/lib/python3.11/subprocess.py&quot;, line 546, in run with Popen(*popenargs, **kwargs) as process: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/usr/local/lib/python3.11/subprocess.py&quot;, line 1022, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File &quot;/usr/local/lib/python3.11/subprocess.py&quot;, line 1899, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg -i cam1_2022-11-15125845.avi -vcodec libx264 cam1_2022-11-15125845-f.mp4' </code></pre> <p>This is how I docker my python app.</p> <pre><code> FROM python:3.11.0 WORKDIR /app/ ENV VIRTUAL_ENV = /env RUN python3 -m venv $VIRTUAL_ENV ENV PATH=&quot;$VIRTUAL_ENV/bin:$PATH&quot; COPY requirements.txt . RUN pip install -r requirements.txt RUN apt-get -y update RUN apt-get install ffmpeg libsm6 libxext6 -y ADD main.py . CMD [&quot;python&quot;,&quot;/app/main.py&quot;] </code></pre>
[ { "answer_id": 74442896, "author": "Abhishek S", "author_id": 9754109, "author_profile": "https://Stackoverflow.com/users/9754109", "pm_score": 1, "selected": false, "text": "main.py" }, { "answer_id": 74442935, "author": "piertoni", "author_id": 1222026, "author_profile": "https://Stackoverflow.com/users/1222026", "pm_score": 1, "selected": true, "text": "docker run -t -i <image-name-or-container-id> /bin/bash\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19139736/" ]
74,442,839
<p>Im creating a simple &quot;debugging&quot; page for visitors for them to be able to check the data they just sent to a url. My wondering was which default php variables are safe to show to visitors? I have tried to my best extent to check the php documentation and looked at the content myself to ensure no sensitive information is exposed, but i still feel like someone with experience might know about some gotcha's that i might have not taking into consideration.</p> <p>My assumptions currently are:</p> <ul> <li><p>$_GET and $_POST and $_REQUEST only holds what the visitors sent us, which would make me believe this is completely safe to show/dump them all the contents of those variables.</p> </li> <li><p>$_COOKIE, this one i think is the cookies set for that visitor, which they anyway have in their browsers and therefore should be safe to show/dump to them</p> </li> <li><p>$_SERVER, not safe to show all content, but should be safe to show them specific headers such as $_SERVER[&quot;HTTP_MY_SPECIFIC_HEADER&quot;]</p> </li> <li><p>$_SESSION, should never be shown to visitors if not something specific such as $_SESSION[&quot;IsLoggedIn&quot;]...</p> </li> </ul> <p>do you think that these assumptions hold up, or am i leaking sensitive information in some cases and opening myself up for vurnerabilites? I think this will help out alot of new php developers to avoid pitfalls in future, by understanding what is allowed to be showed and what should be keept away from displaying to visitors, thanks!</p>
[ { "answer_id": 74443636, "author": "Luke", "author_id": 9034824, "author_profile": "https://Stackoverflow.com/users/9034824", "pm_score": 3, "selected": true, "text": "$_GET" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508192/" ]
74,442,863
<p>I am trying to create an input component that receive and add functions to the specific trigger type. Here is my code. But it doesn't work as my wish. Can Someone help me to achieve this.</p> <p>Main Page</p> <pre><code>import CustomTextInput from &quot;./customTextInput&quot;; const test=()=&gt;{ alert(&quot;test&quot;); } const test1=()=&gt;{ alert(&quot;test1&quot;); } const MainPage=()=&gt;{ return( &lt;CustomTextInput placeholder=&quot;example&quot; events={[ {trigger: &quot;onClick&quot;, action: test}, {trigger: &quot;onKeyUp&quot;, action: test1}, ]} /&gt; ) } </code></pre> <p>Component (customTextInput.js)</p> <pre><code>const CustomTextInput=(props)=&gt;{ &lt;input type=&quot;text&quot; placeholder={props.placeholder} { props.events?.map((event, i)=&gt;{ return( {eval(event.trigger)=event.action} ) }) } /&gt; } export default CustomTextInput; </code></pre> <p>when my code is look like given code, I got this error &quot;Parsing error: Unexpected token, expected '...'&quot;</p> <p>I've tried adding each trigger as each prop, but its very difficult to manage. If I do so, I have to add triggers one by one in my component. So I need to add map to do this</p>
[ { "answer_id": 74443636, "author": "Luke", "author_id": 9034824, "author_profile": "https://Stackoverflow.com/users/9034824", "pm_score": 3, "selected": true, "text": "$_GET" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540454/" ]
74,442,883
<p>I want to format mask 3525,18 Need output: 3.525,18</p> <p>Thank you</p> <p>Need output: 3.525,18</p>
[ { "answer_id": 74443636, "author": "Luke", "author_id": 9034824, "author_profile": "https://Stackoverflow.com/users/9034824", "pm_score": 3, "selected": true, "text": "$_GET" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508342/" ]
74,442,914
<p>I would like a test to expect a Thrown Error in case a class property <code>this.url</code> is not defined.</p> <p>What am I doing wrong here ?</p> <pre class="lang-js prettyprint-override"><code> it('should throw an error if url is not provided by default', async () =&gt; { // Given const Service = require('./services/websocket') // When const Websocket = new Service() // Then expect(Websocket.url).toBeUndefined() expect(Websocket).toThrowError('Websocket URL is not provided') }) </code></pre> <pre class="lang-js prettyprint-override"><code>// services/websocket.js class Websocket { constructor () { this.url = undefined if (!this.url) { throw new TypeError('Websocket URL is not provided') } } } module.exports = Websocket </code></pre> <p>Jest error message:</p> <pre><code> FAIL terminal.test.js Websocket service provider ✕ should throw an error if url is not provided by default (2 ms) ● Websocket service provider › should throw an error if url is not provided by default TypeError: Websocket URL is not provided 4 | 5 | if (!this.url) { &gt; 6 | throw new TypeError('Websocket URL is not provided') | ^ 7 | } 8 | } 9 | } at new Websocket (services/websocket.js:6:13) at Object.&lt;anonymous&gt; (terminal.test.js:7:23) </code></pre>
[ { "answer_id": 74447133, "author": "aspirinemaga", "author_id": 884143, "author_profile": "https://Stackoverflow.com/users/884143", "pm_score": -1, "selected": false, "text": "\n it('should throw an error if url is not provided by default', () => {\n // Given\n const Service = require('./services/websocket')\n\n // When\n let Module\n\n try {\n Module = new Service()\n } catch (error) {\n Module = error\n }\n\n expect(Module).toBeInstanceOf(Error)\n expect(Module.message).toBe('Websocket URL is not defined')\n })\n\n it('should pick up a WS url from env file automatically', () => {\n process.env.WS_URL = 'ws://dummyurl'\n const Service = require('./services/websocket')\n const Module = new Service()\n\n expect(Module.url).toEqual(process.env.WS_URL)\n })\n" }, { "answer_id": 74447199, "author": "Djlewald", "author_id": 7960407, "author_profile": "https://Stackoverflow.com/users/7960407", "pm_score": -1, "selected": false, "text": "it('should throw an error if url is not provided by default', () => {\n const Service = require('./services/websocket')\n expect(new Service()).toThrowError()\n})\n" }, { "answer_id": 74458504, "author": "aspirinemaga", "author_id": 884143, "author_profile": "https://Stackoverflow.com/users/884143", "pm_score": 0, "selected": false, "text": "it('should throw an error if url is not provided by default', () => {\n // Given\n const Service = require('./websocket')\n \n // When\n const Module = () => new Service()\n\n // When\n expect(Module).toThrowError('Websocket URL is not defined')\n})\n" }, { "answer_id": 74478052, "author": "JHIH-LEI", "author_id": 16930765, "author_profile": "https://Stackoverflow.com/users/16930765", "pm_score": 0, "selected": false, "text": "\n it('should throw an error if url is not provided by default', (done) => {\n // Given\n const Service = require('./services/websocket')\n\n // When\n try {\n const Websocket = new Service()\n } catch(err){\n expect(Websocket.url).toBeUndefined()\n expect(err.message).toBe(\"Websocket URL is not provided\")\n done()\n }\n \n\n throw new Error('it did not catch url is not provided error')\n })\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/884143/" ]
74,442,916
<p>Newby here. I would like a simple way, if it exists, to fill in a column with the same string/number.</p> <p>The formula should not specify the number of rows (or the last row to fill in) but should propagate the string/number to the last cell of the column.</p> <p>At the moment I'm using this formula:</p> <pre><code>=ArrayFormula({&quot;Hello&quot;}&amp;$B:$B) </code></pre> <p>that writes my string (&quot;Hello&quot; in this case) concatenated with the content of its right cell. So this work (write just &quot;Hello&quot; in all the column cell) <em>if</em> the column B is empty :)</p> <p>Can I simplify it?</p>
[ { "answer_id": 74447133, "author": "aspirinemaga", "author_id": 884143, "author_profile": "https://Stackoverflow.com/users/884143", "pm_score": -1, "selected": false, "text": "\n it('should throw an error if url is not provided by default', () => {\n // Given\n const Service = require('./services/websocket')\n\n // When\n let Module\n\n try {\n Module = new Service()\n } catch (error) {\n Module = error\n }\n\n expect(Module).toBeInstanceOf(Error)\n expect(Module.message).toBe('Websocket URL is not defined')\n })\n\n it('should pick up a WS url from env file automatically', () => {\n process.env.WS_URL = 'ws://dummyurl'\n const Service = require('./services/websocket')\n const Module = new Service()\n\n expect(Module.url).toEqual(process.env.WS_URL)\n })\n" }, { "answer_id": 74447199, "author": "Djlewald", "author_id": 7960407, "author_profile": "https://Stackoverflow.com/users/7960407", "pm_score": -1, "selected": false, "text": "it('should throw an error if url is not provided by default', () => {\n const Service = require('./services/websocket')\n expect(new Service()).toThrowError()\n})\n" }, { "answer_id": 74458504, "author": "aspirinemaga", "author_id": 884143, "author_profile": "https://Stackoverflow.com/users/884143", "pm_score": 0, "selected": false, "text": "it('should throw an error if url is not provided by default', () => {\n // Given\n const Service = require('./websocket')\n \n // When\n const Module = () => new Service()\n\n // When\n expect(Module).toThrowError('Websocket URL is not defined')\n})\n" }, { "answer_id": 74478052, "author": "JHIH-LEI", "author_id": 16930765, "author_profile": "https://Stackoverflow.com/users/16930765", "pm_score": 0, "selected": false, "text": "\n it('should throw an error if url is not provided by default', (done) => {\n // Given\n const Service = require('./services/websocket')\n\n // When\n try {\n const Websocket = new Service()\n } catch(err){\n expect(Websocket.url).toBeUndefined()\n expect(err.message).toBe(\"Websocket URL is not provided\")\n done()\n }\n \n\n throw new Error('it did not catch url is not provided error')\n })\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511956/" ]
74,442,936
<p>How i can share list changes between multiprocessing parallel process?, im having trouble with that.</p> <pre><code>import multiprocessing listx = [] def one(): global listx time.sleep(5) if 'ok' not in listx: print('not in') else: print('in') def two(): global listx listx.append('ok') if __name__ == '__main__': p1 = multiprocessing.Process(target=one) p2 = multiprocessing.Process(target=two) p1.start() p2.start() # Output : not in </code></pre>
[ { "answer_id": 74447133, "author": "aspirinemaga", "author_id": 884143, "author_profile": "https://Stackoverflow.com/users/884143", "pm_score": -1, "selected": false, "text": "\n it('should throw an error if url is not provided by default', () => {\n // Given\n const Service = require('./services/websocket')\n\n // When\n let Module\n\n try {\n Module = new Service()\n } catch (error) {\n Module = error\n }\n\n expect(Module).toBeInstanceOf(Error)\n expect(Module.message).toBe('Websocket URL is not defined')\n })\n\n it('should pick up a WS url from env file automatically', () => {\n process.env.WS_URL = 'ws://dummyurl'\n const Service = require('./services/websocket')\n const Module = new Service()\n\n expect(Module.url).toEqual(process.env.WS_URL)\n })\n" }, { "answer_id": 74447199, "author": "Djlewald", "author_id": 7960407, "author_profile": "https://Stackoverflow.com/users/7960407", "pm_score": -1, "selected": false, "text": "it('should throw an error if url is not provided by default', () => {\n const Service = require('./services/websocket')\n expect(new Service()).toThrowError()\n})\n" }, { "answer_id": 74458504, "author": "aspirinemaga", "author_id": 884143, "author_profile": "https://Stackoverflow.com/users/884143", "pm_score": 0, "selected": false, "text": "it('should throw an error if url is not provided by default', () => {\n // Given\n const Service = require('./websocket')\n \n // When\n const Module = () => new Service()\n\n // When\n expect(Module).toThrowError('Websocket URL is not defined')\n})\n" }, { "answer_id": 74478052, "author": "JHIH-LEI", "author_id": 16930765, "author_profile": "https://Stackoverflow.com/users/16930765", "pm_score": 0, "selected": false, "text": "\n it('should throw an error if url is not provided by default', (done) => {\n // Given\n const Service = require('./services/websocket')\n\n // When\n try {\n const Websocket = new Service()\n } catch(err){\n expect(Websocket.url).toBeUndefined()\n expect(err.message).toBe(\"Websocket URL is not provided\")\n done()\n }\n \n\n throw new Error('it did not catch url is not provided error')\n })\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20351913/" ]
74,442,952
<p>I have a dataframe like this.</p> <p><a href="https://i.stack.imgur.com/kmwHC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kmwHC.jpg" alt="A dataframe with consecutive zeros in column 'volume'." /></a></p> <p>And I want to recognize the some rows, so that any recognized row is in a block with more than 3 (&gt;=4) consecutive zeros. (marked as cannot_trade)</p> <p>What I've tried is:</p> <pre><code>df['cannot_trade'] = ( (df['volume'] == 0) &amp; (df['volume'].shift(1) == 0) &amp; (df['volume'].shift(2) == 0) &amp; (df['volume'].shift(3) == 0) ) | ( (df['volume'] == 0) &amp; (df['volume'].shift(-1) == 0) &amp; (df['volume'].shift(-2) == 0) &amp; (df['volume'].shift(-3) == 0)) </code></pre> <p>It does recognize long consecutive zeros but we can see in the dataframe that at 'closetime'=='2022-10-17 23:13:00' and 'closetime'=='2022-10-17 23:14:00', the recognition fail, where 'cannot_trade' should have been set 'True'.</p> <p>Do you have any idea how to fix this?</p> <p>Here's the text format of the dataframe:</p> <pre><code> close volume symbol closetime cannot_trade 63292514 0.2544 910 ZRX-USDT-SWAP 2022-10-17 23:01:00 False 63292515 0.2544 0 ZRX-USDT-SWAP 2022-10-17 23:02:00 False 63292516 0.2544 0 ZRX-USDT-SWAP 2022-10-17 23:03:00 False 63292517 0.2544 0 ZRX-USDT-SWAP 2022-10-17 23:04:00 False 63292518 0.2543 222 ZRX-USDT-SWAP 2022-10-17 23:05:00 False 63292519 0.2543 0 ZRX-USDT-SWAP 2022-10-17 23:06:00 False 63292520 0.2546 1119 ZRX-USDT-SWAP 2022-10-17 23:07:00 False 63292521 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:08:00 False 63292522 0.2549 84 ZRX-USDT-SWAP 2022-10-17 23:09:00 False 63292523 0.2549 0 ZRX-USDT-SWAP 2022-10-17 23:10:00 False 63292524 0.2548 181 ZRX-USDT-SWAP 2022-10-17 23:11:00 False 63292525 0.2548 0 ZRX-USDT-SWAP 2022-10-17 23:12:00 True 63292526 0.2548 0 ZRX-USDT-SWAP 2022-10-17 23:13:00 False 63292527 0.2548 0 ZRX-USDT-SWAP 2022-10-17 23:14:00 False 63292528 0.2548 0 ZRX-USDT-SWAP 2022-10-17 23:15:00 True 63292529 0.2546 222 ZRX-USDT-SWAP 2022-10-17 23:16:00 False 63292530 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:17:00 True 63292531 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:18:00 True 63292532 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:19:00 True 63292533 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:20:00 True 63292534 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:21:00 True 63292535 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:22:00 True 63292536 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:23:00 True 63292537 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:24:00 True 63292538 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:25:00 True 63292539 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:26:00 True 63292540 0.2546 0 ZRX-USDT-SWAP 2022-10-17 23:27:00 True 63292541 0.2545 100 ZRX-USDT-SWAP 2022-10-17 23:28:00 False 63292542 0.2545 0 ZRX-USDT-SWAP 2022-10-17 23:29:00 False 63292543 0.2545 0 ZRX-USDT-SWAP 2022-10-17 23:30:00 False 63292544 0.2547 141 ZRX-USDT-SWAP 2022-10-17 23:31:00 False 63292545 0.2548 3 ZRX-USDT-SWAP 2022-10-17 23:32:00 False 63292546 0.2548 0 ZRX-USDT-SWAP 2022-10-17 23:33:00 False 63292547 0.2548 0 ZRX-USDT-SWAP 2022-10-17 23:34:00 False 63292548 0.2552 130 ZRX-USDT-SWAP 2022-10-17 23:35:00 False 63292549 0.2555 214 ZRX-USDT-SWAP 2022-10-17 23:36:00 False 63292550 0.2555 0 ZRX-USDT-SWAP 2022-10-17 23:37:00 True 63292551 0.2555 0 ZRX-USDT-SWAP 2022-10-17 23:38:00 True 63292552 0.2555 0 ZRX-USDT-SWAP 2022-10-17 23:39:00 False 63292553 0.2555 0 ZRX-USDT-SWAP 2022-10-17 23:40:00 True 63292554 0.2555 0 ZRX-USDT-SWAP 2022-10-17 23:41:00 True 63292555 0.2557 103 ZRX-USDT-SWAP 2022-10-17 23:42:00 False 63292556 0.2557 0 ZRX-USDT-SWAP 2022-10-17 23:43:00 False 63292557 0.2557 127 ZRX-USDT-SWAP 2022-10-17 23:44:00 False 63292558 0.2557 0 ZRX-USDT-SWAP 2022-10-17 23:45:00 False 63292559 0.2559 91 ZRX-USDT-SWAP 2022-10-17 23:46:00 False 63292560 0.2558 100 ZRX-USDT-SWAP 2022-10-17 23:47:00 False 63292561 0.2558 0 ZRX-USDT-SWAP 2022-10-17 23:48:00 False 63292562 0.2558 39 ZRX-USDT-SWAP 2022-10-17 23:49:00 False 63292563 0.2558 0 ZRX-USDT-SWAP 2022-10-17 23:50:00 False 63292564 0.2558 0 ZRX-USDT-SWAP 2022-10-17 23:51:00 False 63292565 0.2558 0 ZRX-USDT-SWAP 2022-10-17 23:52:00 False 63292566 0.2555 260 ZRX-USDT-SWAP 2022-10-17 23:53:00 False 63292567 0.2555 0 ZRX-USDT-SWAP 2022-10-17 23:54:00 False 63292568 0.2555 0 ZRX-USDT-SWAP 2022-10-17 23:55:00 False 63292569 0.2550 375 ZRX-USDT-SWAP 2022-10-17 23:56:00 False 63292570 0.2549 43 ZRX-USDT-SWAP 2022-10-17 23:57:00 False 63292571 0.2549 195 ZRX-USDT-SWAP 2022-10-17 23:58:00 False 63292572 0.2550 141 ZRX-USDT-SWAP 2022-10-17 23:59:00 False 63292573 0.2550 209 ZRX-USDT-SWAP 2022-10-18 00:00:00 False </code></pre>
[ { "answer_id": 74442978, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "groupby.transform('count')" }, { "answer_id": 74443045, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 1, "selected": false, "text": "0" }, { "answer_id": 74443054, "author": "Borja_042", "author_id": 7035921, "author_profile": "https://Stackoverflow.com/users/7035921", "pm_score": 0, "selected": false, "text": "so[\"sum\"] = so[\"a\"].rolling(4).sum()\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14937012/" ]
74,442,959
<p>I would like to write some console apps using C# 11. I know that it can be only with .NET 7x. If I write</p> <pre><code>&lt;TargetFramework&gt;netcoreapp7&lt;/TargetFramework&gt; </code></pre> <p>in my .csproj file, I will get NETSDK1045 instead of running. But &quot;file&quot; (type modifier) is useful.</p>
[ { "answer_id": 74442978, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "groupby.transform('count')" }, { "answer_id": 74443045, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 1, "selected": false, "text": "0" }, { "answer_id": 74443054, "author": "Borja_042", "author_id": 7035921, "author_profile": "https://Stackoverflow.com/users/7035921", "pm_score": 0, "selected": false, "text": "so[\"sum\"] = so[\"a\"].rolling(4).sum()\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,442,968
<p>I want my text box to have a date in it, how do I do it?</p> <pre><code>&lt;asp:TextBox ID=&quot;BirthdayRegBt&quot; runat=&quot;server&quot; class=&quot;form-control&quot; placeholder=&quot;Birthday Date&quot; required=&quot;&quot;&gt;&lt;/asp:TextBox&gt; </code></pre>
[ { "answer_id": 74442978, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "groupby.transform('count')" }, { "answer_id": 74443045, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 1, "selected": false, "text": "0" }, { "answer_id": 74443054, "author": "Borja_042", "author_id": 7035921, "author_profile": "https://Stackoverflow.com/users/7035921", "pm_score": 0, "selected": false, "text": "so[\"sum\"] = so[\"a\"].rolling(4).sum()\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20315624/" ]
74,442,972
<p>I have the mongo collection like this</p> <pre><code>[ /* 1 */ { &quot;_id&quot; : 1, &quot;data_id&quot; : 1, &quot;data_test&quot; : &quot;sample1&quot;, &quot;data_list&quot; : [ &quot;sun&quot; ], } /* 2 */ { &quot;_id&quot; : 2, &quot;data_id&quot; : 1, &quot;data_test&quot; : &quot;sample2&quot;, &quot;data_list&quot; : [ &quot;sun&quot;, &quot;mon&quot; ], } /* 3 */ { &quot;_id&quot; : 3, &quot;data_id&quot; : 2, &quot;data_test&quot; : &quot;sample3&quot;, &quot;data_list&quot; : [ &quot;tue&quot; ], } /* 4 */ { &quot;_id&quot; : 4, &quot;data_id&quot; : 2, &quot;data_test&quot; : &quot;sample4&quot;, &quot;data_list&quot; : [ &quot;tue&quot;, &quot;wed&quot; ], } ] </code></pre> <p>I would like to query this to get the count of how many time an element of data_list appear on a single collection where there data_id is the same. Something like this can be achieved using SQL query like this if the data_list is single element and not a list.</p> <pre><code>Select data_list, count(*) from analytics_customer where data_id = 1 group by data_list </code></pre> <p>The output should be like this if we query for only &quot;data_id&quot; : 1</p> <pre><code>{ &quot;sun&quot;: 2, &quot;mon&quot;: 1 } </code></pre> <p>The output for &quot;data_id&quot; : 2</p> <pre><code>{ &quot;tue&quot;: 2, &quot;wed&quot;: 1 } </code></pre>
[ { "answer_id": 74442978, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "groupby.transform('count')" }, { "answer_id": 74443045, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 1, "selected": false, "text": "0" }, { "answer_id": 74443054, "author": "Borja_042", "author_id": 7035921, "author_profile": "https://Stackoverflow.com/users/7035921", "pm_score": 0, "selected": false, "text": "so[\"sum\"] = so[\"a\"].rolling(4).sum()\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15995650/" ]
74,442,980
<p>I have a dataframe like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> <th>col3</th> <th>col N</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>y</td> <td>z</td> <td>f</td> </tr> <tr> <td>y</td> <td>x</td> <td>z</td> <td>f</td> </tr> <tr> <td>f</td> <td>none</td> <td>none</td> <td>none</td> </tr> <tr> <td>z</td> <td>y</td> <td>x</td> <td>f</td> </tr> </tbody> </table> </div> <p>I need to count the rows that equal, regardless of their combinations.</p> <p>It means that, in this case, the output shoud be something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> <th>col3</th> <th>col N</th> <th>freq</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>y</td> <td>z</td> <td>f</td> <td>3</td> </tr> <tr> <td>f</td> <td>none</td> <td>none</td> <td>none</td> <td>1</td> </tr> </tbody> </table> </div> <p>This bacause, according to the input dataset, there are three rows that have the same sequence (line 1, line 2, and line 4).</p> <p>I tried to use the function &quot;value_counts&quot;, however, according to the documentation, this function count only the unique values.</p> <p>N.B. The initial dataset contain over 200 column.</p> <p>Any solution?</p> <p>Thanks</p>
[ { "answer_id": 74443036, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby" }, { "answer_id": 74443257, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "data = {'col1': {0: 'x', 1: 'y', 2: 'f', 3: 'z'},\n 'col2': {0: 'y', 1: 'x', 2: None, 3: 'y'},\n 'col3': {0: 'z', 1: 'z', 2: None, 3: 'x'},\n 'col N': {0: 'f', 1: 'f', 2: None, 3: 'f'}}\ndf = pd.DataFrame(data)\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74442980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19505786/" ]
74,443,028
<p>I have a 10x10 matrix that I am filling with random chars. My problem is that I can't figure out how to insert a string <code>&quot;HOUSE&quot;</code> into the first row of the table.</p> <pre><code>Random rchar = new Random(); string word = &quot;HOUSE&quot;; char[] wordChars = word.ToCharArray(); char[,] arr = new char[10, 10]; //Size of Rows and Cols var rowLength = arr.GetLength(0); var colLength = arr.GetLength(1); for (int x = 0; x &lt; rowLength; x++) { for (int y = 0; y &lt; colLength; y++) { arr[0, y] = wordChars[1]; arr[x, y] = (char)(rchar.Next(65, 91)); Console.Write(arr[x, y] + &quot; &quot;); } Console.WriteLine(); } </code></pre> <p>I was trying to place a new value with the <code>SetValue</code> property but it doesn't work for me because I have a two-dimensional array.</p>
[ { "answer_id": 74443036, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby" }, { "answer_id": 74443257, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "data = {'col1': {0: 'x', 1: 'y', 2: 'f', 3: 'z'},\n 'col2': {0: 'y', 1: 'x', 2: None, 3: 'y'},\n 'col3': {0: 'z', 1: 'z', 2: None, 3: 'x'},\n 'col N': {0: 'f', 1: 'f', 2: None, 3: 'f'}}\ndf = pd.DataFrame(data)\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19579662/" ]
74,443,052
<p>For example i have an array {1,2,2,2,3,3,3,3,4,4,4,4,4,} I need to transform it into {4,4,4,4,4,,3,3,3,3,2,2,2,1} So i have to sort it by the number of repetitions of an array element somehow. I saw some solves of this problem on c++ but i have to write it on C. I can`t use vector or smth. Just Sorting with buffer array or inside of exact array.</p> <p>I tried something like this, but honestly now i etched into a dead end: It is dont work properly as i ment. I have an algoritm in my head:</p> <ol> <li>Program count how times some element was repeated and write in into a second array</li> <li>Program sort second array</li> <li>Program sort first array by second array somehow</li> </ol> <pre><code>#include &lt;stdio.h&gt; int main() { const int size = 10; int A[size], B[size]; int counter1, counter2 = -1; int temp = 0; for (int i = 0; i &lt; size; i++) { printf(&quot;Enter %d element of array: &quot;, i + 1); scanf_s(&quot;%d&quot;, &amp;A[i]); } for (int i = 0; i &lt; size-1; i++) { counter1 = 0; counter2++; for (int j = i; j &lt; size; j++) { if (A[j] == A[j - 1]) { break; } if (A[j] == A[j+1]) { counter1++; B[counter2] = counter1; temp = A[i]; } } } for (int i = 0; i &lt; size; i++) { printf(&quot;El %d = %d\n&quot;,i+1,B[i]); } } </code></pre>
[ { "answer_id": 74443036, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby" }, { "answer_id": 74443257, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "data = {'col1': {0: 'x', 1: 'y', 2: 'f', 3: 'z'},\n 'col2': {0: 'y', 1: 'x', 2: None, 3: 'y'},\n 'col3': {0: 'z', 1: 'z', 2: None, 3: 'x'},\n 'col N': {0: 'f', 1: 'f', 2: None, 3: 'f'}}\ndf = pd.DataFrame(data)\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20481926/" ]
74,443,088
<p>I would like to integrate into my CI/CD pipeline a requirement set condition.</p> <p>I'm developing an Office.js Excel addin and I would like to track client compatibility. There is a way to inspect code to detect the maximum value of requirement set?</p> <p>The codebase is not so small, and I want to keep an eye on client compatibility.</p> <p>Thanks</p>
[ { "answer_id": 74443036, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby" }, { "answer_id": 74443257, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "data = {'col1': {0: 'x', 1: 'y', 2: 'f', 3: 'z'},\n 'col2': {0: 'y', 1: 'x', 2: None, 3: 'y'},\n 'col3': {0: 'z', 1: 'z', 2: None, 3: 'x'},\n 'col N': {0: 'f', 1: 'f', 2: None, 3: 'f'}}\ndf = pd.DataFrame(data)\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120219/" ]
74,443,118
<p>When I want to reinstall my developer environment, I have some issues with gulp.</p> <pre><code>npm install gulp-cli -g npm : npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated At line:1 char:1 + npm install gulp-cli -g + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (npm WARN deprec...-url#deprecated:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated </code></pre> <p>I have tried to install different Node version with NVM and I have this issue on all the node versions.</p> <pre><code>nvm list 14.15.0 14.6.0 12.13.1 12.13.0 </code></pre> <p>Is there a way to resolve this issue, so I could have an SPFX developer environment again?</p>
[ { "answer_id": 74443036, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby" }, { "answer_id": 74443257, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "data = {'col1': {0: 'x', 1: 'y', 2: 'f', 3: 'z'},\n 'col2': {0: 'y', 1: 'x', 2: None, 3: 'y'},\n 'col3': {0: 'z', 1: 'z', 2: None, 3: 'x'},\n 'col N': {0: 'f', 1: 'f', 2: None, 3: 'f'}}\ndf = pd.DataFrame(data)\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11011428/" ]
74,443,129
<p>I have several strings similar like this</p> <pre><code>&quot;apple cost&quot;: &quot;2.78&quot; &quot;orange cost&quot;: &quot;12.59&quot; &quot;melone cost&quot;: &quot;42.12&quot; </code></pre> <p>the number can change/is variable and I want to remove the double quotes around the number. So the result should be like this</p> <pre><code>&quot;apple cost&quot;: 2.78 &quot;orange cost&quot;: 12.59 &quot;melone cost&quot;: 42.12 </code></pre> <p>The price are between 0.01 and 999.99 and the text varies only in relation to the name of the fruit and should always be in the form</p> <p>&quot;fruit name coast&quot;:. This part of the string does not need to be changed</p> <p>How can I do this in Python?</p> <p>I tried this with a expression like this, but the double quotes werent removed.</p> <pre><code>string = '&quot;apple cost&quot;: &quot;2.78&quot;' string = string.replace('&quot;apple cost&quot;: &quot;([0-9]).([1-9]|[0-9][0-9])&quot;', '&quot;apple cost&quot;: ([0-9]).([1-9]|[0-9][0-9])')¨ string = string.replace('&quot;orange cost&quot;: &quot;([0-9]).([1-9]|[0-9][0-9])&quot;', '&quot;orange cost&quot;: ([0-9]).([1-9]|[0-9][0-9])') </code></pre>
[ { "answer_id": 74443036, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby" }, { "answer_id": 74443257, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "data = {'col1': {0: 'x', 1: 'y', 2: 'f', 3: 'z'},\n 'col2': {0: 'y', 1: 'x', 2: None, 3: 'y'},\n 'col3': {0: 'z', 1: 'z', 2: None, 3: 'x'},\n 'col N': {0: 'f', 1: 'f', 2: None, 3: 'f'}}\ndf = pd.DataFrame(data)\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20507217/" ]
74,443,139
<p>I'm having trouble understanding my options for how to optimize this specific query. Looking online, I find various resources, but all for queries that don't match my particular one. From what I could gather, it's very hard to optimize a query when you have an order by combined with a limit.</p> <p>My usecase is that i would like to have a paginated datatable that displayed the latest records first.</p> <p>The query in question is the following (to fetch 10 latest records):</p> <pre class="lang-sql prettyprint-override"><code>select `xyz`.* from xyz where `xyz`.`fk_campaign_id` = 95870 and `xyz`.`voided` = 0 order by `registration_id` desc limit 10 offset 0 </code></pre> <p>&amp; table DDL:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE `xyz` ( `registration_id` int NOT NULL AUTO_INCREMENT, `fk_campaign_id` int DEFAULT NULL, `fk_customer_id` int DEFAULT NULL, ... other fields ... `voided` tinyint unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`registration_id`), .... ~12 other indexes ... KEY `activityOverview` (`fk_campaign_id`,`voided`,`registration_id` DESC) ) ENGINE=InnoDB AUTO_INCREMENT=280614594 DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci; </code></pre> <p>The explain on the query mentioned gives me the following:</p> <pre><code>&quot;id&quot;,&quot;select_type&quot;,&quot;table&quot;,&quot;partitions&quot;,&quot;type&quot;,&quot;possible_keys&quot;,&quot;key&quot;,&quot;key_len&quot;,&quot;ref&quot;,&quot;rows&quot;,&quot;filtered&quot;,&quot;Extra&quot; 1,SIMPLE,db_campaign_registration,,index,&quot;getTop5,winners,findByPage,foreignKeyExistingCheck,limitReachedIp,byCampaign,emailExistingCheck,getAll,getAllDated,activityOverview&quot;,PRIMARY,&quot;4&quot;,,1626,0.65,Using where; Backward index scan </code></pre> <p>As you can see it says it only hits 1626 rows. But, when i execute it - then it takes 200+ seconds to run.</p> <p>I'm doing this to fetch data for a datatable that is to display the latest 10 records. I also have pagination that allows one to navigate pages (only able to go to next page, not last or make any big jumps).</p> <p>To further help with getting the full picture I've put together a dbfiddle. <a href="https://dbfiddle.uk/Jc_K68rj" rel="nofollow noreferrer">https://dbfiddle.uk/Jc_K68rj</a> - this fiddle does not have the same results as my table. But i suspect this is because of the data size that I'm having with my table.</p> <p>The table in question has 120GB data and 39.000.000 active records. I already have an index put in that should cover the query and allow it to fetch the data fast. Am i completely missing something here?</p>
[ { "answer_id": 74453757, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 0, "selected": false, "text": "KEY `activityOverview` (`fk_campaign_id`,`voided`,`registration_id` DESC)\n" }, { "answer_id": 74467028, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 2, "selected": true, "text": "SELECT b.*\n FROM ( SELECT registration_id \n FROM xyz\n where `xyz`.`fk_campaign_id` = 95870\n and `xyz`.`voided` = 0\n order by `registration_id` desc\n limit 10 offset 0 ) AS a\n JOIN xyz AS b USING (registration_id)\n order by `registration_id` desc;\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1231901/" ]
74,443,156
<p>I have this obj, I want to access this p tag content and render it through props. Without dangrouslySetInnerHTML method. What should I've to do?</p> <pre><code>let content = { para: `&lt;p&gt;A listing page is the public view of a listing. It should informations be designed to display all relevant information about a listing.&lt;/p&gt;` } </code></pre>
[ { "answer_id": 74443259, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 0, "selected": false, "text": "String.prototype.slice" }, { "answer_id": 74443275, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 2, "selected": false, "text": "DOMParser" }, { "answer_id": 74443576, "author": "gedeon ebamba", "author_id": 13583619, "author_profile": "https://Stackoverflow.com/users/13583619", "pm_score": -1, "selected": false, "text": "content.para" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19924540/" ]
74,443,173
<p>I am using Cosmos DB and wanted to implement a user friendly id for displaying in UI for end user. For this what I am doing is taking max ID existing in DB and adding 1 to it .</p> <p>The problem that I am facing over here is when multiple user hit this function the max id returned is same and the new ID generated is getting duplicated.</p> <p>how can I make sure that a certain block of code is only executed one at a time.</p> <p>I tried SemaphoreSlim , didn't help. I am expecting to generate auto incremented ID without any duplication .</p>
[ { "answer_id": 74443259, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 0, "selected": false, "text": "String.prototype.slice" }, { "answer_id": 74443275, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 2, "selected": false, "text": "DOMParser" }, { "answer_id": 74443576, "author": "gedeon ebamba", "author_id": 13583619, "author_profile": "https://Stackoverflow.com/users/13583619", "pm_score": -1, "selected": false, "text": "content.para" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508539/" ]
74,443,177
<p>I have a customer table like this</p> <pre><code>id | city | street | street number 1 | Berlin | Bahnhofstraße | 5 2 | New York | Main street | 22 3 | Frankfurt | Bahnhofstraße | 11 4 | London | Bond Street | 63 </code></pre> <p>I made a simple html input, get the value with jquery and perform an simple search with ajax.</p> <p>So when i search for &quot;Bahnh&quot; i fire the SQL query</p> <pre><code>SELECT * FROM `customers` WHERE `street ` LIKE '%Bahnh%' OR city LIKE '%&quot;Bahnh&quot;%' </code></pre> <p>I get the id 1 and 3</p> <p>But is there a way to add the street number in the query? Like when i search for &quot;Bahnhof 11&quot; i only get id 3?</p>
[ { "answer_id": 74443230, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "WHERE" }, { "answer_id": 74443236, "author": "Agustín Tamayo Quiñones", "author_id": 18172381, "author_profile": "https://Stackoverflow.com/users/18172381", "pm_score": 1, "selected": false, "text": "SELECT * \nFROM `customers` \nWHERE `street number` = 11 \nAND (`street ` LIKE '%Bahnh%' OR city LIKE '%\"Bahnh\"%')\n" }, { "answer_id": 74443897, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 1, "selected": false, "text": "ALTER TABLE customers \nADD FULLTEXT INDEX fulltext(street, street_number);\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13238868/" ]
74,443,187
<p>If i have two models:</p> <pre><code>Model_1.objects.all() Model_2.objects.all() </code></pre> <p>Model_1 contains all the elements, Model_2 contains a part of these elements.</p> <p>How can i find the elements contained in Model_1 but not in Model_2?</p> <p>I tried:</p> <pre><code>Model_1.objects.exclude(pk=Model_2.objects.order_by('pk')) </code></pre> <p>It doesn't work.</p>
[ { "answer_id": 74443721, "author": "maciek97x", "author_id": 10626495, "author_profile": "https://Stackoverflow.com/users/10626495", "pm_score": 0, "selected": false, "text": "in[Django doc.]" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18438369/" ]
74,443,220
<p>Here I created a baseadmin model to use in all of my admin models:</p> <pre class="lang-py prettyprint-override"><code>class BaseAdmin(admin.ModelAdmin): base_readonly_fields = ('created', 'updated','removed') def get_readonly_fields(self, request, obj=None): if self.readonly_fields: return tuple(self.readonly_fields) + self.base_readonly_fields else: return self.base_readonly_fields @admin.register(models.Example) class Example(BaseAdmin): list_display = ['id', 'name', 'sf_id', ] </code></pre> <p>The problem with BaseAdmin is sometimes some models don't have the 'removed' or 'updated'. That's why I get an error.</p> <p>So I want to make the baseadmin general, if the field exits this will make it readonly like it is on the baseadmin, otherwise and if there is not such field this will just pass and won't rise any error. Any idea how to check this and make the baseadmin more flexable?</p>
[ { "answer_id": 74444404, "author": "Abhijith K", "author_id": 7406389, "author_profile": "https://Stackoverflow.com/users/7406389", "pm_score": 4, "selected": true, "text": "class BaseAdmin(admin.ModelAdmin):\n base_readonly_fields = ('created',)\n\n def get_readonly_fields(self, request, obj=None):\n if self.readonly_fields:\n return tuple(self.readonly_fields) + self.base_readonly_fields\n\n else:\n return self.base_readonly_fields\n\nclass BaseAdminWithUpdateRemoveField(BaseAdmin):\n base_readonly_fields = ('created', 'updated', 'removed')\n\n@admin.register(models.ExampleUpdateRemoveField)\nclass ExampleWithUpdateRemoveField(BaseAdminWithUpdateRemoveField):\n list_display = ['id', 'name', 'sf_id', ]\n\n@admin.register(models.Example)\nclass Example(BaseAdmin):\n list_display = ['id', 'name', 'sf_id', ]\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19393810/" ]
74,443,235
<p>I would like to replace a configuration yml property using a condition based on environnement variables :</p> <pre><code>spring: datasource: username:${ENV} == 'PROD' ? ${USER_PROD} : ${USER_TEST} password: ${ENV} == 'PROD' ? ${PWD_PROD} : ${PWD_PROD} </code></pre> <p>Is there any way I can do this inside my application.yml or programmaticaly ?</p> <p>I have not faced this situation before</p>
[ { "answer_id": 74443332, "author": "atish.s", "author_id": 6200354, "author_profile": "https://Stackoverflow.com/users/6200354", "pm_score": 2, "selected": true, "text": "application.properties" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508601/" ]
74,443,285
<p>How can I create a new DF such that each teacher should contain a list of Students</p> <p><strong>Teacher df</strong></p> <pre><code> name married school 0 Pep Guardiola True Manchester High School 1 Jurgen Klopp True Liverpool High School 2 Mikel Arteta False Arsenal High 3 Zinadine Zidane True NaN </code></pre> <p><strong>Student df</strong></p> <pre><code> teacher name age height weight 0 Mikel Arteta Bukayo Saka 21 2.1m 80kg 1 Mikel Arteta Gabriel Martinelli 21 2.1m 75kg 2 Pep Guardiola Jack Grealish 27 2.1m 80kg 3 Jurgen Klopp Roberto Firmino 31 2.1m 65kg 4 Jurgen Klopp Andrew Robertson 28 2.1m 70kg 5 Jurgen Klopp Darwin Nunez 23 2.1m 75kg 6 Pep Guardiola Ederson Moraes 29 2.1m 90kg 7 Pep Guardiola Manuel Akanji 27 2.1m 80kg 8 Mikel Arteta Thomas Partey 29 2.1m 80kg </code></pre>
[ { "answer_id": 74443313, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 1, "selected": false, "text": "Series.map" }, { "answer_id": 74443376, "author": "Celius Stingher", "author_id": 11897007, "author_profile": "https://Stackoverflow.com/users/11897007", "pm_score": 0, "selected": false, "text": "df.merge(df.groupby('teacher',as_index=False).agg({'name':list}),\n how='left',\n on='teacher',\n suffixes=('','_list'))\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911813/" ]
74,443,323
<pre><code>DateTime beforeDate = DateTime.now(); await Future.delayed(Duration(seconds: 2)); try { return await FirebaseFirestore.instance .collection('news') .where('id', isEqualTo: id) .get() .then((snapshot) { DateTime afterDate = DateTime.now(); print(afterDate.difference(beforeDate).inMilliseconds);//2.373 seconds return NewsModel.fromJson(snapshot.docs.first.data()); }); } catch (ex) { print('ex: $ex'); rethrow; } </code></pre> <p>This code took 2.373 seconds to complete. How to delay for 2 seconds and do another small task (0.373 seconds) at the same time (so the total delay is 2)?</p>
[ { "answer_id": 74443520, "author": "Risheek Mittal", "author_id": 16973338, "author_profile": "https://Stackoverflow.com/users/16973338", "pm_score": -1, "selected": false, "text": " Future.delayed(Duration(seconds: 2), (){\n // Your code over here\n });\n" }, { "answer_id": 74443558, "author": "RobDil", "author_id": 410996, "author_profile": "https://Stackoverflow.com/users/410996", "pm_score": 3, "selected": true, "text": "final returnValues = await Future.wait<void>([\n Future.delayed(const Duration(seconds: 2)),\n FirebaseFirestore.instance\n .collection('news')\n .where('id', isEqualTo: id)\n .get(),\n]);\n\nfinal mySnapshots = returnValues[1];\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1204050/" ]
74,443,349
<p>I created a class called person with two members name and age then I created two objects of that</p> <p>class p1 and p2 and then I added them to a vector. I tried then to print them but could not.</p> <p>this my code:</p> <pre><code>class Person{ public: string name; int age; }; int main(){ Person p; vector &lt;Person&gt; vector; p.name = &quot;Vitalik&quot;; p.age = 29; Person p2; p2.name = &quot;Bueterin&quot;; p2.age = 50; vector.push_back(p); vector.push_back(p2); for(int i = 0; i &lt; vector.size(); i++){ cout &lt;&lt; vector[i] &lt;&lt; endl; } return 0; } </code></pre> <p>I tried multiple ways to loop through the vector and print the elements but I keep getting this message:</p> <pre><code> error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream&lt;char&gt;') and 'std::__vector_base&lt;Person, std::allocator&lt;Person&gt; &gt;::value_type' (aka 'Person')) cout &lt;&lt; vector[i] &lt;&lt; endl; </code></pre>
[ { "answer_id": 74443386, "author": "jsofri", "author_id": 16500523, "author_profile": "https://Stackoverflow.com/users/16500523", "pm_score": 1, "selected": false, "text": "operator<<" }, { "answer_id": 74443441, "author": "Vslav", "author_id": 13511100, "author_profile": "https://Stackoverflow.com/users/13511100", "pm_score": 3, "selected": true, "text": "operator<<" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20431658/" ]
74,443,368
<p>This is my code:</p> <pre><code>image_array.append(image) label_array.append(i) image_array = np.array(image_array) label_array = np.array(label_array, dtype=&quot;float&quot;) </code></pre> <p>This is the error:</p> <pre><code>AttributeError: 'numpy.ndarray' object has no attribute 'append' </code></pre>
[ { "answer_id": 74443566, "author": "Marco Massetti", "author_id": 8290982, "author_profile": "https://Stackoverflow.com/users/8290982", "pm_score": 1, "selected": false, "text": "image_array = np.append(image_array, [image])\nlabel_array = np.append(label_array, [i])\n" }, { "answer_id": 74443639, "author": "M Imran", "author_id": 3424847, "author_profile": "https://Stackoverflow.com/users/3424847", "pm_score": 2, "selected": false, "text": "import numpy as np\n\n#define NumPy array\nx = np.array([1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23])\n\n#append the value '25' to end of NumPy array\nx = np.append(x, 25)\n\n#view updated array\nx\n\narray([ 1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23, 25])\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17448619/" ]
74,443,380
<p>In Python, you can specify a &quot;step&quot; argument to a list slice that specifies the separation between indices that are selected to be in the slice:</p> <pre class="lang-py prettyprint-override"><code>my_list[start:stop:step] </code></pre> <p>However, none of the list methods in Dart seem to offer this functionality: <code>sublist</code> and <code>getRange</code> just take the start and end index. How can I do this in Dart without using an ugly for-loop?</p> <p>For example, to select only the even indices of a list I currently see no alternative to this:</p> <pre class="lang-dart prettyprint-override"><code>List&lt;Object&gt; myList = ...; List&lt;Object&gt; slice = []; for (var i = 0; i &lt; myList.length; i += 2) { slice.add(myList[i]); } </code></pre> <p>Or slightly less ugly with a list comprehension:</p> <pre class="lang-dart prettyprint-override"><code>[for (var i = 0; i &lt; myList.length; i += 2) myList[i]] </code></pre> <p>I could write my own function or extension method, but that defeats the purpose, I'm looking for ideally a built-in or a third package solution.</p>
[ { "answer_id": 74443566, "author": "Marco Massetti", "author_id": 8290982, "author_profile": "https://Stackoverflow.com/users/8290982", "pm_score": 1, "selected": false, "text": "image_array = np.append(image_array, [image])\nlabel_array = np.append(label_array, [i])\n" }, { "answer_id": 74443639, "author": "M Imran", "author_id": 3424847, "author_profile": "https://Stackoverflow.com/users/3424847", "pm_score": 2, "selected": false, "text": "import numpy as np\n\n#define NumPy array\nx = np.array([1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23])\n\n#append the value '25' to end of NumPy array\nx = np.append(x, 25)\n\n#view updated array\nx\n\narray([ 1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23, 25])\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6117426/" ]
74,443,392
<p>I created a timer that works like this:</p> <pre><code> const targetTime = new Date(props.targetDate).getTime(); const [currentTime, setCurrentTime] = useState(Date.now()); const timeBetween = targetTime - currentTime; const days = Math.floor(timeBetween / (1000 * 60 * 60 * 24)); const hours = Math.floor((timeBetween % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((timeBetween % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((timeBetween % (1000 * 60)) / 1000); useEffect(() =&gt; { const interval = setInterval(() =&gt; { if (timeBetween &lt; 0) { props.onTimerFinish() } setCurrentTime(Date.now()); }, 1000); return () =&gt; { clearInterval(interval) }; }, []); </code></pre> <p>Then I have my UI that are 4 <code>View</code>'s displaying days, hours, min, sec.</p> <p>The <code>onTimerFinish</code> is a Void Function i.e. <code>() =&gt; void</code>. I'm checking <code>if (timeBetween &lt; 0)</code> at ever interval so that the moment it goes to negative I'll know the time is up and I want to trigger the <code>onTimerFinish</code> which is in the parent component of the timer as:</p> <pre><code>const testDate1 = '2022-11-15T09:30:00.000Z'; &lt;MyCountdownTimer targetDate ={testDate1} onTimerFinish={() =&gt; { console.log(&quot;Hello&quot;); }} /&gt; </code></pre> <p>After the timer runs out it doesn't call <code>onTimerFinish</code>. I want to refresh the parent component upon finishing the timer.</p>
[ { "answer_id": 74443566, "author": "Marco Massetti", "author_id": 8290982, "author_profile": "https://Stackoverflow.com/users/8290982", "pm_score": 1, "selected": false, "text": "image_array = np.append(image_array, [image])\nlabel_array = np.append(label_array, [i])\n" }, { "answer_id": 74443639, "author": "M Imran", "author_id": 3424847, "author_profile": "https://Stackoverflow.com/users/3424847", "pm_score": 2, "selected": false, "text": "import numpy as np\n\n#define NumPy array\nx = np.array([1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23])\n\n#append the value '25' to end of NumPy array\nx = np.append(x, 25)\n\n#view updated array\nx\n\narray([ 1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23, 25])\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4337240/" ]
74,443,396
<p>From this pandas df</p> <pre><code>1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 </code></pre> <p>samples_indices = df.sample(frac=0.5, replace=False).index<br /> df.loc[samples_indices] = 'X'</p> <p>will assign 'X' to all columns in randomly selected rows corresponding to 50% of df, like so:</p> <pre><code>X X X X 1 1 1 1 X X X X 1 1 1 1 </code></pre> <p>But how do I assign 'X' to 50% randomly selected cells in the df?<br /> For example like this:</p> <pre><code>X X X 1 1 X 1 1 X X X 1 1 1 1 X </code></pre>
[ { "answer_id": 74443424, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "MultiIndex Series" }, { "answer_id": 74443426, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "import numpy as np\n\ndf[np.random.choice([True, False], size=df.shape)] = 'X'\n\n# with a custom probability:\nN = 0.5\ndf[np.random.choice([True, False], size=df.shape, p=[N, 1-N])] = 'X'\n" }, { "answer_id": 74443571, "author": "Riccardo Bucco", "author_id": 5296106, "author_profile": "https://Stackoverflow.com/users/5296106", "pm_score": 2, "selected": false, "text": "import numpy as np\n\ndf[np.random.permutation(np.hstack([np.ones(df.size // 2), np.zeros(df.size // 2)])).astype(bool).reshape(df.shape)] = 'X'\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8872632/" ]
74,443,452
<p>I have been looking at the decorator design pattern (I am new to the subject of design patterns).</p> <p>I am already using BaseRepository pattern. But I want to use some cache too.</p> <p>Below sample is just a dump example.</p> <p>So I have <strong>IGenericRepository</strong> interface and the implementation to it.</p> <pre><code>public interface IGenericRepository&lt;T&gt; where T : class { T GetById(int id); IEnumerable&lt;T&gt; GetAll(); Task&lt;T&gt; GetByIdAsync(int id); T Add(T entity); void AddRange(IEnumerable&lt;T&gt; entities); Task&lt;T&gt; AddAsync(T entity); Task AddRangeAsync(IEnumerable&lt;T&gt; entities); void Remove(T entity); void RemoveRange(IEnumerable&lt;T&gt; entities); int SaveChanges(); Task&lt;int&gt; SaveChangesAsync(); } </code></pre> <p>Then I created a custom repository for example <strong>IBlogRepository</strong></p> <pre><code>public interface IBlogRepository : IBaseRepository&lt;Blog&gt; { public Task&lt;Blog&gt; GetBlogsByCreatorAsync(int creatorId); } </code></pre> <p>With the implemantation of <strong>BlogRepository</strong></p> <pre><code>public class BlogRepository : BaseRepository&lt;Blog&gt;, IBlogRepository { public BlogRepository(DbContext db) : base(db) { } public Task&lt;Blog&gt; GetBlogsByCreatorAsync(int creatorId) =&gt; db.Blogs.Where(b =&gt; b.CreatorId == creatorId) .ToListAsync(); } </code></pre> <p>I thought this is cool, then I realised I need to improve my &quot;speed&quot;. I am starting use IMemoryCache, but in Repository code like below.</p> <pre><code>public class BlogRepository : BaseRepository&lt;Blog&gt;, IBlogRepository { public BlogRepository(DbContext db, IMemoryCache cache) : base(db) { } public Task&lt;Blog&gt; GetBlogsByCreatorAsync(int creatorId) { // if in cache else go to db } } </code></pre> <p>Then I met with Decorate pattern and I thought why not, I started to use it, but I am struggling now. I created <strong>CachedBlogRepository</strong> which is implement <strong>IBlogRepository</strong>, but when I asked to VS implement all interface method...</p> <pre><code>public class CachedBlogRepository : IBlogRepository { //All BaseRepository methods appeared here... //But I want cache only the GetBlogsByCreatorAsync method } </code></pre> <p>So what is the best practice here? Do I missing something or did I something wrong?</p>
[ { "answer_id": 74443424, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "MultiIndex Series" }, { "answer_id": 74443426, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "import numpy as np\n\ndf[np.random.choice([True, False], size=df.shape)] = 'X'\n\n# with a custom probability:\nN = 0.5\ndf[np.random.choice([True, False], size=df.shape, p=[N, 1-N])] = 'X'\n" }, { "answer_id": 74443571, "author": "Riccardo Bucco", "author_id": 5296106, "author_profile": "https://Stackoverflow.com/users/5296106", "pm_score": 2, "selected": false, "text": "import numpy as np\n\ndf[np.random.permutation(np.hstack([np.ones(df.size // 2), np.zeros(df.size // 2)])).astype(bool).reshape(df.shape)] = 'X'\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5646020/" ]
74,443,453
<p>I'm trying to use pyfirmata to use an Arduino Ultrasonic sensor. I used Arduino Uno board and HC-SR04 Ultrasonic sensor. Here is the code I'm using. The code ran smoothly, it's just that it seems the echo pin failed to get an impulse from the trigger ultrasonic sound, so it keeps on getting False (LOW reading) and thus giving me false distance reading. Does anyone have a solution for this problem?</p> <pre><code>import pyfirmata import time board = pyfirmata.Arduino('COM16') start = 0 end = 0 echo = board.get_pin('d:11:i') trig = board.get_pin('d:12:o') LED = board.get_pin('d:13:o') it = pyfirmata.util.Iterator(board) it.start() trig.write(0) time.sleep(2) while True: time.sleep(0.5) trig.write(1) time.sleep(0.00001) trig.write(0) print(echo.read()) while echo.read() == False: start = time.time() while echo.read() == True: end = time.time() TimeElapsed = end - start distance = (TimeElapsed * 34300) / 2 print(&quot;Measured Distance = {} cm&quot;.format(distance) ) </code></pre> <p>I've tried changing the time.sleep() to several value and it still doesn't work. It works just fine when I'm using Arduino code dirrectly from Arduino IDE.</p>
[ { "answer_id": 74443424, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "MultiIndex Series" }, { "answer_id": 74443426, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "import numpy as np\n\ndf[np.random.choice([True, False], size=df.shape)] = 'X'\n\n# with a custom probability:\nN = 0.5\ndf[np.random.choice([True, False], size=df.shape, p=[N, 1-N])] = 'X'\n" }, { "answer_id": 74443571, "author": "Riccardo Bucco", "author_id": 5296106, "author_profile": "https://Stackoverflow.com/users/5296106", "pm_score": 2, "selected": false, "text": "import numpy as np\n\ndf[np.random.permutation(np.hstack([np.ones(df.size // 2), np.zeros(df.size // 2)])).astype(bool).reshape(df.shape)] = 'X'\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508701/" ]
74,443,465
<p>I can print the current filename with GNU sed using &quot;F&quot;. I can make changes to the pattern space with &quot;s&quot; (and other commands). Is there any way to put the filename into the pattern space so I can manipulate this as well.</p> <p>For example:</p> <pre><code>09:24:25:~ $ sed -n 'F ; s/hello/goodbye/ig ; p' hello.txt hello.txt goodbye world 09:24:42:~ $ </code></pre> <p>Is there a thing I could put instead of &quot;F&quot; which would get this to result in:</p> <pre><code>goodbye.txt goodbye world </code></pre>
[ { "answer_id": 74443759, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 2, "selected": false, "text": "sed" }, { "answer_id": 74443843, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 2, "selected": false, "text": "gnu awk" }, { "answer_id": 74444236, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed '1{h;s/.*/sed -n 1F file/e;x};G' file\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/375363/" ]
74,443,508
<p>Due to the fact that the ListView is not optimized enough, I decided that I would switch to the Recycler View. The first problem that hit me was this one.</p> <p>My RecyclerView adapter:</p> <pre><code>public class MyRecyclerViewAdapter extends RecyclerView.Adapter&lt;MyRecyclerViewAdapter.ViewHolder&gt; { private List&lt;String&gt; mData; private LayoutInflater mInflater; private ItemClickListener mClickListener; // data is passed into the constructor MyRecyclerViewAdapter(Context context, List&lt;String&gt; data) { this.mInflater = LayoutInflater.from(context); this.mData = data; } // inflates the row layout from xml when needed @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.adapter_box, parent, false); return new ViewHolder(view); } // binds the data to the TextView in each row @Override public void onBindViewHolder(ViewHolder holder, int position) { String animal = mData.get(position); holder.myTextView.setText(animal); } // total number of rows @Override public int getItemCount() { return mData.size(); } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView myTextView; ViewHolder(View itemView) { super(itemView); myTextView = itemView.findViewById(R.id.text_adapter); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition()); } } // convenience method for getting data at click position String getItem(int id) { return mData.get(id); } // allows clicks events to be caught void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } // parent activity will implement this method to respond to click events public interface ItemClickListener { void onItemClick(View view, int position); } </code></pre> <p>Using ListView I could do like this:</p> <pre><code>ListView listView = findViewById(R.id.testL); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { if (parent.getItemAtPosition(position).equals(&quot;hello&quot;)) { TextView details = word_dialog.findViewById(R.id.word_edit_desc); details.setText(&quot;hello&quot;); } } }); </code></pre> <p>How can I achieve the same result, but only with the Recycle view?:</p> <pre><code> @Override public void onItemClick(View view, int position) { } </code></pre> <p>I will be very grateful if you can help me!</p> <p>I want to be able to click on the recycler view items in MainActivity.java, I already did it, now I need to be able to do my own actions on each line sorted using equals</p> <pre><code> ArrayList&lt;String&gt; animalNames = new ArrayList&lt;&gt;(); animalNames.add(&quot;Dog&quot;); animalNames.add(&quot;Cow&quot;); animalNames.add(&quot;Camel&quot;); animalNames.add(&quot;Sheep&quot;); animalNames.add(&quot;Goat&quot;); // set up the RecyclerView recyclerView = findViewById(R.id.myList); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new MyRecyclerViewAdapter(this, animalNames); adapter.setClickListener(this); recyclerView.setAdapter(adapter); if (somecode.equals(&quot;Dog&quot;)){ soundPlay(MediaPlayer.create(getBaseContext(), R.raw.star)); } if (somecode.equals(&quot;Camel&quot;)){ soundPlay(MediaPlayer.create(getBaseContext(), R.raw.tick)); } </code></pre>
[ { "answer_id": 74443759, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 2, "selected": false, "text": "sed" }, { "answer_id": 74443843, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 2, "selected": false, "text": "gnu awk" }, { "answer_id": 74444236, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed '1{h;s/.*/sed -n 1F file/e;x};G' file\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19652986/" ]
74,443,516
<p>I have the following signals:</p> <pre><code>logic [X-1:0][Y-1:0] twoDim; logic [(X*Y)-1:0] oneDim; </code></pre> <p>I want to assign the entirety of <code>twoDim</code> to <code>oneDim</code> i.e. if I wrote something like this:</p> <pre><code>assign oneDim = twoDim; </code></pre> <p>And <code>parameter X = 5</code> then I would expect the behaviour to be the same as the following:</p> <pre><code>assign oneDim = { twoDim[4], twoDim[3], twoDim[2], twoDim[1], twoDim[0] }; </code></pre> <p>How would this be accomplished succintly in Synthesizable SystemVerilog for all possible values of X, Y (which are <code>int unsigned</code>) ?</p>
[ { "answer_id": 74443759, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 2, "selected": false, "text": "sed" }, { "answer_id": 74443843, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 2, "selected": false, "text": "gnu awk" }, { "answer_id": 74444236, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed '1{h;s/.*/sed -n 1F file/e;x};G' file\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11127623/" ]
74,443,531
<p>I'm trying to install new dependency to my service,</p> <pre><code>@nest/microservices: ^7.0.3 and got this error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: vb-service-ads@0.0.1 npm ERR! Found: @nestjs/common@8.4.7 npm ERR! node_modules/@nestjs/common npm ERR! @nestjs/common@&quot;^8.4.7&quot; from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer @nestjs/common@&quot;^7.0.0&quot; from @nestjs/microservices@7.6.18 npm ERR! node_modules/@nestjs/microservices npm ERR! @nestjs/microservices@&quot;^7.0.3&quot; from the root project npm ERR! </code></pre> <p>so versions of packages with problem are:</p> <pre><code>&quot;@nestjs/common&quot;: &quot;^8.4.7&quot;, &quot;@nestjs/core&quot;: &quot;^7.6.15&quot; </code></pre> <p>I tried to upgrade versions of core and microservices dependencies to ^8.0.0, and got more dependencies broken and also tried to downgrade common to ^7.6.15 and got same effect. Tried to use yarn instead of npm, it resolved my problem, but i need all packages to be installed by npm</p> <p><a href="https://i.stack.imgur.com/YEwha.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YEwha.png" alt="" /></a></p>
[ { "answer_id": 74443759, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 2, "selected": false, "text": "sed" }, { "answer_id": 74443843, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 2, "selected": false, "text": "gnu awk" }, { "answer_id": 74444236, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed '1{h;s/.*/sed -n 1F file/e;x};G' file\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508564/" ]
74,443,544
<pre><code>enum TokenType{ Eof, Ws, Unknow, //lookahead 1 char If,Else, Id, Int, //lookahead 2 chars Eq,Ne,Lt,Le,Gt,Ge, //lookahead k chars Real, Sci }; class Token{ private: TokenType token; string text; public: Token(TokenType token,string text):token(token),text(text){}; static Token eof(Eof,&quot;Eof&quot;); }; </code></pre> <p>In this code I want to create a Token Object eof, but when I compile it it tells me that the Eof is not a Type. Why?</p> <p>When I use <code>TokenType token=TokenType::Eof</code> it works. But when I passed the Eof into the constructor as a parameter, an error occurred. How could I solve it? Is it related to the scope. I try to use <code>TokenType::Eof</code> as the parameter also fail.</p>
[ { "answer_id": 74443672, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 1, "selected": false, "text": "{}" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18518806/" ]
74,443,635
<p>I am using github api and got the content of manifest.json file.</p> <p>I am trying to add some new json lines into that existing json folder.</p> <p>This the old content which is existing</p> <pre><code> { &quot;short_name&quot;: &quot;React App&quot;, &quot;name&quot;: &quot;Create React App Sample&quot;, &quot;icons&quot;: [ { &quot;src&quot;: &quot;favicon.ico&quot;, &quot;sizes&quot;: &quot;64x64 32x32 24x24 16x16&quot;, &quot;type&quot;: &quot;image/x-icon&quot; }, { &quot;src&quot;: &quot;logo192.png&quot;, &quot;type&quot;: &quot;image/png&quot;, &quot;sizes&quot;: &quot;192x192&quot; }, { &quot;src&quot;: &quot;logo512.png&quot;, &quot;type&quot;: &quot;image/png&quot;, &quot;sizes&quot;: &quot;512x512&quot; } ], &quot;start_url&quot;: &quot;.&quot;, &quot;display&quot;: &quot;standalone&quot;, &quot;theme_color&quot;: &quot;#000000&quot;, &quot;background_color&quot;: &quot;#ffffff&quot; } </code></pre> <p>this is the expected content output , after adding those new json contents it should look like this</p> <pre><code>{ &quot;short_name&quot;: &quot;React App&quot;, &quot;name&quot;: &quot;Create React App Sample&quot;, &quot;icons&quot;: [ { &quot;src&quot;: &quot;maskable.png&quot;, &quot;sizes&quot;: &quot;280x280&quot;, &quot;type&quot;:&quot;image/png&quot;, &quot;purpose&quot;: &quot;any maskable&quot; }, { &quot;src&quot;: &quot;logo192.png&quot;, &quot;sizes&quot;: &quot;192x192&quot;, &quot;type&quot;: &quot;image/png&quot; }, { &quot;src&quot;: &quot;logo256.png&quot;, &quot;sizes&quot;: &quot;256x256&quot;, &quot;type&quot;: &quot;image/png&quot; }, { &quot;src&quot;: &quot;logo348.png&quot;, &quot;sizes&quot;: &quot;348x348&quot;, &quot;type&quot;: &quot;image/png&quot; }, { &quot;src&quot;: &quot;logo512.png&quot;, &quot;sizes&quot;: &quot;512x512&quot;, &quot;type&quot;: &quot;image/png&quot; } ], &quot;start_url&quot;: &quot;.&quot;, &quot;display&quot;: &quot;standalone&quot;, &quot;theme_color&quot;: &quot;#000000&quot;, &quot;background_color&quot;: &quot;#ffffff&quot; } </code></pre> <p>I tried string.replace but it is not working</p> <pre><code> let newContent = oldContent.replace(`{&quot;src&quot;: &quot;favicon.ico&quot;,&quot;sizes&quot;: &quot;64x64 32x32 24x24 16x16&quot;,&quot;type&quot;: &quot;image/x-icon&quot;},`, `{&quot;src&quot;: &quot;logo256.png&quot;,&quot;sizes&quot;: &quot;256x256&quot;,&quot;type&quot;: &quot;image/png&quot;},{&quot;src&quot;: &quot;logo348.png&quot;,&quot;sizes&quot;: &quot;348x348&quot;, &quot;type&quot;: &quot;image/png&quot;},`); </code></pre>
[ { "answer_id": 74443787, "author": "Rana Muhammad Usama", "author_id": 15159541, "author_profile": "https://Stackoverflow.com/users/15159541", "pm_score": 3, "selected": true, "text": "JSON.parse(filedata)" }, { "answer_id": 74443870, "author": "Uri Loya", "author_id": 6447529, "author_profile": "https://Stackoverflow.com/users/6447529", "pm_score": 0, "selected": false, "text": "var json_object = JSON.parse(`{\"src\": \"favicon.ico\"...`);\n\njson_object.icons = \"{\n \"src\": \"maskable.png\",\n \"sizes\": \"280x280\",\n \"type\":\"image/png\",\n \"purpose\": \"any maskable\"\n}\"\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19672461/" ]
74,443,663
<p>This is in unity 2019.4.40f1. I'm trying to rotate an object toward it's movement direction. However, I noticed that this is inaccurate and in investigating I noticed that the inaccuracy comes from the actual movement amounts. What I mean is, in the code below, <code>delta.y / delta.x</code> prints out different values every loop iteration even though <code>destination</code> does not change. As a result, <code>Atan2</code> of course also returns different results. The error every frame is on the 4th 3rd or 4th decimal place, however, over just a few seconds it adds up because it's not random variation but instead seems to be systematic.</p> <p>Also note that at this stage I'm not actually applying the rotation to the object. My expectation is that the code below should move the object from its position to the destination a little bit every frame, in a straight line. This does appear to be the case visually, but numerically there is enough deviation to cause problems with the angle calculations.</p> <pre><code>IEnumerator TweenFunc (object myObject, Vector2 destination, float speed) { while (condition) { currentPosition = myObject.transform.position; delta = destination - currentPosition; Vector2 dir = delta.normalized; frameTime = TimeManager.FrameTime myObject.transform.Translate(dir.x * frameTime * speed, dir.y * frameTime * speed, 0); Debug.Log(delta.y / delta.x); Debug.Log(Mathf.Rad2Deg* Mathf.Atan2(delta.y, delta.x)); yield return true; } } </code></pre> <p>I would like to keep the angle computation consistent. It is possible to pre-compute the angle once, outside of the loop by computing delta first outside of the loop and then getting the angle before entering the loop. However, this solution is not usable in my use-case because the actual angle computation needs to take place in a different part of the code base that is only aware of <code>dir</code> and <code>speed</code> and not <code>destination</code>.</p> <p>Edit for additional info: When traveling from <code>(1.2, -0.2)</code> to <code>(0.2, -3.2)</code> the angle changes from ~<code>108.43352</code> to <code>108.3664</code>. The true angle should be <code>108.435</code>. While this is only a 10th of a degree, if I actually apply the rotation to the object it becomes visible, especially because most of the change appears to happen toward the end of the movement. I wonder if as dir.x and dir.y go to zero accuracy becomes worse in a systematic way. Also, there is no angle drift when traveling in any of the cardinal directions. There, the accuracy of dir.x and dir.y don't require decimal places since they are either 0 or 1, so that could be what's going on.</p> <p>I wonder if there's a way to deal with this since the ultimate goal is actually a pretty common thing - to rotate the object toward its movement direction.</p>
[ { "answer_id": 74443787, "author": "Rana Muhammad Usama", "author_id": 15159541, "author_profile": "https://Stackoverflow.com/users/15159541", "pm_score": 3, "selected": true, "text": "JSON.parse(filedata)" }, { "answer_id": 74443870, "author": "Uri Loya", "author_id": 6447529, "author_profile": "https://Stackoverflow.com/users/6447529", "pm_score": 0, "selected": false, "text": "var json_object = JSON.parse(`{\"src\": \"favicon.ico\"...`);\n\njson_object.icons = \"{\n \"src\": \"maskable.png\",\n \"sizes\": \"280x280\",\n \"type\":\"image/png\",\n \"purpose\": \"any maskable\"\n}\"\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/923757/" ]
74,443,676
<p>I have an array of objects. The object contains two enteries I want to delete one entry and refresh the page with only one entry loading on the page. <a href="https://i.stack.imgur.com/7Y3pv.png" rel="nofollow noreferrer">array</a> the form looks like <a href="https://i.stack.imgur.com/BrZHn.png" rel="nofollow noreferrer">this</a> The array looks like this and the data on my page looks like <a href="https://i.stack.imgur.com/GAdde.png" rel="nofollow noreferrer">this</a>. The functionality I want is if I click on any entry it deletes one entry only and refreshes with the remaining three entries. If I click one the other entries two three and four should be visible and one deleted</p> <p>Currently, if I click on one entry to delete it deletes both entries from the current searched index if the id matches.</p> <pre><code>const [standup, setStandup] = useState({ yesterday: { entry:&quot;&quot;, id:&quot;&quot; }, today: { entry:&quot;&quot;, id:&quot;&quot; } }); </code></pre> <pre><code> const [allStandups, setAllStandups] = useState([]); </code></pre> <p>checked here to delete only entries from yesterday but it is deleting the whole index both entries inside the id.</p> <pre><code>function deleteItem(id) { setAllStandups((prevStandup)=&gt;{ return prevStandup.filter((standup) =&gt; { return (standup.yesterday.id !== id; }); }) } </code></pre> <p><a href="https://i.stack.imgur.com/GbK7H.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GbK7H.gif" alt="result I'm getting" /></a></p>
[ { "answer_id": 74443787, "author": "Rana Muhammad Usama", "author_id": 15159541, "author_profile": "https://Stackoverflow.com/users/15159541", "pm_score": 3, "selected": true, "text": "JSON.parse(filedata)" }, { "answer_id": 74443870, "author": "Uri Loya", "author_id": 6447529, "author_profile": "https://Stackoverflow.com/users/6447529", "pm_score": 0, "selected": false, "text": "var json_object = JSON.parse(`{\"src\": \"favicon.ico\"...`);\n\njson_object.icons = \"{\n \"src\": \"maskable.png\",\n \"sizes\": \"280x280\",\n \"type\":\"image/png\",\n \"purpose\": \"any maskable\"\n}\"\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13248434/" ]
74,443,697
<p>Is it possible to use tshark to check whether one or more ip addresses appear in a pcap file? I know that I can display all occurrences with <code>tshark -r infile -w outfile ip.addr==172.26.29.2 || ip.addr==172.26.31.21</code>, but is there an option to not display all (maybe only the first occurrence.)?</p>
[ { "answer_id": 74452332, "author": "Christopher Maynard", "author_id": 2755698, "author_profile": "https://Stackoverflow.com/users/2755698", "pm_score": 2, "selected": true, "text": "tshark -r infile -Y \"ip\" -T fields -e ip.src > infile_ips.txt" }, { "answer_id": 74486039, "author": "user16139739", "author_id": 16139739, "author_profile": "https://Stackoverflow.com/users/16139739", "pm_score": 0, "selected": false, "text": "tshark -q -z endpoints,ip -z endpoints,ipv6 -r infile\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19541338/" ]
74,443,739
<p>So I have a banner section wherein I want an image to be the background of the banner. I have tried multiple solutions, read trough other people having similar issues and none of them worked for me... im trying to set the background image on the section BFinner-Event. I am using shopify and have uploaded the image to the assets folder. I have also tried linking the background-image url to (assets/banner.png) but that also didnt work.</p> <p>Here is my code:</p> <pre><code>&lt;section class=&quot;BFinner-Event&quot;&gt; &lt;div class=&quot;BFimgContainer&quot;&gt; {% if section.settings.image != blank %} &lt;img src=&quot;{{ section.settings.image | img_url: '300x300'}}&quot; alt=&quot;img&quot; class=&quot;BFimgContainerimg&quot;&gt; {% else %} {% capture current %}{% cycle 1,2 %}{% endcapture %} {{ 'lifestyle-' | append: current | placeholder_svg_tag: 'placeholder-svg'}} {% endif %} &lt;/div&gt; &lt;input type=&quot;text&quot; value=&quot;15Off&quot; id=&quot;BFdiscountCode&quot; style=&quot;display: none;&quot;&gt; &lt;button class=&quot;BFButton&quot; onclick=&quot;copyDiscount()&quot;&gt;{{section.settings.BFButtonText}}&lt;/button&gt; &lt;div class=&quot;BFtwoContainer&quot;&gt; &lt;div class=&quot;BFthreeContainer&quot;&gt; &lt;div class=&quot;BFfourContainer&quot;&gt; &lt;h1 class=&quot;BFconTitle&quot;&gt;{{section.settings.title}}&lt;/h1&gt; &lt;div style=&quot;color: white;&quot;&gt; {{section.settings.description}} &lt;/div&gt; &lt;a href=&quot;{{section.settings.button_link}}&quot; class=&quot;#&quot;&gt;{{section.settings.button_label}}&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;span class=&quot;copySpan&quot; id=&quot;copied&quot;&gt;&lt;/span&gt; &lt;style&gt; .BFinner-Event { display: flex; align-items: center; justify-content: center; margin-top: 30vh !important; /* background-color: #f2f2f2; */ height: 15vh; /* background: black; */ /* background-image: url ({{ 'banner.png' | asset_img_url: 'original' }}); background-size: cover; */ background-image: url ('banner.png'); } @media only screen and (min-width: 1480px) { .BFtwoContainer { max-width: 60%; } } @media only screen and (max-width: 1479px) { .BFtwoContainer { max-width: 70%; } } @media only screen and (max-width: 1220px) { .BFtwoContainer { max-width: 60%; } } .BFconTitle { margin: 0; color: white; /* display: flex; justify-content: center; */ } .BFimgContainer { height: 175%; transform: scale(1.25); } .BFimgContainerimg { height: 100%; } @media only screen and (min-width: 1040px) and (max-width: 1480px) { .BFinner-Event { height: 20vh; } } @media only screen and (max-width: 640px) { .BFinner-Event { height: 25vh; display: flex; flex-direction: column; } @media only screen and (max-width: 320px) { .BFinner-Event { height: 22vh; } } @media only screen and (max-width: 640px) { .BFButton { transform: translateY(-45%) !important; } } @media only screen and (min-width: 250px) and (max-width: 759px) { .BFtwoContainer { max-width: 90%; margin: 0 10vw 0vh 10vw; } } @media only screen and (max-width: 680px) { .BFtwoContainer { margin: 0 10% 0 0; } } @media only screen and (max-width: 640px) { .BFtwoContainer { top: -5vh; position: relative; margin: 0 5% 0 5%; transform: translateY(20%); } } @media only screen and (max-width: 640px) { .BFconTitle { display: flex; justify-content: center; } } @media only screen and (max-width: 680px) and (min-width: 148px){ .BFimgContainer { position: relative; } } } @media only screen and (max-width: 640px){ .BFimgContainer { height: 70%; top: -5vh; } } &lt;/style&gt; </code></pre>
[ { "answer_id": 74443979, "author": "Noman Yousaf", "author_id": 6547177, "author_profile": "https://Stackoverflow.com/users/6547177", "pm_score": 2, "selected": false, "text": ".yourClass{\n background: url(\"https://tpc.googlesyndication.com/simgad/3248856506927570682\");\n background-repeat: no-repeat;\n background-size: cover;\n}\n" }, { "answer_id": 74443988, "author": "Coolis", "author_id": 9399014, "author_profile": "https://Stackoverflow.com/users/9399014", "pm_score": 3, "selected": true, "text": "background-image: url ('banner.png');\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20261507/" ]
74,443,764
<p>I am working with an old django version, and I can't identify which version of django rest framework I would need for a Django 2.1.5</p> <p>I can't find this information in the official <a href="https://www.django-rest-framework.org/#requirements" rel="nofollow noreferrer">django-rest-framework</a> documentation</p> <p>Thanks</p>
[ { "answer_id": 74443979, "author": "Noman Yousaf", "author_id": 6547177, "author_profile": "https://Stackoverflow.com/users/6547177", "pm_score": 2, "selected": false, "text": ".yourClass{\n background: url(\"https://tpc.googlesyndication.com/simgad/3248856506927570682\");\n background-repeat: no-repeat;\n background-size: cover;\n}\n" }, { "answer_id": 74443988, "author": "Coolis", "author_id": 9399014, "author_profile": "https://Stackoverflow.com/users/9399014", "pm_score": 3, "selected": true, "text": "background-image: url ('banner.png');\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11051541/" ]
74,443,765
<p>I have an api response which contains the amazon aws pdf link. Whenever I try to render that pdf in an iframe it gets downloaded and nothing renders inside the iframe. I don't want to use any external library like ng2-pdf-viewer.</p> <p>Here is my code snippet.</p> <pre><code>&lt;iframe [src]=&quot;pdfPreviewURL&quot; type=&quot;application/pdf&quot;&gt;&lt;/iframe&gt; </code></pre> <p>Here pdfPreviewURL is the response pdf aws pdf file link.</p> <p>Thanks in advance. All suggestions are welcomed.</p>
[ { "answer_id": 74443979, "author": "Noman Yousaf", "author_id": 6547177, "author_profile": "https://Stackoverflow.com/users/6547177", "pm_score": 2, "selected": false, "text": ".yourClass{\n background: url(\"https://tpc.googlesyndication.com/simgad/3248856506927570682\");\n background-repeat: no-repeat;\n background-size: cover;\n}\n" }, { "answer_id": 74443988, "author": "Coolis", "author_id": 9399014, "author_profile": "https://Stackoverflow.com/users/9399014", "pm_score": 3, "selected": true, "text": "background-image: url ('banner.png');\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508907/" ]
74,443,781
<p>I'm trying to write a code where if a following bar of an inside bar didn't break the high or low or both of the previous bar of the inside bar, then that bar should also be marked as an inside bar with different bar colour</p> <p>(<a href="https://i.stack.imgur.com/AMMow.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/AMMow.jpg</a>)</p> <p>For e.g. in the above image after the large red bar there are 3 bars that did not break the high or the low of the red bar, I want to mark them as inside bars</p> <p>As I'm a beginner at pine script and coding altogether I wrote a simple code to identify different bars and it worked except for inside bars. I tried using if function, for loop, custom functions, etc. Either I got an error or some different value altogether.</p> <p>`</p> <pre><code>high_bar = high &gt;= high[1] and low &gt;= low[1] low_bar = high &lt;=high[1] and low &lt;= low[1] inside_bar = high &lt; high[1] and low &gt; low[1] outside_bar = high &gt; high[1] and low &lt; low[1] </code></pre> <p>` I wrote this simple code for other bars but as you can guess it only identifies only first inside bar but not the following bars. If anyone can help me with this problem it'll be much appreciated. Thank you!</p>
[ { "answer_id": 74443979, "author": "Noman Yousaf", "author_id": 6547177, "author_profile": "https://Stackoverflow.com/users/6547177", "pm_score": 2, "selected": false, "text": ".yourClass{\n background: url(\"https://tpc.googlesyndication.com/simgad/3248856506927570682\");\n background-repeat: no-repeat;\n background-size: cover;\n}\n" }, { "answer_id": 74443988, "author": "Coolis", "author_id": 9399014, "author_profile": "https://Stackoverflow.com/users/9399014", "pm_score": 3, "selected": true, "text": "background-image: url ('banner.png');\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20507960/" ]
74,443,793
<p>I have a question about creating an appointment if matches the block date to check weekly in the hr organizer within the start date and stop date then cannot make an appointment. I am using <strong>for each</strong> to loop every week, to detect but cannot work.</p> <p><strong>For the scenario sample (This is what I want the result):</strong></p> <p>In the hr organizer, the admin set the user cannot create an appointment every Tuesday from 5 PM until Wednesday 12 PM, it will start from 22 Nov 2022 until 22 Dec 2022. Means that every week Tuesday from 5 PM until Wednesday 12 PM will block to create appointments until the end of 22 Dec 2022.</p> <p>So now the user needs to create an appointment starting on 22 Nov 2022 at 5:40 PM and ending on 22 Nov 2022 at 6:40 PM. By right between this appointment time it won't let the user create the appointment because it has been blocked by the hr organizer. (**I am facing this problem the condition is not correct in my existing code.)</p> <pre class="lang-html prettyprint-override"><code>formatAptStartDate= 22 Nov 2022 17:40 PM aptEndDate = 22 Nov 2022 18:40 PM formatStartDate = 22 Nov 2022 05:00 PM formatEndDate = 23 Nov 2022 12:00:00 PM stopLastDate = 22 Dec 2022 12:00 PM </code></pre> <p><strong>Existing sample code: (This code is not working meet what I mentioned in the above requirements)</strong></p> <pre class="lang-html prettyprint-override"><code>if (repeatType == &quot;Weekly&quot;) { int weekDayNumberAptStartDate = (int)(formatAptStartDate.DayOfWeek + 6) % 7; int weekDayNumberStartDate = (int)(formatStartDate.DayOfWeek + 6) % 7; int weekDayNumberEndDate = (int)(formatEndDate.DayOfWeek + 6) % 7; if (weekDayNumberAptStartDate &gt;= weekDayNumberStartDate &amp;&amp; weekDayNumberAptStartDate &lt;= weekDayNumberEndDate) { if (formatStopLastDate.Date &gt;= formatAptStartDate.Date &amp;&amp; formatStartDate.Date &lt;= formatAptStartDate.Date) { for (DateTime dt = formatStartDate; dt &lt;= stopLastDate; dt = dt.AddDays(7)) { if (formatAptEndDate &lt; dt || formatAptStartDate &gt; formatEndDate) { orgTimeSlot.IsAvailable = true; orgTimeSlot.StartDate = null; orgTimeSlot.StopDate = null; continue; } else { orgTimeSlot.IsAvailable = false; orgTimeSlot.StartDate = formatStartDate; orgTimeSlot.StopDate = formatEndDate; break; } } } } } </code></pre> <p><strong>Remark</strong></p> <p><code>orgTimeSlot.IsAvailable = true;</code> means that if not match the hr organizer block date, it will let the user create an appointment, else if <code>orgTimeSlot.IsAvailable = false;</code> means that the user cannot create an appointment.</p> <p>Hope someone can guide or show me how to solve this problem and can meet the requirements.</p>
[ { "answer_id": 74443979, "author": "Noman Yousaf", "author_id": 6547177, "author_profile": "https://Stackoverflow.com/users/6547177", "pm_score": 2, "selected": false, "text": ".yourClass{\n background: url(\"https://tpc.googlesyndication.com/simgad/3248856506927570682\");\n background-repeat: no-repeat;\n background-size: cover;\n}\n" }, { "answer_id": 74443988, "author": "Coolis", "author_id": 9399014, "author_profile": "https://Stackoverflow.com/users/9399014", "pm_score": 3, "selected": true, "text": "background-image: url ('banner.png');\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14562541/" ]
74,443,801
<p>I'm using angular material formfield with suffix dropdowns with units like cm,mm,etc..,In that I need a value of given number as input and suffix selected dropdowns value in one formcontrolName ,Here its my code.</p> <pre><code>&lt;mat-form-field class=&quot;flex &quot;&gt; &lt;mat-label&gt;Width&lt;/mat-label&gt; &lt;input matInput [formControlName]=&quot;'width'&quot; type=&quot;number&quot; autocomplete=&quot;off&quot;&gt; &lt;mat-select matSuffix &gt; &lt;ng-container *ngFor=&quot;let unit of unitArray&quot; &gt; &lt;mat-option [value]=&quot;unit&quot; &gt;{{unit}}&lt;/mat-option&gt; &lt;/ng-container&gt; &lt;/mat-select&gt; &lt;/mat-form-field&gt; unitArray = ['pt','cm','mm','in','pi'] </code></pre>
[ { "answer_id": 74443979, "author": "Noman Yousaf", "author_id": 6547177, "author_profile": "https://Stackoverflow.com/users/6547177", "pm_score": 2, "selected": false, "text": ".yourClass{\n background: url(\"https://tpc.googlesyndication.com/simgad/3248856506927570682\");\n background-repeat: no-repeat;\n background-size: cover;\n}\n" }, { "answer_id": 74443988, "author": "Coolis", "author_id": 9399014, "author_profile": "https://Stackoverflow.com/users/9399014", "pm_score": 3, "selected": true, "text": "background-image: url ('banner.png');\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19240119/" ]
74,443,848
<p>I have a parent game object that has 20 child objects. Few of them are active and rest are inactive. How do I check my if statement for the 5 and less active child objects? Currently it is just counting the child count irrespective active/inactive state of them.</p> <pre><code>void Start () { //Active Child count if (this.transform.childCount &lt;= 5) { } } </code></pre>
[ { "answer_id": 74443979, "author": "Noman Yousaf", "author_id": 6547177, "author_profile": "https://Stackoverflow.com/users/6547177", "pm_score": 2, "selected": false, "text": ".yourClass{\n background: url(\"https://tpc.googlesyndication.com/simgad/3248856506927570682\");\n background-repeat: no-repeat;\n background-size: cover;\n}\n" }, { "answer_id": 74443988, "author": "Coolis", "author_id": 9399014, "author_profile": "https://Stackoverflow.com/users/9399014", "pm_score": 3, "selected": true, "text": "background-image: url ('banner.png');\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17561671/" ]
74,443,863
<pre><code>@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode = 1 &amp;&amp; resultCode = RESULT_OK &amp;&amp; data!=null){ imagePath = data.getData(); getImageinImageView(); } }` </code></pre> <p>I don't understand why it gives me this error.</p> <p>I'm trying to make a profile picture changer and when the picture is selected, it shows the new profile picture.</p>
[ { "answer_id": 74443935, "author": "Ahmet Emin Saglik", "author_id": 12879242, "author_profile": "https://Stackoverflow.com/users/12879242", "pm_score": 1, "selected": false, "text": "requestCode = 1" }, { "answer_id": 74444024, "author": "cyberbrain", "author_id": 2846138, "author_profile": "https://Stackoverflow.com/users/2846138", "pm_score": 0, "selected": false, "text": "requestCode = 1 && resultCode = RESULT_OK && data!=null" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19601109/" ]
74,443,889
<p>Objective: Copy all files from multiple subfolders into one folder with same filenames. E.g.</p> <pre><code>Source Root Folder 20221110/ AppID1 File1.csv File2.csv /AppID2 File3.csv File4.csv 20221114 AppID3 File5.csv File6.csv and so on Destination Root Folder File1.csv File2.csv File3.csv File4.csv File5.csv File6.csv </code></pre> <p>Approach 1 Azure Data Factory V2 All datasets selected as binary</p> <ol> <li>GET METADATA - CHILDITEMS</li> <li>FOR EACH - Childitem</li> <li>COPY ACTIVITY(RECURSIVE : TRUE, COPY BEHAVIOUR: FLATTEN)</li> </ol> <p>This config renames the files with autogenerated names. If I change the copy behaviour to preserve hierarchy, Both file name and folder structure remains intact.</p> <p>Approach 2</p> <ol> <li>GET METADATA - CHILDITEMS</li> <li>FOR EACH - Childitems</li> <li>Execute PL2 (Pipeline level parameter: @item.name)</li> <li>Get Metadata2 (Parameterised from dataset, invoked at pipeline level)</li> <li>For EACH2- Childitems</li> <li>Copy (Source: FolderName - Pipeline level, File name - ForEach2)</li> </ol> <p>Both approaches not giving the desired output. Any help/Workaround would be appreciated.</p>
[ { "answer_id": 74443935, "author": "Ahmet Emin Saglik", "author_id": 12879242, "author_profile": "https://Stackoverflow.com/users/12879242", "pm_score": 1, "selected": false, "text": "requestCode = 1" }, { "answer_id": 74444024, "author": "cyberbrain", "author_id": 2846138, "author_profile": "https://Stackoverflow.com/users/2846138", "pm_score": 0, "selected": false, "text": "requestCode = 1 && resultCode = RESULT_OK && data!=null" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19128300/" ]
74,443,899
<p>This question follows a previous one that I asked : <a href="https://stackoverflow.com/questions/74156698/trust-querying-event-in-ethereum">Trust Querying Event in Ethereum</a>.</p> <p>In my back-end I listen for an event after a specific transaction. My back-end get the event just after the transaction is added to a new block. However to be sure that the block will not be removed we need to wait that its statut becomes 'finalized'.</p> <p>My question is : how can I manage to do it using ethersjs ?</p> <p>Thanks,</p>
[ { "answer_id": 74443935, "author": "Ahmet Emin Saglik", "author_id": 12879242, "author_profile": "https://Stackoverflow.com/users/12879242", "pm_score": 1, "selected": false, "text": "requestCode = 1" }, { "answer_id": 74444024, "author": "cyberbrain", "author_id": 2846138, "author_profile": "https://Stackoverflow.com/users/2846138", "pm_score": 0, "selected": false, "text": "requestCode = 1 && resultCode = RESULT_OK && data!=null" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18234651/" ]
74,443,937
<p>Actually, I'm learning DOM Manipulation. As you can see, I created the li element but the issue is it is not applying the fontSize to the li.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const title = document.querySelector("#main-heading"); title.style.color = "red"; const listItems = document.querySelectorAll(".list-items"); for (i = 0; i &lt; listItems.length; i++) { listItems[i].style.fontSize = "2rem"; } const ul = document.querySelector("ul"); const li = document.createElement("li"); ul.append(li); li.innerText = "X-men" li.setAttribute('class' , 'list-items' ) </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div class="container"&gt; &lt;h1 id="main-heading"&gt;Favourite Movie&lt;/h1&gt; &lt;ul&gt; &lt;li class="list-items"&gt;The Matric&lt;/li&gt; &lt;li class="list-items"&gt;Star Wars&lt;/li&gt; &lt;li class="list-items"&gt;Harry Potter&lt;/li&gt; &lt;li class="list-items"&gt;Lord of the Rings&lt;/li&gt; &lt;li class="list-items"&gt;Marvel&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74443996, "author": "Maniraj Murugan", "author_id": 7785337, "author_profile": "https://Stackoverflow.com/users/7785337", "pm_score": 1, "selected": true, "text": "for" }, { "answer_id": 74444082, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 1, "selected": false, "text": ".list-items" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74443937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20183342/" ]