ReactJS state value not update correctly on input onChange Posted: 01 Jun 2021 07:56 AM PDT In my app, i have Groups, and i have a select input, to change between group lists. My issue is when i change the select input, the state changes the name of the list, but is not the one im selecting. For example, at initial i have: All Groups Group #1 Group #2 When i choose Group #1, the state in the console says "All Groups". If i choose Group #2, the state in the console says "Group #1" Select Input <select id="selectedPg" name="selectedPg" onChange={event=> { this.valueToState(event.target) this.viewProfileGroup(); }}> viewProfileGroup() // View Selected Profile Group viewProfileGroup = ()=> { const { selectedPg, allProfilesLists } = this.state this.setState({ profilesLists: allProfilesLists.filter(pg => pg.profileGroup === selectedPg) }) console.log(this.state.selectedPg) } |
c# Change special chars in string Posted: 01 Jun 2021 07:56 AM PDT Hello I am using c# and in code from appsettings.json I take strings and convert them if special chars exists. this is my code int? a = applicationRequestViewModel.GetApplicantIndex(); int? g = applicationRequestViewModel.GetGurantorIndex(); foreach (var keys in _options.Value.RegisterParamKeys) { string value = keys.Split(";")[0]; string name = keys.Split(";")[1]; string key = value.Split(":")[typeOfApplicant]; key = Regex.Replace(key, @"[^\[a\]]", "[" + a + "]"); key = Regex.Replace(key, @"[^\[g\]]", "[" + g + "]"); var registrationProperty = new RegistrationProperty() { }; registrationProperty.Name = name; registrationProperty.Value = (string)rss.SelectToken(key); listOfRegistrationProperty.Add(registrationProperty); } from appsettings.json I took below strings "RegisterBatchParams": [ "applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber;applicationNumber", "applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType;applicantType", "applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment;customerSegment", "applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText;applicationStatus", "applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName;customerName" ], for the last string I want to change applicants[a] to with index number but It doesn't convert as expected how can I convert correctly? Thanks in advance |
What is the C++ iterator for STL Queue? Posted: 01 Jun 2021 07:56 AM PDT I know we can not iterate easily in STL Queue, but I want to do something like this: void myFun(Node* root) { queue<pair<int, Node*>> myQueue; myQueue.push(make_pair(0, root)); auto it = myQueue.front(); } This works, however, what should I use instead of the auto keyword for the queues? We use something like this for maps: map<int, Node*>::iterator it = myMap.begin(); But queue<pair<int, Node*>>::iterator it = myQueue.front(); This does not work and throws error: 'iterator' is not a member of 'std::queue<std::pair<int, Node*> >' queue<pair<int, Node*>>::iterator it = myQueue.front(); What's the correct syntax? |
How to map EFCore DBFirst Foreign Key splitted Primary Key Posted: 01 Jun 2021 07:56 AM PDT So I have 2 tables. Article and Specials with Article having multiple Specials. Article PK consist of Specials.ID and Specials.ID2. Now I'm having a really hard time to implement the relation between these two tables. I tried it via FluentAPI but I wasn't able to declare the FK as the splitted PK. builder.Entity<Article_New>() .HasMany<ArticleSpecial>(a => a.Specials) .WithOne() .HasForeignKey(a => new { Articlenumber = a.Articlenumber , a.AusfKz }); which sadly resulted in exceptions. Aswell as manual joins: var articles = _context.Article_New.Join(_context.Specials, o => o.Articlenumber , i => i.Articlenumber + i.AusfKz, (o, i) => new { Articlenumber = o.Articlenumber , Specials= i }).Where(a => a.Artikelnummer == id); Which yielded some results but missing the multiple part of specials in article and just giving me 1 special. |
regular expression to validate email and phone number Posted: 01 Jun 2021 07:56 AM PDT I need to make a regex pattern to validate user's email with the following constraints: - The general form is [name]@[domain].
- [name] consists of letters (a to z, both lowercase and uppercase accepted), digits and dots. This rule also applies to [domain].
- Two dots cannot be positioned next to each other. Dots can't be positioned at the beginning or end of [name]. This applies to [domain] as well. There is at least one dot in [domain].
- [name] length is at least 3.
- The part of [domain] after the last dot (for example, @gmail.com then 'com' is the part after the last dot in domain) contains only letters and have a length of 2 - 5 letters.
Valid email example: 123@1.me, 1.2.3@domain.namee, this.is.my.email@sub.sub.789.main; Invalid email: .dot.at.beginning@domain.com, name@domainwithnodot, test@last.part.consists.num.b3r, there.is space@domain.name) This is the pattern I tried, it's not working for the constraint [name] length >= 3 /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ But since it's too long (I got reference here and there) so I can't spot the problem. The constraints for phone number: - 9 to 11 digits.
- Space, dots and dashes can be used to group/separate the digits. They can't be positioned at the beginning or end of the phone or next to each other.
Valid number: 0123456789, 0-1-2-3.4.5 6.7-8-9, 012.345-6789. Invalid phone examples: 01234567890123 (too long), (0123)456-7890 (parentheses not allowed), 012--3456789 (2 dashes next to each other) My pattern for phone: /^([0-9]([-. ]?)){9,11}[^-. ]$/ |
Equal to operation not working on a field with updated collation Posted: 01 Jun 2021 07:56 AM PDT I was trying to convert an existing varchar column with a unique index on it to a case sensitive column. So to do this, I updated the collation of the particular column. - Previous value: utf8mb4_unicode_ci
- Current value: utf8mb4_bin
Now I have a row in my table TEST_TABLE with test_column value is abcd . When I try to run a simple query like SELECT * FROM TEST_TABLE WHERE test_column = 'abcd'; it returns no result. However when I try SELECT * FROM TEST_TABLE WHERE test_column LIKE 'abcd'; it returns the data correctly. Also when I try SELECT * FROM TEST_TABLE WHERE BINARY test_column = 'abcd'; it returns the data correctly. One more thing I tried was creating a duplicate of the table with column collation set as utf8mb4_bin while creating itself and then copy all data from original table. Then the query SELECT * FROM TEST_TABLE WHERE test_column = 'abcd'; is working alright. So this seems to be a problem with BINARY conversion. Is there any solution to this or Am I doing something wrong ? |
iOS Obj-C unittest app won't start with OCMock and XCTest added Posted: 01 Jun 2021 07:56 AM PDT I am trying to add OCMock (3.8.1) to a Chromium-based iOS app. All the code is Objective-C. We are using the gtest unittest framework just as Google does in Chromium unit tests, so my unittest target did not have XCTest.framework. When I only added OCMock.framework I got a linker error, saying that XCTest was not found. So I added XCTest.framework to my bundle, but then when XCode tries to start the unittests, it says this: error: attach by pid '80485' failed -- no such process. and won't run. I didn't realize OCMock had this dependency on XCTest (I had read previous versions weren't even compatible with it?) I am using the Debug libraries intended for x86 simulator. Any tips would be appreciated. (Note: I haven't even tried writing a single line of code using OCMock yet -- I'm just trying to get the library integrated.) |
JavaScript Classes (two constructors and private variables) Posted: 01 Jun 2021 07:56 AM PDT I am trying to make a class for a Circle. I am supposed to have two private variables - radius and color. I am also supposed to have two constructors, one who does not take in any arguments and one who takes in the radius of the circle. First of all, I don't know how to define a variable private, and when I try to make two constructors I get the error message: "A class may only have one constructor". Any help would be appricated! I am practicing for an exam :) |
Countdown in Django Html Template Posted: 01 Jun 2021 07:56 AM PDT I am trying to implement a countdown, that will give me the number of days and hours until the deadline. I have tried two different methods using the html filter but nothing is displayed. Is the filter not already part of Django? models.py class Quote(models.Model): deadline = models.DateTimeField(auto_now=False, blank=True, null=True) html filter Method 1: {{ quote.deadline|timeuntil:today }} Method 2: {{ quote.deadline|timesince:comment_date }} |
Connecting SpringBoot application to GCP sql while running on cloud run Posted: 01 Jun 2021 07:56 AM PDT Follow up from my prev question: Optimizing connection to GCP mysql from cloud run service? I have previously used the spring-cloud-gcp-starter-sql-mysql to connect to my GCP mysql instance on cloud run, and it works fine albeit cold start time was slow because it does its all its connections in the pool via ssl socket. Therefore im now trying to connect to the database instance locally when running on cloud run. I have been trying different tutorials to no avail, what I currently have done is: - Given my cloud run service acc cloud sql admin permissions
- Added the database connection to cloud run by selecting the db instance through edit revision
My pom.xml contains <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> My application.yml // application config spring: datasource: # url: jdbc:mysql://localhost:3306/<database_name> # url: jdbc:mysql://google/cloudSqlInstance=${<my-project database instance connection name>}&socketFactory=com.google.cloud.sql.mysql.SocketFactory # url: jdbc:mysql:///<my database table name>?cloudSqlInstance=<my-project database instance connection name>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=<db_username>&password=<db_password> # url: jdbc:mysql://<my-project database instance connection name>/<my database table name> driver-class-name: com.mysql.cj.jdbc.Driver username: root password: PC98O7amxcenyL2L hikari: maximum-pool-size: 20 i have trued all 4 URL's listed, but the closest I have gotten so far is by using the first url: url: jdbc:mysql://localhost:3306/owl_database which i managed to run locally by using the cloud sql proxy, but when I deploy it it throws a "Caused by: java.net.ConnectException: Connection refused (Connection refused)" error. Where am I going wrong here? |
How do I make ggplot2 trendlines, one dashed and another a solid line? Posted: 01 Jun 2021 07:56 AM PDT I'd like each trend line on this graph to have a different shape. For example, the "boys" trendline would be dashed, and the "girls" trendline would be a solid line. I am using the ggplot2 library in R. Here is my code. dr <- ggplot(Tempdata, aes(x=Tempdata$EffortfulControl, y=Tempdata$sqrt_Percent.5, color=Tempdata$Sex1M, shape=Tempdata$Sex1M)) + geom_point(aes(shape=Tempdata$Sex1M, color=Tempdata$Sex1M), show.legend = FALSE) + scale_shape_manual(values=c(16,17))+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE) + labs(x="xaxis label", y = "yaxis label", fill= "") + xlim(3,7) + ylim(0,10) dr + scale_colour_grey(start = 0.0, end = .7 , guide_legend(title = "")) + theme_classic() enter image description here |
How can run setInterval self after fullfill the condition Posted: 01 Jun 2021 07:56 AM PDT According to my condition setInterval is not running I want to render after fulfilling the condition with the dynamic time you can see my code below data: function () { return { end_time: '', // ==> this working with dynamically time like on event I'm adding time in the current time } }, mounted() { this.setTimeOutClose(); }, setTimeOutClose() { let _this = this; var now_time = moment.utc().format('h:mm A'); var interval = setInterval(function(){ if(now_time == _this.end_time){ alert("You want to close conversation?"); } //do whatever here.. }, 1000); }, |
Sticky element with outside element scrolling Posted: 01 Jun 2021 07:56 AM PDT I simplified to the maximum my problem. I need to make a text which is inside nested divs sticky to the top of the screen In the snippet provided, the "test" label have to remain on top of the screen until the div is totally out of view. Is there a css way to make this possible? div { border : 1px solid; } .sticky{ position: sticky; } <h1>1st</h1> <div> <p class='sticky'> test </p> <br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br> <br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br> <br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br> </div> <h1>2nd</h1> <div > <p class='sticky'> test2 </p> <br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br> <br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br> <br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br><br><br> <br><br> </div> |
Hidden form value not retrieved or stored Posted: 01 Jun 2021 07:56 AM PDT I have a simple form that can store the date and email, through php, but not a specific hidden value. Goal: To store the hidden value "clubo" to the f.txt . Can you assist please? HTML <form method="post" action="test.php"> <input type="hidden" name="clubo" value="clubo"/> <input type="hidden" name="date" aria-label="date" value="date-through-echo" readonly/> <input required type="email" name="email" placeholder="Email to join the Club!" aria-label="email" multiple> <input type="submit" name="submitclub" value="Join"> </form> PHP $clubo = $_REQUEST['clubo']; $date = $_REQUEST['date']; $email = $_REQUEST['email']; $file = fopen("f.txt", "a"); fwrite($file, $clubo); fwrite($file, $date); fwrite($file, $email); fclose($file); |
Why signing an app for android with apache cordova fails? Posted: 01 Jun 2021 07:56 AM PDT I am using Apache Cordova that allows developers to create apps for various platforms. I created a keystore file in Android Studio and I entered this command in the CLI in order to produce a signed apk file that will be running in android devices: cordova run android --release --keystore=../keystores-android/fd1.jks --storePassword=pass --alias=fd1 --password=pass and I get a bunch of errors, which I don't understand and an unsigned apk file: Checking Java JDK and Android SDK versions ANDROID_SDK_ROOT=undefined (recommended setting) ANDROID_HOME=undefined (DEPRECATED) Using Android SDK: C:\Users\User\AppData\Local\Android\sdk Subproject Path: CordovaLib Subproject Path: app > Task :app:lintVitalRelease F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-land-hdpi\screen.png: Error: The drawable "screen" in drawable-land-hdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-land-ldpi\screen.png: Error: The drawable "screen" in drawable-land-ldpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-land-mdpi\screen.png: Error: The drawable "screen" in drawable-land-mdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-land-xhdpi\screen.png: Error: The drawable "screen" in drawable-land-xhdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-land-xxhdpi\screen.png: Error: The drawable "screen" in drawable-land-xxhdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-land-xxxhdpi\screen.png: Error: The drawable "screen" in drawable-land-xxxhdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-port-hdpi\screen.png: Error: The drawable "screen" in drawable-port-hdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-port-ldpi\screen.png: Error: The drawable "screen" in drawable-port-ldpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-port-mdpi\screen.png: Error: The drawable "screen" in drawable-port-mdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-port-xhdpi\screen.png: Error: The drawable "screen" in drawable-port-xhdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-port-xxhdpi\screen.png: Error: The drawable "screen" in drawable-port-xxhdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] F:\2021-fd-local-server\fd1\platforms\android\app\src\main\res\drawable-port-xxxhdpi\screen.png: Error: The drawable "screen" in drawable-port-xxxhdpi has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier [MissingDefaultResource] Explanation for issues of type "MissingDefaultResource": If a resource is only defined in folders with qualifiers like -land or -en, and there is no default declaration in the base folder (layout or values etc), then the app will crash if that resource is accessed on a device where the device is in a configuration missing the given qualifier. As a special case, drawables do not have to be specified in the base folder; if there is a match in a density folder (such as drawable-mdpi) that image will be used and scaled. Note however that if you only specify a drawable in a folder like drawable-en-hdpi, the app will crash in non-English locales. There may be scenarios where you have a resource, such as a -fr drawable, which is only referenced from some other resource with the same qualifiers (such as a -fr style), which itself has safe fallbacks. However, this still makes it possible for somebody to accidentally reference the drawable and crash, so it is safer to create a default dummy fallback in the base folder. Alternatively, you can suppress the issue by adding tools:ignore="MissingDefaultResource" on the element. (This scenario frequently happens with string translations, where you might delete code and the corresponding resources, but forget to delete a translation. There is a dedicated issue id for that scenario, with the id ExtraTranslation.) 12 errors, 0 warnings Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0. Use '--warning-mode all' to show the individual deprecation warnings. See https://docs.gradle.org/6.5/userguide/command_line_interface.html#sec:command_line_warnings BUILD SUCCESSFUL in 2s 43 actionable tasks: 1 executed, 42 up-to-date Built the following apk(s): F:\2021-fd-local-server\fd1\platforms\android\app\build\outputs\apk\release\app-release-unsigned.apk Checking Java JDK and Android SDK versions ANDROID_SDK_ROOT=C:\Users\User\AppData\Local\Android\sdk (recommended setting) ANDROID_HOME=undefined (DEPRECATED) Using Android SDK: C:\Users\User\AppData\Local\Android\sdk Deploying to emulator emulator-5554 Using apk: F:\2021-fd-local-server\fd1\platforms\android\app\build\outputs\apk\release\app-release-unsigned.apk Package name: com.fd.myteam.fd1 Command failed with exit code 1: adb -s emulator-5554 install -r F:\2021-fd-local-server\fd1\platforms\android\app\build\outputs\apk\release\app-release-unsigned.apk adb: failed to install F:\2021-fd-local-server\fd1\platforms\android\app\build\outputs\apk\release\app-release-unsigned.apk: Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES: Package /data/app/vmdl594732036.tmp/base.apk has no certificates at entry AndroidManifest.xml] Performing Streamed Install Any ideas of what's wrong? Thank you. |
Chess-like Matrix Python Posted: 01 Jun 2021 07:56 AM PDT Good day, I am new in Python. I just want to ask for your help if how can I make a chess board like matrix see for info and if I input a string example "b2" it will return a string "black", and if the input is "a1" the return string would be white. any help is appreciated |
The term 'Install-ChocolateyPackage' is not recognized as the name of a cmdlet, function Posted: 01 Jun 2021 07:56 AM PDT i try to install SQLEXPRADV_x64 "manual" with Install-ChocolateyPackage on an Azure Hosted Agent (Windows-Latest). I do manual as there is no Express Advanced Version available. Error is: The term 'Install-ChocolateyPackage' is not recognized as the name of a cmdlet, function And I can't find the fitting solution in the documentation. The CMDLET should be available on the Agent? - powershell: | $silentArgs = "/IACCEPTSQLSERVERLICENSETERMS /Q /ACTION=install /INSTANCEID=SQLEXPRESS /INSTANCENAME=SQLEXPRESS /UPDATEENABLED=FALSE" $fileFullPath = "SQLEXPRADV_x64_ENU.exe" $packageName = "MsSqlServer2016ExpressAdv" $chocolateyTempDir = Join-Path (Get-Item $env:TEMP).FullName "chocolatey" $tempDir = Join-Path $chocolateyTempDir $packageName $extractPath = "$tempDir\SQLEXPRADV" $setupPath = "$extractPath\setup.exe" Write-Host "Extracting to " $extractPath Start-Process "$fileFullPath" "/Q /x:`"$extractPath`"" -Wait Install-ChocolateyPackage "$packageName" "EXE" "$silentArgs" "$setupPath" -validExitCodes @(0, 3010) displayName: 'install sql express database' |
Will dask map_partitions(pd.cut, bins) actually operate on entire dataframe? Posted: 01 Jun 2021 07:56 AM PDT I need to use pd.cut on a dask dataframe. This answer indicates that map_partitions will work by passing pd.cut as the function. It seems that map_partitions passes only one partition at a time to the function. However, pd.cut will need access to an entire column of my df in order to create the bins. So, my question is: will map_partitions in this case actually operate on the the entire dataframe or am I going to get incorrect results with this this approach? |
QT: stretch factor in QSplitter does not work Posted: 01 Jun 2021 07:57 AM PDT I am using QSplitter in my project, and I want to set the stretch factor for two widget. The following code is recommanded: splitter.setStretchFactor(0, 1) splitter.setStretchFactor(1, 5) And I need to firstly hide one widget, then show it after I click a button. I find the stretch factor does not work. The whole code is: from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import sys class MainWindow(QWidget): def __init__(self): super().__init__() mainLayout = QVBoxLayout() self.setLayout(mainLayout) self.btn = QPushButton('show') self.btn.clicked.connect(self.btnSlot) mainLayout.addWidget(self.btn) layout = QHBoxLayout() mainLayout.addLayout(layout) self.w1 = QWidget() self.w1.setStyleSheet('border: 2px solid #777;') self.w1.hide() self.lay1 = QVBoxLayout() self.lay1.addWidget(QLabel('label 1')) self.w1.setLayout(self.lay1) w2 = QWidget() w2.setStyleSheet('border: 2px solid red;') self.lay2 = QVBoxLayout() w2.setLayout(self.lay2) splitter = QSplitter() splitter.addWidget(self.w1) splitter.addWidget(w2) splitter.setStretchFactor(0, 1) splitter.setStretchFactor(1, 5) layout.addWidget(splitter) def btnSlot(self, check=False): self.w1.show() self.lay2.addWidget(QLabel('label 2')) if __name__ == '__main__': app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() After clicked the 'show' button, the result is: From the above figure, we can see the stretch factor for widget 1/2 is not 1:5. How can I make the strech factor to be 1:5? Any suggestion is appreciated! |
How to restrict access to API Gateway from external GCP? Posted: 01 Jun 2021 07:56 AM PDT How to restrict access to API Gateway from external GCP? Cloud Armor can only use for Load Balancer. I created GCP API Gateway(backend is Flask application on App Engine). And I want to restrict access from external GCP Project. |
HoloLens error: "There were deployment errors. Continue?" Posted: 01 Jun 2021 07:56 AM PDT I'm trying to deploy an application I built in Unity to the HoloLens 2 by following this tutorial. When I go to deploy the application by selecting "Master", "ARM64", "Device" and then "Start without debugging" in Visual Studio I get this error "There were deployment errors. Continue?". If I select yes then I get the below error: Error DEP6957: Failed to connect to device '127.0.0.1' using Universal Authentication. Please verify the correct remote authentication mode is specified in the project debug settings. COMException - Error HRESULT E_FAIL has been returned from a call to a COM component. [0x80004005] XamlControlsGallery I have the Microsoft HoloLens portal open and logged in to the HoloLens, both the laptop and HoloLens are on the same WiFi. I've tried: - Restarting Visual Studio, Microsoft HoloLens portal, the HoloLens, my laptop.
- Rebuilding the project from Unity.
- Using all combinations of "Release" or "Master" and "ARM64" or "x64" and "Device".
|
selenium-webdriver: The geckodriver executable could not be found on the current PATH Posted: 01 Jun 2021 07:56 AM PDT I installed the selenium webdriver using the following command: $ npm i selenium-webdriver Then, I created the directory D:\WebDriver\bin (and added the files geckodriver.exe and operadriver.exe to that directory) and added it to the system's PATH variables. The PATH to the directory that contains both drivers was successfully added, as can be seen below: $ printenv PATH /mnt/d/WebDriver/bin/ $ ls "/mnt/d/WebDriver/bin/" geckodriver.exe operadriver.exe I am also able to run the geckodriver via cmd.exe (Same applies to operadriver): C:\Users\user>geckodriver 1621873805268 geckodriver INFO Listening on 127.0.0.1:4444 When I try to run one example file (google_search) via: /mnt/d/proj/node_modules/selenium-webdriver/example $ node google_search.js I receive the following stacktrace: Error: The geckodriver executable could not be found on the current PATH. Please download the latest version from https://github.com/mozilla/geckodriver/releases/ and ensure it can be found on your PATH. The operadriver also cannot be found when setting up an example that uses the opera driver. Worth mentioning is that I use a Windows Subsystem for Linux (WSL) and ran the commands (node, printenv and npm) in the terminal of that subsystem. The path variable was set on the Windows system and the required drivers were only installed on the Windows system. I can access the installed files on my windows system via the WSL terminal, but selenium still cannot find the specific driver(s). When I run the above mentioned test file (google_search.js) from selenium-webdriver on the Windows system, it does find the web driver and works as expected. I still cannot figure out the reason why the driver is not being found in the WSL. |
Could not download applet (.cap file) into the smart card: SW 6D 00 (Invalid Instruction) Posted: 01 Jun 2021 07:56 AM PDT I am working on a "JCOP3 SecID P60 CS" smart card. I am trying to download the cap file using pyAPDUToolbut, I get the: 6D 00 answer (Invalid Instruction). The same result with 'gp' Could please any one told me where is the problem? |
Jest with Vue 3 - ReferenceError: define is not defined Posted: 01 Jun 2021 07:56 AM PDT I would like to test my component with Jest and inside component, I imported @vue/apollo-composable library and when I run test I get the error: ReferenceError: define is not defined 2 | // libraries 3 | import { defineComponent, ref, watch } from '@vue/composition-api' > 4 | import { useLazyQuery, useResult } from '@vue/apollo-composable' | ^ 5 | import gql from 'graphql-tag' In the jest test I don't use apollo-composable and I don't plan to. Code: import '@/plugins/composition-api' import App from '@/components/App.vue' import Vue from 'vue' import { Wrapper, createLocalVue, mount } from '@vue/test-utils' Vue.use(Vuetify) describe('SelectMediaProcess.vue', () => { let wrapper: Wrapper<Vue> const localVue = createLocalVue() beforeEach(() => { wrapper = mount(SelectMediaProcess, { localVue }) }) it('render', () => { expect(wrapper.exists()).toBe(true) }) }) I read on the internet what I can use: jest.mock('@vue/apollo-composable', () => { // mock implementation }) But when I use this piece of code in my test. I get error: (useLazyQuery is a function from @vue/apollo-composable library) TypeError: Cannot read property 'useLazyQuery' of undefined 19 | 20 | // get default media process > 21 | const { onResult, load: loadDefaultMP } = useLazyQuery< | ^ 22 | getDefaultMediaProcess, 23 | getDefaultMediaProcessVariables 24 | >( Does anyone know what can I do please? EDIT I added these lines to my jest.config.js. It helped others but not me. transformIgnorePatterns: ['<rootDir>/node_modules/(?!@vue/apollo-composable).+\\.js$'] moduleNameMapper: { '@vue/apollo-composable': '@vue/apollo-composable/dist/index.js' } Full jest.config.js: module.exports = { preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel', moduleFileExtensions: ['js', 'ts', 'json', 'vue'], moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1', 'vuetify/lib(.*)': '<rootDir>/node_modules/vuetify/es5$1', '@vue/apollo-composable': '@vue/apollo-composable/dist/index.js' }, modulePaths: ['<rootDir>/src', '<rootDir>/node_modules'], transform: { '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub', '^.+\\.ts?$': 'ts-jest', '.*\\.(vue)$': 'vue-jest' }, transformIgnorePatterns: [ '<rootDir>/node_modules/(?!(vuetify)/)', '<rootDir>/node_modules/(?!@vue/apollo-composable).+\\.js$' ] } and I get these new errors: FAIL tests/unit/selectMediaProcess.spec.ts ● Test suite failed to run Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript. By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules". Here's what you can do: • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. • If you need a custom transformation specify a "transform" option in your config. • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option. You'll find more details and examples of these config options in the docs: https://jestjs.io/docs/en/configuration.html Details: C:\Users\u112200\Documents\deposit-frontend\node_modules\@vue\apollo-composable\dist\index.js:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { useQuery, } from './useQuery'; ^^^^^^ SyntaxError: Unexpected token 'export' 2 | // libraries 3 | import { defineComponent, ref, watch } from '@vue/composition-api' > 4 | import { useLazyQuery, useResult } from '@vue/apollo-composable' | ^ 5 | import gql from 'graphql-tag' 6 | // models 7 | import { allMediaProcesses } from '../models/__generated__/allMediaProcesses' at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17) at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25) at src/components/SelectMediaProcess.vue:4:1 at Object.<anonymous> (src/components/SelectMediaProcess.vue:89:3) Does anyone know what can I do next please? |
GPT-3 Prompts for Sentence-Level and Paragraph-Level Text Summarization / Text Shortening / Text Rewriting Posted: 01 Jun 2021 07:56 AM PDT Need effective prompts for GPT-3 that can accomplish this 'programming' task. Creating effective GPT-3 prompts has essentially become a new form of programming (giving a computer instructions to complete a task). There are getting to be repositories for the nascient, growing 'programming' language of GPT-3 prompts, eg at: https://github.com/martonlanga/gpt3-prompts http://gptprompts.wikidot.com/start https://github.com/wgryc/gpt3-prompts See a working example below, which works ok, but doesn't really address the need, and isn't adequately reliable. This is an important, new, and quickly growing area. Seeking prompts that will accomplish the goal in the Title: summarizing / shortening sentences and / or paragraphs with high reliability, without creating nonsense. Please, reviewers, this is an important question to many people... don't be narrow-minded and decided that because GPT-3 prompts aren't (yet) a 'traditional' computer language they don't have a place here. Thank you for your help Example GPT-3 Prompt: Please summarize the article below. """ Microsoft in talks to buy TikTok Negotiations for ByteDance-owned social media group come as Trump threatens action Microsoft has held talks to acquire TikTok, whose Chinese owner ByteDance faces mounting pressure from the US government to sell the video sharing app or risk being blacklisted in the country, said people briefed on the matter. ... the rest of the article... """ Q: Could you please summarize the article above in three sentences? |
Raspberry Pi QR Scanner high cpu usage Posted: 01 Jun 2021 07:56 AM PDT I am trying to implement a QR scanning application on a Raspberry Pi using nodejs. The application is supposed to run in the background and upload QR codes to a database. I am able to get the basic QR recognizing functionality working with the following code: const cv = require('/usr/local/lib/node_modules/opencv4nodejs') const jsqr = require('jsqr') const PNG = require('pngjs').PNG const FPS = 10 const wCap = new cv.VideoCapture(0) wCap.set(cv.CAP_PROP_FRAME_WIDTH, 600) wCap.set(cv.CAP_PROP_FRAME_HEIGHT, 600) setInterval(() => { const frame = wCap.read() const img = cv.imencode('.png', frame) const png = PNG.sync.read(img) const code = jsqr(png.data, png.width, png.height) if (code) { console.log(`QR Code: ${code.data}`) } else { console.log('No code found.') } }, 1000/FPS) However the CPU usage is 80% and above on a Raspberry Pi 4 with 4GB RAM and an USB camera. I've also tried using fswebcam but it's really slow in capturing a picture. I'm looking for suggestions on how to improve the CPU usage with another library for video capture. Edit: opnecv4nodejs allows for easy conversion to Uint8ClampedArray , which reduces the CPU usage from the image conversion, however the process of video capture looks intensive for the RPi's USB camera. Increasing the interval brings down the CPU load and overheating. setInterval(() => { const frame = wCap.read() const bgraArray = frame.cvtColor(cv.COLOR_BGR2BGRA).getData() const clampedData = new Uint8ClampedArray(bgraArray) const code = jsqr(clampedData, 640, 480) if (code) { console.log(`QR Code: ${code.data}`) } else { console.log('No code found') } }, 5000) Update: The QR processing was moved to a worker thread and that made the application more responsive. function getQR(data) { return new Promise((resolve, reject) => { const worker = new Worker('./src/qr_decoder.js', { workerData: data }) worker.on('message', (qrCode) => resolve(qrCode)); worker.on('error', (error) => reject(error)); }) } The qr_decoder.js file: const jsqr = require('jsqr') const { workerData, parentPort, isMainThread } = require('worker_threads') if (!isMainThread) { try { const qrCode = jsqr(workerData, 1280, 720) if (qrCode) { parentPort.postMessage(qrCode) } else { parentPort.postMessage(undefined) } } catch (error) { throw(error) } } |
Schema/Database Created in Python Code is not appearing in MySQL Workbench / MySQL Server Posted: 01 Jun 2021 07:56 AM PDT I am trying to create the schema/database in python code and am able to create the tables , insert the data into that but when i check in MySQL work bench , the created database in Python is not appearing. my work space details : Installed mysql conector: pip install mysql-connector-python Python Version : 3.8 MySql Version 8.0 here is the code i have written in python code snippet : import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="mysql") mycursor=mydb.cursor() mycursor.execute("create database databaseforpython4") And also able to access the schema created in Python only but not able to create the schema created in MySQL |
Flutter Bottom Navigation Bar not working Posted: 01 Jun 2021 07:56 AM PDT I am trying to use the BottomNavigationBar in Flutter, however it is giving me a weird error that seem to have no reference to my code and I am not able to find this error anywhere online. In fact every tutorial, page, or question I can find says to do it this way. Here is my code from home.dart : ... Imports ... class HomePage extends StatefulWidget { @override State<StatefulWidget> createState() { return HomePageState(); } } class HomePageState extends State<HomePage> { int _selectedTab = 0; final _pageOptions = [ HomePage(), CatPage(), SearchPage(), ]; void _onItemTapped(int index) { setState(() { _selectedTab = index; }); print(index); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Loopt In'), ), body: _pageOptions[_selectedTab], bottomNavigationBar: BottomNavigationBar( currentIndex: _selectedTab, onTap: _onItemTapped, items: [ BottomNavigationBarItem( icon: Icon(Icons.home), title: Text('Home'), ), BottomNavigationBarItem( icon: Icon(Icons.category), title: Text('Categories'), ), BottomNavigationBarItem( icon: Icon(Icons.search), title: Text('Search'), ), ], ), ); } } Interestingly enough when I change the _pageOptions array to have a Text() widgets instead of widgets that I made it work fine, but I don't know why and need it to work with my widgets obviously. Here's the error I'm getting: [VERBOSE-2:shell.cc(181)] Dart Error: Unhandled exception: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 2257 pos 20: '_debugCurrentBuildTarget == context': is not true. #0 _AssertionError._doThrowNew (dart:core/runtime/liberrors_patch.dart:40:39) #1 _AssertionError._throwNew (dart:core/runtime/liberrors_patch.dart:36:5) #2 BuildOwner.buildScope.<anonymous closure> (package:flutter/src/widgets/framework.dart:2257:20) #3 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2261:12) #4 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:817:13) #5 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:709:7) #6 runApp (package:flutter/src/widgets/binding.dart:748:7) #7 main (file:///Users/garrettlove/Documents/learn/Flutter/loopt_in/lib/main.d<…> |
Using regex in filter in Julia Posted: 01 Jun 2021 07:56 AM PDT It is possible to filter items that fits a simple condition to match strings in Julia: y = ["1 123","2512","31 12","1225"] filter(x-> ' ' in x, y) [out]: 2-element Array{String,1}: "1 123" "31 12" But how do I get the reverse where I want to keep the items that doesn't match the condition in a filter? This syntax isn't right: > y = ["1 123","2512","31 12","1225"] > filter(x-> !' ' in x, y) MethodError: no method matching !(::Char) Closest candidates are: !(::Bool) at bool.jl:16 !(::BitArray{N}) at bitarray.jl:1036 !(::AbstractArray{Bool,N}) at arraymath.jl:30 ... in filter(::##93#94, ::Array{String,1}) at ./array.jl:1408 Neither is such Python-like one: > y = ["1 123","2512","31 12","1225"] > filter(x-> ' ' not in x, y) syntax: missing comma or ) in argument list Additionally, I've also tried to use a regex: > y = ["1 123","2512","31 12","1225"] > filter(x-> match(r"[\s]", x), y) TypeError: non-boolean (RegexMatch) used in boolean context in filter(::##95#96, ::Array{String,1}) at ./array.jl:1408 Beyond checking whether a whitespace is in string, how can I use the match() with a regex to filter out items from a list of strings? |
Synchronization of data using Bluetooth or WiFi in android devices Posted: 01 Jun 2021 07:56 AM PDT Is it possible to synchronize data in two android devices? As soon as I enter a data in any of my field of the respective android app I want that data to be automatically sync(pressing a sync button) to the other nearby phone connected to either Bluetooth or same WiFi. |
No comments:
Post a Comment