_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d16901 | val | Using sed:
sed -i '/[/]mymount/ s/^/#/' /etc/fstab
How it works:
*
*-i
Edit the file in-place
*/[/]mymount/
Select only lines that contain /mymount
*
*s/^/#/
For those selected lines, place at the beginning of the line, ^, the character #.
Using awk:
awk '/[/]mymount/{$0="#"$0} 1' /etc/fstab >/etc/fstab.tmp && mv /etc/fstab.tmp /etc/fstab
How it works:
*
*/[/]mymount/ {$0="#"$0}
For those lines containing /mymount and place a # at the beginning of the line.
*1
This is awk's cryptic shorthand for "print each line." | unknown | |
d16902 | val | To answer your actual question: no, you can’t do that, and there’s almost never any need to. Even if you couldn’t get an iterable out of a readable, you could just put byte[0] into another variable and use that.
Instead, you can use the Bytes iterator:
let byte: u8 = io::stdin().bytes().next().unwrap();
A: Rust 1.28+
slice::from_mut is back and it's stable!
use std::{
io::{self, Read},
slice,
};
fn main() {
let mut byte = 0;
let bytes_read = io::stdin().read(slice::from_mut(&mut byte)).unwrap();
if bytes_read == 1 {
println!("read byte: {:?}", byte);
}
}
Rust 1.0+
But that's kinda weird feeling throughout the rest of the code, and it would be more natural to use a single u8 rather than a [u8; 1] that I have to index into.
Creating an array of length 1 would be the most natural way of doing it:
use std::io::{self, Read};
fn main() {
let mut bytes = [0];
let bytes_read = io::stdin().read(&mut bytes).unwrap();
let valid_bytes = &bytes[..bytes_read];
println!("read bytes: {:?}", valid_bytes);
}
However, it is possible to unsafely create a slice from a reference to a single value:
use std::io::{self, Read};
use std::slice;
fn mut_ref_slice<T>(x: &mut T) -> &mut [T] {
// It's important to wrap this in its own function because this is
// the only way to tell the borrow checker what the resulting slice
// will refer to. Otherwise you might get mutable aliasing or a
// dangling pointer which is what Rust is trying to avoid.
unsafe { slice::from_raw_parts_mut(x, 1) }
}
fn main() {
let mut byte = 0u8;
let bytes_read = io::stdin().read(mut_ref_slice(&mut byte)).unwrap();
if bytes_read != 0 {
println!("byte: {}", byte);
}
}
Remember that a slice is basically two things: a pointer to an area of memory and a length. With a slice of length one, you simply need to add a length to a mutable reference and bam! you got yourself a slice.
Earlier versions of Rust had the ref_slice and mut_ref_slice functions. They were removed because their utility was not yet proven (this isn't a common problem), but they were safe to call. The functions were moved to the ref_slice crate, so if you'd like to continue using them, that's one possibility. | unknown | |
d16903 | val | I believe you want
VNormalizedRed = r(:)./(r(:)+g(:)+b(:));
Note the dot in front of the /, which specifies an element-by-element divide. Without the dot, you're solving a system of equations -- which is likely not what you want to do. This probably also explains why you're seeing the high memory consumption.
A: Your entire first code can be rewritten in one vectorized line:
im_normalized = bsxfun(@rdivide, im, sum(im,3,'native'));
Your second slightly modified version as:
im_normalized = bsxfun(@rdivide, im, sqrt(sum(im.^2,3,'native')));
BTW, you should be aware of the data type used for the image, otherwise one can get unexpected results (due to integer division for example). Therefore I would convert the image to double before performing the normalization calculations:
im = im2double(im); | unknown | |
d16904 | val | You can use this regex:
gsub("\\bamp\\b","", x)
# [1] "come on this just encourages the already rampant mispronunciation of phuket"
The \\b means word boundary.
A: You could also split the string into words, and then compare:
x <- 'come on this just encourages the already rampant mispronunciation of phuket'
split_into_words = strsplit(x, ' ')[[1]]
filtered_words = split_into_words[!split_into_words == 'amp']
paste(filtered_words, collapse = ' ')
[1] "come on this just encourages the already rampant mispronunciation of phuket"
A: You could just find the occurrence of "amp" that has a space in front.
> gsub("\\samp", "", x)
## [1] "come on this just encourages the already rampant mispronunciation of phuket"
where \\s means space. This is more readable as
> gsub(" amp", "", x) | unknown | |
d16905 | val | In your modify method, call the appropriate view. I usually pass an instance of the model and el. So, for example:
this.modifyPage = new App.Views.Test({
el: $('#list'),
model: model
});
Though, if you don't need the el as context from the router, it's best to limit the use of jQuery to only the views. | unknown | |
d16906 | val | There isn't much information available in the details given in the question but a few pointers can may be help others who come here searching on the topic.
*
*The cost is a numerical estimate based on table statistics that are calculated when analyze is run on the tables that are involved in the query. If the table has never been analyzed then the plan and the cost may be way sub optimal. The query plan is affected by the table statistics.
*The actual time is the actual time taken to run the query. Again this may not correlate properly to the cost depending on how fresh the table statistics are. The plan may be arrived upon depending on the current table statistics, but the actual execution may find real data conditions different from what the table statistics tell, resulting in a skewed execution time.
Point to note here is that, table statistics affect the plan and the cost estimate, where as the plan and actual data conditions affect the actual time. So, as a best practice, before working on query optimization, always run analyze on the tables.
A few notes:
*
*analyze <table> - updates the statistics of the table.
*vacuum analyze <table> - removes stale versions of the updated records from the table and then updates the statistics of the table.
*explain <query> - only generates a plan for the query using statistics of the tables involved in the query.
*explain (analyze) <query> - generates a plan for the query using existing statistics of the tables involved in the query, and also runs the query collecting actual run time data. Since the query is actually run, if the query is a DML query, then care should be taken to enclose it in begin and rollback if the changes are not intended to be persisted.
A: *
*Cost meaning
*
*The costs are in an arbitrary unit. A common misunderstanding is that they are in milliseconds or some other unit of time, but that’s not the case.
*The cost units are anchored (by default) to a single sequential page read costing 1.0 units (seq_page_cost).
*
*Each row processed adds 0.01 (cpu_tuple_cost)
*Each non-sequential page read adds 4.0 (random_page_cost).
*There are many more constants like this, all of which are configurable.
*Startup cost
*
*The first numbers you see after cost= is known as the “startup cost”. This is an estimate of how long it will take to fetch the first row.
*The startup cost of an operation includes the cost of its children.
*Total cost
*
*After the startup cost and the two dots, is known as the “total cost”. This estimates how long it will take to return all the rows.
*example
QUERY PLAN |
--------------------------------------------------------------+
Sort (cost=66.83..69.33 rows=1000 width=17) |
Sort Key: username |
-> Seq Scan on users (cost=0.00..17.00 rows=1000 width=17)|
*
*We can see that the total cost of the Seq Scan operation is 17.00, and the startup cost of the Seq Scan is 0.00. For the Sort operation, the total cost is 69.33, which is not much more than its startup cost (66.83).
*Actual time meaning
*
*The “actual time” values are in milliseconds of real time, it is the result of EXPLAIN's ANALYZE. Note: the EXPLAIN ANALYZE option performs the query (be careful with UPDATE and DELETE)
*EXPLAIN ANALYZE could be used to compare the estimated number of rows with the actual rows returned by each operation.
*Helping the planner estimate more accurately
*
*Gather better statistics
*
*tables also change over time, so tuning the autovacuum settings to make sure it runs frequently enough for your workload can be very helpful.
*If you’re having trouble with bad estimates for a column with a skewed distribution, you may benefit from increasing the amount of information Postgres gathers by using the ALTER TABLE SET STATISTICS command, or even the default_statistics_target for the whole database.
*Another common cause of bad estimates is that, by default, Postgres will assume that two columns are independent. You can fix this by asking it to gather correlation data on two columns from the same table via extended statistics.
*Tune the constants it uses for the calculations
*
*Assuming you’re running on SSDs, you’ll likely at minimum want to tune your setting of random_page_cost. This defaults to 4, which is 4x more expensive than the seq_page_cost we looked at earlier. This ratio made sense on spinning disks, but on SSDs it tends to penalize random I/O too much.
Source:
*
*PG doc - using explain
*Postgres explain cost | unknown | |
d16907 | val | Well there are several different possibilities. Using four different boolean properties is a clean solution. You then have to use the if ... elsif statements to find out what happened.
A more C way of doing that would be to define bitmasks which can be OR'ed together and stored as an NSUInteger. If this would semantically makes sense you could group them together in an enum, but that is the C way.
You could also define a custom subclass of NSManagedObject and write some convenience methods to check these options. Depends a bit on what they are good for.
A: You could use reflection (e.g., class_copyPropertyList and class_getProperty) to check what properties the class has, and examine their values, but that's a pretty heavy-handed approach when you already know which four properties are relevant. I wouldn't suggest this approach, and I wouldn't call it more Cocoa-ish, just more abstracted.
If you're looking at specific combinations of states, I think GorillaPatch's suggestion is right: You would turn those four booleans into a single 4-bit integer and compare it against bit masks representing the various combinations you're interested in. | unknown | |
d16908 | val | In need to make your camera to chase your player. You can do this by:
camera.setChaseEntity(player);
Just have a look at AndEngine Examples. It has an example which exactly serves your need. Follow the link below to download the code as well:
http://code.google.com/p/andengineexamples/
•TMXTiledMapExample | unknown | |
d16909 | val | The problem is that I was using
pkg_check_modules(WEBKIT REQUIRED webkitgtk-3.0)
instead of
pkg_check_modules(WEBKIT REQUIRED webkit2gtk-3.0) | unknown | |
d16910 | val | A great way would be to use the HTTP programming features of Play. | unknown | |
d16911 | val | After some code digging I figure it out:
any C/C++ parameter that accepts a pointer to a list of values should be wrapped in python with
MyType=ctypes.ARRAY(/*any ctype*/,len)
MyList=MyType()
and filled with
MyList[index]=/*that ctype*/
in mycase the solution was:
from ctypes import *
path="test.dll"
lib = cdll.LoadLibrary(path)
Lines=["line 1","line 2"]
string_pointer= ARRAY(c_char_p,len(Lines))
c_Lines=string_pointer()
for i in range(len(Lines)):
c_Lines[i]=c_char_p(Lines[i].encode("utf-8"))
lib.SetLines(c_Lines,len(lines)) | unknown | |
d16912 | val | Basically, the answer is Yes, you need a class.
There is no concept of 'reference to int' that you can store as a field. In C# it is limited to parameters.
And while there is an unsafe way (pointer to int, int*) the complexities of dealing with the GC in that scenario make it impractical and inefficient.
So your second example looks OK.
A: You cannot store a reference to a variable, for precisely the reason that someone could do what you are doing: take a reference to a local variable, and then use that reference after the local variable's storage is reclaimed.
Your approach of making the variable into a field of a class is fine. An alternative way of doing the same thing is to make getter and setter delegates to the variable. If the delegates are closed over an outer local variable, that outer local will be hoisted to a field so that its lifetime is longer than that of the delegates.
A: It is not possible to store a reference as a field.
You need to hold the int in a class. | unknown | |
d16913 | val | You provided a declaration but you also need a definition. Add this to your kernel.c, at the top after the include:
DBConnection * conn;
A: extern DBConnection * conn;
declares the variable without defining it.
You need to add a file scope definition in one source file, for example in kernel.c:
DBConnection * conn;
A: extern doesn't allocate memory for the variable it qualifies, it only allows it to be used. You'll need a declaration of conn without the extern. You could add this to your kernel.c:
DBConnection * conn;
A: Try This :
#include "kernel.h"
DBConnection * conn
int get_info() {
conn = (DBConnection *) malloc(sizeof(DBConnection));
}
You need to add the file scope of conn in kernel.c
A: The extern keyword simply states that there is a variable somewhere in the final linked binary that has that name and type, it doesn't define said variable. The error message you're getting is about not being able to find the definition that the extern is referring to.
Define your method in your .C file, outside of any function definition.
A: to use a variable in many files declare it outside a function in any file and then use the extern nameofvar to use it in the other files example
file 1 :
int externalvar;
main(void)
{
//stuff ...
}
file 2 :
extern externalvar;
void someFunc(void)
{
externalvar = 5;
//stuff ...
}
A: Actually this is not a compiler error, but the error found during linker stage. Because, for compilation, the extern declaration is more than enough where compiler got to know a object and its type where declared in some other file. As long as the compilable file .c file knows the object declared somewhere than it will not throw any error. so the below code snippet in .c file also will not throw any compilation error.
extern DBConnection * conn
int get_info()
{
conn = (DBConnection *) malloc(sizeof(DBConnection));
}
But in the linker stage the kernel.o(object file) while linking looks for the real location of this objects reference, by that time if it is not able to find this object defined in some other object file than an linker error will be thrown. | unknown | |
d16914 | val | Get selectionStart and selectionEnd:
val startIndex = editText.selectionStart
val endIndex = editText.selectionEnd
A: You need to make use of this class Selection
https://developer.android.com/reference/android/text/Selection
Try out method from it | unknown | |
d16915 | val | [splitView convertRect:modallyPresentedVC.view.bounds fromView:modallyPresentedVC.view] should do the trick. Make sure to call it in the completion block of the presentation (after all animation has finished). | unknown | |
d16916 | val | I think I've found the solution. HornetQ (such as WebLogic JMS) provide an ability of message grouping: http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html/message-grouping.html. Following this opportunity I can established the processing of the same marked messages with the same consumer. Bingo! | unknown | |
d16917 | val | Notepad apparently saved the file with a byte order mark, a nonprintable character at the beginning that just marks it as UTF-8 but is not required (and indeed not recommended) to use. You can ignore or remove it; other text editors often give you the choice of using UTF-8 with or without a BOM.
A: That's actually not a blank character, it's a BOM - Byte Order Mark. Windows uses the BOM to mark files as unicode (UTF-8, UTF-16 and UTF-32) encoded files.
I think you can save the files without the BOM even in Notepad (it's not required actually).
A: Well, you may be trying to read your file using a different encoding.
You need to use the OutputStreamReader class as the reader parameter for your BufferedReader. It does accept an encoding. Review Java Docs for it.
Somewhat like this:
BufeferedReader out = new BufferedReader(new OutputStreamReader(new FileInputStream("jedis.txt),"UTF-8")))
Or you can set the current system encoding with the system property file.encoding to UTF-8.
java -Dfile.encoding=UTF-8 com.jediacademy.Runner arg1 arg2 ...
You may also set it as a system property at runtime with System.setProperty(...) if you only need it for this specific file, but in a case like this I think I would prefer the OutputStreamWriter.
By setting the system property you can use FileReader and expect that it will use UTF-8 as the default encoding for your files. In this case for all the files that you read and write.
If you intend to detect decoding errors in your file you would be forced to use the OutputStreamReader approach and use the constructor that receives an decoder.
Somewhat like
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
BufeferedReader out = new BufferedReader(new InputStreamReader(new FileInputStream("jedis.txt),decoder));
You may choose between actions IGNORE | REPLACE | REPORT
A: the null character, for example. when you use (char)0, is translated to ''
It might be that filereader is reading in a null character at the start of the file. I'm not sure why though...
A:
Even if I tried to use s1.trim(); its length still 5.
I expect that you are doing this:
s1.trim();
That doesn't do what you want it to do. Java Strings are immutable, and the trim() method is creating a new String ... which you are then throwing away. You need to do this:
s1 = s1.trim();
... which assigns the reference to the new String created by trim() to something so that you can use it.
(Note: trim() doesn't always create a new String. If the original string has no leading or trailing whitespace, the trim() method simply returns it as-is.) | unknown | |
d16918 | val | Instead of searching, we can just *loop** through each Hyperlink in the Hyperlinks collection:
Sub RemoveHighlightFromHyperlinks()
Dim a As Hyperlink
For Each a In ActiveDocument.Hyperlinks
If a.Range.HighlightColorIndex <> 15 Then a.Range.HighlightColorIndex = wdAuto
Next a
End Sub
It loops through all hyperlinks in the document. If HighlightColorIndex <> 15 then remove HighlightColorIndex (by setting to wdAuto.)
More Information:
*
*MSDN : Hyperlinks Collection (Word)
*MSDN : Hyperlink Object (Word)
*MSDN : Range.HighlightColorIndex Property (Word) | unknown | |
d16919 | val | Like this:
SQLFIDDLE
set @curr_user = 1;
set @maxid = (select max(u1.id) maxid from users u1);
set @minid = (select min(u2.id) minid from users u2);
set @next_user = (if(@curr_user = @maxid
,@minid
,@curr_user +1));
set @prev_user = (if(@curr_user = @minid
,@maxid
,@curr_user - 1));
SELECT t1.name as prevuser, t2.name as curruser, t3.name as nextuser
FROM users t1
join users t2
on 1=1
JOIN users t3
on 1=1
WHERE t1.id = @prev_user
AND t2.id = @curr_user
and t3.id = @next_user
EDIT: I made a slight adjustment so it would work even if there are missing id's, let's say you have user 1,3,4,5,7 this would get user 4,5,7 if current is 5 SQLFIDDLE
set @curr_user = 3;
set @maxid = (select max(u1.id) maxid from users u1);
set @minid = (select min(u2.id) minid from users u2);
set @nextid = (select min(id) from users where id > @curr_user );
set @previd = (select max(id) from users where id < @curr_user );
set @next_user = (if(@curr_user = @maxid
,@minid
,@nextid));
set @prev_user = (if(@curr_user = @minid
,@maxid
,@previd));
SELECT t1.name as prevuser, t2.name as curruser, t3.name as nextuser
FROM users t1
join users t2
on 1=1
JOIN users t3
on 1=1
WHERE t1.id = @prev_user
AND t2.id = @curr_user
and t3.id = @next_user | unknown | |
d16920 | val | If you want each number to have at least one non-zero digit you may try something like this (updated with help of Tims comments):
^0*[1-9]\\d*(_0*[1-9]\\d*)*$
The [1-9] makes sure there is (at least) one non-zero digit in each group, where as the 0* before allows any number of zeros. After that one non-zero digit, any digits including (but not only) zero can be allowed: \\d*.
Update 2: Added anchors as suggested by Daniël to make sure the whole string is matched.
A: As it stands you will need to define your regexp of what you consider a number and repeat it. As far as I can tell you would like to have something like
s.matches("0[1-9][0-9]*|[1-9][0-9]*")
to match a single number string. As regexps cannot be factored you will need to repeat yourself for the _, as in
s.matches("0[1-9][0-9]*|[1-9][0-9]*(_(0[1-9][0-9]*|[1-9][0-9]*)*")
that should do the trick as long as you do not want 0 as an answer and you want to avoid double leading zeros. In all it is a horrible expression though.
A: try this
s.matches("\\d*[1-9](_\\d+)*") | unknown | |
d16921 | val | Android NDK r9 contains the following toolchains:
*
*arm-linux-androideabi-4.6
*arm-linux-androideabi-4.8
*arm-linux-androideabi-clang3.2
*arm-linux-androideabi-clang3.3
*llvm-3.2
*llvm-3.3
*mipsel-linux-android-4.6
*mipsel-linux-android-4.8
*mipsel-linux-android-clang3.2
*mipsel-linux-android-clang3.3
*x86-4.6
*x86-4.8
*x86-clang3.2
*x86-clang3.3
There is no toolchain for gcc 4.7. However, your Application.mk contains the line:
NDK_TOOLCHAIN_VERSION := 4.7
Which tells the NDK to look for the 4.7 toolchain. And it fails.
So, the solution to your problem is changing the NDK_TOOLCHAIN_VERSION variable to 4.6, 4.8, clang3.2, clang3.3, or just clang (which will use the most recent version of Clang available in the NDK).
A: Check your project path if is contain spaces and non-english characters.
I moved my project into somewhere without spaces, re-build it and works. | unknown | |
d16922 | val | The problem is that the return value of return_color is not used, since the reference to the function passed as a command option is used to call it but not to store the result. What you can do is to store the values as attributes of the class in return_color and add a return statement in get_color after the call to start the mainloop:
def get_color()
# Initialize the attributes with a default value
self.r = ''
self.g = ''
self.b = ''
# ...
root.mainloop()
return self.r, self.g, self.b
def return_color(self):
# Entry.get returns a string, don't need to call to str()
self.r = self.enter1.get()
self.g = self.enter2.get()
self.b = self.enter3.get()
root.destroy()
Before using the color, you can check that the format is correct. Then I suggest you to rename the functions with more meaningful names; and create a Tk element, withdraw it and use a Toplevel in your class (if you create more than one Custom object, you are actually creating multiple Tk elements, and that's something which should be avoided). | unknown | |
d16923 | val | XBOX One has maximum available memory of 1 GB for Apps and 5 for Games.
https://learn.microsoft.com/en-us/windows/uwp/xbox-apps/system-resource-allocation
While in PC the fps is 30 (as the memory has no such restrictions).
This causes the frame rate to drop. However, the fps did improve when running it on release mode or published to MS Store. | unknown | |
d16924 | val | Simply change the JSON.stringify for a URLSearchParams and remove the content-type header, fetch will automatically add the correct content-type when it detects URLSearchParams as a body
return fetchModule.fetch(config.apiUrl + "auth/register", {
body: new URLSearchParams({
"username": viewModel.get("username"),
"firstname": viewModel.get("firstname"),
"lastname": viewModel.get("lastname"),
"email": viewModel.get("email"),
"password": viewModel.get("password")
}),
method: "POST"
}).then(handleErrors);
A: I don't think the {N} runtime has access to URLSearchParams class, it's browser specific.
You could achieve the same with a simple loop through keys in object,
var data = {
"username": viewModel.get("username"),
"firstname": viewModel.get("firstname"),
"lastname": viewModel.get("lastname"),
"email": viewModel.get("email"),
"password": viewModel.get("password")
};
var endocedStr = "";
for (var prop in data) {
if(endocedStr) {
endocedStr += "&";
}
endocedStr += prop + "=" + data[prop];
}
return fetchModule.fetch(config.apiUrl + "auth/register", {
body: endocedStr
method: "POST"
}).then(handleErrors); | unknown | |
d16925 | val | There also are solutions for playing Youtube Videos in an app on Github.
Like this one: https://github.com/rinov/YoutubeKit
Or this one: https://github.com/gilesvangruisen/Swift-YouTube-Player
Just simply add the pod for the project that you want to use, install the pod in terminal, and you can use the functionality in that project.
Hope that this is helpful.
A: Here's another solution if you don't want to use the API provided by YouTube and instead continue using a UIWebView.
YouTube has functionality to load any video in fullscreen in a webview without any of the scrolling features using a URL in the format https://www.youtube.com/embed/<videoId>.
For example, to load Gangnam Style using this method, simply direct the UIWebView to the URL https://www.youtube.com/embed/9bZkp7q19f0.
A: The API that YouTube provides to embed videos in iOS apps is indeed written in Objective-C, but it works just as well in Swift.
To install the library via CocoaPods, follow the CocoaPods setup instructions and add the following line to your Podfile:
pod ‘youtube-ios-player-helper’, ‘~> 0.1’
Once you have run pod install, be sure to use the .xcworkspace file from now on in Xcode.
To import the pod, simply use the following import statement at the top of your Swift files:
import youtube_ios_player_helper
You can then create youtube player views as follows:
let playerView = YTPlayerView()
You can include this view in your layouts as you would any other UIView. In addition, it includes all of the functions listed in the YouTube documentation. For instance, to load and play a video, use the following function:
playerView.load(withVideoId: videoId);
Where videoId is the string id found in the URL of the video, such as "9bZkp7q19f0".
A: Play youtube video in Swift 4.0
if let range = strUrl.range(of: "=") {
let strIdentifier = strUrl.substring(from: range.upperBound)
let playerViewController = AVPlayerViewController()
self.present(playerViewController, animated: true, completion: nil)
XCDYouTubeClient.default().getVideoWithIdentifier(strIdentifier) {
[weak playerViewController] (video: XCDYouTubeVideo?, error: Error?) in
if let streamURLs = video?.streamURLs, let streamURL =
(streamURLs[XCDYouTubeVideoQualityHTTPLiveStreaming] ??
streamURLs[YouTubeVideoQuality.hd720] ??
streamURLs[YouTubeVideoQuality.medium360] ??
streamURLs[YouTubeVideoQuality.small240]) {
playerViewController?.player = AVPlayer(url: streamURL)
} else {
self.dismiss(animated: true, completion: nil)
}
}
} | unknown | |
d16926 | val | found the answer! I needed to install @types/jasmine and then import it like this: import { } from 'jasmine'; | unknown | |
d16927 | val | You are not making a mistake if you are doing this in the controller.
In the MVC pattern, the controller listens for model changes and updates the view. That is what the controller is supposed to do. Here,
view.getRightPanel().getDrawPanel().appendText(model.getResults());
I guess you are changing the text in a draw panel in the view that controller is controlling, which is exactly what the controller is supposed to do.
Do be careful not to change update the model directly from the view, or update the view from the model though. That violates MVC.
I also suggest you to create multiple controllers to control different panels on the screen. I think that way it will be more manageable. | unknown | |
d16928 | val | What is the end of page load? window.onload?
var start = new Date();
$(window).load(function() {
$('body').html(new Date() - start);
});
jsFiddle.
If you're supporting newer browsers, you can swap the new Date() with Date.now().
A: With large pages or pages containing inline JavaScript, it is a good idea to monitor how long pages take to load.
The code below is different from waiting until onload is fired and only measures page load time. [+]
<html>
<head>
<script type="text/javascript">
var t = new Date();
</script>
… (your page) …
<script type="text/javascript">
new Image().src = '/load.gif?' + (new Date().getTime() - t.getTime());
</script>
</body>
<html>
load.gif can be a generic 1*1 pixel GIF. You can extract the data from your log files using grep and sed.
Also check here.
*
*Page load time with Jquery
*Javascript: time until page load
One good diagnostic tool to help measure page load time is [jQTester]. It is a plugin that has you place small amounts of code at the top and bottom of your page. When the page finishes loading, you get a notification saying how long it took the page to load | unknown | |
d16929 | val | It is probably taking a long time because you are expecting the mean to be exactly equal to the expected_avg. Because it is a random variable in which one out of n observations can change the average, this is a problem, especially as n grows. If this is allowed, you could use a method such that the mean is sufficiently close, e.g. at most 5% away. Suppose that we call this tolerance. Try something like the following:
while abs((avg-expected_avg)/expected_avg) > tolerance:
l = np.random.randint(a, b, size=n)
avg = np.mean(l) | unknown | |
d16930 | val | It depends on how much messy the strings are, in worst cases this regexp-based solution should do the job:
import re
x=re.compile(r"^\s*(mr|mrs|ms|miss)[\.\s]+", flags=re.IGNORECASE)
x.sub("", text)
(I'm using re.compile() here since for some reasons Python 2.6 re.sub doesn't accept the flags= kwarg..)
UPDATE: I wrote some code to test that and, although I wasn't able to figure out a way to automate results checking, it looks like that's working fine.. This is the test code:
import re
x=re.compile(r"^\s*(mr|mrs|ms|miss)[\.\s]+", flags=re.IGNORECASE)
names = ["".join([a,b,c,d]) for a in ['', ' ', ' ', '..', 'X'] for b in ['mr', 'Mr', 'miss', 'Miss', 'mrs', 'Mrs', 'ms', 'Ms'] for c in ['', '.', '. ', ' '] for d in ['Aaaaa', 'Aaaa Bbbb', 'Aaa Bbb Ccc', ' aa ']]
print "\n".join([" => ".join((n,x.sub('',n))) for n in names])
A: Depending on the complexity of your data and the scope of your needs you may be able to get away with something as simple as stripping titles from the lines in the csv using replace() as you iterate over them.
Something along the lines of:
titles = ["Mr.", "Mrs.", "Ms", "Dr"] #and so on
for line in lines:
line_data = line
for title in titles:
line_data = line_data.replace(title,"")
#your code for processing the line
This may not be the most efficient method, but depending on your needs may be a good fit.
How this could work with the code you posted (I am guessing the Mr./Mrs. is part of column 1, the first name):
import csv
books = csv.reader(open("books.csv","rU"))
for row in books:
first_name = row[1]
last_name = row[0]
for title in titles:
first_name = first_name.replace(title,"")
print '.'.(first_name, last_name) | unknown | |
d16931 | val | DateTime.Parse tries a number of formats - some to do with the current culture, and some more invariant ones. It looks like it's including an attempt to parse with the ISO-8601 format of "yyyy-MM-dd" - which is valid for your first example, but not for your second. (There aren't 35 days in December.)
As it's trying to parse multiple formats, it doesn't necessarily make sense to isolate which part is "wrong" - different parts could be invalid for different formats.
How you should tackle this depends on where your data comes from. If it's meant to be machine-readable data, it's best to enforce a culture-invariant format (ideally ISO-8601) rather than using DateTime.Parse: specify the format you expect using DateTime.ParseExact or DateTime.TryParseExact. You still won't get information about which part is wrong, but it's at least easier to reason about. (That will also make it easier to know which calendar system is being used.)
If the data is from a user, ideally you'd present them with some form of calendar UI so they don't have to enter the text at all. At that point, only users who are entering the text directly would produce invalid input, and you may well view it as "okay" for them to get a blanket error message of "this value is invalid".
I don't believe .NET provides any indication of where the value was first seen to be invalid, even for a single value. Noda Time provides more information when parsing via the exception, but not in a machine-readable way. (The exception message provides diagnostic information, but that's probably not something to show the user.)
In short: you probably can't do exactly what you want to do here (without writing your own parser or validator) so it's best to try to work out alternative approaches. Writing a general purpose validator for this would be really hard.
If you only need to handle ISO-8601 dates, it's relatively straightforward:
*
*Split the input by dashes. If there aren't three dashes, it's invalid
*Parse each piece of the input as an integer. That can fail (on each piece separately)
*Validate that the year is one you're happy to handle
*Validate that the month is in the range 1-12
*Validate that the day is valid for the month (use DateTime.DaysInMonth to help with that)
Each part of that is reasonably straightforward, but what you do with that information will be specific to your application. We don't really have enough context to help write the code without making significant assumptions. | unknown | |
d16932 | val | You could create two interfaces. One will contains the methods that you will implement in both classes and the other one the extra method that you want for the other class. Then just implement the right interface to the right class.
public interface A {
public void doSomething1();
public void doSomething2();
}
public interface B extends A {
public void doSomething3();
}
Then
public class ClassB implements B{
public void doSomething1(){
System.out.println("doSomething 1");
}
public void doSomething2(){
System.out.println("doSomething 2");
}
public void doSomething3(){
System.out.println("doSomething 3");
}
}
public class ClassA implements A{
public void doSomething1(){
System.out.println("doSomething 1");
}
public void doSomething2(){
System.out.println("doSomething 2");
}
}
A: This issue is solved by introducing such called Adapter: this is an abstract class, which implements all methods from inherited interface. In your desired class you could override only that methods, which you want:
public abstract class AAdapter implements A(){
public void doSomething1(){
}
public void doSomething2(){
}
public void doSomething3(){
}
}
and in your class:
public class C extends AAdapter(){
@Override
public void doSomething1(){
system.out.println("doSomething 1");
}
@Override
public void doSomething2(){
system.out.println("doSomething 2");
}
}
A: You can create a simple implementation of your interface that always trigger NoSuchMethodError or any other runtime exception.
And then simply extends that class and override only the useful methods.
Or as stated in another answer, you might consider redesigning your interfaces.
A: You can consider creating stub implementation:
public class SimpleA implements A {
@Override
public void doSomething1() {
throw new UnsupportedOperationException();
}
// rest omitted
}
Now your classes can extend SimpleA and override only needed methods. | unknown | |
d16933 | val | use this:
final DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
if (isOkayClicked) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
}
isOkayClicked = false;
}
};
final DatePickerDialog datePickerDialog = new DatePickerDialog(
HomePageActivity.this, R.style.DialogTheme, datePickerListener,
year, month, day); //use your activity name here instead of HomePageActivity
datePickerDialog.getDatePicker().setMaxDate(new Date().getTime()); // setting the max date
datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
isOkayClicked = false;
}
}
});
datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE,
"Change", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
isOkayClicked = true;
DatePicker datePicker = datePickerDialog
.getDatePicker();
datePickerListener.onDateSet(datePicker,
datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth());
}
}
});
datePickerDialog.setCancelable(false);
datePickerDialog.show();
if needed, remove final keyword..
add this to values/styles.xml
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">#e9671c</item> // you can change the color here
</style>
A: hope this will help you
place this in your on click event
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
also add below Fragment in your Project
class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
}
} | unknown | |
d16934 | val | UUIDs in general are meant and optimized to be unique. They do not offer a guaranteed randomness. You should not use UUIDs as secrets and/or random number generator.
There are several versions how UUIDs are generated, most of them are not random, but rather predictable. See the Wikipedia article on UUIDs and the various versions.
If you want to avoid collisions for IDs, use UUIDs, if you want secrets, use strong cryptographic (P)RNGs.
Also note, that the variant is encoded in the UUID itself, so at least this part of the UUID is not random at all.
EDIT: There is an interesting article by Raymond Chen in his famous blog "Old New Thing" about almost exactly this question. | unknown | |
d16935 | val | You need to use quotes:
input[name="data[title]"] {} | unknown | |
d16936 | val | Simply put, if you only have 1 for-loop that you want to parallelise use #pragma omp parallel for simd.
If you want to parallelise multiple for-loops or add any other parallel routines before or after the current for-loop, use:
#pragma omp parallel
{
// Other parallel code
#pragma omp for simd
for (int i = 0; i < 100; ++i)
{
c[i] = a[i] ^ b[i];
}
// Other parallel code
}
This way you don't have to reopen the parallel section when adding more parallel routines, reducing overhead time. | unknown | |
d16937 | val | I think you should turn your useProjectArtifact to true (this is the default value).
It determines whether the artifact produced during the current project's build should be included in this dependency set. | unknown | |
d16938 | val | I suggest using $timeout instead of setTimeout which will automatically trigger a digest cycle. | unknown | |
d16939 | val | This is because the current initialization action explicitly launches the jupyter notebook service calling launch-jupyter-kernel.sh. Initialization actions aren't the same as GCE startup-scripts in that they don't re-run on startup; the intent normally is that initialization actions need not be idempotent, but instead if they want to restart on startup need to add some init.d/systemd configs to do so explicitly.
For the one-off case, you can just SSH into the master, then do:
sudo su
source /etc/profile.d/conda.sh
nohup jupyter notebook --allow-root --no-browser >> /var/log/jupyter_notebook.log 2>&1 &
If you want this to happen automatically on startup, you can try to put that in a startup script via GCE metadata, though if you're doing that at cluster creation time you'll need to make sure it doesn't collide with the Dataproc initialization action (also, startup scripts might run before the dataproc init action, so the first attempt you might just want to allow to fail silently).
Longer term, we should update the initialization action to add the entry into init.d/systemd so that the init action itself configures auto restart on reboot. There's no one dedicated to this at the moment, but if you or anyone you know is up to the task, contributions are always well appreciated; I filed https://github.com/GoogleCloudPlatform/dataproc-initialization-actions/issues/108 to track this feature.
A: I fixed the problem by connecting to master machine using ssh and created a systemd service(followed dennis-huo's comment above).
*
*go to /usr/lib/systemd/system
*sudo su
*create a systemd unit file called "jupyter-notebook.service" with content
[Unit]
Description=Start Jupyter Notebook Server at reboot
[Service]
Type=simple
ExecStart=/opt/conda/bin/jupyter notebook --allow-root --no-browser
[Install]
WantedBy=multi-user.target
*systemctl daemon-reload
*systemctl enable jupyter-notebook.service
*systemctl start jupyter-notebook.service
Next step will be to include above code into dataproc-initialization-actions.
Hope that helps. | unknown | |
d16940 | val | The loop(s) in getLocation loop over the dimensions of a 2x scaled copy of the Image, but then attempt to access the pixels of the original. Given the original is half the size, when you are half-way through the loop you will be out of bounds of the image dimensions. Either:
*
*Don't scale the Image
*If you must scale the Image, check the pixel value of the scaled image rather than the original.
As an aside, the code posted contains redundant calls...a) in getLocation if you are going to scale, consider scaling the image once rather than placing that code within the loop itself b) no need to call getLocation twice with the same parameters. Call it once and just use the returned array | unknown | |
d16941 | val | You can use:
$('#clickme').click(function(){
// logic here
});
A: Like this, readonly catch click, disabled doesen't . fiddle
$(function(){
$('#clickme').on('click', function(){
alert(1)
})
})
A: <input type="text" readonly value="Click me" id="clickme" onClick="myFunction()"/>
<script>
...
function myFunction(){
// Your function
}
...
</script>
A: Just add a click event to the textbox.
JQuery:
$("#clickme").click(function(){
alert("do something");
});
JsFiddle
A: Jquery is awesome if you include it.
$('#clickme').on('click', function(e) {
// do something
});
A: Without more information as to what, precisely, you want to do, I'd suggest:
$('#clickme').on('click', function(){
// to allow for editing of contents:
$(this).prop('readonly', false);
});
JS Fiddle demo.
Or:
$('#clickme').on('click', function(){
// to do something if this is readonly:
if (this.readOnly) {
// for example:
console.log('this input is readonly');
}
});
JS Fiddle demo.
A: You can use jquery as
$('#clickme').click(function(){
alert('clickable');
// Your Method.
});
Add few style too
#clickme
{
cursor:pointer;
cursor:hand;
}
Check out this Demo
A: you can use onclick function, like
<input type="text" readonly value="Click me" id="clickme" onclick="myfunction()" />
A: $('#clickme').click(function(){
alert('Textbox is clicked)
}); | unknown | |
d16942 | val | for %%i in (%file%) do @echo %%~nxi
n for name
x for extension
for more options see for /? | unknown | |
d16943 | val | There is an issue with ionic when you have a custom button in the navbar and the page is not root.
You can find a quick fix here..
Ionic 3: Menutoggle keeps getting hidden
A: The solution is that, set the page to the root page.
page.ts:
movetopage1()
{
this.navCtrl.setRoot(Page1);
}
This is the method that comes in the Ionic sidebar theme.
This is the one that comes in the Ionic sidebar theme:
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
} | unknown | |
d16944 | val | After talking to @derickr on twitter, I used xdebug.auto_trace=1 in my PHP INI to trace the problem. The problem was in this line of code:
$stack = $front->getPlugin('ActionStack');
This is found in the function above named getStack(). The auto_trace showed that the first time getStack() runs, it runs correctly. The reason that PHPUnit was causing the error to show up is that when it runs the Code Coverage report, the dispatcher runs multiple times thus entering getStack() again and triggering the aforementioned line of code. The code needed the following change to remove the error and properly locate the plug-in in memory:
$stack = $front->getPlugin('Zend_Controller_Plugin_ActionStack');
The Code Coverage report now generates properly. Hopefully this will help explain the problem for others who find themselves with similar errors.
-Ross
A: Properly your PHPUnit test is not correct. | unknown | |
d16945 | val | for(int i = NUM_LEDS; i > 1; i--)
You need to start from NUM_LEDS - 1 and go to zero:
for(int i = NUM_LEDS - 1; i >= 0; i--)
Because NUM_LEDS itself is out of range. | unknown | |
d16946 | val | Since I see that you are formatting your results as CSV I am curious as to whether you have looked at the CSVResponseFormat that Solr has supported since release 3.1 | unknown | |
d16947 | val | Sorry our logging guidance is a little hard to find - something that we are currently working on resolving - but for now please take a look at the following resources:
Client logging overview - Essentially all client library operations are output using System.Diagnostics, so you intercept and write to text / xml file just using a standard TraceListener.
Analytics and Server logs - We have extensive service side logging capabilities as well - which troubleshooting distributed apps much simpler.
Let me know if you have any questions.
Jason | unknown | |
d16948 | val | You can just add some more nodes
schematic <- grViz("digraph lexicon {
# node definitions with substituted label text
node [fontname = Helvetica, shape = rectangle, style=filled,color=lightgrey]
tab1 [label = '@@1']
tab2 [label = '@@2']
tab3 [label = '@@3']
tab4 [label = '@@4']
tab5 [label = '@@5']
node [shape = rectangle, fillcolor=PeachPuff]
tab6 [label = '@@6']
node [shape = rectangle, fillcolor=CadetBlue]
tab7 [label = '@@7']
node [shape = rectangle, fillcolor=Lavender]
tab8 [label = '@@8']
node [fontname = Helvetica, shape = rectangle, style=bold]
m1 [label = 'Did not agree to participate n=18']
m2 [label = 'Under 18 years n=11']
m3 [label = 'No smoke in past 3 months n=8']
m4 [label = 'Did not complete survey n=155']
# ------> NEW NODES
node [fontname = Helvetica, shape = rectangle, style=bold, width = 2.5, height = 1, ALIGN = LEFT]
q1 [label = 'Question 1 \\l\n\n']
q2 [label = 'Question 2 \\l\n\n']
q3 [label = 'Question 3 \\l\n\n']
a11 [label = 'Answer 1 \\l\n\n']
a21 [label = 'Answer 1 \\l\n\n']
a22 [label = 'Answer 2 \\l\n\n']
a23 [label = 'Answer 3 \\l\n\n']
a31 [label = 'Answer 1 \\l\n\n']
a32 [label = 'Answer 2 \\l\n\n']
a33 [label = 'Answer 3 \\l\n\n']
# creating horizontal lines
node [shape=none, width=0, height=0, label='']
{rank=same; tab1 -> m1}
{rank=same; tab2 -> m2}
{rank=same; tab3 -> m3}
{rank=same; tab4 -> m4}
# edge definitions with the node IDs
tab1 -> tab2 -> tab3 -> tab4 -> tab5->{tab6 tab7 tab8};
#--------> ATTACH NEW NODES
tab6 -> q1 -> a11
tab7 -> q2 -> a21 -> a22 -> a23
tab8 -> q3 -> a31 -> a32 -> a33
}
[1]: 'Raw Data n=434'
[2]: 'Agreed to participate n=406'
[3]: 'Over 18 years n=491'
[4]: 'smoke in past 3 months=403'
[5]: 'Final sample n=238'
[6]: 'Group1 n=82'
[7]: 'Group2 n=98'
[8]: 'Group3 n=88'
")
jpeg(file = "schematic.jpg")
schematic | unknown | |
d16949 | val | Use:
df = pd.DataFrame({'A': [1, 2, 3,5,7], 'B': [1.45, 2.33, np.nan, np.nan, np.nan],
'C': [4, 5, 6,8,7], 'D': [4.55, 7.36, np.nan,9,10],
'E':list('abcde')})
print (df)
A B C D E
0 1 1.45 4 4.55 a
1 2 2.33 5 7.36 b
2 3 NaN 6 NaN c
3 5 NaN 8 9.00 d
4 7 NaN 7 10.00 e
def treat_mis_value_nu(df):
#get only numeric columns to dataframe
df_nu = df.select_dtypes(include=['number'])
#get only columns with NaNs
df_nu = df_nu.loc[:, df_nu.isnull().any()]
#get columns for remove with mean instead sum/len, it is same
cols_to_drop = df_nu.columns[df_nu.isnull().mean() <= 0.30]
#replace missing values of original columns and remove above thresh
return df.fillna(df_nu.median()).drop(cols_to_drop, axis=1)
print (treat_mis_value_nu(df))
A C D E
0 1 4 4.55 a
1 2 5 7.36 b
2 3 6 8.18 c
3 5 8 9.00 d
4 7 7 10.00 e
A: I would recommend looking at the sklearn Imputer transformer. I don't think it it can drop columns but it can definetly fill them in a 'generic way' - for example, filling in missing values with the median of the relevant column.
You could use it as such:
from sklearn.preprocessing import Imputer
imputer = Imputer(strategy='median')
num_df = df.values
names = df.columns.values
df_final = pd.DataFrame(imputer.transform(num_df), columns=names)
If you have additional transformations you would like to make you could consider making a transformation Pipeline or could even make your own transformers to do bespoke tasks. | unknown | |
d16950 | val | Scopes are same as class methods, so within the scope you are implicitly call another class methods. And your distinct_mechanics_sql is an instance method, to use it inside a scope declare it as:
def self.distinct_mechanics_sql
or
def Mechanics.distinct_mechanics_sql
or
class << self
def distinct_mechanics_sql
...
end
end | unknown | |
d16951 | val | This has nothing to do with API nor with the csv format actually, it's just that:
since the myFile = open('AutoCSV.csv', "w") is in a for loop it just continues to "open and close" the file
Indeed - and not only that but it clears the file each time it reopens it, as documented here:
'w' for writing (truncating the file if it already exists)
Also, you're not using with open() correctly, you want:
with open("path/to/your/file.ext") as f:
# your code using the file here
Hopefully the fix is simple: open the file before your outer loop. Now may I ask why you didn't tried this directly instead of posting here ?
A: Since you don't provide any input data, I'll have to do this blindly. Does this works for you?:
import csv
import requests
headers = {} #something
with open('AutoCSV.csv', "w", , newline='') as csv_output_file:
file_writer = csv.writer(csv_output_file)
for current_page_start in range(0, 2500, 500):
url_to_retrieve = f"https://api.rainforestcloud.com/rest/device?networkName=Company&take=500&skip={current_page_start}"
json_response = requests.get(url_to_retrieve, headers=headers).json()
for response_element in json_response:
data_to_write = (response_element['deviceGuid'], response_element['status'])
file_writer.writerow(data_to_write) | unknown | |
d16952 | val | This was actually really simple now that I look at it, once I have verified that I was authenticated I could use the same HttpClient (that holds the cookies) to request other files and push files to the web server using MultipartEntity | unknown | |
d16953 | val | A recent release of U-SQL has added diagnostic logging for UDOs. See the release notes here.
// Enable the diagnostics preview feature
SET @@FeaturePreviews = "DIAGNOSTICS:ON";
// Extract as one column
@input =
EXTRACT col string
FROM "/input/input42.txt"
USING new Utilities.MyExtractor();
@output =
SELECT *
FROM @input;
// Output the file
OUTPUT @output
TO "/output/output.txt"
USING Outputters.Tsv(quoting : false);
This was my diagnostic line from the UDO:
Microsoft.Analytics.Diagnostics.DiagnosticStream.WriteLine(System.String.Format("Concatenations done: {0}", i));
This is the whole UDO:
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Analytics.Interfaces;
namespace Utilities
{
[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class MyExtractor : IExtractor
{
//Contains the row
private readonly Encoding _encoding;
private readonly byte[] _row_delim;
private readonly char _col_delim;
public MyExtractor()
{
_encoding = Encoding.UTF8;
_row_delim = _encoding.GetBytes("\n\n");
_col_delim = '|';
}
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{
string s = string.Empty;
string x = string.Empty;
int i = 0;
foreach (var current in input.Split(_row_delim))
{
using (System.IO.StreamReader streamReader = new StreamReader(current, this._encoding))
{
while ((s = streamReader.ReadLine()) != null)
{
//Strip any line feeds
//s = s.Replace("/n", "");
// Concatenate the lines
x += s;
i += 1;
}
Microsoft.Analytics.Diagnostics.DiagnosticStream.WriteLine(System.String.Format("Concatenations done: {0}", i));
//Create the output
output.Set<string>(0, x);
yield return output.AsReadOnly();
// Reset
x = string.Empty;
}
}
}
}
}
And these were my results found in the following directory:
/system/jobservice/jobs/Usql/2017/10/20.../diagnosticstreams
A: good question. I have been asking myself the same thing. This is theoretical, but I think it would work (I'll updated if I find differently).
One very hacky way is that you could insert rows into a table with your log messages as a string column. Then you can select those out and filter based on some log_producer_id column. You also get the benefit of logging if part of the script works, but later parts do not assuming the failure does not roll back. Table can be dumped at end as well to file.
For the error cases, you can use the Job Manager in ADLA to open the job graph and then view the job output. The errors often have detailed information for data-related errors (e.g. row number in file with error and a octal/hex/ascii dump of the row with issue marked with ###).
Hope this helps,
J
ps. This isn't a comment or an answer really, since I don't have working code. Please provide feedback if the above ideas are wrong. | unknown | |
d16954 | val | I'm unsure what "quirks/limitations" you're running into using inline-block, but if you apply it to .item.w1 only, it seems to work.
You'll also need to remove float: none here:
@media only screen
and (max-width : 768px)
and (orientation : portrait) {
.item.w1, .item.w2 {
float: none;
width: 100%;
}
}
Fiddle | unknown | |
d16955 | val | The issue is not so much with Rx as it is with the usage of the Context.
You should try to keep the response handling logic within your Handler, that is don't pass the Context around, rather get the objects you need and pass them to your services.
As an example
path('myendpoint') { MyRxService service ->
byMethod {
get {
// do something when request is GET
}
post {
request.body.map { typedData ->
extractItem(typeData) // extract your item from the request first
}.flatMap { item ->
service.saveJsonAsItemLocation(item).promiseSingle() // then once it's extracted pass the item to your "saveJsonAsItemLocation" method
}.then { ItemLocationStore updatedItem ->
response.headers.add(HttpHeaderNames.LOCATION, "/itemloc/v1/save/${updatedItem.tcin}/${updatedItem.store}")
context.response.status(HttpResponseStatus.CREATED.code()).send()
}
}
}
}
My guess is that you have something like this:
get {
// get stuff
}
post {
// post stuff
}
The reason this doesn't work is that Ratpack doesn't use Routing Table for handling incoming requests, instead it uses chain delegation. The get {} binds to root path and GET http method and post {} binds to root path and POST http method. Because get {} matches the path, Ratpack considers the handler matched and since the handler is for GET it considers it a 405.
There are chain methods available that binds regardless of HTTP Method such as all {} and path {}. Chain#all will handle all paths and methods where as Chain#path(String) matches against specific path.
Hope this helps. | unknown | |
d16956 | val | Try adding the following request header:
[req addRequestHeader:@"Cache-Control" value:@"no-cache"];
I encountered the same problem as you and adding the above code solved the problem for me.
Taken from ASIHTTPRequest seems to cache JSON data always | unknown | |
d16957 | val | You can use DelegateCommand for this. Which helps you use one Generic class for all commands instead of creating individual Command classes.
public sealed class MyViewModel : INotifyPropertyChanged
{
private ICommand _test;
private bool _success;
public bool ShowSuccess
{
get { return _success; }
set
{
_success = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShowSuccess)));
}
}
public ICommand TestCommand
{
get
{
_test = _test ?? new DelegateCommand((arg) => ShowSuccess = true);
return _test;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
A: I strongly recomment taking a look at ReactiveUI - UI framework based around Rx - you don't have to use all of its features, like built in dependency injection or view location, but it's also very cool. It's not worth to reinvent the wheel in this case.
It has an implementation of ICommand that not only supports asynchronous work out of the box, it also allows commands to return stuff (VERY usefull) and takes care of disabling buttons when executing.
It also comes with DynamicData - a cure to all problems related to collections.
So, most basic sample would be:
TestCommand = ReactiveCommand.CreateFromTask<int>(async paramater =>{
var result = await DoStuff(parameter); // ConfigureAwait(false) might be helpful in more complex scenarios
return result + 5;
}
TestCommand.Log(this) // there is some customization available here
.Subscribe(x => SomeVmProperty = x;); // this always runs on Dispatcher out of the box
TestCommand.ThrownExceptions.Log(this).Subscribe(ex => HandleError(ex));
this.WhenAnyValue(x => x.SearchText) // every time property changes
.Throttle(TimeSpan.FromMilliseconds(150)) // wait 150 ms after the last change
.Select(x => SearchText)
.InvokeCommand(Search); // we pass SearchText as a parameter to Search command, error handling is done by subscribing to Search.ThrownExceptions. This will also automatically disable all buttons bound to Search command
What is even more useful, I think, is being able to subscribe in the View code behind.
// LoginView.xaml.cs
ViewModel.Login.Where(x => !x.Success).Subscribe(_ =>{
PasswordBox.Clear();
PasswordBox.Focus();
}); | unknown | |
d16958 | val | Just escape the special characters in regex
df = pd.DataFrame({'texts': [
'This is really important(actually) because it has really some value',
'This is not at all necessary for it @ to get that']})
keyword = 'important(actually)'
df[df.apply(lambda x:
x.astype(str).str.contains(
re.escape(keyword), flags=re.I)).any(axis=1)]
Output:
texts
0 This is really important(actually) because it ...
A: contains use regex and brackets are special chapter in regex
You can disable the regex by add regex=False:
df_filter=df[df.apply(lambda x: x.astype(str).str.contains(keyword, regex=False)).any(axis=1)] | unknown | |
d16959 | val | I propose two alternatives:
*
*If the IP of the given host is mandatory for your application to work properly, you could get it into the constructor and re-throw the exception as a configuration error:
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
{
try {
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
catch (UnknownHostException e)
{
throw new ServiceConfigurationError(e.toString(),e);
}
}
}
*
*But if it is not that mandatory, and this error might be recovered somehow, simply declare UnknownHostException in the constructor's throws clause (which will force you to capture/rethrow that exception in all the call hierarchy of your class' constructor):
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
throws UnknownHostException
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
}
A: This is my simple method using my android application.
private static int timeout = 500;
private static int isIpAddressString(String tstr, byte[] ipbytes)
{
final String str = tstr;
boolean isIpAddress = true;
StringTokenizer st = new StringTokenizer(str, ".");
int idx = 0;
if(st.countTokens() == 4)
{
String tmpStr = null;
byte[] ipBytes = new byte[4];
while(st.hasMoreTokens())
{
tmpStr = st.nextToken();
for (char c: tmpStr.toCharArray()) {
if(Character.isDigit(c)) continue;
else
{
//if(c != '.')
{
isIpAddress = false;
break;
}
}
}
if(!isIpAddress) break;
ipBytes[idx] = (byte)(Integer.valueOf(tmpStr.trim()).intValue());
idx++;
}
System.arraycopy(ipBytes, 0, ipbytes, 0, ipbytes.length);
}
return idx;
}
public static boolean canResolveThisUrlString(final String TAG, String urlStr)
{
String resolveUrl = urlStr;
boolean isResolved = false;
java.net.InetAddress inetaddr = null;
try
{
//java.net.InetAddress addr = java.net.InetAddress.getByName(resolveUrl);
byte[] ipbytes = new byte[4];
if(isIpAddressString(urlStr, ipbytes) == 4)
{
inetaddr = java.net.InetAddress.getByAddress(ipbytes);
}
else
{
String host = null;
if(resolveUrl.startsWith("http") ||resolveUrl.startsWith("https") )
{
URL url = new URL(resolveUrl);
host = url.getHost();
}
else
host = resolveUrl;
inetaddr = java.net.InetAddress.getByName(host);
}
//isResolved = addr.isReachable(SettingVariables.DEFAULT_CONNECTION_TIMEOUT);
isResolved = inetaddr.isReachable(timeout);
//isResolved = true;
}
catch(java.net.UnknownHostException ue)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, ue);
ue.printStackTrace();
isResolved = false;
}
catch(Exception e)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, e);
e.printStackTrace();
isResolved = false;
}
//System.out.println(isResolved + "::::::::" + inetaddr.toString());
return isResolved;
}
You can test it with
public static void main(String[] args)
{
String urlString = "https://www.google.com";
String urlString1 = "www.google.com";
String urlString2 = "https://www.google.co.kr/search?q=InetAddress+create&rlz=1C1NHXL_koKR690KR690&oq=InetAddress+create&aqs=chrome..69i57j0l5.5732j0j8&sourceid=chrome&ie=UTF-8";
String urlString3 = "127.0.0.1";
//URL url = null;
try {
boolean canResolved = canResolveThisUrlString(null, urlString);
System.out.println("resolved " + canResolved + " : url [" + urlString + "]");
canResolved = canResolveThisUrlString(null, urlString1);
System.out.println("resolved " + canResolved + " : url [" + urlString1 + "]");
canResolved = canResolveThisUrlString(null, urlString2);
System.out.println("resolved " + canResolved + " : url [" + urlString2 + "]");
canResolved = canResolveThisUrlString(null, urlString3);
System.out.println("resolved " + canResolved + " : url [" + urlString3 + "]");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you've got a UnknownHostException from your app when the url you've requested can't be resolved by whatever dns servers.
This case, you can not get any host name with ip address like 'www.girionjava.com' host in the internet world. | unknown | |
d16960 | val | Depending on your OS, there are three approaches (all of which add considerable performance losses but might be acceptable for your app)
*
*Check process list - You can execute a console command to check the list of runniing processes. I dont think this is possible on windows but no problem on linux. Take EXTRA care to filter any and all variables used there as running console command can be a big security risk.
*running files - Create a file on start of your script and check for it's existance. I think this is how most (even non PHP) processes check if they are running. Performance loss and security issues should be minimal, you have to take care that the file is properly removed though, even in case ofa an error.
*info in storage - Like the file solution, you can add information into your database or other storage system. Performance loss is slightly bigger than file IO but if you already have a db connection for your script, it might be worth it. It's also easier to store more informatione for your current process there or add logging to it. | unknown | |
d16961 | val | I actually had to wrap the $modal and $modalInstance services to take a type T. The above answer (which I had initially tried) will not work because the $modalInstance result is a promise of type 'any'. The wrapped $modalInstance is a promise of type T.
module my.interfaces {
export interface IMyModalService<T> {
open(options: ng.ui.bootstrap.IModalSettings): IMyModalServiceInstance<T>;
}
export interface IMyModalScope<T> extends ng.ui.bootstrap.IModalScope {
$dismiss(reason?: any): boolean;
$close(result?: T): boolean;
}
export interface IMyModalServiceInstance<T> extends ng.ui.bootstrap.IModalServiceInstance {
close(result?: T): void;
dismiss(reason?: any): void;
result: angular.IPromise<T>;
opened: angular.IPromise<any>;
rendered: angular.IPromise<any>;
}
A: this.$modal.open(options).result.then((result: myType) => {
Now result is declared to be of your type
}); | unknown | |
d16962 | val | The sockaddr is a generic socket address. If you remember, you can create TCP/IPv4, UDP/IPv4, UNIX, TCP/IPv6, UDP/IPv6 sockets (and more!) through the same operating system API - socket().
All of these different socket types have different actual addresses - composed of different fields.
sockaddr_in is the actual IPv4 address layout (it has .sin_port and .sin_addr). A UNIX domain socket will have type sockaddr_un and will have different fields defined, specific to the UNIX socket family.
Basically sockaddr is a collection of bytes, it's size being the maximum of sizes of all supported (by the O/S) socket/address families such that it can hold all of the supported addresses.
A: Taking a look at sockaddr_in
struct sockaddr_in
{
__SOCKADDR_COMMON (sin_);
in_port_t sin_port; /* Port number. */
struct in_addr sin_addr; /* Internet address. */
/* Pad to size of `struct sockaddr'. */
unsigned char sin_zero[sizeof (struct sockaddr) -
__SOCKADDR_COMMON_SIZE -
sizeof (in_port_t) -
sizeof (struct in_addr)];
};
And if we see sockaddr
* Structure describing a generic socket address. */
struct sockaddr
{
__SOCKADDR_COMMON (sa_); /* Common data: address family and length. */
char sa_data[14]; /* Address data. */
};
So actually, they are not exchangeable, but but they have the same size so you can use it with no problem and cast between those structures.
But remember you must know what you are doing or probably will get segfaults or unexpected behavior. | unknown | |
d16963 | val | You would want something like this...
$myImagesList = array (
'image1.png',
'image2.png',
'image3.png',
'image4.png'
);
shuffle ($myImagesList);
$i = 0;
foreach ($myImagesList as $img) {
$i++;
if ($i % 3 === 0) { /* show content */ }
echo '<img src="/image/' . $img . '" width="200" height="140" border="0" />';
}
This will give you the content section every third iteration, no matter the size of the list.
A: If you want to add a div(content) between those two pairs of images - add additional condition into your loop:
...
for ($i=0; $i<4; $i++) {
if ($i == 1) echo '<div>some content ...</div>';
echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
}
A: Go with the most readable solution - the one that doesn't make you fall and debug later when changing something.
$splitAtNumber = 2; // or dynamically use count($myImagesList) / 2 or ....
// output first part of the array
for ($i = 0; $i < $splitAtNumber; $i++) {
echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
}
// Output your content
echo 'content';
// Output second part of the array
for ($i = splitAtNumber; $i < count($myImagesList); $i++) {
echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
} | unknown | |
d16964 | val | just use explode with your string and if pattern is always the same then get last element of the array and your work is done
$pizza = "piece1/piece2/piece3/piece4/piece5/piece6";
$pieces = explode("/", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
Then reverse your array get first four elements of array and combine them using "implode"
to get desired string
A: This function below can work like a substr start from nth occurrence
function substr_after_nth($str, $needle, $key)
{
$array = explode($needle, $str);
$temp = array();
for ($i = $key; $i < count($array); $i++) {
$temp[] = $array[$i];
}
return implode($needle, $temp);
}
Example
$str = "hello-world-how-are-you-doing";
substr after 4th occurrence of "-" to get "you-doing"
call the function above as
echo substr_after_nth($str, "-", 4);
it will result as
you-doing | unknown | |
d16965 | val | This line 'value' => '$data->jobs->id' raised an error Trying to get property of non-object because you have been permitted to accessed the property of object instead of array of objects (jobs)
The workaround is you declare a function to do the task on the controller which rendered your gridview
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
...
array(
'name'=>'newColumn',
//call the method 'gridDataColumn' from the controller
'value'=>array($this,'gridDataColumn'),
'type'=>'raw'
)
),
));
class MyController extends Controller
{
//called on rendering the column for each row
protected function gridDataColumn($data,$row)
{
$cellResult = "";
//do your loop here
//example
foreach ( $data->children as $child ) {
$cellResult .=$child->id . "<br/>";
$cellResult .=$child->name . "<br/>";
}
return $cellResult ;
}
...
}
Yii Tutorial
CGridView: Render customized/complex datacolumns | unknown | |
d16966 | val | //Hi Bob
I approached the problem from a slightly different angle: Instead of using position absolute I used display flex 2 times. Is this the flex you're looking for?
.container {
display: flex;
flex-direction: row;
}
.container > div {
flex: 0 0 50%;
}
.container2 {
display: flex;
flex-direction: column;
}
.a {
background: yellow;
}
.b {
background: orange;
flex: 0 1 100%;
}
.c {
background: red;
}
<div class="container">
<div class="a">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div><div class="container2">
<div class="b">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
<div class="c">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div></div>
Saw your comment and edited my first answer in this new code snippet. Does this one work?
.container {
display: flex;
flex-direction: row;
}
.container > div {
flex: 0 0 50%;
}
.container2 {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.a {
background: yellow;
}
.b {
background: orange;
flex: 1 0 auto;
overflow: auto;
position: relative;
}
.b-inner {
position: absolute;
width: 100%
}
.c {
background: red;
flex: 0 0 auto;
}
<div class="container">
<div class="a">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div><div class="container2">
<div class="b"><div class="b-inner">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div></div>
<div class="c">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div></div> | unknown | |
d16967 | val | It's a combination of typing errors and wrong use of SET and/or SELECT. If I understand you correctly, you may try to use the following statement:
DECLARE @a varchar(2550)
SELECT @a =
'ALTER DATABASE ' +
CAST(DB_NAME() AS VARCHAR(50)) +
' MODIFY FILE ( NAME = ' +
QUOTENAME( df.name,'''') + ', NEWNAME = ''' +
QUOTENAME( DB_NAME()) +
CASE
WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN '.mdf'' )'
WHEN df.type_desc = 'LOG' THEN '_log.ldf'' )'
WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN '.ndf'' )'
END
FROM sys.database_files df
SELECT @a
As an important note, when you use SELECT @local_variable and the SELECT statement returns more than one value, the variable is assigned the last value that is returned. So if you want to generate a complex statement for all database files, you need to concatenate the returned rows (using FOR XML PATH or STRING_AGG()). In this case, as @GordonLinoff commented, you may declare the @a variable as nvarchar(max):
DECLARE @a nvarchar(max) = N''
SELECT @a = (
SELECT
N'ALTER DATABASE ' +
CAST(DB_NAME() AS VARCHAR(50)) +
N' MODIFY FILE ( NAME = ' +
QUOTENAME( df.name,'''') +
N', NEWNAME = ''' +
QUOTENAME( DB_NAME()) +
CASE
WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN N'.mdf'' )'
WHEN df.type_desc = 'LOG' THEN N'_log.ldf'' )'
WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN N'.ndf'' )'
END +
N';'
FROM sys.database_files df
FOR XML PATH('')
)
SELECT @a
A: I think you're looking for something like this
declare @a nvarchar(max);
with file_cte as (
select
N'ALTER DATABASE ' + quotename(db_name()) +
N' MODIFY FILE ( NAME = ' + quotename( df.name,'''') +
N', NEWNAME = ''' + quotename(db_name()) +
case when df.type_desc = N'ROWS' AND df.file_id = 1 then N'.mdf'' )'
when df.type_desc = N'LOG' THEN N'_log.ldf'' )'
when df.type_desc = N'ROWS' AND df.file_id != 1 then N'.ndf'' )' end string
from sys.database_files df)
select @a=concat(string_agg(string, ';'), ';')
from file_cte;
select @a; | unknown | |
d16968 | val | The key concept here is that std::move by itself won't do any moving.
You can think of it as marking the object as a object that can be moved from.
The signature for function_call_move is
void function_call_move( unique_ptr<int>&& ptr );
Which means it can only receive objects that could be moved from, formally known as rvalues, and bind that to a reference. The act of associating an rvalue to a rvalue reference don't invalidate the state of the original object either.
So, unless function_call_move actually moves ptr to another std::unique_ptrinside it, your call to function_call_move(std::move(intptr)); won't invalidate intptr and your usage will be perfectly fine. | unknown | |
d16969 | val | Types like sql.NullInt64 do not implement any special handling for JSON marshaling or unmarshaling, so the default rules apply. Since the type is a struct, it gets marshalled as an object with its fields as attributes.
One way to work around this is to create your own type that implements the json.Marshaller / json.Unmarshaler interfaces. By embedding the sql.NullInt64 type, we get the SQL methods for free. Something like this:
type JsonNullInt64 struct {
sql.NullInt64
}
func (v JsonNullInt64) MarshalJSON() ([]byte, error) {
if v.Valid {
return json.Marshal(v.Int64)
} else {
return json.Marshal(nil)
}
}
func (v *JsonNullInt64) UnmarshalJSON(data []byte) error {
// Unmarshalling into a pointer will let us detect null
var x *int64
if err := json.Unmarshal(data, &x); err != nil {
return err
}
if x != nil {
v.Valid = true
v.Int64 = *x
} else {
v.Valid = false
}
return nil
}
If you use this type in place of sql.NullInt64, it should be encoded as you expect.
You can test this example here: http://play.golang.org/p/zFESxLcd-c
A: If you use the null.v3 package, you won't need to implement any of the marshal or unmarshal methods. It's a superset of the sql.Null structs and is probably what you want.
package main
import "gopkg.in/guregu/null.v3"
type Person struct {
Name string `json:"id"`
Age int `json:"age"`
NickName null.String `json:"nickname"` // Optional
}
If you'd like to see a full Golang webserver that uses sqlite, nulls, and json you can consult this gist. | unknown | |
d16970 | val | finish the function with
def getStatistics(students)
...
# snip
...
return average, highest, lowest | unknown | |
d16971 | val | Well when I created my tables in MySQL I used capital names for all my table names. For some reason when running it locally, the table names were still uppercase in development mode, but were lowercase for test mode. So, in my user model, I simply changed the self.table_name = "USERS" to self.table_name = "users" and that fixed my problem. | unknown | |
d16972 | val | Convert the string to Date Object then you will be able to use that function.
Here is MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
this.employee={}
this.employee.dob='1/2/2018'
let birthDate = this.employee.dob;
console.log(birthDate);
console.log(new Date(birthDate).toDateString());
// | unknown | |
d16973 | val | There's one approach that involves one query, it could be close but not as performant (as it uses $unwind) and won't give you the desired result (only the filtered company):
var pipeline = [
{
"$group": {
"_id": "$company",
"total": { "$sum": 1 },
"employees": { "$push": "$employee" }
}
},
{
"$project": {
"_id": 0,
"company": "$_id",
"employee_count": "$total"
"randomemployee": "$employees"
}
},
{ "$unwind": "$randomemployee" },
{ "$match": { "company": arg } },
{ "$sample": { size: 1 } }
];
collection.aggregate(pipeline, function(err, result){
console.log(result);
});
However, for a solution that uses callbacks from multiple queries, this can be handled easily with use of async module.
To get all distinct companies, number of employees for each company, random employee for each company consider using the async.waterfall() function where the first task returns the aggregation results with all distinct companies and number of employees for each company.
The second task uses the results from taks 1 above to iterate over using async.forEachOf(). This allows you to perform an asynchronous task for each item, and when they're all done do something else. With each document from the array, run the aggregation operation that uses the $sample operator to get a random document with the specified company. With each result, create an extra field with the random employee and push that to an array with the final results that you can access at the end of each task.
Below shows this approach:
var async = require("async");
async.waterfall([
// Load full aggregation results (won't be called before task 1's "task callback" has been called)
function(callback) {
var pipeline = [
{
"$group": {
"_id": "$company",
"total": { "$sum": 1 }
}
},
{
"$project": {
"_id": 0,
"company": "$_id",
"employee_count": "total"
}
}
];
collection.aggregate(pipeline, function(err, results){
if (err) return callback(err);
callback(results);
});
},
// Load random employee for each of the aggregated results in task 1
function(results, callback) {
var docs = []
async.forEachOf(
results,
function(value, key, callback) {
var pipeline = [
{ "$match": { "company": value.company } },
{ "$sample": { size: 1 } }
];
collection.aggregate(pipeline, function (err, data) {
if (err) return callback(err);
value["randomemployee"] = data[0].employee;
docs.push(value);
callback();
});
},
function(err)
callback(null, docs);
}
);
},
], function(err, result) {
if (err) return next(err);
console.log(JSON.stringify(result, null, 4));
}
);
With the the async.series() function, this is useful if you need to execute a set of async functions in a certain order.
Consider the following approach if you wish to get the all the distinct companies and their employee count as one result and the other random employee as another:
var async = require("async"),
locals = {},
company = "One";
async.series([
// Load random company
function(callback) {
var pipeline = [
{ "$match": { "company": company } },
{ "$sample": { size: 1 } }
];
collection.aggregate(pipeline, function(err, result){
if (err) return callback(err);
locals.randomcompany = result[0];
callback();
});
},
// Load full aggregation results (won't be called before task 1's "task callback" has been called)
function(callback) {
var pipeline = [
{
"$group": {
"_id": "$company",
"total": { "$sum": 1 }
}
},
{
"$project": {
"_id": 0,
"company": "$_id",
"employee_count": "total"
}
}
];
collection.aggregate(pipeline, function(err, result){
if (err) return callback(err);
locals.aggregation = result;
callback();
});
}
], function(err) { //This function gets called after the two tasks have called their "task callbacks"
if (err) return next(err);
//Here locals will be populated with 'randomcompany' and 'aggregation'
console.log(JSON.stringify(locals, null, 4));
}
);
A: db.comp.aggregate([
{$group:{_id:'$company',emp:{$addToSet:'$employee'}}},
{$project:{emp:1,employee_count:{'$size':'$emp'},
randomvalue:{'$literal':Math.random()}}},
{$project:{emp:1,employee_count:1,
randomposition:{'$floor':
{'$multiply':['$randomvalue', '$employee_count']}}}},
{$project:{'Company':'$_id', _id:0, employee_count:1,
randomemployee:{'$arrayElemAt':['$emp','$randomposition']}}},
{$sort:{Company:1}} ])
Seems to work!
A couple of results:
{ "employee_count" : 4, "Company" : "One", "randomemployee" : "Mike" }
{ "employee_count" : 2, "Company" : "Two", "randomemployee" : "Johnny" }
{ "employee_count" : 4, "Company" : "One", "randomemployee" : "Mickey" }
{ "employee_count" : 2, "Company" : "Two", "randomemployee" : "David" } | unknown | |
d16974 | val | If by open you mean that you want to get a file() object back, then:
import os
filename = "Your_file.something"
username = os.environ["USER"]
f = open(os.path.join("/Users", username, "Desktop", filename), <mode>)
But there should be a $HOME variable present which will give you the real home folder even if it is not named as the user:
f = open(os.path.join(os.environ["HOME"], "Desktop/Your_file.something"), <mode>)
That is if shell alias for home folder won't work:
f = open("~/Desktop/Your_file.something", <mode>)
BTW, <mode> is of course the mode you wish to open your file in ("r", "w", "rb", "wb", "a", "ab", etc.) | unknown | |
d16975 | val | Oracle provides the following code snippet for programmatically retrieving an html page here.
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Instead of printing to console, you can save the contents to a file by using a FileWriter and BufferedWriter (example from this question):
FileWriter fstream = new FileWriter("fileName");
BufferedWriter fbw = new BufferedWriter(fstream);
while ((line = in.readLine()) != null) {
fbw.write(line + "\n");
}
A: Webpages are already HTML, if you want to save a webpage as HTML you can do this via the Firefox > Save Page As menu on Firefox. Or through File menu on other browsers.
If you need to download multiple pages in HTML from the same website or from a list of URLs there is a software that will make it easier for you: http://www.httrack.com/ | unknown | |
d16976 | val | Just you need to change variable m to get expected output
m = 77; // here what i have changed from $m to m
var xhr = new XMLHttpRequest();
xhr.open("POST", "try.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("m=" + escape(m));
A: You have two problems.
Variable names
At the top of your code you create a variable called $m but later you try to read m.
This will throw a ReferenceError which you would have spotted if you had looked at the Console in your browser's Developer Tools
You never look at the response
Once you fix that error, your code will make the request … but you don't do anything with the response.
You should add a load event listener for that.
function alert_response() {
alert(this.responseText);
}
xhr.addEventListener("load", alert_response);
Asides
*
*escape is deprecated because it doesn't work properly. Use encodeURIComponent instead.
*PHP sticks a text/html content-type on the response by default, by echoing out user input without modification or filtering, you are vulnerable to XSS attacks. Take steps to defend yourself. | unknown | |
d16977 | val | The ACTION attribute of an HTML form can be set with a relative URL:
/operation/validateLogin.php
or
/validateLogin.php
It's actually recommended to work with relative URLs for HTML elements:
Absolute vs relative URLs
However, when working with PHP an absolute URL is your best option:
http://localhost/demoAPP/operation/validateLogin.php
The use of absolute URLs will relieve your code of accidental URL concatenation.
I had trouble recently figuring out which type of URL to use for certain situations, but this is what I've realized...
PHP (local/server language) = Absolute Local/Server Address
require "C:/dev/www/DEMO/operation/login/validateLogin.php";
include "C:/dev/www/DEMO/operation/login/validateLogin.php";
header("Location: http://localhost/demoapp/login.php/?em=28"); (redirect to a web address)
This may seem really simple but remembering this will save you a lot of troubleshooting time.
If you are using .PHP files, alter the URL in any way, and are not using absolute URLs you will most certainly receive errors.
Additional: You'll notice that you can use a web address for HTML attributes and not run into any problems. However, with PHP requires and includes you can only use local addresses. There is a reason for this limitation and it's all because of one important PHP setting...
https://help.dreamhost.com/hc/en-us/articles/214205688-allow-url-include | unknown | |
d16978 | val | ok accourding to the thread that you found you could try this code.
in the contructor add this code
private bool _keyboardIsOn;
cto(){
// Initio
keyboardService.KeyboardIsShown += (sender, e){ _keyboardIsOn = true; }
keyboardService.KeyboardIsHidden += (sender, e){ _keyboardIsOn = false; }
}
No you could check if _keyboardIsOn and add your coditions. | unknown | |
d16979 | val | Given
import java.net.URI;
URI oldUri;
you can do that translation by creating a new uri from the old.
URI newUri = new URI(
oldUri.getScheme(),
"www.newsite.com",
translatePath(oldUri.getPath()),
oldUri.getQuery(),
oldUri.getFragment());
You haven't provided enough examples for me to know what translatePath should do, but given a string like "/a1.html" it returns "/b1.html". | unknown | |
d16980 | val | You can use .trim() as in if ($(this).html().trim().length > len) {
Demo
$(function() {
let len = 70
$('.demo').each(function() {
if ($(this).html().trim().length > len) {
var str = $(this).html().substring(0, len - 1) + "<a class='more'>...顯示更多</a>";
$(this).html(str);
}
});
});
.content {
display: flex;
justify-content: space-between;
border: 1px solid #222;
padding: 10px;
}
.demo {
overflow: hidden;
text-overflow: clip;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.photo {
width: 100px;
height: 100px;
border: 1px;
border-radius: 16px;
margin-left: 10px;
}
.more {
text-decoration: none;
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<div class="demo">
Lorem ipsum dolor sit amet consectetur Lore
</div>
<img class="photo" src="https://images.unsplash.com/photo-1622734659223-f995527e6c7b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=668&q=80" alt="">
</div> | unknown | |
d16981 | val | A common technique is to create a relationship between elements by using data attributes. In your case, you could put an attribute on each input/radio button that references the id of the element you want to affect.
<input type="radio" value="a" name="radgrp1" data-target="a1" /> Yes <br />
Then using some jQuery you could do this:
$('input[type="radio"]').change(function(){
var id = $(this).attr('data-target');
$('#' + id).css('background-color', 'rgb(255, 255, 255)');
});
A: You may try this (assumed there is no document.body.onclick event handler other than this)
var radios = document.querySelectorAll('input[name^=radgrp]');
document.body.onclick = function(e){
var evt = e || window.event, target = evt.target || evt.srcElement;
if(target.name) {
var prefix = target.name.substr(0, 6), suffix = target.name.substr(6);
if(prefix && prefix == 'radgrp') {
if(target.value == 'a' ) {
document.getElementById('a' + suffix).style.color = 'green';
}
else {
document.getElementById('a' + suffix).style.color = '';
}
}
}
};
Put this code just before the closing </body> tag between <script> tags like
<script type='text/javascript'> // code goes here </script>
Also, you may check this for registering events using different approaches.
Update :
querySelectorAll won't work in IE-6 so you may try this alternative solution for IE-6 to work. Also, if you use jQuery (put the code in <head> between <script>), you may use this example and in case of jQuery, you have to add jQuery script in your <head> section section first. | unknown | |
d16982 | val | Can you just do this?
First script:
....
cost=$(ssh $remore_node "sh cost_computation.sh <parameters>")
if [ $cost -eq 0 ]
then
....
else
....
fi
Second script (cost_computation):
....
computation of the cost
echo $cost | unknown | |
d16983 | val | The default style is indeterminate. Set it to false and everything should be OK:
indicator.isIndeterminate = false | unknown | |
d16984 | val | GoogleService failed to initialize, status: 10, Missing google app id value from from string resources with name google_app_id.
01-23 10:31:31.578 30044-30073/E/FA: Missing google_app_id. Firebase Analytics disabled. See
01-23 10:31:33.758 30044-30044/ E/AndroidRuntime: FATAL EXCEPTION: main
Process: , PID: 30044
java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process . Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@16.0.4:240)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
A: Remove dependencies block from top-level gradle file:
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
And update to classpath 'com.android.tools.build:gradle:3.3.0' and classpath 'com.google.gms:google-services:4.2.0'
In result your Gradle Files should be Like This For Android Studio 3.3 (stable channel)
build.gradle(project:yourProject)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.11'
repositories {
google()
jcenter()
// Add repository
maven {
url 'https://maven.fabric.io/public'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.2.0'
classpath 'io.fabric.tools:gradle:1.26.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
// Add repository
maven {
url 'https://maven.google.com/'
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle(Module:app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
android {
compileSdkVersion 28
defaultConfig {
applicationId "sanaebadi.info.teacherhandler"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
dataBinding {
enabled = true
}
}
dependencies {
def room_version = "2.1.0-alpha03"
def lifecycle_version = "2.0.0"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha02'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
//Firebase
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.8'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.google.firebase:firebase-storage:16.0.5'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.firebase:firebase-database:16.0.5'
}
gradle-wrapper.properties
#Tue Jan 15 07:24:23 EST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
A: update to classpath 'com.google.gms:google-services:4.2.0' in project level build.gradle. | unknown | |
d16985 | val | FB2 Supports reflow by design which is the reason for poor table support in many ebook readers as two column is contra the basic reflow principle.
Thus HTML can support tables but are not always "expected" nor supported well in many ebook readers.
Daisy epubtest "basic" did not include tables ! But they are tested in Accessibility: Non-visual Reading. Adobe fails the visual display by not adjusting the 4 cell contents to fit device, and fails on navigation.
MuPDF show the table as one column with cells reflowing to fit the page width, Calibre uses varying width columns but can also have issues.
If you need a fixed layout, then PDF was designed to maintain page layout, Thus the answer is probably use PDF with a page column and font size targeted to suit a pocket book such as A6, two column, no margins, 6pt.
If it is for your own use only, then ebook format targeted for your device, may well work if the columns are fixed to half screen width. | unknown | |
d16986 | val | I think, you won't need str() function with Criteria API, since you can first convert numerics into Strings with API functions like: Integer.toString() then set as Parameter like;
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("age", Integer.toString(age) ) )
.list(); | unknown | |
d16987 | val | I think the problem is that I was trying to use a range condition halfway through the index.
I added a key on:
(`MarkedForDeletion`,`DeviceId`,`Acknowledged`,`Ended`,`StartedAt`)
Then rewrote the query to this:
SELECT COUNT(`AlarmId`) AS `n`
FROM `Alarms`
WHERE
(
`Ended` = FALSE
AND `Acknowledged` = FALSE
AND `StartedAt` < FROM_UNIXTIME(1519101900)
AND `MarkedForDeletion` = FALSE
AND `DeviceId` = UNHEX('00030000000000000000000000000000')
) OR (
`EndedAt` > FROM_UNIXTIME(1519101900)
AND `Pinned` = TRUE
AND `StartedAt` < FROM_UNIXTIME(1519101900)
AND `MarkedForDeletion` = FALSE
AND `DeviceId` = UNHEX('00030000000000000000000000000000')
);
Now I get an index merge and the query is instant.
A: *
*OR is notoriously hard to optimize.
*MySQL almost never uses two indexes in a single query.
To avoid both of those, turn OR into UNION. Each SELECT can use its a different index. So, build an optimal INDEX for each.
Actually, since you are only doing COUNT, you may as well evaluate two separate counts and add them.
SELECT ( SELECT COUNT(*)
FROM `Alarms`
WHERE `EndedAt` IS NULL
AND `Acknowledged` = FALSE
AND `StartedAt` < FROM_UNIXTIME(1519101900)
AND `MarkedForDeletion` = FALSE
AND `DeviceId` = UNHEX('00030000000000000000000000000000' )
) +
( SELECT COUNT(*)
FROM `Alarms`
WHERE `EndedAt` > FROM_UNIXTIME(1519101900)
AND `Pinned` = TRUE
AND `StartedAt` < FROM_UNIXTIME(1519101900)
AND `MarkedForDeletion` = FALSE
AND `DeviceId` = UNHEX('00030000000000000000000000000000')
) AS `n`;
INDEX(DeviceId, Acknowledged, MarkedForDeletion, EndedAt, StartedAt) -- for first
INDEX(DeviceId, Pinned, MarkedForDeletion, EndedAt, StartedAt) -- for second
INDEX(DeviceId, Pinned, MarkedForDeletion, StartedAt, EndedAt) -- for second
Well, that won't work if there is overlap. So, let's go back to the UNION pattern:
SELECT COUNT(*) AS `n`
FROM
(
( SELECT AlarmId
FROM `Alarms`
WHERE `EndedAt` IS NULL
AND `Acknowledged` = FALSE
AND `StartedAt` < FROM_UNIXTIME(1519101900)
AND `MarkedForDeletion` = FALSE
AND `DeviceId` = UNHEX('00030000000000000000000000000000')
)
UNION DISTINCT
( SELECT AlarmId
FROM `Alarms`
WHERE `EndedAt` > FROM_UNIXTIME(1519101900)
AND `Pinned` = TRUE
AND `StartedAt` < FROM_UNIXTIME(1519101900)
AND `MarkedForDeletion` = FALSE
AND `DeviceId` = UNHEX('00030000000000000000000000000000')
)
);
Again, add those indexes.
The first few columns in each INDEX can be in any order, since they are tested with = (or IS NULL). The last one or two are "range" tests. Only the first range will be used for filtering, but I included the other column so that the index would be "covering".
My formulations may be better than "index merge". | unknown | |
d16988 | val | You can use whatever you want for multiplexing (select(), poll(), epoll_wait()). But you shouldn't read from stdin with fgets() because multiplexing knows nothing about if we've got complete line or no. So it may block in some cases. You should write custom line reading function, that will indicate that there is no complete line yet and return immediately. | unknown | |
d16989 | val | Windows 10 Installation
*
*
*
*Make sure you have both "remote registry" and "windows update service" installed.
*
*If you have previously attempted an install, you may have a couple of groups marked as AS_ in your user manager, make sure you delete these "AS_XXXX" -- delete these. I found that I would still get a 1603 after attempting again.
*
*Run your installation and you should get success. | unknown | |
d16990 | val | Solved my own question. Looks like I used the wrong function. This works:
<cfloop index="i" from="1" to="#ArrayLen(combinations)#">
<cfif Find(combinations[i][1],"#patterns#")>
<cfset combinations[i][2] = combinations[i][2] + 1>
<cfset found = 1>
</cfif>
</cfloop>
<cfif not found>
<cfset arrayAppend(combinations,["#patterns#",1]) >
</cfif>
A: Instead of using a 2-dimensional array, you could also use a structure instead, in which the keys are the patterns and the values the counts. That naturally avoids duplicates because the keys of a structure can only exist once.
The code for creating the structure would look something like this:
<cfset combinations = {}>
<cfloop query="#dbresults#">
<cfif not structKeyExists(combinations, dbresults.pattern)>
<cfset combinations[dbresults.pattern] = 1>
<cfelse>
<cfset combinations[dbresults.pattern]++>
</cfif>
</cfloop>
In the end you just have to loop over the structure to output the counts:
<cfloop collection="#combinations#" item="pattern">
<cfoutput><p>#pattern# - #combinations[pattern]#</p></cfoutput>
</cfloop> | unknown | |
d16991 | val | You could derive MyAttrAttribute from TheirAttrAttribute, and then Attribute.GetCustomAttribute method should work with both types:
public static Attribute GetCustomAttribute(
Assembly element,
Type attributeType
)
....
attributeType
Type: System.Type
The type, or a base type, of the custom attribute to search for. | unknown | |
d16992 | val | If your libcurl function invoke actually returns zero, then it was invoked fine and there's no problem with your DLLs or similar, but sounds like like you need to tweak your libcurl usage.
A: I've found the reason but I don't know a decent solution.
The bundled libcurl-4.dll only works for https requests if you also bundle the ssl folder that contains certificates. I feel like this is something where it should be using the OS' certs (Windows) but I don't know how to do that. | unknown | |
d16993 | val | Problem was fixed by downloading new Monodevelop: 2.8.6 beta
A: This behavior cannot be disabled, since there is no other way that MonoDevelop can use to communicate with xcode 4. This is because MonoDevelop creates an Xcode project on the fly (when you dbl clic any xib file within MD) and then MD launches xcode with the generated xcode project.
when you do all necessary changes in xcode and you switch back to MD the OnFocus event of MD (i don't really know if thats the event's name btw) process the changes you have done on the xcode project and modifies it in order to maintain both projects (xcode and MD) on sync
My suggestion is just make all necessary changes on xcode save them and then close it, then work on MD as usual and if you need to reopen xcode again work on it, Xcode won't bother you as long as you don't focus the MD window
I hope this helps.
Alex | unknown | |
d16994 | val | You don't change $_SESSION anywhere in your code. The foreach just exposes a copy of each element. You could change it by using a reference &:
foreach($_SESSION['cart_array'] as &$row) {
Also, notice that quotes are required for string indexes $_SESSION['cart_array']. If you had error reporting on you would see a Notice for Undefined constant: cart_array.
A: From php.net:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?> | unknown | |
d16995 | val | I should not answer after 3 beers. My bad, did not see you appending /n.
Consider using a plain Service and the FusedLocationProvider. | unknown | |
d16996 | val | Just use an order desc, and limit
select *
from yourTable
order by `date` desc
limit 3
Limit with 1 argument : argument = number of rows.
Limit with 2 argument : first = offset, second = number (offset starting at 0, not 1)
first row
limit 1 -- or limit 0, 1
second row
limit 1, 1
third row
limit 2, 1 | unknown | |
d16997 | val | As @fabian mentioned, Box is not suitable for customizing the texture. By default the image you set as diffuse map will be applied for each of its six faces, and, as you already discovered, this means that it will stretch the image to accommodate the different sides.
Using the FXyz library, we can easily try the Carbon-Kevlar pattern. But obviously we have to select a size for it. Like 100 x 30.
@Override
public void start(Stage primaryStage) {
Box box = new Box(100, 30, 50);
PhongMaterial material = new PhongMaterial();
Patterns pattern = new Patterns(100, 30);
material.setDiffuseMap(pattern.createPattern(Patterns.CarbonPatterns.CARBON_KEVLAR, false));
box.setMaterial(material);
Scene scene = new Scene(new Group(box), 500, 400, true, SceneAntialiasing.BALANCED);
primaryStage.setScene(scene);
primaryStage.show();
}
While the texture fits perfectly fine the front face with dimensions 100x30, this image is distorted to fit in the same way the other faces 50x50 and 100x50.
Solution 1
We can try to generate our own Box, so we can decide how to apply the diffuse map.
Creating a TriangleMesh for a cuboid is easy in terms of vertices and faces or normals.
The tricky part is setting the texture coordinates. In the following snippet I set them based on one of the different possible 2D net images of the 3D cuboid:
public MeshView createCuboid(float w, float h, float d) {
float hw = w / 2f;
float hh = h / 2f;
float hd = d / 2f;
float points[] = {
hw, hh, hd,
hw, hh, -hd,
hw, -hh, hd,
hw, -hh, -hd,
-hw, hh, hd,
-hw, hh, -hd,
-hw, -hh, hd,
-hw, -hh, -hd};
float L = 2 * w + 2 * d;
float H = h + 2 * d;
float tex[] = {
d / L, 0f,
(d + w) / L, 0f,
0f, d / H,
d / L, d / H,
(d + w) / L, d / H,
(2 * d + w) / L, d / H,
1f, d / H,
0f, (d + h) / H,
d / L, (d + h) / H,
(d + w) / L, (d + h) / H,
(2 *d + w) / L, (d + h) / H,
1f, (d + h) / H,
d / L, 1f,
(d + w) / L, 1f};
float normals[] = {
1f, 0f, 0f,
-1f, 0f, 0f,
0f, 1f, 0f,
0f, -1f, 0f,
0f, 0f, 1f,
0f, 0f, -1f,
};
int faces[] = {
0, 0, 10, 2, 0, 5, 1, 0, 9,
2, 0, 5, 3, 0, 4, 1, 0, 9,
4, 1, 7, 5, 1, 8, 6, 1, 2,
6, 1, 2, 5, 1, 8, 7, 1, 3,
0, 2, 13, 1, 2, 9, 4, 2, 12,
4, 2, 12, 1, 2, 9, 5, 2, 8,
2, 3, 1, 6, 3, 0, 3, 3, 4,
3, 3, 4, 6, 3, 0, 7, 3, 3,
0, 4, 10, 4, 4, 11, 2, 4, 5,
2, 4, 5, 4, 4, 11, 6, 4, 6,
1, 5, 9, 3, 5, 4, 5, 5, 8,
5, 5, 8, 3, 5, 4, 7, 5, 3};
TriangleMesh mesh = new TriangleMesh();
mesh.setVertexFormat(VertexFormat.POINT_NORMAL_TEXCOORD);
mesh.getPoints().addAll(points);
mesh.getTexCoords().addAll(tex);
mesh.getNormals().addAll(normals);
mesh.getFaces().addAll(faces);
return new MeshView(mesh);
}
Now we can generate the image, but using the net dimensions:
@Override
public void start(Stage primaryStage) {
MeshView box = createCuboid(100, 30, 50);
PhongMaterial material = new PhongMaterial();
Patterns pattern = new Patterns(300, 160);
material.setDiffuseMap(pattern.createPattern(Patterns.CarbonPatterns.CARBON_KEVLAR, false));
box.setMaterial(material);
box.getTransforms().addAll(rotateX, rotateY);
Scene scene = new Scene(new Group(box), 500, 400, true, SceneAntialiasing.BALANCED);
primaryStage.setScene(scene);
primaryStage.show();
}
Note that the image is not distorted anymore.
You can play with its size to get a more fine or dense pattern (with a bigger image pattern).
Note that you can find this Cuboid primitive in the FXyz library, among many other 3D primitives.
Also you can find different texture modes (density maps, images, patterns...) | unknown | |
d16998 | val | You could add a media query like this:
@media (max-width: 768px) {
.card_new {
width: 100%;
}
}
See http://jsfiddle.net/j8GyV/25/
A: So I knew what you meant so I decided to add styling to td to make it wrap.
td {
display: -webkit-flex; /* Safari */
-webkit-flex-wrap: wrap; /* Safari 6.1+ */
display: flex;
flex-wrap: wrap;
min-width: 10%;
}
And it worked!
http://jsfiddle.net/j8GyV/30/ | unknown | |
d16999 | val | I've had good success using FFmpeg wrappers in C# in times gone by. Here is one that I've used: https://github.com/Ruslan-B/FFmpeg.AutoGen . It takes some work to master the FFmpeg compilation process, which is typically done via cross-compile from Linux, and is typically a necessary part of this. It also takes some work to understand the FFmpeg API. There are a lot of options and steps to extracting frames, and some difficulties in making it performant, especially the display of the extract frames. This project won't be as easy as you were hoping; however, you will have the full FFmpeg power at your fingertips when done. | unknown | |
d17000 | val | Suppose there is a temperature sensor, when that gets disconnected from machine, class B draws a content blocker image on the whole area of QWidget that it owns, I can monitor sensor connect /disconnect and suppose C's fun. OnDisconnect() gets called, I will call B::OnDisconnect(), B will draw blocker image on its own QWidget, not on the one which is owned by C.
This has everything to do with C++'s rather inflexible method implementation inheritance when compared e.g. to the Common LISP Object System.
Since B's obscuration is always meant to be on top of B's contents, what you effectively need is for B to provide an overlay that draws on top of its contents, even if paintEvent is overriden in derived classes.
See this answer for a simple example, or another answer for an overlay with blur graphical effect.
This is fairly easy to accomplish by having B add an optional overlay widget to itself.
Example:
class OverlayWidget; // from https://stackoverflow.com/a/19367454/1329652
class ObscureOverlay : public OverlayWidget
{
public:
ObscureOverlay(QWidget * parent = {}) : OverlayWidget{parent} {}
protected:
void paintEvent(QPaintEvent *) override {
QPainter p{this};
p.fillRect(rect(), {Qt::black});
}
};
class A : public QWidget {
...
protected:
void paintEvent(QPaintEvent *) override { ... }
};
class B : public A {
...
ObscureOverlay m_obscure{this};
public:
B() {
m_obscure.hide();
}
Q_SLOT void OnDisconnect() {
m_obscure.show();
...
}
};
class C : public B {
...
protected:
void paintEvent(QPaintEvent * event) override {
B::paintEvent(event);
...
}
};
If you don't have the source code to B, you can add the overlay to C, replicating original B's functionality when obscured. All of Qt's slots are effectively virtual, so if you pass a C to someone expecting B and connecting to its OnDisconnect slot, it will be C's slot that will get invoked.
class C : public B {
Q_OBJECT
...
ObscureOverlay m_obscure{this};
public:
explicit C(QWidget * parent = {}) : B{parent} {
m_obscure.hide();
}
Q_SLOT void OnDisconnect() { // slots are effectively virtual
m_obscure.show();
B::OnDisconnect();
}
protected:
void paintEvent(QPaintEvent * event) override {
B::paintEvent(event);
QPainter p{this};
...
}
}; | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.