This question comes up as one of the top 3 hits for the Google search for "how to suppress -Wunused-result in c++", so I'm adding this answer here since I figured it out and want to help the next person.
-Wunused
(or one of its sub-errors) or -Wunused -Werror
only, the solution is to cast to void
:For -Wunused
or one of its sub-errors only1, you can just cast it to void
to disable the warning. This should work for any compiler and any IDE for both C and C++.
1Note 1: see gcc documentation here, for example, for a list of these warnings: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html, then search for the phrase "All the above -Wunused options combined" and look there for the main -Wunused
warning and above it for its sub-warnings. The sub-warnings that -Wunused
contains include:
-Wunused-but-set-parameter
-Wunused-but-set-variable
-Wunused-function
-Wunused-label
-Wunused-local-typedefs
-Wunused-parameter
-Wno-unused-result
-Wunused-variable
-Wunused-const-variable
-Wunused-const-variable=n
-Wunused-value
-Wunused
= contains all of the above -Wunused
options combinedExample of casting to void
to suppress this warning:
// some "unused" variable you want to keep around
int some_var = 7;
// turn off `-Wunused` compiler warning for this one variable
// by casting it to void
(void)some_var; // <===== SOLUTION! ======
For C++, this also works on functions which return a variable marked with [[nodiscard]]
:
C++ attribute: nodiscard (since C++17)
If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.
(Source: https://en.cppreference.com/w/cpp/language/attributes/nodiscard)
So, the solution is to cast the function call to void
, as this is actually casting the value returned by the function (which is marked with the [[nodiscard]]
attribute) to void
.
Example:
// Some class or struct marked with the C++ `[[nodiscard]]` attribute
class [[nodiscard]] MyNodiscardClass
{
public:
// fill in class details here
private:
// fill in class details here
};
// Some function which returns a variable previously marked with
// with the C++ `[[nodiscard]]` attribute
MyNodiscardClass MyFunc()
{
MyNodiscardClass myNodiscardClass;
return myNodiscardClass;
}
int main(int argc, char *argv[])
{
// THE COMPILER WILL COMPLAIN ABOUT THIS FUNCTION CALL
// IF YOU HAVE `-Wunused` turned on, since you are
// discarding a "nodiscard" return type by calling this
// function and not using its returned value!
MyFunc();
// This is ok, however, as casing the returned value to
// `void` suppresses this `-Wunused` warning!
(void)MyFunc(); // <===== SOLUTION! ======
}
Lastly, you can also use the C++17 [[maybe_unused]]
attribute: https://en.cppreference.com/w/cpp/language/attributes/maybe_unused.
The answer from @laughing_man is quite accurate. But still, I wanted to give a recommendation which I learned from Kafka expert Stephane Maarek.
Kafka isn’t meant to handle large messages.
Your API should use cloud storage (Ex AWS S3), and just push to Kafka or any message broker a reference of S3. You must find somewhere to persist your data, maybe it’s a network drive, maybe it’s whatever, but it shouldn't be message broker.
Now, if you don’t want to go with the above solution
The message max size is 1MB (the setting in your brokers is called message.max.bytes
) Apache Kafka. If you really needed it badly, you could increase that size and make sure to increase the network buffers for your producers and consumers.
And if you really care about splitting your message, make sure each message split has the exact same key so that it gets pushed to the same partition, and your message content should report a “part id” so that your consumer can fully reconstruct the message.
You can also explore compression, if your message is text-based (gzip, snappy, lz4 compression) which may reduce the data size, but not magically.
Again, you have to use an external system to store that data and just push an external reference to Kafka. That is a very common architecture and one you should go with and widely accepted.
Keep that in mind Kafka works best only if the messages are huge in amount but not in size.
Source: https://www.quora.com/How-do-I-send-Large-messages-80-MB-in-Kafka
Assuming you're running on a Windows machine...
F12
keyScripts
, or Sources
, tab in the developer toolsThen during execution debugging you can do a handful of stepping motions...
F8
Continue: Will continue until the next breakpointF10
Step over: Steps over next function call (won't enter the
library)F11
Step into: Steps into the next function call (will
enter the library)Shift + F11
Step out: Steps out of the current
functionUpdate
After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.
It seems the problem can arise from more than one reasons. Following two steps worked when I was having same error.
Array.prototype.groupBy = function (groupingKeyFn) {_x000D_
if (typeof groupingKeyFn !== 'function') {_x000D_
throw new Error("groupBy take a function as only parameter");_x000D_
}_x000D_
return this.reduce((result, item) => {_x000D_
let key = groupingKeyFn(item);_x000D_
if (!result[key])_x000D_
result[key] = [];_x000D_
result[key].push(item);_x000D_
return result;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
var a = [_x000D_
{type: "video", name: "a"},_x000D_
{type: "image", name: "b"},_x000D_
{type: "video", name: "c"},_x000D_
{type: "blog", name: "d"},_x000D_
{type: "video", name: "e"},_x000D_
]_x000D_
console.log(a.groupBy((item) => item.type));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
with Kotlin I execute this code:
requireContext().startActivity<YourTargetActivity>()
Your values
object is obviously an Object[]
containing a String[]
containing the values.
String[] stringValues = (String[])values[0];
I think the answer above solves your problem but I thought I'd share a method that gives you the minimum and all the indices the minimum appears in.
minval = min(mylist)
ind = [i for i, v in enumerate(mylist) if v == minval]
This passes the list twice but is still quite fast. It is however slightly slower than finding the index of the first encounter of the minimum. So if you need just one of the minima, use Matt Anderson's solution, if you need them all, use this.
JavaScript has Function-Level variable scope which means you will have to declare your variable outside $(document).ready()
function.
Or alternatively to make your variable to have global scope, simply dont use var
keyword before it like shown below. However generally this is considered bad practice because it pollutes the global scope but it is up to you to decide.
$(document).ready(function() {
intro = null; // it is in global scope now
To learn more about it, check out:
The best method hiding email addresses is only good until bot programmer discover this "encoding" and implement a decryption algorithm.
The JavaScript option won't work long, because there are a lot of crawler interpreting JavaScript.
There's no answer, imho.
\n
in c3 working correctlyusing System;
namespace testing2
public class Test {
public static void Main(string[] args) {
Console.WriteLine("Enter your name");
String s = Console.ReadLine();
Console.WriteLine("Your name is " + s + "\n" + "Thank You");
}
}
The clearer option is to use tonumber.
As of 5.3.2, this function will automatically detect (signed) integers, float (if a point is present) and hexadecimal (both integers and floats, if the string starts by "0x" or "0X").
The following snippets are shorter but not equivalent :
a + 0 -- forces the conversion into float, due to how + works.
a | 0 -- (| is the bitwise or) forces the conversion into integer.
-- However, unlike `math.tointeger`, it errors if it fails.
One graph can replace many words:
Enjoy! :-)
# I have updated the correct image...
Kotlin
do this instead:For Example,
// * The Method I Mentioned Above
private fun parseTheValue(@NonNull valueYouWantToParse: String)
{
val intent = Intent(this, AnotherActivity::class.java)
intent.putExtra("value", valueYouWantToParse)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent)
this.finish()
}
Then just call parseTheValue("the String that you want to parse")
e.g,
val theValue: String
parseTheValue(theValue)
then in the other activity,
val value: Bundle = intent.extras!!
// * enter the `name` from the `@param`
val str: String = value.getString("value").toString()
// * For testing
println(str)
Hope This Help, Happy Coding!
~ Kotlin Code Added By John Melody~
If you are just trying to figure out what a malware does, it might be much easier to run it under something like the free tool Process Monitor which will report whenever it tries to access the filesystem, registry, ports, etc...
Also, using a virtual machine like the free VMWare server is very helpful for this kind of work. You can make a "clean" image, and then just go back to that every time you run the malware.
Here is another way to view your app's memory usage:
adb shell dumpsys meminfo <com.package.name> -d
Sample output:
Applications Memory Usage (kB):
Uptime: 2896577 Realtime: 2896577
** MEMINFO in pid 2094 [com.package.name] **
Pss Private Private Swapped Heap Heap Heap
Total Dirty Clean Dirty Size Alloc Free
------ ------ ------ ------ ------ ------ ------
Native Heap 3472 3444 0 0 5348 4605 102
Dalvik Heap 2349 2188 0 0 4640 4486 154
Dalvik Other 1560 1392 0 0
Stack 772 772 0 0
Other dev 4 0 4 0
.so mmap 2749 1040 1220 0
.jar mmap 1 0 0 0
.apk mmap 218 0 32 0
.ttf mmap 38 0 4 0
.dex mmap 3161 80 2564 0
Other mmap 9 4 0 0
Unknown 76 76 0 0
TOTAL 14409 8996 3824 0 9988 9091 256
Objects
Views: 30 ViewRootImpl: 2
AppContexts: 4 Activities: 2
Assets: 2 AssetManagers: 2
Local Binders: 17 Proxy Binders: 21
Death Recipients: 7
OpenSSL Sockets: 0
SQL
MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
For overall memory usage:
adb shell dumpsys meminfo
https://developer.android.com/studio/command-line/dumpsys#meminfo
Try the 'requests' module, it's much simpler.
#pip install requests for installation
import requests
url = 'https://www.google.com/'
r = requests.get(url)
r.text
more info here > http://docs.python-requests.org/en/master/
You can also use events to trigger the Popdown.
Here's a fiddle based on satchmorun's solution. It dispenses with the PopdownAPI, and the top-level controller instead $broadcast
s 'success' and 'error' events down the scope chain:
$scope.success = function(msg) { $scope.$broadcast('success', msg); };
$scope.error = function(msg) { $scope.$broadcast('error', msg); };
The Popdown module then registers handler functions for these events, e.g:
$scope.$on('success', function(event, msg) {
$scope.status = 'success';
$scope.message = msg;
$scope.toggleDisplay();
});
This works, at least, and seems to me to be a nicely decoupled solution. I'll let others chime in if this is considered poor practice for some reason.
I had the same problem. I tried everything listed on this page. When I re-installed Composer it worked like before. I had a PHP version mismatch that was corrected with a new install establishing the dependencies with the PHP path installed in my system environment variables.
I DO NOT RECOMMEND the composer config -g -- disable-tls true
approach.
By the way the way to reverse this is composer config -g -- disable-tls false
.
To check if a path is an existing file:
Return
True
if path is an existing regular file. This follows symbolic links, so bothislink()
andisfile()
can be true for the same path.
You should learn objective c and program native apps. Do not rely on these things you think will make life easier. Apple has made sure the easiest way is using their native tools and language. For your 100 lines of javascript I can do the same in 3 lines of code or no code at all depending on the element. Watch some tutorials - if you understand javascript then objective c is not hard. Workarounds are miserable and apple can pull the plug on you anytime they want.
The map
function can be very useful here.
Using map
we can apply any function to each element of an iterable.
Python 3.x
>>> def my_mul(x,y):
... return x*y
...
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>>
>>> list(map(my_mul,a,b))
[2, 6, 12, 20]
>>>
Of course:
map(f, iterable)
is equivalent to
[f(x) for x in iterable]
So we can get our solution via:
>>> [my_mul(x,y) for x, y in zip(a,b)]
[2, 6, 12, 20]
>>>
In Python 2.x map()
means: apply a function to each element of an iterable and construct a new list.
In Python 3.x, map
construct iterators instead of lists.
Instead of my_mul
we could use mul
operator
Python 2.7
>>>from operator import mul # import mul operator
>>>a = [1,2,3,4]
>>>b = [2,3,4,5]
>>>map(mul,a,b)
[2, 6, 12, 20]
>>>
Python 3.5+
>>> from operator import mul
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>> [*map(mul,a,b)]
[2, 6, 12, 20]
>>>
Please note that since map()
constructs an iterator we use *
iterable unpacking operator to get a list.
The unpacking approach is a bit faster then the list
constructor:
>>> list(map(mul,a,b))
[2, 6, 12, 20]
>>>
You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:
http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
The other advantage of using curl is that you also can keep the HTTP way of sending parameters to your script if you need to, by using $_GET
, $_POST
etc like this:
*/5 * * * * curl --request GET 'http://exemple.com/path/check.php?param1=1¶m2=2'
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)Your code is very vague and not understandable, but I can provide you with an alternative.
First of all, if you want temp
to go through the whole string, you can do something like this:
char *temp;
for (temp = your_string; *temp; ++temp)
/* do something with *temp */
The term *temp
as the for
condition simply checks whether you have reached the end of the string or not. If you have, *temp
will be '\0'
(NUL
) and the for
ends.
Now, inside the for, you want to find the bits that compose *temp
. Let's say we print the bits:
for (as above)
{
int bit_index;
for (bit_index = 7; bit_index >= 0; --bit_index)
{
int bit = *temp >> bit_index & 1;
printf("%d", bit);
}
printf("\n");
}
To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7
to bit_index = sizeof(*temp)*8-1
In my case it was because I had opened SmartGit's Log in the respective Git project and Total Commander in the respective project directory. When I closed both I was able to rebase without any problem.
The more I think about it, the more I suspect Total Commander, i.e. Windows having a lock on opened directory the git rebase was trying to something with.
Friendly advice: When you try to fix something, always do one change at a time. ;)
Wrap the name in a span, give it a class and assign a style to that class:
<td><span class="names">Name text you want bold</span> rest of your text</td>
style:
.names { font-weight: bold; }
Posting as a new answer since my edit of @King-Wizard's answer was rejected.
Make your class a delegate of the UITextField and override touchesBegan.
Swift 4
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
//Called when 'return' key is pressed. Return false to keep the keyboard visible.
func textFieldShouldReturn(textField: UITextField) -> Bool {
return true
}
// Called when the user clicks on the view (outside of UITextField).
override func touchesBegan(touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
As you're dealing with an array of strings, you can simply use array_filter()
, which conveniently handles all this for you:
print_r(array_filter($linksArray));
Keep in mind that if no callback is supplied, all entries of array equal to FALSE
(see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0'
, you will need a custom callback:
// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));
// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));
// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));
String hexToAscii(String s) {
int n = s.length();
StringBuilder sb = new StringBuilder(n / 2);
for (int i = 0; i < n; i += 2) {
char a = s.charAt(i);
char b = s.charAt(i + 1);
sb.append((char) ((hexToInt(a) << 4) | hexToInt(b)));
}
return sb.toString();
}
private static int hexToInt(char ch) {
if ('a' <= ch && ch <= 'f') { return ch - 'a' + 10; }
if ('A' <= ch && ch <= 'F') { return ch - 'A' + 10; }
if ('0' <= ch && ch <= '9') { return ch - '0'; }
throw new IllegalArgumentException(String.valueOf(ch));
}
You need to write a selector which selects the correct <input>
first. Ideally you use the element's ID $('#element_id')
, failing that the ID of it's container $('#container_id input')
, or the element's class $('input.class_name')
.
Your element has none of these and no context, so it's hard to tell you how to select it.
Once you have figured out the proper selector, you'd use the attr method to access the element's attributes. To get the name, you'd use $(selector).attr('name')
which would return (in your example) 'xxxxx'
.
I was just fighting with this exact scenario, but with quite a few more views that needed to resize and move down as necessary. It was driving me nuts, but I finally figured it out.
Here's the key: Interface Builder likes to throw in extra constraints as you add and move views and you may not notice. In my case, I had a view half way down that had an extra constraint that specified the size between it and its superview, basically pinning it to that point. That meant that nothing above it could resize larger because it would go against that constraint.
An easy way to tell if this is the case is by trying to resize the label manually. Does IB let you grow it? If it does, do the labels below move as you expect? Make sure you have both of these checked before you resize to see how your constraints will move your views:
If the view is stuck, follow the views that are below it and make sure one of them doesn't have a top space to superview constraint. Then just make sure your number of lines option for the label is set to 0 and it should take care of the rest.
Use a Razor to dynamically change your URL by calling your action like this:
$.ajax({
type: "POST",
url: '@Url.Action("ActionName", "ControllerName")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
dataType: "json",
success: function(recData) { alert('Success'); },
error: function() { alert('A error'); }
});
If you are using Query builder then you may use a blow
DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()
If you are working with Eloquent then you can use as below
$sendUsersList = Newsletter Subscription:: select ('*')
->whereIn('id', $send_users_list)
->get();
StringUtils.isBlank
also returns true
for just whitespace:
isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
On the left we have the app organized by type. Not too bad for smaller apps, but even here you can start to see it gets more difficult to find what you are looking for. When I want to find a specific view and its controller, they are in different folders. It can be good to start here if you are not sure how else to organize the code as it is quite easy to shift to the technique on the right: structure by feature.
On the right the project is organized by feature. All of the layout views and controllers go in the layout folder, the admin content goes in the admin folder, and the services that are used by all of the areas go in the services folder. The idea here is that when you are looking for the code that makes a feature work, it is located in one place. Services are a bit different as they “service” many features. I like this once my app starts to take shape as it becomes a lot easier to manage for me.
A well written blog post: http://www.johnpapa.net/angular-growth-structure/
Example App: https://github.com/angular-app/angular-app
I hit this error because I was specifying a label attribute in my geom (geom_text
) but was specifying a color in the top level aes:
df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)
# don't do this!
ggplot(df, aes(x=V6, y=V1, color=V1)) +
geom_text(angle=45, label=df$V1, size=2)
To fix this, I just moved the label attribute out of the geom and into the top level aes:
df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)
# do this!
ggplot(df, aes(x=V6, y=V1, color=V1, label=V1)) +
geom_text(angle=45, size=2)
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
You can use CTRL + SHIFT + A and then simply type theme
to go directly to the theme settings. Same goes for pretty much any setting, refactoring or action you're looking for.
It's a pity to use .NET and not use collections and lambda to save your time and code lines This is an example of how this works: Transform yourDataTable to Enumerable, filter it if you want , according a "FILTER_ROWS_FIELD" column, and if you want, group your data by a "A_GROUP_BY_FIELD". Then get the count, the sum, or whatever you wish. If you want a count and a sum without grouby don't group the data
var groupedData = from b in yourDataTable.AsEnumerable().Where(r=>r.Field<int>("FILTER_ROWS_FIELD").Equals(9999))
group b by b.Field<string>("A_GROUP_BY_FIELD") into g
select new
{
tag = g.Key,
count = g.Count(),
sum = g.Sum(c => c.Field<double>("rvMoney"))
};
If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.
To read a file line by line (also for extreme big files) can be done by the following functions:
DDFileReader * reader = [[DDFileReader alloc] initWithFilePath:pathToMyFile];
NSString * line = nil;
while ((line = [reader readLine])) {
NSLog(@"read line: %@", line);
}
[reader release];
Or:
DDFileReader * reader = [[DDFileReader alloc] initWithFilePath:pathToMyFile];
[reader enumerateLinesUsingBlock:^(NSString * line, BOOL * stop) {
NSLog(@"read line: %@", line);
}];
[reader release];
The class DDFileReader that enables this is the following:
Interface File (.h):
@interface DDFileReader : NSObject {
NSString * filePath;
NSFileHandle * fileHandle;
unsigned long long currentOffset;
unsigned long long totalFileLength;
NSString * lineDelimiter;
NSUInteger chunkSize;
}
@property (nonatomic, copy) NSString * lineDelimiter;
@property (nonatomic) NSUInteger chunkSize;
- (id) initWithFilePath:(NSString *)aPath;
- (NSString *) readLine;
- (NSString *) readTrimmedLine;
#if NS_BLOCKS_AVAILABLE
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL *))block;
#endif
@end
Implementation (.m)
#import "DDFileReader.h"
@interface NSData (DDAdditions)
- (NSRange) rangeOfData_dd:(NSData *)dataToFind;
@end
@implementation NSData (DDAdditions)
- (NSRange) rangeOfData_dd:(NSData *)dataToFind {
const void * bytes = [self bytes];
NSUInteger length = [self length];
const void * searchBytes = [dataToFind bytes];
NSUInteger searchLength = [dataToFind length];
NSUInteger searchIndex = 0;
NSRange foundRange = {NSNotFound, searchLength};
for (NSUInteger index = 0; index < length; index++) {
if (((char *)bytes)[index] == ((char *)searchBytes)[searchIndex]) {
//the current character matches
if (foundRange.location == NSNotFound) {
foundRange.location = index;
}
searchIndex++;
if (searchIndex >= searchLength) { return foundRange; }
} else {
searchIndex = 0;
foundRange.location = NSNotFound;
}
}
return foundRange;
}
@end
@implementation DDFileReader
@synthesize lineDelimiter, chunkSize;
- (id) initWithFilePath:(NSString *)aPath {
if (self = [super init]) {
fileHandle = [NSFileHandle fileHandleForReadingAtPath:aPath];
if (fileHandle == nil) {
[self release]; return nil;
}
lineDelimiter = [[NSString alloc] initWithString:@"\n"];
[fileHandle retain];
filePath = [aPath retain];
currentOffset = 0ULL;
chunkSize = 10;
[fileHandle seekToEndOfFile];
totalFileLength = [fileHandle offsetInFile];
//we don't need to seek back, since readLine will do that.
}
return self;
}
- (void) dealloc {
[fileHandle closeFile];
[fileHandle release], fileHandle = nil;
[filePath release], filePath = nil;
[lineDelimiter release], lineDelimiter = nil;
currentOffset = 0ULL;
[super dealloc];
}
- (NSString *) readLine {
if (currentOffset >= totalFileLength) { return nil; }
NSData * newLineData = [lineDelimiter dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle seekToFileOffset:currentOffset];
NSMutableData * currentData = [[NSMutableData alloc] init];
BOOL shouldReadMore = YES;
NSAutoreleasePool * readPool = [[NSAutoreleasePool alloc] init];
while (shouldReadMore) {
if (currentOffset >= totalFileLength) { break; }
NSData * chunk = [fileHandle readDataOfLength:chunkSize];
NSRange newLineRange = [chunk rangeOfData_dd:newLineData];
if (newLineRange.location != NSNotFound) {
//include the length so we can include the delimiter in the string
chunk = [chunk subdataWithRange:NSMakeRange(0, newLineRange.location+[newLineData length])];
shouldReadMore = NO;
}
[currentData appendData:chunk];
currentOffset += [chunk length];
}
[readPool release];
NSString * line = [[NSString alloc] initWithData:currentData encoding:NSUTF8StringEncoding];
[currentData release];
return [line autorelease];
}
- (NSString *) readTrimmedLine {
return [[self readLine] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#if NS_BLOCKS_AVAILABLE
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL*))block {
NSString * line = nil;
BOOL stop = NO;
while (stop == NO && (line = [self readLine])) {
block(line, &stop);
}
}
#endif
@end
The class was done by Dave DeLong
This solved my issues
sudo apt-get install php7.1-xml
or
sudo apt-get install php7.2-xml
If you want to by pass the time and resources it takes to count(*) your 3million row tables. Try this per SQL SERVER Central by Kendal Van Dyke.
Row Counts Using sysindexes If you're using SQL 2000 you'll need to use sysindexes like so:
-- Shows all user tables and row counts for the current database
-- Remove OBJECTPROPERTY function call to include system objects
SELECT o.NAME,
i.rowcnt
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
WHERE i.indid < 2 AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY o.NAME
If you're using SQL 2005 or 2008 querying sysindexes will still work but Microsoft advises that sysindexes may be removed in a future version of SQL Server so as a good practice you should use the DMVs instead, like so:
-- Shows all user tables and row counts for the current database
-- Remove is_ms_shipped = 0 check to include system objects
-- i.index_id < 2 indicates clustered index (1) or hash table (0)
SELECT o.name,
ddps.row_count
FROM sys.indexes AS i
INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_ID
INNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_ID
AND i.index_id = ddps.index_id
WHERE i.index_id < 2 AND o.is_ms_shipped = 0 ORDER BY o.NAME
Though this is an old question, I thought I'd post my answer anyway, if that helps someone in future
JArray array = JArray.Parse(jsonString);
foreach (JObject obj in array.Children<JObject>())
{
foreach (JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
//Do something with name and value
//System.Windows.MessageBox.Show("name is "+name+" and value is "+value);
}
}
This solution uses Newtonsoft library, don't forget to include using Newtonsoft.Json.Linq;
We had the same problem using Django+nginx+gunicorn. From Gunicorn documentation we have configured the graceful-timeout that made almost no difference.
After some testings, we found the solution, the parameter to configure is: timeout (And not graceful timeout). It works like a clock..
So, Do:
1) open the gunicorn configuration file
2) set the TIMEOUT to what ever you need - the value is in seconds
NUM_WORKERS=3
TIMEOUT=120
exec gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--timeout $TIMEOUT \
--log-level=debug \
--bind=127.0.0.1:9000 \
--pid=$PIDFILE
One reason: the literal 0
has a bad tendency to acquire the type int
, e.g. in perfect argument forwarding or more in general as argument with templated type.
Another reason: readability and clarity of code.
I stumbled upon this because of SonarQube's rule "squid:S2699": "Add at least one assertion to this test case."
I had a simple test whose only goal was to go through without throwing exceptions.
Consider this simple code:
public class Printer {
public static void printLine(final String line) {
System.out.println(line);
}
}
What kind of assertion can be added to test this method? Sure, you can make a try-catch around it, but that is only code bloat.
The solution comes from JUnit itself.
In case no exception is thrown and you want to explicitly illustrate this behaviour, simply add expected
as in the following example:
@Test(expected = Test.None.class /* no exception expected */)
public void test_printLine() {
Printer.printLine("line");
}
Test.None.class
is the default for the expected value.
MongoVue is the best I found till now, it has great features like database or collection copy and text mode viewing for records which is extremely useful
var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
Example: http://jsfiddle.net/e27r8/
This uses the closest()
[docs] method to get the first ancestor that has a nested h3 span b
, then does a .find()
.
Of course you could have multiple matches.
Otherwise, you're looking at doing a more direct traversal.
var link = $("#me").closest("h3 + div").prev().find('span b');
edit: This one works with your updated HTML.
Example: http://jsfiddle.net/e27r8/2/
EDIT: Updated to deal with updated question.
var link = $("#me").closest("h3 + *").prev().find('span b');
This makes the targeted element for .closest()
generic, so that even if there is no parent, it will still work.
Example: http://jsfiddle.net/e27r8/4/
In general closing and re-open VS 2015 fixed most problems I have ran across. Once I did need to run a repair on one of my computers.
However I was about to do this Closing and re-opening VS2015 resolved the issue for me
I figured that I would instead right click on the project and Unload Project then right click and Reload project THEN Manage Nuget worked!
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
It seems they offer a js
option for the format parameter, which will return JSONP. You can retrieve JSONP like so:
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
console.log(data);
});
I wanted to set the width of the first column of the table, and I found this worked (in FF7) - the first column is 50px wide:
#MyTable>thead>tr>th:first-child { width:50px;}
where my markup was
<table id="MyTable">
<thead>
<tr>
<th scope="col">Col1</th>
<th scope="col">Col2</th>
</tr>
</thead>
<tbody>
...
</tbody>
</table>
The content of the table/tables in PostgreSQL database can be deleted in several ways.
Deleting table content using sql:
Deleting content of one table:
TRUNCATE table_name;
DELETE FROM table_name;
Deleting content of all named tables:
TRUNCATE table_a, table_b, …, table_z;
Deleting content of named tables and tables that reference to them (I will explain it in more details later in this answer):
TRUNCATE table_a, table_b CASCADE;
Deleting table content using pgAdmin:
Deleting content of one table:
Right click on the table -> Truncate
Deleting content of table and tables that reference to it:
Right click on the table -> Truncate Cascaded
Difference between delete and truncate:
From the documentation:
DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. http://www.postgresql.org/docs/9.3/static/sql-delete.html
TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows from a table. TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. http://www.postgresql.org/docs/9.1/static/sql-truncate.html
Working with table that is referenced from other table:
When you have database that has more than one table the tables have probably relationship. As an example there are three tables:
create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);
create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);
create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);
And some prepared data for these tables:
insert into customers values (1, 'John', 'Smith');
insert into orders values
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);
insert into loyalty_cards values (100, 'A123456789', 1);
Table orders references table customers and table loyalty_cards references table customers. When you try to TRUNCATE / DELETE FROM the table that is referenced by other table/s (the other table/s has foreign key constraint to the named table) you get an error. To delete content from all three tables you have to name all these tables (the order is not important)
TRUNCATE customers, loyalty_cards, orders;
or just the table that is referenced with CASCADE key word (you can name more tables than just one)
TRUNCATE customers CASCADE;
The same applies for pgAdmin. Right click on customers table and choose Truncate Cascaded.
Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)
Google Chromes developer tools has a search function built into the scripts section
If you are unfamiliar with this tool: (just in case)
Doing a quick search for the #ID should take you to the binding function eventually.
Ex: searching for #foo
would take you to
$('#foo').click(function(){ alert('bar'); })
I suggest split (not saying that the other answers are invalid, this is just another way to do it):
def findreplace(char, string):
return ''.join(string.split(char))
Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below
In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'
And the speed...
In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204
Not as fast as replace or translate, but ok.
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
?php
/* Database config */
$db_host = 'localhost';
$db_user = '~';
$db_pass = '~';
$db_database = 'banners';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
I did it like this.
$(document).ready(function(){
$("#yourid").click(function(){
$(this).load('@Url.Action("Details")');
});
});
Details Method:
public IActionResult Details()
{
return PartialView("Your Partial View");
}
A little variation with a more compact lookup table and using C++17 features:
std::string base64_decode(const std::string_view in) {
// table from '+' to 'z'
const uint8_t lookup[] = {
62, 255, 62, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255,
255, 0, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
255, 255, 255, 255, 63, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51};
static_assert(sizeof(lookup) == 'z' - '+' + 1);
std::string out;
int val = 0, valb = -8;
for (uint8_t c : in) {
if (c < '+' || c > 'z')
break;
c -= '+';
if (lookup[c] >= 64)
break;
val = (val << 6) + lookup[c];
valb += 6;
if (valb >= 0) {
out.push_back(char((val >> valb) & 0xFF));
valb -= 8;
}
}
return out;
}
If you don't have std::string_view, try instead std::experimental::string_view.
You can use mosquitto_sub
(which is part of the mosquitto-clients
package) and subscribe to the wildcard topic #
:
mosquitto_sub -v -h broker_ip -p 1883 -t '#'
I tried with a rest client.
Headers :
it works fine. I retrieve 200 OK with a good body.
Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.
This is not answering the question itself, but I found this question searching for the solution to convert a string to symbol and use it on a hash.
hsh = Hash.new
str_to_symbol = "Book Author Title".downcase.gsub(/\s+/, "_").to_sym
hsh[str_to_symbol] = 10
p hsh
# => {book_author_title: 10}
Hope it helps someone like me!
You can try creating a css for your font with font-face (like explained here)
Step #1
Create a css file with font face and place it somewhere, like in assets/fonts
customfont.css
@font-face {
font-family: YourFontFamily;
src: url("/assets/font/yourFont.otf") format("truetype");
}
Step #2
Add the css to your .angular-cli.json in the styles
config
"styles":[
//...your other styles
"assets/fonts/customFonts.css"
]
Do not forget to restart ng serve
after doing this
Step #3
Use the font in your code
component.css
span {font-family: YourFontFamily; }
This code works!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title></title>
<script>
function addRow() {
$('.displaynone').show();
$('.displaynone td')
.wrapInner('<div class="innerDiv" style="height:0" />');
$('div').animate({"height":"20px"});
}
</script>
<style>
.mycolumn{border: 1px solid black;}
.displaynone{display: none;}
</style>
</head>
<body>
<table align="center" width="50%">
<tr>
<td class="mycolumn">Row 1</td>
</tr>
<tr>
<td class="mycolumn">Row 2</td>
</tr>
<tr class="displaynone">
<td class="mycolumn">Row 3</td>
</tr>
<tr>
<td class="mycolumn">Row 4</td>
</tr>
</table>
<br>
<button onclick="addRow();">add</button>
</body>
</html>
Improved version of Komang answer (add referer and user agent, check if you can write the file), return true if it's ok, false if there is an error :
public function downloadImage($url,$filename){
if(file_exists($filename)){
@unlink($filename);
}
$fp = fopen($filename,'w');
if($fp){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$result = parse_url($url);
curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
$raw=curl_exec($ch);
curl_close ($ch);
if($raw){
fwrite($fp, $raw);
}
fclose($fp);
if(!$raw){
@unlink($filename);
return false;
}
return true;
}
return false;
}
If you want the event to be fired whenever something is changed within the element then you could use the keyup event.
You can of course use a loop, or you can insert them in a single statement, e.g.
Insert into db
(names,email,password)
Values
('abc','def','mypassword')
,('ghi','jkl','mypassword2')
,('mno','pqr','mypassword3')
It really depends where you're getting your data from.
If you use a loop, wrapping it in a transaction will make it a bit faster.
UPDATE
What if i want to insert unique names?
If you want to insert unique names, then you need to generate data with unique names. One way to do this is to use Visual Studio to generate test data.
SELECT DISTINCT Contract, Activity
FROM Contract WHERE Contract IN (
SELECT Contract
FROM Contract
GROUP BY Contract
HAVING COUNT( DISTINCT Activity ) = 1 )
def decorator(argument):
def real_decorator(function):
def wrapper(*args):
for arg in args:
assert type(arg)==int,f'{arg} is not an interger'
result = function(*args)
result = result*argument
return result
return wrapper
return real_decorator
Usage of the decorator
@decorator(2)
def adder(*args):
sum=0
for i in args:
sum+=i
return sum
Then the
adder(2,3)
produces
10
but
adder('hi',3)
produces
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-143-242a8feb1cc4> in <module>
----> 1 adder('hi',3)
<ipython-input-140-d3420c248ebd> in wrapper(*args)
3 def wrapper(*args):
4 for arg in args:
----> 5 assert type(arg)==int,f'{arg} is not an interger'
6 result = function(*args)
7 result = result*argument
AssertionError: hi is not an interger
git remote update && git status
Found this on the answer to Check if pull needed in Git
git remote update
to bring your remote refs up to date. Then you can do one of several things, such as:
git status -uno
will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.
git show-branch *master
will show you the commits in all of the branches whose names end in master (eg master and origin/master).If you use
-v
withgit remote update
you can see which branches got updated, so you don't really need any further commands.
What I did was download my sql dump in a "db-dump" folder, and mounted it:
mysql:
image: mysql:5.6
environment:
MYSQL_ROOT_PASSWORD: pass
ports:
- 3306:3306
volumes:
- ./db-dump:/docker-entrypoint-initdb.d
When I run docker-compose up
for the first time, the dump is restored in the db.
this works for me.....
comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];
It's not a good idea to set a foreign key constraint to 0, because if you do, your database would not ensure it is not violating referential integrity. This could lead to inaccurate, misleading, or incomplete data.
You make a foreign key for a reason: because all the values in the child column shall be the same as a value in the parent column. If there are no foreign key constraints, a child row can have a value that is not in the parent row, which would lead to inaccurate data.
For instance, let's say you have a website for students to login and every student must register for an account as a user. You have one table for user ids, with user id as a primary key; and another table for student accounts, with student id as a column. Since every student must have a user id, it would make sense to make the student id from the student accounts table a foreign key that references the primary key user id in the user ids table. If there are no foreign key checks, a student could end up having a student id and no user id, which means a student can get an account without being a user, which is wrong.
Imagine if it happens to a large amount of data. That's why you need the foreign key check.
It's best to figure out what is causing the error. Most likely, you are trying to delete from a parent row without deleting from a child row. Try deleting from the child row before deleting from the parent row.
Use req.app
, req.app.get('somekey')
The application variable created by calling express()
is set on the request and response objects.
The good practice is to use like this:
$.ajax({
type: "POST",
url: "/ajax/request.html",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
console.log(response.blablabla);
// put on console what server sent back...
}
});
and the php part is:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo json_encode(array("blablabla"=>$variable));
}
?>
I'm using a newer version of the SPO Management Shell. For me to get the error to go away, I changed my Import-Module statement to use:
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;
I also use the newer command:
Connect-SPOService
utf8
is MySQL's older, flawed implementation of UTF-8 which is in the process of being deprecated.utf8mb4
is what they named their fixed UTF-8 implementation, and is what you should use right now.In their flawed version, only characters in the first 64k character plane - the basic multilingual plane - work, with other characters considered invalid. The code point values within that plane - 0 to 65535 (some of which are reserved for special reasons) can be represented by multi-byte encodings in UTF-8 of up to 3 bytes, and MySQL's early version of UTF-8 arbitrarily decided to set that as a limit. At no point was this limitation a correct interpretation of the UTF-8 rules, because at no point was UTF-8 defined as only allowing up to 3 bytes per character. In fact, the earliest definitions of UTF-8 defined it as having up to 6 bytes (since revised to 4). MySQL's original version was always arbitrarily crippled.
Back when MySQL released this, the consequences of this limitation weren't too bad as most Unicode characters were in that first plane. Since then, more and more newly defined character ranges have been added to Unicode with values outside that first plane. Unicode itself defines 17 planes, though so far only 7 of these are used.
In an effort not to break old code making any particular assumptions, MySQL retained the broken implementation and called the newer, fixed version utf8mb4
. This has led to some confusion with the name being misinterpreted as if it's some kind of extension to UTF-8 or alternative form of UTF-8, rather than MySQL's implementation of the true UTF-8.
Future versions of MySQL will eventually phase out the older version, and for now it can be considered deprecated. For the foreseeable future you need to use utf8mb4
to ensure correct UTF-8 encoding. After sufficient time has passed, the current utf8
will be removed, and at some future date utf8
will rise again, this time referring to the fixed version, though utf8mb4
will continue to unambiguously refer to the fixed version.
Just restart the IDE you are using, then it will work.
If you are looking for the folder such as brushes, curves, etc. you can try:
/home/<username>/.gimp-2.8
This folder will contain all the gimp folders
.
Good Luck.
now('milli'); // 120335360.999686
now('micro') ; // 120335360966.583
now('nano') ; // 120335360904333
Known that now
is :
const now = (unit) => {
const hrTime = process.hrtime();
switch (unit) {
case 'milli':
return hrTime[0] * 1000 + hrTime[1] / 1000000;
case 'micro':
return hrTime[0] * 1000000 + hrTime[1] / 1000;
case 'nano':
default:
return hrTime[0] * 1000000000 + hrTime[1];
}
};
Hi Actually this is my same question but I didn't get anything.Now I got mobile number and his email-Id from particular Android real device(Android Mobile).Now a days 90% people using what's App application on Android Mobile.And now I am getting Mobile no and email-ID Through this What's app API.Its very simple to use see this below code.
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
for (Account ac : accounts)
{
acname = ac.name;
if (acname.startsWith("91")) {
mobile_no = acname;
}else if(acname.endsWith("@gmail.com")||acname.endsWith("@yahoo.com")||acname.endsWith("@hotmail.com")){
email = acname;
}
// Take your time to look at all available accounts
Log.i("Accounts : ", "Accounts : " + acname);
}
and import this API
import android.accounts.Account;
import android.accounts.AccountManager;
If you are using MySql Workbench, its very easy to get all details of Database size, each table size, index size etc.
Like this:
#include <vector>
// ...
std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));
(Pre-C++11 you need to leave whitespace between the angled brackets.)
Fail module works great! Thanks.
I had to define my fact before checking it, otherwise I'd get an undefined variable error.
And I had issues when doing setting the fact with quotes and without spaces.
This worked:
set_fact: flag="failed"
This threw errors:
set_fact: flag = failed
All presented solutions are not working properly.
strtotime() and DateTime::add or DateTime::modify give sometime invalid results.
Examples:
- 31.08.2019 + 1 month gives 01.10.2019 instead 30.09.2019
- 29.02.2020 + 1 year gives 01.03.2021 instead 28.02.2021
(tested on PHP 5.5, PHP 7.3)
Below is my function based on idea posted by Angelo that solves the problem:
// $time - unix time or date in any format accepted by strtotime() e.g. 2020-02-29
// $days, $months, $years - values to add
// returns new date in format 2021-02-28
function addTime($time, $days, $months, $years)
{
// Convert unix time to date format
if (is_numeric($time))
$time = date('Y-m-d', $time);
try
{
$date_time = new DateTime($time);
}
catch (Exception $e)
{
echo $e->getMessage();
exit;
}
if ($days)
$date_time->add(new DateInterval('P'.$days.'D'));
// Preserve day number
if ($months or $years)
$old_day = $date_time->format('d');
if ($months)
$date_time->add(new DateInterval('P'.$months.'M'));
if ($years)
$date_time->add(new DateInterval('P'.$years.'Y'));
// Patch for adding months or years
if ($months or $years)
{
$new_day = $date_time->format("d");
// The day is changed - set the last day of the previous month
if ($old_day != $new_day)
$date_time->sub(new DateInterval('P'.$new_day.'D'));
}
// You can chage returned format here
return $date_time->format('Y-m-d');
}
Usage examples:
echo addTime('2020-02-29', 0, 0, 1); // add 1 year (result: 2021-02-28)
echo addTime('2019-08-31', 0, 1, 0); // add 1 month (result: 2019-09-30)
echo addTime('2019-03-15', 12, 2, 1); // add 12 days, 2 months, 1 year (result: 2019-09-30)
This answer is obsolete. Technology has moved on. Unless you're working with legacy systems see Joel's answer.
There is no string concatenation operator in EL. If you don't need the concatenated string to pass into some other operation, just put these expressions next to each other:
${value}${(empty value)? 'none' : ' enabled'}
You could retrieve the body text of the whole page like this:
bodyText = self.driver.find_element_by_tag_name('body').text
then use an assert to check it like this:
self.assertTrue("the text you want to check for" in bodyText)
Of course, you can be specific and retrieve a specific DOM element's text and then check that instead of retrieving the whole page.
Because Dictionary
is a generic class ( Dictionary<TKey, TValue>
), so that accessing its content is type-safe (i.e. you do not need to cast from Object
, as you do with a Hashtable
).
Compare
var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];
to
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;
However, Dictionary
is implemented as hash table internally, so technically it works the same way.
One of the way is Using below sql queries
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
Try This
.content {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 250px;_x000D_
width: 200px;_x000D_
border: solid;_x000D_
word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.content h1 , .content h2 {_x000D_
margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
.content p {_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="content">_x000D_
<h1>heading 1</h1>_x000D_
<h2>heading 2</h2>_x000D_
<p>Some more or less text</p>_x000D_
<a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
Just simply add following key in your info.plist
file :
<key>UIUserInterfaceStyle</key>
<string>Light</string>
You are returning char, and not char*, which is the pointer to the first character of an array.
If you want to return a new character array instead of doing in-place modification, you can ask for an already allocated pointer (char*) as parameter or an uninitialized pointer. In this last case you must allocate the proper number of characters for new string and remember that in C parameters as passed by value ALWAYS, so you must use char** as parameter in the case of array allocated internally by function. Of course, the caller must free that pointer later.
Replacing substrings should not be that hard.
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Tests:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Output:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
When you're using foreign key, your order of columns should be same for insertion.
For example, if you're adding (userid, password)
in table1 from table2 then from table2 order should be same (userid, password)
and not like (password,userid)
where userid
is foreign key in table2 of table1.
Display line numbers:
:set nu
Stop showing the line numbers:
:set nonu
Its short for :set nonumber
ps. These commands are to be run in normal mode.
Put that file in assets.
For project created in Android Studio project you need to create assets folder under the main folder.
Read that file as:
public String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and then you can simply read this string
return by this function as
JSONObject obj = new JSONObject(json_return_by_the_function);
For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html
Hope you will get what you want.
mvnrepository.com isn't a repository. It's a search engine. It might or might not tell you what repository it found stuff in if it's not central; since you didn't post an example, I can't help you read the output.
Try this:
SELECT h.year, h.id, h.rate
FROM (SELECT h.year, h.id, h.rate, IF(@lastid = (@lastid:=h.id), @index:=@index+1, @index:=0) indx
FROM (SELECT h.year, h.id, h.rate
FROM h
WHERE h.year BETWEEN 2000 AND 2009 AND id IN (SELECT rid FROM table2)
GROUP BY id, h.year
ORDER BY id, rate DESC
) h, (SELECT @lastid:='', @index:=0) AS a
) h
WHERE h.indx <= 5;
Ensure right margin is not exceeded
File > Settings > Editor > Code Style > Java > Wrapping and Braces > Ensure right margin is not exceeded
Reformat code
Code > Reformat code...
or press Ctrl + Alt + L
If you have something like this:
thisLineIsVeryLongAndWillBeChanged(); // comment
it will be converted to
thisLineIsVeryLongAndWillBeChanged();
// comment
instead of
// comment
thisLineIsVeryLongAndWillBeChanged();
This is why I select pieces of code before reformatting if the code looks like in the previous example.
IntelliJ IDEA 14: File > Settings > Editor > Code Style > Wrap when typing reaches right margin
IntelliJ IDEA 15, 2016 & 2017: File > Settings > Editor > Code Style > Wrap on typing
So I had a project that required downloading assets from firebase storage, so I had to solve this problem myself. Here is How :
1- First, make a model data for example class Choice{}
, In that class defines a String variable called image Name so it will be like that
class Choice {
.....
String imageName;
}
2- from a database/firebase database, go and hardcode the image names to the objects, so if you have image name called Apple.png, create the object to be
Choice myChoice = new Choice(...,....,"Apple.png");
3- Now, get the link for the assets in your firebase storage which will be something like that
gs://your-project-name.appspot.com/
4- finally, initialize your firebase storage reference and start getting the files by a loop like that
storageRef = storage.getReferenceFromUrl(firebaseRefURL).child(imagePath);
File localFile = File.createTempFile("images", "png");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//Dismiss Progress Dialog\\
}
5- that's it
You probably want ANSI color codes. Most *nix terminals support them.
I faced the same problem. There are two types of permissions in Android:
Here is the strategy to get dangerous permissions in Android 6.0
onRequestPermissionsResult
Here is my case: I need to write to external storage.
First, I check if I have the permission:
...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(parentActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
Then check the user's approval:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
You can also use INT_MAX:
http://www.cplusplus.com/reference/climits/
it's equivalent to using numeric_limits.
CLOCK_REALTIME
represents the machine's best-guess as to the current wall-clock, time-of-day time. As Ignacio and MarkR say, this means that CLOCK_REALTIME
can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.
CLOCK_MONOTONIC
represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.
If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC
is the best option.
Note that on Linux, CLOCK_MONOTONIC
does not measure time spent in suspend, although by the POSIX definition it should. You can use the Linux-specific CLOCK_BOOTTIME
for a monotonic clock that keeps running during suspend.
Pretty sure nobody answer your question to your exact terms, you want it for dynamic text
var newString = myString.substring( myString.indexOf( "," ) +1, myString.length );
It takes a substring from the first comma, to the end
You can use C style string formatting:
"%d:%d:d" % (hours, minutes, seconds)
See here, especially: https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html
(The system will create a new log file.)
Delete or move the renamed log file.
Did you try gcc -S -fverbose-asm -O source.c
then look into the generated source.s
assembler file ?
The generated assembler code goes into source.s
(you could override that with -o
assembler-filename ); the -fverbose-asm
option asks the compiler to emit some assembler comments "explaining" the generated assembler code. The -O
option asks the compiler to optimize a bit (it could optimize more with -O2
or -O3
).
If you want to understand what gcc
is doing try passing -fdump-tree-all
but be cautious: you'll get hundreds of dump files.
BTW, GCC is extensible thru plugins or with MELT (a high level domain specific language to extend GCC; which I abandoned in 2017)
Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x)
. The %c
format specification works for any integer type.
The better pattern is to create a standalone BroadcastReceiver
. This insures that your app can respond to the broadcast, whether or not the Service
is running. In fact, using this pattern may remove the need for a constant-running Service
altogether.
Register the BroadcastReceiver
in your Manifest, and create a separate class/file for it.
Eg:
<receiver android:name=".FooReceiver" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
When the receiver runs, you simply pass an Intent
(Bundle
) to the Service
, and respond to it in onStartCommand()
.
Eg:
public class FooReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do your work quickly!
// then call context.startService();
}
}
I do not think you can do it in CSS, but you can calculate a pixel perfect width with javascript. Let's say you use jQuery:
HTML code:
<div id="container">
<div id="col1"></div>
<div id="col2"></div>
<div id="col3"></div>
</div>
JS Code:
$(function(){
var total = $("#container").width();
$("#col1").css({width: Math.round(total/3)+"px"});
$("#col2").css({width: Math.round(total/3)+"px"});
$("#col3").css({width: Math.round(total/3)+"px"});
});
I believe you would have to "git revert" back to that commit and then push it. Or you could cherry-pick
a commit into a new branch, and push that to the branch on the remote repository. Something like:
git branch onecommit
git checkout onecommit
git cherry-pick 7300a6130d9447e18a931e898b64eefedea19544 # From the other branch
git push origin {branch}
In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:
As said, fs.readFile
is an asynchronous action. It means that when you tell node to read a file, you need to consider that it will take some time, and in the meantime, node continued to run the following code. In your case it's: console.log(content);
.
It's like sending some part of your code for a long trip (like reading a big file).
Take a look at the comments that I've written:
var content;
// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
// in the meantime, please continue and run this console.log
console.log(content);
That's why content
is still empty when you log it. node has not yet retrieved the file's content.
This could be resolved by moving console.log(content)
inside the callback function, right after content = data;
. This way you will see the log when node is done reading the file and after content
gets a value.
Arrays have numerical indexes. So,
a = new Array();
a['a1']='foo';
a['a2']='bar';
and
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
are not adding elements to the array, but adding .a1
and .a2
properties to the a
object (arrays are objects too). As further evidence, if you did this:
a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length); // outputs zero because there are no items in the array
Your third option:
c=['c1','c2','c3'];
is assigning the variable c
an array with three elements. Those three elements can be accessed as: c[0]
, c[1]
and c[2]
. In other words, c[0] === 'c1'
and c.length === 3
.
Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.
a = {};
a['a1']='foo';
a['a2']='bar';
It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.
If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.
Quality Accepts 0 - 100
0 = MAX Compression (Least Quality which is suitable for Small images)
100 = Least Compression (MAX Quality which is suitable for Big images)
If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.
i.e.
package main
import "fmt"
import "time"
func main() {
go heartBeat()
time.Sleep(time.Second * 5)
}
func heartBeat() {
for range time.Tick(time.Second * 1) {
fmt.Println("Foo")
}
}
Although my answer is not related to datatables it addresses the issue of DOM manipulation and e.g. jQuery plugin initialization for directives used on elements which have their contents updated in async manner.
Instead of implementing a timeout one could just add a watch that will listen to content changes (or even additional external triggers).
In my case I used this workaround for initializing a jQuery plugin once the ng-repeat was done which created my inner DOM - in another case I used it for just manipulating the DOM after the scope property was altered at controller. Here is how I did ...
HTML:
<div my-directive my-directive-watch="!!myContent">{{myContent}}</div>
JS:
app.directive('myDirective', [ function(){
return {
restrict : 'A',
scope : {
myDirectiveWatch : '='
},
compile : function(){
return {
post : function(scope, element, attributes){
scope.$watch('myDirectiveWatch', function(newVal, oldVal){
if (newVal !== oldVal) {
// Do stuff ...
}
});
}
}
}
}
}]);
Note: Instead of just casting the myContent variable to bool at my-directive-watch attribute one could imagine any arbitrary expression there.
Note: Isolating the scope like in the above example can only be done once per element - trying to do this with multiple directives on the same element will result in a $compile:multidir Error - see: https://docs.angularjs.org/error/$compile/multidir
If you're calling "new mysqli(..)" from within a class that is namespaced, you might see a similar error Fatal error: Class 'foo\bar\mysqli' not found in
. The way to fix this is to explicitly set it to the root namespace with a preceding backslash like so:
<?php
$mysqli = new \MySQLi($db_server, $db_user, $db_pass, $db_name);
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)]autorelease];
-(void)saveAction:(UIBarButtonItem *)sender{
//perform your action
}
Multicast sender that broadcasts to a multicast group:
#!/usr/bin/env python
import socket
import struct
def main():
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.sendto('Hello World!', (MCAST_GRP, MCAST_PORT))
if __name__ == '__main__':
main()
Multicast receiver that reads from a multicast group and prints hex data to the console:
#!/usr/bin/env python
import socket
import binascii
def main():
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except AttributeError:
pass
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
sock.bind((MCAST_GRP, MCAST_PORT))
host = socket.gethostbyname(socket.gethostname())
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))
while 1:
try:
data, addr = sock.recvfrom(1024)
except socket.error, e:
print 'Expection'
hexdata = binascii.hexlify(data)
print 'Data = %s' % hexdata
if __name__ == '__main__':
main()
Jon Skeet has written a library called morelinq which has a DistinctBy()
operator. See here for the implementation. Your code would look like
IEnumerable<Note> distinctNotes = Notes.DistinctBy(note => note.Author);
Update: After re-reading your question, Kirk has the correct answer if you're just looking for a distinct set of Authors.
Added sample, several fields in DistinctBy:
res = res.DistinctBy(i => i.Name).DistinctBy(i => i.ProductId).ToList();
Python 3 seconds with microsecond decimal resolution:
from datetime import datetime
print(datetime.now().timestamp())
Python 3 integer seconds:
print(int(datetime.now().timestamp()))
datetime.utcnow().timestamp()
!datetime.utcnow()
is a non-timezone aware object. See reference: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects
For something like 1am UTC:
from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())
or
print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())
if you remove the tzinfo=timezone.utc
or +00:00
, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp()
is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp()
gives a timestamp from 7 hours in the future!
All above answers are great, but I will suggest an other option:
<style name="FlatButtonStyle" parent="Base.Widget.AppCompat.Button">
<item name="android:stateListAnimator">@null</item>
<!-- more style custom here -->
</style>
Monkey is right, according to the link given by monkey
Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.
I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting
This is an old post, but to save people some time if you get here now like I did, I suggest you have a look at the CodeHollow.FeedReader package which supports a wider range of RSS versions, is easier to use and seems more robust. https://github.com/codehollow/FeedReader
No idea how you got your results, since it would not sort by string value... You should reverse a1
and a2
in your example
Best way in any case (as per Mladen) is:
metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }
metrics.sort_by {|_key, value| value}
# ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]
If you need a hash as a result, you can use to_h
(in Ruby 2.0+)
metrics.sort_by {|_key, value| value}.to_h
# ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}
Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:
^([A-Z]{3})$
The {3}
indicates that the [A-Z]
must appear exactly 3 times.
It's worth reading Oracle Java Tutorial - Getting and Setting Field Values
Field#set(Object object, Object value) sets the field represented by this Field
object on the specified object argument to the specified new value.
It should be like this
f.set(objectOfTheClass, new ConcurrentHashMap<>());
You can't set any value in null
Object If tried then it will result in NullPointerException
Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.
Please use the below statement
select * from all_objects ao where ao.OBJECT_TYPE = 'TABLE' and ao.OWNER = 'YOUR_SCHEMA_NAME'
For this you need to run the "tomcat6w" application that is part of the standard Tomcat distribution in the "bin" directory. E.g. for windows the default is "C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin\tomcat6w.exe". The "tomcat6w" application starts a GUI. If you select the "Java" tab you can enter all Java options.
It is also possible to pass JVM options via the command line to tomcat. For this you need to use the command:
<tomcatexecutable> //US//<tomcatservicename> ++JvmOptions="<JVMoptions>"
where "tomcatexecutable" refers to your tomcat application, "tomcatservicename" is the tomcat service name you are using and "JVMoptions" are your JVM options. For instance:
"tomcat6.exe" //US//tomcat6 ++JvmOptions="-XX:MaxPermSize=128m"
Hi. As per my knowledge let me clear the concept of default constructor:
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
I read this information from the Java Tutorials.
This is because you didn't make your Facebook app live. For this go to:
Facebook developer page->Select your app->you will see top of the right your live option is disable and click to enable it->It will refer to you in "basic setting section"->You have to add "privacy policy url" and "Terms and services url" also you may select app category->then save the setting.
Note: You can use any blogspot or website to make your privacy policy also terms and condition page.Both I gave same url which worked.
#ifdef 0
...
#endif
#ifdef expect a macro rather than expression when using constant or expression
#if 0
...
#endif
or
#if !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif
if #ifdef is used the it reports this error
#ifdef !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif
Where #ifdef expect a macro rather than macro expresssion
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
startActivityForResult(intent, 0);
} catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);
}
and in onActivityResult():
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
}
if(resultCode == RESULT_CANCELED){
//handle cancel
}
}
}
This assumes you have other languages already added in Language Support. (To check this, Menu > Language Support)
Now to make the keyboard language appear in the Panel:
The icon 'en' or your language should now appear in the right panel tray. Click it to switch language.
In previous Mint versions, the shortcut for switching language was LEFT SHIFT + CAPS.
It seems now there is no default, and it must be added:
Keyboard Preferences is also accessible by right-clicking the language icon in the Panel.
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
copy connection string to app.config
or web.config
file in the project which has set to "Set as StartUp
Project" and if in the case of using entity framework in data layer project - please install entity framework nuget in main project.
You can do this using dataset property of the element, using with or without jquery it work... i'm not aware of old browser
Note: that when you use dash ('-') sign, you need to use capital case. Eg. a-b => aB
function onContentLoad() {_x000D_
var item = document.getElementById("id1");_x000D_
var x = item.dataset.x;_x000D_
var data = item.dataset.myData;_x000D_
_x000D_
var resX = document.getElementById("resX");_x000D_
var resData = document.getElementById("resData");_x000D_
_x000D_
resX.innerText = x;_x000D_
resData.innerText = data;_x000D_
_x000D_
console.log(x);_x000D_
console.log(data);_x000D_
}
_x000D_
<body onload="onContentLoad()">_x000D_
<div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
Read 'x':_x000D_
<label id="resX"></label>_x000D_
<br/>Read 'my-data':_x000D_
<label id="resData"></label>_x000D_
</body>
_x000D_
No you cannot do that in Java. you can however write a method as follows:
boolean isContains(int i, int ... numbers) {
// code to check if i is one of the numbers
for (int n : numbers) {
if (i == n) return true;
}
return false;
}
Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.
Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.
As a guess, I would try using this:
Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate
I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b
In Solution Explorer, please select files you want to copied to output directory and assign two properties: - Build action = Content - Copy to Output Directory = Copy Always
This will do the trick.
You can use SublimeREPL (you need to have Package Control installed first).
You can also use the tag, this works in divs and everything else:
<center><form></form></center>
This link will help you with the tag:
Bullets take the color
property of the list:
.listStyle {
color: red;
}
Note if you want your list text to be a different colour, you have to wrap it in say, a p
, for example:
.listStyle p {
color: black;
}
<ul class="listStyle">
<li>
<p><strong>View :</strong> blah blah.</p>
</li>
<li>
<p><strong>View :</strong> blah blah.</p>
</li>
</ul>
div {
background: #dbdbdb;
-webkit-transition: .5s all;
-webkit-transition-delay: 5s;
-moz-transition: .5s all;
-moz-transition-delay: 5s;
-ms-transition: .5s all;
-ms-transition-delay: 5s;
-o-transition: .5s all;
-o-transition-delay: 5s;
transition: .5s all;
transition-delay: 5s;
}
div:hover {
background:#5AC900;
-webkit-transition-delay: 0s;
-moz-transition-delay: 0s;
-ms-transition-delay: 0s;
-o-transition-delay: 0s;
transition-delay: 0s;
}
This will add a transition delay, which will be applicable to almost every browser..
I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.
dangerouslySetInnerHtml
to embed the <video>
code. For example:<div dangerouslySetInnerHTML={{ __html: `
<video class="video-js" playsinline autoplay loop muted>
<source src="../video_path.mp4" type="video/mp4"/>
</video>`}}
/>
Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)
One solution could be to reshape the date from wide to long putting all the departments in one column and counts in another, group by the employer id (in this case, the row number), and then filter to the department(s) with the max value. There are a couple of options for handling ties with this approach too.
library(tidyverse)
# sample data frame with a tie
df <- data_frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,5))
# If you aren't worried about ties:
df %>%
rownames_to_column('id') %>% # creates an ID number
gather(dept, cnt, V1:V3) %>%
group_by(id) %>%
slice(which.max(cnt))
# A tibble: 3 x 3
# Groups: id [3]
id dept cnt
<chr> <chr> <dbl>
1 1 V3 9.
2 2 V1 8.
3 3 V2 5.
# If you're worried about keeping ties:
df %>%
rownames_to_column('id') %>%
gather(dept, cnt, V1:V3) %>%
group_by(id) %>%
filter(cnt == max(cnt)) %>% # top_n(cnt, n = 1) also works
arrange(id)
# A tibble: 4 x 3
# Groups: id [3]
id dept cnt
<chr> <chr> <dbl>
1 1 V3 9.
2 2 V1 8.
3 3 V2 5.
4 3 V3 5.
# If you're worried about ties, but only want a certain department, you could use rank() and choose 'first' or 'last'
df %>%
rownames_to_column('id') %>%
gather(dept, cnt, V1:V3) %>%
group_by(id) %>%
mutate(dept_rank = rank(-cnt, ties.method = "first")) %>% # or 'last'
filter(dept_rank == 1) %>%
select(-dept_rank)
# A tibble: 3 x 3
# Groups: id [3]
id dept cnt
<chr> <chr> <dbl>
1 2 V1 8.
2 3 V2 5.
3 1 V3 9.
# if you wanted to keep the original wide data frame
df %>%
rownames_to_column('id') %>%
left_join(
df %>%
rownames_to_column('id') %>%
gather(max_dept, max_cnt, V1:V3) %>%
group_by(id) %>%
slice(which.max(max_cnt)),
by = 'id'
)
# A tibble: 3 x 6
id V1 V2 V3 max_dept max_cnt
<chr> <dbl> <dbl> <dbl> <chr> <dbl>
1 1 2. 7. 9. V3 9.
2 2 8. 3. 6. V1 8.
3 3 1. 5. 5. V2 5.
Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.
package com.zetcode.bean;
import org.springframework.stereotype.Component;
@Component
public class Message {
private String message = "Hello there!";
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
This is a simple bean. It is decorated with the @Component
annotation for auto-detection by Spring container.
package com.zetcode.main;
import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "com.zetcode")
public class Application {
public static void main(String[] args) {
ApplicationContext context
= new AnnotationConfigApplicationContext(Application.class);
Application p = context.getBean(Application.class);
p.start();
}
@Autowired
private Message message;
private void start() {
System.out.println("Message: " + message.getMessage());
}
}
This is the main Application
class. The @ComponentScan
annotation searches for components. The @Autowired
annotation injects the bean into the message
variable. The AnnotationConfigApplicationContext
is used to create the Spring application context.
My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.
I found this plain JavaScript code very handy!
#<script type="text/javascript">
function toggle_visibility(id)
{
var e = document.getElementById(id);
if ( e.style.display == 'block' )
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
<th nowrap="nowrap">
or
<th style="white-space:nowrap;">
or
<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>
A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.
The simpler way:
h = ''
i = None
j = 0
k = 1
print h or i or j or k
Will print 1
print k or j or i or h
Will print 1
In my situation, we are using Git Flow and GitHub. All you need to do this is: Compare your feature branch with your develop branch on GitHub.
It will show the commits only made to your feature branch.
For example:
https://github.com/your_repo/compare/develop...feature_branch_name
With :after and :before you can do that.
HTML:
<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>
CSS:
div {
height: 100px;
position: relative;
}
.a {
background: #9C9E9F;
}
.b {
background: linear-gradient(to right, #9c9e9f, #f6f6f6);
}
.a:after, .c:before, .c:after {
content: '';
width: 50%;
height: 100%;
top: 0;
right: 0;
display: block;
position: absolute;
}
.a:after {
background: #f6f6f6;
}
.c:before {
background: #9c9e9f;
left: 0;
}
.c:after {
background: #33CCFF;
right: 0;
height: 80%;
}
And a demo.
In my case here is what I did to cause the diverged message: I did git push
but then did git commit --amend
to add something to the commit message. Then I also did another commit.
So in my case that simply meant origin/master was out of date. Because I knew no-one else was touching origin/master, the fix was trivial: git push -f
(where -f
means force)
ui-number-mask
for angular, https://github.com/assisrafael/angular-input-masks
only this:
<input ui-number-mask ng-model="valores.irrf" />
If you put value one by one....
need: 120,01
digit per digit
= 0,01
= 0,12
= 1,20
= 12,00
= 120,01 final number.
You should remove navbar-fixed-top
class otherwise navbar stays fixed on top of page where you want logo.
If you want to place logo inside navbar:
Navbar height (set in @navbarHeight
LESS variable) is 40px
by default. Your logo has to fit inside or you have to make navbar higher first.
Then use brand
class:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
</div>
</div>
</div>
If your logo is higher than 20px
, you have to fix stylesheets as well.
If you do that in LESS:
.navbar .brand {
@elementHeight: 32px;
padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}
@elementHeight
should be set to your image height.
Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52
Alternatively you can calculate padding values yourself and use pure CSS.
This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50
$xml = <<<XML
<root>
<elem attrib="value" />
</root>
XML;
$sxml = simplexml_load_string($xml);
$attrs = $sxml->elem->attributes();
echo $attrs["attrib"]; //or just $sxml->elem["attrib"]
Use SimpleXMLElement::attributes
.
Truth is, the SimpleXMLElement get_properties
handler lies big time. There's no property named "@attributes", so you can't do $sxml->elem->{"@attributes"}["attrib"]
.
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
You have the most efficient representation already - it's the bare minimum that needs to be checked unless you know for sure that x1 < x2 etc, then use the solutions others have provided.
You should probably note that some compilers will actually optimise this for you - by returning as soon as any of those 4 expressions return true. If one returns true, so will the end result - so the other checks can just be skipped.
The best solution for me is:
// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}
It checks to see whether the specific object is contained in the list.
You might be better using the Find method on the list.
Here's an example
List<CartProduct> lst = new List<CartProduct>();
CartProduct objBeer;
objBeer = lst.Find(x => (x.Name == "Beer"));
Hope that helps
You should also look at LinQ - overkill for this perhaps, but a useful tool nonetheless...
I had the same problem, and found a detailed explanation in http://www.webmasterworld.com/apache/3163397.htm
My solution (the subdomains contents should be in a folder called sd_subdomain
:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} subdomain\.domain\.com
RewriteCond $1 !^sd_
RewriteRule (.*) /sd_subdomain/$1 [L]
You can resolve this issue by downgrading Source Compatibility and Target Compatibility Java Version to 1.8 in Latest Android Studio Version 3.4.1
Open Module Settings (Project Structure) Winodw by right clicking on app folder or Command + Down Arrow on Mac
Change Source Compatibility and Target Compatibility Version to 1.8
Click on Apply or OK Thats it. It will solve your issue.
Also you can manually add in build.gradle (Module: app)
android {
...
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
...
}
$file = __DIR__."/file1.txt";
$f = fopen($file, "r");
$array1 = array();
while ( $line = fgets($f, 1000) )
{
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
print_r($array);
The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.
The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)
<div>
<canvas id="chartDiv" height="400" width="600"></canvas>
<div id="legendDiv"></div>
</div>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "The Flash's Speed",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Superman's Speed",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>
The simples way is to use 'to' property:
<Link to="chart" target="_blank" to="http://link2external.page.com" >Test</Link>
To append entries to the table:
for row in data:
name = ??? # figure out the name of the drug
number = ??? # figure out the number you want to append
drug_dictionary[name].append(number)
To loop through the data:
for name, numbers in drug_dictionary.items():
print name, numbers
To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.
Now, add the style to the div class and use the text-align property with center as its value.
See the below example.
<style>
.myDivElement{
text-align:center;
}
.myDivElement ul li{
display:inline;
}
</style>
<div class="myDivElement">
<ul>
<li>Home</li>
<li>About</li>
<li>Gallery</li>
<li>Contact</li>
</ul>
</div>
Here is the reference website Center Align Unordered List
If you don't care about IE =6, you could use pure CSS ...
.forum:hover { background-color: #380606; }
.forum { color: white; }_x000D_
.forum:hover { background-color: #380606 !important; }_x000D_
/* we use !important here to override specificity. see http://stackoverflow.com/q/5805040/ */_x000D_
_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
With jQuery, usually it is better to create a specific class for this style:
.forum_hover { background-color: #380606; }
and then apply the class on mouseover, and remove it on mouseout.
$('.forum').hover(function(){$(this).toggleClass('forum_hover');});
$(document).ready(function(){_x000D_
$('.forum').hover(function(){$(this).toggleClass('forum_hover');});_x000D_
});
_x000D_
.forum_hover { background-color: #380606 !important; }_x000D_
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
If you must not modify the class, you could save the original background color in .data()
:
$('.forum').data('bgcolor', '#380606').hover(function(){
var $this = $(this);
var newBgc = $this.data('bgcolor');
$this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);
});
$(document).ready(function(){_x000D_
$('.forum').data('bgcolor', '#380606').hover(function(){_x000D_
var $this = $(this);_x000D_
var newBgc = $this.data('bgcolor');_x000D_
$this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);_x000D_
});_x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
or
$('.forum').hover(
function(){
var $this = $(this);
$this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
},
function(){
var $this = $(this);
$this.css('background-color', $this.data('bgcolor'));
}
);
$(document).ready(function(){_x000D_
$('.forum').hover(_x000D_
function(){_x000D_
var $this = $(this);_x000D_
$this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');_x000D_
},_x000D_
function(){_x000D_
var $this = $(this);_x000D_
$this.css('background-color', $this.data('bgcolor'));_x000D_
}_x000D_
); _x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
You can create a new row with $
in your data frame corresponding to the Means
DF$Mean <- rowMeans(DF[,2:4])
SELECT owner, table_name
FROM dba_constraints
WHERE constraint_name = <<your constraint name>>
will give you the name of the table. If you don't have access to the DBA_CONSTRAINTS
view, ALL_CONSTRAINTS
or USER_CONSTRAINTS
should work as well.
The easiest method for obtaining both a setter
and a getter
for a property which works for any type including dynamic
and ExpandoObject
is to use FastMember
which also happens to be the fastest method around (it uses Emit).
You can either get a TypeAccessor
based on a given type or an ObjectAccessor
based of an instance of a given type.
Example:
var staticData = new Test { Id = 1, Name = "France" };
var objAccessor = ObjectAccessor.Create(staticData);
objAccessor["Id"].Should().Be(1);
objAccessor["Name"].Should().Be("France");
var anonymous = new { Id = 2, Name = "Hilton" };
objAccessor = ObjectAccessor.Create(anonymous);
objAccessor["Id"].Should().Be(2);
objAccessor["Name"].Should().Be("Hilton");
dynamic expando = new ExpandoObject();
expando.Id = 3;
expando.Name = "Monica";
objAccessor = ObjectAccessor.Create(expando);
objAccessor["Id"].Should().Be(3);
objAccessor["Name"].Should().Be("Monica");
var typeAccessor = TypeAccessor.Create(staticData.GetType());
typeAccessor[staticData, "Id"].Should().Be(1);
typeAccessor[staticData, "Name"].Should().Be("France");
typeAccessor = TypeAccessor.Create(anonymous.GetType());
typeAccessor[anonymous, "Id"].Should().Be(2);
typeAccessor[anonymous, "Name"].Should().Be("Hilton");
typeAccessor = TypeAccessor.Create(expando.GetType());
((int)typeAccessor[expando, "Id"]).Should().Be(3);
((string)typeAccessor[expando, "Name"]).Should().Be("Monica");
//lower for v4 some version
public function videos() {
$instance =$this->hasMany('Video');
$instance->getQuery()->where('available','=', 1);
return $instance
}
//v5
public function videos() {
return $this->hasMany('Video')->where('available','=', 1);
}
for me it was just a little compile error and sadly Android Studio doesn't show it . please search manually . trying to enable work offline and clean&rebuild may help you more
AndroChef Java Decompiler produces very good code that you can use directly in your projects...
Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact.
Documentation is here
> db.test.insert({x: 1})
> db.test.find() // no criteria
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) // explicit
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c")) // shortcut
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
The two methods previously described are not enough today. I personnally use :
input[type="text"]{
background-color: transparent;
border: 0px;
outline: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
width:5px;
color:transparent;
cursor:default;
}
It also removes the shadow set on some browsers, hide the text that could be input and make the cursor behave as if the input was not there.
You may want to set width to 0px also.
Kotlin solution, based on what others wrote here:
fun isTableExists(database: SQLiteDatabase, tableName: String): Boolean {
database.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '$tableName'", null)?.use {
return it.count > 0
} ?: return false
}
Try this and tell my if it works hope it help you:
string value = Convert.ToString(Console.ReadLine());
Switch(value)
{
Case "abc":
break;
default:
break;
}
host just includes the port number if there is one specified. If there is no port number specifically in the URL, then it returns the same as hostname. You pick whether you care to match the port number or not. See https://developer.mozilla.org/en/window.location for more info.
I would assume you want hostname to just get the site name.
You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?
When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
}
It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
System.out.println(array[count]);
}
At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini
itself.
String ini = "Hi there";
for (int count = 0; count < ini.length(); count++) {
System.out.println(ini.charAt(count));
}
Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string
String ini = "Hi there"; // stored in String constant pool
is stored differently in memory than
String ini = new String("Hi there"); // stored in heap memory and String constant pool
, which is stored differently than
char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string
.
A simple JavaScript function will do the job.
function ClearFields() {
document.getElementById("textfield1").value = "";
document.getElementById("textfield2").value = "";
}
And just have your button call it:
<button type="button" onclick="ClearFields();">Clear</button>
You can have the program create an .ics (iCal) version of the calendar and then you can import this .ics into whichever calendar program you'd like: Google, Outlook, etc.
I know this post is quite old, so I won't bother inputting any code. But please comment on this if you'd like me to provide an outline of how to do this.
I fixed my entire 500 problem like this:
A. Check php.ini parameters
B. Update IIS manager parameters
in this step, you get 500 errors like this and with no html loading.
in this step, you can see html page including php errors like this.
AND DONE :)
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
I had the same problem, but solution for my case is not listed in answers.
My antivirus program (AVG) determined file MyProg.exe
as a virus and put it into the 'virus storehouse'. You need to check this storehouse and if file is there - then just restore it. It helped me out.
You need to restart mongo to solve the topology error, then just change some options of mongoose or mongoclient to overcome this problem:
var mongoOptions = {
useMongoClient: true,
keepAlive: 1,
connectTimeoutMS: 30000,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 5000,
useNewUrlParser: true
}
mongoose.connect(mongoDevString,mongoOptions);
class User(object):
email = 'none'
firstname = 'none'
lastname = 'none'
def __init__(self, email=None, firstname=None, lastname=None):
self.email = email
self.firstname = firstname
self.lastname = lastname
@classmethod
def print_var(cls, obj):
print ("obj.email obj.firstname obj.lastname")
print(obj.email, obj.firstname, obj.lastname)
print("cls.email cls.firstname cls.lastname")
print(cls.email, cls.firstname, cls.lastname)
u1 = User(email='abc@xyz', firstname='first', lastname='last')
User.print_var(u1)
In the above code, the User class has 3 global variables, each with value 'none'. u1 is the object created by instantiating this class. The method print_var prints the value of class variables of class User and object variables of object u1. In the output shown below, each of the class variables User.email
, User.firstname
and User.lastname
has value 'none'
, while the object variables u1.email
, u1.firstname
and u1.lastname
have values 'abc@xyz'
, 'first'
and 'last'
.
obj.email obj.firstname obj.lastname
('abc@xyz', 'first', 'last')
cls.email cls.firstname cls.lastname
('none', 'none', 'none')
I have that kind of spring setup working
an abstract class with an autowired field
public abstract class AbstractJobRoute extends RouteBuilder {
@Autowired
private GlobalSettingsService settingsService;
and several children defined with @Component
annotation.
split
slice
concentrate
This is a good workout for beginners and it's easy to achieve.
Another advanced method is a function like this:
def trim(s):
return trim(s[slice])
And for this question, you just want to remove the last characters, so you can write like this:
def trim(s):
return s[ : -3]
I think you are over to care about what those three characters are, so you lost. You just want to remove last three, nevertheless who they are!
If you want to remove some specific characters, you can add some if judgements:
def trim(s):
if [conditions]: ### for some cases, I recommend using isinstance().
return trim(s[slice])