WPF Radio Button style to fill its background with image on selection Posted: 30 Mar 2021 10:31 AM PDT I am relatively new with WPF applications and after so many attempts still unable to achieve this. A guidance to this would be awesome ! |
Where do Sass arguments/variables come from? Posted: 30 Mar 2021 10:30 AM PDT I'm learning Sass (and JavaScript as well). I'm a bit confused on the variables used in arguments when writing a mixin. In the code below, after the mixin name we have the arguments, which I understand are variables ($image, $direction). What I'm confused about is - I believe (for example) $image and $direction are not random names/values - are these what they call SassExpressions? And is there a library or list of these somewhere? Does $direction refer to flex-direction? And $image refers to background image? Are these just CSS properties but with a shorthand? Sorry for the very newb question. @mixin replace-text($image, $direction) |
where is token stored in backend, when we use mern stack? Posted: 30 Mar 2021 10:30 AM PDT Using django-rest-framework, when we use token authentication, one separate table is created for token and user mapping? How or where are token stored when we use jsonwebtoken in nodejs, express, mongoose? |
MPL ANN in OpenCV Posted: 30 Mar 2021 10:30 AM PDT I´m working on MLP network in emgucv. as I finished parsing mnist dataset into trainData and trainLabels and while tried to train ne network I ran into a problem, ERROR MESSAGE :"'OpenCV: output training data should be a floating-point matrix with the number of rows equal to the number of training samples and the number of columns equal to the size of last (output) layer'" Any help would be greatly appreciated as I´m out of ideas how to fix this. This is my train data: Matrix trainData; -- it is a float[42000,784] .... This is is trainLabels: Matrix trainLabels; -- it is a int[42000,1] this is code of my MLP: Matrix layerSize = new Matrix(new int[] { 2828, 2020, 10}); ANN_MLP network = new ANN_MLP(); network.SetLayerSizes(layerSize); network.SetActivationFunction(ANN_MLP.AnnMlpActivationFunction.SigmoidSym, 0, 0); network.TermCriteria = new MCvTermCriteria(100, 1e-6); network.SetTrainMethod(ANN_MLP.AnnMlpTrainMethod.Backprop, 0.1, 0.1); return network; Both trainData and trainLabels are matching with their row count... I have 10 output neurons for each class (mnist classifying numbers from 0-9) my trainLabels holds exactly 1 int number as label for specific row ... I really have no idea why it is not working. |
Module '"bootstrap"' has no exported member 'Bootstrap' Posted: 30 Mar 2021 10:30 AM PDT I am getting this error when trying to import the Bootstrap Module: '"bootstrap"' has no exported member 'Bootstrap'. Notsure how to resolve. import { Bootstrap } from 'bootstrap'; |
WPF AutoComplete TextBox with Append Posted: 30 Mar 2021 10:30 AM PDT So, I know there's quite a few posts on here with a similar question, but most of them are at least a decade old. The ones which are relatively new, don't give me what I am looking for. Here's what I am looking for. I want a textbox that can mimic the "TO" field in the Outlook Email Compose window. I want it to be able to allow to autocomplete multiple email addresses. Some of the solutions I found allow autocomplete for only 1 entry and after that, it stops. There are third party tools out there like SyncFusion, but it's expensive. Here are some of the solutions I looked at: Post1 Post2 Post3 Post4 Any suggestions please? |
Can't see apache in services list Posted: 30 Mar 2021 10:30 AM PDT I am trying to stand my laravel project up succesfully. To do this,I did all changings in conf files. As last operation,I should restart the server to let changings valid. (Using xampp) But the problem is that I couldn't find apache service in services list. I've tried to restart server from xampp. But still couldn't reach to laravel page. What am I doing wrong? |
Right way to performance test scenarios in Jmeter Posted: 30 Mar 2021 10:30 AM PDT Im currently load testing an application which includes scenarios such as login, create ticket, modify ticket, search ticket and log out. I used http recorder to record samplers and can replay the test for the required number of users But the problem is when I look at the results, the response times I see would correspond to the end to end scenario which is in the order of multiple seconds. Eg: loading home page takes 5 seconds because it authenticates the user login and loads the appropriate home page. But when someone sees the response times they would wonder why it takes 5 seconds just to load the home page and might end up saying the application performance is poor. I don't know if I'm doing the right way to load test application scenarios. Should I remove the samplers that aren't directly making calls to the authenticate or such scenario related requests? Or should I keep them but clearly articulate in my report the fact that it's all end to end times for a scenario as it'd load during ui interaction? How to determine the performance of the solution in this case? Please can someone guide me. |
How do you correctly cleanup and re-use SysV shared memory segments? Posted: 30 Mar 2021 10:30 AM PDT I have been writing some gnarly test code for an API that uses the Linux SysV SHM interface. i.e. ftok(), shmget(), shmctl(), shmat() Unfortunately I am not free to alter this interface (for example to use shm_open() instead or nuke it from orbit). I discovered a bug via an integration test which spawns two unrelated processes using the shared memory in that it was not cleaning up shared memory segments using shmdt(). I further discovered that the convention is to use: shmctl(segmentId, IPC_RMID, 0); to tell the system that the segment can be deleted once all processes have detached. Adding this to the integration tests fixed the bug that the shared memory was not cleaned up. Looking at segments using ipcs -m you can see they are now marked "dest". I have also created lower-level 'unit' tests which work by forking a child process to create the shared memory. Attempting to apply the same correction to the test code I have some strange observations: If I do the right thing and add calls to shmctl(segmentId, IPC_RMID) the tests stop working. If I remove such calls the tests start working again. (for now my solution is simply not to use IPC_RMID in the unit test code) I'm not sure if this is the problem but, investigating further due to ftok() being collision prone the same Id is used for some tests after a previous test has deleted it. This is not the case for every failure though. If I change from O_CREAT to O_CREAT|O_EXCL opening re-using the same token fails with EEXIST. (suggesting 'dest' segments still exist in some sense and can be re-used) I also notice that from running many tests I have a fair number of shm segments listed as "dest" but with nattach=2 meaning two processes failed to call shmdt(). If I list the pids that supposedly created it and last used it using ipcs -mp they are not the processes that created or used it. Instead they belong to things like firefox which is just slightly confusing! I don't understand this. Presumably they will disappear on reboot but they don't seem directly related to this issue. I think these came killing the earlier integration tests before I fixed the missing shmdt() and shmctl(IPC_RMID) issues. Many segments listed by ipcs -m have a key of 0x00000000 which seems suspicious. Q Is there something special about how (sysV) SHM works in the context of parent and child processes which means the IPC_RMID behaves differently and or is not required? Q Is there programmatic way to make it safe to re-use a segment Id after having 'removed' it using IPC_RMID a short while previously in a child process? Q Is there a way to force removal (unattach / delete) the segments marked dest in "ipcs -m" without rebooting? (at the OS level) Q Is "ipcs -pm" displaying actual pid's or something else? Is there another way to find out what the system thinks is really still attached? (I believe nothing is as I used kill -9 on everything using the SHM interface) Q Is there a way to force detach a process as if shmdt() has been called? |
Make a new bool column based on substring value in another column Posted: 30 Mar 2021 10:30 AM PDT Suppose I have the following data frame, df = pd.DataFrame({'col1':['hello today is a good day','today was good, hello?','today was ok'], 'col2':[1,2,3]}) that is col1 col2 0 hello today is a good day 1 1 today was good, hello? 2 2 today was ok 3 I want to make a new bool column where the value is true when we have hello in col1 and false when there is no hello in col1 . The desired df should look like: col1 col2 is there hello? 0 hello today is a good day 1 True 1 today was good, hello? 2 True 2 today was ok 3 False I've tried doing: df['is there hello?'] = df[df['col1'].str.contains("hello")].notnull().astype('bool') but this seem not to work as the shapes are not matching, I wonder what am I doing wrong? |
How to list all guild memebers in discord.js v12 Posted: 30 Mar 2021 10:30 AM PDT I'm trying to list all users from specified server on bot start, I'm using discord.js v12.5.1 const guild = client.guilds.cache.find(g => g.id === "my guild id"); guild.members.forEach(member => console.log(member.username)); error I receive: guild.members.forEach(member => console.log(member)); ^ TypeError: Cannot read property 'members' of undefined |
how to create boost::asio server that listen to two different ports Posted: 30 Mar 2021 10:30 AM PDT I'm using boost 1.75.0 and I'm trying to update my server so he can listen to two different ports at the same time let's say IP 127.0.0.1 port 6500 and port 6600. do I need to hold in the Server two sockets? this is my server #include <boost/asio/io_service.hpp> #include <boost/asio.hpp> #include <queue> #include "Session.h" using boost::asio::ip::tcp; class Server { public: Server(boost::asio::io_service &io_service, short port) : acceptor_(io_service, tcp::endpoint(tcp::v4(), port)), socket_(io_service) { do_accept(); } private: void do_accept(){ acceptor_.async_accept(socket_, [this](boost::system::error_code ec) { if (!ec) { std::cout << "accept connection\n"; std::make_shared<Session>(std::move(socket_))->start(); } do_accept(); }); } tcp::acceptor acceptor_; tcp::socket socket_; }; this is my Session class #include <boost/asio/io_service.hpp> #include <boost/asio.hpp> #include "message.h" #include <fstream> #include <boost/bind/bind.hpp> namespace { using boost::asio::ip::tcp; auto constexpr log_active=true; using boost::system::error_code; using namespace std::chrono_literals; using namespace boost::posix_time; }; class Session : public std::enable_shared_from_this<Session> { public: Session(tcp::socket socket) : socket_(std::move(socket)) , { } ~Session()= default; void start(); void do_write_alive(); private: void do_read_header(); void do_read_body(); void do_write(); using Strand = boost::asio::strand<tcp::socket::executor_type>; using Timer = boost::asio::steady_timer; tcp::socket socket_{strand_}; Strand strand_{make_strand(socket_.get_executor())}; Timer recv_deadline_{strand_}; Timer send_deadline_{strand_}; enum { max_length = 1024 }; char data_[max_length]; }; I didn't include the implementation of the Session class only the constructor because there not relevant. |
Applying DuplicateMessageFilter to slack appender in logback Posted: 30 Mar 2021 10:31 AM PDT My Application uses logback for logging and use logback-slack-appender to post only error level log events to slack channel. I want to apply a duplicate message filter to the slack appender so that we don't get very large number of repetitive alerts in some application error scenarios. I found a turbofilter called DuplicateMessageFilter which can be applied to logcontext level but it cannot be applied to appender.How can I implement duplicate message filtering at the appender level? Is it possible? |
Merge cells of tables in the header in Word VBA Posted: 30 Mar 2021 10:30 AM PDT I would like to merge two cells of the second table in the header of my Word document. I created the script below but it has a run-time error: '5491'.The requested member of the collection does not exist. The error occured on this line" With xTable(2)" Sub mergercells() Set xTable = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Tables With xTable(2) .Cell(Row:=3, Column:=2).Merge _ MergeTo:=.Cell(Row:=3, Column:=1) .Borders.Enable = False End With End Sub Thanks, |
Zero initialization of std::vector<std::array<double,10>> Posted: 30 Mar 2021 10:30 AM PDT Consider the following code std::vector<std::array<double,10>> a(10); If I understand the standard correctly a will not be zero initialized, because en.cppreference.com on std::vector constructors says - Constructs the container with count default-inserted instances of T. No copies are made.
So because default initializing std::array<double, 10> does not fill it with zeros, a will also not contain zeros. Is this true? How can I enforce zero initialization? Will a.data() point to 100 continuous double values? Edit: This is the output from godbolt on gcc 10.2 with -O2 main: mov edi, 800 sub rsp, 8 call operator new(unsigned long) mov rdi, rax lea rdx, [rax+800] .L2: mov QWORD PTR [rax], 0x000000000 add rax, 80 mov QWORD PTR [rax-72], 0x000000000 mov QWORD PTR [rax-64], 0x000000000 mov QWORD PTR [rax-56], 0x000000000 mov QWORD PTR [rax-48], 0x000000000 mov QWORD PTR [rax-40], 0x000000000 mov QWORD PTR [rax-32], 0x000000000 mov QWORD PTR [rax-24], 0x000000000 mov QWORD PTR [rax-16], 0x000000000 mov QWORD PTR [rax-8], 0x000000000 cmp rdx, rax jne .L2 mov esi, 800 call operator delete(void*, unsigned long) xor eax, eax add rsp, 8 ret So it does seems to be zero initialized. Then the question remains why. |
Heroku não carrega a aplicação, página branca Posted: 30 Mar 2021 10:30 AM PDT I have a application in Vue.js that im trying to deploy on Heroku. The build and deploy were successfull, didnt return any errors. But, when i open it on the browser, there are no componentes, only a blank page. The title its different to, as you can see at this image: Browser image At Heroku heroku log --tail i get this message: Heroku log image I believe that the problem is on the deploy, as locally in my machine its working correctly. But i didnt understand the error and dont know how to solve it. |
ASP.NET API failing to publish on azure Posted: 30 Mar 2021 10:30 AM PDT I'm trying to publish an C# API to azure, I followed all the steps in this documentation here but for some reason when I publish the application the build succeeds and crashes when this below line gets executed Generating swagger file to 'C:\Users\user\Projs\API\bin\Release\netcoreapp3.1\swagger.json'. and the only error log that gets printed is Failed to generate swagger file. Error dotnet swagger tofile --serializeasv2 --output "C:\Users\user\Downloads\Projs\API\bin\Release\netcoreapp3.1\swagger.json" "C:\Users\user\Downloads\Projs\API\bin\Release\netcoreapp3.1\API.dll" v1 Unhandled exception. System.IO.FileLoadException: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest definition does not match the assembly reference. (0x80131040) File name: 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Be sure that the Startup.cs for your application is calling AddSwaggerGen from within ConfigureServices in order to generate swagger file. Visit https://go.microsoft.com/fwlink/?LinkId=2131205&CLCID=0x409 for more information. This is my startup.cs public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc( "v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" }); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseSwagger(c => { c.SerializeAsV2 = true; }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/swagger.json", "MyAPI V1"); }); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } This is my .csproj file <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <UseNETCoreGenerator>true</UseNETCoreGenerator> <UserSecretsId>d844b2a8-00b0-473d-8f97-9dca9f2899bd</UserSecretsId> </PropertyGroup> <PropertyGroup Condition="'$(TargetFramework)' == 'net45'"> <AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects> </PropertyGroup> <ItemGroup> <Folder Include="Model\" /> <Folder Include="Context\" /> <Folder Include="Contracts\ServiceResponse\" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNet.SignalR" Version="2.4.1" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.13" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.13" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.11"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.10" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.11"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="AutoMapper" Version="10.1.1" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.2.4" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" /> <PackageReference Include="System.Runtime" Version="4.3.1" /> </ItemGroup> </Project> I have tried solutions from these links but none of them worked Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies https://github.com/Azure/azure-functions-vs-build-sdk/issues/160 Could not load file or assembly 'System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Is there a way to fix this? |
Twincat C++ - Visual studio configuration error Posted: 30 Mar 2021 10:30 AM PDT I am trying to write C++ projects in Twincat, but I get the following error during building. I have followed the steps mentioned here till the end and has configured WINDDK7 variable in my system environment settings. I do not understand why the build throws error even though the configuration is correct. Can somebody please help? P.S I am a beginner in Twincat. |
ESP8266 is reset while overwriting the existing database Posted: 30 Mar 2021 10:30 AM PDT If the test program is started by deleting (resetting) the database file each time it is run, the procedures are working. /* This creates two empty databases, populates values, and retrieves them back from the SPIFFS file system. */ #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> #include <vfs.h> #include <SPI.h> #include <FS.h> extern "C" { #include "user_interface.h" } #include <ESP8266WiFi.h> sqlite3* db1; void WiFiOff() { wifi_station_disconnect(); wifi_set_opmode(NULL_MODE); wifi_set_sleep_type(MODEM_SLEEP_T); wifi_fpm_open(); wifi_fpm_do_sleep(0xFFFFFFF); } const char* data = "Callback function called"; static int callback(void* data, int argc, char** argv, char** azColName) { int i; Serial.printf("%s: ", (const char*)data); for (i = 0; i < argc; i++) { Serial.printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } Serial.printf("\n"); return 0; } int db_open(const char* filename, sqlite3** db) { int rc = sqlite3_open(filename, db); if (rc) { Serial.printf("Can't open database: %s\n", sqlite3_errmsg(*db)); return rc; } else { Serial.printf("Opened database successfully\n"); } return rc; } char* zErrMsg = 0; int db_exec(sqlite3* db, const char* sql) { Serial.println(sql); long start = micros(); int rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if (rc != SQLITE_OK) { Serial.printf("SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { Serial.printf("Operation done successfully\n"); } Serial.print(F("Time taken:")); Serial.println(micros() - start); return rc; } void OpenDatabase(); void CreateTable(); void InsertValues(); void SelectValues(); void setup() { Serial.begin(74880); system_update_cpu_freq(SYS_CPU_160MHZ); WiFiOff(); if (!SPIFFS.begin()) { Serial.println("Failed to mount file system"); return; } // list SPIFFS contents Dir dir = SPIFFS.openDir("/"); while (dir.next()) { String fileName = dir.fileName(); size_t fileSize = dir.fileSize(); Serial.printf("FS File: %s, size: %ld\n", fileName.c_str(), (long)fileSize); } Serial.printf("\n"); // remove existing file SPIFFS.remove("/test1.db"); sqlite3_initialize(); OpenDatabase(); CreateTable(); InsertValues(); SelectValues(); */ // list SPIFFS contents dir = SPIFFS.openDir("/"); while (dir.next()) { String fileName = dir.fileName(); size_t fileSize = dir.fileSize(); Serial.printf("FS File: %s, size: %ld\n", fileName.c_str(), (long)fileSize); } Serial.printf("\n"); } void loop() { } void OpenDatabase() { int rc; // Open databases File db_file_obj_1; vfs_set_spiffs_file_obj(&db_file_obj_1); if (db_open("/test1.db", &db1)) return; } void CreateTable() { int rc; // Create Table rc = db_exec(db1, "CREATE TABLE IF NOT EXISTS test1 (id INTEGER, content);"); if (rc != SQLITE_OK) { sqlite3_close(db1); return; } } void InsertValues() { int rc; // Insert Values rc = db_exec(db1, "INSERT INTO test1 VALUES (1, 'Hello, Hurol from test1');"); if (rc != SQLITE_OK) { sqlite3_close(db1); return; } } void SelectValues() { int rc; // Select Values rc = db_exec(db1, "SELECT * FROM test1"); if (rc != SQLITE_OK) { sqlite3_close(db1); return; } } } deleting the existing database file ... // remove existing file SPIFFS.remove("/test1.db"); But when the INSERT or SELECT procedure is executed on the table created without deleting the existing database, ESP8266 is reset. // remove existing file // SPIFFS.remove("/test1.db"); (If deletion of the existing database file is canceled) How can I get the best document about the reset problem when using ESP8266 and SQLite? Can you please help in this matter? Thank you from now. |
Is there a way to see commit hash instead of HEAD? Posted: 30 Mar 2021 10:30 AM PDT I got conflict: Is there an option to show last commit hash for changes at HEAD (green underline). I expect this: HEAD, 476ce2c Simplify interface: remove 'rs' parameter which will be similar to >>>>>>> section |
Creating a new column with two unique conditions in pandas? Posted: 30 Mar 2021 10:30 AM PDT Trying to figure out something complex with pandas - I have this sample dataframe: Date Value Diff 4/2/2019 17:00 864 57 4/2/2019 17:15 864 0 4/2/2019 17:30 864 0 4/2/2019 17:45 864 0 4/2/2019 18:00 864 0 ... 5/2/2019 07:00 864 0 5/2/2019 07:15 864 0 5/2/2019 07:30 864 0 5/2/2019 07:45 864 0 5/2/2019 08:00 864 0 5/2/2019 08:15 864 0 5/2/2019 08:30 1564 700 5/2/2019 08:45 1784 223 5/2/2019 09:00 1904 120 5/2/2019 09:15 2095 191 5/2/2019 09:30 2095 183 5/2/2019 09:45 2095 85 5/2/2019 10:00 2095 58 5/2/2019 10:15 2095 134 5/2/2019 10:30 2555 78 5/2/2019 10:45 2678 123 5/2/2019 11:00 2777 99 The expected dataframe is this: Date Value Diff NewCol1 4/2/2019 17:00 864 57 57 4/2/2019 17:15 864 0 63.63 4/2/2019 17:30 864 0 63.63 4/2/2019 17:45 864 0 63.63 4/2/2019 18:00 864 0 63.63 ... 5/2/2019 07:00 864 0 63.63 5/2/2019 07:15 864 0 63.63 5/2/2019 07:30 864 0 63.63 5/2/2019 07:45 864 0 63.63 5/2/2019 08:00 864 0 63.63 5/2/2019 08:15 864 0 63.63 5/2/2019 08:30 1564 700 63.63 5/2/2019 08:45 1784 223 223 5/2/2019 09:00 1904 120 120 5/2/2019 09:15 2095 191 191 5/2/2019 09:30 2095 183 183 5/2/2019 09:45 2095 85 85 5/2/2019 10:00 2095 58 58 5/2/2019 10:15 2095 134 134 5/2/2019 10:30 2555 78 78 5/2/2019 10:45 2678 123 123 5/2/2019 11:00 2777 99 99 ... There are two conditions to create the NewCol1 , When Value is repeated, if Diff is 0, and only between time range from 07:00 to 18:00, count the number of 0 + 1 and the difference of the Value and divide it (in this example, (1564 - 864) / 11 ). Take note that the + 1 is to account the row after the last 0 , which is the row at 08:30 and this sort of occurrence will always happen consecutively such as this example patern (example 4/2/2019 17:15 to 5/2/2019 08:30 ) If Value is repeated, and Diff is more than 0, copy the Diff in that row to NewCol1 including the row after the last repeated Value with Diff more than 0 (example 5/2/2019 09:45 to 5/2/2019 10:30 ) Is pandas able to fully do the above conditions to this dataframe? If not, what other Python way can I try? Prefer to avoid if else as efficiently is important since there will be hundred thousands of rows. |
Random numbers with user-defined continuous probability distribution Posted: 30 Mar 2021 10:30 AM PDT I would like to simulate something on the subject of photon-photon-interaction. In particular, there is Halpern scattering. Here is the German Wikipedia entry on it Halpern-Streuung. And there the differential cross section has an angular dependence of (3+(cos(theta))^2)^2. I would like to have a generator of random numbers between 0 and 2*Pi, which corresponds to the density function ((3+(cos(theta))^2)^2)*(1/(99*Pi/4)). So the values around 0, Pi and 2*Pi should occur a little more often than the values around Pi/2 and 3. I have already found that there is a function on how to randomly output discrete values with user-defined probability values numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2]) . I could work with that in an emergency, should there be nothing else. But actually I already want a continuous probability distribution here. I know that even if there is such a Python command where you can enter a mathematical distribution function, it basically only produces discrete distributions of values, since no irrational numbers with 1s and 0s can be represented. But still, such a command would be more elegant with a continuous function. |
Passing Concrete implementation of interface to bundle arguments in fragment Android Posted: 30 Mar 2021 10:30 AM PDT Here is my scenario in Android : There is an sdk .aar where fragment is exposed to be consumed by clients. AAR developers have also exposed us the interface which they want clients to implement. Fragment has some logic encapsulated to call interface methods directly based on some conditions and concrete implementation lies with clients. We both (as client and AAR team) are working on figuring out the way where clients can pass the concrete implementation of interface as bundle arguments in Kotlin using this Best practice for instantiating a new Android Fragment AAR does not understand the concrete implementation class. How to pass Concrete implementation of interface to bundle arguments in fragment Android ''' interface AppInterface { fun getUser(): User } ''' |
Calling solidity smart contract with javascript to mint token does not seem to work Posted: 30 Mar 2021 10:30 AM PDT I have a newby ethereum question--just getting started and trying to understand the Ethereum dev environment. I have a very simple 721 test contract that I deployed to Ropsten and I can use REMIX to use it and it works to mint and to view balance etc. Here is the 'contract' : https://ropsten.etherscan.io/address/0x97E0175415cB7D758cFB0ffc27Be727360664B90 // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@0xcert/ethereum-erc721/src/contracts/tokens/nf-token-metadata.sol"; import "@0xcert/ethereum-erc721/src/contracts/ownership/ownable.sol"; contract Icollect is NFTokenMetadata, Ownable { uint256 public tokenCounter; constructor() NFTokenMetadata () { nftName = "Icollect"; nftSymbol = "ICOL"; tokenCounter = 0; } function mint(string calldata _uri) external onlyOwner { super._mint(msg.sender, tokenCounter); super._setTokenUri(tokenCounter, _uri); tokenCounter = tokenCounter + 1; } } The contract seems to work when I test locally with this test javascript and hardhat async function main() { const contract_address = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; const Icollect = await ethers.getContractFactory("Icollect"); const icollect = await Icollect.attach(contract_address); const mint_return = await icollect.mint("https://test.test"); console.log("mint returned: ", mint_return); console.log("owner:", await icollect.owner()); console.log("owner:", await icollect.ownerOf(0)); console.log("symbol:", await icollect.symbol()); console.log("URI:", await icollect.tokenURI(0)); console.log("token counter:", await icollect.tokenCounter()); } main() .then(() => process.exit(0)) .catch(error => { console.error(error); process.exit(1); }); The PROBLEM: When I try to mint a token from on a web page I can't seem to get the 'mint' transaction to work (when I need gas). However, viewing variables works (like name and owner of contract). Any idea what I'm doing wrong here. const transaction = contract.methods.mint(NFT_URI); I'm building the object, then signing it and then sending it. The transaction seems to work but I don't see the additional token. Here is one of the example 'mint' transaction using code below: https://ropsten.etherscan.io/tx/0x6f3fc389355ffedfe135ac049837ac2d1a6eb6aad1dd10b055addfa70814e0fd But using REMIX to query 'tokenCounter' shows that I never increase the count. document.getElementById('mintbutton').onclick = async function() { let NFT_URI = document.getElementById("nft_uri").value; let contract_address = document.getElementById("contract_address").value; const contract = await new web3.eth.Contract(abi, contract_address); let account_address = document.getElementById("account_address").value; const account = web3.eth.accounts.privateKeyToAccount(privateKey).address; const transaction = contract.methods.mint(NFT_URI); let nonce_count = await web3.eth.getTransactionCount(account_address); //build the transaction const txObject = { nonce: nonce_count, to: account_address, //value: web3.utils.toHex(21000), //gasLimit: web3.utils.toHex(1000000), gasPrice: web3.utils.toHex(web3.utils.toWei('10','gwei')), gas: await transaction.estimateGas({from: account}), data: transaction.encodeABI() }; const signed = await web3.eth.accounts.signTransaction(txObject, privateKey); const return_from_send = await web3.eth.sendSignedTransaction(signed.rawTransaction); return_string = "blockHash: " + return_from_send.blockHash + "<br>" + "blockNumber: <a href='https://ropsten.etherscan.io/block/" + return_from_send.blockNumber + "'>" + return_from_send.blockNumber + "</a><br>" + "contractAddress: " + return_from_send.contractAddress + "<br>" + "cumulativeGasUsed: " + return_from_send.cumulativeGasUsed + "<br>" + "from: <a href='https://ropsten.etherscan.io/address/" + return_from_send.from + "'>" + return_from_send.from + "</a><br>" + "gasUsed: " + return_from_send.gasUsed + "<br>" + "status: " + return_from_send.status + "<br>" + "to: <a href='https://ropsten.etherscan.io/address/" + return_from_send.to + "'>" + return_from_send.to + "</a><br>" + "transactionHash: <a href='https://ropsten.etherscan.io/tx/" + return_from_send.transactionHash + "'>" + return_from_send.transactionHash + "</a><br>" + "transactionIndex: " + return_from_send.transactionIndex + "<br>" + "type: " + return_from_send.type + "<br>"; $('#mint_return').html(return_string); var x = document.getElementById("showDIV3"); x.style.display = "block"; } Patrick - here is a link to the console.log https://imgur.com/XBQTAxT |
Chart widget inside the content section (Laravel-backpack) Posted: 30 Mar 2021 10:30 AM PDT Is there any way to put the chart widget inside the content section? I made nav-tabs area and want to put a chart inside one of the tabs. Thank you! What i did: @section('content') <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#home" role="tab" aria-controls="home">Обзор</a></li> <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#profile" role="tab" aria-controls="">Потребление</a></li> <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#messages" role="tab" aria-controls="messages">Расписание</a></li> <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#docs" role="tab" aria-controls="messages">Документация</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="home" role="tabpanel"> <div class="container-fluid"> <div class="animated fadeIn"> <div class="row"> @php Widget::add([ 'type' => 'chart', 'wrapperClass' => 'col-md-3', 'controller' => \App\Http\Controllers\Admin\Charts\VoltageChartController::class, 'content' => [ 'header' => 'New Entries', // optional ] ]); @endphp ... |
How to enable AWS RDS loging/logout logs Posted: 30 Mar 2021 10:31 AM PDT Is it possible to enable/export RDS user login/logout events to CloudWatch? or are there any other aws related tools to achieve this? |
How to fix the clumped up text? How to fix the background not going all the way down? Posted: 30 Mar 2021 10:31 AM PDT In this code, my text on the sidebar side keeps no getting clumped up together. How can I fix that? Also, how can I extend the sidebar's background all the way to the point where it meets the footer like how the area main does. The whole page is set up in a grid from Grommet. I tried using padding and margin as shown in the code but it still does not work. I also tried some functions in the CSS but it still did not work. import React from "react"; import { Grommet, Box, Grid, Heading, Paragraph, List, Text, Button, Form, FormField, TextInput } from "grommet"; import { Gremlin, LocationPin, FormNext, DocumentText } from "grommet-icons"; import { custom } from "grommet/themes"; import { deepMerge } from "grommet/utils"; import "./Purpleheader.css"; import "./TechnicalScholarshipApp.css"; import { Simple } from "./StatesForm"; import { Household } from "./Household"; import { Phone } from "./PhoneForm"; import { MainFooter } from "../Footer/Footer"; const data = [ { text: "You are a graduating senior from Stranahan High School" }, { text: "You will attend a certified educational institution this fall, with a definite one or two year goal in mind. For example, x-ray tech, beautician, welder, etc. ", }, { text: "You have completed the application and the attached the following:" }, ]; const data2 = [ { text2: "A copy of your Stranahan transcript, including the first semester of your senior year." }, { text2: "Two letters of recommendation. One from an educator, one from a mentor, employer, or community member." }, { text2: "A copy of your Federal Financial Aid form." }, { text2: "A copy of your Stranahan transcript, including the first semester of your senior year." }, { text2: "A short essay that addresses one of the following:" }, ]; const data3 = [ { text3: "One major accomplishment I have achieved and why it was important." }, { text3: "One major obstacle in my life and how I overcame it." }, { text3: "What impact my education at Stranahan has had on me." }, ]; const data4 = [ { text4: "These completed materials must be submitted in an envelope or organized folder to Ms. Lewis no later than Friday, March 3rd.", }, ]; const customTheme = deepMerge(custom, { formField: { label: { requiredIndicator: true, }, }, }); const TechnicalScholarshipApp = () => ( <Grommet themes={custom}> <Box> <Grid className="PurpleHeader" rows={["xxsmall"]} areas={[["header"]]} gap="small"> <Box background="brand" gridArea="header"> <h2>Technical/Vacational Scholarship Application </h2> </Box> </Grid> <Box className="bodypage"> <Grid rows={["xlarge"]} columns={["1/2", "1/2"]} areas={[["sidebar", "main", "footer", "footer"]]}> <Box background="light-5" gridArea="sidebar"> <Box pad={{ top: "medium", bottom: "large" }}> <Heading textAlign="center">Stranahan Education Endowment Foundation</Heading> </Box> <Box pad={{ top: "large", left: "large" }}> <Heading textAlign="center" size="small"> One or Two Year Scholarship Application </Heading> </Box> <Box align="center" pad={{ bottom: "xlarge", top: "large" }}> <Paragraph textAlign="center" size="large"> This form is for a five hundred dollar grant toward a technical, vocational or medical career. Your application cannot be considered unless the following requirements are met: </Paragraph> </Box> <Box pad={{ bottom: "xlarge", left: "small" }} align="center"> <List data={data} border={false}> {(datum) => ( <Box direction="row-responsive" gap="medium" align="center"> <LocationPin size="large" /> <Text weight="bold">{datum.text}</Text> </Box> )} </List> </Box> <Box pad={{ top: "xlarge", left: "large", right: "xlarge", bottom: "xlarge" }} align="center"> <List data={data2} pad="medium" border={false}> {(datum) => ( <Box direction="row-responsive" gap="medium" align="center"> <FormNext size="large" /> <Text weight="bold">{datum.text2}</Text> </Box> )} </List> </Box> <Box pad={{ top: "xlarge", left: "medium", top: "xlarge", bottom: "xlarge" }} align="center" margin={{ top: "xlarge" }} > <List data={data3} pad="medium" border={false}> {(datum) => ( <Box direction="row-responsive" gap="medium" align="center"> <DocumentText size="large" /> <Text weight="bold">{datum.text3}</Text> </Box> )} </List> </Box> <Box pad={{ top: "xlarge", left: "large", right: "xlarge" }} align="center" margin={{ top: "xlarge" }} > <List data={data4} pad="medium" border={false}> {(datum) => ( <Box direction="row-responsive" gap="medium" align="center"> <FormNext size="large" /> <Text weight="bold">{datum.text4}</Text> </Box> )} </List> </Box> </Box> <Grommet theme={custom}> <Box background="light-2" gridArea="main" className="mainForm"> <Box align="center" pad="large"> <Heading textAlign="center" size="small"> One or Two Year Scholarship Application </Heading> </Box> <Box align="center" pad="large"> <Form> <FormField name="firstName" htmlFor="firstName" label="First Name" required> <TextInput id="firstName" name="firstName" /> </FormField> <FormField name="lastName" htmlFor="lastName" label="Last Name" required> <TextInput id="lastName" name="lastName" /> </FormField> <FormField name="streetAddress" htmlFor="streetAddress" label="Street Address" required > <TextInput id="streetAddress" name="streetAddress" /> </FormField> <FormField name="addressLine2" htmlFor="addressLine2" label="Address Line 2"> <TextInput id="addressLine2" name="addressLine2" /> </FormField> <FormField name="city" htmlFor="city" label="City" required> <TextInput id="city" name="city" /> </FormField> <Box> <FormField name="zipCode" htmlFor="zipCode" label="Zip Code" required> <TextInput id="zipCode" name="zipCode" /> </FormField> </Box> <Simple /> <Phone /> <FormField name="email" htmlFor="email" label="Email" required> <TextInput id="email" name="email" type="email" /> </FormField> <Household /> <FormField name="mothersOccupation" htmlFor="mothersOccupaton" label="Mothers Occupation" > <TextInput id="mothersOccupation" name="mothersOccupation" /> </FormField> <FormField name="fathersOccupation" htmlFor="fathersOccupaton" label="Fathers Occupation" > <TextInput id="fathersOccupation" name="fathersOccupation" /> </FormField> <Button type="submit" label="Submit" primary /> <Text margin={{ left: "small" }} size="small" color="status-critical"> * Required Field </Text> </Form> <Box gridArea="footer" pad={{ top: "large" }}> <MainFooter /> </Box> </Box> </Box> </Grommet> </Grid> </Box> </Box> </Grommet> ); export default TechnicalScholarshipApp; |
AWS Redshift Cursor's fails with: DECLARE CURSOR may only be used in transaction blocks; Posted: 30 Mar 2021 10:30 AM PDT First, I understand cursors are not performant but I need one in my specific case. In AWS Redshift I have the following code: BEGIN; DECLARE newCursor CURSOR FOR SELECT * FROM DBFoo.TableBar; FETCH NEXT FROM newCursor; CLOSE newCursor; I get the following error: Amazon Invalid operation: DECLARE CURSOR may only be used in transaction blocks; Since "BEGIN;" directly precedes "DECLARE newCursor CURSOR" I don't understand why it is failing, or how to get it to work edit: I am connecting to Redshift via Datagrip. This is a brand new session. If I declare the cursor before the BEGIN is also failed because it requires a transaction block |
How to share React components in monorepo, by source? Posted: 30 Mar 2021 10:30 AM PDT I have a monorepo containing 3 different React projects: - SHARED_COMPONENTS src Button.tsx package.json - APP_A src main.ts package.json - APP_B src main.ts package.json How can I import the Button(.tsx) module from both main.ts files? E.g. I want to define my shared components inside the SHARED_COMPONENTS folder, and use these components inside APP_A and APP_B. I do not want to compile the Button (and share it with tools like bit.dev or npm registry). I want to include the source file of Button.tsx, and let each individual build script (the ones for APP_A, and APP_B) compile/transpile the source of Button.tsx. In other words, Button.tsx should become part of the source code of f.e. APP_A. I do not want to include it as a compiled component. All projects (SHARED_COMPONENTS, APP_A, APP_B) are created with CRA. But if necessary the webpack config can be overridden, or we can eject and go manual. I believe the main problem is that ../SHARED_COMPONENTS lays outside of the src directory for each individual APP project, and hence we cannot include the source code from shared components. Are there solutions for this? Links to a guide or a thorough explanation would be much appreciated. I've tried searching extensively but the material I find often suggests packaging the shared components and share them with bit.dev/npm registry, which is what we don't want. We try this at the moment, and it's very cumbersome for the development cycle. |
Accessing the index in 'for' loops? Posted: 30 Mar 2021 10:30 AM PDT How do I access the index in a for loop like the following? ints = [8, 23, 45, 12, 78] for i in ints: print('item #{} = {}'.format(???, i)) I want to get this output: item #1 = 8 item #2 = 23 item #3 = 45 item #4 = 12 item #5 = 78 When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case? |
No comments:
Post a Comment