# Check delegate? first must be connected owner of view controller
# Simple implementation of the didSelectRowAt function.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("row selection: \(indexPath.row)")
}
My answer addresses the error in general and not the exact code of the OP. No answer mentioned this note so I just thought I add it.
The code below would also generate the same error:
class Actor {
let agent : String? // BAD! // Its value is set to nil, and will always be nil and that's stupid so Xcode is saying not-accepted.
// Technically speaking you have a way around it, you can help the compiler and enforce your value as a constant. See Option3
}
Others mentioned that Either you create initializers or you make them optional types, using ! or ? which is correct. However if you have an optional member/property, that optional should be mutable ie var
. If you make a let
then it would never be able to get out of its nil
state. That's bad!
So the correct way of writing it is:
class Actor {
var agent : String? // It's defaulted to `nil`, but also has a chance so it later can be set to something different || GOOD!
}
Or you can write it as:
class Actor {
let agent : String? // It's value isn't set to nil, but has an initializer || GOOD!
init (agent: String?){
self.agent = agent // it has a chance so its value can be set!
}
}
or default it to any value (including nil
which is kinda stupid)
class Actor {
let agent : String? = nil // very useless, but doable.
let company: String? = "Universal"
}
If you are curious as to why let
(contrary to var
) isn't initialized to nil
then read here and here
If you want to print the text of a UITableViewCell
according to its matching NSIndexPath
, you have to use UITableViewDelegate
's tableView:didSelectRowAtIndexPath:
method and get a reference of the selected UITableViewCell
with UITableView
's cellForRowAtIndexPath:
method.
For example:
import UIKit
class TableViewController: UITableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
switch indexPath.row {
case 0: cell.textLabel?.text = "Bike"
case 1: cell.textLabel?.text = "Car"
case 2: cell.textLabel?.text = "Ball"
default: cell.textLabel?.text = "Boat"
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
print(selectedCell?.textLabel?.text)
// this will print Optional("Bike") if indexPath.row == 0
}
}
However, for many reasons, I would not encourage you to use the previous code. Your UITableViewCell
should only be responsible for displaying some content given by a model. In most cases, what you want is to print the content of your model (could be an Array
of String
) according to a NSIndexPath
. By doing things like this, you will separate each element's responsibilities.
Thereby, this is what I would recommend:
import UIKit
class TableViewController: UITableViewController {
let toysArray = ["Bike", "Car", "Ball", "Boat"]
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toysArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = toysArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let toy = toysArray[indexPath.row]
print(toy)
// this will print "Bike" if indexPath.row == 0
}
}
As you can see, with this code, you don't have to deal with optionals and don't even need to get a reference of the matching UITableViewCell
inside tableView:didSelectRowAtIndexPath:
in order to print the desired text.
@IBAction func chooseProfilePicBtnClicked(sender: AnyObject) {
let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openCamera()
}
let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openGallary()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
}
// Add the actions
picker.delegate = self
alert.addAction(cameraAction)
alert.addAction(gallaryAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
func openCamera(){
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
picker.sourceType = UIImagePickerControllerSourceType.Camera
self .presentViewController(picker, animated: true, completion: nil)
}else{
let alert = UIAlertView()
alert.title = "Warning"
alert.message = "You don't have camera"
alert.addButtonWithTitle("OK")
alert.show()
}
}
func openGallary(){
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(picker, animated: true, completion: nil)
}
//MARK:UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
picker .dismissViewControllerAnimated(true, completion: nil)
imageViewRef.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
print("picker cancel.")
}
Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your function here
}
Swift 3
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
// your function here
}
Swift 2
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
Works for me in Swift 2.0
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
override func tableView(tableView: UITableView,
editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let block = UITableViewRowAction(style: .Normal, title: "Block") { action, index in
print("Block")
self.removeObjectAtIndexPath(indexPath, animated: true)
}
let delete = UITableViewRowAction(style: .Default, title: "Delete") { action, index in
print("Delete")
self.removeObjectAtIndexPath(indexPath, animated: true)
}
return [delete, block]
}
Below steps are worked for me, Hope this will work for you as well,
then write below code in a java file and run
System.setProperty("webdriver.ie.driver","path of your IE driver exe\IEDriverServer.exe");
InternetExplorerDriver driver=new InternetExplorerDriver();
driver.manage().window().maximize();
Thread.Sleep(10100);
driver.get("http://www.Google.com");
Thread.Sleep(10000);
Your observation is correct. This behavior is happening due to the reuse of cells. But you dont have to do any thing with the prepareForReuse. Instead do your check in cellForItem and set the properties accordingly. Some thing like..
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvCell" forIndexPath:indexPath];
if (cell.selected) {
cell.backgroundColor = [UIColor blueColor]; // highlight selection
}
else
{
cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor redColor]; // Default color
}
This solved my problem: Kotlin Code:
val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
fragmentTransaction.add(dialogFragment, tag)
fragmentTransaction.commitAllowingStateLoss()
How is commitAllowingStateLoss()
is different than commit()
?
As per documentation:
Like commit()
but allows the commit to be executed after an activity's state is saved.
https://developer.android.com/reference/android/app/FragmentTransaction#commitAllowingStateLoss()
P.S: you can show Fragment Dialogs or can load fragments by this method. Applicable for both.
I think it needs to be checked if any row is selected or not? The below code would check it:
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
if (selectedItem != undefined)
alert("The Row Is SELECTED");
else
alert("NO Row Is SELECTED")
Define an Outlet:
@IBOutlet weak var pickerView: UIPickerView! // for example
Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:
pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)
If you inspect the Swift 2.0 framework you'll see .selectRow
defined as:
func selectRow(row: Int, inComponent component: Int, animated: Bool)
option clicking .selectRow in Xcode displays the following:
To make values empty you can do the following:
$("#element").val('');
To get the selected value you can do:
var value = $("#element").val();
Where #element
is the id of the element you wish to select.
You are trying to load a XIB named DetailViewController
, but no such XIB exists or it's not member of your current target.
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
this worked for me:
jQuery('form').attr("placeholder","Wert eingeben");
but now this don't work:
// Prioritize "important" elements on medium.
skel.on('+medium -medium', function() {
jQuery.prioritize(
'.important\\28 medium\\29',
skel.breakpoint('medium').active
);
});
You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.
You can have a look at here for more information.
A few of my view controllers were missing the storyboardIdentifier attribute.
Before:
<viewController
id="pka-il-u5E"
customClass="YourViewControllerName"
customModule="ModuleName"
customModuleProvider="target"
sceneMemberID="viewController">
After:
<viewController
storyboardIdentifier="YourViewControllerName" <----
id="pka-il-u5E"
customClass="YourViewControllerName"
customModule="ModuleName"
customModuleProvider="target"
sceneMemberID="viewController">
In my case i was trying to present the viewController (i have the reference of the viewController in the TabBarViewController) from different view controllers and it was crashing with the above message. In that case to avoid presenting you can use
viewController.isBeingPresented
!viewController.isBeingPresented {
// Present your ViewController only if its not present to the user currently.
}
Might help someone.
If you use performSelectorInBackground:withObject:
to spawn a new thread, then the performed selector is responsible for setting up the new thread's autorelease pool, run loop and other configuration details – see "Using NSObject to Spawn a Thread" in Apple's Threading Programming Guide.
You'd probably be better off using Grand Central Dispatch, though:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self getResultSetFromDB:docids];
});
GCD is a newer technology, and is more efficient in terms of memory overhead and lines of code.
Updated with a hat tip to Chris Nolet, who suggested a change that makes the above code simpler and keeps up with Apple's latest GCD code examples.
NSInteger SelectedRow;
SelectedRow = [yourPickerView selectedRowInComponent:0];
selectedPickerString = [YourPickerArray objectAtIndex:SelectedRow];
self.YourTextField.text= selectedPickerString;
// if you want to move pickerview to selected row then
for (int i = 0; I<YourPickerArray.count; i++) {
if ([[YourPickerArray objectAtIndex:i] isEqualToString:self.YourTextField.text]) {
[yourPickerView selectRow:i inComponent:0 animated:NO];
}
}
In Swift 3.0
let number:NSNumber = 25
let strValue = String(describing: number as NSNumber)
print("As String => \(strValue)")
We can get the number value in String.
This is a solution for Swift 4
in tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
just add
tableView.deselectRow(at: indexPath, animated: true)
it works like a charm
example:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
//some code
}
My solution based on data model:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let rowDetails = viewModel.rowDetails(forIndexPath: indexPath)
return rowDetails.enabled ? indexPath : nil
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
let rowDetails = viewModel.rowDetails(forIndexPath: indexPath)
return rowDetails.enabled
}
Use this category to select a table row and execute a given segue after a delay.
Call this within your viewDidAppear
method:
[tableViewController delayedSelection:withSegueIdentifier:]
@implementation UITableViewController (TLUtils)
-(void)delayedSelection:(NSIndexPath *)idxPath withSegueIdentifier:(NSString *)segueID {
if (!idxPath) idxPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self performSelector:@selector(selectIndexPath:) withObject:@{@"NSIndexPath": idxPath, @"UIStoryboardSegue": segueID } afterDelay:0];
}
-(void)selectIndexPath:(NSDictionary *)args {
NSIndexPath *idxPath = args[@"NSIndexPath"];
[self.tableView selectRowAtIndexPath:idxPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)])
[self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:idxPath];
[self performSegueWithIdentifier:args[@"UIStoryboardSegue"] sender:self];
}
@end
A simple example is
2 == '2' -> true, values are SAME because of type conversion.
2 === '2' -> false, values are NOT SAME because of no type conversion.
Giving my 2 cents on this.
I had a Custom UITableViewCell and there was a button covering the whole cell, so when the touch happened, the button was selected and not the cell.
Either remove the button or in my case, I set User Interation Enable to false on the button, that way the cell was the one selected.
I would try the itemStateChanged()
method of the ItemListener
interface if jodonnell's solution fails.
The first example will actually embed HTML within the div
whereas the second example will escape the text by means of replacing element-related characters with their corresponding character entities so that it displays literally (i.e. the HTML will be displayed not rendered).
Scrolling with animation:
Your DIV:
<div class='messageScrollArea' style='height: 100px;overflow: auto;'>
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
</div>
jQuery part:
jQuery(document).ready(function(){
var $t = $('.messageScrollArea');
$t.animate({"scrollTop": $('.messageScrollArea')[0].scrollHeight}, "slow");
});
You can just pass it
def my_function(my_data):
my_data["schoolname"] = "something"
print my_data
or if you really want to
def my_function(**kwargs):
kwargs["schoolname"] = "something"
print kwargs
The with
function will let you use shorthand column references and sum
will count TRUE
results from the expression(s).
sum(with(aaa, sex==1 & group1==2))
## [1] 3
sum(with(aaa, sex==1 & group2=="A"))
## [1] 2
As @mnel pointed out, you can also do:
nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3
nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2
The benefit of that is that you can do:
nrow(aaa)
## [1] 6
And, the behaviour matches Stata's count
almost exactly (syntax notwithstanding).
*EDIT: I wrote an article about how to do this https://medium.com/riow/mongodb-data-collection-change-85b63d96ff76
It's new in mongodb 3.6 https://docs.mongodb.com/manual/release-notes/3.6/ 2018/01/10
$ mongod --version
db version v3.6.2
In order to use changeStreams the database must be a Replication Set
More about Replication Sets: https://docs.mongodb.com/manual/replication/
Your Database will be a "Standalone" by default.
How to Convert a Standalone to a Replica Set: https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set/
The following example is a practical application for how you might use this.
* Specifically for Node.
/* file.js */
'use strict'
module.exports = function (
app,
io,
User // Collection Name
) {
// SET WATCH ON COLLECTION
const changeStream = User.watch();
// Socket Connection
io.on('connection', function (socket) {
console.log('Connection!');
// USERS - Change
changeStream.on('change', function(change) {
console.log('COLLECTION CHANGED');
User.find({}, (err, data) => {
if (err) throw err;
if (data) {
// RESEND ALL USERS
socket.emit('users', data);
}
});
});
});
};
/* END - file.js */
Useful links:
https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set
https://docs.mongodb.com/manual/tutorial/change-streams-example
https://docs.mongodb.com/v3.6/tutorial/change-streams-example
http://plusnconsulting.com/post/MongoDB-Change-Streams
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
In Spark 2.4
To compare with one value:
df.filter(lower(trim($"col_name")) === "<value>").show()
To compare with collection of value:
df.filter($"col_name".isInCollection(new HashSet<>(Arrays.asList("value1", "value2")))).show()
If you want to export just single table, or subset of data from some table, you can do it directly from result window:
Also with Kotlin:
fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
putString(key, list?.joinToString(",") ?: "")
return this
}
fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
val value = getString(key, null)
if (value.isNullOrBlank())
return defValue
return ArrayList (value.split(",").map { it.toInt() })
}
To answer the original question. According to java docs here:
"NoSuchMethodError" Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
Another option is to go with bokeh. IMO, it is a good alternative at least for real-time plots. Here is a bokeh version of the code in the question:
from bokeh.plotting import curdoc, figure
import random
import time
def update():
global i
temp_y = random.random()
r.data_source.stream({'x': [i], 'y': [temp_y]})
i += 1
i = 0
p = figure()
r = p.circle([], [])
curdoc().add_root(p)
curdoc().add_periodic_callback(update, 100)
and for running it:
pip3 install bokeh
bokeh serve --show test.py
bokeh shows the result in a web browser via websocket communications. It is especially useful when data is generated by remote headless server processes.
If you have .NET v4 installed (so if you have a newer windows or if you apply the windows updates)
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe somefile.cs
or
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.sln
or
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.csproj
It's highly probable that if you have .NET installed, the %FrameworkDir%
variable is set, so:
%FrameworkDir%\v4.0.30319\csc.exe ...
%FrameworkDir%\v4.0.30319\msbuild.exe ...
a = Array.new(Array.new(4))
0.upto(a.length-1) do |i|
0.upto(a.length-1) do |j|
a[i[j]] = 1
end
end
0.upto(a.length-1) do |i|
0.upto(a.length-1) do |j|
print a[i[j]] = 1 #It's not a[i][j], but a[i[j]]
end
puts "\n"
end
Based on @md-nazrul-islam reply, This is what I did with SCSS:
ul.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
margin: 0 0 10px 25px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
border-color: rgba(0, 0, 0, 0.2);
//@include border-radius(5px);
@include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
@include background-clip(padding-box);
*border-right-width: 2px;
*border-bottom-width: 2px;
li.ui-menu-item{
padding:0 .5em;
line-height:2em;
font-size:.8em;
&.ui-state-focus{
background: #F7F7F7;
}
}
}
You needed to iconv your source.
That said, the TEX-based compiler invoked by latex
doesn't really support variable-length encodings; it needs big libraries that tell it that certain bytes go together. Xelatex is Unicode-aware and works much better.
Using map
:
def caesar(text, key):
return ''.join(map(lambda c:
chr((ord(c.lower()) - ord('a') + key) % 26 + ord('a')) if c.isalpha() else ''
, text))
Yes, it is:
<div id="myid">Some Content........</div>
document.getElementById('#myid').style.width = '50%';
You use Global variables :-D.
Like this:
<script type="text/javascript">
var obj1 = "somevalue";
var obj2 = "someothervalue";
</script>
<script type="text/javascript" src="file.js"></script">
The JavaScript code in 'file.js' can access to obj1
and obj2
without problem.
EDIT Just want to add that if 'file.js' wants to check if obj1
and obj2
have even been declared you can use the following function.
function IsDefined($Name) {
return (window[$Name] != undefined);
}
Hope this helps.
In my case it was enough to exclude only path 'META-INF/DEPENDENCIES' on yourProject/app/build.gradle
inside android{}
. Here it is
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
And then do Clean Project and Rebuild Project.
I don't think the accepted answer is entirely correct. It is order dependent. Here is an example that will not work correctly with an approach from the answer.
create table xxx (
id varchar(64),
is_enabled boolean
);
insert into xxx (id, is_enabled) values ('1',true);
insert into xxx (id, is_enabled) values ('2',true);
insert into xxx (id, is_enabled) values ('3',true);
UPDATE public.xxx AS pns
SET is_enabled = u.is_enabled
FROM (
VALUES
(
'3',
false
,
'1',
true
,
'2',
false
)
) AS u(id, is_enabled)
WHERE u.id = pns.id;
select * from xxx;
So the question still stands, is there a way to do it in an order independent way?
---- after trying a few things this seems to be order independent
UPDATE public.xxx AS pns
SET is_enabled = u.is_enabled
FROM (
SELECT '3' as id, false as is_enabled UNION
SELECT '1' as id, true as is_enabled UNION
SELECT '2' as id, false as is_enabled
) as u
WHERE u.id = pns.id;
I think this command killall is exactly what you need. The command is described as "kill processes by name".It's easy to use.For example
killall chrome
This command will kill all process of Chrome.Here is a link about killall command
http://linux.about.com/library/cmd/blcmdl1_killall.htm
Hope this command could help you.
The pseudo-code "implementation" of strcmp
would go something like:
define strcmp (s1, s2):
p1 = address of first character of str1
p2 = address of first character of str2
while contents of p1 not equal to null:
if contents of p2 equal to null:
return 1
if contents of p2 greater than contents of p1:
return -1
if contents of p1 greater than contents of p2:
return 1
advance p1
advance p2
if contents of p2 not equal to null:
return -1
return 0
That's basically it. Each character is compared in turn an a decision is made as to whether the first or second string is greater, based on that character.
Only if the characters are identical do you move to the next character and, if all the characters were identical, zero is returned.
Note that you may not necessarily get 1 and -1, the specs say that any positive or negative value will suffice, so you should always check the return value with < 0
, > 0
or == 0
.
Turning that into real C would be relatively simple:
int myStrCmp (const char *s1, const char *s2) {
const unsigned char *p1 = (const unsigned char *)s1;
const unsigned char *p2 = (const unsigned char *)s2;
while (*p1 != '\0') {
if (*p2 == '\0') return 1;
if (*p2 > *p1) return -1;
if (*p1 > *p2) return 1;
p1++;
p2++;
}
if (*p2 != '\0') return -1;
return 0;
}
Also keep in mind that "greater" in the context of characters is not necessarily based on simple ASCII ordering for all string functions.
C has a concept called 'locales' which specify (among other things) collation, or ordering of the underlying character set and you may find, for example, that the characters a
, á
, à
and ä
are all considered identical. This will happen for functions like strcoll
.
Assuming int is a 16 bit integer (which depends on the C implementation, most are 32 bit nowadays) the bit representation differs like the following:
5 = 0000000000000101
-5 = 1111111111111011
if binary 1111111111111011 would be set to an unsigned int, it would be decimal 65531.
You can break a text using an entity in between the value. See the entity in example below:
<input style="width:100px;" type="button" value="Click here 
 to 
 start playing">
You can't do it the way you've written it because C++ class member functions have a hidden this
parameter passed in. pthread_create()
has no idea what value of this
to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has no this
parameter), or a plain ordinary function to bootstrap the class:
class C
{
public:
void *hello(void)
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
Try closing and re-opening the file.
It is possible to get this error in eclipse when there is absolutely nothing wrong with the file location or package declaration. Try that before spending a lot of time trying these other solutions. Sometimes eclipse just gets confused. It's worked for me on a number of occasions. I credit the idea to Joshua Goldberg.
A simple way of doing this is via nargin
(N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.
It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b
and c
. Will exit if a
is not present.
function [ output_args ] = input_example( a, b, c )
if nargin < 1
error('input_example : a is a required input')
end
if nargin < 2
b = 20
end
if nargin < 3
c = 30
end
end
If the files which you are loading are cached and if the changes you have made does not reflect in the code then there are 2 ways you can deal with this
Clear the Cache as everyone told
If u want Cache and only the files have to be reloaded , you can go to network tab of the dev tool and clear whatever was loaded. next time it will not load it from cache. you will have your latest changes.
Just remove the throw
from the catch block — change it to an echo
or otherwise handle the error.
It's not telling you that objects can only be thrown in the catch block, it's telling you that only objects can be thrown, and the location of the error is in the catch block — there is a difference.
In the catch block you are trying to throw something you just caught — which in this context makes little sense anyway — and the thing you are trying to throw is a string.
A real-world analogy of what you are doing is catching a ball, then trying to throw just the manufacturer's logo somewhere else. You can only throw a whole object, not a property of the object.
For Centos I was missing php-mysql library:
yum install php-mysql
service httpd restart
There is no need to enable any extension in php.ini, it is loaded by default.
I found maybe best solution for parallax effect which work on all devices.
Main thing is to set all sections with z-index greater than parallax section.
And parallax image element to set fixed with max width and height
body, html { margin: 0px; }_x000D_
section {_x000D_
position: relative; /* Important */_x000D_
z-index: 1; /* Important */_x000D_
width: 100%;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
section.blue { background-color: blue; }_x000D_
section.red { background-color: red; }_x000D_
_x000D_
section.parallax {_x000D_
z-index: 0; /* Important */_x000D_
}_x000D_
_x000D_
section.parallax .image {_x000D_
position: fixed; /* Important */_x000D_
top: 0; /* Important */_x000D_
left: 0; /* Important */_x000D_
width: 100%; /* Important */_x000D_
height: 100%; /* Important */_x000D_
background-image: url(https://www.w3schools.com/css/img_fjords.jpg);_x000D_
background-repeat: no-repeat;_x000D_
background-position: center;_x000D_
-webkit-background-size: cover;_x000D_
-moz-background-size: cover;_x000D_
-o-background-size: cover;_x000D_
background-size: cover;_x000D_
}
_x000D_
<section class="blue"></section>_x000D_
<section class="parallax">_x000D_
<div class="image"></div>_x000D_
</section>_x000D_
<section class="red"></section>
_x000D_
Years ago, Apple joined the OpenJDK project, transferring their formerly proprietary macOS-specific JVM code as free-of-cost open-source. Apple ceased distribution of their own branded JVM/JDK, relying on Oracle’s branded releases to include a version for macOS.
Oracle has recently announced their intention to bring their Oracle-branded JVM release to feature parity with the OpenJDK project, with virtually the same code base. The company even donated their previously commercial tools, Flight Recorder & Mission Control, to the OpenJDK project. This is part of the shift to a new rapid “release train” plan for predictably scheduled versioning of Java and OpenJDK. Notably, the periods for free-of-cost public updates is now shortened. See this 2017-09 announcement and this posting by Mark Reinhold.
As a result of all this, macOS users of Java have a choice of vendors for a Java implementation. At this point, at least three sources are based on OpenJDK for macOS:
Meanwhile, IBM donated code for a JVM to the Eclipse Foundation, now housed in the OpenJ9 project. I wonder if they might support a macOS release as well, though it is too soon to tell.
Personally, I am currently using the Zulu release of Java 10.0.1 from Azul on macOS High Sierra successfully with IntelliJ 2018.2 to produce Java-backed web apps with Vaadin.
Both Oracle and Azul provide utterly easy-to-use installers to install the JVM/JDK on your Mac. Verify your installation by using the Terminal.app (or equivalent) to type and run:
java -version
You will find the Java installations in this folder at the root level of your drive (not in your home folder):
/Library/Java/JavaVirtualMachines
Each version from each vendor is found there, in a labeled nested folder. You can delete any installation simply by deleting the nested folder for that version and providing your system password when prompted.
You can download the Java Development Kit (JDK) for Java 8 for the supported versions of Mac OS X:
Each version of JVM you install can be found here:
/Library/Java/JavaVirtualMachines
For more instructions and FAQ, see this Oracle Guide.
For every release of Java 7 since Update 4, a Mac version has been ready alongside the other platforms. Runs on Macs with 64-bit hardware on Lion (10.7.3+), Mountain Lion (10.8.3+), and Mavericks (10.9.x).
Oracle announced the official release of the JDK for Java SE 7 Update 4 on Mac OS X (Lion), as of 2012-04-26. No more need for the tricks discussed on this page.
Installation is simple per these instructions:
This release has a few limitations, most notably the lack of support for Java Web Start and the Java Plugin for web browsers. That support is expected later this year.
After installing, read the JDK for Mac ReadMe. Most importantly, if you want Java 7 to be the default, drag it to the top of the list in the Java Preferences app found in your Utilities folder.
Mac OS X easily supports multiple JVMs simultaneously. Each is now found here:
/Library/Java/JavaVirtualMachines
Congratulations to the Apple & Oracle teams for their achievement. This geek gets a thrill seeing Mac OS X listed as a "Certified System Configuration".
Tip: To start Eclipse on a Mac with only Java 7 installed, open the alias file named eclipse rather than the file named Eclipse.app.
Apple continues to supply an up-to-date implementation of Java 6 for all versions of Mac OS X up through Mountain Lion.
If you do something that requires Java, such as type "java -version" in Terminal.app, a dialog appears offering to install Java for you. If you accept, installation happens automatically similar to other "Software Updates" from Apple.
You will find Java installed in this location, different than Java 7 & 8:
/System/Library/Java/JavaVirtualMachines
Java 6 has reached end-of-life with Oracle as of 2013-02 (unless you have a commercial support agreement with Oracle). So you should be moving to Java 7 or 8.
In Terminal.app, type java -version
to verify which version is the current default.
After installing a fresh version, you may want to visit the folder described above to delete old versions. Move the folder to the Trash, and provide your System password complete the move.
By the way, Apple provides a mailing list for developers’ technical issues related to Java on OS X.
Mike Goodwin answer is great but it seemed, when I tried it, that it was aimed at MVC5/WebApi 2.1. The dependencies for Microsoft.AspNet.WebApi.Cors didn't play nicely with my MVC4 project.
The simplest way to enable CORS on WebApi with MVC4 was the following.
Note that I have allowed all, I suggest you limit the Origin's to just the clients you want your API to serve. Allowing everything is a security risk.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
We do this to allow the OPTIONS http verb
public class BaseApiController : ApiController
{
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
}
It doesn't inherit from Element
because not all event targets are elements.
Element, document, and window are the most common event targets, but other objects can be event targets too, for example XMLHttpRequest, AudioNode, AudioContext, and others.
Even the KeyboardEvent
you're trying to use can occur on a DOM element or on the window object (and theoretically on other things), so right there it wouldn't make sense for evt.target
to be defined as an Element
.
If it is an event on a DOM element, then I would say that you can safely assume evt.target
. is an Element
. I don't think this is an matter of cross-browser behavior. Merely that EventTarget
is a more abstract interface than Element
.
Further reading: https://typescript.codeplex.com/discussions/432211
df = pd.DataFrame(['-',3,2,5,1,-5,-1,'-',9])
df = df.where(df!='-', None)
Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...
http://www.jetbrains.com/idea/features/editions_comparison_matrix.html
it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.
I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.
Anyway this tells that story too... http://www.jetbrains.com/products.html
Request and Superagent are pretty good libraries to use.
note: request is deprecated, use at your risk!
Using request
:
var request=require('request');
request.get('https://someplace',options,function(err,res,body){
if(err) //TODO: handle err
if(res.statusCode === 200 ) //etc
//TODO Do something with response
});
Use jFeed - a jQuery RSS/Atom plugin. According to the docs, it's as simple as:
jQuery.getFeed({
url: 'rss.xml',
success: function(feed) {
alert(feed.title);
}
});
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
One of the alternatives to Python's conditional expression
"yes" if boolean else "no"
is the following:
{True:"yes", False:"no"}[boolean]
which has the following nice extension:
{True:"yes", False:"no", None:"maybe"}[boolean_or_none]
The shortest alternative remains:
("no", "yes")[boolean]
but there is no alternative to
yes() if boolean else no()
if you want to avoid the evaluation of yes()
and no()
, because in
(no(), yes())[boolean] # bad
both no()
and yes()
are evaluated.
I used this query and it worked for me:
CREATE EVENT `exec`
ON SCHEDULE EVERY 5 SECOND
STARTS '2013-02-10 00:00:00'
ENDS '2015-02-28 00:00:00'
ON COMPLETION NOT PRESERVE ENABLE
DO
call delete_rows_links();
Use this it will work,
<body>
<h1>Adding 'a' and 'b'</h1>
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="a"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
var m = document.getElementById("a").value;
var n = document.getElementById("b").value;
var sum = m + n;
alert(sum);
}
</script>
</body>
Depending on the location of your config file System.Reflection.Assembly.GetExecutingAssembly().Location
might do what you need.
For my case, I had to pass DBNULL.Value
(using if else condition) from code for stored procedures parameter that are not defined null
but value is null
.
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaFrom the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.
If you're able to use Underscore.js in your project, the _.filter() array function makes this a snap:
// find all strings in array containing 'thi'
var matches = _.filter(
[ 'item 1', 'thing', 'id-3-text', 'class' ],
function( s ) { return s.indexOf( 'thi' ) !== -1; }
);
The iterator function can do whatever you want as long as it returns true for matches. Works great.
Update 2017-12-03:
This is a pretty outdated answer now. Maybe not the most performant option in a large batch, but it can be written a lot more tersely and use native ES6 Array/String methods like .filter()
and .includes()
now:
// find all strings in array containing 'thi'
const items = ['item 1', 'thing', 'id-3-text', 'class'];
const matches = items.filter(s => s.includes('thi'));
Note: There's no <= IE11 support for String.prototype.includes()
(Edge works, mind you), but you're fine with a polyfill, or just fall back to indexOf()
.
Herman's solution worked for me, but the ...
had me mixed up for a bit. I'm including the demo I worked up based on his answer. The additional features in my answer include foreign key support, auto incrementing keys, and use of the last_insert_rowid()
function to get the last auto generated key in a transaction.
My need for this information came up when I hit a transaction that required three foreign keys but I could only get the last one with last_insert_rowid()
.
PRAGMA foreign_keys = ON; -- sqlite foreign key support is off by default
PRAGMA temp_store = 2; -- store temp table in memory, not on disk
CREATE TABLE Foo(
Thing1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
);
CREATE TABLE Bar(
Thing2 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
FOREIGN KEY(Thing2) REFERENCES Foo(Thing1)
);
BEGIN TRANSACTION;
CREATE TEMP TABLE _Variables(Key TEXT, Value INTEGER);
INSERT INTO Foo(Thing1)
VALUES(2);
INSERT INTO _Variables(Key, Value)
VALUES('FooThing', last_insert_rowid());
INSERT INTO Bar(Thing2)
VALUES((SELECT Value FROM _Variables WHERE Key = 'FooThing'));
DROP TABLE _Variables;
END TRANSACTION;
There is no function that does this in the C standard. Unix systems that comply with POSIX are required to have strcasecmp
in the header strings.h
; Microsoft systems have stricmp
. To be on the portable side, write your own:
int strcicmp(char const *a, char const *b)
{
for (;; a++, b++) {
int d = tolower((unsigned char)*a) - tolower((unsigned char)*b);
if (d != 0 || !*a)
return d;
}
}
But note that none of these solutions will work with UTF-8 strings, only ASCII ones.
Console.Read()
reads just a single character, while Console.ReadLine()
reads all characters until the end of line.
My guess is that you've got something in method1
which wraps one exception in another, and uses the toString()
of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage()
behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message
Considering the following code:
import java.util.Optional;
// one class needs to have a main() method
public class Test
{
public String orelesMethod() {
System.out.println("in the Method");
return "hello";
}
public void test() {
String value;
value = Optional.<String>ofNullable("test").orElseGet(this::orelesMethod);
System.out.println(value);
value = Optional.<String>ofNullable("test").orElse(orelesMethod());
System.out.println(value);
}
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
Test test = new Test();
test.test();
}
}
if we get value
in this way: Optional.<String>ofNullable(null)
, there is no difference between orElseGet() and orElse(), but if we get value
in this way: Optional.<String>ofNullable("test")
, orelesMethod()
in orElseGet()
will not be called but in orElse()
it will be called
Does xxxxxxxxxxxx specify a file name or directory name on the target
(F = file, D = directory)? D
if a File : (echo F)
if a Directory (echo D)
This mini javascript libary (1.3 KB) can do all these things
https://github.com/Norair1997/norjs/
nor.event(["#first"], ["touchstart", "click"], [doSomething, doSomething]);
I just came across this article by Danny Kalev which has a great tip for C++14 and up.
template<typename T>
constexpr T pi = T(3.1415926535897932385);
I thought this was pretty cool (though I would use the highest precision PI in there I could), especially because templates can use it based on type.
template<typename T>
T circular_area(T r) {
return pi<T> * r * r;
}
double darea= circular_area(5.5);//uses pi<double>
float farea= circular_area(5.5f);//uses pi<float>
Use disabled true property
<TouchableOpacity disabled={true}> </TouchableOpacity>
Well, since liquibase is open source there's always the source code which you could check.
Some of the data type classes seem to have a method toDatabaseDataType()
which should give you information about what type works (is used) on a specific data base.
Use
[self dismissViewControllerAnimated:NO completion:nil];
div{
width:auto;
height:auto;
}
You can use conda remove --force
.
The documentation says:
--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
state
The problem is that you are using a lower case v.
You need to set it to Value and it should fix your issue:
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })
It can be, but it's a hack.
See Is DoEvents Evil?.
Direct from the MSDN page that thedev referenced:
Calling this method causes the current thread to be suspended while all waiting window messages are processed. If a message causes an event to be triggered, then other areas of your application code may execute. This can cause your application to exhibit unexpected behaviors that are difficult to debug. If you perform operations or computations that take a long time, it is often preferable to perform those operations on a new thread. For more information about asynchronous programming, see Asynchronous Programming Overview.
So Microsoft cautions against its use.
Also, I consider it a hack because its behavior is unpredictable and side effect prone (this comes from experience trying to use DoEvents instead of spinning up a new thread or using background worker).
There is no machismo here - if it worked as a robust solution I would be all over it. However, trying to use DoEvents in .NET has caused me nothing but pain.
If you add height in .wrapper
class then your scroll is working, without height
scroll is not working.
Try this http://jsfiddle.net/ZcrFr/3/
CSS:
.wrapper {
position: relative;
overflow: scroll;
width: 1000px;
height: 800px;
}
I worked it around through this "hiding" div ...
<div STYLE="position:absolute;display:none;"><INPUT type='file' id='file1' name='files[]'></div>
if no luck with above try to it a class or even id something like textarea.foo and then your style. or try to !important
Intent i = new Intent(MainPoliticalLogin.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
Manually add it when you build the query:
SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2
UNION ALL
...
EXAMPLE:
DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))
INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'
INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'
SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2
RESULT:
SiteName column1 column2
Site1 1 a
Site1 2 b
Site2 3 c
Site2 4 d
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
<form method = 'post' action = '' id = 'theForm'>
...
</form>
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data
above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET
super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success
function is called, and any and all output produced by the PHP script will be stored in the variable html
.
...
success: function(html) {
alert(html);
}
...
reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.
Is there any better choice in this kind of scenario?
it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.
fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?
you can get sticky header functionality by copying these 2 files into your project. i had no issues with this implementation:
see an example of the 2 files being used in this small github project i whipped up
Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).
This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.
Just for fun I thought I'd throw a forEach(f())
solution in too.
var a=[];
"14 2".split(" ").forEach(function(e){a.push(parseInt(e,10))});
// a = [14,2]
From my experience, the http://www.facebook.com/sharer.php does not use meta tags. It uses the string you pass. See below.
http://www.facebook.com/sharer.php?s=100&p[title]=THIS IS MY TITLE&p[summary]=THIS IS MY SUMMARY&p[url]=http://www.MYURL.com&&p[images][0]=http://www.MYURL.com/img/IMAGEADDRESS
The meta tags work with Facebook's developer like/send buttons, as does the other Open Graph info. So if you use one of Facebook's actual elements like the comments and such, that will all tie into the Open Graph stuff.
UPDATE: There are two ways to use the sharer * note the ?s versus the ?u value in the query string
1 ==> STRING: http://www.facebook.com/sharer.php?s + content from above
~~> Will pull info from the string.
2 ==> URL: http://www.facebook.com/sharer.php?u=url where url equals an actual url
~~> Will scrape the page provided in the url value
~~> You can test test the values here: https://developers.facebook.com/tools/debug
To push a single tag:
git push origin <tag_name>
And the following command should push all tags (not recommended):
git push --tags
The best way is:
public interface IDeepClonable<T> where T : class
{
T DeepClone();
}
public class MyObj : IDeepClonable<MyObj>
{
public MyObj Clone()
{
var myObj = new MyObj();
myObj._field1 = _field1;//value type
myObj._field2 = _field2;//value type
myObj._field3 = _field3;//value type
if (_child != null)
{
myObj._child = _child.DeepClone(); //reference type .DeepClone() that does the same
}
int len = _array.Length;
myObj._array = new MyObj[len]; // array / collection
for (int i = 0; i < len; i++)
{
myObj._array[i] = _array[i];
}
return myObj;
}
private bool _field1;
public bool Field1
{
get { return _field1; }
set { _field1 = value; }
}
private int _field2;
public int Property2
{
get { return _field2; }
set { _field2 = value; }
}
private string _field3;
public string Property3
{
get { return _field3; }
set { _field3 = value; }
}
private MyObj _child;
private MyObj Child
{
get { return _child; }
set { _child = value; }
}
private MyObj[] _array = new MyObj[4];
}
Why not just convert both strings to lowercase before you call find()
?
Notice:
In host computer/server go to Sql server management studio --> open Security Section on left hand --> right click on Login, select New Login and then create a new account for your database which you want to connect to.
Check the TCP/IP Protocol is Enable. go to All programs --> Microsoft SQL server 2008 --> Configuration Tools --> open Sql server configuration manager. On the left hand select client protocols (based on your operating system 32/64 bit). On the right hand, check TCP/IP Protocol be Enabled.
In Remote computer/server, open Data source administrator. Control panel --> Administrative tools --> Data sources (ODBC).
In User DSN or System DSN , click Add button and select Sql Server driver and then press Finish.
Enter Name.
Enter Server, note that: if you want to enter host computer address, you should enter that`s IP address without "\\". eg. 192.168.1.5 and press Next.
Select With SQL Server authentication using a login ID and password entered by the user.
At the bellow enter your login ID and password which you created on first step. and then click Next.
If shown Database is your database, click Next and then Finish.
Same everyday problem.
I just created a simple vc project to solve this problem.
It copies the file as Base64 encoded data directly to the clipboard, and then this can be pasted into the PuTTY console and decoded on the remote side.
This solution is for relatively small files (relative to the connection speed to your remote console).
Download clip_b64.exe
and place it in the SendTo folder (or a .lnk
shortcut to it). To open this folder, in the address bar of the explorer, enter shell:sendto
or %appdata%\Microsoft\Windows\SendTo
.
You may need to install VC 2017 redist to run it, or use the statically linked clip_b64s.exe
execution.
In the File Explorer, right-click the file you are transferring to open the context menu, then go to the "Send To" section and select Clip_B64
from the list.
Run the shell command base64 -d > file-name-you-want
and right-click in the console (or press Shift + Insert
) to place the clipboard content in it, and then press Ctrl + D
to finish.
voila
Using seeds.rb
file or FactoryBot
is great, but these are respectively great for fixed data structures and testing.
The seedbank
gem might give you more control and modularity to your seeds. It inserts rake tasks and you can also define dependencies between your seeds. Your rake task list will have these additions (e.g.):
rake db:seed # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/ENVIRONMENT/*.seeds.rb. ENVIRONMENT is the current environment in Rails.env.
rake db:seed:bar # Load the seed data from db/seeds/bar.seeds.rb
rake db:seed:common # Load the seed data from db/seeds.rb and db/seeds/*.seeds.rb.
rake db:seed:development # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/development/*.seeds.rb.
rake db:seed:development:users # Load the seed data from db/seeds/development/users.seeds.rb
rake db:seed:foo # Load the seed data from db/seeds/foo.seeds.rb
rake db:seed:original # Load the seed data from db/seeds.rb
Set LDFLAGS and CFLAGS when you run make:
$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make
If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib
Continuous Integration with Jenkins, after code is pushed to repository from Git command/ GUI:
.git/hooks
folder.The hooks
folder contains the few files. Check for the "post-commit". If not present, create a file, "post-commit" without a file extension:
C:\work\test\\.git\hooks\post-commit
Edit the "post-commit" file with the below command. Make sure it is present in your local source code hooks folder.
curl -u userName:apiToken -X POST http://localhost:8080/jenkins/job/jobName/build?token=apiToken
Example:
curl -u admin:f1c55b3a07bb2b69b9dd549e96898384 -X POST http://localhost:8080/jenkins/job/Gitcommittest/build?token=f1c55b3a07bb2b69b9dd549e96898384
5.
userName
: Jenkins user name
jobName
: Job name of the build
apiToken
: To get your API token, go to your Jenkins user page (top right in the interface). It is available in the "Configure" menu on the left of the page: "Show API token"
Make changes in your source code and commit the code to repository.
Your job, http://localhost:8080/jenkins/job/Gitcommittest/
, should be building.
substring().
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
Due to the way Python works, it is necessary for it to run your modules when it imports them.
To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this if
:
if __name__ == "__main__":
# this won't be run when imported
You may want to put this code in a main()
method, so that you can either execute the file directly, or import the module and call the main()
. For example, assume this is in the file foo.py
.
def main():
print "Hello World"
if __name__ == "__main__":
main()
This program can be run either by going python foo.py
, or from another Python script:
import foo
...
foo.main()
Let's not forget Jerry, its jQuery in java: a fast and concise Java Library that simplifies HTML document parsing, traversing and manipulating; includes usage of css3 selectors.
Example:
Jerry doc = jerry(html);
doc.$("div#jodd p.neat").css("color", "red").addClass("ohmy");
Example:
doc.form("#myform", new JerryFormHandler() {
public void onForm(Jerry form, Map<String, String[]> parameters) {
// process form and parameters
}
});
Of course, these are just some quick examples to get the feeling how it all looks like.
For non-servers this requires Remote Server Administration Tools for Windows __
Use Memoize
The op's derivation of state is a direct manipulation of props, with no true derivation needed. In other words, if you have a prop which can be utilized or transformed directly there is no need to store the prop on state.
Given that the state value of start_time
is simply the prop start_time.format("HH:mm")
, the information contained in the prop is already in itself sufficient for updating the component.
However if you did want to only call format on a prop change, the correct way to do this per latest documentation would be via Memoize: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization
Try with the following code
public static ArrayList<Customer> getAllCustomer() throws ClassNotFoundException, SQLException {
Connection conn=DBConnection.getDBConnection().getConnection();
Statement stm;
stm = conn.createStatement();
String sql = "Select * From Customer";
ResultSet rst;
rst = stm.executeQuery(sql);
ArrayList<Customer> customerList = new ArrayList<>();
while (rst.next()) {
Customer customer = new Customer(rst.getString("id"), rst.getString("name"), rst.getString("address"), rst.getDouble("salary"));
customerList.add(customer);
}
return customerList;
}
this is my model class
public class Customer {
private String id;
private String name;
private String salary;
private String address;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
this is my view method
private void reloadButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
ArrayList<Customer> customerList = null;
try {
try {
customerList = CustomerController.getAllCustomer();
} catch (SQLException ex) {
Logger.getLogger(veiwCustomerFrame.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (Exception ex) {
Logger.getLogger(ViewCustomerForm.class.getName()).log(Level.SEVERE, null, ex);
}
DefaultTableModel tableModel = (DefaultTableModel) customerTable.getModel();
tableModel.setRowCount(0);
for (Customer customer : customerList) {
Object rowData[] = {customer.getId(), customer.getName(), customer.getAddress(), customer.getSalary()};
tableModel.addRow(rowData);
}
} catch (Exception ex) {
Logger.getLogger(ViewCustomerForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
Instead of
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
use:
@Html.EditorFor(x => x.Remember)
That will give you a checkbox specifically for Remember
The following code fetches a JSON object from a webserver, and parses it to an NSDictionary. I have used the openweathermap API that returns a simple JSON response for this example. For keeping it simple, this code uses synchronous requests.
NSString *urlString = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk"; // The Openweathermap JSON responder
NSURL *url = [[NSURL alloc]initWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
Nslog(@"%@",res);
I dont know about XamGrid
but that's what i'll do with a standard wpf DataGrid
:
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Since the TextBlock
and the TextBox
specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.
first to list the commits use
git log --oneline
then find the SHA of the commit (Message), then I used
git log --stat 8zad24d
(8zad24d) is the SHA assosiated with the commit you are intrested in (the first couples sha example (8zad24d) you can select 4 char or 6 or 8 or the entire sha) to find the right info
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
Hey Please have a look here-
I have same answer here on my blog ..
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
To delete all stashes older than 40 days, use:
git reflog expire --expire-unreachable=40.days refs/stash
Add --dry-run
to see which stashes are deleted.
See https://stackoverflow.com/a/44829516/946850 for an explanation and much more detail.
I have to disagree, we can make $lookup work with IDs array if we preface it with $match stage.
// replace IDs array with lookup results_x000D_
db.products.aggregate([_x000D_
{ $match: { products : { $exists: true } } },_x000D_
{_x000D_
$lookup: {_x000D_
from: "products",_x000D_
localField: "products",_x000D_
foreignField: "_id",_x000D_
as: "productObjects"_x000D_
}_x000D_
}_x000D_
])
_x000D_
It becomes more complicated if we want to pass the lookup result to a pipeline. But then again there's a way to do so (already suggested by @user12164):
// replace IDs array with lookup results passed to pipeline_x000D_
db.products.aggregate([_x000D_
{ $match: { products : { $exists: true } } },_x000D_
{_x000D_
$lookup: {_x000D_
from: "products",_x000D_
let: { products: "$products"},_x000D_
pipeline: [_x000D_
{ $match: { $expr: {$in: ["$_id", "$$products"] } } },_x000D_
{ $project: {_id: 0} } // suppress _id_x000D_
],_x000D_
as: "productObjects"_x000D_
}_x000D_
}_x000D_
])
_x000D_
The answer is technically neither. According to the Java Virtual Machine Specification, the area for storing string literals is in the runtime constant pool. The runtime constant pool memory area is allocated on a per-class or per-interface basis, so it's not tied to any object instances at all. The runtime constant pool is a subset of the method area which "stores per-class structures such as the runtime constant pool, field and method data, and the code for methods and constructors, including the special methods used in class and instance initialization and interface type initialization". The VM spec says that although the method area is logically part of the heap, it doesn't dictate that memory allocated in the method area be subject to garbage collection or other behaviors that would be associated with normal data structures allocated to the heap.
You can use a 3-d party library that sends Http request and handles the response. One of the well-known products would be Apache commons HTTPClient: HttpClient javadoc, HttpClient Maven artifact. There is by far less known but much simpler HTTPClient (part of an open source MgntUtils library written by me): MgntUtils HttpClient javadoc, MgntUtils maven artifact, MgntUtils Github. Using either of those libraries you can send your REST request and receive response independently from Spring as part of your business logic
Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2
:
1,000.46
But in Germany you would change comma and point:
1.000,46
This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measure
of the Zend Framework for this task. This component will parse the string to a float by the users language.
This is how i solved my problem
xampp/mysql/data
directoryDid you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
I have also been through this problem,
First i tried setting my password of root to blank using command :
SET PASSWORD FOR root@localhost=PASSWORD('');
But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.
SET PASSWORD FOR [email protected]=PASSWORD('');
Just replace localhost with 127.0.0.1 and you are done .
Immutable simply mean unchangeable or unmodifiable. Once string object is created its data or state can't be changed
Consider bellow example,
class Testimmutablestring{
public static void main(String args[]){
String s="Future";
s.concat(" World");//concat() method appends the string at the end
System.out.println(s);//will print Future because strings are immutable objects
}
}
Let's get idea considering bellow diagram,
In this diagram, you can see new object created as "Future World". But not change "Future".Because String is immutable
. s
, still refer to "Future". If you need to call "Future World",
String s="Future";
s=s.concat(" World");
System.out.println(s);//print Future World
Why are string objects immutable in java?
Because Java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "Future".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
First, backup
your existing repo:
(a) mkdir backup
(b) cd backup
(c) git clone non_bare_repo
Second, run the following:
git clone --bare -l non_bare_repo new_bare_repo
Use some external app like sed:
<exec executable="sed" inputstring="${wersja}" outputproperty="wersjaDot">
<arg value="s/_/./g"/>
</exec>
<echo>${wersjaDot}</echo>
If you run Windows get it googling for "gnuwin32 sed".
The command s/_/./g
replaces every _
with .
This script goes well under windows. Under linux arg may need quoting.
JSONArray objects have a function getJSONObject(int index)
, you can loop through all of the JSONObjects by writing a simple for-loop:
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}
Another alternative is to just add jbundle dependency. This is more Android Studio friendly as Android Studio doesn't give the message "cannot resolve symbol..."
dependencies {
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}
Having a look at MySQL documentation for the string functions, we can also use CHAR_LENGTH()
and CHARACTER_LENGTH()
as well.
Scott Mitchell provides in a blog post solutions for removing unnecessary headers.
As already said here in other answers, for the Server
header, there is the http module solution, or a web.config solution for IIS 10+, or you can use URLRewrite instead for blanking it.
The most practical solution for an up-to-date (IIS 10 +) setup is using removeServerHeader
in the web.config:
<system.webServer>
...
<security>
<requestFiltering removeServerHeader="true" />
</security>
...
</system.webServer>
For X-AspNet-Version
and X-AspNetMvc-Version
, he provides a better way than removing them on each response: simply not generating them at all.
Use enableVersionHeader
for disabling X-AspNet-Version
, in web.config
<system.web>
...
<httpRuntime enableVersionHeader="false" />
...
</system.web>
Use MvcHandler.DisableMvcResponseHeader
in .Net Application_Start event for disabling X-AspNetMvc-Version
MvcHandler.DisableMvcResponseHeader = true;
And finally, remove in IIS configuration the X-Powered-By
custom header in web.config.
<system.webServer>
...
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
...
</system.webServer>
Beware, if you have ARR (Application Request Routing), it will also add its own X-Powered-By
, which will not be removed by custom headers settings. This one has to be removed through the IIS Manager, Editor configuration on the IIS root (not on a site): go to system.webServer/proxy
node and set arrResponseHeader
to false
. After an IISReset
, it is taken into account.
(I have found this one here, excepted this post is about old IIS 6.0 way of configuring things.)
Do not forget that solution by application code does not apply by default to header generated on static content (you may activate the runAllManagedModulesForAllRequests
for changing that, but it causes all requests to run .Net pipeline). It is not an issue for X-AspNetMvc-Version
since it is not added on static content (at least if static request are not run in .Net pipeline).
Side note: when the aim is to cloak used technology, you should also change standard .Net cookie names (.ASPXAUTH
if forms auth activated (use name
attribute on forms
tag in web.config), ASP.NET_SessionId
(use <sessionState cookieName="yourName" />
in web.config under system.web
tag), __RequestVerificationToken
(change it by code with AntiForgeryConfig.CookieName
, but unfortunately does not apply to the hidden input this system generates in the html)).
As another answer says, you can take advantage of truthy/falsy evaluations if you know that 0
is the only falsy element possibly in your array. All elements in an array are falsy iff there are not any truthy elements in it.*
>>> a = np.zeros(10)
>>> not np.any(a)
True
However, the answer claimed that any
was faster than other options due partly to short-circuiting. As of 2018, Numpy's all
and any
do not short-circuit.
If you do this kind of thing often, it's very easy to make your own short-circuiting versions using numba
:
import numba as nb
# short-circuiting replacement for np.any()
@nb.jit(nopython=True)
def sc_any(array):
for x in array.flat:
if x:
return True
return False
# short-circuiting replacement for np.all()
@nb.jit(nopython=True)
def sc_all(array):
for x in array.flat:
if not x:
return False
return True
These tend to be faster than Numpy's versions even when not short-circuiting. count_nonzero
is the slowest.
Some input to check performance:
import numpy as np
n = 10**8
middle = n//2
all_0 = np.zeros(n, dtype=int)
all_1 = np.ones(n, dtype=int)
mid_0 = np.ones(n, dtype=int)
mid_1 = np.zeros(n, dtype=int)
np.put(mid_0, middle, 0)
np.put(mid_1, middle, 1)
# mid_0 = [1 1 1 ... 1 0 1 ... 1 1 1]
# mid_1 = [0 0 0 ... 0 1 0 ... 0 0 0]
Check:
## count_nonzero
%timeit np.count_nonzero(all_0)
# 220 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.count_nonzero(all_1)
# 150 ms ± 4.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
### all
# np.all
%timeit np.all(all_1)
%timeit np.all(mid_0)
%timeit np.all(all_0)
# 56.8 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.4 ms ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 55.9 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# sc_all
%timeit sc_all(all_1)
%timeit sc_all(mid_0)
%timeit sc_all(all_0)
# 44.4 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.7 ms ± 599 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 288 ns ± 6.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
### any
# np.any
%timeit np.any(all_0)
%timeit np.any(mid_1)
%timeit np.any(all_1)
# 60.7 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 60 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.7 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# sc_any
%timeit sc_any(all_0)
%timeit sc_any(mid_1)
%timeit sc_any(all_1)
# 41.7 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 287 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
* Helpful all
and any
equivalences:
np.all(a) == np.logical_not(np.any(np.logical_not(a)))
np.any(a) == np.logical_not(np.all(np.logical_not(a)))
not np.all(a) == np.any(np.logical_not(a))
not np.any(a) == np.all(np.logical_not(a))
Had to restart the Eclipse after completing the installation of ARM EABI v7a system image.
The problem with <select>
is, it's sometimes disconnected with the state of what's currently rendered and unless something has changed in the option list, no change value is returned. This can be a problem when trying to select the first option from a list. The following code can get the first-option the first-time selected, but onchange="changeFontSize(this)"
by its self would not. There are methods described above using a dummy option to force a user to make a change value to pickup the actual first value, such as starting the list with an empty value. Note: onclick would call the function twice, the following code does not, but solves the first-time problem.
<label>Font Size</label>
<select name="fontSize" id="fontSize" onfocus="changeFontSize(this)" onchange="changeFontSize(this)">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="extraLarge">Extra large</option>
</select>
<script>
function changeFontSize(x){
body=document.getElementById('body');
if (x.value=="extraLarge") {
body.style.fontSize="25px";
} else {
body.style.fontSize=x.value;
}
}
</script>
If you are developing test driven (TDD), you will test your private methods.
Not sure exactly what all the code you posted does, but to answer the question posed in the title, you can use + as the normal string concat function as well as str().
"hello " + str(10) + " world" = "hello 10 world"
Hope that helps!
Such is how I have it embedded and outputted to my HTML web page:
<div class="container">
<p class="text-center">Copyright ©
<script>
var CurrentYear = new Date().getFullYear()
document.write(CurrentYear)
</script>
</p>
</div>
Output to HTML page is as follows:
Copyright © 2018
They are a number of things to worry about when connecting to SQL Server on another machine.
Very often SQL Server may be running as a default instance which means you can simply specify the hostname/IP address, but you may encounter a scenario where it is running as a named instance (SQL Server Express Edition for instance). In this scenario you'll have to specify the hostname/instance name.
Yes if the structure is of the same type. Think it as a memory copy.
Since you're using GNUmake, use a pattern rule for compiling object files:
$(OBJDIR)/%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
What you should do is to serialize your form data and send it to the controller action. ASP.NET MVC will bind the form data to the EditPostViewModel
object( your action method parameter), using MVC model binding feature.
You can validate your form at client side and if everything is fine, send the data to server. The valid()
method will come in handy.
$(function () {
$("#yourSubmitButtonID").click(function (e) {
e.preventDefault();
var _this = $(this);
var _form = _this.closest("form");
var isvalid = _form .valid(); // Tells whether the form is valid
if (isvalid)
{
$.post(_form.attr("action"), _form.serialize(), function (data) {
//check the result and do whatever you want
})
}
});
});
When I got this error, it may have been because of my UPDATE syntax being wrong, but after I fixed the update query I got the same error again...so I went to the ODBC Data Source Administrator
and found that my connection was read-only. After I made the connection read-write and re-connected it worked just fine.
Add only the class center-block
to an image, this works with Bootstrap 4 as well:
<img src="..." alt="..." class="center-block" />
Note: center-block
works even when img-responsive
is used
To anyone else looking for this, I wasn't able to use certutil -importpfx
into a specific store, and I didn't want to download the importpfx tool supplied by jaspernygaard's answer in order to avoid the requirement of copying the file to a large number of servers. I ended up finding my answer in a powershell script shown here.
The code uses System.Security.Cryptography.X509Certificates
to import the certificate and then moves it into the desired store:
function Import-PfxCertificate {
param([String]$certPath,[String]$certRootStore = “localmachine”,[String]$certStore = “My”,$pfxPass = $null)
$pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
if ($pfxPass -eq $null)
{
$pfxPass = read-host "Password" -assecurestring
}
$pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet")
$store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
}
The getRow()
method will always yield 0 after a query:
Retrieves the current row number.
Second, you output totalrec
but never assign anything to it.
I'd define that I want a maximum number of non-] characters between [
and ]
. These need to be escaped with backslashes (and in Java, these need to be escaped again), and the definition of non-] is a character class, thus inside [
and ]
(i.e. [^\\]]
). The result:
FOO\\[([^\\]]+)\\]
Use Array.prototype.concat.apply to handle multiple arrays' concatenation:
var resultArray = Array.prototype.concat.apply([], arrayOfArraysToConcat);
Example:
var a1 = [1, 2, 3],
a2 = [4, 5],
a3 = [6, 7, 8, 9];
Array.prototype.concat.apply([], [a1, a2, a3]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
I used the following solution:
.svg
image to JSX with https://svg2jsx.herokuapp.com/react-native-svg
component with https://svgr.now.sh/ (check the "React Native checkbox)The accepted answer above did not work for me, because it ordered the weeks by alphabetical order, not chronological order:
2012/1
2012/10
2012/11
...
2012/19
2012/2
Here's my solution to count and group by week:
SELECT CONCAT(YEAR(date), '/', WEEK(date)) AS week_name,
YEAR(date), WEEK(date), COUNT(*)
FROM column_name
GROUP BY week_name
ORDER BY YEAR(DATE) ASC, WEEK(date) ASC
Generates:
YEAR/WEEK YEAR WEEK COUNT
2011/51 2011 51 15
2011/52 2011 52 14
2012/1 2012 1 20
2012/2 2012 2 14
2012/3 2012 3 19
2012/4 2012 4 19
Non greedy search in vim is done using {-} operator. Like this:
%s/style=".\{-}"//g
just try:
:help non-greedy
java.time has the Temporal interface which you can use to create Instant objects from most of the the time classes. Instant represents milliseconds on the timeline in the Epoch - the base reference for all other dates and times.
We need to convert the Date into a ZonedDateTime, with a Time and a Zone, to do the conversion:
LocalDate ldate = ...;
Instant instant = Instant.from(ldate.atStartOfDay(ZoneId.of("GMT")));
Date date = Date.from(instant);
Not every browser (e.g. IE 6) has options to remember credentials.
One thing you can do is to (once the user successfully logs in) store the user information via cookie and have a "Remember Me on this machine" option. That way, when the user comes again (even if he's logged off), your web application can retrieve the cookie and get the user information (user ID + Session ID) and allow him/her to carry on working.
Hope this can be suggestive. :-)
import java.util.Date;
public class IsDateBetween {
public static void main (String[] args) {
IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date
}
public IsDateBetween(String dd) {
long from=Date.parse("01/01/2000"); // From some date
long to=Date.parse("12/12/2010"); // To Some Date
long check=Date.parse(dd);
int x=0;
if((check-from)>0 && (to-check)>0)
{
x=1;
}
System.out.println ("From Date is greater Than ToDate : "+x);
}
}
The z-index
property only works on elements with a position
value other than static
(e.g. position: absolute;
, position: relative;
, or position: fixed
).
There is also position: sticky;
that is supported in Firefox, is prefixed in Safari, worked for a time in older versions of Chrome under a custom flag, and is under consideration by Microsoft to add to their Edge browser.
Important
For regular positioning, be sure to include position: relative
on the elements where you also set the z-index
. Otherwise, it won't take effect.
For existing project end existing repository with files:
git init
git remote add origin <.git>
git checkout -b master
git branch --set-upstream-to=origin/master master
git pull --allow-unrelated-histories
Use JavaScript by adding an onChange
attribute to your input tags
<input onChange="this.form.submit()" ... />
You should use whatever is cheapest and best known for your platform and call it a day. Obfuscation of high-level languages is a hard problem, because VM opcode streams don't suffer from the two biggest problems native opcode streams do: function/method identification and register aliasing.
What you should know about bytecode reversing is that it is already standard practice for security testers to review straight X86 code and find vulnerabilities in it. In raw X86, you cannot necessarily even find valid functions, let alone track a local variable throughout a function call. In almost no circumstances do native code reversers have access to function and variable names --- unless they're reviewing Microsoft code, for which MSFT helpfully provides that information to the public.
"Dotfuscation" works principally by scrambling function and variable names. It's probably better to do this than publish code with debug-level information, where the Reflector is literally giving up your source code. But anything you do beyond this is likely to get into diminishing returns.
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
int version = Build.VERSION.SDK_INT;
String versionRelease = Build.VERSION.RELEASE;
Log.e("MyActivity", "manufacturer " + manufacturer
+ " \n model " + model
+ " \n version " + version
+ " \n versionRelease " + versionRelease
);
E/MyActivity: manufacturer ManufacturerX
model SM-T310
version 19
versionRelease 4.4.2
Looks like this is an ancient post really :-) But guys, the best workaround I have for this, to be 100% that it works without complicated code, is to use both functions of encoding/decoding to base64. These are atob() and btoa(). By far the easiest and best way, no need to worry if you missed any characters to be escaped.
George
I use hive jdbc in a java maven project and have the same issues.
My method is to add a log4j2.xml file under src/main/java/resources
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyClassName {
private static final Logger LOG = LoggerFactory.getLogger(MyClassName.class);
}
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="<your_package_name>.<your_class_name>" level="debug">
<AppenderRef ref="Console"/>
</Logger>
<Root level="WARN">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
This is what worked for me (On RHEL, CentOS:
sudo yum install postgresql postgresql-devel python-devel
And now include the path to your postgresql binary dir with you pip install:
sudo PATH=$PATH:/usr/pgsql-9.3/bin/ pip install psycopg2
Make sure to include the correct path. Thats all :)
UPDATE: For python 3, please install python3-devel
instead of python-devel
Put your breakpoint. Right-click the breakpoint image on the margin and choose Breakpoint Properties:
Configure condition as you see fit:
Developer Tools > Elements > Computed > Rendered Fonts
The picture you attached to your question shows the Style
tab. If you change to the next tab, Computed
, you can check the Rendered Fonts, that shows the actual font-family rendered.
Right click in the project explorer on whichever module is giving errors. Go to PyDev->Remove Error Markers.
For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.
Here is a link to the caniuse js MutationObserver
Simple usage with powerful results.
var observer = new MutationObserver(function (mutations) {
//your action here
});
//set up your configuration
//this will watch to see if you insert or remove any children
var config = { subtree: true, childList: true };
//start observing
observer.observe(elementTarget, config);
When you don't need to observe any longer just disconnect.
observer.disconnect();
Check out the MDN documentation for more information
If your Activity extends ListActivity, you can simply override the OnListItemClick()
method like so:
/** {@inheritDoc} */
@Override
protected void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
// TODO : Logic
}
If dgv(11, dgv.CurrentRow.Index).Selected = True Then
dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
Exit Sub
End If
Would this relationship not be better expressed as a one-to-many foreign key relationship to a Friends
table? I understand that myFriends
are just strings but I would think that a better design would be to create a Friend
model and have MyClass
contain a foreign key realtionship to the resulting table.
Use square brackets instead of quotation marks:
IF [%1] == [] GOTO MyLabel
Parentheses are insecure: only use square brackets.
As of the latest versions of SQLite 3 you can issue:
.fullschema
to see all of your create statements.
This worked for me, based on your code, generating a 93Mb png image with color noise and the desired dimensions:
import matplotlib.pyplot as plt
import numpy
w = 7195
h = 3841
im_np = numpy.random.rand(h, w)
fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(im_np, aspect='normal')
fig.savefig('figure.png', dpi=1)
I am using the last PIP versions of the Python 2.7 libraries in Linux Mint 13.
Hope that helps!
What regex engine are you using? Most of them will support the following expression:
\{\d+:\d+\}
The \d
is actually shorthand for [0-9]
, but the important part is the addition of +
which means "one or more".
this is the code of your button
<a href="AddNewUserAdmin"
class="btn btn-info "
ng-click="showaddnewuserpage()">
<span class="glyphicon glyphicon-plus-sign"></span> Add User</a>
in the controller just add this function.
var app = angular.module('userAPP', []);
app.controller('useraddcontroller', function ($scope, $http, $window) {
$scope.showaddnewuserpage = function () {
$window.location.href = ('/AddNewUserAdmin');
}
});
You simply need to use simpleCart
It is a free and open-source javascript shopping cart that easily integrates with your current website.
You will get the full source code at github
Writing the properties file with multiple comments is not supported. Why ?
PropertyFile.java
public class PropertyFile extends Task {
/* ========================================================================
*
* Instance variables.
*/
// Use this to prepend a message to the properties file
private String comment;
private Properties properties;
The ant property file task is backed by a java.util.Properties
class which stores comments using the store() method. Only one comment is taken from the task and that is passed on to the Properties
class to save into the file.
The way to get around this is to write your own task that is backed by commons properties instead of java.util.Properties
. The commons properties file is backed by a property layout which allows settings comments for individual keys in the properties file. Save the properties file with the save() method and modify the new task to accept multiple comments through <comment>
elements.
JObjects can be enumerated via JProperty objects by casting it to a JToken:
foreach (JProperty x in (JToken)obj) { // if 'obj' is a JObject
string name = x.Name;
JToken value = x.Value;
}
If you have a nested JObject inside of another JObject, you don't need to cast because the accessor will return a JToken:
foreach (JProperty x in obj["otherObject"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects
string name = x.Name;
JToken value = x.Value;
}
You can use the "export" solution just like what other guys have suggested. I'd like to provide you with another solution for permanent convenience: you can use any path as GOPATH when running Go commands.
Firstly, you need to download a small tool named gost
: https://github.com/byte16/gost/releases . If you use ubuntu, you can download the linux version(https://github.com/byte16/gost/releases/download/v0.1.0/gost_linux_amd64.tar.gz).
Then you need to run the commands below to unpack it :
$ cd /path/to/your/download/directory
$ tar -xvf gost_linux_amd64.tar.gz
You would get an executable gost
. You can move it to /usr/local/bin
for convenient use:
$ sudo mv gost /usr/local/bin
Run the command below to add the path you want to use as GOPATH into the pathspace gost
maintains. It is required to give the path a name which you would use later.
$ gost add foo /home/foobar/bar # 'foo' is the name and '/home/foobar/bar' is the path
Run any Go command you want in the format:
gost goCommand [-p {pathName}] -- [goFlags...] [goArgs...]
For example, you want to run go get github.com/go-sql-driver/mysql
with /home/foobar/bar
as the GOPATH, just do it as below:
$ gost get -p foo -- github.com/go-sql-driver/mysql # 'foo' is the name you give to the path above.
It would help you to set the GOPATH and run the command. But remember that you have added the path into gost
's pathspace. If you are under any level of subdirectories of /home/foobar/bar
, you can even just run the command below which would do the same thing for short :
$ gost get -- github.com/go-sql-driver/mysql
gost
is a Simple Tool of Go which can help you to manage GOPATHs and run Go commands. For more details about how to use it to run other Go commands, you can just run gost help goCmdName
. For example you want to know more about install
, just type words below in:
$ gost help install
You can also find more details in the README of the project: https://github.com/byte16/gost/blob/master/README.md
There's another way to overcome this problem. Whether it's a better way depends on your situation.
The problem results from lazy loading, so one way to avoid it is not to have lazy loading, through the use of Include:
var results = myContext.Customers
.Include(x => x.Orders)
.Include(x => x.Addresses)
.Include(x => x.PaymentMethods);
If you use the appropriate Include
s, you can avoid enabling MARS. But if you miss one, you'll get the error, so enabling MARS is probably the easiest way to fix it.
Please use the following style. margin:auto
normally used to center align the content. display:table
is needed for span
element
<span style="margin:auto; display:table; border:1px solid red;">
This is some text in a div element!
</span>
FORCE_INDEX
is going to be deprecated after MySQL 8:
Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in
a future release of MySQL, and at some time thereafter to be removed altogether.
https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
You should be using JOIN_INDEX
, GROUP_INDEX
, ORDER_INDEX
, and INDEX
instead, for v8.
You can do it without dealing with encoding by using BlockCopy:
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);
If your icons are in an icon stack you can use the following code:
.icon-stack{ margin: auto; display: block; }
You can use the following code to fit your system screen and task bar is visible.
private void Form1_Load(object sender, EventArgs e)
{
// hide max,min and close button at top right of Window
this.FormBorderStyle = FormBorderStyle.None;
// fill the screen
this.Bounds = Screen.PrimaryScreen.Bounds;
}
No need to use:
this.TopMost = true;
That line interferes with alt+tab
to switch to other application. ("TopMost" means the window stays on top of other windows, unless they are also marked "TopMost".)
Another simple way to do this: go on the origin branch and do a merge --squash
. This command doesn't do the "squashed" commit. when you do it, all commit messages of yourBranch will be gathered.
$ git checkout master
$ git merge --squash yourBranch
$ git commit # all commit messages of yourBranch in one, really useful
> [status 5007e77] Squashed commit of the following: ...
Are you using unmanaged code? If you are not using unmanaged code, according to Microsoft, memory leaks in the traditional sense are not possible.
Memory used by an application may not be released however, so an application's memory allocation may grow throughout the life of the application.
From How to identify memory leaks in the common language runtime at Microsoft.com
A memory leak can occur in a .NET Framework application when you use unmanaged code as part of the application. This unmanaged code can leak memory, and the .NET Framework runtime cannot address that problem.
Additionally, a project may only appear to have a memory leak. This condition can occur if many large objects (such as DataTable objects) are declared and then added to a collection (such as a DataSet). The resources that these objects own may never be released, and the resources are left alive for the whole run of the program. This appears to be a leak, but actually it is just a symptom of the way that memory is being allocated in the program.
For dealing with this type of issue, you can implement IDisposable. If you want to see some of the strategies for dealing with memory management, I would suggest searching for IDisposable, XNA, memory management as game developers need to have more predictable garbage collection and so must force the GC to do its thing.
One common mistake is to not remove event handlers that subscribe to an object. An event handler subscription will prevent an object from being recycled. Also, take a look at the using statement which allows you to create a limited scope for a resource's lifetime.
I'd question the wisdom, but perhaps:
source.TakeWhile(x => x != value).Count();
(using EqualityComparer<T>.Default
to emulate !=
if needed) - but you need to watch to return -1 if not found... so perhaps just do it the long way
public static int IndexOf<T>(this IEnumerable<T> source, T value)
{
int index = 0;
var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
foreach (T item in source)
{
if (comparer.Equals(item, value)) return index;
index++;
}
return -1;
}
You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.
function updateStyleSheet(filename) {
newstylesheet = "style_" + filename + ".css";
if ($("#dynamic_css").length == 0) {
$("head").append("<link>")
css = $("head").children(":last");
css.attr({
id: "dynamic_css",
rel: "stylesheet",
type: "text/css",
href: newstylesheet
});
} else {
$("#dynamic_css").attr("href",newstylesheet);
}
}
The example above is copied from:
$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');
The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.
I shall try the solution with jQuery, for sure it should give a nice result. Of course you have to load jQuery ... What about a pop-up with something like this? Of course this is dependant on the user authorizing pop-ups.
<html>
<head>
<script language="javascript">
var ret;
function returnfunction()
{
alert(ret);
}
</script>
</head>
<body>
<form>
<label id="QuestionToAsk" name="QuestionToAsk">Here is talked.</label><br />
<input type="button" value="Yes" name="yes" onClick="ret=true;returnfunction()" />
<input type="button" value="No" onClick="ret=false;returnfunction()" />
</form>
</body>
</html>
This can be done pretty easily. All I did was move the existing directory, not under version control, to a temporary directory. Then I checked out the SVN version to my correct directory name, copied the files from the temporary directory into the SVN directory, and reverted the files in the SVN directory. If that does not make sense there is an example below:
/usr/local/www
mv www temp_www
svn co http://www.yourrepo.com/therepo www
cp -pR ./temp_www/* ./www
svn revert -R ./www/*
svn update
I hope this helps and am not sure why just a simple SVN update did not change the files back?
Here is a side-by-side comparison of several application starters/generators and other technologies including MEAN.js, MEAN.io, and cleverstack. I keep adding alternatives as I find time and as that happens, the list of potentially provided benefits keeps growing too. Today it's up to around 1600. If anyone wants to help improve its accuracy or completeness, click the next link and do a questionnaire about something you know.
Compare app technologies project
From this database, the system generates reports like the following:
Simple and easiest steps
Ctrl + Z
----------> Suspends the processbg
--------------> Resumes and runs backgrounddisown %1
-------------> required only if you need to detach from the terminalYou can do exactly that via the various sizeWithFont:
methods in NSString UIKit Additions. In your case the simplest variant should suffice (since you don't have multi-line labels):
NSString *someString = @"Hello World";
UIFont *yourFont = // [UIFont ...]
CGSize stringBoundingBox = [someString sizeWithFont:yourFont];
There are several variations of this method, eg. some consider line break modes or maximum sizes.
Use a slice, not an arrray. Just create it using
reg := []string {"a","b","c"}
An alternative would have been to convert your array to a slice when joining :
fmt.Println(strings.Join(reg[:],","))
Read the Go blog about the differences between slices and arrays.
To view the EntityValidationErrors
collection, add the following Watch expression to the Watch window.
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
I'm using visual studio 2013
In javascript, it is not possible but yes with the help of “Web Clips” we can create a "add to home screen" icon or shortcut in iPhone( by the code file of .mobileconfig)
http://appdistro.cttapp.com/webclip/
after create a mobileconfig file we can pass this url in iphone safari browser install certificate and after done it check your iphone home screen there is a shortcut icon of your Web page or webapp..
Short answer is:
junk$nm[junk$nm %in% "B"] <- "b"
Take a look at Index vectors in R Introduction (if you don't read it yet).
EDIT. As noticed in comments this solution works for character vectors so fail on your data.
For factor best way is to change level:
levels(junk$nm)[levels(junk$nm)=="B"] <- "b"
If using a where clause be sure to include .First()
if you do not want a IQueryable object.
One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:
import math
import numpy
import scipy
import sympy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False
Whilst this is counter intuitive this is the way that i sped up this operation by a huge amount.
Exactly what i was doing:
ArrayList < HashMap < String , String >> results; // This has been filled with a whole bunch of results
ArrayList < HashMap < String , String > > discard = findResultsToDiscard(results);
results.removeall(discard);
However the remove all method was taking upwards of 6 seconds (NOT including the method to get the discard results) to remove approximately 800 results from an array of 2000 (ish).
I tried the iterator method suggested by gustafc and others on this post.
This did speed up the operation slightly (down to about 4 seconds) however this was still not good enough. So i tried something risky...
ArrayList < HashMap < String, String>> results;
List < Integer > noIndex = getTheDiscardedIndexs(results);
for (int j = noIndex.size()-1; j >= 0; j-- ){
results.remove(noIndex.get(j).intValue());
}
whilst the getTheDiscardedIndexs save an array of index's rather then an array of HashMaps. This it turns out sped up removing objects much quicker ( about 0.1 of a second now) and will be more memory efficient as we dont need to create a large array of results to remove.
Hope this helps someone.
Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.
First, some definitions:
Bar
is a TypeName in Public Class Bar
, or in Dim Foo as Bar
. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.System.Type
objects which contain a value. This value indicates a type; just like a String
would take some text or an Int
would take a number, except we are storing types instead of text or numbers. Type
objects contain the type definitions, as well as its corresponding TypeName.Second, the theory:
Foo.GetType()
returns a Type
object which contains the type for the variable Foo
. In other words, it tells you what Foo
is an instance of.GetType(Bar)
returns a Type
object which contains the type for the TypeName Bar
.In some instances, the type an object has been Cast
to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer
cast into an Object
:
Dim MyVal As Integer = 42
Dim MyObj As Object = CType(MyVal, Object)
So, is MyObj
of type Object
or of type Integer
? MyObj.GetType()
will tell you it is an Integer
.
Type Of Foo Is Bar
feature, which allows you to ascertain a variable Foo
is compatible with a TypeName Bar
. Type Of MyObj Is Integer
and Type Of MyObj Is Object
will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it.
More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarksThe test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.
Public Sub TestMethod1()
Dim MyValInt As Integer = 42
Dim MyValDble As Double = CType(MyValInt, Double)
Dim MyObj As Object = CType(MyValDble, Object)
Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
Debug.Print(MyObj.GetType.ToString) 'Returns System.Double
Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False
Debug.Print(TypeOf MyObj Is Integer) 'Returns False
Debug.Print(TypeOf MyObj Is Double) '# Returns True
Debug.Print(TypeOf MyObj Is Object) '# Returns True
End Sub
EDIT
You can also use Information.TypeName(Object)
to get the TypeName of a given object. For example,
Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"
@media screen and (max-width:480px) { … }
screen
here is to set the screen size of the media query. E.g the maximum width of the display area is 480px. So it is specifying the screen as opposed to the other available media types.
@media only screen and (max-width: 480px;) { … }
only screen
here is used to prevent older browsers that do not support media queries with media features from applying the specified styles.
I've found 3rd Party Libraries Like this one:
https://github.com/Tuszy/MTLabel
To be the easiest solution.
Used pattern :
ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"
Used reference file:
'<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>'
Example for Input:
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
You might be interested in visiting this blog post concerning all the possible ways to assign an attribute or update record (updated to Rails 4) update_attribute, update, update_column, update_columns etc.
http://www.davidverhasselt.com/set-attributes-in-activerecord/. For example it differs in aspects such as running validations, touching object's updated_at or triggering callbacks.
As an answer to the OP's question update_attribute
does not by pass callbacks.
Navigate to the folder on your new machine you want to download from git on git bash.
Use below command to download the code from any branch you like
git clone 'git ssh url' -b 'Branch Name'
It will download the respective branch code.
Swift 4.1
use it when you delete row using selectedTag of row.
self.tableView.beginUpdates()
self.yourArray.remove(at: self.selectedTag)
print(self.allGroups)
let indexPath = NSIndexPath.init(row: self.selectedTag, section: 0)
self.tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)
self.tableView.endUpdates()
self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .automatic)
Since x!=x
returns the same boolean array with np.isnan(x)
(because np.nan!=np.nan
would return True
), you could also write:
np.argwhere(x!=x)
However, I still recommend writing np.argwhere(np.isnan(x))
since it is more readable. I just try to provide another way to write the code in this answer.
In case you prefer more functional style:
// map - instance of google Map v3
// markers - array of Markers
var bounds = markers.reduce(function(bounds, marker) {
return bounds.extend(marker.getPosition());
}, new google.maps.LatLngBounds());
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
One thing you can do is to use raw SQL:
case class Bar(x1: Int, y1: Int, z1: Int, v1: String)
case class Foo(x2: Int, y2: Int, z2: Int, v2: String)
val bar = sqlContext.createDataFrame(sc.parallelize(
Bar(1, 1, 2, "bar") :: Bar(2, 3, 2, "bar") ::
Bar(3, 1, 2, "bar") :: Nil))
val foo = sqlContext.createDataFrame(sc.parallelize(
Foo(1, 1, 2, "foo") :: Foo(2, 1, 2, "foo") ::
Foo(3, 1, 2, "foo") :: Foo(4, 4, 4, "foo") :: Nil))
foo.registerTempTable("foo")
bar.registerTempTable("bar")
sqlContext.sql(
"SELECT * FROM foo LEFT JOIN bar ON x1 = x2 AND y1 = y2 AND z1 = z2")
As of Docker version 1.10.3, build 20f81dd
Unless you told Docker otherwise, Docker always launches your containers in the bridge network. So you can try this command below:
docker network inspect bridge
Which should then return a Containers section which will display the IP address for that running container.
[
{
"Name": "bridge",
"Id": "40561e7d29a08b2eb81fe7b02736f44da6c0daae54ca3486f75bfa81c83507a0",
"Scope": "local",
"Driver": "bridge",
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.17.0.0/16"
}
]
},
"Containers": {
"025d191991083e21761eb5a56729f61d7c5612a520269e548d0136e084ecd32a": {
"Name": "drunk_leavitt",
"EndpointID": "9f6f630a1743bd9184f30b37795590f13d87299fe39c8969294c8a353a8c97b3",
"IPv4Address": "172.17.0.2/16",
"IPv6Address": ""
}
},
"Options": {
"com.docker.network.bridge.default_bridge": "true",
"com.docker.network.bridge.enable_icc": "true",
"com.docker.network.bridge.enable_ip_masquerade": "true",
"com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
"com.docker.network.bridge.name": "docker0",
"com.docker.network.driver.mtu": "1500"
}
}
]
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
IndexOf
accepts also a reference type. Suppose the following scenario:
var arr = [{item: 1}, {item: 2}, {item: 3}];_x000D_
var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]_x000D_
var l = found.length;_x000D_
_x000D_
while(l--) {_x000D_
var index = arr.indexOf(found[l])_x000D_
arr.splice(index, 1);_x000D_
}_x000D_
_x000D_
console.log(arr.length); //1
_x000D_
Differently:
var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
while(!found && l--) {
found = arr[l] === item2;
}
console.log(l, arr[l]);// l is index, arr[l] is the item you look for
In case you want an awk-only solution without creating a temporary file and usable with version!=(gawk 4.1.0):
awk '{a[b++]=$0} END {for(c=0;c<=b;c++)print a[c]>ARGV[1]}' file
Instead of creating a new virtual environment, you just have to access to your initially created virtual environment when you started the project.
You just have to do the following in your command line:
1)pipenv shell
to access the backend virtual environment that you have initially created.
2) Then, python manage.py runserver
Let me know if it works for you or not.
If you have Homebrew installed, you can do this.
# check the zsh info
brew info zsh
# install zsh
brew install --without-etcdir zsh
# add shell path
sudo vim /etc/shells
# add the following line into the very end of the file(/etc/shells)
/usr/local/bin/zsh
# change default shell
chsh -s /usr/local/bin/zsh
Hope it helps, thanks.