Iterators are first choice over operator[]
. C++11 provides std::begin()
, std::end()
functions.
As your code uses just std::vector
, I can't say there is much difference in both codes, however, operator []
may not operate as you intend to. For example if you use map, operator[]
will insert an element if not found.
Also, by using iterator
your code becomes more portable between containers. You can switch containers from std::vector
to std::list
or other container freely without changing much if you use iterator such rule doesn't apply to operator[]
.
The range of char is 127 to -128. If you assign 212, ch stores -44 (212-128-128) not 212.So if you try to print a negative number as unsigned you get (MAX value of unsigned int)-abs(number) which in this case is 4294967252
So if you want to store 212 as it is in ch the only thing you can do is declare ch as
unsigned char ch;
now the range of ch is 0 to 255.
Are you attempting to do this inside of an XCTest and on the verge of smashing your laptop? This is the thread for you: Why can't code inside unit tests find bundle resources?
you can use indexOf for this
var a = 'how are you';
if (a.indexOf('are') > -1) {
return true;
} else {
return false;
}
Edit: This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if
clause is not required at all because the expression itself is a boolean. Here is a better version of it which you should use,
var a = 'how are you';
return a.indexOf('are') > -1;
Update in ECMAScript2016:
var a = 'how are you';
return a.includes('are'); //true
This is how I do it in my code.
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
or
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
to be precise.
See also:
You need to capture the key window for a screenshot or a UIView. You can do it in Retina Resolution using UIGraphicsBeginImageContextWithOptions and set its scale parameter 0.0f. It always captures in native resolution (retina for iPhone 4 and later).
This one does a full screen screenshot (key window)
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
This code capture a UIView in native resolution
CGRect rect = [captureView bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[captureView.layer renderInContext:context];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
This saves the UIImage in jpg format with 95% quality in the app's document folder if you need to do that.
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/capturedImage.jpg"]];
[UIImageJPEGRepresentation(capturedImage, 0.95) writeToFile:imagePath atomically:YES];
by this function:
ALTER FUNCTION [dbo].[isnull](@input nvarchar(50),@ret int = 0)
RETURNS int
AS
BEGIN
return (case when @input='' then @ret when @input is null then @ret else @input end)
END
and use this:
dbo.isnull(value,0)
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
A generator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.
>>> def myGenerator():
... yield 'These'
... yield 'words'
... yield 'come'
... yield 'one'
... yield 'at'
... yield 'a'
... yield 'time'
>>> myGeneratorInstance = myGenerator()
>>> next(myGeneratorInstance)
These
>>> next(myGeneratorInstance)
words
and so on. The (or one) benefit of generators is that because they deal with data one piece at a time, you can deal with large amounts of data; with lists, excessive memory requirements could become a problem. Generators, just like lists, are iterable, so they can be used in the same ways:
>>> for word in myGeneratorInstance:
... print word
These
words
come
one
at
a
time
Note that generators provide another way to deal with infinity, for example
>>> from time import gmtime, strftime
>>> def myGen():
... while True:
... yield strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
>>> myGeneratorInstance = myGen()
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:17:15 +0000
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:18:02 +0000
The generator encapsulates an infinite loop, but this isn't a problem because you only get each answer every time you ask for it.
This worked perfectly for me without css. I think css would put some icing on the cake though.
<form>
<label for="First Name" >First Name:</label>
<input type="text" name="username" size="15" maxlength="30" />
<label for="Last Name" >Last Name:</label>
<input type="text" name="username" size="15" maxlength="30" />
</form>
Nearly every answer proposes a static function as a solution, but thinking Object-Oriented (for reusability-purposes and clarity) I came up with a Solution via Delegation through the CharSequence-Interface (which also opens up usability on mutable CharSequence-Classes).
The following Class can be used either with or without Separator-String/CharSequence and each call to "toString()" builds the final repeated String. The Input/Separator are not only limited to String-Class, but can be every Class which implements CharSequence (e.g. StringBuilder, StringBuffer, etc)!
/**
* Helper-Class for Repeating Strings and other CharSequence-Implementations
* @author Maciej Schuttkowski
*/
public class RepeatingCharSequence implements CharSequence {
final int count;
CharSequence internalCharSeq = "";
CharSequence separator = "";
/**
* CONSTRUCTOR - RepeatingCharSequence
* @param input CharSequence to repeat
* @param count Repeat-Count
*/
public RepeatingCharSequence(CharSequence input, int count) {
if(count < 0)
throw new IllegalArgumentException("Can not repeat String \""+input+"\" less than 0 times! count="+count);
if(count > 0)
internalCharSeq = input;
this.count = count;
}
/**
* CONSTRUCTOR - Strings.RepeatingCharSequence
* @param input CharSequence to repeat
* @param count Repeat-Count
* @param separator Separator-Sequence to use
*/
public RepeatingCharSequence(CharSequence input, int count, CharSequence separator) {
this(input, count);
this.separator = separator;
}
@Override
public CharSequence subSequence(int start, int end) {
checkBounds(start);
checkBounds(end);
int subLen = end - start;
if (subLen < 0) {
throw new IndexOutOfBoundsException("Illegal subSequence-Length: "+subLen);
}
return (start == 0 && end == length()) ? this
: toString().substring(start, subLen);
}
@Override
public int length() {
//We return the total length of our CharSequences with the separator 1 time less than amount of repeats:
return count < 1 ? 0
: ( (internalCharSeq.length()*count) + (separator.length()*(count-1)));
}
@Override
public char charAt(int index) {
final int internalIndex = internalIndex(index);
//Delegate to Separator-CharSequence or Input-CharSequence depending on internal index:
if(internalIndex > internalCharSeq.length()-1) {
return separator.charAt(internalIndex-internalCharSeq.length());
}
return internalCharSeq.charAt(internalIndex);
}
@Override
public String toString() {
return count < 1 ? ""
: new StringBuilder(this).toString();
}
private void checkBounds(int index) {
if(index < 0 || index >= length())
throw new IndexOutOfBoundsException("Index out of Bounds: "+index);
}
private int internalIndex(int index) {
// We need to add 1 Separator-Length to total length before dividing,
// as we subtracted one Separator-Length in "length()"
return index % ((length()+separator.length())/count);
}
}
public static void main(String[] args) {
//String input = "12345";
//StringBuffer input = new StringBuffer("12345");
StringBuilder input = new StringBuilder("123");
//String separator = "<=>";
StringBuilder separator = new StringBuilder("<=");//.append('>');
int repeatCount = 2;
CharSequence repSeq = new RepeatingCharSequence(input, repeatCount, separator);
String repStr = repSeq.toString();
System.out.println("Repeat="+repeatCount+"\tSeparator="+separator+"\tInput="+input+"\tLength="+input.length());
System.out.println("CharSeq:\tLength="+repSeq.length()+"\tVal="+repSeq);
System.out.println("String :\tLength="+repStr.length()+"\tVal="+repStr);
//Here comes the Magic with a StringBuilder as Input, as you can append to the String-Builder
//and at the same Time your Repeating-Sequence's toString()-Method returns the updated String :)
input.append("ff");
System.out.println(repSeq);
//Same can be done with the Separator:
separator.append("===").append('>');
System.out.println(repSeq);
}
Repeat=2 Separator=<= Input=123 Length=3
CharSeq: Length=8 Val=123<=123
String : Length=8 Val=123<=123
123ff<=123ff
123ff<====>123ff
If you really want constants, not just variables looking like constants, the standard way to do it is to use immutable dictionaries. Unfortunately it's not built-in yet, so you have to use third party recipes (like this one or that one).
I think it's worth noting that all the style and CSS based solutions don't work when a page is running in compatibility mode. The compatibility mode renderer ignores the ::-ms-clear element, even though the browser shows the x.
If your page needs to run in compatibility mode, you may be stuck with the X showing.
In my case, I am working with some third party data bound controls, and our solution was to handle the "onchange" event and clear the backing store if the field is cleared with the x button.
This Link worked for me all situations you may try this.
One way to control the locale settings is to set the java system properties user.language and user.region.
I found that (at least in Visual Studio 2010) you need to set the output verbosity to at least Detailed to be able to spot the problem.
It might be that my problem was a reference that was previously a GAC reference, but that was no longer the case after my machine's reinstall.
I came upon this post, and while it has already been answered, felt I should post some information that helped me with this problem specific to IE 10, and might help others arriving at this post with a similar problem.
I was baffled how animated gifs were just not displaying in IE 10 and then found this gem.
Tools→Internet Options→Advanced→MultiMedia→Play animations in webpages
hope this helps.
Simply check if the global variable is available, if not check again. In order to prevent the maximum callstack being exceeded set a 100ms timeout on the check:
function check_script_loaded(glob_var) {
if(typeof(glob_var) !== 'undefined') {
// do your thing
} else {
setTimeout(function() {
check_script_loaded(glob_var)
}, 100)
}
}
Very old thread, I know, but here's my contribution, as the thread is not solved yet.
It takes leap years into consideration and does not asume any fixed number of days per month or year.
It might be flawed in border cases as I haven't tested it thoroughly, but it works for all the dates provided in the original question, thus I'm confident.
function calculate() {_x000D_
var fromDate = document.getElementById('fromDate').value;_x000D_
var toDate = document.getElementById('toDate').value;_x000D_
_x000D_
try {_x000D_
document.getElementById('result').innerHTML = '';_x000D_
_x000D_
var result = getDateDifference(new Date(fromDate), new Date(toDate));_x000D_
_x000D_
if (result && !isNaN(result.years)) {_x000D_
document.getElementById('result').innerHTML =_x000D_
result.years + ' year' + (result.years == 1 ? ' ' : 's ') +_x000D_
result.months + ' month' + (result.months == 1 ? ' ' : 's ') + 'and ' +_x000D_
result.days + ' day' + (result.days == 1 ? '' : 's');_x000D_
}_x000D_
} catch (e) {_x000D_
console.error(e);_x000D_
}_x000D_
}_x000D_
_x000D_
function getDateDifference(startDate, endDate) {_x000D_
if (startDate > endDate) {_x000D_
console.error('Start date must be before end date');_x000D_
return null;_x000D_
}_x000D_
var startYear = startDate.getFullYear();_x000D_
var startMonth = startDate.getMonth();_x000D_
var startDay = startDate.getDate();_x000D_
_x000D_
var endYear = endDate.getFullYear();_x000D_
var endMonth = endDate.getMonth();_x000D_
var endDay = endDate.getDate();_x000D_
_x000D_
// We calculate February based on end year as it might be a leep year which might influence the number of days._x000D_
var february = (endYear % 4 == 0 && endYear % 100 != 0) || endYear % 400 == 0 ? 29 : 28;_x000D_
var daysOfMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];_x000D_
_x000D_
var startDateNotPassedInEndYear = (endMonth < startMonth) || endMonth == startMonth && endDay < startDay;_x000D_
var years = endYear - startYear - (startDateNotPassedInEndYear ? 1 : 0);_x000D_
_x000D_
var months = (12 + endMonth - startMonth - (endDay < startDay ? 1 : 0)) % 12;_x000D_
_x000D_
// (12 + ...) % 12 makes sure index is always between 0 and 11_x000D_
var days = startDay <= endDay ? endDay - startDay : daysOfMonth[(12 + endMonth - 1) % 12] - startDay + endDay;_x000D_
_x000D_
return {_x000D_
years: years,_x000D_
months: months,_x000D_
days: days_x000D_
};_x000D_
}
_x000D_
<p><input type="text" name="fromDate" id="fromDate" placeholder="yyyy-mm-dd" value="1999-02-28" /></p>_x000D_
<p><input type="text" name="toDate" id="toDate" placeholder="yyyy-mm-dd" value="2000-03-01" /></p>_x000D_
<p><input type="button" name="calculate" value="Calculate" onclick="javascript:calculate();" /></p>_x000D_
<p />_x000D_
<p id="result"></p>
_x000D_
I personally use both cookies and session.
Cookies only used when user click on "remember me" checkbox. and also cookies are encrypted and data only decrypt on the server. If anyone tries to edit cookies our decrypter able to detect it and refuse the request.
I have seen so many sites where login info are stored in cookies, anyone can just simply change the user's id and username in cookies to access anyone account.
Thanks,
Your css with doesn't have any effect as the outer element doesn't have a width defined (and body is missing as well).
A different approach is to deliver already scaled images. http://www.sencha.com/products/io/ for example delivers the image already scaled down depending on the viewing device.
This is very .Net-centric, but has anybody tried Pex?
I was extremely sceptical until I tried it - and wow, what a performance. Before I thought "I'm not going to be convinced by this concept until I understand what it's actually doing to benefit me". It took a single run for me to change my mind and say "I don't care how you know there's the risk of a fatal exception there, but there is and now I know I have to deal with it"
Perhaps the only downside to this behaviour is that it will flag up everything and give you a six month backlog. But, if you had code debt, you always had code debt, you just didn't know it. Telling a PM there are a potential two hundred thousand points of failure when before you were aware of a few dozen is a nasty prospect, which means it is vital that the concept is explained first.
func change(string: inout String) {
var character: Character = .normal
enum Character {
case space
case newLine
case normal
}
for i in stride(from: string.count - 1, through: 0, by: -1) {
// first get index
let index: String.Index?
if i != 0 {
index = string.index(after: string.index(string.startIndex, offsetBy: i - 1))
} else {
index = string.startIndex
}
if string[index!] == "\n" {
if character != .normal {
if character == .newLine {
string.remove(at: index!)
} else if character == .space {
let number = string.index(after: string.index(string.startIndex, offsetBy: i))
if string[number] == " " {
string.remove(at: number)
}
character = .newLine
}
} else {
character = .newLine
}
} else if string[index!] == " " {
if character != .normal {
string.remove(at: index!)
} else {
character = .space
}
} else {
character = .normal
}
}
// startIndex
guard string.count > 0 else { return }
if string[string.startIndex] == "\n" || string[string.startIndex] == " " {
string.remove(at: string.startIndex)
}
// endIndex - here is a little more complicated!
guard string.count > 0 else { return }
let index = string.index(before: string.endIndex)
if string[index] == "\n" || string[index] == " " {
string.remove(at: index)
}
}
Here's an extension method which does not suffer from integer overflow (like some of the above answers do). It also caches some powers of 10 for efficiency.
static double[] pow10 = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10 };
public static double Truncate(this double x, int precision)
{
if (precision < 0)
throw new ArgumentException();
if (precision == 0)
return Math.Truncate(x);
double m = precision >= pow10.Length ? Math.Pow(10, precision) : pow10[precision];
return Math.Truncate(x * m) / m;
}
Just restart R Studio after installing the new version of R. To confirm you're on the new version, >version and you should see the new details.
Step 1: View page code
<input type="button" id="btnExport" value="Export" class="btn btn-primary" />
<script>
$(document).ready(function () {
$('#btnExport').click(function () {
window.location = '/Inventory/ExportInventory';
});
});
</script>
Step 2: Controller Code
public ActionResult ExportInventory()
{
//Load Data
var dataInventory = _inventoryService.InventoryListByPharmacyId(pId);
string xml=String.Empty;
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(dataInventory.GetType());
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, dataInventory);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
xml = xmlDoc.InnerXml;
}
var fName = string.Format("Inventory-{0}", DateTime.Now.ToString("s"));
byte[] fileContents = Encoding.UTF8.GetBytes(xml);
return File(fileContents, "application/vnd.ms-excel", fName);
}
If you do not want to depend on throwing exception (which you probably should not) you can try this:
public static <T> T cast(Object o, Class<T> clazz) {
return clazz.isInstance(o) ? clazz.cast(o) : null;
}
I know that this is an old topic but none of the solution mentioned worked for me. I have done something else that worked:
You need to:
select regexp_replace(field, E'[\\n\\r\\u2028]+', ' ', 'g' )
I had the same problem in my postgres d/b, but the newline in question wasn't the traditional ascii CRLF, it was a unicode line separator, character U2028. The above code snippet will capture that unicode variation as well.
Update... although I've only ever encountered the aforementioned characters "in the wild", to follow lmichelbacher's advice to translate even more unicode newline-like characters, use this:
select regexp_replace(field, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' )
My answer is a bit different because I've tried these methods but they didn't work. My code uses an extra class that checks for a Boolean flag in a public static class as the database values are read or where I prefer it just before an object is added to a List object or something as such. See the change in the code below. I added the ThreadWatcher.StopThread property. for this explation I'm nog going to reinstate the current thread because it's not your issue but that's as easy as setting the property to false before accessing the next thread...
private void combobox2_TextChanged(object sender, EventArgs e)
{
//Stop the thread here with this
ThreadWatcher.StopThread = true;//the rest of this thread will run normally after the database function has stopped.
if (cmbDataSourceExtractor.IsBusy)
cmbDataSourceExtractor.CancelAsync();
while(cmbDataSourceExtractor.IsBusy)
Application.DoEvents();
var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
V2 = combobox2.Text};
cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
}
all fine
private void cmbDataSourceExtractor_DoWork(object sender, DoWorkEventArgs e)
{
if (this.cmbDataSourceExtractor.CancellationPending)
{
e.Cancel = true;
return;
}
// do stuff...
}
Now add the following class
public static class ThreadWatcher
{
public static bool StopThread { get; set; }
}
and in your class where you read the database
List<SomeObject>list = new List<SomeObject>();
...
if (!reader.IsDbNull(0))
something = reader.getString(0);
someobject = new someobject(something);
if (ThreadWatcher.StopThread == true)
break;
list.Add(something);
...
don't forget to use a finally block to properly close your database connection etc. Hope this helps! Please mark me up if you find it helpful.
I thought that since the js file was already loaded, that I didn't need to load/enqueue it again in the separate add_ajax function.
But this must be necessary, or I did this and it's now working.
Hopefully will help someone else.
Here is the corrected code from the question:
// code to load jquery - working fine
// code to load javascript file - working fine
// ENABLE AJAX :
function add_ajax()
{
wp_enqueue_script(
'function',
'http://host/blog/wp-content/themes/theme/js.js',
array( 'jquery' ),
'1.0',
1
);
wp_localize_script(
'function',
'ajax_script',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
$dirName = get_stylesheet_directory(); // use this to get child theme dir
require_once ($dirName."/ajax.php");
add_action("wp_ajax_nopriv_function1", "function1"); // function in ajax.php
add_action('template_redirect', 'add_ajax');
Add maven directory /bin
to System variables under the name Path
.
To check this, you can echo %PATH%
Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.
tomcat/conf/server.xml
.<Connector port="8080" protocol="HTTP/1.1" address="127.0.0.1" connectionTimeout="20000" redirectPort="8443" />
Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.
It's better to run the subquery once, in the FROM clause, to get the max date per control number.
SELECT n.*
FROM tblpm n
INNER JOIN (
SELECT control_number, MAX(date_updated) AS date_updated
FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated);
In Swift 5, you can utilize dot notation for a bit quicker syntax:
myButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
Otherwise, you'll use:
myButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
class C:
a = 5
b = [1,2,3]
def foobar():
b = "hi"
for attr, value in C.__dict__.iteritems():
print "Attribute: " + str(attr or "")
print "Value: " + str(value or "")
Prints:
python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:
Maybe you are already using the system proxy setting - in this case unset all git proxies will work:
git config --global --unset http.proxy
git config --global --unset https.proxy
This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.
Follow below steps (assuming you are building it using CMake GUI)
Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it
Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.
Unzip the folder.
Open CMake
Click Browse Source and navigate to your openCV folder.
Click Browse Build and navigate to your build Folder.
Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.
Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)
Click Configure again, then Click Generate.
Go to build folder
# cd build
# make
# sudo make install
To access the first and last elements, try.
var nodes = div.querySelectorAll('[move_id]');
var first = nodes[0];
var last = nodes[nodes.length- 1];
For robustness, add index checks.
Yes, the order of nodes is pre-order depth-first. DOM's document order
is defined as,
There is an ordering, document order, defined on all the nodes in the document corresponding to the order in which the first character of the XML representation of each node occurs in the XML representation of the document after expansion of general entities. Thus, the document element node will be the first node. Element nodes occur before their children. Thus, document order orders element nodes in order of the occurrence of their start-tag in the XML (after expansion of entities). The attribute nodes of an element occur after the element and before its children. The relative order of attribute nodes is implementation-dependent.
With the Entity Framework most of the time SaveChanges()
is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.
Sometimes though the SaveChanges(false) + AcceptAllChanges()
pairing is useful.
The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.
I.e. something like this (bad):
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save and discard changes
context1.SaveChanges();
//Save and discard changes
context2.SaveChanges();
//if we get here things are looking good.
scope.Complete();
}
If context1.SaveChanges()
succeeds but context2.SaveChanges()
fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1
, so you can't replay or effectively log the failure.
But if you change your code to look like this:
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save Changes but don't discard yet
context1.SaveChanges(false);
//Save Changes but don't discard yet
context2.SaveChanges(false);
//if we get here things are looking good.
scope.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
While the call to SaveChanges(false)
sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager
if you want.
This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager
somewhere.
I was a bit puzzled that norm.fit
apparently only worked with the expanded list of sampled values. I tried giving it two lists of numbers, or lists of tuples, but it only appeared to flatten everything and threat the input as individual samples. Since I already have a histogram based on millions of samples, I didn't want to expand this if I didn't have to. Thankfully, the normal distribution is trivial to calculate, so...
# histogram is [(val,count)]
from math import sqrt
def normfit(hist):
n,s,ss = univar(hist)
mu = s/n
var = ss/n-mu*mu
return (mu, sqrt(var))
def univar(hist):
n = 0
s = 0
ss = 0
for v,c in hist:
n += c
s += c*v
ss += c*v*v
return n, s, ss
I'm sure this must be provided by the libraries, but as I couldn't find it anywhere, I'm posting this here instead. Feel free to point to the correct way to do it and downvote me :-)
In simplest terms,
When you say you are forking a repository, you are basically creating a copy of the original repository under your GitHub ID in your GitHub account.
and
When you say you are cloning a repository, you are creating a local copy of the original repository in your system (PC/laptop) directly without having a copy in your GitHub account.
Navigate to http://www.oracle.com/technetwork/java/javase/downloads/index.html
Under Addition Resources and Under Java SE 8 Documentation
Click Download button
Under Java SE Development Kit 8 Documentation > Java SE Development Kit 8u77 Documentation
Accept the License Agreement and click on the download zip file
Unzip the downloaded file Start the API docs from jdk-8u77-docs-all\docs\api\index.html
Navigate to http://docs.oracle.com/javase/
From Release dropdown select either of Java SE 7/6/5
In corresponding JAVA SE page and under Downloads left side menu Click JDK 7/6/5 Documentation or Java SE Documentation
Now in next page select the appropriate Java SE Development Kit 7uXX Documentation.
Accept License Agreement and click on Download zip file
Unzip the file and Start the API docs from
jdk-7uXX-docs-all\docs\api\index.html
If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString()
.
function EnableHyperLink(id) {
$('#' + id).attr('onclick', 'Pagination("' + id + '")');//onclick event which u
$('#' + id).addClass('enable-link');
$('#' + id).removeClass('disable-link');
}
function DisableHyperLink(id) {
$('#' + id).addClass('disable-link');
$('#' + id).removeClass('enable-link');
$('#' + id).removeAttr('onclick');
}
.disable-link
{
text-decoration: none !important;
color: black !important;
cursor: default;
}
.enable-link
{
text-decoration: underline !important;
color: #075798 !important;
cursor: pointer !important;
}
Try This:
$this->db->where('sell_date BETWEEN "'. date('Y-m-d', strtotime($start_date)). '" and "'. date('Y-m-d', strtotime($end_date)).'"');
Hope this will work
With .net 4 you could perhaps look at the ExpandoObject
, however, don't use it for this simple case as what would have been compile-time errors become run-time errors.
class Program
{
static void Main(string[] args)
{
dynamic employee, manager;
employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
manager = new ExpandoObject();
manager.Name = "Allison Brown";
manager.Age = 42;
manager.TeamSize = 10;
WritePerson(manager);
WritePerson(employee);
}
private static void WritePerson(dynamic person)
{
Console.WriteLine("{0} is {1} years old.",
person.Name, person.Age);
// The following statement causes an exception
// if you pass the employee object.
// Console.WriteLine("Manages {0} people", person.TeamSize);
}
}
// This code example produces the following output:
// John Smith is 33 years old.
// Allison Brown is 42 years old.
Something else worth mentioning is an anonymous type for within a method, but you need to create a class if you want to return it.
var MyStuff = new
{
PropertyName1 = 10,
PropertyName2 = "string data",
PropertyName3 = new ComplexType()
};
'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).
if( x != null && x.equals("*BINGO*") {
then do something with x...
}
If you refer to https://github.com/smalot/bootstrap-datetimepicker You need to set the date value by: $('#datetimepicker1').data('datetimepicker').setDate(new Date(value));
Your original regular expression has flaws: it wouldn't match 04:00
for example.
This may work better:
^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$
One way is to use ANSI escape sequences:
import sys
import time
for i in range(10):
print("Loading" + "." * i)
sys.stdout.write("\033[F") # Cursor up one line
time.sleep(1)
Also sometimes useful (for example if you print something shorter than before):
sys.stdout.write("\033[K") # Clear to the end of line
If you want to print in the tabular form with, then you can use this:
echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;
If you want some element to contain a value that is HTML, take a look at ngBindHtmlUnsafe.
If you want to style options in a native select, no it is not possible.
If this happens you would need to set the PATH for your environment (so that it gets the right Python from the environment and Scripts\ on Windows).
Imagine you have created an environment called py33 by using:
conda create -n py33 python=3.3 anaconda
Here the folders are created by default in Anaconda\envs, so you need to set the PATH as:
set PATH=C:\Anaconda\envs\py33\Scripts;C:\Anaconda\envs\py33;%PATH%
Now it should work in the command window:
activate py33
The line above is the Windows equivalent to the code that normally appears in the tutorials for Mac and Linux:
$ source activate py33
More info: https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/8T8i11gO39U
Does `anaconda` create a separate PYTHONPATH variable for each new environment?
Only client side problem(duplicate key for ip):
Solve variants:
For clear one ip(default port 22):
ssh-keygen -f -R 7.7.7.7
For one ip(non default port):
ssh-keygen -f -R 7.7.7.7:333
Fast clear all ips:
cd ~; rm .ssh/known_hosts
7.7.7.7 - ssh your server ip connect
333 - non standart port
Most of sample codes written here will get unexpected result with extra-zero versions. For example,
func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending
}
This method won't return true with passed version "10.3.0" in iOS "10.3". This kind of result does not make sense and they must be regarded as same version. To get accurate comparison result, we must consider comparing all of number components in version string. Plus, providing global methods in all capital letters is not a good way to go. As version type we use in our SDK is a String, it's make sense that extending comparing functionality in String.
To compare system version, all of the following examples should work.
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThan: "99.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(equalTo: UIDevice.current.systemVersion))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThan: "3.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThanOrEqualTo: "10.3.0.0.0.0.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThanOrEqualTo: "10.3"))
You can check it out in my repository here https://github.com/DragonCherry/VersionCompare
The following javascript and python scripts give identical outputs. I think it's what you are looking for.
JavaScript
new Date().toISOString()
Python
from datetime import datetime
datetime.utcnow().isoformat()[:-3]+'Z'
The output they give is the utc (zelda) time formatted as an ISO string with a 3 millisecond significant digit and appended with a Z.
2019-01-19T23:20:25.459Z
You can use
slack://
in order to open the Slack desktop application. For example, on mac, I've run:
open slack://
from the terminal and it opens the Mac desktop Slack application. Still, I didn't figure out the URL that should be used for opening a certain team, channel or message.
You can use this method to draw polyline on googleMap
// Draw polyline on map
public void drawPolyLineOnMap(List<LatLng> list) {
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(Color.RED);
polyOptions.width(5);
polyOptions.addAll(list);
googleMap.clear();
googleMap.addPolyline(polyOptions);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : list) {
builder.include(latLng);
}
final LatLngBounds bounds = builder.build();
//BOUND_PADDING is an int to specify padding of bound.. try 100.
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, BOUND_PADDING);
googleMap.animateCamera(cu);
}
You need to add this line in your gradle in case you haven't.
compile 'com.google.android.gms:play-services-maps:8.4.0'
Scott Murray wrote a great explanation of this[1]. For instance, for the code snippet:
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
He explains using the following:
Note that we use attr() to apply transform as an attribute of g. SVG transforms are quite powerful, and can accept several different kinds of transform definitions, including scales and rotations. But we are keeping it simple here with only a translation transform, which simply pushes the whole g group over and down by some amount.
Translation transforms are specified with the easy syntax of translate(x,y), where x and y are, obviously, the number of horizontal and vertical pixels by which to translate the element.
[1]: From Chapter 8, "Cleaning it up" of Interactive Data Visualization for the Web, which used to be freely available and is now behind a paywall.
Depending on your needs, like if you want to allow the data to eventually expire or set limitations on how many records to store, you could also look at https://github.com/jmdobry/angular-cache which allows you to define if the cache sits in memory, localStorage, or sessionStorage.
Since php4 you can use a string formater:
$num = 5;
$word = 'banana';
$format = 'can you say %d times the word %s';
echo sprintf($format, $num, $word);
Source: sprintf()
This is actually very simple. To disable text selection (and also click+drag-ing text (e.g a link in Chrome)), just use the following jQuery code:
$('body, html').mousedown(function(event) {
event.preventDefault();
});
All this does is prevent the default from happening when you click with your mouse (mousedown()
) in the body
and html
tags. You can very easily change the element just by changing the text in-between the two quotes (e.g change $('body, html')
to $('#myUnselectableDiv')
to make the myUnselectableDiv
div to be, well, unselectable.
A quick snippet to show/prove this to you:
$('#no-select').mousedown(function(event) {_x000D_
event.preventDefault();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="no-select">I bet you can't select this text, or drag <a href="#">this link</a>, </span>_x000D_
<br/><span>but that you can select this text, and drag <a href="#">this link</a>!</span>
_x000D_
Please note that this effect is not perfect, and performs the best while making the whole window not selectable. You might also want to add
the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)
as well, by using that section of Vladimir's answer above. (get to his post here)
if you want to find index for more than 2 occurrence:
public static int ordinalIndexOf(String fullText,String subText,int pos){
if(fullText.contains(subText)){
if(pos <= 1){
return fullText.indexOf(subText);
}else{
--pos;
return fullText.indexOf(subText, ( ordinalIndexOf(fullText,subText,pos) + 1) );
}
}else{
return -1;
}
}
It means that trackDAO
should not be serialized.
For small changes, I have used hexedit:
http://rigaux.org/hexedit.html
Simple but fast and useful.
A Git repository doesn't have a name. You can just rename the directory containing your worktree if you want.
Use "$@"
to represent all the arguments:
for var in "$@"
do
echo "$var"
done
This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:
sh test.sh 1 2 '3 4'
1
2
3 4
I used FPDF v. 1.53 and didn't want to upgrade because of possible side effects. I used the following code according to Yacoby:
Line 1164:
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
$mqr=get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
}
Line 1203:
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
set_magic_quotes_runtime($mqr);
}
Local storage: It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.
//Set the value in a local storage object
localStorage.setItem('name', myName);
//Get the value from storage object
localStorage.getItem('name');
//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege
Session Storage: It is same like local storage date except it will delete all windows when browser windows closed by a web user.
//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";
Read More Click
It ignores the cached content when refreshing...
https://support.google.com/a/answer/3001912?hl=en
F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content
You need to set ulimit -c
. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited
and check if everything is correct ulimit -a
. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>
.
You can use full datetime
variables with timedelta
, and by providing a dummy date then using time
to just get the time value.
For example:
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())
results in the two values, three seconds apart:
11:34:59
11:35:02
You could also opt for the more readable
b = a + datetime.timedelta(seconds=3)
if you're so inclined.
If you're after a function that can do this, you can look into using addSecs
below:
import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)
This outputs:
09:11:55.775695
09:16:55
Depending on your platform you can use: sqlite3 file_name.db from the terminal. .tables will list the tables, .schema is full layout. SQLite commands like: select * from table_name; and such will print out the full contents. Type: ".exit" to exit. No need to download a GUI application.Use a semi-colon if you want it to execute a single command. Decent SQLite usage tutorial http://www.thegeekstuff.com/2012/09/sqlite-command-examples/
Use the DateValue()
function to convert a string
to date
data type. That's the easiest way of doing this.
DateValue(String Date)
Looking at the error message, part of the code of your Default.aspx
is :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AmeriaTestTask.Default" %>
but AmeriaTestTask.Default
does not exists, so you have to change it, most probably to the class defined in Default.aspx.cs. For example for web api aplications, the class defined in Global.asax.cs is : public class WebApiApplication : System.Web.HttpApplication
and in the asax page you have :
<%@ Application Codebehind="Global.asax.cs" Inherits="MyProject.WebApiApplication" Language="C#" %>
Add below properties to the Edittext controller in the layout file
<Edittext
android:focusableInTouchMode="true"
android:cursorVisible="false"
android:focusable="false" />
I have been using this solution for while and it works fine for me.
you can do:
for k in ax.get_xmajorticklabels():
if some-condition:
k.set_color(any_colour_you_like)
draw()
I think that there is a more simple approach to all given here, and is the method Number.toFixed()
already implemented in JavaScript.
simply write:
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
etc...
If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html
If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/
You should be installing grunt-cli to the devDependencies of the project and then running it via a script in your package.json. This way other developers that work on the project will all be using the same version of grunt and don't also have to install globally as part of the setup.
Install grunt-cli with npm i -D grunt-cli
instead of installing it globally with -g
.
//package.json
...
"scripts": {
"build": "grunt"
}
Then use npm run build
to fire off grunt.
You can do this in many ways before clicking on add items:
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid")));// instead of id u can use cssSelector or xpath of ur element.
or
wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));
You can also wait like this. If you want to wait until invisible of previous page element:
wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));
Here is the link where you can find all the Selenium WebDriver APIs that can be used for wait
and its documentation.
For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root
can run smoothly.
The simplest change would be something like this:
public static void main (String[] args) throws Exception {
testconnect obj = new testconnect();
obj.con2 = DriverManager.getConnection(obj.getConnectionUrl2());
obj.con2.close();
}
There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);
BOOST_FOREACH(std::string const& token, tokens)
{
std::cout << "<" << *tok_iter << "> " << "\n";
}
If you want revert last commit listen:
Step 1:
Check your local commits with messages
$ git log
Step 2:
Remove last commit without resetting the changes from local branch (or master)
$ git reset HEAD^
OR if you don't want last commit files and updates listens
$ git reset HEAD^ --hard
Step 3:
We can update the files and codes and again need to push with force it will delete previous commit. It will keep new commit.
$ git push origin branch -f
That's it!
WCF = Windows COMMUNICATION Foundation
WPF = Windows PRESENTATION Foundation.
WCF deals with communication (in simple terms - sending and receiving data as well as formatting and serialization involved), WPF deals with presentation (UI)
The following ex commands will (re-)split any number of windows:
:vertical ball
:ball
If there are hidden buffers, issuing these commands will also make the hidden buffers visible.
Add
background-size:100% 100%;
to your css underneath background-image.
You can also specify exact dimensions, i.e.:
background-size: 30px 40px;
Here: JSFiddle
int days = (int) (milliseconds / 86 400 000 )
The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:
=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60
I use the following piece of CSS and JavaScript. It uses an extra class dropdown-submenu
. I tested it with Bootstrap 4 beta.
It supports multi level sub menus.
$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {_x000D_
if (!$(this).next().hasClass('show')) {_x000D_
$(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
}_x000D_
var $subMenu = $(this).next('.dropdown-menu');_x000D_
$subMenu.toggleClass('show');_x000D_
_x000D_
_x000D_
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
$('.dropdown-submenu .show').removeClass('show');_x000D_
});_x000D_
_x000D_
_x000D_
return false;_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu a::after {_x000D_
transform: rotate(-90deg);_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: .8em;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
top: 0;_x000D_
left: 100%;_x000D_
margin-left: .1rem;_x000D_
margin-right: .1rem;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<li><a class="dropdown-item" href="#">Action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li class="dropdown-submenu">_x000D_
<a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
_x000D_
_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
I would recommend overriding the onResume()
method in activity number 1, and in there include code to refresh your array adapter, this is done by using [yourListViewAdapater].notifyDataSetChanged();
Read this if you are having trouble refreshing the list: Android List view refresh
I found the solution now based on https://github.com/FasterXML/jackson-module-hibernate
I extended the object mapper and added the attributes in the inherited constructor.
Then the new object mapper is registered as a bean.
<!-- https://github.com/FasterXML/jackson-module-hibernate -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<array>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<bean class="de.company.backend.spring.PtxObjectMapper"/>
</property>
</bean>
</array>
</property>
</bean>
You cannot simply add a link using CSS. CSS is used for styling.
You can style your using CSS.
If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.
You can accomplish that very easily using jQuery.
I have done a sample for you. You can refer that.
$('#link').attr('href','http://www.google.com');
This single line will do the trick.
I created this little function that replaces string on string (case-sensitive) with limit, without the need of Regexp. It works fine.
function str_replace_limit($search, $replace, $string, $limit = 1) {
$pos = strpos($string, $search);
if ($pos === false) {
return $string;
}
$searchLen = strlen($search);
for ($i = 0; $i < $limit; $i++) {
$string = substr_replace($string, $replace, $pos, $searchLen);
$pos = strpos($string, $search);
if ($pos === false) {
break;
}
}
return $string;
}
Example usage:
$search = 'foo';
$replace = 'bar';
$string = 'foo wizard makes foo brew for evil foo and jack';
$limit = 2;
$replaced = str_replace_limit($search, $replace, $string, $limit);
echo $replaced;
// bar wizard makes bar brew for evil foo and jack
Maybe this will help for beginners
<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8">
<title></title>
<link rel="icon" href="favicon.ico">
<link rel="stylesheet" href="custom.css">
</head>
<body>
<div ng-include src="'view/01.html'"></div>
<div ng-include src="'view/02.html'"></div>
<script src="angular.min.js"></script>
</body>
</html>
I figured it out myself. I need
select extract(day from sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) from dual
A 32-bit process is still limited to the same constraints in a 64-bit OS. The issue is that memory pointers are only 32-bits wide, so the program can't assign/resolve any memory address larger than 32 bits.
Example for any language:
'My name is ??????'.toLocaleLowerCase().includes('??????'.toLocaleLowerCase())
As said a previous answer, you can run the command
jest -t 'fix-order-test'
If you have an it
inside of a describe
block, you have to run
jest -t '<describeString> <itString>'
2 things FYI -
Just to extend the answer from @Rockney and @k2col the improved code can look like:
@NonNull
public static Spanned fromHtml(@NonNull String html) {
if (CompatUtils.isApiNonLowerThan(VERSION_CODES.N)) {
return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
} else {
//noinspection deprecation
return Html.fromHtml(html);
}
}
Where the CompatUtils.isApiNonLowerThan
:
public static boolean isApiNonLowerThan(int versionCode) {
return Build.VERSION.SDK_INT >= versionCode;
}
The difference is that there are no extra local variable and the deprecation is only in else
branch. So this will not suppress all method but single branch.
It can help when the Google will decide in some future versions of Android to deprecate even the fromHtml(String source, int flags)
method.
There are a number of ways of Calling an external Command from Python. There are some Functions and Modules with the Good Helper Functions that can make it really easy. But the Recommended among all is the Subprocess
Module.
import subprocess as s
s.call(["command.exe","..."])
Call function will start the external process, pass some command line arguments and wait for it to finish. When it finishes you continue executing. Arguments in Call function are passed through the list. The first argument in the list is the command typically in the form of an executable file and subsequent arguments in the list whatever you want to pass.
If you have called processes from the command line in the windows before you'll be aware that you often need to quote arguments. You need to put quotations mark around it, if there's a space then there's a backslash and there are some complicated rules but you can avoid a whole lot of that in python by using subprocess
module because it is a list and each item is known to be a distinct and python can get quoting correctly for you.
In the end, after the list, there are a number of optional parameters one of these is a shell and if you set shell equals to true then your command is going to be run as if you have typed in at the command prompt.
s.call(["command.exe","..."], shell=True)
This gives you access to functionality like piping, you can redirect to files, you can call multiple commands in one thing.
One more thing, if your script relies on the process succeeding then you want to check the result and the result can be checked with the check call helper function.
s.check_call(...)
It is exactly the same as a call function, it takes the same arguments, takes the same list, you can pass in any of the extra arguments but it going to wait for the functions to complete. And if the exit code of the function is anything other then zero, it will through an exception in the python script.
Finally, if you want tighter control Popen
constructor which is also from the subprocess
module. It also takes the same arguments as incall & check_call function but it returns an object representing the running process.
p=s.Popen("...")
It does not wait for the running process to finish also it's not going to throw any exception immediately but it gives you an object that will let you do things like wait for it to finish, let you communicate to it, you can redirect standard input, standard output if you want to display output somewhere else and a lot more.
$name=array();
while($result=mysql_fetch_array($res)) {
$name[]=array('Id'=>$result['id']);
// here you want to fetch all
// records from table like this.
// then you should get the array
// from all rows into one array
}
try this tool https://github.com/kamranahmedse/git-standup
```bash
$ git standup [-a <author name>]
[-w <weekstart-weekend>]
[-m <max-dir-depth>]
[-f]
[-L]
[-d <days-ago>]
[-D <date-format>]
[-g]
[-h]
```
Below is the description for each of the flags
- `-a` - Specify author to restrict search to (name or email)
- `-w` - Specify weekday range to limit search to (e.g. `git standup -w SUN-THU`)
- `-m` - Specify the depth of recursive directory search
- `-L` - Toggle inclusion of symbolic links in recursive directory search
- `-d` - Specify the number of days back to include
- `-D` - Specify the date format for "git log" (default: relative)
- `-h` - Display the help screen
- `-g` - Show if commit is GPG signed or not
- `-f` - Fetch the latest commits beforehand
Option 1:
NSString *haystack = @"value:hello World:value";
NSString *haystackPrefix = @"value:";
NSString *haystackSuffix = @":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle); // -> "hello World"
Option 2:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];
This one might be a bit over the top for your rather trivial case though.
Option 3:
NSString *needle = [haystack componentsSeparatedByString:@":"][1];
This one creates three temporary strings and an array while splitting.
All snippets assume that what's searched for is actually contained in the string.
Using DatabaseUtils.queryNumEntries()
:
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
or (more inefficiently)
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
In Activity:
int profile_counts = db.getProfilesCount();
db.close();
If you can not use *ngif, [class.hide] works in angular 7. example:
<mat-select (selectionChange)="changeFilter($event.value)" multiple [(ngModel)]="selected">
<mat-option *ngFor="let filter of gridOptions.columnDefs"
[class.hide]="filter.headerName=='Action'" [value]="filter.field">{{filter.headerName}}</mat-option>
</mat-select>
replace the query inside your model function with this
$query = $this->db->query("SELECT id FROM home");
in view:
echo $query->num_rows();
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String
in as the string-to-match argument to the string.replace
method, it doesn't do a string replace. It converts the string to a RegExp
and does a regex substitution. As Gumbo explains, a regex substitution requires the g
?lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
If you've only got one DataView, you can sort using that instead:
table.DefaultView.Sort = "columnName asc";
Haven't tried it, but I guess you can do this with any number of DataViews, as long as you reference the right one.
You can get the favicon showing up in Django the same way you can do in any other framework: just use pure HTML.
Add the following code to the header of your HTML template.
Better, to your base HTML template if the favicon is the same across your application.
<link rel="shortcut icon" href="{% static 'favicon/favicon.png' %}"/>
The previous code assumes:
You can find useful information about file format support and how to use favicons in this article of Wikipedia https://en.wikipedia.org/wiki/Favicon.
I can recommend use .png
for universal browser compatibility.
EDIT:
As posted in one comment,
"Don't forget to add {% load staticfiles %}
in top of your template file!"
I assume you're looking for this:
string[,] Tablero = new string[3,3];
The syntax for a jagged array is:
string[][] Tablero = new string[3][];
for (int ix = 0; ix < 3; ++ix) {
Tablero[ix] = new string[3];
}
Bind-address XXX.XX.XX.XXX in /etc/my.cnf
comment line:
or
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
quit;
add firewall rule:
iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT
I've found a way to get only the Contacts application:
git clone https://android.googlesource.com/platform/packages/apps/Contacts
which is good enough for me for now, but doesn't answer the question of browsing the code on the web.
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
I struggled for half a day to get JSCH to work without using the System.in as the input stream to no avail. I tried Ganymed http://www.ganymed.ethz.ch/ssh2/ and had it going in 5 minutes. All the examples seem to be aimed at one usage of the app and none of the examples showed what i needed. Ganymed's example Basic.java Baaaboof Has everything i need.
I migrated my mac, and it unlinked all my homebrew installs - including OpenSSL. This broke gem install
, which is how I first noticed the problem and started trying to repair this.
After a million solutions (when migrating to OSX Sierra - 10.12.5), the solution ended up being comically simple:
brew reinstall ruby
brew reinstall openssl
The best way to check for named elements is to use exist()
, however the above answers are not using the function properly. You need to use the where
argument to check for the variable within the list.
foo <- list(a=42, b=NULL)
exists('a', where=foo) #TRUE
exists('b', where=foo) #TRUE
exists('c', where=foo) #FALSE
No, Java doesn't support user-defined operator overloading. The only aspect of Java which comes close to "custom" operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer. You can't define your own operators which act in the same way though.
For a Java-like (and JVM-based) language which does support operator overloading, you could look at Kotlin or Groovy. Alternatively, you might find luck with a Java compiler plugin solution.
for bootstrap 4 documentation
<div class="row justify-content-end">
<div class="col-4">
Start of the row
</div>
<div class="col-4">
End of the row
</div>
</div>
Try this:
export CURLNAME="john:@31&3*J"
curl -d -u "${CURLNAME}" https://www.example.com
String#toLowerCase and String#toUpperCase are the methods you need.
If you want to add the absent serialVersionUID for a bunch of files, IntelliJ IDEA may not work very well. I come up some simple script to fulfill this goal with ease:
base_dir=$(pwd)
src_dir=$base_dir/src/main/java
ic_api_cp=$base_dir/target/classes
while read f
do
clazz=${f//\//.}
clazz=${clazz/%.java/}
seruidstr=$(serialver -classpath $ic_api_cp $clazz | cut -d ':' -f 2 | sed -e 's/^\s\+//')
perl -ni.bak -e "print $_; printf qq{%s\n}, q{ private $seruidstr} if /public class/" $src_dir/$f
done
You save this script, say as add_serialVersionUID.sh
in your ~/bin
folder. Then you run it in the root directory of your Maven or Gradle project like:
add_serialVersionUID.sh < myJavaToAmend.lst
This .lst includes the list of Java files to add the serialVersionUID in the following format:
com/abc/ic/api/model/domain/item/BizOrderTransDO.java
com/abc/ic/api/model/domain/item/CardPassFeature.java
com/abc/ic/api/model/domain/item/CategoryFeature.java
com/abc/ic/api/model/domain/item/GoodsFeature.java
com/abc/ic/api/model/domain/item/ItemFeature.java
com/abc/ic/api/model/domain/item/ItemPicUrls.java
com/abc/ic/api/model/domain/item/ItemSkuDO.java
com/abc/ic/api/model/domain/serve/ServeCategoryFeature.java
com/abc/ic/api/model/domain/serve/ServeFeature.java
com/abc/ic/api/model/param/depot/DepotItemDTO.java
com/abc/ic/api/model/param/depot/DepotItemQueryDTO.java
com/abc/ic/api/model/param/depot/InDepotDTO.java
com/abc/ic/api/model/param/depot/OutDepotDTO.java
This script uses the JDK serialVer tool. It is ideal for a situation when you want to amend a huge number of classes which had no serialVersionUID set in the first place while maintain the compatibility with the old classes.
if you want to select a single value then use
$('#select').val(1).change()
if you want to select multiple values then set value in array so you can use this code
$('#select').val([1,2,3]).change()
I want to add something on @Michael Laffargue's post:
jqXHR.done()
is faster!
jqXHR.success()
have some load time in callback and sometimes can overkill script. I find that on hard way before.
UPDATE:
Using jqXHR.done()
, jqXHR.fail()
and jqXHR.always()
you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:
/* Initialize some your AJAX function */
function call_ajax(attr){
var settings=$.extend({
call : 'users',
option : 'list'
}, attr );
return $.ajax({
type: "POST",
url: "//exapmple.com//ajax.php",
data: settings,
cache : false
});
}
/* .... Somewhere in your code ..... */
call_ajax({
/* ... */
id : 10,
option : 'edit_user'
change : {
name : 'John Doe'
}
/* ... */
}).done(function(data){
/* DO SOMETHING AWESOME */
});
What was working for me (ASP.NET Core), was to set return type ContentResult
, then wrap the HMTL into it and set the ContentType to "text/html; charset=UTF-8"
. That is important, because, otherwise it will not be interpreted as HTML and the HTML language would be displayed as text.
Here's the example, part of a Controller class:
/// <summary>
/// Startup message displayed in browser.
/// </summary>
/// <returns>HTML result</returns>
[HttpGet]
public ContentResult Get()
{
var result = Content("<html><title>DEMO</title><head><h2>Demo started successfully."
+ "<br/>Use <b><a href=\"http://localhost:5000/swagger\">Swagger</a></b>"
+ " to view API.</h2></head><body/></html>");
result.ContentType = "text/html; charset=UTF-8";
return result;
}
To address the --rebase
vs. --merge
option:
Let's say you have super repository A and submodule B and want to do some work in submodule B. You've done your homework and know that after calling
git submodule update
you are in a HEAD-less state, so any commits you do at this point are hard to get back to. So, you've started work on a new branch in submodule B
cd B
git checkout -b bestIdeaForBEver
<do work>
Meanwhile, someone else in project A has decided that the latest and greatest version of B is really what A deserves. You, out of habit, merge the most recent changes down and update your submodules.
<in A>
git merge develop
git submodule update
Oh noes! You're back in a headless state again, probably because B is now pointing to the SHA associated with B's new tip, or some other commit. If only you had:
git merge develop
git submodule update --rebase
Fast-forwarded bestIdeaForBEver to b798edfdsf1191f8b140ea325685c4da19a9d437.
Submodule path 'B': rebased into 'b798ecsdf71191f8b140ea325685c4da19a9d437'
Now that best idea ever for B has been rebased onto the new commit, and more importantly, you are still on your development branch for B, not in a headless state!
(The --merge
will merge changes from beforeUpdateSHA to afterUpdateSHA into your working branch, as opposed to rebasing your changes onto afterUpdateSHA.)
You should use something like this:
<div style="text-align:center">
<input type="submit" />
</div>
Or you could use something like this. By giving the element a width and specifying auto
for the left and right margins the element will center itself in its parent.
<input type="submit" style="width: 300px; margin: 0 auto;" />
This works for making disabled select options act as headers. It doesnt remove the default text shadow of the :disabled option but it does remove the hover effect. In IE you wont get the font color but at least the text-shadow is gone. Here is the html and css:
select option.disabled:disabled{color: #5C3333;background-color: #fff;font-weight: bold;}_x000D_
select option.disabled:hover{color: #5C3333 !important;background-color: #fff;}_x000D_
select option:hover{color: #fde8c4;background-color: #5C3333;}
_x000D_
<select>_x000D_
<option class="disabled" disabled>Header1</option>_x000D_
<option>Item1</option>_x000D_
<option>Item1</option>_x000D_
<option>Item1</option>_x000D_
<option class="disabled" disabled>Header2</option>_x000D_
<option>Item2</option>_x000D_
<option>Item2</option>_x000D_
<option>Item2</option>_x000D_
<option class="disabled" disabled>Header3</option>_x000D_
<option>Item3</option>_x000D_
<option>Item3</option>_x000D_
<option>Item3</option>_x000D_
</select>
_x000D_
Above steps resolved my issuses.
Another option, see logging options in settings.py described by this post
http://dabapps.com/blog/logging-sql-queries-django-13/
debug_toolbar slows down each page load on your dev server, logging does not so it's faster. Outputs can be dumped to console or file, so the UI is not as nice. But for views with lots of SQLs, it can take a long time to debug and optimize the SQLs through debug_toolbar since each page load is so slow.
Javascript doesn't have access to the user's filesystem for security reasons. FileReader
is only for files manually selected by the user.
After checking the permission of the folder, it is okay with 744. I had the problem with a plugin that is installed on my WordPress site. The plugin has hooked that are in the corn job I suspected.
With a simple sudo it can fix the issue
sudo git pull origin master
You have it working.
give input through your keyboard
a=float(input("enter the 1st number : "))
b=float(input("enter the 2nd number : "))
c=float(input("enter the 3rd number : "))
calculate the discriminant
d = (b**2) - (4*a*c)
possible solution are
sol_1 = (-b-(0.5**d))/(2*a)
sol_2 = (-b+(0.5**d))/(2*a)
print the result
print('The solution are %0.f,%0.f'%(sol_1,sol_2))
According to http://www.php.net/manual/en/function.is-numeric.php, is_numeric alows something like "+0123.45e6" or "0xFF". I think this not what you expect.
preg_match can be slow, and you can have something like 0000 or 0051.
I prefer using ctype_digit (works only with strings, it's ok with $_GET).
<?php
$id = $_GET['id'];
if (ctype_digit($id)) {
echo 'ok';
} else {
echo 'nok';
}
?>
The problem is that these two queries are each returning more than one row:
select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')
select isbn from dbo.lending where lended_date between @fdate and @tdate
You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1
), OR you can switch your =
to IN
and return multiple rows, like this:
select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))
You state that you want to encrypt/decrypt a password. I'm not sure exactly of what your specific use case is but, generally, passwords are not stored in a form where they can be decrypted. General practice is to salt the password and use suitably powerful one-way hash (such as PBKDF2).
Take a look at the following link for more information.
You can use the following code:
function isTouchDevice() {
var el = document.createElement('div');
el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
return typeof el.ongesturestart === "function";
}
Source: Detecting touch-based browsing and @mplungjan post.
The above solution was based on detecting event support without browser sniffing article.
You can check the results at the following test page.
Please note that the above code tests only whether the browser has support for touch, not the device. So if you've laptop with touch-screen, your browser may not have the support for the touch events. The recent Chrome supports touch events, but other browser may not.
You could also try:
if (document.documentElement.ontouchmove) {
// ...
}
but it may not work on iPhone devices.
For those of you using python3 you can use:
python3 setup.py install
Cross-browser rotate for any element. Works in IE7 and IE8. In IE7 it looks like not working in JSFiddle but in my project worked also in IE7
var elementToRotate = $('#rotateMe');
var degreeOfRotation = 33;
var deg = degreeOfRotation;
var deg2radians = Math.PI * 2 / 360;
var rad = deg * deg2radians ;
var costheta = Math.cos(rad);
var sintheta = Math.sin(rad);
var m11 = costheta;
var m12 = -sintheta;
var m21 = sintheta;
var m22 = costheta;
var matrixValues = 'M11=' + m11 + ', M12='+ m12 +', M21='+ m21 +', M22='+ m22;
elementToRotate.css('-webkit-transform','rotate('+deg+'deg)')
.css('-moz-transform','rotate('+deg+'deg)')
.css('-ms-transform','rotate('+deg+'deg)')
.css('transform','rotate('+deg+'deg)')
.css('filter', 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')')
.css('-ms-filter', 'progid:DXImageTransform.Microsoft.Matrix(SizingMethod=\'auto expand\','+matrixValues+')');
Edit 13/09/13 15:00 Wrapped in a nice and easy, chainable, jquery plugin.
Example of use
$.fn.rotateElement = function(angle) {
var elementToRotate = this,
deg = angle,
deg2radians = Math.PI * 2 / 360,
rad = deg * deg2radians ,
costheta = Math.cos(rad),
sintheta = Math.sin(rad),
m11 = costheta,
m12 = -sintheta,
m21 = sintheta,
m22 = costheta,
matrixValues = 'M11=' + m11 + ', M12='+ m12 +', M21='+ m21 +', M22='+ m22;
elementToRotate.css('-webkit-transform','rotate('+deg+'deg)')
.css('-moz-transform','rotate('+deg+'deg)')
.css('-ms-transform','rotate('+deg+'deg)')
.css('transform','rotate('+deg+'deg)')
.css('filter', 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')')
.css('-ms-filter', 'progid:DXImageTransform.Microsoft.Matrix(SizingMethod=\'auto expand\','+matrixValues+')');
return elementToRotate;
}
$element.rotateElement(15);
JSFiddle: http://jsfiddle.net/RgX86/175/
An activity populates the ActionBar in its onCreateOptionsMenu()
method.
Instead of using setcustomview()
, just override onCreateOptionsMenu
like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
If an actions in the ActionBar is selected, the onOptionsItemSelected()
method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
break;
case R.id.menuitem2:
Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
had the same problem; my issue was selinux was set to enforcing.
I kept getting the "failed to open stream: Permission denied" error even after chmoding to 777 and making sure all parent folders had execute permissions for the apache user. Turns out my issue was that selinux was set to enforcing (I'm on centos7), this is a devbox so I turned it off.
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
You have to enable USB debugging before plugging your device in to the computer. Unplug device then try to enable USB debugging. This should work. If so, you can then plug it back into the computer and it should work
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
You can achieve this by two methods
Using XML Add this attribute to toolbar XML app:menu = "menu_name"
Using java By overriding onCreateOptionMenu(Menu menu)
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.demo_menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
for more details or implementating click on the menu go through this article https://bedevelopers.tech/android-toolbar-implementation-using-android-studio/
I used the code that provided Erik, works great, but i have a complex custom adapter for my listview and i was confronted with twice implementation of the code that updates the UI. I've tried to get the new view from my adapters getView method(the arraylist that holds the listview data has allready been updated/changed):
View cell = lvOptim.getChildAt(index - lvOptim.getFirstVisiblePosition());
if(cell!=null){
cell = adapter.getView(index, cell, lvOptim); //public View getView(final int position, View convertView, ViewGroup parent)
cell.startAnimation(animationLeftIn());
}
It's working well, but i dont know if this is a good practice. So i don't need to implement the code that updates the list item two times.
Don't do things like [A-Z] or [0-9]. Do \p{Lu} and \d instead. Of course, this is valid for perl based regex flavours. This includes java.
I would suggest that you don't make some huge regex. First split the text in sentences. then tokenize it (split into words). Use a regex to check each token/word. Skip the first token from sentence. Check if all tokens are uppercase beforehand and skip the whole sentence if so, or alter the regex in this case.
You can simply set xhr.responseType = 'json';
const xhr = new XMLHttpRequest();_x000D_
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');_x000D_
xhr.responseType = 'json';_x000D_
xhr.onload = function(e) {_x000D_
if (this.status == 200) {_x000D_
console.log('response', this.response); // JSON response _x000D_
}_x000D_
};_x000D_
xhr.send();_x000D_
_x000D_
You can fill your data table like the below code.I am also fetching the connections at runtime using a predefined XML file that has all the connection.
public static DataTable Execute_Query(string connection, string query)
{
Logger.Info("Execute Query has been called for connection " + connection);
connection = "Data Source=" + Connections.run_singlevalue(connection, "server") + ";Initial Catalog=" + Connections.run_singlevalue(connection, "database") + ";User ID=" + Connections.run_singlevalue(connection, "username") + ";Password=" + Connections.run_singlevalue(connection, "password") + ";Connection Timeout=30;";
DataTable dt = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(connection))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.SelectCommand.CommandTimeout = 1800;
da.Fill(dt);
}
con.Close();
}
}
Logger.Info("Execute Query success");
return dt;
}
catch (Exception ex)
{
Console.Write(ex.Message);
return null;
}
}
After trying @regeter's solution and seeing it didn't solve my problem when I was searching for a foreign/primary key to see all tables/columns where it exists, it didn't work. After reading how it failed for another who tried to use a unique identifier, I have made the modifications and here is the updated result: (works with both int, and guids... you will see how to easily extend)
CREATE PROC [dbo].[SearchAllTables_Like]
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('guid', 'int', 'char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
I checked all the answers but informing only to kill PID
.
In case if you have terminal access shared by all it will not help or maybe you do not have permission to kill PID.
In this case what you can do is:
Double click on server
Go to Overview and change ports in Ports
like this:
It worked for me
virtualenv --no-site-packages --distribute -p /usr/bin/python3 ~/.virtualenvs/py3
Add pointer-events: none;
to the overlay.
Original answer: My suggestion would be that you could capture the click event with the overlay, hide the overlay, then refire the click event, then display the overlay again. I'm not sure if you'd get a flicker effect though.
[Update] Exactly this problem and exactly my solution just appeared in this post: "Forwarding Mouse Events Through Layers". I know its probably a little late for the OP, but for the sake of somebody having this problem in the future, I though I would include it.
For ASP.NET Core You can use asp-route-* attribute:
<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">
An example: Imagine that you have a Vehicle Controller with actions
Index
Details
Edit
and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.
//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
..............
..............
public string ReturnUrl {get;set;}
}
Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>
Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>
Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
<div class="box-footer">
<a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
<button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
</div>
</form>
In your controller:
// GET: Vehicle/Edit/5
public ActionResult Edit(int id,string previous)
{
var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
//or by this code if you are not use automapper
var viewModel = new VehicleViewModel();
if (!string.IsNullOrWhiteSpace(previous)
viewModel.ReturnUrl = previous;
else
viewModel.ReturnUrl = "Index";
return View(viewModel);
}
[HttpPost]
public IActionResult Edit(VehicleViewModel model, string previous)
{
if (!string.IsNullOrWhiteSpace(previous))
model.ReturnUrl = previous;
else
model.ReturnUrl = "Index";
.............
.............
return RedirectToAction(model.ReturnUrl);
}
If using Nginx
and getting a similar problem, then this might help:
Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.
If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
To go up a directory in a link, use ..
. This means "go up one directory", so your link will look something like this:
<a href="../index.html">Home</a>
I had the same problem in Windows. I solved it adding: include mime.types; under http{ in my nginx.conf file. Then it still didn't work.. so I looked at the error.log file and I noticed it was trying to charge the .css and javascript files from the file path but with an /http folder between. Ex: my .css was in : "C:\Users\pc\Documents\nginx-server/player-web/css/index.css" and it was taking it from: "C:\Users\pc\Documents\nginx-server/html/player-web/css/index.css" So i changed my player-web folder inside an html folder and it worked ;)
No need to use str.replace
or string.replace
here, just convert that string to a raw string:
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
Below is the repr
version of the above string, that's why you're seeing \\
here.
But, in fact the actual string contains just '\'
not \\
.
>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'
>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3
But when you're going to print this string you'll not get '\\'
in the output.
>>> print strs
C:\Users\Josh\Desktop\20130216
If you want the string to show '\\'
during print
then use str.replace
:
>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
repr
version will now show \\\\
:
>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
Sample programs as follows and provided on link also https://oracle-concepts-learning.blogspot.com/
plsql table or associated array.
DECLARE
TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20);
salary_list salary;
name VARCHAR2(20);
BEGIN
-- adding elements to the table
salary_list('Rajnish') := 62000; salary_list('Minakshi') := 75000;
salary_list('Martin') := 100000; salary_list('James') := 78000;
-- printing the table name := salary_list.FIRST; WHILE name IS NOT null
LOOP
dbms_output.put_line ('Salary of ' || name || ' is ' ||
TO_CHAR(salary_list(name)));
name := salary_list.NEXT(name);
END LOOP;
END;
/
Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch()
to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.
Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.
If you have access to JavaScript, you can create an element and read its computed style.
function defaultValueOfCssPropertyForElement(cssPropertyName, elementTagName, opt_pseudoElement) {
var pseudoElement = opt_pseudoElement || null;
var element = document.createElement(elementTagName);
document.body.appendChild(element);
var computedStyle = getComputedStyle(element, pseudoElement)[cssPropertyName];
element.remove();
return computedStyle;
}
// Usage:
defaultValueOfCssPropertyForElement('display', 'div'); // Output: 'block'
defaultValueOfCssPropertyForElement('content', 'div', ':after'); // Output: 'none'
I wrote a code used to count vowels. You may use this to count any character of your choosing. I hope this helps! (coded in Python 3.6.0)
while(True):
phrase = input('Enter phrase you wish to count vowels: ')
if phrase == 'end': #This will to be used to end the loop
quit() #You may use break command if you don't wish to quit
lower = str.lower(phrase) #Will make string lower case
convert = list(lower) #Convert sting into a list
a = convert.count('a') #This will count letter for the letter a
e = convert.count('e')
i = convert.count('i')
o = convert.count('o')
u = convert.count('u')
vowel = a + e + i + o + u #Used to find total sum of vowels
print ('Total vowels = ', vowel)
print ('a = ', a)
print ('e = ', e)
print ('i = ', i)
print ('o = ', o)
print ('u = ', u)
A possible workaround that allows to enable database session timeout without an external scheduled task is to use the extension pg_timeout that I have developped.
AndAlso is much like And, except it works like && in C#, C++, etc.
The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".
This is sometimes very useful, e.g. in an expression such as:
If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
...
End If
Using the old And in the above expression would throw a NullReferenceException if myObj were null.
with a little help of math
#include <math.h>
int main(){
int a = -1;
unsigned int b;
b = abs(a);
}
These configurations worked in January of 2020 on my new machine build:
(1 - x64 only) Windows 10 x64, Office 365 x64, AccessDatabaseEngine_x64 2016 installed with /passive argument, VStudio build settings set to x64 explicitly, with the following connection string: Provider= Microsoft.ACE.OLEDB.16.0; Data Source=D:...\MyDatabase.accdb
(2 - x64 or x32) Windows 10 x64, Office 365 x64, AccessDatabaseEngine_x64 2016 installed with /passive argument, PLUS AccessDatabaseEngine 2010 (32bit) installed with /passive argument, VStudio build settings set to AnyCPU, with the following connection string: Provider= Microsoft.ACE.OLEDB.16.0; Data Source=D:...\MyDatabase.accdb
(3 - x32 only) Windows 10 x64, Office 365 x32, AccessDatabaseEngine 2010 (32bit) installed with /passive argument, VStudio build settings set to x86, with the following connection string: Provider= Microsoft.ACE.OLEDB.12.0; Data Source=D:...\MyDatabase.accdb
FAILURE NOTES
Using the ACE.OLEDB.12.0 x64 provider in the connection string failed with only the AccessDatabaseEngine_x64 2016 installed as above in (1).
Using AnyCPU in the visual studio build settings failed in (1). Setting x64 is required. Maybe this is because AnyCPU means that Vstudio must see an x32 ACE.OLEDB.nn.0 provider at compile time.
The ACE.OLEDB.12.0 2016 x32 /passive engine would NOT install when it saw x64 applications around. (The ACE.OLEDB.12.0 2010 x32 /passive installer worked.)
CONCLUSIONS
To use x64 build settings, you need to have the 2016 x64 database engine AND the ACE.OLEDB.16.0 connection-string provider AND explicit x64 build settings to work with Office 365 in January of 2020. Using the /passive option makes installations easy. Credit to whoever posted that tip!
To use AnyCPU, I needed to have both the ACE.OLEDB.12.0 2010 x32 engine and the ACE.OLEDB.16.0 x64 engines installed. That way Vstudio could see both x32 and x64 engines at "AnyCPU" compile time. I could change the provider connection string to ACE.OLEDB.12.0 for x32 operation or to ACE.OLEDB.16.0 for x64 operation. Both worked fine.
To use x86 build settings, you need to have the 2010 x32 database engine AND the ACE.OLEDB.12.0 connection-string provider AND explicit x86 build settings to work with Office 365 x32 in January of 2020.
Use the hasClass
method:
jQueryCollection.hasClass(className);
or
$(selector).hasClass(className);
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
Note: If you pass a className
argument that contains whitespace, it will be matched literally against the collection's elements' className
string. So if, for instance, you have an element,
<span class="foo bar" />
then this will return true
:
$('span').hasClass('foo bar')
and these will return false
:
$('span').hasClass('bar foo')
$('span').hasClass('foo bar')
You can do this way:
String cert = DataAccessUtils.singleResult(
jdbcTemplate.queryForList(
"select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN where ID_STR_RT = :id_str_rt and ID_NMB_SRZ = :id_nmb_srz",
new MapSqlParameterSource()
.addValue("id_str_rt", "999")
.addValue("id_nmb_srz", "60230009999999"),
String.class
)
)
DataAccessUtils.singleResult + queryForList:
You should use profiles.
<profiles>
<profile>
<id>otherOutputDir</id>
<build>
<directory>yourDirectory</directory>
</build>
</profile>
</profiles>
And start maven with your profile
mvn compile -PotherOutputDir
If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :
<properties>
<buildDirectory>${project.basedir}/target</buildDirectory>
</properties>
<build>
<directory>${buildDirectory}</directory>
</build>
And compile like this :
mvn compile -DbuildDirectory=test
That's because you can't change the target directory by using -Dproject.build.directory
If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.
df['date'] = df['date'].astype('datetime64[ns]')
or use datetime64[D] if you want Day precision and not nanoseconds
print(type(df_launath['date'].iloc[0]))
yields
<class 'pandas._libs.tslib.Timestamp'>
the same as when you use pandas.to_datetime
You can try it with other formats then '%Y-%m-%d' but at least this works.
If you are using Git GUI, first fetch then merge.
Fetch via Remote menu >> Fetch >> Origin. Merge via Merge menu >> Merge Local.
The following dialog appears.
Select the tracking branch radio button (also by default selected), leave the yellow box empty and press merge and this should update the files.
I had already reverted some local changes before doing these steps since I wanted to discard those anyways so I don't have to eliminate via merge later.
http://msdn.microsoft.com/en-us/library/ms191503.aspx
i would advice to create table with unique name before bulk inserting.
It seems like you want
wait $PID
which will return when $pid
finishes.
Otherwise you can use
ps -p $PID
to check if the process is still alive (this is more effective than kill -0 $pid
because it will work even if you don't own the pid).
This worked for me.
I created a folder then changed into the folder using CD option from command prompt.
Then executed the jar from there.
d:\LS\afterchange>jar xvf ..\mywar.war
requests
https://github.com/kennethreitz/requests/
Here's a few common ways to use it:
import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}
# GET
r = requests.get(url)
# GET with params in URL
r = requests.get(url, params=payload)
# POST with form-encoded data
r = requests.post(url, data=payload)
# POST with JSON
import json
r = requests.post(url, data=json.dumps(payload))
# Response, status etc
r.text
r.status_code
httplib2
https://github.com/jcgregorio/httplib2
>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT',
'content-type': 'text/html'}
Just add:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Pretty straight forward to do:
$(function() {
$('#toptitle').html('New word');
});
The html function accepts html as well, but its straight forward for replacing text.
Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?
Maybe this url can help you: Activating Browser Modes with Doctype
Edit: Today we were able to override the compatibility view with:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
I've really taken recently to display: table
to give things a fixed size such as to enable margin: 0 auto
to work. Has made my life a lot easier. You just need to get past the fact that 'table' display doesn't mean table html.
It's especially useful for responsive design where things just get hairy and crazy 50% left this and -50% that just become unmanageable.
style
{
display: table;
margin: 0 auto
}
In addition if you've got two buttons and you want them the same width you don't even need to know the size of each to get them to be the same width - because the table will magically collapse them for you.
(this also works if they're inline and you want to center two buttons side to side - try doing that with percentages!).
Use:
SELECT DATE_FORMAT(NAME_COLUMN, "%d/%l/%Y") AS 'NAME'
SELECT DATE_FORMAT(NAME_COLUMN, "%d/%l/%Y %H:%i:%s") AS 'NAME'
Reference: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html
declare @temp as varchar
set @temp='Measure'
if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
The problem is with your notificationId
. Think it as an array index. Each time you update your notification, the notificationId
is the place it takes to store value. As you are not incrementing your int value (in this case, your notificationId
), this always replaces the previous one. The best solution I guess is to increment it just after you update a notification. And if you want to keep it persistent, then you can store the value of your notificationId
in sharedPreferences
. Whenever you come back, you can just grab the last integer value (notificationId
stored in sharedPreferences
) and use it.
The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.
It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.
So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.
Otherwise, some users may not enjoy the smooth scrolling of your website / platform.
I can give a simpler example on how it can be applicable.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
// Add smooth scrolling to all links_x000D_
$("a").on('click', function(event) {_x000D_
// Make sure this.hash has a value before overriding default behavior_x000D_
if (this.hash !== "") {_x000D_
// Prevent default anchor click behavior_x000D_
event.preventDefault();_x000D_
// Store hash_x000D_
var hash = this.hash;_x000D_
// Using jQuery's animate() method to add smooth page scroll_x000D_
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area_x000D_
$('html, body').animate({_x000D_
scrollTop: $(hash).offset().top_x000D_
}, 800, function(){_x000D_
// Add hash (#) to URL when done scrolling (default click behavior)_x000D_
window.location.hash = hash;_x000D_
});_x000D_
} // End if_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
<style>_x000D_
#section1 {_x000D_
height: 600px;_x000D_
background-color: pink;_x000D_
}_x000D_
#section2 {_x000D_
height: 600px;_x000D_
background-color: yellow;_x000D_
}_x000D_
</style>
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<h1>Smooth Scroll</h1>_x000D_
<div class="main" id="section1">_x000D_
<h2>Section 1</h2>_x000D_
<p>Click on the link to see the "smooth" scrolling effect.</p>_x000D_
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>_x000D_
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>_x000D_
</div>_x000D_
<div class="main" id="section2">_x000D_
<h2>Section 2</h2>_x000D_
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Use this..
$("#myform input[type='radio']:checked").val();
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function myTimer() {
console.log(' each 1 second...');
}
var myVar = setInterval(myTimer, 1000);
call this line to stop the loop:
clearInterval(myVar);
In terms of entities (or objects) you have a Class
object which has a collection of Students
and a Student
object that has a collection of Classes
. Since your StudentClass
table only contains the Ids and no extra information, EF does not generate an entity for the joining table. That is the correct behaviour and that's what you expect.
Now, when doing inserts or updates, try to think in terms of objects. E.g. if you want to insert a class with two students, create the Class
object, the Student
objects, add the students to the class Students
collection add the Class
object to the context and call SaveChanges
:
using (var context = new YourContext())
{
var mathClass = new Class { Name = "Math" };
mathClass.Students.Add(new Student { Name = "Alice" });
mathClass.Students.Add(new Student { Name = "Bob" });
context.AddToClasses(mathClass);
context.SaveChanges();
}
This will create an entry in the Class
table, two entries in the Student
table and two entries in the StudentClass
table linking them together.
You basically do the same for updates. Just fetch the data, modify the graph by adding and removing objects from collections, call SaveChanges
. Check this similar question for details.
Edit:
According to your comment, you need to insert a new Class
and add two existing Students
to it:
using (var context = new YourContext())
{
var mathClass= new Class { Name = "Math" };
Student student1 = context.Students.FirstOrDefault(s => s.Name == "Alice");
Student student2 = context.Students.FirstOrDefault(s => s.Name == "Bob");
mathClass.Students.Add(student1);
mathClass.Students.Add(student2);
context.AddToClasses(mathClass);
context.SaveChanges();
}
Since both students are already in the database, they won't be inserted, but since they are now in the Students
collection of the Class
, two entries will be inserted into the StudentClass
table.
Make a private class inside where you make the array and the have a getter and setter for it. Unless you need each position in the array to be something unique, like random, then use int? as an array and then on get if the position is equal null fill that position and return the new random value.
IsVisibleHandler
{
private bool[] b = new bool[10000];
public bool GetIsVisible(int x)
{
return !b[x]
}
public void SetIsVisibleTrueAt(int x)
{
b[x] = false //!true
}
}
Or use
public void SetIsVisibleAt(int x, bool isTrue)
{
b[x] = !isTrue;
}
As setter.
It is compile time error for a Static Library
that is caused by Static Linker
ld: library not found for -l<Library_name>
Library not found for
when you have not include a library path to the Library Search Paths
ld
means Static Linker
which can not find a location of the library. As a developer you should help the linker and point the Library Search Paths
```
Build Settings -> Search Paths -> Library Search Paths
```
.xcodeproj
) with Cocoapods support, run pod update
. To fix it just close this project and open created a workspace instead (.xcworkspace
)Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).
Instead, I used this method:
Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:
The primitive wrapper types are reference types that are automatically created behind the scenes whenever strings, numbers, or Booleans are read.For example :
var name = "foo";
var firstChar = name.charAt(0);
console.log(firstChar);
This is what happens behind the scenes:
// what the JavaScript engine does
var name = "foo";
var temp = new String(name);
var firstChar = temp.charAt(0);
temp = null;
console.log(firstChar);
Because the second line uses a string (a primitive) like an object, the JavaScript engine creates an instance of String so that charAt(0) will work.The String object exists only for one statement before it’s destroyed check this
The instanceof operator returns false because a temporary object is created only when a value is read. Because instanceof doesn’t actually read anything, no temporary objects are created, and it tells us the values aren’t instances of primitive wrapper types. You can create primitive wrapper types manually
Do you mean that you want to center it vertically or horizontally? You said you specified the height
to 800 pixels, and wanted the div not to stretch when the width
was greater than that...
To center horizontally, you can use the margin: auto;
attribute in CSS. Also, you'll have to make sure that the body
and html
elements don't have any margin or padding:
html, body { margin: 0; padding: 0; }
#centeredDiv { margin-right: auto; margin-left: auto; width: 800px; }
Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _claim;
public ClaimAuthorizeAttribute(string Claim)
{
_claim = Claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
{
return;
}
context.Result = new ForbidResult();
}
}
A tip for others: if you have NI applications installed, the NI Application Web Server also uses the port 8080.
This means that your ArrayList has integers in some elements. The casting should work unless there's an integer in one of your elements.
One way to make sure that your arraylist has no integers is by declaring it as a Doubles array.
ArrayList<Double> marks = new ArrayList<Double>();
I'm not using JAX-RS, but I've got a similar scenario where I use:
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());