text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Android, BottomNavigationView, set weight for each item? I am using Bottom navigation bar in my app. It contains 3 items as in below:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.MainActivity">
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#ffffff"
android:layout_weight="9">
<GridView
android:id="@+id/gvMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3" />
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="bottom"
android:layout_weight="1"
android:background="?android:attr/windowBackground"
android:backgroundTint="#f5f5f5"
app:menu="@menu/navigation" />
</LinearLayout>
Here there is the "@menu/navigation" code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/navigation_home"
android:icon="@drawable/ic_home_black_24dp"
android:title="Button1"/>
<item
android:id="@+id/navigation_dashboard"
android:icon="@drawable/ic_dashboard_black_24dp"
android:title="Button2"/>
<item
android:id="@+id/navigation_notifications"
android:icon="@drawable/ic_notifications_black_24dp"
android:title="Button3"/>
</menu>
Now I want to somehow have the middle button take half the space provided and the other two share the other half. But no weight attribute is present. In other words, I want to set the layout weight for the button2 to 2 and for the button1 and button3 to 1. Is there a way to do this?
Any help or tips is appreciated.
Below are the shapes that might help:
Current layout:
Current State
MY goal is to change it like this:
What I want
A: Here is my suggestion:
you can use an layout to replace the menu:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="52dp"
android:orientation="horizontal">
<FrameLayout
android:id="@+id/fl_page_home"
android:layout_width="wrap_content"
android:layout_height="57dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center_horizontal"
android:background="your drawable"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="32dp"
android:text="your text" />
</FrameLayout>
<FrameLayout
android:id="@+id/fl_page_dashboard"
android:layout_width="wrap_content"
android:layout_height="57dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center_horizontal"
android:background="your drawable"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="32dp"
android:text="your text" />
</FrameLayout>
<FrameLayout
android:id="@+id/fl_page_notification"
android:layout_width="wrap_content"
android:layout_height="57dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center_horizontal"
android:background="your drawable"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="32dp"
android:text="your text" />
</FrameLayout>
</LinearLayout>
and height is flexable and you can new a new xml to write this as bottom Navigation and then include to your LinearLayout.
In Java class you can implement onclick listener.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43777208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OpenCV with XCode GUI and c++ Is it possible, using only c++ to design an opencv GUI using XCode's Cocoa Framework?
A: You can use this c++ library wxwidgets. Add the path to xcode and it should work fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36532140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: counting occurrence of name in list of namedtuple (the name is in a nested tuple) As the title says, i'm trying to count the occurrence of a name in a list of namedtuples, with the name i'm looking for in a nested tuple.
It is an assignment for school, and a big part of the code is given.
The structure of the list is as follows:
paper = namedtuple( 'paper', ['title', 'authors', 'year', 'doi'] )
for (id, paper_info) in Summaries.iteritems():
Summaries[id] = paper( *paper_info )
It was easy to get the number of unique titles for each year, since both 'title' and 'year' contain one value, but i can't figure out how to count the number of unique authors per year.
I don't expect you guys to give me the entire code or something, but if you could give me a link to a good tutorial about this subject this would help a lot.
I did google around a lot, but i cant find any helpful information!
I hope i'm not asking too much, first time i ask a question here.
EDIT:
Thanks for the responses so far. This is the code i have now:
authors = [
auth
for paper in Summaries.itervalues()
for auth in paper.authors
]
authors
The problem is, i only get a list of all the authors with this code. I want them linked to the year tough, so i can check the amount of unique authors for each year.
A: For keeping track of unique objects, I like using set. A set behaves like a mathematical set in that it can have at most one copy of any given thing in it.
from collections import namedtuple
# by convention, instances of `namedtuple` should be in UpperCamelCase
Paper = namedtuple('paper', ['title', 'authors', 'year', 'doi'])
papers = [
Paper('On Unicorns', ['J. Atwood', 'J. Spolsky'], 2008, 'foo'),
Paper('Discourse', ['J. Atwood', 'R. Ward', 'S. Saffron'], 2012, 'bar'),
Paper('Joel On Software', ['J. Spolsky'], 2000, 'baz')
]
authors = set()
for paper in papers:
authors.update(paper.authors) # "authors = union(authors, paper.authors)"
print(authors)
print(len(authors))
Output:
{'J. Spolsky', 'R. Ward', 'J. Atwood', 'S. Saffron'}
4
More compactly (but also perhaps less readably), you could construct the authors set by doing:
authors = set([author for paper in papers for author in paper.authors])
This may be faster if you have a large volume of data (I haven't checked), since it requires fewer update operations on the set.
A: If you don't want to use embeded type set() and want to understand the logic, use a list and if bifurcation.
If we don't use set() in senshin's code:
# authors = set()
# for paper in papers:
# authors.update(paper.authors) # "authors = union(authors, paper.authors)"
authors = []
for paper in papers:
for author in paper.authors:
if not author in authors:
authors.append(author)
You can get similar result as senshin's. I hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26683155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CS50 Why can't my code crack a four digit password? I've encountered a problem in C that held me for the past 6 hours, and after research and studies, I decided to seek for help! Sorry, my English is not my first language and I am a beginner coder.
I am able to crack all passwords that are three digits long. However, it seems like I cannot crack passwords that are four digits long. I've tried my best to make some comprehension and figure out my mistakes in the code, but it seems I cannot do so. Please help!
Also, it would be very nice if there would be more explanations why I cannot crack a four digit long passwords instead of plain solution. Thank you in advance!
#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <crypt.h>
#include <unistd.h>
int main (int argc, char* argv[])
{
if (argc != 2){
printf("Invalid input\n");
return 1;
}
char* hash = argv[1];
char code[4];
char* alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int length = strlen(alphabet);
for (int a = 0; a <= length; a++)
{
code[0] = alphabet[a];
printf("%s\n", code);
if (strcmp(crypt(code, "50"), hash) == 0)
{
printf("%s\n", code);
return 0;
}
for (int b = 0; b <= length; b++)
{
code[1] = alphabet[b];
//printf("%s\n", code[1]);
if (strcmp(crypt(code, "50"), hash) == 0)
{
printf("%s\n", code);
return 0;
}
for (int c = 0; c <= length; c++)
{
code[2] = alphabet[c];
//printf("%s\n", code[2]);
if (strcmp(crypt(code, "50"), hash) == 0)
{
printf("%s\n", code);
return 0;
}
for (int d = 0; d <= length; d++)
{
code[3] = alphabet[d];
//printf("%s\n", code[3]);
if (strcmp(crypt(code, "50"), hash) == 0)
{
printf("%s\n", code);
return 0;
}
}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53133629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to SPLIT cell content into sets of 50000 characters in new columns Google Sheets I have 3 columns A, B & C as shown in the image. Column A contains the search key. The second column B contains names and their respective content in the third column C.
I am filtering rows that contain the text in A1 in B:C and concatenating them. The challenge is that each text in the third column is roughly 40k characters. The filter formula works well so the issue is the character limit. This formula =ArrayFormula(query(C1:C,,100000)) which I have in F1 concatenates more than 50000 characters but I am not how to apply it for my case.
Tried to wrap my formula in E1 inside the query function but it wasn't successful. Like so:
=ArrayFormula(query(CLEAN(CONCATENATE(FILTER(C1:C, B1:B=A1))),,100000)).
I also tried to SPLIT the concatenated result into sets of 50000 characters and put the extras in the next columns but wouldn't manage either. The formula I tried in this case is:
=SPLIT(REGEXREPLACE(CLEAN(CONCATENATE(FILTER(C1:C, B1:B=A1))),".{50000}", "$0,"),",")
The link to the spreadsheet
https://docs.google.com/spreadsheets/d/1rhVSQJBGaPQu6y2WbqkO2_UqzyfCc3_76t4AK3PdF7M/edit?usp=sharing
A: Since cell is limited to 50,000 characters, using CONCATENATE is not possible. Alternative solution is to use Google Apps Script's custom function. The good thing about Apps Script is it can handle millions of string characters.
To create custom function:
*
*Create or open a spreadsheet in Google Sheets.
*Select the menu item Tools > Script editor.
*Delete any code in the script editor and copy and paste the code below.
*At the top, click Save.
To use custom function:
*
*Click the cell where you want to use the function.
*Type an equals sign (=) followed by the function name and any input value — for example, =myFunction(A1) — and press Enter.
*The cell will momentarily display Loading..., then return the result.
Code:
function myFunction(text) {
var arr = text.flat();
var newStr = arr.join(' ');
var slicedStr = stringChop(newStr, 50000);
return [slicedStr];
}
function stringChop(str, size){
if (str == null) return [];
str = String(str);
size = ~~size;
return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str];
}
Example:
Based on your sample spreadsheet, there are 4 rows that matches the criteria of the filter and each cell contains 38,976 characters, which is 155,904 characters in total. Dividing it by 50,000 is 3.12. The ceiling of 3.12 is 4 which means we have 4 columns of data.
Usage:
Paste this in cell E1:
=myFunction(FILTER(C1:C, B1:B=A1))
Output:
Reference:
*
*Custom Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68166267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How would I write a malware detection software? What are the resources I need to go through to fully understand how this works? I've looked up online but all I got are software solutions rather than how the software actually detects them.
I want to be able to detect a malware that's in my computer. Let's say there's a trojan horse in my Computer. How would I write a program to detect it?
I'm a beginner at Information Security.
Thanks in advance.
A: Well most endpoint security products have:
- an on-demand scanning component.
- a real-time scanning component.
- hooks into other areas of the OS to inspect data before "released". E.g. Network layer for network born threats.
- a detection engine - includes file extractors
- detection data that can be updated.
- Run time scanning elements.
There are many layers and components that all need to work together to increase protection.
Here are a few scenarios that would need to be covered by a security product.
*
*Malicious file on disk - static scanning - on-demand. Maybe the example you have.
A command line/on-demand scanner would enumerate each directory and file based on what was requested to be scanned. The process would read files and pass streams of data to a detection engine. Depending on the scanning settings configured and exclusions, files would be checked. The engine can understand/unpack the files to check types. Most have a file type detection component. It could just look at the first few bytes of a file as per this - https://linux.die.net/man/5/magic. Quite basic but it gives you an idea on how you can classify a file type before carrying out more classifications. It could be as simple as a few check-sums of a file at different offsets.
In the case of your example of a trojan file. Assuming you are your own virus lab, maybe you have seen the file before, analyzed it an written detection for it as you know it is malicious. Maybe you can just checksum part of the file and publish this data to you product. So you have virusdata.dat, in it you might have a checksum and a name for it. E.g.
123456789, Troj-1
You then have a scanning process, that loads your virus data file at startup and opens the file for scanning. You scanner checksums the file as per the lab scenario and you get a match with the data file. You display the name as it was labelled. This is the most basic example really and not that practical bu hopefully it serves some purpose. Of course you will see the problem with false positives.
Other aspects of a product include:
*
*A process writing a malicious file to disk - real-time.
In order to "see" file access in real-time and get in that stack you would want a file system filter driver. A file system mini filter for example on Windows: https://msdn.microsoft.com/en-us/windows/hardware/drivers/ifs/file-system-minifilter-drivers. This will guarantee that you get access to the file before it's read/written. You can then scan the file before it's written or read by the process to give you a chance to deny access and alert. Note in this scenario you are blocking until you come to a decision whether to allow or block the access. It is for this reason that on-access security products can slow down file I/O. They typically have a number of scanning threads that a driver can pass work to. If all threads are busy scanning then you have a bit of an issue. You need to handle things like zip bombs, etc and bail out before tying up a scanning engine/CPU/Memory etc...
*A browser downloading a malicious file.
You could reply on the on-access scanner preventing a file hitting the disk by the browser process but then the browsers can render scripts before hitting the file system. As a result you might want to create a component to intercept traffic before the web browser. There are a few possibilities here. Do you target specific browsers with plugins or do you go down a level and intercept the traffic with a local proxy process. Options include hooking the network layer with a Layered Service Provider (LSP) or WFP (https://msdn.microsoft.com/en-us/windows/hardware/drivers/network/windows-filtering-platform-callout-drivers2). Here you can redirect traffic to an in or out of process proxy to examine the traffic. SSL traffic poses an issue here unless you're going to crack open the pipe again more work.
*Then there is run-time protection, where you don't detect a file with a signature but you apply rules to check behavior. For example a process that creates a start-up registry location for itself might be treated as suspicious. Maybe not enough to block the file on it's own but what if the file didn't have a valid signature, the location was the user's temp location. It's created by AutoIt and doesn't have a file version. All of these properties can give weight to the decision of if it should be run and these form the proprietary data of the security vendor and are constantly being refined. Maybe you start detecting applications as suspicious and give the user a warning so they can authorize them.
This is a massively huge topic that touches so many layers. Hopefully this is the sort of thing you had in mind.
A: Among the literature, "The Art of Computer Virus Research and Defense" from Peter Szor is definitely a "must read".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41392665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Salesforce - Eliminate the "Action" column in the support view The support view has the "Action" column. How do you disable it? The end users do not need this column, and it takes up so much space.
See screenshot
A: I've successfully used Adblock plus to remove elements from the view. The action column has a unique class (x-grid3-td-ACTION_COLUMN) so if you add the rule ##td.x-grid3-td-ACTION_COLUMN it should remove the column.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16699460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kendo UI Angular Upload File to Backend as Node.JS I am using Kendo Upload Control to upload files to Node.js backend which used GridFS multer.
Angular
<kendo-upload
[saveField]="file"
[withCredentials]="false"
[saveUrl]="uploadUrl"
(autoUpload)="false"
[multiple]="false"
(select)="selectProfilePic($event)"></kendo-upload>
But the node.js API doesn't pick up the request. I am using [saveField]="file" to pass the uploaded file and the node.js below.
var storage = new GridFsStorage({
//url: mongoose.connection.client.s.url,
//options: options,
db: mongoose.connection,
file: (req, file) => {
return new Promise((resolve, reject) => {
myCrypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
router.post('/upload', upload.single('file'), fileUpload);
module.exports = router;
function fileUpload(req, res) {
console.log("fileUpload")
try {
res.send({ file: req.file })
}
catch(err){
console.log(err);
res.send(err)
}
}
Logs
2019-07-21T19:34:33.679205+00:00 app[web.1]: File Controller
2019-07-21T19:34:33.680436+00:00 app[web.1]: {}
2019-07-21T19:34:33.983631+00:00 app[web.1]: MulterError: Unexpected
field 2019-07-21T19:34:33.983647+00:00 app[web.1]: at
wrappedFileFilter (/app/node_modules/multer/index.js:40:19)
2019-07-21T19:34:33.983649+00:00 app[web.1]: at Busboy.
(/app/node_modules/multer/lib/make-middleware.js:114:7)
2019-07-21T19:34:33.983650+00:00 app[web.1]: at Busboy.emit
(events.js:198:13) 2019-07-21T19:34:33.983670+00:00 app[web.1]: at
Busboy.emit (/app/node_modules/busboy/lib/main.js:38:33)
2019-07-21T19:34:33.983671+00:00 app[web.1]: at PartStream.
(/app/node_modules/busboy/lib/types/multipart.js:213:13)
2019-07-21T19:34:33.983673+00:00 app[web.1]: at PartStream.emit
(events.js:198:13) 2019-07-21T19:34:33.983674+00:00 app[web.1]: at
HeaderParser. (/app/node_modules/dicer/lib/Dicer.js:51:16)
2019-07-21T19:34:33.983675+00:00 app[web.1]: at HeaderParser.emit
(events.js:198:13) 2019-07-21T19:34:33.983677+00:00 app[web.1]: at
HeaderParser._finish
(/app/node_modules/dicer/lib/HeaderParser.js:68:8)
2019-07-21T19:34:33.983678+00:00 app[web.1]: at SBMH.
(/app/node_modules/dicer/lib/HeaderParser.js:40:12)
2019-07-21T19:34:33.983679+00:00 app[web.1]: at SBMH.emit
(events.js:198:13) 2019-07-21T19:34:33.983680+00:00 app[web.1]: at
SBMH._sbmh_feed (/app/node_modules/streamsearch/lib/sbmh.js:159:14)
2019-07-21T19:34:33.983682+00:00 app[web.1]: at SBMH.push
(/app/node_modules/streamsearch/lib/sbmh.js:56:14)
2019-07-21T19:34:33.983683+00:00 app[web.1]: at HeaderParser.push
(/app/node_modules/dicer/lib/HeaderParser.js:46:19)
2019-07-21T19:34:33.983685+00:00 app[web.1]: at Dicer._oninfo
(/app/node_modules/dicer/lib/Dicer.js:197:25)
2019-07-21T19:34:33.983686+00:00 app[web.1]: at SBMH.
(/app/node_modules/dicer/lib/Dicer.js:127:10)
2019-07-21T19:34:33.989908+00:00 heroku[router]: at=info method=POST
path="/v1/file/upload" host=herokuapp.com
request_id=aa1010df-d244-46bc-9b36-f8e437d5ad2a fwd="80.233.46.84"
dyno=web.1 connect=0ms service=312ms status=500 bytes=286
protocol=https
A: Is there any chance you had to set the field name to some file variable? So, I believe you expected [saveField]="file" to set field name to 'file' string but instead it searches for some this.filevariable which is undefined so you got field name set to the default 'files' value?
A: Followed @GProst suggestions and analysed a bit and the below fix worked and I don't know the solution yet.
As per the Kendo UI angular documentation,
Sets the FormData key which contains the files submitted to saveUrl.
The default value is files.
So, I just changed the parameter name from file to files and it worked.
const upload = multer({ storage });
router.post('/upload', upload.single('files'), fileUpload);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57136218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UITextView is partially scrolled down when view opened I create a UITextView and add a lot of text to it. When I launch the view, the UITextView is always partially scrolled down. Of cause the user can scroll up, but it just feels weird.
What happens? Did I miss any obvious settings?
Please refer to the following image. Part of text is cut out. I borrow the text from link.
I started a simple Single View Application. This is how my viewDidLoad looks like:
- (void)viewDidLoad {
[super viewDidLoad];
NSString* path = [[NSBundle mainBundle] pathForResource:@"license"
ofType:@"txt"];
NSString* terms = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
self.textField.text = terms;
}
And this is my storyboard:
This is how it looks after manually scroll up to the top.
A: Add this line at the end of your viewDidLoad:
[self.textField scrollRangeToVisible:NSMakeRange(0, 1)];
Like this:
- (void)viewDidLoad {
[super viewDidLoad];
NSString* path = [[NSBundle mainBundle] pathForResource:@"license"
ofType:@"txt"];
NSString* terms = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
self.textField.text = terms;
[self.textField scrollRangeToVisible:NSMakeRange(0, 1)];
}
A: This used to happens on all iPhone/iPod devices under landscape mode, and solutions by the others will work. Now it only happens for iPhone 6+ or iPhone 6s+ under landscape mode. This is a work around for it:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
dispatch_async(dispatch_get_main_queue(), ^{
[self.textView scrollRangeToVisible:NSMakeRange(0, 1)];
});
}
The view is scrolled somehow after the viewWillAppear and before viewDidAppear, and that's why we need the dispatch above.
A: I had the same problem and I solved it by getting the previous scroll position and reseting it after updating the "text"
CGPoint p = [self.texField contentOffset];
self.textField.text = terms;
[self.textField setContentOffset:p animated:NO];
[self.textField scrollRangeToVisible:NSMakeRange([tv.text length], 0)];
A: For those using Xamarin, this is the only solution that works for me:
textView.Text = "very long text";
DispatchQueue.MainQueue.DispatchAsync(() =>
{
textView.ContentOffset = new CGPoint(0, 0);
});
A: The best working solution for me (Objective C):
- (void)viewDidLayoutSubviews {
[self.myTextView setContentOffset:CGPointZero animated:NO];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29547361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Using StepVerifier in a parallel testing environment I am having some trouble when using StepVerifier's withVirtualTime and create methods in a parallel testing environment.
private static final Duration DELAY = Duration.ofSeconds(1);
public void testA() {
StepVerifier.withVirtualTime(() -> Mono.just(1).delayElement(DELAY))
.thenAwait(DELAY)
.expectNext(1)
.expectComplete()
.verify();
}
public void testB() {
StepVerifier.create(Mono.just(1).delayElement(DELAY))
.thenAwait(DELAY)
.expectNext(1)
.expectComplete()
.verify();
}
Maven Surefire plugin configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<groups>unit</groups>
<includes>
<include>**/*Test.java</include>
</includes>
<parallel>methods</parallel>
<threadCount>2</threadCount>
<trimStackTrace>false</trimStackTrace>
</configuration>
</plugin>
These tests fail with the following exceptions (The full stack traces available on GitHub, please refer links below.):
[ERROR] testA(com.github.hisener.StepVerifierTest) Time elapsed: 0.04 s <<< FAILURE!
java.lang.NullPointerException: timedScheduler
at java.base/java.util.Objects.requireNonNull(Objects.java:246)
[ERROR] testB(com.github.hisener.StepVerifierTest) Time elapsed: 0.043 s <<< FAILURE!
reactor.core.Exceptions$ReactorRejectedExecutionException: Scheduler unavailable
at reactor.core.Exceptions.failWithRejected(Exceptions.java:249)
I don't think it's related to delayElements, for instance, one of the following tests uses timeout and they also fail:
public void testA() {
StepVerifier.withVirtualTime(() -> Mono.just(1)).expectNext(1).expectComplete().verify();
}
public void testB() {
StepVerifier.create(Mono.just(1).timeout(DELAY)).expectNext(1).expectComplete().verify();
}
I have tested on both TestNG and Junit 5, but no luck. The code is available on GitHub:
*
*TestNG https://github.com/hisener/reactor-test-test
*JUnit 5 https://github.com/hisener/reactor-test-test/tree/junit5
A: StepVerifier#withVirtualTime replaces ALL default Schedulers with the virtual time one, so it is not a good idea to use it in parallel
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57509263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C# item Drag Fix I move three controls using this code on MouseMove Event :
if (inHareket)
{
GelenResimcik.Left = e.X + GelenResimcik.Left -MouseDownLocation.X;
GelenResimcik.Top = e.Y + GelenResimcik.Top - MouseDownLocation.Y;
GelenResimcik.BackColor = Color.Transparent;
ResimHareket.Left = e.X + ResimHareket.Left - MouseDownLocation.X;
ResimHareket.Top = e.Y + ResimHareket.Top - MouseDownLocation.Y;
Yonlendir.Left = e.X + Yonlendir.Left - MouseDownLocation.X;
Yonlendir.Top = e.Y + Yonlendir.Top - MouseDownLocation.Y;
Aktar.Left = e.X + Aktar.Left - MouseDownLocation.X;
Aktar.Top = e.Y + Aktar.Top - MouseDownLocation.Y;
Vazgec.Left = e.X + Vazgec.Left - MouseDownLocation.X;
Vazgec.Top = e.Y + Vazgec.Top - MouseDownLocation.Y;
}
and if I try move them faster the result is :
Notice : When i stop moving, the glow is not visible, it is only moving faster.
What shall I do?
EDIT :
My Controls
this.Yonlendir = new System.Windows.Forms.PictureBox();
this.Vazgec = new System.Windows.Forms.PictureBox();
this.Aktar = new System.Windows.Forms.PictureBox();
this.ResimHareket = new System.Windows.Forms.PictureBox();
this.GelenResimcik = new System.Windows.Forms.PictureBox();
My Init :
((System.ComponentModel.ISupportInitialize)(this.Yonlendir)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Vazgec)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Aktar)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ResimHareket)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.GelenResimcik)).BeginInit();
this.SuspendLayout();
//
// Yonlendir
//
this.Yonlendir.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Yonlendir.Cursor = System.Windows.Forms.Cursors.Arrow;
this.Yonlendir.Image = global::Surface.Properties.Resources.rotate;
this.Yonlendir.Location = new System.Drawing.Point(26, 74);
this.Yonlendir.Name = "Yonlendir";
this.Yonlendir.Padding = new System.Windows.Forms.Padding(5);
this.Yonlendir.Size = new System.Drawing.Size(30, 30);
this.Yonlendir.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.Yonlendir.TabIndex = 14;
this.Yonlendir.TabStop = false;
this.Yonlendir.Click += new System.EventHandler(this.Yonlendir_Click);
//
// Vazgec
//
this.Vazgec.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Vazgec.Cursor = System.Windows.Forms.Cursors.Arrow;
this.Vazgec.Image = global::Surface.Properties.Resources.iptal;
this.Vazgec.Location = new System.Drawing.Point(93, 8);
this.Vazgec.Name = "Vazgec";
this.Vazgec.Padding = new System.Windows.Forms.Padding(5);
this.Vazgec.Size = new System.Drawing.Size(30, 30);
this.Vazgec.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.Vazgec.TabIndex = 13;
this.Vazgec.TabStop = false;
this.Vazgec.Click += new System.EventHandler(this.buton1_Click);
//
// Aktar
//
this.Aktar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Aktar.Cursor = System.Windows.Forms.Cursors.Arrow;
this.Aktar.Image = global::Surface.Properties.Resources.kaydet;
this.Aktar.Location = new System.Drawing.Point(57, 8);
this.Aktar.Name = "Aktar";
this.Aktar.Padding = new System.Windows.Forms.Padding(5);
this.Aktar.Size = new System.Drawing.Size(30, 30);
this.Aktar.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.Aktar.TabIndex = 12;
this.Aktar.TabStop = false;
this.Aktar.Click += new System.EventHandler(this.Onayla_Click);
//
// ResimHareket
//
this.ResimHareket.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.ResimHareket.Cursor = System.Windows.Forms.Cursors.Arrow;
this.ResimHareket.Image = global::Surface.Properties.Resources.hareket;
this.ResimHareket.Location = new System.Drawing.Point(26, 38);
this.ResimHareket.Name = "ResimHareket";
this.ResimHareket.Padding = new System.Windows.Forms.Padding(5);
this.ResimHareket.Size = new System.Drawing.Size(30, 30);
this.ResimHareket.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ResimHareket.TabIndex = 11;
this.ResimHareket.TabStop = false;
this.ResimHareket.Click += new System.EventHandler(this.ResimHareket_Click);
this.ResimHareket.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ResmiHareket_MouseDown);
this.ResimHareket.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ResmiHareket_MouseMove);
this.ResimHareket.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ResimHareket_MouseUp);
//
// GelenResimcik
//
this.GelenResimcik.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.GelenResimcik.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.GelenResimcik.Location = new System.Drawing.Point(57, 39);
this.GelenResimcik.Name = "GelenResimcik";
this.GelenResimcik.Size = new System.Drawing.Size(438, 452);
this.GelenResimcik.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.GelenResimcik.TabIndex = 2;
this.GelenResimcik.TabStop = false;
My Timer (Interval 100):
private void ResimKontrol_Tick(object sender, EventArgs e)
{
try
{
if (ontanimli.Height != 0)
{
GelenResimcik.Image = ontanimliGelen;
GelenResimcik.Parent = cizim;
entegreGoster();
}
}
catch
{
}
}
entegreGoster and entegreGizle
public void entegreGoster() { GelenResimcik.BringToFront();ResimHareket.BringToFront();Aktar.BringToFront();Vazgec.BringToFront(); Yonlendir.BringToFront(); }
public void entegreGizle() { GelenResimcik.SendToBack(); ResimHareket.SendToBack(); Aktar.SendToBack(); Vazgec.SendToBack(); Yonlendir.SendToBack(); }
My MouseDown event :
private void ResmiHareket_MouseDown(object sender, MouseEventArgs e)
{
MouseDownLocation = e.Location;
inHareket = true;
}
I start timer when Open new form
Ontanimlilar ontanimli = new Ontanimlilar();
ontanimli.Show();
ResimKontrol.Start();
ontanimliGelen (public static pictureBox)
ontanimli Class :
Ciz.ontanimliGelen = seciliRes.Image;
this.Close();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40845162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Insert Element between each List element Is there a better way to insert an Element between each pair of elements into a List in Java than iterating through it
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1,2,3,5,8,13,21));
for (int i = 1; i < exampleInts.size(); i++) {
int delimiter = 0;
exampleInts.add(i, delimiter);
i++;
}
A: No, there is no ready utils for this in standard java libraries.
BTW, your loop is incorrect and will work infinitely until memory end. You should increment i variable one more time:
for (int i = 1; i < exampleInts.size(); i++) {
int delimiter = 0;
exampleInts.add(i, delimiter);
i++;
}
or change loop conditions to for (int i = 1; i < exampleInts.size(); i+=2) {
A: Try this solution it is working correctly.
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1, 2, 3, 5,
8, 13, 21));
int size = (exampleInts.size()-1)*2;
for (int i = 0; i < size; i+=2) {
int delimiter = 0;
exampleInts.add(i+1, delimiter);
}
System.out.println(exampleInts);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31160854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Displaying XML in JSF I have a method that gives back a formatted XML string. I want to show that on a JSF page in a nicely wrapped, readable way. I used this solution first.
<pre><h:outputText value="myBean.xml"/></pre>
The result is indented, but it doesn't wrap very long lines (with a lot of attributes for e.g.)
RichFaces is also available in my project. What would you suggest?
Thanks in advance,
Daniel
A: Not sure if I understand you right, but if it is a plain vanilla String with XML data which you want to display as-is in the JSF page, then the first logical step would be to escape the HTML entities so that it's not been parsed as HTML. You can use h:outputText for this, it by default escapes HTML entities (which is controllable by the 'escape' attribute by the way):
<h:outputText value="#{bean.xmlString}" />
Or if it is formatted and you want to preserve the formatting, then apply the CSS white-space:pre property on the parent HTML element.
Or if you want to add syntax highlighting (colors and so on), then consider a Javascript library which does the task. Googling "javascript xml syntax highlighting" should yield enough results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1656033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Understanding the slicing syntax in Numpy? I have an x dimensional matrix in Numpy. For this example, I will use a 2x2 array.
np.array([[2, 2], [3,3]])
How would I alternate adding a row and column of some value so the result would look like:
array([[2, x, 3, x],
[x, x, x, x].
[2, x, 3, x],
[x, x, x, x]])
This answer gives a helpful start by saying to set rows in a correctly-sized destination matrix b from a matrix a like so a[::2] = b but what does the ::2 do in the slicing syntax and how can I make it work on columns?
In short what do the x y and z parameters do in the following: a[x:y:z]?
A: If I understand what you want correctly, this should work:
import numpy as np
a = np.array([[2,2],[3,3]])
b = np.zeros((len(a)*2,len(a)*2))
b[::2,::2]=a
This 'inserts' the values from your array (here called a) into every 2nd row and every 2nd column
Edit:
based on your recent edits, I hope this addition will help:
x:y:z means you start from element x and go all the way to y (not including y itself) using z as a stride (e.g. 2, so every 2 elements, so x, x+2, x+4 etc up to x+2n that is the closest to y possible)
so ::z would mean ALL elements with stride z (or ::2 for every 2nd element, starting from 0)
You do that for each 'dimension' of your array, so for 2d you'd have [::z1,::z2] for going through your entire data, striding z1 on the rows and z2 on the columns.
If that is still unclear, please specify what is not clear in a comment.
One final clarification - when you type only : you implicitly tell python 0:len(array) and the same holds for ::z which implies 0:len(array):z.
and if you just type :: it appears to imply the same as : (though I haven't delved deep into this specific example)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54613544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a easy way to filter mulitfield in django's admin site? The Model:
class Person(Model):
(...)
fathers = models.ManyToManyField('Person', related_name="fathers_children", blank=True)
mothers = models.ManyToManyField('Person', related_name="fathers_children", blank=True)
sex = models.CharField(null=True, blank=True, max_length=1)
admin.py:
class PersonAdmin(admin.ModelAdmin):
form = PersonAdminForm
model = Person
fields = ('last_name', 'birth_date','fathers','mothers')
ordering = ['last_name','birth_date']
admin.site.register(Person, PersonAdmin)
(maybe I cut to much, but I think it is self descriptive)
Please don't think why person can have more than one father/mother - it is intentional.
And now when I enter to e.g /admin/person/836, got the form with two MultipleChoiceFields containing full list of persons.
I want to reduce both - fathers should contains males, mothers - females. But how to do it?
A: You can simply limit the queryset for those fields by overriding the init method in the PersonAdminForm class:
class PersonAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PersonAdminForm, self).__init__(*args, **kwargs)
self.fields['fathers'].queryset = Person.objects.filter(sex='m')
self.fields['mothers'].queryset = Person.objects.filter(sex='f')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40308948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adjusting of php.ini I know that it is possible to set parameters in php.ini like this:
error_log = "%sprogdir%/userdata/logs/%phpdriver%_error.log"
How can I properly run php using command line and set these parameters? Similarly:
php -c path/to/php/ini [here something like this: %sprogdir%=path1 %phpdriver%=path2]
A: Are you looking to be able to export a parameter to environment variables using PHP? If so, the exec command may be what you're looking for: PHP: exec - Manual.
You'd execute something similar to this I believe:
<?php
echo exec('export phpdriver=value');
?>
EDIT: Due to misunderstanding of the question.
To correctly answer the question, we are going to create a script to set some environment variables before executing some PHP from the command line.
Here is our example shell - php_runner.sh
#!/bin/bash
export progsdir=$1
export phpdriver=$2
php -c path/to/php/ini
Once this is created (remember to set correct permissions as well), we can execute it from command line as such:
/path/to/php_runner.sh path1 path2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20811313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Dismatched image texture with geometry I have created a planegeometry and a texture which is made by ImageUtils with CanvasRenderer,
and then I created a mesh and finished all relative parameters'settings. The result is that a PlaneGeometry with the image
texture in the space,but a diagonal line is showed up,what's more, one image are divided into two
parts by this diagonal line,thus images on this two parts become dismatched.How should I resolve it? The key code are as follows:
var planeGeo=new THREE.PlaneGeometry(2000,3000);
var map = THREE.ImageUtils.loadTexture( 'images/greenLines.png' );
map.wrapS=map.wrapT = THREE.RepeatWrapping;
map.repeat.set(2,2);
map.anisotropy = 16;
var planeMaterial=new THREE.MeshBasicMaterial({color:0xFFBBEE,map:map,overdraw:true});
var planeMesh=new THREE.Mesh(planeGeo,planeMaterial);
planeMesh.position.set(2000,-2000,5000);
scene.add(planeMesh);
NOTICE:the images are constructed by green lines.The result displays that lines are cut and one
line has become two lines which are located on two divided triangles .
Now how should I modify my code so that the two parts of this image looks matched well without displacement!
Can the diagonal line be removed?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13192741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Window in tkinter automatically closes I have some code here that I copied from the tkinter tutorials so I am sure it is 100% correct:
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
It is supposed to work but instead, when I run the program it shows the window for about 1 millisecond and then closes immediately. How do I fix this?
I am using Python 3.8.
A: mainloop() should be called on a tk.Tk object but in your code app is a tk.Frame object. So, try ...
root.mainloop()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66513049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compare two files in two different folders and replace it by the newer With this VBScript code I was able to copy files. If the file exists it does nothing, if not it will copy the files needed.
Dim Photo
SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"
Set ObjPhoto = CreateObject("Scripting.FileSystemObject")
For Each Photo In ObjPhoto.GetFolder( SourceFolder).Files
If Not ObjPhoto.FileExists(ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))) Then
photo.Copy ObjPhoto.BuildPath(DistinationFolder, Photo.Name), True
End If
Next
I want to compare the files if the source files also exists in the destination folder and replace it by the newer.
A: If you want to overwrite based on the last modified date, then the File object has the property you want: DateLastModified. (You can check all properties of the File object here.)
You already have access to the source file objects (your code's Photo variable) so you just need to get the target's file object.
Something like this should work:
Dim Photo
Dim targetFile, bmpTargetFilename, jpgTargetFilename
SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"
Set ObjPhoto = CreateObject("Scripting.FileSystemObject")
For Each Photo In ObjPhoto.GetFolder(SourceFolder).Files
bmpTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))
jpgTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Photo.Name)
If ObjPhoto.FileExists(bmpTargetFilename) Then
' Get the target file object
Set targetFile = ObjPhoto.GetFile(jpgTargetFilename)
' Now compare the last modified dates of both files
If Photo.DateLastModified > targetFile.DateLastModified Then
Photo.Copy jpgTargetFilename, True
End If
Else
Photo.Copy jpgTargetFilename, True
End If
Next
A couple of notes:
*
*It seems you are checking for the existence of a .BMP file yet copying a .JPG file, so I made it explicit by using two variables.
*I am also assuming you want to compare the JPG files, since those are the ones being copied.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30530377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: using cURL to retrieve JSON data for use with jQuery I've been reading this helpful post:
http://techslides.com/hacking-the-google-trends-api
It shows how you can use cURL in command line/terminal to request data from google trends, for example;
curl --data "ajax=1&cid=actors&geo=US&date=201310" http://www.google.com/trends/topcharts/trendingchart
Gives you a big block of what I think is JSON. Below is an example of what I am doing to use cURL within my PHP to get data like this- however I cannot find anything that would get the data from the above cURL command to work in PHP like below.
<?php
//initialize session
$url = "http://www.google.com/trends/hottrends/atom/feed?pn=p1";
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
//execute session
$data = curl_exec($ch);
echo $data;
//close session
curl_close($ch);
?>
How do I go about getting the data from above?
A: You can do the same with the PHP cURL extension. You just need to set the options through curl_setopt, so you would do something like this
$url = "http://www.google.com/trends/topcharts/trendingchart";
$fields = "ajax=1&cid=actors&geo=US&date=201310";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
Now you have the response of the website in $data and you can do whatever you want with it.
You can find the PHP cURL documentation on http://php.net/curl
A: Try this
// Complete url with paramters
$url = "http://www.google.com/trends/topcharts/trendingchart?ajax=1&cid=actors&geo=US&date=201310";
// Init session
$ch = curl_init();
// Set options
curl_setopt($ch, CURLOPT_URL, $url);
// Set option to return the result instead of echoing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute session
$data = curl_exec($ch);
// Close session
curl_close($ch);
// Dump json decoded result
var_dump(json_decode($data, true));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36108881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to prevent a click on the underlying element? How to prevent a click on the underlying element? When I hover the mouse over the board on the website https://08ce2429.my-trello-frontend.pages.dev/ - the label "Delete board" appears, when I click on it, the board is deleted, but the board page also opens. How to prevent this?
My code of the board element:
return (
<div key={props.id} className={`board-home id${props.id}`}>
<Link
className="board-link"
to={{ pathname: '/board/' + props.id }}
state={{ id: props.id }}
>
<div className="board-fade">
<h2 className="board-title">{props.title}</h2>
<div
className="delete-board"
id={String(props.id)}
onClick={(e) => {
try {
e.stopPropagation()
alert('stopPropagation')
} catch (err) {
alert(err)
}
// (document.querySelector(`.id${props.id}`) as HTMLElement).style.pointerEvents = "none"
deleteBoard((e.target as HTMLElement).getAttribute('id')!)
}}
>
Delete board
</div>
</div>
</Link>
<Routes>
<Route path="/board/:id" element={<Board />} />
</Routes>
</div>
)
stopPropagation() does not help.
A: Just use e.preventDefault() in onClick
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74495913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why is it possible to set a value in a slice using reflection? According to The Laws of Reflection it is not possible to set the value of an element as follows, you need to use its address.
This will not work:
var x float64 = 3.4
v := reflect.ValueOf(x)
v.SetFloat(7.1) // Error: will panic.
This will work:
var x float64 = 3.4
p := reflect.ValueOf(&x) // Note: take the address of x.
p.Elem().SetFloat(7.1)
So why will the following work when using slices?
floats := []float64{3}
v := reflect.ValueOf(floats)
e := v.Index(0)
e.SetFloat(6)
fmt.Println(floats) // prints [6]
http://play.golang.org/p/BWLuq-3m85
Surely v.Index(0) is taking the value instead of address from slice floats, thus meaning it shouldn't be settable like the first example.
A: In your first example, you pass the actual x. This will copy x and give it to reflect.ValueOf. When you try to do v.SetFloat, as it get only a copy, it has no way to change the original x variable.
In your second example, you pass the address of x, so you can access the original variable by dereferencing it.
In the third example, you pass floats to reflect.ValueOf, which is a slice. "Slice hold references to the underlying array" (http://golang.org/doc/effective_go.html#slices). Which mean that through the slice, you actually have a reference to the underlying object. You won't be able to change the slice itself (append & co) but you can change what the slice refers to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24440902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Proxy error: Could not proxy request /send from localhost:3000 to http://localhost:3001/ I'm sending some data from my ReactJS front-end application to my node/express backend, however, whenever I send the data, I get the error message mentioned in the title.
https://ibb.co/KbpwqZv
contact.js
This is my react js code where i declare my react from those who communicate with backend via axios
import React, { useState } from 'react'
import "./Contact.css";
import Axios from 'axios';
import {API} from '../backend';
const Contact = () => {
const [state,setState]= useState({
name:'',
lastname:'',
email:'',
message:'',
})
const [result,setResult] = useState(null);
const sendMail = e =>{
e.preventDefault();
Axios.post('/send',{...state})
.then(response => {
setResult(response.data);
setState({
name:'',
lastname:'',
email:'',
message:''
})
})
.catch(()=>{
setResult({
success:false,
message:"Something went wrong. Try again later"
})
setState("");
})
}
const onInputChange = e =>{
const {name,value} = e.target;
setState({
...state,
[name]: value
})
}
console.log("API is",API);
return (
<>
{result && (
<p className={`${result.success ? 'success' : 'error'}`}>
{result.message}
</p>
)}
<section className='contactus'>
<div className="container">
<h1 className='title'>CONTACT US</h1>
<form >
<div className="singleItem">
<label htmlFor="name">Name</label>
<input type="text"
name="name"
className="name"
placeholder="Your Name..."
value={state.name}
onChange={onInputChange}
/>
</div>
{/* <div className="singleItem">
<label htmlFor="Lastname">LastName</label>
<input type="text"
name="LastName"
className="LastName"
placeholder="Your Last Name..."
value={state.lastname}
onChange={onInputChange}
/>
</div> */}
<div className="singleItem">
<label htmlFor="email">Email</label>
<input type="email"
name="email"
className="email"
placeholder="Your Email..."
value={state.email}
onChange={onInputChange}
/>
</div>
<div className='textArea singleItem'>
<label htmlFor="message">Message</label>
<textarea name="message"
id=""
col="30"
rows="5"
placeholder="Your Message..."
value={state.message}
onChange={onInputChange}
>
</textarea>
</div>
<div className="msg">Message has been Sent</div>
<button type="button" className='btn btn-primary' onClick={sendMail}>Submit</button>
</form>
</div>
</section>
</>
)
}
export default Contact;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65760459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to mass update in Eloquent given an array of keys and values efficiently I have a very large (millions of rows) database table where I need to add some missing data from a 3rd party to every row.
The data source has a 'reference key' which is my only way to map to the correct item in the table
Each row needs 1 number updated
I can loop through the 3rd party data source and perform an eloquent Update to each row using a unique identifier, but this is very slow from my tests:
Orders
id, reference_key, new_value
int, string, double(8,2)
foreach ($xml as $row) {
Order::where('reference_key', $reference_key)
->update('new_value', (float)$row->new_value);
}
Is there a more efficient way I can do this?
A: I would do update statement to do all in once like this :
UPDATE OrderTable
INNER JOIN table_to_fill ON OrderTable.refkey = table_to_fill.refkey
SET OrderTable.value = table_to_fill.value
A: Eloquent is very powerfull to manage complicated relationship, joins, eager loaded models etc... But this abstraction has a performance cost. Each model have to be created, filled and saved, it is packed with tons of features you don't need for this precise use case.
When editing thousand or even millions of records, it is highly inefficient to use Eloquent models. Instead you can either use the laravel Query builder or a raw SQL statement.
I would recommend this approach:
$table = Db::table('orders');
foreach ($xml as $row) {
$table->where('reference_key', $reference_key)
->update('new_value', (float)$row->new_value);
}
But you can also do something like this:
foreach ($xml as $row) {
DB::statement('UPDATE orders SET new_value=? WHERE reference_key=?',
[(float)$row->new_value, $reference_key]);
}
It will cut down your execution time significantly but the loop over millions of XML lines will still take a long time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69988880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i get the position in the Array list model class in the Observer using Live Data? Observer<ArrayList<ActionModel>> arrayListObserve=new Observer<ArrayList<ActionModel>>() {
@Override
public void onChanged(@Nullable ArrayList<ActionModel> actionModels) {
Action1.setText(actionModels.get(position).getBackground_remarks());
}
};
here,i can get the ActionModel class object but i can't get the position of the arraylist so how can i get the position of arraylist??
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55156848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using repeat.vim for keymapping I'm trying to set a custom keymapping to do debug-stepping with gdb and pyclewn, like this:
nnoremap <leader>ds :Cstep<CR>
Now when pressing . I'd like this to be repeated, since stepping is probably something I'm going to do often. I found repeat.vim and a helpful SO answer, so I tried this:
nnoremap <silent> <Plug>CCstep :Cstep <bar> silent! call repeat#set("\<Plug>CCstep", v:count)<CR>
nmap <leader>ds <Plug>CCstep
I also tried using :Cstep<CR>:silent [...] instead of :Cstep <bar> silent to seperate the two commands.
Both variants don't seem to work. I either get a blinking screen (bell) when pressing . or something random happens, like some chars getting deleted.
What am I doing wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17590186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Shinydashboard 'topbar' Is it possible to place some items in the horizontal bar next to the dashboardHeader? I know you can place notificationItem on the far right like in this example. But I would like to use the same options as in dashboardSidebar like adding filters etc. I want such a filter on top:
A: Hi You can do something like this:
library(shiny)
library(shinydashboard)
CustomHeader <- dashboardHeader()
CustomHeader$children[[3]]$children <- div(style="min-width:200px;",tags$input(id="searchbox",placeholder = " Search...",type="text",class="chooser-input-search",style="width:200px;height:50px;"))
ui <- dashboardPage(
CustomHeader,
dashboardSidebar(),
dashboardBody()
)
server <- function(input, output, session) {}
shinyApp(ui, server)
A: Based on Pork Chop answer, you can simply use selectInput (or other shiny inputs) that you put in a div with float:left to span horizontally:
CustomHeader <- dashboardHeader()
CustomHeader$children[[3]]$children <- list(
div(style="float:left;height:50px",selectInput("select1", NULL, c("a","b","c"))),
div(style="float:left;height:50px",selectInput("select2", NULL, c("d","e","f"))))
ui <- dashboardPage(
CustomHeader,
dashboardSidebar(),
dashboardBody(textOutput("text1"),textOutput("text2"))
)
server <- function(input, output, session) {
output$text1 <- renderText({input$select1})
output$text2 <- renderText({input$select2})
}
shinyApp(ui, server)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40396410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to find gzip file is empty compressed file How to find gzip file is empty using perl
a.txt.gz when i uncompress its empty
how to find the compress gz are empty ?
A: You can't directly get the size of the uncompressed file, but you can use seek for it. Create an object from the file and try to seek to the first byte. If you can seek, then your file is at least 1 byte in size, otherwise it is empty.
#!/usr/bin/env perl
use strict;
use warnings;
use IO::Uncompress::Gunzip;
use Fcntl qw(:seek);
my $u = IO::Uncompress::Gunzip->new('readme.gz');
if ( $u->seek(1, SEEK_CUR) ) {
print "Can seek, file greather than zero\n";
}
else {
print "Cannot seek, file is zero\n";
}
A: You could use IO::Compress::Gzip which comes with Perl 5.10 and above (or download it via CPAN). And use that to read the file.
However, you could just do a stat on the file and simply see if it contains only 26 bytes since an empty file will consist of just a 26 byte header.
I guess it simply depends what you're attempting to do. Are you merely trying to determine whether a gzipped file is empty or did you plan on reading it and decompress it first? If it's the former, stat would be the easiest. If it's the latter, use the IO::Compress::Gzip module and not a bunch of system commands to call gzip. The IO::Compress::Gzip comes with all Perl distributions 5.10 and greater, so it's the default way of handling Zip.
A: To check the content of a compressed tar-file, use
tar -ztvf file.tgz
To list content of a .gz-file, use
gzip --list file.gz
Wrap that in perl and check the uncompressed field in the output
$ gzip --list fjant.gz
compressed uncompressed ratio uncompressed_name
26 0 0.0% fjant
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6153358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java Swing Window is Too Tall I am building a small application using Java Swing. The application will be used on several different computers. I am using a GridLayout. The problem is that the window is not adjustable since I show the gui like this:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(getContentPane());
pack();
setVisible(true);
I am aware that pack() is causing this. The program works fine on my computer but the window is relatively tall. On some other computers the bottom is cut off so that the user cannot access some features. What is the best solution for this? I have thought of several approaches but none of them seem optimal:
*
*Rearrange the window so that this is not a problem.
*Add a scroll bar.
Unfortunately, I would like to keep the window structured as it is since it looks nice and is intuitive. I already have scroll bars for some selectors so I think adding a scroll bar for the window will look very cluttered and add confusion.
I would appreciate any suggestions. Thanks.
A: If you don't want to add a scroll bar, and you don't want to rearrange the widgets, then the only options left are
*
*Lay the items out on more than one window (two pages for example).
*Change the scaling of the items (shrink them)
There is not an infinite number of approaches. The more approaches you decide are unsuitable will limit the opportunities to address the key issues. In your case, you have two dramatically different screen layouts, the obvious solution would be to detect the screen parameters, and select one of two different layouts, each tailored to look good.
A: Too much controls in a window is much boring. So why don't you categorize the controls and add them in different tabs using JTabbedPane ?
A: I think this is more suitable. If this is not desired, then adding a scroll pane would be better. Well shrinking the controls may not be that helpful
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29292948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to open iOS app from browser? I have to open my iOS app whenever user open a link of my app in browser. I have already used a like myApp:// but i want to open my app even when user open an http link a from browser. Just like pinterest. Pinterest opens app even if i open a regular http link like this http://www.pinterest.com/pseudoamber/ and using URL scheme as well like this pinterest://www.pinterest.com/pseudoamber/. My app is opening on myApp://www.myapp.com now i want to open my app when user open an http link like this http://www.myapp.com
Anybody please help
A: Here is an example using jQuery:
$(document).ready(function() {
var user_agent_header = navigator.userAgent;
if(user_agent_header.indexOf('iPhone')!=-1 || user_agent_header.indexOf('iPod')!=-1 || user_agent_header.indexOf('iPad')!=-1){
setTimeout(function() { window.location="myApp://www.myapp.com";}, 25);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23077411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: laravel validate conditional image field i have a field that required, and can be 2 value type : String (path) and Image file
how can write validation rule for this ?
if value is string check file_exist and if is file must be image
thanks
A: Maybe there's an easier way to do this. However, I think a custom rule as such should work.
$validator = Validator::make($request->all(), [
'image' => [
'required',
function ($attribute, $value, $fail) {
if(is_file($value)) {
if (true !== mb_strpos($value->getMimeType(), "image")) {
return $fail($attribute.' is invalid.');
}
}
if (is_string($value)) {
if(! file_exists($value)) {
return $fail($attribute.' is invalid.');
}
}
},
],
]);
A: i found my answer with FormRequest
MyTestFormRequest
<?php
use Illuminate\Foundation\Http\FormRequest;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class MyTestFormRequest extends FormRequest
{
public function rules()
{
$rules = [
"image" => ['required']
];
if(is_string($this->image)) {
$rules['image'][] = new FileExistsRule;
} else if($this->image instanceof UploadedFile) {
$rules['image'][] = 'image';
$rules['image'][] = 'dimensions:ratio=1/1';
}
return $rules;
}
}
FileExistsRule
<?php
use Illuminate\Contracts\Validation\Rule;
class FileExistsRule implements Rule
{
public function passes($attribute, $value)
{
return file_exists(public_path($value));
}
public function message()
{
return 'The file not exists';
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54168048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Catch Spotify app events in the background I'm observing changes on the Player model and console.logging the currently played song.
When I switch away from the app it works fine - but only for a minute or so.
Is there a way to keep the app alive?
A: Currently, the app object only lives on for 60 seconds after the context has been deselected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10542621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to pass id from button to modal <div class="panel panel-default">
<div id="view_query">
<div class="panel-heading">
<h3 class="panel-title">Reply Query</h3>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-hover table-bordered" id="example-1">
<thead>
<th>Name</th>
<th>Title</th>
<th class="no-sorting">Description</th>
<th class="no-sorting">Photo</th>
<th class="no-sorting">Date</th>
<th class="no-sorting">Actions</th>
</thead>
<tbody>
<?php for($i=1;$i<=12;$i++){?>
<tr>
<td>'NAME'</td>
<td>'Title'</td>
<td>'Description'</td>
<td>
<img src="" height="80px" width="100px">
</td>
<td>'dd/mm/yyyy'</td>
<td class="action">
<input type="submit" value=" Reply" href="javascript:;" onclick="jQuery('#modal-6').modal('show', {backdrop: 'static'});" style="background-color: #313437;border:1px solid #313437" class="btn btn-primary btn-single btn-sm fa-input">
<input type="text" hidden="" value="<?php echo $i;?>" name="id">
</input>
</td>
<?php }?>
</tr>
<!-- <form method="post" action="">
<button name="submit" id="btn_reply" class="btn btn-dark btn_add_record form-control text-left fa-input" value=" Reply" style="color:#fff" type="submit"></button>
<input type="text" hidden="" value="<?php echo $i;?>" name="id">
</form> -->
<!-- <a href="index.php?p=query&id= <?php echo $i;?>" id="btn_reply" class="btn btn-primary btn_add_record "><i class="fa fa-reply"></i> Reply</a> -->
</tbody>
</table>
</div>
</div>
</div>
</div>
This is my code of view data.when user click on reply button, i want to display modal.it displayed it but which button is clicked how i know?
i want to pass id to identified it so please help me how to pass it.
<div class="modal fade validate" id="modal-6">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Reply Query</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="form-group col-md-6">
<label class="control-label">Title</label>
<input class="form-control" disabled="" name="question" data-validate="required" data-message-required="Please Enter Title" placeholder="Enter Title" type="text">
</div>
<div class="form-group col-md-6">
<label class="control-label">URL</label>
<input class="form-control" name="url" disabled="" data-validate="required" data-message-required="Please Enter URL" placeholder="Enter URL" type="text">
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group no-margin">
<label for="description" class="control-label">Description</label>
<textarea class="form-control autogrow" id="description" placeholder="Describe Description Regarding Query"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label class="control-label">Image Upload</label>
<div>
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;" data-trigger="fileinput"> <img src="http://placehold.it/200x150" alt="..."> </div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px"></div>
<div> <span class="btn btn-white btn-file"> <span class="fileinput-new">Select image</span> <span class="fileinput-exists">Change</span>
<input type="file" name="..." accept="image/*"> </span> <a href="#" class="btn btn-orange fileinput-exists" data-dismiss="fileinput">Remove</a> </div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info">Send</button>
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
This is the code of modal.
A: Will suggest more easy and less complicated approach and bootstrap framework will handle the rest.
replace following
<td class="action">
<input type="submit" value=" Reply" href="javascript:;" onclick="jQuery('#modal-6').modal('show', {backdrop: 'static'});" style="background-color: #313437;border:1px solid #313437" class="btn btn-primary btn-single btn-sm fa-input">
<input type="text" hidden="" value="<?php echo $i;?>" name="id"></input>
</td>
With
<td class="action">
<button type="button" data-toggle="modal" data-target="#modal-6" data-id="This Is Id" class="btn btn-primary btn-single btn-sm fa-input">Reply</button>
</td>
Use data-toggle and data-target attributes to open the modal and with additional data-id attribute and show.bs.modal or shown.bs.modal modal events, can pass the value to modal
$(document).ready(function() {
$('#modal-6').on('show.bs.modal', function(e) {
var id = $(e.relatedTarget).data('id');
alert(id);
});
});
To keep the backdrop: 'static' add it in Modal HTML Markup
<div class="modal fade validate" id="modal-6" data-backdrop="static" data-keyboard="false">
<!--- Rest of the modal code ---->
</div>
A: I have been inspirited by @Shehary but had to use it with little different syntax.
$(document).ready(function() {
$('#modal-6').on('show.bs.modal', function(e) {
var id = $(e.relatedTarget.id).selector;
alert(id);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35823856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to automatically setup Google Account in Android Emulator I am trying to do some Android Automation using Python/Appium on GitLab.
I have found the way to create and launch the Android Emulator using the command line options.
But when the emulator opens, it requires the Google Account Setup in order to use Play Store/Gmail etc.
Creating a script through Appium is possible but would be little bit tedious work.
Is there any simpler way using some command line configuration during the initial setup to automatically setup the Google Account
avdmanager create avd --force --name "MyEmulator" --package "system-images;android-31;google_apis_playstore;x86_64" --device "pixel"
A: I've found you just need to pipe echo "no" into avdmanager create then start the emulator.
Something like this:
echo "y" | sdkmanager "system-images;android-31;google_apis_playstore;x86_64"
echo "no" | avdmanager create avd -n MyEmulator -k "system-images;android-31;google_apis_playstore;x86_64"
emulator64-arm -avd MyEmulator -noaudio -no-window -accel on
sleep 300 # wait for avd to start
# or detect when booting is finished
See also: How to create Android Virtual Device with command line and avdmanager?
You'll also need to wait for the avd to start. You can either sleep for a reasonably long period of time or try something more sophisticated like polling adb -e shell getprop init.svc.bootanim to see if the output says "stopped" -- example reference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71892337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Click A button faster We are playing a clicker game on a website where a button will be displayed at a random time, first 7 players to click it will be shown as the winners of that round. I wrote the clicker function bellow and always use it on my Chrome console.
(function () {
setInterval(() => {
const button = document.querySelector(“.click-button);
if (!button) return;
button.click();
}, 5);
})();
I was playing it with mobile network of 50 - 70 mbps of speed and was among the top 5 until when other players started using VPS Machine which have over 4gbps of internet speed. I now have a VPS running Windows server 2022 but cant still perform better. So My question is, Is it that my VPS speed is slower than their own or My Laptop have less specification than their own or I need a better javascript code than the one above?
Running the above code on a VPS server with a download speed of 4.3gbps and upload speed of 4.1gbps through a browser console and click faster
A: Your code can be a little faster by caching the function and the button outside the interval
(function() {
const button = document.querySelector(".click-button");
const buttonClick = () => button.click();
if (button) setInterval(buttonClick, 5);
})();
If the button does not exist at all, then the code above will not work. Then you do need the mutation oberver
A: Instead of polling for the button, you could use a MutationObserver that will notify you when the button changes or is inserted into the document. Unless you can get to the event that triggers the button activation, this is probably the fastest you can do.
Assuming that the button is inserted into a <div id="button-container"></div>:
const callback = mutations => {mutations.forEach(m => m.addedNodes.forEach(node => node.tagName === 'BUTTON' && node.click()))}
const observer = new MutationObserver(callback)
const container = document.getElementById('button-container')
observer.observe(container, {childList: true})
Have a look at this codepen
Replacing the forEach() with a for will give you a few additional nanoseconds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75268109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: HTable.get(List) results order What is the order of the Result array returned by a call to HTable.get(List<Get>)?
I mean, is correct to assume that is the same order of the input list?
A: The order in the result array will be the same as the order of the input list. Like the batch method, the ordering of execution of the actions is not defined but the result will always be in the same order. Since it will have a null in the results array for gets that failed, it would have been difficult to determine which have failed without looking in each Result instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12270821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Change colors of solid in drawable selector I have the following drawable:
<item android:state_pressed="true" android:text="texting .....">
<shape
xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<stroke android:width="@dimen/circleStrokeThickness" android:color="@color/earlGreen" />
<solid
android:color="@color/lightGrey"/>
<size
android:width="100dp"
android:height="100dp"/>
</shape>
</item>
<item android:state_pressed="false" android:text="texting .....">
<shape
xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<stroke android:width="4dp" android:color="@color/earlGreen" />
<solid
android:color="@android:color/white"/>
<size
android:width="100dp"
android:height="100dp"/>
</shape>
</item>
However, I need a number of similar one where the solid color is different but the rest is the same.
Is there any easy way to do this or should I just define a number of xml files?
I know it is possible to change the background color at runtime but I can't see how to get to the colour of a specific state.
A: You can define id for shape item <item android:id="@+id/shape_bacground"../> then at runtime you have to get background of your view and cast it to LayerDrawable and use findDrawableByLayerId() for find your shape and set it's color using
setColor(). Here is sample code:
drawable xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/float_button_shadow1">
</item>
<item
android:id="@+id/shape_bacground"
android:bottom="2dp"
android:left="1dp"
android:top="1dp"
android:right="1dp">
<shape android:shape="oval" >
<solid android:color="#1E88E5" />
</shape>
</item>
</layer-list>
Changing color
try {
LayerDrawable layer = (LayerDrawable) view.getBackground();
GradientDrawable shape = (GradientDrawable) layer
.findDrawableByLayerId(R.id.shape_bacground);
shape.setColor(backgroundColor);// set new background color here
rippleColor = makePressColor();
} catch (Exception ex) {
// Without bacground
}
A:
You can do same thing by programatically, Where you can change any
color at runtime by making function and passing Color in parameter.
ShapeDrawable sd1 = new ShapeDrawable(new RectShape());
sd1.getPaint().setColor(CommonUtilities.color);
sd1.getPaint().setStyle(Style.STROKE);
sd1.getPaint().setStrokeWidth(CommonUtilities.stroke);
sd1.setPadding(15, 10, 15, 10);
sd1.getPaint().setPathEffect(
new CornerPathEffect(CommonUtilities.corner));
ln_back.setBackgroundDrawable(sd1);
Hope it will help you !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35337482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Integrating Robolectric and Cucumber I want to combine both Robolectric and Cucumber (JVM).
Currently I have two classes ActivityStepdefs where two step definitions for activity management are defined.
My second class is RoActivity Where for example an activity is created from it's class name, and where Robolectric will be used.
When I run RoActivityTest using RobolectricTestRunner the test in this class passes, but when I run RunCukesTest (class for running features as junit test) the code from RoActivity is not running as part of Robolectric, i.e. RunCukesTest search for features on my project and match it with a method inside ActivityStepdefs and finally this class will call a method from RoActivity
Is possible to run test with both junit both* runners?
I'm not sure but perhaps it's possible to do something like powermock, using junit rules.
In that case for which one should I have to define the rule?
*Cucumber and Robolectric
A: My small 5 cents.
Cucumber is mostly used for acceptance tests (correct me if you use it for unit testing) and Robolectric is mostly used for unit testing.
As for me, it is overkill to write cucumber during TDD. And Robolectric is still not android and I would run acceptance tests on real device or at least emulator.
A: I'am facing the same problem, after some google work, I got a solution:
@RunWith(ParameterizedRobolectricTestRunner::class)
@CucumberOptions( features = ["src/test/features/test.feature","src/test/features/others.feature"], plugin = ["pretty"])
class RunFeatures(val index: Int, val name:String) {
companion object {
@Parameters(name = "{1}")
@JvmStatic
fun features(): Collection<Array<Any>> {
val runner = Cucumber(RunFeatures::class.java)
Cucumber()
val children = runner.children
return children.mapIndexed{index, feature ->
arrayOf(index,feature.name)
}
}
}
@Test
fun runTest() {
val core = JUnitCore()
val feature = Cucumber(RunFeatures::class.java).children[index]!!
core.addListener(object: RunListener() {
override fun testFailure(failure: Failure?) {
super.testFailure(failure)
fail("$name failed:\n"+failure?.exception)
}
})
val runner = Request.runner(feature)
core.run(runner)
}
}
but seems not an pretty solution for me, can somebody help me out these problem:
*
*must explicitly list all feature file path. but cannot use pattern such as *.feature
*when failed cannot know which step failed.
*parameter can only pass primitive type data,
I've get into cucumber source , but seems CucumberOptions inline Cucumber , I cannot pass it programmatically but can only use annotation .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16761357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What the best way to display html in the recyclerView? In the recyclerView I display comments. Comments are stored as HTML.
I tried to display the comments in webView - all displayed well (with the ability to use custom *.css) but recyclerView significantly retarding while scrolling. And I was not able to make it "transparent" to the touch, because commentView support ripple effect (android:background="?attr/selectableItemBackground") but webView - no.
Also I tried to display the comments in textView as spannable. Everything works fast but much more difficult to customize the appearance.
Help me to choose the best way to display the comments in recyclerView.
As a result I want to get something like this:
A: Here htmlString will is holding you html content.
TextView textView = (TextView)findViewById(R.id.tv_string);
textView.setText(Html.fromHtml(htmlString));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37887769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Inserting Row and getting Id, get error I insert a value / new row and I need the ID, but I get an error...
SQL code:
INSERT INTO [StoneTable] ([StoneName]) VALUES (@StoneName)
SELECT SCOPE_IDENTITY()
Using this code to insert row and getting the ID:
stoneTableTableAdapter = new StoneTableTabelleTableAdapter();
int id = Convert.ToInt32(stoneTableTableAdapter.InsertStoneNameAndReturnId("anything"));
//And on this 2nd Line I got an error
Error message:
There was an error parsing the query. [ Token line number = 2,Token line offset = 1,Token in error = SELECT ]
What's the problem? In my other project I use the same syntax, with no problems. Tried with @@IDENTITY, as well not working....
A: See the answer to this question for a suggestion on how to make your example work:
You should change your INSERT to return that inserted ID to you right away (in an OUTPUT clause)
A: You can only issue a single statement per batch in SQL Server Compact, and you cannot use Scope_identity, but must use @@IDENTITY (remember to keep the connection open betweeen the two calls)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8377589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use div's height to determine another div's padding or margin-top I am using the following jQuery to work out the width of a div (thats in %), to then tell another div to set it's height to that in pixels.
<script>
$("#top").height($("#left").width());
$("#bottom").height($("#left").width());
</script>
It's working really well. Now my next problem is, that I want my div called 'wrapper' to have a padding-top or margin-top of the pixel value it returns for the height. I tried changing 'height' to 'padding-top', but that didn't seem to work.
The end result is a web page with a series of 4 black div acting as a border around the edge, it calculates 5% of the with of the window, and that determine's the pixel value for how how the top and bottom black div's are. That way it's exactly even. Now I want my inside wrapper div, to start exactly that far down the web page too.
A: Use the jQuery outerWidth function to retrieve the width inclusive of padding, borders and optionally margin as well (if you send true as the only argument to the outerWidth method).
A: Tested Solution: Find height of a div and use it as margin top of another div.
$('.topmargindiv').css('margin-top', function() {
return $('.divheight').height();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17005933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to divide workers and aggregate results? Given a payload submitted to a parentWorker:
*
*I divide the work amongst otherWorkers and I add the taskId of the parentWorker as an additional property in the payload
*each of the otherWorkers finish what they are responsible for
What I want is to know if 5 or 10 or 20 otherWorkers were queued/kicked off then when do they all finish? Because when all of them are finished, I want to start the next part of my workflow: nextWorker!
So the ideal pipeline is: parentWorker > X # of otherWorkers > everyone done? > nextWorker
How can I make this happen?
Please don't answer with a polling-based solution. I'm not looking for that.
I thought of using a cache:
*
*where the parentWorker would set the total # of otherWorkers that will be created, like: cachekey_<parertTaskId>_workersCreated: 10
*then the otherWorkers would decrement the # atomically by -1 after they finish and eventually the count will reach zero: cachekey_<parertTaskId>_workersCreated: 0 but who is supposed to act on that count?
a) If the idea is to let otherWorkers decrement it then check the value and to see if it is zero and kick off nextWorker ... that is flawed in a situation where:
cachekey_<parertTaskId>_workersCreated: 2
otherWorker9 sends -1
otherWorker10 sends -1
otherWorker9 checks and otherWorker10 checks
both get back 0 and both will kick off nextWorker! We only wanted one instance.
b) other bad ideas:
cachekey_<parertTaskId>_workersCreated: 2
otherWorker9 checks and otherWorker10 checks
neither one kicks off nextWorker because value!==1
otherWorker9 sends -1
otherWorker10 sends -1
its over and noone is left to act on cachekey_<parertTaskId>_workersCreated: 0
A: There's unfortunately no automated/very simple/built-in way to do this.
Regarding your idea to use a cache, if you use something like Redis, it's increment and decrement operations are atomic so you'd never get a case where both workers got back the same number. One worker and one worker only would get the zero back: http://redis.io/commands/decr
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37865739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: android list point to position I have 3 items in my listView, problem is that the pointToPosition() method is returning 1 for first item in the list and -1 for third item in the list. The rawx and rawy positions are correct as they match the dX and dY positions given by the device dev tools. I can not therefore work out how to get the correct cursor position for the list item especially the last position as code returns -1 rather than position 2. I can paste further code if required
int pos = listView.pointToPosition((int) arg1.getRawX(), (int) arg1.getRawY());
Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/x"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.buzz.ContactFragment"
tools:ignore="MergeRootFrame"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:id="@+id/contact_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@null"
/>
...
Fragment
public class ContactFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>,
GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener, View.OnTouchListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
gdc = new GestureDetectorCompat(getActivity().getApplicationContext(), this);
View rootView = inflater.inflate(
R.layout.fragment_contact, container, false);
listView = (ListView) rootView.findViewById(R.id.contact_list);
...
}
...
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
int pos = listView.pointToPosition((int) arg1.getRawX(), (int) arg1.getRawY());
Cursor cursor = (Cursor)listView.getItemAtPosition(pos);
...
}
...
A: The issue has been resolved based on suggestions found on the web but sorry can not remember the url.
public int getTouchPosition(MotionEvent motionEvent){
// Transient properties
int mDismissAnimationRefCount = 0;
float mDownX;
int mDownPosition=-1;
View mDownView=null;
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
}
return mDownPosition;
}
Can use the position to get the cursor position used to populate the view
Cursor cursor = (Cursor)mListView.getItemAtPosition(mDownPosition);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29055509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Box2d: Place object besides another one precisely? I was wondering about how to place fixtures right beside another one. Btw. I have probably confused myself.
So here is what I want to do:
LIKE THIS ILLUSTRATION
Could I just accomplish this by applying the sum of something like this positionX of leftWall + sizeX/2 of leftWall + sizeX/2 of box, to the box climbing the wall? Or is there some box2d function that automatically calculates the position?
After I have accomplished this, I will add a constant velocity to the box and therefore I need it to be exact plus the fact that it looks better. I have just confused myself too much and I do not know how but can anybody tell me what they would do?
Thanks! Much appreciated!
A: Go with "the sum of something".
I don't see it is a problem.
If you really dislike it, just write your own function to do it.
As you already know, it is not hard.
Detail
Box2D is not an architectural library.
As far as I know, there is no such function.
In 3D Physics and Graphics, I also faced a little inconvenience like this.
There are 2 choices for me :-
*
*hard code "the sum of something" (I start to love this phrase.)
*encapsulate such library (e.g. Box2D) / code a utility function
I usually pick one of the choices, depends on situation.
Because it is only little inconvenience, I believe the first is suitable for your situation.
By the way, there are reserved margin between colliding fixtures, so I think you can't set the exact position.
there is always a small margin of space added around the fixture by default.
A: An explanation of what's going on...
For static and kinematic bodies, where you place them is where they'll be. In other words, if you call b2Body::SetTransform with a position of pos and then call b2Body::GetPosition, the returned value should equal pos. This should hold true even if these bodies overlap each other. They won't move unless you tell them to.
Dynamic bodies behave differently however. They behave more like we'd expect solid bodies to behave in the real world. But we can do things to them still that couldn't practically be done to real solid objects. For instance, we can call b2Body::SetTransform on one dynamic body to place it (or part of it) within another body. Now the physics engine works to figure out where to move the dynamic body so that it's not within the other body anymore (and in a way that's intended to appear reasonable enough given what the initial overlap may look like).
More precisely, the 2.3.2 Box2D library will resolve the overlap of two bodies (where one or both are dynamic) as much as b2_maxLinearCorrection for each position iteration until minSeparation >= -3.0f * b2_linearSlop where minSeparation is the distance separating the closest vertices (of both shapes) in the separating plane minus the sum of the vertex radiuses (of both shapes). The "sequential solver" does this via impulses but without influencing the body velocity values so that neither body acts as if it had any additional momentum.
You can take a look at the code involved in the b2ContactSolver::SolvePositionConstraints method of the b2ContactSolver.cpp file.
So in a sense, the Box2D world step "calculates the position" for you. Note however the following caveats:
*
*This position resolution doesn't always complete in one step. I.e. users may watch as the box moves out from the wall till it appears entirely out.
*If you place the box too far into the wall, it will appear on the opposite side of the wall.
*You may want to factor in to your expectations the total of the vertex radiuses - i.e. sum the values of the shapes' m_radius values. This is referred to as the reserved margin of space. For two polygons, this will be 4.0f * b2_linearSlop or 0.02f (2 centimeters).
Insofar as placing an object beside another precisely then:
*
*You can place non-dynamic bodies beside each other as precisely as floating-point values allow.
*You can place a dynamic body beside another body only as close as position resolution allows (and only as precisely as floating-point values allow). Any closer, and the "sequential solver" will move it back out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42051227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery drop down menu strange behavior My Problem (Fiddle)
My problem is that on my jquery animated dropdown menu, when you hover over the "Other" link, the sub menu does not appear. When using firefox to 'Inspect Element', I find height is animated, and the width appears to be alright, yet all I see is the left border.
I noticed that if I have that particular section display as a block, when you animate the first menu it is shown, but upon entering the unordered list, it disappears (ex). I imagine it is somehow related to this, but I can not figure out what is causing this.
Any incite into what I'm probably just overlooking would be great, and of course much appreciated.
Notes:
*
*I have had this problem in Firefox, Chrome, Opera, and IE.
*It's designed such that it could work with only css. The the first .each is overriding default css hover behavior.
*the empty span holds the arrow image.
*only relevant code is posted. However, you may view my site here
*If you have any tips on making something more efficient, always welcome.
A: http://jsfiddle.net/sailorob/4cdTV/5/
I've removed your CSS for simplicity's sake and simplified your functions by utilizing jQuery slideUp and slideDown, which essentially handle many of the css properties you were managing with your functions. From here, I think it would be fairly simple to work back in some of your CSS.
When utilizing javascript/jQuery/animation on menus, I highly suggest using timers (setTimeout) for firing mouseenters and 'leaves. This way, your menu is more forgiving when a user accidentally moves their mouse a few pixels out of the menu and it closes.
A: Well, in debugging the JS and CSS I found that if you remove ALL the JS you have, the drop down menu with sub menus work fine. The Other li opens up the ul below it just fine. Note, it doesn't animate without the JS though.
Here's a forked fiddle.
I tested it in latest Chrome and Firefox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12097965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: problem while extracting data from api in react I have created an API to access data from the database. I have fetched the api data using axios and I want to display it. I have mapped the data, but it returns empty array for the first time.
const ExpenseList = () => {
const [result, setResult] = useState([]);
const expenseDetails = async () => {
try {
let res = await axios.get("http://127.0.0.1:8000/expense");
let result = res.data;
setResult(result);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
expenseDetails()
}, []);
console.log("result", result)
return (
<Container className='list-group'>
<Row className='title-row'>
<Col className='title-col-expenses'>Expenses</Col>
</Row>
{
result.map((items)=>{
<ExpenseItem id={items.id} name={items.name} cost={items.cost} />
})}
</Container>
)
}
I have attached a screenshot of console where I have logged "result"
Click to view image
A: as CevaComic said you are setting the initial value as an empty array.
useEffect will only work after the component has been rendered, so when you will console.log the data stored in result you will get the initial value.
Only after the component will render for the second time, because of the changed made inside setResult, the data from the api will be logged.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75121344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: string.Format give wrong thousand seperator in html razor C# block string.Format("{0:#,0}",19091507)
string.Format give wrong thousand seperator in html razor C# block
Expected Output : 19,091,507
Current Output : 1,90,91,507
Please help me.
A: You can try following.
int @value= 19091507;
Console.WriteLine(@value.ToString("#,#.##", System.Globalization.CultureInfo.CreateSpecificCulture("en-US")));
For me following is also working.
int @value= 19091507;
Console.WriteLine(string.Format("{0:#,#.##}", @value));
You can also try.
int @value= 19091507;
Console.WriteLine(string.Format(System.Globalization.CultureInfo.CreateSpecificCulture("en-US"),"{0:#,#.##}", @value));
It depends on your culture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71436968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find the position of equal elements in a matrix using Matlab Suppose I have:
m = [1,2,3;1,4,5;6,4,7]
I want to get a list containing the positions of the elements in the matrix m so that the positions of equal elements are grouped together. The output for matrix m must be:
{{1,1},{2,1}},{{2,2},{3,2}},{1,2},{1,3},{2,3},{3,1},{3,3}
% 1 2 3 4 5 6 7
We can see here that the positions for the elements that are all equal to each other are grouped together.
A: The simplest way would be to loop through every unique value and determine the row and column positions that match each value. Something like this could work:
val = unique(m);
pos = cell(1, numel(val));
for ii = 1 : numel(val)
[r,c] = find(m == val(ii));
pos{ii} = [r,c];
end
pos would be a cell array containing all of the positions for each unique value. We can show what these positions are by:
>> format compact; celldisp(pos)
pos{1} =
1 1
2 1
pos{2} =
1 2
pos{3} =
1 3
pos{4} =
2 2
3 2
pos{5} =
2 3
pos{6} =
3 1
pos{7} =
3 3
This of course is not meaningful unless you specifically show each unique value per group of positions. Therefore, we can try something like this instead where we can loop through each element in the cell array as well as display the corresponding element that each set of positions belongs to:
for ii = 1 : numel(val)
fprintf('Value: %f\n', val(ii));
fprintf('Positions:\n');
disp(pos{ii});
end
What I get is now:
Value: 1.000000
Positions:
1 1
2 1
Value: 2.000000
Positions:
1 2
Value: 3.000000
Positions:
1 3
Value: 4.000000
Positions:
2 2
3 2
Value: 5.000000
Positions:
2 3
Value: 6.000000
Positions:
3 1
Value: 7.000000
Positions:
3 3
A: This gives you what you want, except for the fact that indices of unique elements are also wrapped in cell twice, just like the indices of repeating elements:
m = [1,2,3;1,4,5;6,4,7];
[~, idx] = ismember(m(:), unique(m(:)));
linInd = 1:numel(m);
[i,j] = ind2sub(size(m), linInd);
res = accumarray(idx, linInd, [], @(x) {num2cell([i(x);j(x)]',2)});
Result:
>> celldisp(res)
res{1}{1} =
2 1
res{1}{2} =
1 1
res{2}{1} =
1 2
res{3}{1} =
1 3
res{4}{1} =
2 2
res{4}{2} =
3 2
res{5}{1} =
2 3
res{6}{1} =
3 1
res{7}{1} =
3 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37602059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JAVA a reliable equivalent for php's MCRYPT_RIJNDAEL_256 I need to access some data that used PHP encryption. The PHP encryption is like this.
base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($cipher), $text, MCRYPT_MODE_ECB));
As value of $text they pass the time() function value which will be different each time that the method is called in. I have implemented this in Java. Like this,
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
int i = (b & 0xFF);
if (i < 0x10) hex.append('0');
hex.append(Integer.toHexString(i));
}
return hex.toString();
}
public static byte[] rijndael_256(String text, byte[] givenKey) throws DataLengthException, IllegalStateException, InvalidCipherTextException, IOException{
final int keysize;
if (givenKey.length <= 192 / Byte.SIZE) {
keysize = 192;
} else {
keysize = 256;
}
byte[] keyData = new byte[keysize / Byte.SIZE];
System.arraycopy(givenKey, 0, keyData, 0, Math.min(givenKey.length, keyData.length));
KeyParameter key = new KeyParameter(keyData);
BlockCipher rijndael = new RijndaelEngine(256);
ZeroBytePadding c = new ZeroBytePadding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(rijndael, c);
pbbc.init(true, key);
byte[] plaintext = text.getBytes(Charset.forName("UTF8"));
byte[] ciphertext = new byte[pbbc.getOutputSize(plaintext.length)];
int offset = 0;
offset += pbbc.processBytes(plaintext, 0, plaintext.length, ciphertext, offset);
offset += pbbc.doFinal(ciphertext, offset);
return ciphertext;
}
public static String encrypt(String text, String secretKey) throws Exception {
byte[] givenKey = String.valueOf(md5(secretKey)).getBytes(Charset.forName("ASCII"));
byte[] encrypted = rijndael_256(text,givenKey);
return new String(Base64.encodeBase64(encrypted));
}
I have referred this answer when creating MCRYPT_RIJNDAEL_256 method."
Encryption in Android equivalent to php's MCRYPT_RIJNDAEL_256
"I have used apache codec for Base64.Here's how I call the encryption function,
long time= System.currentTimeMillis()/1000;
String encryptedTime = EncryptionUtils.encrypt(String.valueOf(time), secretkey);
The problem is sometimes the output is not similar to PHP but sometimes it works fine.
I think that my MCRYPT_RIJNDAEL_256 method is unreliable.
I want to know where I went wrong and find a reliable method so that I can always get similar encrypted string as to PHP.
A: The problem is likely to be the ZeroBytePadding. The one of Bouncy always adds/removes at least one byte with value zero (a la PKCS5Padding, 1 to 16 bytes of padding) but the one of PHP only pads until the first block boundary is encountered (0 to 15 bytes of padding). I've discussed this with David of the legion of Bouncy Castle, but the PHP zero byte padding is an extremely ill fit for the way Bouncy does padding, so currently you'll have to do this yourself, and use the cipher without padding.
Of course, as a real solution, rewrite the PHP part to use AES (MCRYPT_RIJNDAEL_128), CBC mode encryption, HMAC authentication, a real Password Based Key Derivation Function (PBKDF, e.g. PBKDF2 or bcrypt) and PKCS#7 compatible padding instead of this insecure, incompatible code. Alternatively, go for OpenSSL compatibility or a known secure container format.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26562421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Moving back to the the previous fragment tab (KEYCODE_BACK) Moving back to the previous fragment tab (KEYCODE_BACK)
I have something like
TAB
FA – FB –FC - FD
How can I implement something that when the back button is pressed it moves to the previous fragment i.e. from FD-->FC and from FC-->FB and from FB-->FA (TAB)
With the code below it moves from FD-->FB and from FC-->FA how can I correct this.
Thank you
View.setFocusableInTouchMode(true);//Called in Fragment D
View.requestFocus();
View.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment fragment = new FragmentC(); //move to previous fragment (FC)
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.my_container, fragment)
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return true;
}
else {
return false;
}
}
});
A: If you use addToBackstack to open new Fragments, it should work without the keyback listener. The fragmentTransaction manages this for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39351659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I can not install Entity Framework Power Tools Beta 4 on VS 2013 express Desktop Edition This is my first post and I hope that it meets all of the requirements!
System:
Windows 10
VS 2013 Desktop Express
I am attempting to install Entity Framework Power Tools Beta 4 but when I search through "Extensions and Updates" -> "Online" for "Entity Framework Power Tools Beta 4," it can not locate the package.
I thought to myself, perhaps it is only in vs 2015 that you can find this or perhaps it is only in non-express editions. Thus, I turned to the Intergoogles! I found the following site:
https://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
And there is support for vs2013 on this download! Yet, it says that it cannot locate any application on my machine that would use this if installed.
Can someone give me some guidance? Am I SOL if I am using VS 2013 but want access to the Entity Framework Power Tools Beta 4? I am using EF6 if that helps.
Thank you!
A: The Express edition do not support extensions, use Community edition 2013 instead. Julie Lerman has an updated version, that has been fixed to work with VS 2015 http://thedatafarm.com/data-access/installing-ef-power-tools-into-vs2015/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35688958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there strict type check in TypeScript? I'm codding some library with TypeScript, and I want to protect calls my methods from incorrect meaning data. Let's see next example:
type BookId = number;
type AuthorId = number;
BooksService.getById(bookId: BookId): Book {
// ...
};
let authorId: AuthorId;
// I need to get some type error in next lene, because getById() expect receive BookId, not AuthorId:
book = BooksService.getById(authorId);
Is it possible to get this error? How to upgrade my example to get it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55416977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: XSLT transformation stripping all namespaces from soap:env I have this Input XML to which i need to apply the XSL and transform it to a another XML which is on higher version. Lets say V3. So input XML is on version V1.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:NS1="http://www.test1/Error/v1"
xmlns:NS2="http://www.test1/Error/schema/SCRIPT"
xmlns:tns="http://www.test1/webservice/Service/v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<tns:Sample>
<NS2:Message release="006" version="010">
<NS2:Header>
<NS2:TestMessage>1</NS2:TestMessage>
</NS2:Header>
<NS2:Body>
<NS2:SampleTx>
<NS2:Element1>
<NS2:IdName>
<NS2:ID>
<NS2:IDValue>114</NS2:IDValue>
</NS2:ID>
</NS2:IdName>
</NS2:Element1>
</NS2:SampleTx>
</NS2:Body>
</NS2:Message>
</tns:Sample>
</soapenv:Body>
</soapenv:Envelope>
The XSL I am applying is
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:djh="http://www.test1/webservice/Service/v1"
xmlns:NS1="http://www.test1/Error/v1"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<xsl:output indent="yes"/>
<xsl:template match="@*|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="djh:*">
<xsl:element name="{name()}" namespace="http://www.test1/webservice/Service/v3">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
and the output I get is
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<tns:sendCancelRx xmlns:tns="http://www.test1/webservice/Service/v3">
<NS2:Message release="006" version="010"
xmlns:NS2="http://www.ncpdp.org/schema/SCRIPT">
<NS2:Header>
<NS2:TestMessage>1</NS2:TestMessage>
</NS2:Header>
<NS2:Body>
<NS2:SampleTx>
<NS2:Element1>
<NS2:IdName>
<NS2:ID>
<NS2:IDValue>114</NS2:IDValue>
</NS2:ID>
</NS2:IdName>
</NS2:Element1>
</NS2:SampleTx>
</NS2:Body>
</NS2:Message>
</tns:sendCancelRx>
</soapenv:Body>
</soapenv:Envelope>
It strips all the namespace declaration from xmlns:NS1="http://www.test1/Error/v1" xmlns:NS2="http://www.test1/Error/schema/SCRIPT" xmlns:tns="http://www.test1/webservice/Service/v1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
and the output I want is
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:NS1="http://www.test1/Error/v3"
xmlns:NS2="http://www.test1/Error/schema/SCRIPT"
xmlns:tns="http://www.test1/webservice/Service/v3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<tns:Test>
<NS2:Message release="006" version="010">
<NS2:Header>
<NS2:TestMessage>1</NS2:TestMessage>
</NS2:Header>
<NS2:Body>
<NS2:SampleTx>
<NS2:Element1>
<NS2:IdName>
<NS2:ID>
<NS2:IDValue>114</NS2:IDValue>
</NS2:ID>
</NS2:IdName>
</NS2:Element1>
</NS2:SampleTx>
</NS2:Body>
</NS2:Message>
</tns:Test>
</soapenv:Body>
</soapenv:Envelope>
I would appreciate if someone could let me know what is missing from my XSL.
A: Not sure why you say that it's stripping all those namespace prefix declarations. It strips those that aren't needed, but it leaves the declarations for NS2 and tns (and soapenv).
Having declarations for namespace prefixes that are unused accomplishes nothing. Why do you care? All the elements in your output XML are in the correct namespace. That's what matters to any downstream XML consumer.
(I'm assuming that the change of the namespace URI for NS2 is not part of the problem you're trying to solve.)
XSLT makes sure that each element in the output XML is in the proper namespace. Other than that, it doesn't offer fine control over where namespace prefixes are declared, because it doesn't affect the semantics of the output XML.
A: The difference between xsl:element name="{name()}" and xsl:copy is that xsl:copy copies the namespace declarations, while xsl:element doesn't. So use xsl:copy if you want them retained.
A: The following XSLT preserves all of the namespace declarations (used and unused) and changes the tns namespace-uri to http://www.test1/webservice/Service/v3:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:djh="http://www.test1/webservice/Service/v1"
xmlns:tns="http://www.test1/webservice/Service/v3"
xmlns:NS1="http://www.test1/Error/v1"
xmlns:NS2="http://www.test1/Error/schema/SCRIPT"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<xsl:output indent="yes"/>
<xsl:template match="@*|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="djh:*">
<!--reconstruct an element using the new v3 namespace,
but use the same namespace-prefix "tns"-->
<xsl:element name="tns:{local-name()}"
namespace="http://www.test1/webservice/Service/v3">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{name()}" namespace="{namespace-uri()}">
<!--copy all of the namespace declarations,
except for "tns" - which is v1 in the source XML -->
<xsl:copy-of select=
"namespace::*
[not(name()='tns')]"/>
<!--copy the namespace declaration for "tns" from the XSLT,
which is v3, and add it to the element-->
<xsl:copy-of select=
"document('')/*/namespace::*[name()='tns']"/>
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
It produces the following output with Saxon 9.x (does not preserve unused namespaces with Xalan, but that apparently is due to XALANJ-1959):
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:NS1="http://www.test1/Error/v1"
xmlns:NS2="http://www.test1/Error/schema/SCRIPT"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tns="http://www.test1/webservice/Service/v3">
<soapenv:Body>
<tns:Sample>
<NS2:Message release="006" version="010">
<NS2:Header>
<NS2:TestMessage>1</NS2:TestMessage>
</NS2:Header>
<NS2:Body>
<NS2:SampleTx>
<NS2:Element1>
<NS2:IdName>
<NS2:ID>
<NS2:IDValue>114</NS2:IDValue>
</NS2:ID>
</NS2:IdName>
</NS2:Element1>
</NS2:SampleTx>
</NS2:Body>
</NS2:Message>
</tns:Sample>
</soapenv:Body>
</soapenv:Envelope>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17118699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: pandas isin needs hashable data? Does the pandas.Series.isin function require the data to be hashable? I did not find this requirement in the documentation (Series.isin or Series, though I see the index needs to be hashable, not the data).
foo = ['x', 'y']
bar = pd.Series(foo, index=['a', 'b'])
baz = pd.Series([foo[0]], index=['c'])
print(bar.isin(baz))
works as expected and returns
a True
b False
dtype: bool
However, the following fails with the error TypeError: unhashable type: 'list':
foo = [['x', 'y'], ['z', 't']]
bar = pd.Series(foo, index=['a', 'b'])
baz = pd.Series([foo[0]], index=['c'])
print(bar.isin(baz))
Is that intended? Is it documented somewhere? Or is it a bug in pandas?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61235207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSON to Array C# Trying to get all info from a json file into an array with C# using Newtonsoft.Json only.
namespace tslife
{
partial class game
{
world[] game_intro = _read_world<world>("intro");
//** other code **//
public void update()
{
//crashes: System.NullReferenceException: Object reference not set to an instance of an object
Console.WriteLine(game_intro[0].data.Text);
}
private static T[] _read_world<T>(string level)
{
var json_data = string.Empty;
string st = "";
try
{
var stream = File.OpenText("Application/story/"+level+".json");
//Read the file
st = stream.ReadToEnd();
}
catch(SystemException e){}
json_data = st;
//Console.WriteLine(json_data);
// if string with JSON data is not empty, deserialize it to class and return its instance
T[] dataObject = JsonConvert.DeserializeObject<T[]>(json_data);
return dataObject;
}
}
}
public class worldData {
public string Text { get; set; }
public string Icon { get; set; }
public int sectionID { get; set; }
}
public class world
{
public worldData data;
}
I don't know if it is the formatting of the json however, but I'm stuck after searching else where.
[{
"world":
{
"Text":"Hi",
"Icon":"image01.png",
"sectionID": 0
}
},
{
"world":
{
"Text":"Hey",
"Icon":"image02.png",
"sectionID": 1
}
}
]
A: In serialization and deserialization without annotation the membernames need to match your JSON structure.
The class world and worldData are OK-ish but the world class is missing the property world.
If I change your class structure to this:
public class worldData {
public string Text { get; set; }
public string Icon { get; set; }
public int sectionID { get; set; }
}
// notice I had to change your classname
// because membernames cannot be the same as their typename
public class worldroot
{
public worldData world { get; set; }
}
I can deserialize your json in an array whicjh gives me two elements:
var l = JsonConvert.DeserializeObject<worldroot[]>(json);
And on the catching of exceptions: Only catch exceptions if you are going to do something sensible with them.
try
{
var stream = File.OpenText("Application/story/"+level+".json");
//Read the file
st = stream.ReadToEnd();
}
catch(SystemException e){}
empty catches like that are useless and only hinder in debugging. You can live with unchecked exceptions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26689620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Find duplicates of exactly two items from Array1 in Array2 using LINQ C# Say I've got an
Array1 [1,2,3]
and a List of arrays Array2 [3,2,4] Array3 [2,16,5]
I need to return only those elements of the List which contain exactly two ints from Array1. In this case, Array2 since integers 2 and 3 intersect;
Thanks
A: Try to combine Where() and Count():
var matches = new int[] { 1, 2, 3 };
var data = new List<int[]>
{
new int[] { 3, 2, 4 },
new int[] { 2, 16, 5 }
};
var result = data.Where(x => x.Count(matches.Contains) == 2);
A: since it's int[] you can use the .Intersect() directly. For example
from a in arrays where a.Intersect(Array1).Count() == 2 select a
//arrays contains Array2 and Array3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40576550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unable to connect AWS redshift from AWS lambda I'm trying to connect to AWS Redshift from my AWS Lambda function:
var Redshift = require('node-redshift');
const getLOOKUP_LOV_JSON= async ()=>{
try{
var client = {
host: "redshift-host",
user: 'admin',
database: 'dev',
password: 'password',
port: "5439"
};
return new Promise(function (resolve, reject) {
var redshiftClient = new Redshift(client, {rawConnection: true});
console.log("before Connect");
redshiftClient.connect(function(err){
console.log("after connect");
if(err){
console.log(err);
throw err;
}
else{
redshiftClient.query('SELECT * FROM "Persons"', {raw: true}, function(err, data){
if(err){
console.log(err);
throw err;
}
else{
console.log(data);
redshiftClient.close();
}
});
}
});
My code execute till before connect method ,I did not get any issue in my logger,it's print "before Connect" only.
A: The AWS Lambda function will need to be configured to connect to a private subnet in the same VPC as the Amazon Redshift cluster.
you would be getting timeout issue. to fix this you need to put your lambda function in VPC
you can do that following the tutorial https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html
Then add inbound rule in security group of Redshift for lambda function security group on port 5439
https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-security-groups.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67278079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Customize/Trim/Replace Wordpress Single Category Title I want to trim the Category Name from left to right. For example the Category Name is Men | Clothing, so I want to trim Men |, that just Clothing is displayed on the page.
I just found a line for trimming at the End:
<?php echo rtrim(single_cat_title('', false), 'g'); ?>
Or a line for replacing Men |, but then the output is Category: Clothing :
<?php echo str_replace("Men | ", "", get_the_archive_title()); ?>
I'm happy about any help. Thank you.
A: if your category name is like this : $str ="X | Y" and you want Y
You can try this:
$exp = explode("|", $str)
$y = $exp[1]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68544116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Changing background color of GtkEntry I have written a C language program with many GtkEntry's for data input. I have created the UI using Glade and the GtkEntrys emit an on_entry#_changed() signal when modified. My program checks the validity of the input, which has certain requirements. e.g., must be valid hexadecimal.
I would like the background of a GtkEntry to go red while it is invalid, and turn back to the original color when acceptable. The original color is dependent upon the desktop style set by the user. For example, on Ubuntu, I'm using a "Dark" style, so the box is dark gray.
What is the best way to implement this background color switching so that it applies to an individual GtkEntry and renders the user's chosen style color when the data is ok? I see a lot of discussion out there but it is often using deprecated functions.
A: You can use the error style class to mark the entry as having error. The following is a minimal example that checks if an entry has a valid hex digit and updates the entry style:
/* main.c
*
* Compile: cc -ggdb main.c -o main $(pkg-config --cflags --libs gtk+-3.0) -o main
* Run: ./main
*
* Author: Mohammed Sadiq <www.sadiqpk.org>
*
* SPDX-License-Identifier: LGPL-2.1-or-later OR CC0-1.0
*/
#include <gtk/gtk.h>
static void
entry_changed_cb (GtkEntry *entry)
{
GtkStyleContext *style;
const char *text;
gboolean empty;
g_assert (GTK_IS_ENTRY (entry));
style = gtk_widget_get_style_context (GTK_WIDGET (entry));
text = gtk_entry_get_text (entry);
empty = !*text;
/* Loop until we reach an invalid hex digit or the end of the string */
while (g_ascii_isxdigit (*text))
text++;
if (empty || *text)
gtk_style_context_add_class (style, "error");
else
gtk_style_context_remove_class (style, "error");
}
static void
app_activated_cb (GtkApplication *app)
{
GtkWindow *window;
GtkWidget *entry;
window = GTK_WINDOW (gtk_application_window_new (app));
entry = gtk_entry_new ();
gtk_widget_set_halign (entry, GTK_ALIGN_CENTER);
gtk_widget_set_valign (entry, GTK_ALIGN_CENTER);
gtk_widget_show (entry);
gtk_container_add (GTK_CONTAINER (window), entry);
g_signal_connect_object (entry, "changed",
G_CALLBACK (entry_changed_cb),
app, G_CONNECT_AFTER);
entry_changed_cb (GTK_ENTRY (entry));
gtk_window_present (window);
}
int
main (int argc,
char *argv[])
{
g_autoptr(GtkApplication) app = gtk_application_new (NULL, 0);
g_signal_connect (app, "activate", G_CALLBACK (app_activated_cb), NULL);
return g_application_run (G_APPLICATION (app), argc, argv);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74584399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DICOM and the Image Position Patient I am trying to figure out if DICOM Image Position (0020,0032) is an absolute coordinate or just the coordinates for whatever slice orientation I have?
For example, I have two planes, a sagittal and a coronal plane interleaved with respective Image Positions in mm in the form of (x,y,z) from the DICOM header. My question, is the (x,y,z) coordinate for the sagittal plane in the same 3D space as the (x,y,z) coordinate for the coronal plane or are the Image Position values specific for that plane only.
So, is the Image Position referenced off some absolute origin point or is changed for each specific image orientation?
Many thanks!
A: Image Position (Patient) (0020,0032) specifies the origin of the image with respect to the patient-based coordinate system and patient based coordinate system is a right handed system. All three orthogonal planes should share the same Frame of Reference UID (0020,0052) to be spatially related to each other.
A: Yes, the image position (0020,0032) coordinates are absolute coordinates. They are relative to an origin point called the "frame of reference". It doesn't matter where the frame of reference is, but for CT/MRI scanners you can think of it as a fixed point for that particular scanner, relative to the scanner table (the table moves the patient through the scanner, so the frame of reference has to move too - otherwise the z-coodinates wouldn't change!)
What's important when comparing two images is not where the frame of reference is, but whether the same frame of reference is being used. If they are from the same scanner then they probably will be, but the way to check is whether the Frame of Reference UID (0020,0052) is the same.
A few things to note: if you have a stack of 2D slices then the Image Position tag contains the coordinates of the CENTRE of the first voxel of the 2D SLICE (not the whole stack of slices). So it will be different for each slice.
Even if two orthogonal planes line up at an edge, the Image Position coordinates won't necessarily be the same because the voxel dimensions could be different, so the centre of the voxel on one plane isn't necessarily the same as the centre of the voxel on another plane.
Also, it's worth emphasising that the coordinates are relative in some way to the scanner, not to the patient. When your planes are all reconstructed from the same data then everything is consistent. But if two scans were taken at different times then the coordinates of patient features will not necessarily match up as the patient may have moved.
A: Yes, Image position is the absolute values of x, y, and z in the real-world coordinate system.
In MRI we have three different coordinate systems.
1. Real-world coordinate system
2. logical coordinate system
3. anatomical coordinate system.
sometimes they are referred with other names. There are heaps of names on the internet, but conceptually there are three of them.
To uniquely represent the status of the slice in the real world coordinate system we need to pinpoint its position and orientation.
The absolute x, y, and z of the first voxel that is transmitted (the one at the upper left corner of the slice) are considered as the image position. that's straightforward. But that is not enough. what if the slice is rotated?
So we have to determine the orientation as well.
To do that, we consider the first row and column of the image and calculate the cosine of their angles with respect to the main axes of the coordinate system as the image orientation.
Knowing these conventions, by looking at the image position (0020, 0032) and image orientation (0020, 0037) we can precisely pinpoint the slice in the real-world coordinate system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30814720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: String Boolean error java Can somebody tell me what I am doing wrong over here,
(Util.parseBoolean((String)request.getAttribute("testVal"), false))
I am getting this error.
java.lang.ClassCastException: java.lang.Boolean incompatible with java.lang.String
If what value I get from the request would do this. Thanks
Util just looks for request value and if it is y or true than sends back boolean value true. but my issue is when it goes to this line its throwing exception saying that error so I am not able to know whats happening
A: When you get an exception and you don't understand what's causing it, a good first step is to isolate exactly where it is happening. There are a lot of things happening in that one line of code, so it's difficult to know exactly what operation is causing the error.
Seeing the full stack trace of the exception might help, since it would give an idea of where you are in the execution path when the exception occurs.
However, a simple debugging technique is to break that one line with many operations into many lines with fewer operations, and see which line actually generates the exception. In your case this might be something like:
Object o = request.getAttribute("testVal");
String s = (String) o;
boolean b = Util.parseBoolean( s, false )
If the cause suggested by Shivan Dragon is correct, then the exception would occur on the second of these three lines.
A: Most likely this code: request.getAttribute("testVal") returns a Boolean, which cannot be cast to String, hence the (runtime) exception.
Either:
*
*check for code that populates the request attribute "testVal" with the boolean value (something like request.setAttribute("testVal", Boolean.FALSE)) and replace the value with a String
or
*
*Don't cast the value to String in your code, and don't use what seems to be a utility class for building a boolean value out of a String (*)
(*) which, btw, the Boolean class can do all by its lonesome self, no need to make your own library for that:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Boolean.html#valueOf(java.lang.String)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12186141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Getting input into a process While talking with a friend over yahoo messenger, I told him would be really cool to make a bot to answer with generic messages when someone starts a conversation. Upon thinking about what I told him, I realized it would be quite interesting to do something like that. The problem is that I don't know much about win32.
So my question is this: how do you 'link' a process to both another one and the windows environment? The goal would be to have an application running in the background which makes some sort of a query to see what windows are opened and when a new yahoo messenger conversation window appears it should send a list of keystroke events to that window.
I could use either C# or VC++ for the programming part and I can use any help: either specific answers or tips that could help me - e.g.: what to google for. So far my google research only came up with some apps/dlls/code that do that for you and some scripting stuff and I'm not exactly searching for that. I want to do all the work myself so I can learn from it.
A: It seems like you basically want to control other applications.
There are roughly 2 ways to do this on windows
1 - Use the low level windows API to blindly fire keyboard and mouse events at your target application.
The basic way this works is using the Win32 SendInput method, but there's a ton of other work you have to do to find window handles, etc, etc
2 - Use a higher level UI automation API to interact with the application in a more structured manner.
The best (well, newest anyway) way to do this is using the Microsoft UI Automation API which shipped in windows vista and 7 (it's available on XP as well). Here's the MSDN starter page for it.
We use the microsoft UI automation API at my job for automated UI testing of our apps, and it's not too bad. Beware though, that no matter how you chose to solve this problem, it is fraught with peril, and whether or not it works at all depends on the target application.
Good luck
A: Not quite the same domain as what you're looking for, BUT this series of blog posts will tell you what you need to know (and some other cool stuff).
http://www.codingthewheel.com/archives/how-i-built-a-working-poker-bot
A: If you really want to learn everything from scratch, then you should use C++ and native WIN32 API functions.
If you want to play a bit with C#, then you should look the pinvoke.net site and Managed Windows API project.
What you'll surely need is the Spy++ tool.
A: Check out Autohotkey. This is the fastest way to do what you want.
A: http://pinvoke.net/ seems to be the website you are looking for. The site explains how to use Windows API functions in higher level languages. Search on pinvoke for any of the functions I've listed below and it gives you the code necessary to be able to use these functions in your application.
You'll likely want to use the FindWindow function to find the window in which you're interested.
You'll need the process ID, so use GetWindowThreadProcessId to grab it.
Next, you'll need to use OpenProcess allow for reading of the process's memory.
Afterwards, you'll want to use ReadProcessMemory to read into the process's memory to see what happening with it.
Lastly, you'll want to use the PostMessage function to send key presses to the window handle.
Welcome to the wonderful world of Windows API programming.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4925818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: modalPresentationStyle formSheet issues on iphone XR, XS Max I am displaying modal UIViewController with modalPresentationStyle = .formSheet but it has some issues on iphone XR and XS Max. It's displayed behind notch. Image bellow from left side iphone XR, XS, X.
UIViewController use autolayout and is presented like this:
let contentViewController = UINib(nibName: "EditViewController", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! EditViewController
let navController = UINavigationController(rootViewController: contentViewController)
navController.modalPresentationStyle = UIModalPresentationStyle.formSheet
let popover = navController.presentationController!
popover.delegate = self
self.present(navController, animated: true, completion: nil)
delegate:
extension MyController: UIAdaptivePresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
}
There is same issue with modalPresentationStyle = .pageSheet. It works fine with other modalPresentationStyles ie fullscreen
It's on iOS 12.1, swift 3
Any idea how to fix this? Thanks
A: UIKit does not support that.
The only possibilities are sheet to full screen and page sheet to form sheet on iPad. As specified in the documentation :
In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.
So UIKit already adapts it.
Unfortunately you will have to implement your own custom transition controller.
A: As GaétanZ said, better use another modal presentation style like overFullScreen for compact horizontal size clases and leave the formSheet for the horizontally regular ones.
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
if controller.traitCollection.horizontalSizeClass == .regular {
return .formSheet
}
return .overFullScreen
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54106894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Adding background color to the selected cell in Google sheets by script All,
I am trying to make a timestamp sheet. The idea is whenever a user will press a button the selected cell will get the current time and background color will change to RED.
I managed to fix the time part but not able to get it change color. The closest I got to it is :
function timeStampM() {
SpreadsheetApp.getActiveSheet()
.getActiveCell()
.setValue(new Date());
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getDataRange();
var actCell = sheet.getActiveCell();
var actData = actCell.getValue();
var actRow = actCell.getRow();
if (actData != '' && actRow != 1) //Leaving out empty and header rows
{
range.getRange(actRow, 2).setBackground('red');
}
}
This colors the cell in the 2 column of the selected cell rather than the cell itself. Any help will be hugely appreciated.
_Best Regards
A: this appears to work:
function timeStampM() {
SpreadsheetApp.getActiveSheet()
.getActiveCell()
.setValue(new Date());
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getDataRange();
var actCell = sheet.getActiveCell();
var actData = actCell.getValue();
var actRow = actCell.getRow();
if (actData != '' && actRow != 1) //Leaving out empty and header rows
{
actCell.setBackground('Red');
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44026675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Xamarin Android 5.1.1, Leaflet, Mapbox not working in webview I have created an app that supports all Android 5.1.1, Android 9 and Android 10 rugged tablets. The application is built in Xamarin Android native (not Xamarin Forms). The application uses Leaflet to show maps in a Webview. A custom maps server feeds map tiles to Leaftlet.
Now bosses want to replace the custom maps server with Mapbox. Means, now Mapbox should feed map tiles to Leaflet. I have successfully got it working on Android 9, and Android 10 (in Xamarin Android, Leaflet, Webview). But maps do not show up on Android 5.1.1 at all. My Mapbox initialization code is as below:
var mapboxTiles = L.tileLayer(
`https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=<my_token>`,
{
attribution: '© <a href="https://www.mapbox.com/feedback/">Mapbox</a>',
tileSize: 512,
zoomOffset: -1,
});
map.addLayer(mapboxTiles);
This same piece of code works well on Android 9, and Android 10. But it does not work at Android 5.1.1. I have debugged WebView using Chrome (chrome://inspect) and in case of Android 5.1.1 the JavaScript file (in which I have written the above code) does not even load at all. I want that MapBox should work on Android 5.1.1 also.
Any help or guidance would be appreciated. Thanks guys.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69620225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cypress: import modules via alias in my project i am using cypress with plain javascript. i am facing the challenge of importing the modules (page objects) via aliases instead of spaghetti code like ../../../../folder/page.js.
I don't use typescript or react.js and don't have a src folder/directory.
my tests run locally in the browser or via a docker image (pipeline).
I would like to transform from this:
import { LoginPage } from "../../pages/loginPage.js";
to something like this:
import { LoginPage } from "@Pages/loginPage.js";
but I always get an error:
Error: Webpack Compilation Error
./cypress/e2e/accountOverview/accountOverviewPageTest.spec.js
Module not found: Error: Can't resolve 'Pages/loginPage.js' in 'C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\e2e\accountOverview'
resolve 'Pages/loginPage.js' in 'C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\e2e\accountOverview'
Parsed request is a module
using description file: C:\Users\User\automated_frontend_tests\automated_frontend_tests\package.json (relative path: ./cypress/e2e/accountOverview)
Field 'browser' doesn't contain a valid alias configuration
Looked for and couldn't find the file at the following paths:
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\e2e\accountOverview\node_modules]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\e2e\node_modules]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\node_modules]
[C:\Users\node_modules]
[C:\node_modules]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js]
[C:\Users\User\node_modules\Pages\loginPage.js]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.js]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.js]
[C:\Users\User\node_modules\Pages\loginPage.js.js]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.json]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.json]
[C:\Users\User\node_modules\Pages\loginPage.js.json]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.jsx]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.jsx]
[C:\Users\User\node_modules\Pages\loginPage.js.jsx]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.mjs]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.mjs]
[C:\Users\User\node_modules\Pages\loginPage.js.mjs]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.coffee]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.coffee]
[C:\Users\User\node_modules\Pages\loginPage.js.coffee]
@ ./cypress/e2e/accountOverview/accountOverviewPageTest.spec.js 5:17-46
I have tried several solutions, including:
//webpack.config.js
module.exports = {
resolve: {
alias: {
"@pages": path.resolve(__dirname, "cypress/pages/*"),
},
},
};
//testspec file
import { LoginPage } from "@pages/loginPage.js";
const loginPage = new LoginPage();
@Uzair Khan:
I tried your solution, but it still didn't work. The error message remains the same. It seems that the IDE does not search in the correct folder, but only in ...\node_modules\@page\loginPage.js which makes no sense.
If I enter const loginPage = new LoginPage(), the module LoginPage() cannot be found by the IDE either. Something is wrong with the solution. Do I still have to install any packages via NPM?
A: In your webpack.config.js file add resolve.alias which you want to make alias. It looks like something this below:
resolve: {
alias: {
'@page': path.resolve(__dirname, '{path you want to make alias}')
}
}
Since you are using cypress, you have to update the resolve path in cypress.config.js. Here is mine cypress.config.js
import { defineConfig } from 'cypress'
import webpack from '@cypress/webpack-preprocessor'
import preprocessor from '@badeball/cypress-cucumber-preprocessor'
import path from 'path'
export async function setupNodeEvents (on, config) {
// This is required for the preprocessor to be able to generate JSON reports after each run, and more,
await preprocessor.addCucumberPreprocessorPlugin(on, config)
on(
'file:preprocessor',
webpack({
webpackOptions: {
resolve: {
extensions: ['.ts', '.js', '.mjs'],
alias: {
'@page': path.resolve('cypress/support/pages/')
}
},
module: {
rules: [
{
test: /\.feature$/,
use: [
{
loader: '@badeball/cypress-cucumber-preprocessor/webpack',
options: config
}
]
}
]
}
}
})
)
// Make sure to return the config object as it might have been modified by the plugin.
return config
}
And import in other file via that alias you set in cypress.config.js. Here is mine for example:
import page from '@page/visit.js'
const visit = new page()
When('I visit duckduckgo.com', () => {
visit.page()
})
A: I think both answers are nearly there, this is what I have for src files:
const webpack = require('@cypress/webpack-preprocessor')
...
module.exports = defineConfig({
...
e2e: {
setupNodeEvents(on, config) {
...
// @src alias
const options = {
webpackOptions: {
resolve: {
alias: {
'@src': path.resolve(__dirname, './src')
},
},
},
watchOptions: {},
}
on('file:preprocessor', webpack(options))
...
path.resolve() resolves a relative path into an absolute one, so you need to start the 2nd param with ./ or ../.
Also, don't use wildcard * in the path, you just need a single folder that will be substituted for the alias in the import statement.
If in doubt, check the folder returned (in the terminal)
module.exports = defineConfig({
...
e2e: {
setupNodeEvents(on, config) {
const pagesFolder = path.resolve(__dirname, './cypress/pages')
console.log('pagesFolder', pagesFolder)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74488552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to adjust nav menu based nav item name character length? My problem: if the name of a main nav item in my dropdown menu increases in character length, my dropdown menu breaks (see attached imageTwo).
I’m using relative units of measure (ems mostly) in hopes that would give some responsiveness to my design and adjust the layout in case of an increase in character length of the main nav items but it didn’t work.
My main menu is relatively positioned and the sub-menus are absolutely positioned. These sub-menus, rather than dropdown vertically as is standard, instead expand horizontally in parallel to the main menu above it (see attached imageOne).
My goal now is to figure out how to correct code so that, in case of an increase or decrease in number of characters for the nav items in the main menu a) my main nav menu can readjust it’s width appropriately and b) my sub-menu will readjust it’s positioning to appear directly beneath the main menu above it.
My thought is, I will need to use some jQuery to do this but I wondered if it was possible using only CSS.
I’ve posted my CSS below; please let me know if more information is needed.
#navigation {
background: rgb(102,102,102);
max-height: 3.34em;
padding: 0;
position: relative;
max-width: 48.5em;
border-radius: 0;
}
#navigation .child-menu, #navigation .child-menu2 {
display: none;
}
#navigation li.hover #admin-submenu {
left: -405px;
}
#navigation li.hover .child-menu {
background: #47766c;
display: block;
position: absolute;
width: 80em;
z-index: 250;
top: 39px;
left: -334px;
}
#navigation ul li ul li:hover .child-menu2 {
background: #47766C;
display: block;
left: 0;
position: absolute;
top: 40px;
width: 110px;
z-index: 250;
}
A: #navigation ul li ul {
position:absolute;
min-width:100%;
height:40px;
margin:0px;
padding:0px;
left:0px;
top:40px;
}
#navigation ul li ul li {
float:left;
height:40px;
display:block;
padding-left:15px;
padding-right:15px;
}
You have to set the min-width of the submenus ul tag to 100% or same width as the page. Then its left:0px; Then the top is 40px or same as the parent menu height.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11675720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are the minimum required configurations at sender side and receiver side in spring boot RabbitMQ? I have just started with Spring boot RabbitMQ. I would like to know how can we separately configure producer code and consumer code in case of spring boot rabbitmq (annotations config). I mean to say, if I want to write rabbitmq producer code in spring boot and consumer code in python , or vice versa- consumer code in spring boot and producer code in python..I found no separate producer and consumer configurations in spring boot. For example,in case of Spring XML configuration, at the sender side, we only have exchange name and routing key available. There is no information at the producer side regarding queue name or type of exchange. But in contrast to this, in case of Spring boot, the Queue is configured at the sender side only, including the exchange binding. Can you please help me with separate sender and receiver configurations using spring boot. I am working on cross technology rabbitmq. So I would like to know sender and receiver minimum configurations required. Please help.
For eg- https://github.com/Civilis317/spring-amqp, in this code, at the producer side, in configuration file, the queue is configured. But in case of xml configuration, the producer had no idea about the queue. I would like to know what is the minimum configuration required at the sender in case of spring boot rabbitmq.
I mean to say, in xml configuration, the exchange-queue binding details were found at the consumer side xml file. But in spring boot, the exchange-queue binding is found at the sender config files only. Is it how it is written??
A:
But in contrast to this, in case of Spring boot, the Queue is configured at the sender side only, including the exchange binding.
That is not correct. What is leading you to that conclusion?
Messages are sent to an exchange with a routing key; the producer knows nothing about the queue(s) that are bound to the exchange.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49477356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When is error checking too much? During the process of my PHP learning I have been trying to read up on the best practices for error reporting and handling, but statements vary person to person and I have struggled to come up with a clear concise way of handling errors in my applications. I use exceptions on things that could go wrong, but for the most part it is hard for me to understand whether an exception should kill the application and display an error page or just be caught and silently dealt with.
Something that seems to elude me is, is there such thing as too much reporting? Every single time you call a function something could go horribly wrong meaning that if you were to confirm every single function call you would have to fill pages with if statements and work out what effect one failure may have on the rest. Is there a concise document or idea for error reporting that could clear this up for me? Are there best practices? What are the best examples of good error handling?
Currently I do the following:
*
*Add important event results to an array to be logged and emailed to me if a fatal error was to occur
*Display abstract/generic errors for fatal errors.
*Use exceptions for cases that are likely to fail
*Turn on error reporting in a development environment and off for live environment
*Validate all user input data
*Sanitizing invalid user input
*Display concise, informative error messages to users without providing a platform for exploitation.
A: Exceptions are the only thing that you haven't understood IMHO: exceptions are meant to be out of your control, are meant to be caught be dealt with from outside the scope they are thrown in. The try block has a specific limit: it should contain related actions. For example take a database try catch block:
$array = array();
try {
// connect throws exception on fail
// query throws exception on fail
// fetch results into $array
} catch (...) {
$array[0]['default'] = 'me';
$array[0]['default2'] = ...;
...
}
as you can see I put every database related function inside the try block. If the connection fails the query and the fetching is not performed because they would have no sense without a connection. If the querying fails the fetching is skipped because there would be no sense in fetching no results. And if anything goes wrong, I have an empty $array to deal with: so I can, for example, populate it with default data.
Using exceptions like:
$array = array();
try {
if (!file_exists('file.php')) throw new Exception('file does not exists');
include('file.php');
} catch (Exception $e) {
trigger_error($e->getMessage());
}
makes no sense. It just a longer version of:
if (!file_exists('file.php')) trigger_error('file does not exists');
include('file.php');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14500176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Android Studio - Cardview must click twice even i change android:focusableInTouchMode="false" im sorry. im begginer on android. i jus write a code with 4 cardview and the first one must click twice to work. But, the others cardview work with 1 click :(
And 3 others cardview can work without i give focusableInTouchMode property. Im confused with this issue and i have read about button clicked twice, it doesn't for me too. Please help me :)
Would you help me?
Here it;s my code :
...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<android.support.v7.widget.CardView
android:id="@+id/bangunan_menu"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_margin="10dp"
android:focusableInTouchMode="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:focusableInTouchMode="false">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/bangunan"
android:focusableInTouchMode="false"/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data Bangunan"
android:textSize="12sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:focusableInTouchMode="false"/>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/penyewa_menu"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/penyewa"/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data Penyewa"
android:textSize="12sp"
android:textStyle="bold"
android:layout_marginTop="10dp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</LinearLayout>
...
Thank you :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49227719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .net Word Interop closing issue I'm developing an application in vb.net that use Microsoft.Office.Interop.Word for printing an output in a Word document. If I close the application I want to close the doc (with the "Save As..." dialog). If the user wants to close the doc before the application ends this should be possible. Everything seems work fine, but after the closing (in both the case) I get this error:
This file is in use by another application or user.
(C:...\Templates\Normal.dotm)
I supposed the problem is that the doc owner is the application so the user can't close it... But the error also happens when the doc is closed by the application (with the quit method).
The code I run in frmMain_FormClosing is:
If _objWord IsNot Nothing Then
Try
_objWord.Quit()
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_objDoc)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_objWord)
Catch ex As Exception
End Try
End If
I do the same with Excel and I don't have any problem.
A: When adding a document, make sure you use
Dim d As Word.Document = w.Documents.Add()
and not
d = New Word.Document 'this syntax can cause a memory leak!'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13088039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Qt Widget temporarily fullscreen Consider a QWidget, normally a child in some Layout.
Supposed I want to make it fullScreen for a while, then have it return to it's old spot.
QWidget::setFullScreen() requires that the widget needs to be an independent window - any ideas how to work it out?
A: The simplest way I can see is to reparent to 0. Something like this:
#include <QApplication>
#include <QPushButton>
class MyButton : public QPushButton
{
public:
MyButton(QWidget* parent) : QPushButton(parent) {}
void mousePressEvent(QMouseEvent*) {
this->setParent(0);
this->showMaximized();
this->show();
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget mainWidget;
MyButton button(&mainWidget);
mainWidget.show();
return a.exec();
}
A: I have modified the previous example. The previous example never goes back to normal screen.
Just copy paste the code and it will run.
#include <QApplication>
#include <QPushButton>
class MyButton : public QPushButton
{
public:
MyButton(QWidget* parent) : QPushButton(parent) {
m_pParent = parent;
maxMode = false;
}
QWidget * m_pParent;
bool maxMode;
Qt::WindowFlags m_enOrigWindowFlags;
QSize m_pSize;
void mousePressEvent(QMouseEvent*) {
if (maxMode== false)
{
m_enOrigWindowFlags = this->windowFlags();
m_pSize = this->size();
this->setParent(0);
this->setWindowFlags( Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
this->showMaximized();
maxMode = true;
}
else
{
this->setParent(m_pParent);
this ->resize(m_pSize);
this->overrideWindowFlags(m_enOrigWindowFlags);
this->show();
maxMode = false;
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget mainWidget;
MyButton button(&mainWidget);
mainWidget.show();
return a.exec();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12338548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to delete complete records from all tables in SQL Server I want to delete User table, Fruit table and UserFruitMapping table based on UserID.
How can I achieve this?
A: All these answers are poor and honestly none of you would be touching my databases. You are teaching him the wrong way. Tell me why should you delete from a table when there is no relationship between Fruit and User table? You DELETE only from the HREF/link table for there is the only relationship. Otherwise your database Architecture is badly designed. There should be A CASCADE DELETE on UserID on the Mapping table.
A: Create a simple stored procedure for this
CREATE PROCEDURE Delete_ThreeTablesData
@UserId INT
AS
BEGIN
DELETE FROM Fruit
WHERE FruitId = (SELECT TOP 1 FruitId
FROM UserFruitMapping
WHERE UserId = @UserId)
DELETE FROM UserFruitMapping
WHERE UserId = @UserId
DELETE FROM User
WHERE UserId = @UserId
END
A: Deleteing records from all tables can be a really messy task. Especially when there are lots of Foregin Key constraints.
If I find myself in a similar situation, I prefer to Script out the database obviously without the data and just drop the old database.
Finally create a new Fresh database using the script.
Where to find Advance Scripting options
To select "Schema Only" when generating scripts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37987322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails / Factory Girl: Uninitialized constant FactoryGirl (NameError) I installed the factory_girl gem, and when I run my tests I get an error:
`block in ': uninitialized constant FactoryGirl (NameError)
This is my spec_helper.rb
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
How can it be fixed?
A: In spec/spec_helper.rb, try adding
FactoryGirl.find_definitions
under
require 'factory_girl_rails'
or make sure you follow factory_bot's Getting Started guide.
A: This must be your answer.
The required addition should be made in spec/support/factory_girl.rb
https://stackoverflow.com/a/25649064/1503970
A: I'm just putting this here for anyone clumsy like me. Everything was fine, but I was calling FactoryGirl in one place, when I only have FactoryBot installed. Newbie error. Hope it might help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27545598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to show data in FlatList in React-Native I am learning react-native and trying to fetch data from API and showing it in the flat list but I am not getting an idea of how can I do that in functional component as I have been through many tutorials on the internet but all of them uses class-based components.
Below is my code:
import React, {useEffect,useState} from 'react';
import {View,Text,StyleSheet} from 'react-native';
const List = () => {
const[post,setPost] = useState([]);
useEffect(() => {
const url = 'http://api.duckduckgo.com/?q=simpsons+characters&format=json';
fetch(url).then((res) => res.json())
.then((resp) => console.warn(resp))
.catch((err) => console.warn(err));
},[]);
return(
<View>
<Text style={styles.textStyle}>Hello there</Text>
</View>
);
};
const styles = StyleSheet.create({
testStyle:{
flex: 1,
justifyContent:"center",
alignItems:"center"
}
});
export default List;
Data I have successfully retrieved from the server but How can I show this data in FlatList.
A: First you need to save your response in your state to refer later on. And then use Flatlist component of react-native
const List = () => {
const[post,setPost] = useState([]);
useEffect(() => {
const url = 'http://api.duckduckgo.com/?q=simpsons+characters&format=json';
fetch(url).then((res) => res.json())
.then((resp) => setPost(resp.RelatedTopics))
.catch((err) => console.warn(err));
},[]);
const renderItem = ({ item }) => (
<Text style={styles.textStyle}>{item.Text}</Text>
);
return(
<View>
<FlatList
data={post}
renderItem={renderItem}
keyExtractor={item => item.FirstURL}
/>
</View>
);
};
Refer this official doc with example for more detail
A: First you'd want to take a look at the docs. I didn't read the docs when I started playing around with FlatList and wrote my own buggy, confusing code to figure out what items were on-screen. While trying to make it less buggy, I found an amazingly simple way of doing that. It will save you time, I promise.
With that said you are going to want a few items
*
*Your list (you have).
*a component that renders a single item of your list. This component will have two relevant props: index and item. Index is as you have probably guessed, and item is data the list item has
So assuming you have a list like this
const data = [
{name:"Harry Potter", phone:1234},
{name:"Ron Weasley", phone:4321}
]
Your renderItem component may look like:
const renderItem=({index,item})=>{
let style = [{fontSize:14}]
// if first item give it spacing at top
if(index == 0)
style.push({paddingTop:5})
return(
<View style={style}>
<Text>Name:{item.name}</Text>
<Text>Phone:{item.phone}</Text>
</View>
)
})
*A keyExtractor function, which should generate a string unique for all components in your app for each item of your list.
Bring this all together and you get:
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item,key) => item.id || 'harry-potter-character'+i}
/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67789965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to open app store with in our ipad or iphone application? Hi i want to open app store with in our application with the specific publisher search or specific application types..on clicking of button..let's say More App's...
A: To generate a link that is universal and not specific to an App Store Country do the following
Use
itms-apps://**ax.itunes**.apple.com/app/yourAppLinker
where yourAppLinker is the part of the link generated in (http://itunes.apple.com/linkmaker), as in Matthew Frederick's post, which contains your application name and id
it worked for me
cheers
A: For IOS7 and later for example:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id547101139"]];
A: *
*You can get the appropriate URL to your app here:
http://itunes.apple.com/linkmaker
If you enter the name of your company the linkmaker will provide an "artist link" that shows all of your apps.
*If you use the itms-apps:// prefix the user is sent directly to the
App Store App with the specified app showing rather than the ugly
first-Safari-then-the-App-Store-App shuffle that you get without that
UTI. A la:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:
@"itms-apps://yourAppLinkHere"]];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4437779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Is there a way to generate XmlSchema from XML serializable class in C#? I have following class:
[Serializable]
public class Person
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public int Age { get; set; }
}
Now when I get an XML file from somewhere (eg. web service) I need to deserialize it to the instance of this class. Before doing that I'd like to check the XML file against schema to ensure XML has proper structure. I know I can create schema via XSD.exe tool like this:
xsd.exe MyAssembly.dll /type:Person
This will create a physical .xsd schema file that I can then load to XmlSchema object. However I want to skip this manual generation of schema file and instead create XmlSchema dynamically in memory for a given class. This way when Person class is changed the code that generates XmlSchema directly from it will always have the schema that matches the current definition of the class. This is preferred way for me instead of always manually invoking xsd.exe tool every time Person class is changed.
So is it possible to programmatically create XmlSchema from a Person class?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21708210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unity - Why particle system gets transparent? I just created an particle system where you see a blinking add-icon. The problem is that if something gets behind the particle system, it gets transparent and I dont know why. I read that changing the shader could fix it, but it didnt work. I tried every shader in "Particles/..."
Here you how it looks like:
A: I seems that your object doesn't get transparent, but rather that it is being covered by the other object even though it should be in front of it.
Sorting is a common problem with objects that use some sort of blending:
In this case this is probably due to the other object being in a ui element. You could try to enforce the draw order by modifying the render queue in the material, or force it to use depth testing by using an alpha cutout shader instead (but its edges will not look as nicely anti-aliased without an extra MSAA or FXAA)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54235331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get the row number of a named Excel cell in MATLAB I'm working with a quite big Excel file in MATLAB with the xlsread function. I'm particularly interested in a named cell, let's say it's called FIRST_DATA. So in MATLAB I call:
[num, txt, raw] = xlsread(filename,sheet,'FIRST_DATA')
But I'm not interested in the data that this cell contains, but in the number of the row of this cell. How can I get this information?
My first guess is reading the data in the cell first, then reading the whole sheet and finally searching the resulting matrix for the cell data to find the row. But I hope for a more convenient way or one with less effort.
Thank you for your help!
A: There is a way using ActiveX, as suggested by Adiel in the Comments. Code example:
excelapp = actxserver('Excel.Application');
workbook = excelapp.Workbooks.Open('myspreadsheet.xlsx');
worksheet = workbook.Sheets.Item('sheet_with_data');
worksheet.Activate;
row_number = worksheet.Range('FIRST_DATA').Row;
Close(workbook);
Quit(excelapp);
delete(ExcelApp);
You should be closing everything properly to to prevent potential memory leaks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40904270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I keep the publisher from being stripped from fpassthru exes files? I am creating a simple proxy downloader that just passes the file stream through the server. It seems to work with most files alright, but exe seems to have a problem in that the 'publisher' is some how stripped.
$url = "http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe"
$bname = basename($url);
$ext = pathinfo($url, PATHINFO_EXTENSION);
header('Content-type: application/'.$ext);
header('Content-Disposition: attachment; filename="'.$bname.'"');
fpassthru(fopen($url, 'rb'));
I've tried using different header information for exes:
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
This does not make a difference. In both cases, the exe files is downloaded, and it can be run but windows 8 complains about it having an 'unknown' publisher. This does not happen when downloading the exe directly. It seems like I am just about there, but something is slightly off. In what step is the exe being modified (the reading or the output)? How do I do this properly? Thank you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21948449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Timthumb returning 404 on remote images only I am using timthumb to present images inside a Wordpress theme. It works fine when showing images from the same server but as soon as I try to load external images (in this case youtube thumbnails) it returns a 404 as if the script itself couldn't be found. The script is there though, if I load local images it behaves as expected. I have t set to allow external images, and specifically those from img.youtube.com
The strange thing is the exact same theme works as expected on my localhost and the external images show up fine, so I'm guessing it's something wrong on the hosting. Any suggestions as to what this may be?
A: IS your host allows to load images from external source. means out side of server ? This may be a problem.
A: HostGator do not allow absolute paths to use with TimThumb (even if it's hosted in your own account) as described in this article: http://support.hostgator.com/articles/specialized-help/technical/timthumb-basics.
To fix the absolute path issue, you'll would need to hack your theme functions to strip off your domain from the image path:
$url = "/path/to/timthumb.php?src=" . str_replace(site_url(), '', $path_to_image);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14713174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to invoke unit test a Print Event handler in c# I have below method which will get invoked when I call Print() method. I need to unit test the same. Is there any suggestions on how to do this?
internal PrintRemovalController(IApplicationContextHelper applicationContextHelper)
{
_applicationContextHelper = applicationContextHelper;
using (PrintDocument)
_printDocument.PrintPage += PrintDocument_PrintPage;
}
public void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
Font printFont = null;
try
{
PrintDetails pd;
do
{
pd = _printLines[_printPosition];
printFont = new Font("Courier New", 11, pd.Style);
if (pd.Text != "PAGE~~END")
e.Graphics.DrawString(pd.Text, printFont, Brushes.Black, pd.XPos, d.YPos);
_printPosition++;
}
while (pd.Text != "PAGE~~END");
e.HasMorePages = _printPosition < _printLines.Count;
}
finally
{
if (printFont != null)
printFont.Dispose();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43673772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: To access the text area in the html rendered using Iframe which itself is loaded withing a cshtml page I have an iframe loaded within a Cshtml page. The Iframe contains an html form. i need to add an image in front of each text area of the form when the main page(cshtml page) is loaded. Have tried a lot of things but nothing has worked as such. Below is the code i am trying:
$("#iframe").ready(function() {
$.each($('input[type=text],textarea'), function() {
var idOfCurrentElement = $(this).attr('id');
var classNameOfCurrentElement = $(this).attr('class');
var visibilityOfCurrentElement = $(this).css('visibility');
if(classNameOfCurrentElement != "hidden" && visibilityOfCurrentElement == "visible")
$("<img src='~/images/pic' alt='Pic'>");
});
});
A: You must access iframe content, not your page.
$("#iframe").ready(function() {
$.each($('#iframe').contents().find('input[type=text],textarea'), function() {
var $thatButton = $(this);
var idOfCurrentElement = thatButton .attr('id');
var classNameOfCurrentElement = thatButton ).attr('class');
var visibilityOfCurrentElement = thatButton .css('visibility');
if(classNameOfCurrentElement != "hidden" && visibilityOfCurrentElement == "visible")
//do what you want.
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45113061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get all orders data from flipkart seller api Can someone help me to get all order data from Flipkart seller API?
Currently, I am using this but it fetches the Orderitmes list of different orders. Is there any API to fetch directly all orders?
$url = "https://api.flipkart.net/sellers/v2/orders/search";
$curl = curl_init();
$json = '{
"sort": {
"field": "dispatchByDate",
"order": "desc"
}
}';
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Authorization:Bearer '.$tokan['access_token'],
''
));
$result = curl_exec($curl);
$ee = curl_getinfo($curl);
echo "<pre>";
//print_r($ee);
curl_close($curl);
$result = json_decode($result,true);
print_r($result);
Please revert if anybody has any solution.
Thanks in advance!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73080734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is There a dict with User Provided Key Function in Python? Some objects, numpy const arrays for example, are perfectly hashable but happened not to be (due to __eq__ being repurposed as an arithmetic operator, in the numpy case). Some objects, numpy arrays again for example, have multiple defintions of equility (id-equility and value-equility). For those object, a dict with user provided key function (as in sorted) would be very useful.
My question is: Is there a dict with user provided key function, either builtin or implemented in few lines, in Python?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60437302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Conditional xpath using precompiled xpath I am using XPATH in my project and i need to traverse through the nodes conditionally
public static String getNodeContentForMultipleTag1(XPathExpression expr,Document doc) {
try {
NodeList typeResult = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < typeResult.getLength(); i++) {
Node typeResultNode = typeResult.item(i);
System.out.println(typeResultNode.getTextContent());
}
} catch (XPathExpressionException e) {
throw new RuntimeException("Failed parsing expression",e);
}
return null;
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
String s="<ex><DtTm><TxDtTm><Cd>ABCD</Cd><dt>1234</dt></TxDtTm><TxDtTm><Cd>XYZ</Cd><dt>891</dt></TxDtTm></DtTm></ex>";
InputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
DocumentBuilder db= XpathInstanceUtil.getDocumentBuilderFactory().newDocumentBuilder();
Document doc = db.parse(inputStream);
XPath xpath = XpathInstanceUtil.getXPathFactory().newXPath();
XPathExpression expr = xpath.compile("/ex/DtTm/TxDtTm");
inputStream.close();
long st = System.currentTimeMillis();
getNodeContentForMultipleTag1(expr, doc);
long end = System.currentTimeMillis();
System.out.println(end-st);
long st1 = System.currentTimeMillis();
getNodeContentForMultipleTag1(expr, doc);
long end1 = System.currentTimeMillis();
System.out.println(end1-st1);
}
if the Cd value is ABCD i should get 1234 as result.
I have tried the following
public static String getNodeContentForMultipleTag(String expresssion,String expectedNode,String expectedExpressionTag,Document doc) {
try {
XPath xpath = XpathInstanceUtil.getXPathFactory().newXPath();
NodeList typeResult = (NodeList) evaluateXPath(doc,expresssion,xpath,XPathConstants.NODESET);
NodeList valueResult= (NodeList) evaluateXPath(doc,expectedExpressionTag,xpath,XPathConstants.NODESET);
//NodeList typeResult = (NodeList) xpath.evaluate(expresssion,doc, XPathConstants.NODESET);
//NodeList valueResult = (NodeList) xpath.evaluate(expectedExpressionTag,doc, XPathConstants.NODESET);
for (int i = 0; i < typeResult.getLength(); i++) {
Node typeResultNode = typeResult.item(i);
typeResultNode.getParentNode().removeChild(typeResultNode);
Node valueResultNode = valueResult.item(i);
if(typeResultNode.getTextContent().equals(expectedNode) && valueResultNode!=null){
valueResultNode.getParentNode().removeChild(valueResultNode);
return valueResultNode.getTextContent();
}
}
} catch (XPathExpressionException e) {
throw new RuntimeException("Failed parsing expression"+expresssion,e);
}
return null;
}
This is how expressions look like
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
String s="<ex><DtTm><TxDtTm><Cd>ABCD</Cd><dt>1234</dt></TxDtTm><TxDtTm><Cd>XYZ</Cd><dt>891</dt></TxDtTm></DtTm></ex>";
InputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
DocumentBuilder db= XpathInstanceUtil.getDocumentBuilderFactory().newDocumentBuilder();
Document doc = db.parse(inputStream);
String ss = getNodeContentForMultipleTag("/ex/DtTm/TxDtTm/Cd", "XYZ", "/ex/DtTm/TxDtTm/dt", doc);
System.out.println(ss);
}
But the its performance is very low.How it should be changed to parse efficiently
A: This code seems completely bizarre. Why are you doing all this work in Java rather than in XPath? Why are you modifying the DOM tree as you search it?
You just need to execute the XPath expression /ex/DtTm/TxDtTm[Cd='ABCD']/dt and you're there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43866228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apache Camel message exchange does not wait for the response I have following code for publishing message to activeMQ and reading response via exchange. But code seem to be returning instantaneously and not waiting for the response. Could you please point what is wrong with the following Scala code.
def sendAndReceiveExtractionDetails(request:String, header: String) : String = {
val exchange: DefaultExchange = new DefaultExchange(camel, ExchangePattern.InOut)
exchange.getIn.setBody(request)
exchange.getIn.setHeader("meshId", header)
producer.send("activemq:queue:extractor-jobs?requestTimeout=1400000", exchange)
val out: apache.camel.Message = exchange.getOut()
out.getBody().toString
}
A: It seems to ignore the ExchangePattern you set. Have you tried to set it on your JMS URI as activemq:queue:...&exchangePattern=InOut?
I am not sure if you also need to define the JMSReplyTo header on the message or if this is done automatically when the exchangePattern is InOut.
A: Use the request method on the producer as that is for InOut
A: Following code works for me:
def sendAndReceiveExtractionDetails(request:String, header: String) : String = {
camel.createProducerTemplate()
.sendBody("activemq:queue:extractor-jobs?requestTimeout=1400000", ExchangePattern.InOut, request).toString
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51035385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AttributeError: Movie instance has no attribute 'number_of_seasons' i'm learning to code with python and i'm stuck on a error:
AttributeError: Movie instance has no attribute 'number_of_seasons'
So the problem is clear but i'm not sure how to solve it. Basically i created some classes and i would like to display some Movie and Series that has different attributes.
this is the media.py file where i created my classes and attributes:
class Video():
"""This class created for both common info movies and series"""
def __init__(self, movie_title, story_line, url_poster, url_trailer, badge):
self.title = movie_title
self.storyline = story_line
self.poster = url_poster
self.trailer = url_trailer
self.badge = badge
def show_trailer(self):
webbrowser.open(self.trailer)
# here i define the class called Film for all movies
class Movie(Video):
"""This class is used to create all movies"""
def __init__(self, movie_title, story_line, url_poster, url_trailer, badge, movie_duration, movie_actors):
Video.__init__(self, movie_title, story_line, url_poster, url_trailer, badge)
self.duration = movie_duration
self.actors = movie_actors
# here i define the class called Series for all series with episodes and seasons
class Series(Video):
def __init__(self, movie_title, story_line, url_poster, url_trailer, badge, number_of_seasons, number_of_episodes):
Video.__init__(self, movie_title, story_line, url_poster, url_trailer, badge)
self.number_of_seasons = number_of_seasons
self.number_of_episodes = number_of_episodes
Then i have the enterteinment_center.py file where i added only 1 movie and 1 serie:
import media
import fresh_tomatoes
ironman = media.Movie("Ironman",
"Genius, billionaire, and playboy Tony Stark, who has inherited the defense contractor Stark Industries from his father",
"http://cdn.collider.com/wp-content/uploads/2015/04/iron-man-1-poster.jpg",
"https://www.youtube.com/watch?v=8hYlB38asDY",
"http://i.imgur.com/45WNQmL.png",
"126 minutes",
"English")
games_of_thrones = media.Series("Games Of Thrones",
"The series is generally praised for what is perceived as a sort of medieval realism.",
"https://vignette3.wikia.nocookie.net/gameofthrones/images/2/2c/Season_1_Poster.jpg/revision/latest?cb=20110406150536",
"https://www.youtube.com/watch?v=iGp_N3Ir7Do&t",
"http://i.imgur.com/45WNQmL.png",
"7 Seasons",
"12 episodes")
movies = [ironman, games_of_thrones, ironman, games_of_thrones, ironman, games_of_thrones]
fresh_tomatoes.open_movies_page(movies)
and the last file that creates the html is fresh_tomatoes.py but i will paste here only the piece of code that i think is useful for the fix:
def create_movie_tiles_content(movies):
# The HTML content for this section of the page
content = ''
for movie in movies:
if isinstance(movie, Movie):
# Extract the youtube ID from the url
youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer)
youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer)
trailer_youtube_id = youtube_id_match.group(0) if youtube_id_match else None
# Append the tile for the movie with its content filled in
content += movie_tile_content.format(
movie_title=movie.title,
poster_image_url=movie.poster,
trailer_youtube_id=trailer_youtube_id,
film_badge=movie.badge,
film_description=movie.storyline
)
elif isinstance(movie, Series):
# Extract the youtube ID from the url
youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer)
youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer)
trailer_youtube_id = youtube_id_match.group(0) if youtube_id_match else None
# Append the tile for the movie with its content filled in
content += movie_tile_content.format(
movie_title=movie.title,
poster_image_url=movie.poster,
trailer_youtube_id=trailer_youtube_id,
film_badge=movie.badge,
film_description=movie.storyline,
serie_season=movie.number_of_seasons
)
return content
def open_movies_page(movies):
# Create or overwrite the output file
output_file = open('fresh_tomatoes.html', 'w')
# Replace the placeholder for the movie tiles with the actual dynamically generated content
rendered_content = main_page_content.format(movie_tiles=create_movie_tiles_content(movies))
# Output the file
output_file.write(main_page_head + rendered_content)
output_file.close()
# open the output file in the browser
url = os.path.abspath(output_file.name)
webbrowser.open('file://' + url, new=2) # open in a new tab, if possible
So basically movie and series has some different attributes so if i want to display for example numbers of seasons for Games of Throne i will get an error telling that the movie Ironman don't have any attribute called numbers of season.
hope somebody can help on this! thanks a lot !
A: You cannot use the same function to extract values for classes with different attributes.
You need to assign a default value for each attribute in each class , or change the function to check the type of the movie in your loop.
For example :
for movie in movies:
if isinstance(movie, Movie):
# add movie attributes to the content
content += movie_tile_content.format(
movie_title=movie.title,
poster_image_url=movie.poster,
trailer_youtube_id=trailer_youtube_id,
film_badge=movie.badge,
film_description=movie.storyline,
serie_seasons='no season'
)
elif isinstance(movie, Series):
# add series attributes to the content
content += movie_tile_content.format(
movie_title=movie.title,
poster_image_url=movie.poster,
trailer_youtube_id=trailer_youtube_id,
film_badge=movie.badge,
film_description=movie.storyline,
serie_seasons=movie.number_of_seasons
)
This pattern allow you to change the content depending on the type of the media/video.
You may need to import the types in your second file:
from media import Movie, Series
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44844553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i split a column based on a condition in Python pandas My one of the columns consist following data -
Numbers
100 K
25.20 K
250 K
33.45 K
250
100
10
5
4
1
In the above Numbers column, I want to multiply numbers with K with 1000's and the other numbers without K, i want to leave them as it is.
How can I perform this conditional splitting and multiplication of column Numbers
Thanks in advance.
A: You could use numpy.where() with a boolean mask to identify your rows that contain 'K':
mask = df['Numbers'].str.contains('K')
df['Numbers'] = np.where(mask, df['Numbers'].str.extract(r'([\d\.]+)', expand=False).astype(float)*1000, df['Numbers'])
Yields:
Numbers
0 100000
1 25200
2 250000
3 33450
4 250
5 100
6 10
7 5
8 4
9 1
A: Here's a way to do using a custom function:
import re
def func(s):
# extract the digits with decimal
s = float(re.sub('[^0-9\\.]', '', s))*1000
return s
is_k = df['col'].str.contains('K')
df.loc[is_k, 'col2'] = df.loc[is_k, 'col'].apply(func)
df['col2'] = df['col2'].combine_first(df['col'])
col col2
0 100 K 100000
1 25.20 K 25200
2 250 K 250000
3 250 250
4 100 100
5 10 10
Sample Data
s=["100 K", "25.20 K", "250 K", "250", "100","10"]
df = pd.DataFrame({'col': s})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62606121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Where are api documentation and demo for JAVA OCR? I want to use the JAVA OCR : http://sourceforge.net/p/javaocr/
I can't find the api documentation and the demo. In the download file, I have only the jars.
Can somebody help me?
Thanks
A: You can find demo code at OCRScannerDemo for old api, for new api new api demo
About api javadoc you can generate it with maven.
To get source code : git clone http://git.code.sf.net/p/javaocr/source javaocr-source
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18441791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java Socks5 client and UDP support with Dante server I am writing SOCKS5 client
Ive got autorization and udp associate ready over TCP
Ive got address and port of the relay server but i am missing something with udp transmition...
clientSocket = new DatagramSocket();
IPAddress = InetAddress.getByName(serverHostname);
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = "xxx";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData,
sendData.length,
IPAddress,
sCon.getDstPort());
byte[] addr = sendPacket.getAddress().getAddress();
byte[]head = new byte[6+addr.length];
head[0] = (byte) 0x00; //RSV
head[1] = (byte) 0x00; //RSV
head[2] = (byte) 0x00; //frag
head[3] = (byte) 0x01; //Address type
//Put Address
System.arraycopy(addr,0,head,4,addr.length);
//Put port
head[head.length - 2] = (byte) (sendPacket.getPort() >> 8);
head[head.length - 1] = (byte) (sendPacket.getPort());
byte[] buf = new byte[head.length + sendPacket.getLength()];
byte[] data = sendPacket.getData();
//Merge
System.arraycopy(head,0,buf,0,head.length);
System.arraycopy(data,0,buf,head.length,sendPacket.getLength());
DatagramPacket updated = new DatagramPacket(
buf,
buf.length,
relayAddr,
relayPort);
clientSocket.send(updated);
Socks5 srever -> 192.168.11.52
serverHostname -> 192.168.11.39
client IP -> 192.168.11.49
Example situation
Target /192.168.11.39, port 9876
SOCKS5 RelayAddr /192.168.11.52, RelayPort 56945
Dante log
block(0): udp: expected from 192.168.11.39.148, got it from 192.168.11.49.59124
Every time there is 192.168.11.39*.148* and i dont understand where is something wrong.
DatagramPacket never reaches the destination host
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21392412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add value to a row in MySQL if it's greater than another value I have a table, Users, that contains a unique id, an integer 'econ', and some other irrelevant data. I'm trying to create a SQL statement for a simple gambling implementation. I have access to the user id, the amount bet, and the amount they potentially win. I need to verify that the user currently possesses more money than the total bet and if so UPDATE the row to Users.econ + winnings. (If the user lost the bet I'm simply using a negative number as the winnings value). I can do this with a couple separate statements but I'd prefer to use one so I don't have to deal with transactions.
Model:
User: id (varchar), econ (integer), other
Current implementation:
*
*SQL: SELECT econ from Users WHERE id = 'xyz'
*Logic: if (econ > bet) newEcon = econ + winnings, else throw error
*SQL: UPDATE Users SET econ = newEcon WHERE id = 'xyz'
Desired Result:
Example 1:
User model: id: 10, econ: 300
SQL request: id: 10, bet: 200, winnings: 300
Result: User: id: 10, econ: 600
Example 2:
User model: id: 5, econ: 50
SQL request: id: 5, bet: 100, winnings: 500
Result: User: id: 5, econ: 50 (unchanged)
Example 3:
User model: id: 12, econ: 200
SQL request: id: 12, bet: 100, winnings: -100
Result: User: id: 12, econ: 100
A: this query is working :
update accbalance set econ = econ + @winnings where id=@id and econ > @bet ;
Next time please create a sqlfiddle , it can help .
the query was tested in :
http://sqlfiddle.com/#!9/960009/1 .
A: You should be able to integrate the comparison into your UPDATE query:
UPDATE users
SET econ = econ + ?
WHERE econ > ? AND id = ?
Here I've used placeholders on the assumption you would prepare the query, in order they are for winnings, bet and id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58635625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: rownum & aliasing in HQL Need help...
how to translate this SQL query to HQL :
select "row" from (select rownum as "row", globalId from globalTable where valid='T') where globalId = "g123";
globalTable :
globalId _ valid
g000 _ T
g111 _ F
g222 _ T
g123 _ T
it should return 3.
Thanks.
A: your query can be converted one query:
select rownum as "row" from globalTable where valid='T' and globalId = "g123"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5728208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Multiple tables, eliminate data Suppose there are three tables T1, T2 and T3.
*
*T1 has columns Ordernum and bizdate
*T2 has columns Ordernum and Orderitem
*T3 has columns Orderitem and Catid
FYI: there are multiple orderitems under each ordernum; each ordertiem has multiple catids.
I want to eliminate ordernums where any itemnum has catid=100.
As I said, each ordernum has multiple orderitem, so I would like to eliminate all orderitem even if only one orderitem in a ordernum has catid=100 .
In other words, I want to print only ordernum where catid != 100
A: You can use a subquery that picks out the orders with that category and use to filter out those orders:
select
OrderNum
from
T1 as t
where
not exists(
select *
from T1
inner join T2 on T2.Ordernum = T1.Ordernum
inner join T3 on T3.Orderitem = T2.Orderitem and T3.Catid = 100
where T1.Ordernum = t.Ordernum
)
A: You can to use EXISTS clause:
SELECT T1.OrderNum
FROM T1
WHERE NOT EXISTS
(SELECT * FROM T2 INNER JOIN T3 ON T2.Orderitem = T3.Orderitem
WHERE T1.OrderNum = T2.OrderNum AND T3.Catid != 100)
A: you need to select all and then exclude them on where statement. I think this will work.
SELECT a1.OrderNum FROM T1 a1
INNER JOIN T2 a2 ON a1.OrderNum = a2.OrderNum
INNER JOIN T3 a3 ON a2.Orderitem = a3.Orderitem
WHERE not a1.OrderNum in
(select ordernum from T2 where orderitem in
(select Orderitem from T3 where T2.OrderItem = OrderItem and Catid = 100))
or maybe with subjoin is better:
WHERE not a1.OrderNum in
(select sa2.ordernum from T2 sa2 where sa2.orderitem in
(select sa3.Orderitem
INNER JOIN T3 sa3 on sa2.OrderItem = sa3.OrderItem and sa3.Catid = 100))
A: here it is ;
select *
from T1
where ordernum not in (select ordernum
from t2,t3
where t2.Orderitem=t3.Orderitem
and t3.catid=100)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25878012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Get Tables Data in out parameters of Store Procedures in mysql I was trying to get data into the Output parameters of Stored Procedure in mysql but I am not getting it back.
HERE IS THE QUERY
Creation
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_initial_data`(
out usersData varchar(500),
out employeesData varchar(500)
)
BEGIN
SELECT * into usersData FROM users;
SELECT * into employeesData FROM employees;
END
Calling
Call get_initial_data(@users, @employees)
select @users
select @employees
I tried this and I am able to create the Store Procedure but not able to call, its giving me this Error...
Error Code: 1172. Result consisted of more than one row
Can you help me in this, am I passing the Output parameters correctly and also the Data type of that?
Please let me know your response on this....
A: An output parameter can contain only a single value. You are trying to return result sets via the output variable. This is not how output parameters work.
You read the result sets coming from the procedure; no need to use output variables.
CREATE PROCEDURE get_initial_data()
BEGIN
SELECT * FROM users;
SELECT * FROM employees;
END
Output parameters are useful in a situation where you have a procedure calling another procedure and use the output of the called procedure. Even then, you can only use single values with output parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75384021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to extract text in each line of a pdf file using python I have gone through many solutions for extracting data from pdf file but could not find a solution to this particular problem
I have a pdf file that has the following data format in it
UPC Product Description Subcategory Name Pkg type
018894300199 Big Y Mozzarella String 16oz 16oz Pkg Cheese PKG
I need to extract the UPC, Product description and Sub name for each line of the pdf file using python
I was able to extract the text from the pdf file using the code below
from PyPDF2 import PdfFileReader, PdfFileWriter
pdfFileObj = open('grocery2.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
print(pdfReader.numPages)
pageObj = pdfReader.getPage(1)
pagecontent = pageObj.extractText()
I have more than 500 pages of product data. what is the most efficient way of extracting the UPC, Product description and Sub name for each line of the page?
A: Since they are distinguished by spaces and your strings themselves have spaces using the extracted text will probably not be too helpful. I would have to see the full pdf to know if this would work but try:
From tabula import read_pdf
df = read_pdf("grocery2.pdf")
Then you can do any dataframe operations to extract different values ie.
df1 = df[['UPC', 'Product Description']]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47464866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get CameraId from Camera object in android I am developing on Nexus 7 that only has a front-facing camera. Thus, most of the default camera-related retrievals fail as they try to return information for first back-facing camera. What I would like to know is whether it is possible to retrieve the camera ID from an already retrieved camera object?
Please, understand that I do not want to iterate over the list of cameras in order to match one to the current camera. Also, I did retrieve the camera using that method but didn't need to persist the ID of the camera.
In one of my classes, separate from camera acquisition class, I am trying to get a hold of the camcorder's profile. I invoke it with CamcorderProfile.get(CamcorderProfile.HIGH_QUALITY); Documentation states that get(int quality):
Returns the camcorder profile for the first back-facing camera on the device at the given quality level. If the device has no back-facing camera, this returns null.
Thus, I need a cameraId for the currently open (front-facing) camera.
Thanks for any help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16346024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Does cached-resources plugin work with Grails 1.3.7 Maybe a dumb question...? (I think only Grails 1.2.* is supported?)
Im trying to use cached-resources with grails 1.3.7 following the simple example for the jquery plugin
E.g.
JqueryResources.groovy
modules = {
'jquery' {
resource url:[plugin:'jquery',dir:'js/jquery', file:'jquery-1.4.4-min.js'], disposition:'head'
}
}
I am getting the following exception
2011-05-13 17:35:11,944 [main] ERROR resource.ResourceService - Resource not found: /plugins/jquery-1.4.4.1/js/jquery/jquery-1.4.4-min.js
2011-05-13 17:35:11,991 [main] ERROR plugins.DefaultGrailsPluginManager - Error configuring dynamic methods for plugin [resources:1.0-RC2]: java.io.FileNotFoundException: Cannot locate resource [/plugins/jquery-1.4.4.1/js/jquery/jquery-1.4.4-min.js]
org.codehaus.groovy.runtime.InvokerInvocationException: java.io.FileNotFoundException: Cannot locate resource [/plugins/jquery-1.4.4.1/js/jquery/jquery-1.4.4-min.js]
at org.grails.tomcat.TomcatServer.start(TomcatServer.groovy:212)
at grails.web.container.EmbeddableServer$start.call(Unknown Source)
at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy:158)
Maybe im defining the path to the resource incorrectly?
E.g. Path to jquery. ../web-app/js/jquery/jquery-1.4.4-min.js
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5988763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to use fwrite properly I'm unable to figure out how to use fwrite here. I'm getting a segmentation fault. Is there any other way I can write 0x00 to rgbtRed, rgbtBlue and rgbtGreen? I've looked up online, but couldn't find the right way to do this.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
typedef uint8_t BYTE;
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
int main (void)
{
RGBTRIPLE triple;
/*code which opens a bmp file, copies it and exports it to another
file based on the changes which I ask it.
I'm trying to set R's (of RGB) value to 0 to see if that solves
the problem. I'm trying to figure out how to set the value to 0*/
fwrite(&triple.rgbtRed, sizeof(uint8_t), 1, 0x00);
}
A: fwrite is for writing to a file, but you want to set memory to zero, which is not quite the same thing.
With this line of code, the whole triple structure is set to zero.
memset(&triple, 0, sizeof triple);
A: Fourth argument of fwrite should be opened for writing FILE
Giving zero has result in exception
FILE * aFileYouWrite = fopen("afilename.xyz","wb");
memset(&triple, 0, sizeof triple);
fwrite(&triple.rgbtRed, sizeof(uint8_t), 1, aFileYouWrite );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50679782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: How to check if a string only contains chars from an array? I try to check if a word (wordToCheck) only consists of letters from an array (letters) and also contains every letter in the array only as often (or rather not more times than they are in the array) as it actually is inside of the array.
Here are examples of what the desired function should return:
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]) === true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]) === false
How can I make this code work?
function checkIfWordContainsLetters(wordToCheck, letters) {
var lettersToString = letters.toString();
var lettersTrimmed = lettersToString.replace(/,/gi, "?");
var regEx = new RegExp(lettersTrimmed, "gi");
if (wordToCheck.match(regEx)!== null) {
return true;
}
else return false;
}
A: You could use this ES6 function:
function checkIfWordContainsLetters(wordToCheck, letters){
return !letters.reduce((a, b) => a.replace(b,''), wordToCheck.toLowerCase()).length;
}
console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));
The idea is to go through each letter in the letters array, and remove one (not more!) occurrence of it in the given wordToCheck argument (well, not exactly in it, but taking a copy that lacks that one character). If after making these removals there are still characters left over, the return value is false -- true otherwise.
Of course, if you use Internet Explorer, you won't have the necessary ES6 support. This is the ES5-compatible code:
function checkIfWordContainsLetters(wordToCheck, letters){
return !letters.reduce(function (a, b) {
return a.replace(b, '');
}, wordToCheck.toLowerCase()).length;
}
console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));
A: As long as it is not the best solution for long strings for which using some clever regex is definitely better, it works for short ones without whitespaces.
function checkIfWordContainsLetters(word, letters){
word = word.toLowerCase().split('');
for(var i = 0; i < letters.length; i++) {
var index = word.indexOf( letters[i].toLowerCase() );
if( index !== -1 ) {
// if word contains that letter, remove it
word.splice( index , 1 );
// if words length is 0, return true
if( !word.length ) return true;
}
}
return false;
}
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]); // returns true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]); // returns false
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41066729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.