You need to make the decode function return an array by passing in the true
parameter.
json_decode(file_get_contents($file),true);
Use console.log(JSON.stringify(result))
to get the JSON in a string format.
EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty
and access the property if it does exist:
var obj = {id : "007", name : "James Bond"};
console.log(obj); // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj)); //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
console.log(obj.id); //007
}
it occured when I changed the applicationId in app gradle file. It works for me after I sync gradle.
If you want to get the index of the selected radio button inside a control you can use this method:
public static int getCheckedRadioButton(Control c)
{
int i;
try
{
Control.ControlCollection cc = c.Controls;
for (i = 0; i < cc.Count; i++)
{
RadioButton rb = cc[i] as RadioButton;
if (rb.Checked)
{
return i;
}
}
}
catch
{
i = -1;
}
return i;
}
Example use:
int index = getCheckedRadioButton(panel1);
The code isn't that well tested, but it seems the index order is from left to right and from top to bottom, as when reading a text. If no radio button is found, the method returns -1.
Update: It turned out my first attempt didn't work if there's no radio button inside the control. I added a try and catch block to fix that, and the method now seems to work.
or try this (from http://drupal.org/node/870058)
Download wkhtmltopdf. Or better install it with a package manager:
sudo apt-get install wkhtmltopdf
Extract it and move it to /usr/local/bin/
wkhtmltopdf
so that now you have an executable at /usr/local/bin/wkhtmltopdf
sudo chmod a+x /usr/local/bin/wkhtmltopdf
Install required support packages.
sudo apt-get install openssl build-essential xorg libssl-dev
Check to see if it works: run
/usr/local/bin/wkhtmltopdf http://www.google.com test.pdf
If it works, then you are done. If you get the error "Cannot connect to X server" then continue to number 7.
We need to run it headless on a 'virtual' x server. We will do this with a package called xvfb.
sudo apt-get install xvfb
We need to write a little shell script to wrap wkhtmltopdf in xvfb. Make a file called wkhtmltopdf.sh
and add the following:
xvfb-run -a -s "-screen 0 640x480x16" wkhtmltopdf "$@"
Move this shell script to /usr/local/bin
, and set permissions:
sudo chmod a+x /usr/local/bin/wkhtmltopdf.sh
Check to see if it works once again: run
/usr/local/bin/wkhtmltopdf.sh http://www.google.com test.pdf
Note that http://www.google.com may throw an error like "A finished ResourceObject received a loading finished signal. This might be an indication of an iframe taking to long to load." You may want to test with a simpler page like http://www.example.com
.
->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;
->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;
->DECLARE val1 int;
->DECLARE val2 int;
->SELECT student__id,student_name INTO val1,val2 FROM student_details;
--HAPPY CODING--
class Demo(models.Model):
...
@property
def property_name(self):
...
If you want to use the same property name:
class DemoSerializer(serializers.ModelSerializer):
property_name = serializers.ReadOnlyField()
class Meta:
model = Product
fields = '__all__' # or you can choose your own fields
If you want to use different property name, just change this:
new_property_name = serializers.ReadOnlyField(source='property_name')
What you can do and what you should do are different matters.
If the list is very short, or you are only ever going to call find once then use the linear approach above.
However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.
This worked for me:
<script>
jQuery.noConflict();
// Use jQuery via jQuery() instead of via $()
jQuery(document).ready(function(){
jQuery("div").hide();
});
</script>
Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".
Read full reason here: https://api.jquery.com/jquery.noconflict/
If this solves your issue, it's likely another library is also using $.
You can use order() to sort date data.
# Sort date ascending order
d[order(as.Date(d$V3, format = "%d/%m/%Y")),]
# Sort date descending order
d[rev(order(as.Date(d$V3, format = "%d/%m/%y"))),]
Hope this helps,
Link to my quora answer https://qr.ae/TWngCe
Thanks
You could use
Calendar cal = Calendar.getInstance();
cal.setTime(beginupd);
long millis = cal.getTimeInMillis();
Lodash has a "map" function that works just like jQuerys:
var myArr = [{ name: "john", age:23 },_x000D_
{ name: "john", age:43 },_x000D_
{ name: "jimi", age:10 },_x000D_
{ name: "bobi", age:67 }];_x000D_
_x000D_
var johns = _.map(myArr, function(o) {_x000D_
if (o.name == "john") return o;_x000D_
});_x000D_
_x000D_
// Remove undefines from the array_x000D_
johns = _.without(johns, undefined)
_x000D_
/*
It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"[email protected]","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"[email protected]"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"[email protected]"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"[email protected]"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
//use the add method from the list and returns it.
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Marcio's excellent solution to this question was of great help to me in adding subviews of any kind to a UIActionSheet.
For reasons that are not (yet) entirely clear to me, the bounds of the UIActionSheet can only be set after it has been displayed; both sagar's and marcio's solutions successfully address this with a setBounds:CGRectMake(...) message being sent to the actionsheet after it is shown.
However, setting the UIActionSheet bounds after the sheet has been displayed creates a jumpy transition when the ActionSheet appeaars, where it "pops" into view, and then only scrolls in over the final 40 pixels or so.
When sizing a UIPickerView after adding subviews, I recommend wrapping the setBounds message sent to the actionSheet inside an animation block. This will make the entrance of the actionSheet appear smoother.
UIActionSheet *actionSheet = [[[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
// add one or more subviews to the UIActionSheet
// this could be a UIPickerView, or UISegmentedControl buttons, or any other
// UIView. Here, let's just assume it's already set up and is called
// (UIView *)mySubView
[actionSheet addSubview:myView];
// show the actionSheet
[actionSheet showInView:[UIApplication mainWindow]];
// Size the actionSheet with smooth animation
[UIView beginAnimations:nil context:nil];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
[UIView commitAnimations];
You can just simply add the following code;
<a class="btn btn-primary" href="http://localhost:8080/Home" role="button">Home Page</a>
Maybe it's better to use the path detecting mouse.
In BrowserClosureNotice you have a demo example and pure javascript library to do it.
It isn't perfect, but avoid problems of document or mouse events...
Let's take two questions, example string "2014-04-08 12:30"
How can I obtain a LocalDateTime instance from the given string?
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
// Parsing or conversion
final LocalDateTime dt = LocalDateTime.parse("2014-04-08 12:30", formatter)
dt
should allow you to all date-time related operations
How can I then convert the LocalDateTime instance back to a string with the same format?
final String date = dt.format(formatter)
In Python 3:
a = (None, False, 0, 1)
assert next(filter(None, a)) == 1
In Python 2.6:
a = (None, False, 0, 1)
assert next(iter(filter(None, a))) == 1
EDIT: I thought it was obvious, but apparently not: instead of None
you can pass a function (or a lambda
) with a check for the condition:
a = [2,3,4,5,6,7,8]
assert next(filter(lambda x: x%2, a)) == 3
I had this and managed to fix it using this SO answer: Metadata file '.dll' could not be found
I had to uncheck all of the boxes, click Apply, reenable all of the checkboxes and then click apply again, but it fixed the problem.
Try this
Sheets("your sheetname").range("A5:X50").Value = ""
You can also use
ActiveSheet.range
You did forget to include stdafx.h
in your source (as I cannot see it your code). If you didn't, then make sure #include "stdafx.h"
is the first line in your .cpp
file, otherwise you will see the same error even if you've included "stdafx.h"
in your source file (but not in the very beginning of the file).
You have to check which version of Excel you are targeting?
If you are targeting Excel 2010 use version 14 (as per Grant's screenshot answer), Excel 2007 use version 12 . You can not support Excel 2003 using vS2012 as they do not have the correct Interop dll installed.
The best way to wait for page loads when using the Java bindings for WebDriver is to use the Page Object design pattern with PageFactory. This allows you to utilize the AjaxElementLocatorFactory
which to put it simply acts as a global wait for all of your elements. It has limitations on elements such as drop-boxes or complex javascript transitions but it will drastically reduce the amount of code needed and speed up test times. A good example can be found in this blogpost. Basic understanding of Core Java is assumed.
http://startingwithseleniumwebdriver.blogspot.ro/2015/02/wait-in-page-factory.html
I had enough success just catchig socket.timeout
and socket.error
; although socket.error can be raised for lots of reasons. Be careful.
import socket
import logging
hostname='google.com'
port=443
try:
sock = socket.create_connection((hostname, port), timeout=3)
except socket.timeout as err:
logging.error(err)
except socket.error as err:
logging.error(err)
Something like this should work:
<%=Html.TextBox("test", new { style="width:50px" })%>
Or better:
<%=Html.TextBox("test")%>
<style type="text/css">
input[type="text"] { width:50px; }
</style>
Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
E.g.
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
Yeah you can use reflections to access private variables. Altough not a good idea.
Check this out:
http://en.wikibooks.org/wiki/Java_Programming/Reflection/Accessing_Private_Features_with_Reflection
numpy.ndarray
can contain any type of element, e.g. int
, float
, string
etc. Check the type an do a conversion if neccessary.
Try this-
CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
insert into student (name,user_name,branch) values (name ,user_name,branch);
END
You can actually disable all database constraints in a single SQL command and the re-enable them calling another single command. See:
I am currently working with SQL Server 2005 but I am almost sure that this approach worked with SQL 2000 as well
Put this code where you define recycler view in activity.
rv_list.addOnItemTouchListener(
new RecyclerItemClickListener(activity, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View v, int position) {
Toast.makeText(activity, "" + position, Toast.LENGTH_SHORT).show();
}
})
);
Then make separate class and put this code:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Here's a simple way using ngModel
(final Angular 2)
<!-- my.component.html -->
<div class="form-group">
<label for="options">Options:</label>
<div *ngFor="let option of options">
<label>
<input type="checkbox"
name="options"
value="{{option.value}}"
[(ngModel)]="option.checked"/>
{{option.name}}
</label>
</div>
</div>
// my.component.ts
@Component({ moduleId:module.id, templateUrl:'my.component.html'})
export class MyComponent {
options = [
{name:'OptionA', value:'1', checked:true},
{name:'OptionB', value:'2', checked:false},
{name:'OptionC', value:'3', checked:true}
]
get selectedOptions() { // right now: ['1','3']
return this.options
.filter(opt => opt.checked)
.map(opt => opt.value)
}
}
For a more cross-browser solution you could style all inputs the way you want the non-typed, text, and password then another style the overrides that style for radios, checkboxes, etc.
input { border:solid 1px red; }
input[type=radio],
input[type=checkbox],
input[type=submit],
input[type=reset],
input[type=file]
{ border:none; }
- Or -
could whatever part of your code that is generating the non-typed inputs give them a class like .no-type
or simply not output at all? Additionally this type of selection could be done with jQuery.
As the others already mentioned: the division operator is / rather than **. If you wanna print the ** character within a string you have to escape it:
print("foo \\")
# will print: foo \
I think to print the string you wanted I think you gonna need this code:
print("Length between sides: " + str((length*length)*2.6) + " \\ 1.5 = " + str(((length*length)*2.6)/1.5) + " Units")
And this one is a more readable version of the above (using the format method):
message = "Length between sides: {0} \\ 1.5 = {1} Units"
val1 = (length * length) * 2.6
val2 = ((length * length) * 2.6) / 1.5
print(message.format(val1, val2))
For a clear understanding, please take a look at my codepen implementations https://codepen.io/serdarsenay/pen/XELWqN
Biggest difference is the need to sort your sample before applying binary search, therefore for most "normal sized" (meaning to be argued) samples will be quicker to search with a linear search algorithm.
Here is the javascript code, for html and css and full running example please refer to above codepen link.
var unsortedhaystack = [];
var haystack = [];
function init() {
unsortedhaystack = document.getElementById("haystack").value.split(' ');
}
function sortHaystack() {
var t = timer('sort benchmark');
haystack = unsortedhaystack.sort();
t.stop();
}
var timer = function(name) {
var start = new Date();
return {
stop: function() {
var end = new Date();
var time = end.getTime() - start.getTime();
console.log('Timer:', name, 'finished in', time, 'ms');
}
}
};
function lineerSearch() {
init();
var t = timer('lineerSearch benchmark');
var input = this.event.target.value;
for(var i = 0;i<unsortedhaystack.length - 1;i++) {
if (unsortedhaystack[i] === input) {
document.getElementById('result').innerHTML = 'result is... "' + unsortedhaystack[i] + '", on index: ' + i + ' of the unsorted array. Found' + ' within ' + i + ' iterations';
console.log(document.getElementById('result').innerHTML);
t.stop();
return unsortedhaystack[i];
}
}
}
function binarySearch () {
init();
sortHaystack();
var t = timer('binarySearch benchmark');
var firstIndex = 0;
var lastIndex = haystack.length-1;
var input = this.event.target.value;
//currently point in the half of the array
var currentIndex = (haystack.length-1)/2 | 0;
var iterations = 0;
while (firstIndex <= lastIndex) {
currentIndex = (firstIndex + lastIndex)/2 | 0;
iterations++;
if (haystack[currentIndex] < input) {
firstIndex = currentIndex + 1;
//console.log(currentIndex + " added, fI:"+firstIndex+", lI: "+lastIndex);
} else if (haystack[currentIndex] > input) {
lastIndex = currentIndex - 1;
//console.log(currentIndex + " substracted, fI:"+firstIndex+", lI: "+lastIndex);
} else {
document.getElementById('result').innerHTML = 'result is... "' + haystack[currentIndex] + '", on index: ' + currentIndex + ' of the sorted array. Found' + ' within ' + iterations + ' iterations';
console.log(document.getElementById('result').innerHTML);
t.stop();
return true;
}
}
}
-- check if server exists in table sys.server
select * from sys.servers
-- set database security
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
-- add the external dbserver
EXEC sp_addlinkedserver @server='#servername#'
-- add login on external server
EXEC sp_addlinkedsrvlogin '#Servername#', 'false', NULL, '#username#', '#password@123"'
-- control query on remote table
select top (1000) * from [#server#].[#database#].[#schema#].[#table#]
You can use functional operation for a more neat code
Set<String> set = new HashSet<String>();
set.forEach((s) -> {
System.out.println(s);
});
<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>
Just an example
This Code is to parse the XML wraps the JSON Response and display in the front end using ajax.
Required JavaScript code.
_x000D_
<script type="text/javascript">_x000D_
$.ajax({_x000D_
method:"GET",_x000D_
url: "javatpoint.html", _x000D_
_x000D_
success : function(data) { _x000D_
_x000D_
var json=JSON.parse(data); _x000D_
var tbody=$('tbody');_x000D_
for(var i in json){_x000D_
tbody.append('<tr><td>'+json[i].id+'</td>'+_x000D_
'<td>'+json[i].firstName+'</td>'+_x000D_
'<td>'+json[i].lastName+'</td>'+_x000D_
'<td>'+json[i].Download_DateTime+'</td>'+_x000D_
'<td>'+json[i].photo+'</td></tr>')_x000D_
} _x000D_
},_x000D_
error : function () {_x000D_
alert('errorrrrr');_x000D_
}_x000D_
});_x000D_
_x000D_
</script>
_x000D_
[{ "id": "1", "firstName": "Tom", "lastName": "Cruise", "photo": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg" }, { "id": "2", "firstName": "Maria", "lastName": "Sharapova", "photo": "https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg" }, { "id": "3", "firstName": "James", "lastName": "Bond", "photo": "https://pbs.twimg.com/profile_images/664886718559076352/M00cOLrh.jpg" }] `
URL url=new URL("www.example.com");
URLConnection si=url.openConnection();
InputStream is=si.getInputStream();
String str="";
int i;
while((i=is.read())!=-1){
str +=str.valueOf((char)i);
}
str =str.replace("</string>", "");
str=str.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
str = str.replace("<string xmlns=\"http://tempuri.org/\">", "");
PrintWriter out=resp.getWriter();
out.println(str);
`
Using mongoose.js you can count documents,
const count = await Schema.countDocuments();
const count = await Schema.countDocuments({ key: value });
The iframe element.
<iframe src="name.html"></iframe>
But content that you way to have appear on multiple pages is better handled using templates.
In a single line you could do:
private static File[] bar(){
return new File[]{};
}
Receive POST and GET request in nodejs :
1).Server
var http = require('http');
var server = http.createServer ( function(request,response){
response.writeHead(200,{"Content-Type":"text\plain"});
if(request.method == "GET")
{
response.end("received GET request.")
}
else if(request.method == "POST")
{
response.end("received POST request.");
}
else
{
response.end("Undefined request .");
}
});
server.listen(8000);
console.log("Server running on port 8000");
2). Client :
var http = require('http');
var option = {
hostname : "localhost" ,
port : 8000 ,
method : "POST",
path : "/"
}
var request = http.request(option , function(resp){
resp.on("data",function(chunck){
console.log(chunck.toString());
})
})
request.end();
I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.
import org.openqa.selenium.Keys;
String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);
element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field
I hope it helps..
These modules can't be installed using npm.
Actually you can install a module by specifying instead of a name a local path. As long as the repository has a valid package.json
file it should work.
Type npm -l
and a pretty help will appear like so :
CLI:
...
install npm install <tarball file>
npm install <tarball url>
npm install <folder>
npm install <pkg>
npm install <pkg>@<tag>
npm install <pkg>@<version>
npm install <pkg>@<version range>
Can specify one or more: npm install ./foo.tgz bar@stable /some/folder
If no argument is supplied and ./npm-shrinkwrap.json is
present, installs dependencies specified in the shrinkwrap.
Otherwise, installs dependencies from ./package.json.
What caught my eyes was: npm install <folder>
In my case I had trouble with mrt
module so I did this (in a temporary directory)
Clone the repo
git clone https://github.com/oortcloud/meteorite.git
And I install it globally with:
npm install -g ./meteorite
One can also install in the same manner the repo to a local npm project with:
npm install ../meteorite
And also one can create a link to the repo, in case a patch in development is needed:
npm link ../meteorite
Nowadays npm supports also github and git repositories (see https://docs.npmjs.com/cli/v6/commands/npm-install), as a shorthand you can run :
npm i github.com:some-user/some-repo
I use org.apache.commons.codec.binary.Base64 to convert a UUID into a url-safe unique string that is 22 characters in length and has the same uniqueness as UUID.
I posted my code on Storing UUID as base64 String
This is the one liner code:
$sub_directories = array_map('basename', glob($directory_path . '/*', GLOB_ONLYDIR));
This code gives you an error because your Add
function needs to be static
:
static public int Add(int x, int y)
In C# there is a distinction between functions that operate on instances (non-static) and functions that do not operate on instances (static). Instance functions can call other instance functions and static functions because they have an implicit reference to the instance. In contrast, static functions can call only static functions, or else they must explicitly provide an instance on which to call a non-static function.
Since public static void Main(string[] args)
is static, all functions that it calls need to be static as well.
Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)
A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.
Here's some code to illustrate. A point is time is captured in three different ways.
var moment = require( 'moment' );
var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );
//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );
//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate = ' + utcDate );
//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );
Which outputs this:
localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570
In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).
As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!
Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.
Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate )
, and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log
calls in the example.
| is bitwise or, || is logical or.
You don't need to convert your dates to timestamp before the sorting, but it's a good idea though because it will take more time to sort without it.
$data = array(
array(
"title" => "Another title",
"date" => "Fri, 17 Jun 2011 08:55:57 +0200"
),
array(
"title" => "My title",
"date" => "Mon, 16 Jun 2010 06:55:57 +0200"
)
);
function sortFunction( $a, $b ) {
return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);
I think this is the easiest way to loop in react js
<ul>
{yourarray.map((item)=><li>{item}</li>)}
</ul>
Got this error while trying to access model objects in apps.py
:
class QuizConfig(AppConfig):
name = 'quiz'
def ready(self):
print('===============> Django just started....')
questions_by_category = Question.objects.filter(category=2) # <=== Guilty line of code.
Trying to access Question
before the app has loaded the model class caused the error for me.
Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:
var array = [];
calendars.forEach(function(item) {
array.push(item.id);
});
console.log(array);
You can also use the map()
method to generate an Array filled with the results of calling the specified function on each element. Something like:
var array = calendars.map(function(item) {
return item.id;
});
console.log(array);
And, since ECMAScript 2015 has been released, you may start seeing examples using let
or const
instead of var
and the =>
syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):
let array = calendars.map(item => item.id);
console.log(array);
Your question contains the string literal "\b[A-Z]{2,}\b"
,
but that \b
will mean backspace, because there is no r-modifier.
Try: r"\b[A-Z]{2,}\b"
.
I'm leaving this answer for someone who gets in this scenario as I did.
I stumbled here and there before noticing that I mistakenly dragged and dropped the Support Library JAR file into my src folder and it was lying there. Since I had no idea how it happened or when I dropped it there, I could never imagine something was wrong there.
I was getting the same error, I found the problem after sometime and removed it. Project is now working fine.
Adding both android:layout_centerInParent
and android:layout_centerVertical
work for me to center ImageView
both vertical and horizontal:
<ImageView
..
android:layout_centerInParent="true"
android:layout_centerVertical="true"
/>
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
The accepted answer didn't work for me.
If you have a multi configuration, adding the following to your WebSecurityConfig class worked for me (ensure that your Order(1) is lower than all of your other Order annotations in the class):
/* UNCOMMENT TO DISABLE SPRING SECURITY */
/*@Configuration
@Order(1)
public static class DisableSecurityConfigurationAdapater extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
}
}*/
You can achieve this by adding this simple php code block
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
the_content();
endwhile; else: ?>
<p>!Sorry no posts here</p>
<?php endif; ?>
I was having trouble with a local DB.
I was able to solve this problem by stopping SQL server, and then starting SQL server, and then using the SSMS UI to change the DB properties to Multi_User.
The DB went into "Single User" Mode when i was attempting to restore a backup. I hadn't created a backup of the target database before attempting to restore (SQL 2017). this will get you every time.
Stop SQL Server, Start SQL Server, then run the above Scripts or use the UI.
Use an iterator.
List comprehension:
>>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
>>> [c+next(si, '') for c in si]
['abcde', 'fghijklmn', 'opqr']
Generator expression:
>>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
>>> pair_iter = (c+next(si, '') for c in si)
>>> pair_iter # can be used in a for loop
<generator object at 0x4ccaa8>
>>> list(pair_iter)
['abcde', 'fghijklmn', 'opqr']
Using map, str.__add__, iter
>>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
>>> map(str.__add__, si, si)
['abcde', 'fghijklmn', 'opqr']
next(iterator[, default]) is available starting in Python 2.6
Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.
Try this:
NameValuePair[] params = new BasicNameValuePair[] {
new BasicNameValuePair("param1", param1),
new BasicNameValuePair("param2", param2),
};
class A:
pass
a = A()
str(a.__class__)
The sample code above (when input in the interactive interpreter) will produce '__main__.A'
as opposed to 'A'
which is produced if the __name__
attribute is invoked. By simply passing the result of A.__class__
to the str
constructor the parsing is handled for you. However, you could also use the following code if you want something more explicit.
"{0}.{1}".format(a.__class__.__module__,a.__class__.__name__)
This behavior can be preferable if you have classes with the same name defined in separate modules.
The sample code provided above was tested in Python 2.7.5.
Here is some workaround that actually worked for me, it is the same solution as in the most popular answer - just add hw.keyboard=yes to config.ini but since this didn't work for me I additionally
I had a similar exception:
java.lang.SecurityException: class "org.hamcrest.Matchers"'s signer information does not match signer information of other classes in the same package
The root problem was that I included the Hamcrest library twice. Once using Maven pom file. And I also added the JUnit 4 library (which also contains a Hamcrest library) to the project's build path. I simply had to remove JUnit from the build path and everything was fine.
Alternate solution. Include your external CSS in your HTML file by
<link rel="stylesheet" href="css/applyCSS.css"/>
inside the applyCSS.css:
#applyCSS {
/** Your Style**/
}
Paste this code in any of your source files and re-build. Worked for me !
#include stdio.h
FILE _iob[3];
FILE* __cdecl __iob_func(void) {
_iob[0] = *stdin;
_iob[0] = *stdout;
_iob[0] = *stderr;
return _iob;
}
On BSD systems and Android you can also use fgetln
:
#include <stdio.h>
char *
fgetln(FILE *stream, size_t *len);
Like so:
size_t line_len;
const char *line = fgetln(stdin, &line_len);
The line
is not null terminated and contains \n
(or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream. You are allowed to modify the returned line
buffer.
I recently got the same problem and after looking for duplicates I was able to fix it just by setting (missing) primary key on the table. Hope this could help
use this
select * from xxx where dates between '10/oct/2012' and '10/dec/2012'
you are entering string, So give the name of month as according to format...
instanceof
is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
val() returns the value of the <select>
element, i.e. the value
attribute of the selected <option>
element.
Since you actually want the inner text of the selected <option>
element, you should match that element and use text() instead:
var nationality = $("#dancerCountry option:selected").text();
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
var tmpList = {};
while (Object.keys(list).length) {
var key = Object.keys(list).reduce((a, b) => list[a] > list[b] ? a : b);
tmpList[key] = list[key];
delete list[key];
}
list = tmpList;
console.log(list); // { foo: 116, you: 100, me: 75, bar: 15 }
If all you need is a tool for reading, then this thing will open the file instantly http://www.readfileonline.com/
This will print 76.66
:
print("Number: ", f"{76.663254: .2f}")
Here's my quick and dirty version. I know all of my dates were using the US Eastern time zone. You can change the offset or otherwise make it smarter as you need to. I was doing a one-time migration so this was Good Enough.
CREATE FUNCTION [dbo].[ConvertToUtc]
(
@date datetime
)
RETURNS DATETIME
AS
BEGIN
-- Declare the return variable here
DECLARE @utcDate datetime;
DECLARE @offset int;
SET @offset = (SELECT CASE WHEN
@date BETWEEN '1987-04-05 02:00 AM' AND '1987-10-25 02:00 AM'
OR @date BETWEEN '1988-04-03 02:00 AM' AND '1988-10-30 02:00 AM'
OR @date BETWEEN '1989-04-02 02:00 AM' AND '1989-10-29 02:00 AM'
OR @date BETWEEN '1990-04-01 02:00 AM' AND '1990-10-28 02:00 AM'
OR @date BETWEEN '1991-04-07 02:00 AM' AND '1991-10-27 02:00 AM'
OR @date BETWEEN '1992-04-05 02:00 AM' AND '1992-10-25 02:00 AM'
OR @date BETWEEN '1993-04-04 02:00 AM' AND '1993-10-31 02:00 AM'
OR @date BETWEEN '1994-04-03 02:00 AM' AND '1994-10-30 02:00 AM'
OR @date BETWEEN '1995-04-02 02:00 AM' AND '1995-10-29 02:00 AM'
OR @date BETWEEN '1996-04-07 02:00 AM' AND '1996-10-27 02:00 AM'
OR @date BETWEEN '1997-04-06 02:00 AM' AND '1997-10-26 02:00 AM'
OR @date BETWEEN '1998-04-05 02:00 AM' AND '1998-10-25 02:00 AM'
OR @date BETWEEN '1999-04-04 02:00 AM' AND '1999-10-31 02:00 AM'
OR @date BETWEEN '2000-04-02 02:00 AM' AND '2000-10-29 02:00 AM'
OR @date BETWEEN '2001-04-01 02:00 AM' AND '2001-10-28 02:00 AM'
OR @date BETWEEN '2002-04-07 02:00 AM' AND '2002-10-27 02:00 AM'
OR @date BETWEEN '2003-04-06 02:00 AM' AND '2003-10-26 02:00 AM'
OR @date BETWEEN '2004-04-04 02:00 AM' AND '2004-10-31 02:00 AM'
OR @date BETWEEN '2005-04-03 02:00 AM' AND '2005-10-30 02:00 AM'
OR @date BETWEEN '2006-04-02 02:00 AM' AND '2006-10-29 02:00 AM'
OR @date BETWEEN '2007-03-11 02:00 AM' AND '2007-11-04 02:00 AM'
OR @date BETWEEN '2008-03-09 02:00 AM' AND '2008-11-02 02:00 AM'
OR @date BETWEEN '2009-03-08 02:00 AM' AND '2009-11-01 02:00 AM'
OR @date BETWEEN '2010-03-14 02:00 AM' AND '2010-11-07 02:00 AM'
OR @date BETWEEN '2011-03-13 02:00 AM' AND '2011-11-06 02:00 AM'
OR @date BETWEEN '2012-03-11 02:00 AM' AND '2012-11-04 02:00 AM'
OR @date BETWEEN '2013-03-10 02:00 AM' AND '2013-11-03 02:00 AM'
OR @date BETWEEN '2014-03-09 02:00 AM' AND '2014-11-02 02:00 AM'
OR @date BETWEEN '2015-03-08 02:00 AM' AND '2015-11-01 02:00 AM'
OR @date BETWEEN '2016-03-13 02:00 AM' AND '2016-11-06 02:00 AM'
OR @date BETWEEN '2017-03-12 02:00 AM' AND '2017-11-05 02:00 AM'
OR @date BETWEEN '2018-03-11 02:00 AM' AND '2018-11-04 02:00 AM'
OR @date BETWEEN '2019-03-10 02:00 AM' AND '2019-11-03 02:00 AM'
OR @date BETWEEN '2020-03-08 02:00 AM' AND '2020-11-01 02:00 AM'
OR @date BETWEEN '2021-03-14 02:00 AM' AND '2021-11-07 02:00 AM'
THEN 4
ELSE 5 END);
SELECT @utcDate = DATEADD(hh, @offset, @date)
RETURN @utcDate;
END
In C, except for a few special cases, an array reference always "decays" to a pointer to the first element of the array. Therefore, it isn't possible to pass an array "by value". An array in a function call will be passed to the function as a pointer, which is analogous to passing the array by reference.
EDIT: There are three such special cases where an array does not decay to a pointer to it's first element:
sizeof a
is not the same as sizeof (&a[0])
.&a
is not the same as &(&a[0])
(and not quite the same as &a[0]
).char b[] = "foo"
is not the same as char b[] = &("foo")
.The accepted answer is very old.
I found a better modern answer here:
https://kevinmccarthy.org/2016/07/25/streaming-subprocess-stdin-and-stdout-with-asyncio-in-python/
and made some changes:
import sys
import asyncio
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
async def _read_stream(stream, cb):
while True:
line = await stream.readline()
if line:
cb(line)
else:
break
async def _stream_subprocess(cmd, stdout_cb, stderr_cb):
try:
process = await asyncio.create_subprocess_exec(
*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
await asyncio.wait(
[
_read_stream(process.stdout, stdout_cb),
_read_stream(process.stderr, stderr_cb),
]
)
rc = await process.wait()
return process.pid, rc
except OSError as e:
# the program will hang if we let any exception propagate
return e
def execute(*aws):
""" run the given coroutines in an asyncio loop
returns a list containing the values returned from each coroutine.
"""
loop = asyncio.get_event_loop()
rc = loop.run_until_complete(asyncio.gather(*aws))
loop.close()
return rc
def printer(label):
def pr(*args, **kw):
print(label, *args, **kw)
return pr
def name_it(start=0, template="s{}"):
"""a simple generator for task names
"""
while True:
yield template.format(start)
start += 1
def runners(cmds):
"""
cmds is a list of commands to excecute as subprocesses
each item is a list appropriate for use by subprocess.call
"""
next_name = name_it().__next__
for cmd in cmds:
name = next_name()
out = printer(f"{name}.stdout")
err = printer(f"{name}.stderr")
yield _stream_subprocess(cmd, out, err)
if __name__ == "__main__":
cmds = (
[
"sh",
"-c",
"""echo "$SHELL"-stdout && sleep 1 && echo stderr 1>&2 && sleep 1 && echo done""",
],
[
"bash",
"-c",
"echo 'hello, Dave.' && sleep 1 && echo dave_err 1>&2 && sleep 1 && echo done",
],
[sys.executable, "-c", 'print("hello from python");import sys;sys.exit(2)'],
)
print(execute(*runners(cmds)))
It is unlikely that the example commands will work perfectly on your system, and it doesn't handle weird errors, but this code does demonstrate one way to run multiple subprocesses using asyncio and stream the output.
There are a number of diff plugins available via Package Control. I've used Sublimerge Pro, which worked well enough, but it's a commercial product (with an unlimited trial period) and closed-source, so you can't tweak it if you want to change something, or just look at its internals. FileDiffs is quite popular, judging by the number of installs, so you might want to try that one out.
Give the name to both of the buttons and Get the check the value from form.
<div>
<input name="submitButton" type="submit" value="Register" />
</div>
<div>
<input name="cancelButton" type="submit" value="Cancel" />
</div>
On controller side :
public ActionResult Save(FormCollection form)
{
if (this.httpContext.Request.Form["cancelButton"] !=null)
{
// return to the action;
}
else if(this.httpContext.Request.Form["submitButton"] !=null)
{
// save the oprtation and retrun to the action;
}
}
None of the above responses are working for error that has no body but still has some describing text. For me, it was SSL certificate problem: unable to get local issuer certificate
error. So I looked right into the code, because doc does't really say much, and did this (in Guzzle 7.1):
try {
// call here
} catch (\GuzzleHttp\Exception\RequestException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
// message is in $response->getReasonPhrase()
} else {
$response = $e->getHandlerContext();
if (isset($response['error'])) {
// message is in $response['error']
} else {
// Unknown error occured!
}
}
}
I know this is older, but wanted to contribute another possibly solution.
If you want to keep the project location, as I did, I found that copying the .project file from another project into the project's directory, then editing the .project file to name it properly, then choosing the Import Existing Projects into Workspace option worked for me.
In Windows, I used a file monitor to see what Eclipse was doing, and it was simply erroring out for some unknown reason when trying to create the .project file. So, I did that manually and it worked for me.
If you are using Github / Github Enterprise, you can use the Web UI by hitting the url /compare
of your repository path, for instance, https://github.com/http4s/http4s/compare.
You can select the branch / commit / tag that you want to compare:
And the diff will be presented in the github interface at the url /compare/{x1}...{x2}
where are x2
and x1
are the branch / commit / tag you want to compare, for instance:
https://github.com/http4s/http4s/compare/main...dotty
You can see more in the Github Doc.
There is another tricky way. The main idea is to double the section number, and first one only shows the headerView while the second one shows the real cells.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionCount * 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section%2 == 0) {
return 0;
}
return _rowCount;
}
What need to do then is to implement the headerInSection delegates:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (section%2 == 0) {
//return headerview;
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (section%2 == 0) {
//return headerheight;
}
return 0;
}
This approach also has little impact on your datasources:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int real_section = (int)indexPath.section / 2;
//your code
}
Comparing with other approaches, this way is safe while not changing the frame or contentInsets of the tableview. Hope this may help.
using jQuery:
$( ".myClass" ).load(function() {
var myId = $(this).data("id");
$('.myClass').attr('id', myId);
});
LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall
# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)
test: $(SRC)
gcc -o $@ $^ $(CFLAGS) $(LIBS)
The add_marker still has a closure issue, cause it uses the marker variable outside the google.maps.event.addListener scope.
A better implementation would be:
function add_marker(racer_id, point, note) {
var marker = new google.maps.Marker({map: map, position: point, clickable: true});
marker.note = note;
google.maps.event.addListener(marker, 'click', function() {
info_window.content = this.note;
info_window.open(this.getMap(), this);
});
return marker;
}
I also used the map from the marker, this way you don't need to pass the google map object, you probably want to use the map where the marker belongs to anyway.
Double the backslashes in the path, like this:
driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
You need to go into your SDK installation directory, and make sure that the /build-tools sub-directory matches the buildToolsVersion
in your app's build.gradle file:
I arrived to this question looking for the same but for Chromium (actually I'm using https://ungoogled-software.github.io). So in case anyone else is looking for the same:
Handling of extension MIME type requests
Always prompt for install
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
Per the docs, replace
returns the new string - it does not modify the string you pass it.
var tt="88,9827";
tt = tt.replace(/,/g, '.');
^^^^
alert(tt);
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));
16 is the zoom level
pushing a value (not necessarily stored in a register) means writing it to the stack.
popping means restoring whatever is on top of the stack into a register. Those are basic instructions:
push 0xdeadbeef ; push a value to the stack
pop eax ; eax is now 0xdeadbeef
; swap contents of registers
push eax
mov eax, ebx
pop ebx
grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"
Another alternative approach is:
How do I create a Java string from the contents of a file?
Other option is to use utilities provided open source libraries
http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/IOUtils.html
Why java doesn't provide such a common util API ?
a) to keep the APIs generic so that encoding, buffering etc is handled by the programmer.
b) make programmers do some work and write/share opensource util libraries :D ;-)
The following are not needed as they they not fix the error:
ps -ef|grep oracle
SQL> startup mount
SQL> create pfile from spfile;
Restarting the database will flush your pool and that solves a effect not the problem.
Fixate your large_pool so it can not go lower then a certain point or add memory and set a higher max memory.
We ran into this problem when working with node on Windows.
Rather than requiring anyone who attempts to run the app to set these variables, we provided a fallback within the application.
var environment = process.env.NODE_ENV || 'development';
In a production environment, we would define it per the usual methods (SET/export).
There is no rule. I find CTEs more readable, and use them unless they exhibit some performance problem, in which case I investigate the actual problem rather than guess that the CTE is the problem and try to re-write it using a different approach. There is usually more to the issue than the way I chose to declaratively state my intentions with the query.
There are certainly cases when you can unravel CTEs or remove subqueries and replace them with a #temp table and reduce duration. This can be due to various things, such as stale stats, the inability to even get accurate stats (e.g. joining to a table-valued function), parallelism, or even the inability to generate an optimal plan because of the complexity of the query (in which case breaking it up may give the optimizer a fighting chance). But there are also cases where the I/O involved with creating a #temp table can outweigh the other performance aspects that may make a particular plan shape using a CTE less attractive.
Quite honestly, there are way too many variables to provide a "correct" answer to your question. There is no predictable way to know when a query may tip in favor of one approach or another - just know that, in theory, the same semantics for a CTE or a single subquery should execute the exact same. I think your question would be more valuable if you present some cases where this is not true - it may be that you have discovered a limitation in the optimizer (or discovered a known one), or it may be that your queries are not semantically equivalent or that one contains an element that thwarts optimization.
So I would suggest writing the query in a way that seems most natural to you, and only deviate when you discover an actual performance problem the optimizer is having. Personally I rank them CTE, then subquery, with #temp table being a last resort.
Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal
would work as expected.
package main
import (
"encoding/json"
"fmt"
"strconv"
)
// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler
type Num int
func (n *Num) UnmarshalText(text []byte) error {
i, err := strconv.Atoi(string(text))
if err != nil {
return err
}
*n = Num(i)
return nil
}
func (n Num) MarshalText() (text []byte, err error) {
return []byte(strconv.Itoa(int(n))), nil
}
type Foo struct {
Number Num `json:"number"`
Title string `json:"title"`
}
func main() {
datas := make(map[Num]Foo)
for i := 0; i < 10; i++ {
datas[Num(i)] = Foo{Number: 1, Title: "test"}
}
jsonString, err := json.Marshal(datas)
if err != nil {
panic(err)
}
fmt.Println(datas)
fmt.Println(jsonString)
m := make(map[Num]Foo)
err = json.Unmarshal(jsonString, &m)
if err != nil {
panic(err)
}
fmt.Println(m)
}
Output:
map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]
To remove the default MouseOver
behaviour on the Button
you will need to modify the ControlTemplate
. Changing your Style
definition to the following should do the trick:
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Green"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
EDIT: It's a few years late, but you are actually able to set the border brush inside of the border that is in there. Idk if that was pointed out but it doesn't seem like it was...
Just use $(selector).is(':checked')
It returns a boolean value.
I was trying to copy the size data measured from Chrome Network and stumbled on this post. I just found an easier way to "export" the data out to excel which is to copy the table and paste to excel.
The trick is click Control + A (select all) and once the entire table will be highlighted, paste it to Microsoft Excel. The only issue is if there are too many fields, not all rows are copied and you might have to copy and paste several times.
UPDATED: I found that copying the data only works when I turn off the filter options (the funnel-looking button above the table). – bendur
String
has a charAt
method that returns the character at the specified position. Like arrays and List
s, String
is 0-indexed, i.e. the first character is at index 0
and the last character is at index length() - 1
.
So, assuming getSymbol()
returns a String
, to print the first character, you could do:
System.out.println(ld.getSymbol().charAt(0)); // char at index 0
A very simple answer is.
Step 1:
Firstly add your untracked files to which you want to delete:
using git add .
or git add <filename>
.
Step 2:
Then delete them easily using command git rm -f <filename>
here rm=remove and -f=forcely.
I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'), `
<button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
$('#btnPurchaseClose').trigger('click');// for close popup
$('#btnOpenPurchase').trigger('click');`// for open popup
Try Winhttrack
...offline browser utility.
It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.
WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...
Add z-indez in class ui-datepicker
<style>
.ui-datepicker{ z-index:1151 !important; }
</style>
I don't see any problem, unless you are not managing them using a connection pool.
If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.
use from configurations must be very very easy like this :
var config = new MiniConfig("setting.conf");
config.AddOrUpdate("port", "1580");
if (config.TryGet("port", out int port)) // if config exist
{
Console.Write(port);
}
for more details see MiniConfig
Use Capture list
Defining a Capture List
Each item in a capture list is a pairing of the weak or unowned keyword with a reference to a class instance (such as self) or a variable initialized with some value (such as delegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.
Place the capture list before a closure’s parameter list and return type if they are provided:
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}
If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by the in keyword:
lazy var someClosure: Void -> String = {
[unowned self, weak delegate = self.delegate!] in
// closure body goes here
}
In my case the IP address of our git host had changed.
Simply flushing the DNS cache fixed the problem.
You don't have to use jQuery or Javascript.
Use the name
tag of the select and let the form do it's job.
<select name="agent_id" id="agent_id">
echo $line | tr " " "\n"
gives the output similar to those of most of the answers above; without using loops.
In your case, you also mention ll=<...output...>
,
so, (given that I don't know much python and assuming you need to assign output to a variable),
ll=`echo $line | tr " " "\n"`
should suffice (remember to echo "$ll"
instead of echo $ll
)
We have new technology for this problem: the java.time framework built into Java 8 and later.
Your input string is in standard ISO 8601 format. That standard is used by default in the java.time classes for parsing/generating textual representations of date-time values.
OffsetDateTime odt = OffsetDateTime.parse( "2012-10-01T09:45:00.000+02:00" );
Your Question suggests you want to truncate to a whole second.
OffsetDateTime odtTruncatedToWholeSecond = odt.truncatedTo( ChronoUnit.SECONDS );
It seems you want to omit the offset and time zone info. The pre-defined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME
does that.
And apparently you want to use a space in the middle rather than the standard T
. You could define your own formatter for this, but I would just do a string manipulation to replace the T
with a SPACE.
String output = odtTruncatedToWholeSecond.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " );
As the comments on the Question suggest, strictly speaking you can accomplish your goal by working only with strings and not converting to any date-time objects. But I provide this Answer here assuming you may have other business logic to work with these date-time values.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles.
Here's a quick example reusing the assumed values and LOGFILE from the question:
import logging
from logging.handlers import RotatingFileHandler
from logging import handlers
import sys
log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
log.addHandler(ch)
fh = handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)
fh.setFormatter(format)
log.addHandler(fh)
Simply put, clearfix is a hack.
It is one of those ugly things that we all just have to live with as it is really the only reasonable way of ensuring floated child elements don't overflow their parents. There are other layout schemes out there but floating is too commonplace in web design/development today to ignore the value of the clearfix hack.
I personally lean towards the Micro Clearfix solution (Nicolas Gallagher)
.container:before,
.container:after {
content:"";
display:table;
}
.container:after {
clear:both;
}
.container {
zoom:1; /* For IE 6/7 (trigger hasLayout) */
}
For Notepad++ 5.9
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageButton android:id="@+id/btnFindMe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity = "center"
android:background="@drawable/findme">
</ImageButton>
</LinearLayout>
The above code will work.
headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('www.example.com', None, headers)
html = urllib2.urlopen(req).read()
Or, a bit shorter:
req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' })
html = urllib2.urlopen(req).read()
Following on from Tuong Lu Kim's answer:
Assuming:
ga('create', 'UA-XXXXX-Y', 'auto');
...if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'....
Excerpt from:
Automatic cookie domain configuration sets the _ga cookie on the highest level domain it can. For example, if your website address is blog.example.co.uk, analytics.js will set the cookie domain to .example.co.uk. In addition, if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'.
The recommended JavaScript tracking snippet sets the string 'auto' for the cookieDomain field:
This can also be achieved using the Scalar-Valued Function
in MSSQL 2008
Declare your function as following,
CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500)
AS
BEGIN
DECLARE @SchoolName varchar(500)
SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', '
FROM maskdetails MD WITH (NOLOCK)
AND MD.MaskId=@MaskId
RETURN @SchoolName
END
And then your final query will be like
SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid
ORDER BY m.maskname ;
Note: You may have to change the function, as I don't know the complete table structure.
Here's a simple function using a regexp that imitates the a
tag behavior.
Pros
Cons
-
function getLocation(href) {
var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
href: href,
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
}
-
getLocation("http://example.com/");
/*
{
"protocol": "http:",
"host": "example.com",
"hostname": "example.com",
"port": undefined,
"pathname": "/"
"search": "",
"hash": "",
}
*/
getLocation("http://example.com:3000/pathname/?search=test#hash");
/*
{
"protocol": "http:",
"host": "example.com:3000",
"hostname": "example.com",
"port": "3000",
"pathname": "/pathname/",
"search": "?search=test",
"hash": "#hash"
}
*/
EDIT:
Here's a breakdown of the regular expression
var reURLInformation = new RegExp([
'^(https?:)//', // protocol
'(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
'(/{0,1}[^?#]*)', // pathname
'(\\?[^#]*|)', // search
'(#.*|)$' // hash
].join(''));
var match = href.match(reURLInformation);
You don't need the 'values' clause when using a 'select' as your source.
insert into table1 (col1, col2)
select t1.col1, t2.col2 from oldtable1 t1, oldtable2 t2;
One thing you should know is $ prefix refers to an Angular Method, $$ prefixes refers to angular methods that you should avoid using.
below is an example template and its controllers, we'll explore how $broadcast/$on can help us achieve what we want.
<div ng-controller="FirstCtrl">
<input ng-model="name"/>
<button ng-click="register()">Register </button>
</div>
<div ng-controller="SecondCtrl">
Registered Name: <input ng-model="name"/>
</div>
The controllers are
app.controller('FirstCtrl', function($scope){
$scope.register = function(){
}
});
app.controller('SecondCtrl', function($scope){
});
My question to you is how do you pass the name to the second controller when a user clicks register? You may come up with multiple solutions but the one we're going to use is using $broadcast and $on.
$broadcast vs $emit
Which should we use? $broadcast will channel down to all the children dom elements and $emit will channel the opposite direction to all the ancestor dom elements.
The best way to avoid deciding between $emit or $broadcast is to channel from the $rootScope and use $broadcast to all its children. Which makes our case much easier since our dom elements are siblings.
Adding $rootScope and lets $broadcast
app.controller('FirstCtrl', function($rootScope, $scope){
$scope.register = function(){
$rootScope.$broadcast('BOOM!', $scope.name)
}
});
Note we added $rootScope and now we're using $broadcast(broadcastName, arguments). For broadcastName, we want to give it a unique name so we can catch that name in our secondCtrl. I've chosen BOOM! just for fun. The second arguments 'arguments' allows us to pass values to the listeners.
Receiving our broadcast
In our second controller, we need to set up code to listen to our broadcast
app.controller('SecondCtrl', function($scope){
$scope.$on('BOOM!', function(events, args){
console.log(args);
$scope.name = args; //now we've registered!
})
});
It's really that simple. Live Example
Other ways to achieve similar results
Try to avoid using this suite of methods as it is neither efficient nor easy to maintain but it's a simple way to fix issues you might have.
You can usually do the same thing by using a service or by simplifying your controllers. We won't discuss this in detail but I thought I'd just mention it for completeness.
Lastly, keep in mind a really useful broadcast to listen to is '$destroy' again you can see the $ means it's a method or object created by the vendor codes. Anyways $destroy is broadcasted when a controller gets destroyed, you may want to listen to this to know when your controller is removed.
Running example:
//If you want add the element before the actual content, use before()_x000D_
$(function () {_x000D_
$('#AddBefore').click(function () {_x000D_
$('#Content').before('<p>Text before the button</p>');_x000D_
});_x000D_
});_x000D_
_x000D_
//If you want add the element after the actual content, use after()_x000D_
$(function () {_x000D_
$('#AddAfter').click(function () {_x000D_
$('#Content').after('<p>Text after the button</p>');_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
_x000D_
<div id="Content">_x000D_
<button id="AddBefore">Add before</button>_x000D_
<button id="AddAfter">Add after</button>_x000D_
</div>
_x000D_
NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.
Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.
Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.
Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.
Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.
PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.
Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.
I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.
Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC
Yes, It is possible,
Just add a class like anyclass
and give some CSS style. Live
.anyClass {
height:150px;
overflow-y: scroll;
}
.anyClass {_x000D_
height:150px;_x000D_
overflow-y: scroll;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class=" col-md-2">_x000D_
<ul class="nav nav-pills nav-stacked anyClass">_x000D_
<li class="nav-item">_x000D_
<a class="nav-link active" href="#">Active</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li><li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li><li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li><li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li><li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link disabled" href="#">Disabled</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
The GUI for managing SSL certs on Chromium on Linux did NOT work properly for me. However, their docs gave the right answer. The trick was to run the command below that imports the self-signed SSL cert. Just update the name of the <certificate-nickname>
and certificate-filename.cer
, then restart chromium/chrome.
From the Docs:
On Linux, Chromium uses the NSS Shared DB. If the built-in manager does not work for you then you can configure certificates with the NSS command line tools.
Get the tools
Debian/Ubuntu:
sudo apt-get install libnss3-tools
Fedora:
su -c "yum install nss-tools"
Gentoo:
su -c "echo 'dev-libs/nss utils' >> /etc/portage/package.use && emerge dev-libs/nss"
(You need to launch all commands below with thenss
prefix, e.g.,nsscertutil
.) Opensuse:sudo zypper install mozilla-nss-tools
To trust a self-signed server certificate, we should use
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n <certificate-nickname> -i certificate-filename.cer
List all certificates
certutil -d sql:$HOME/.pki/nssdb -L
The TRUSTARGS are three strings of zero or more alphabetic characters, separated by commas. They define how the certificate should be trusted for SSL, email, and object signing, and are explained in the certutil docs or Meena's blog post on trust flags.
Add a personal certificate and private key for SSL client authentication Use the command:
pk12util -d sql:$HOME/.pki/nssdb -i PKCS12_file.p12
to import a personal certificate and private key stored in a PKCS #12 file. The TRUSTARGS of the personal certificate will be set to “u,u,u”.
Delete a certificate
certutil -d sql:$HOME/.pki/nssdb -D -n <certificate nickname>
Excerpt From: https://chromium.googlesource.com/chromium/src/+/HEAD/docs/linux_cert_management.md
When there's no project, Code::Blocks only compiles and links the current file. That file, from your picture, is secrypt.cpp
, which does not have a main function. In order to compile and link both source files, you'll need to do it manually or add them to the same project.
Contrary to what others are saying, using a Windows subsystem with main
will still work, but there will be no console window.
Your other attempt, compiling and linking just trial.cpp
, never links secrypt.cpp
. This would normally result in an undefined reference to jRegister()
, but you've declared the function inside main
instead of calling it. Change main
to:
int main()
{
jRegister();
return 0;
}
Instead of using sed
to filter out the certificate, you can also pipe the openssl s_client
output through openssl x509 -out certfile.txt
, for example:
echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt
I use a function for this (if the workbook already has VBA).
Function Quote(inputText As String) As String
Quote = Chr(34) & inputText & Chr(34)
End Function
This is from Sue Mosher's book "Microsoft Outlook Programming". Then your formula would be:
="Maurice "&Quote("Rocket")&" Richard"
This is similar to what Dave DuPlantis posted.
Instead of setting up a scope variable to indicate data loading status, it is better to have a directive does everything for you:
angular.module('directive.loading', [])
.directive('loading', ['$http' ,function ($http)
{
return {
restrict: 'A',
link: function (scope, elm, attrs)
{
scope.isLoading = function () {
return $http.pendingRequests.length > 0;
};
scope.$watch(scope.isLoading, function (v)
{
if(v){
elm.show();
}else{
elm.hide();
}
});
}
};
}]);
With this directive, all you need to do is to give any loading animation element an 'loading' attribute:
<div class="loading-spiner-holder" data-loading ><div class="loading-spiner"><img src="..." /></div></div>
You can have multiple loading spinners on the page. where and how to layout those spinners is up to you and directive will simply turn it on/off for you automatically.
SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2
FROM product p
LEFT JOIN customer1 c1 ON p.cid = c1.cid
LEFT JOIN customer2 c2 ON p.cid = c2.cid
Is too simple by using the Windows Explorer search inside the project folder. Done.
Oddly enough I found that if you parse from a string it works.
int i = 0;
Long l = Long.parseLong(String.valueOf(i));
int back = Integer.parseInt(String.valueOf(l));
Win.
If you want to find the control from code behind you have to use runat="server"
attribute on control. And then you can use Control.FindControl
.
<div class="tab-pane active" id="portlet_tab1" runat="server">
Control myControl1 = FindControl("portlet_tab1");
if(myControl1!=null)
{
//do stuff
}
If you use runat server and your control is inside the ContentPlaceHolder
you have to know the ctrl name would not be portlet_tab1 anymore. It will render with the ctrl00 format.
Something like: #ctl00_ContentPlaceHolderMain_portlet_tab1. You will have to modify name if you use jquery.
You can also do it using jQuery on client side without using the runat-server attribute:
<script type='text/javascript'>
$("#portlet_tab1").removeClass("Active");
</script>
To work around the RETURN/GO issue you could put RAISERROR ('Oi! Stop!', 20, 1) WITH LOG
at the top.
This will close the client connection as per RAISERROR on MSDN.
The very big downside is you have to be sysadmin to use severity 20.
Edit:
A simple demonstration to counter Jersey Dude's comment...
RAISERROR ('Oi! Stop!', 20, 1) WITH LOG
SELECT 'Will not run'
GO
SELECT 'Will not run'
GO
SELECT 'Will not run'
GO
Try a versiontracker search instead. SqliteManager from SQLabs ($49, Mac & Windows) is the one I prefer, but I haven't really evaluated the other alternatives.
<td><input type="radio" name="gender" value="Male" id="male" <? if($gender=='Male')
{?> checked="" <? }?>/>Male
<input type="radio" name="gender" value="Female" id="female" <? if($gender=='Female') {?> checked="" <?}?>/>Female<br/> </td>
Setting -ObjC
to Other Linker Flags
in Build Settings of the target solved the problem.
io.on('connect', onConnect);
function onConnect(socket){
// sending to the client
socket.emit('hello', 'can you hear me?', 1, 2, 'abc');
// sending to all clients except sender
socket.broadcast.emit('broadcast', 'hello friends!');
// sending to all clients in 'game' room except sender
socket.to('game').emit('nice game', "let's play a game");
// sending to all clients in 'game1' and/or in 'game2' room, except sender
socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");
// sending to all clients in 'game' room, including sender
io.in('game').emit('big-announcement', 'the game will start soon');
// sending to all clients in namespace 'myNamespace', including sender
io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');
// sending to individual socketid (private message)
socket.to(<socketid>).emit('hey', 'I just met you');
// sending with acknowledgement
socket.emit('question', 'do you think so?', function (answer) {});
// sending without compression
socket.compress(false).emit('uncompressed', "that's rough");
// sending a message that might be dropped if the client is not ready to receive messages
socket.volatile.emit('maybe', 'do you really need it?');
// sending to all clients on this node (when using multiple nodes)
io.local.emit('hi', 'my lovely babies');
};
I use apache common IO to read a text file into a single string
String str = FileUtils.readFileToString(file);
simple and "clean". you can even set encoding of the text file with no hassle.
String str = FileUtils.readFileToString(file, "UTF-8");
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);
plt.show()
This is the output:
Found a step-by-step way to achieve this (for 1 font):
(as of Sep-9 2013)
- Choose your font at http://www.google.com/fonts
- Add the desired one to your collection using "Add to collection" blue button
- Click the "See all styles" button near "Remove from collection" button and make sure that you have selected other styles you may also need such as 'bold'...
- Click the 'Use' tab button on bottom right of the page
- Click the download button on top with a down arrow image
- Click on "zip file" on the the popup message that appears
- Click "Close" button on the popup
- Slowly scroll the page until you see the 3 tabs "Standrd|@import|Javascript"
- Click "@import" tab
- Select and copy the url between
'url('
and')'
- Copy it on address bar in a new tab and go there
- Do "File > Save page as..." and name it "desiredfontname.css" (replace accordingly)
- Decompress the fonts .zip file you downloaded (.ttf should be extracted)
- Go to "http://ttf2woff.com/" and convert any .ttf extracted from zip to .woff
- Edit
desiredfontname.css
and replace any url within it [between'url('
and')'
] with the corresponding converted .woff file you got on ttf2woff.com; path you write should be according to your server doc_root- Save the file and move it at its final place and write the corresponding
<link/>
CSS tag to import these in your HTML page- From now, refer to this font by its
font-family
name in your styles
That's it. Cause I had the same problem and the solution on top did not work for me.
If the database is installed on a different machine it has probably correct version of pg_dump installed. This means that you can execute pg_dump command remotely with SSH:
ssh username@dbserver pg_dump books > books.out
You can also use public key authentication for passwordless execution. Steps to achieve that:
if (isSet($_SESSION['started'])){
if((mktime() - $_SESSION['started'] - 60*30) > 0){
//Logout, destroy session, etc.
}
}
else {
$_SESSION['started'] = mktime();
}
add_shortcode( 'seriesposts', 'series_posts' );
function series_posts( $atts )
{ ob_start();
$myseriesoption = get_option( '_myseries', null );
$type = $myseriesoption;
$args=array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => 5, 'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>';
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>';
endwhile;
echo '</ul>';
}
wp_reset_query();
return ob_get_clean(); }
//this will generate a shortcode function to be used on your site [seriesposts]
Here's a three-step, somewhat minimalist version of ThorSummoner's answer for the sake of clarity. It doesn't quite do what I want (I'll explain at the bottom), but it works okay.
setup.py
filepath_to/project_name/
setup.py
In setup.py
, write:
import setuptools
setuptools.setup(name='project_name')
Run this code in console:
python -m pip install --editable filepath_to/project_name
Instead of python
, you may need to use python3
or something, depending on how your python is installed. Also, you can use -e
instead of --editable
.
Now, your directory will look more or less like this. I don't know what the egg stuff is.
filepath_to/project_name/
setup.py
test_3.egg-info/
dependency_links.txt
PKG-INFO
SOURCES.txt
top_level.txt
This folder is considered a python package and you can import from files in this parent directory even if you're writing a script anywhere else on your computer.
Let's say you make two files, one in your project's main directory and another in a sub directory. It'll look like this:
filepath_to/project_name/
top_level_file.py
subdirectory/
subfile.py
setup.py |
test_3.egg-info/ |----- Ignore these guys
... |
Now, if top_level_file.py
looks like this:
x = 1
Then I can import it from subfile.py
, or really any other file anywhere else on your computer.
# subfile.py OR some_other_python_file_somewhere_else.py
import random # This is a standard package that can be imported anywhere.
import top_level_file # Now, top_level_file.py works similarly.
print(top_level_file.x)
This is different than what I was looking for: I hoped python had a one-line way to import from a file above. Instead, I have to treat the script like a module, do a bunch of boilerplate, and install it globally for the entire python installation to have access to it. It's overkill. If anyone has a simpler method than doesn't involve the above process or importlib
shenanigans, please let me know.
In order to add a label to the map you need to create a custom overlay. The sample at http://blog.mridey.com/2009/09/label-overlay-example-for-google-maps.html uses a custom class, Layer
, that inherits from OverlayView
(which inherits from MVCObject
) from the Google Maps API. He has a revised version (adds support for visibility, zIndex and a click event) which can be found here: http://blog.mridey.com/2011/05/label-overlay-example-for-google-maps.html
The following code is taken directly from Marc Ridey's Blog (the revised link above).
Layer class
// Define the overlay, derived from google.maps.OverlayView
function Label(opt_options) {
// Initialization
this.setValues(opt_options);
// Label specific
var span = this.span_ = document.createElement('span');
span.style.cssText = 'position: relative; left: -50%; top: -8px; ' +
'white-space: nowrap; border: 1px solid blue; ' +
'padding: 2px; background-color: white';
var div = this.div_ = document.createElement('div');
div.appendChild(span);
div.style.cssText = 'position: absolute; display: none';
};
Label.prototype = new google.maps.OverlayView;
// Implement onAdd
Label.prototype.onAdd = function() {
var pane = this.getPanes().overlayImage;
pane.appendChild(this.div_);
// Ensures the label is redrawn if the text or position is changed.
var me = this;
this.listeners_ = [
google.maps.event.addListener(this, 'position_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'visible_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'clickable_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'text_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'zindex_changed', function() { me.draw(); }),
google.maps.event.addDomListener(this.div_, 'click', function() {
if (me.get('clickable')) {
google.maps.event.trigger(me, 'click');
}
})
];
};
// Implement onRemove
Label.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
// Label is removed from the map, stop updating its position/text.
for (var i = 0, I = this.listeners_.length; i < I; ++i) {
google.maps.event.removeListener(this.listeners_[i]);
}
};
// Implement draw
Label.prototype.draw = function() {
var projection = this.getProjection();
var position = projection.fromLatLngToDivPixel(this.get('position'));
var div = this.div_;
div.style.left = position.x + 'px';
div.style.top = position.y + 'px';
div.style.display = 'block';
this.span_.innerHTML = this.get('text').toString();
};
Usage
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>
Label Overlay Example
</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="label.js"></script>
<script type="text/javascript">
var marker;
function initialize() {
var latLng = new google.maps.LatLng(40, -100);
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marker = new google.maps.Marker({
position: latLng,
draggable: true,
zIndex: 1,
map: map,
optimized: false
});
var label = new Label({
map: map
});
label.bindTo('position', marker);
label.bindTo('text', marker, 'position');
label.bindTo('visible', marker);
label.bindTo('clickable', marker);
label.bindTo('zIndex', marker);
google.maps.event.addListener(marker, 'click', function() { alert('Marker has been clicked'); })
google.maps.event.addListener(label, 'click', function() { alert('Label has been clicked'); })
}
function showHideMarker() {
marker.setVisible(!marker.getVisible());
}
function pinUnpinMarker() {
var draggable = marker.getDraggable();
marker.setDraggable(!draggable);
marker.setClickable(!draggable);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="height: 200px; width: 200px"></div>
<button type="button" onclick="showHideMarker();">Show/Hide Marker</button>
<button type="button" onclick="pinUnpinMarker();">Pin/Unpin Marker</button>
</body>
</html>
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
Every time you get this kind of error
bash: <command>: command not found
On a host with that command already working with this solution:
dpkg -S $(which <command>)
Don't have a host with that package installed? Try this:
apt-file search /bin/<command>
According to python docs:
has_key()
is deprecated in favor ofkey in d
.
f(a, b) = s(a+b) + a
, where s(n) = n*(n+1)/2
s(a+b+1)-s(a+b) = a+b+1
< a
. I did not understand what You mean by:
should always yield an integer on either the positive or the negative side of integers
How can I write (greater than), (less than) characters in this forum?
Catching Exception
will catch a RuntimeException
I had the same problem. I tried installing Visual Studio 2010 SP1 but it didn't worked.
Finally I get Microsoft.Web.Infrastructure.dll from the colleague. You can find the dll into your friends PC where the project is perfectly working. Try to search dll into Temp/Temporary ASP.NET Files. Go to Temp using %temp% into run window.
After getting dll into your pc, just add reference to your project and it will work.
This might work:
public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
if(numbers[i]=='1')
result += Math.pow(2, (numbers.length-i - 1));
return result;
}
This works for me ( case for + register, what i use like exchange buffer between aps ):
imap <silent> <S-Insert> <C-O>:set noai<CR><C-R>+<C-O>:set ai<CR>
Abstraction is hiding the information or providing only necessary details to the client.
e.g Car Brakes- You just know that pressing the pedals will stop the vehicle but you don't need to know how it works internally.
Advantage of Abstraction Tomorrow if brake implementation changes from drum brake to disk brake, as a client, you don't need to change(i.e your code will not change)
Encapsulation is binding the data and behaviors together in a single unit. Also it is a language mechanism for restricting access to some components(this can be achieved by access modifiers like private,protected etc.)
For e.g. Class has attributes(i.e data) and behaviors (i.e methods that operate on that data)
set style="height:300px !important;" and "imgBanner" for img tag.
<img src="/image/1.jpg" class="imgBanner" style="width:100%; height:300px !important;">
then if you want responsive image, so you can use jquery as:
$.(function(){
$(window).resize(respWhenResize);
respWhenResize();
})
respWhenResize(){
if (pagesize < 578) {
$('.imgBanner').css('height','200px')
} else if (pagesize > 578 ) {
$('.imgBanner').css('height','300px')
}
}
Very simple: no color, no opacity:
rgba(0, 0, 0, 0);
This isn't my answer, but it definitely resonates with me. It's from ThoughtWorks' Technology Radar from October 2012:
Two things have caused fatigue with XML-based build tools like Ant and Maven: too many angry pointy braces and the coarseness of plug-in architectures. While syntax issues can be dealt with through generation, plug-in architectures severely limit the ability for build tools to grow gracefully as projects become more complex. We have come to feel that plug-ins are the wrong level of abstraction, and prefer language-based tools like Gradle and Rake instead, because they offer finer-grained abstractions and more flexibility long term.
I know this is a old question and the above solutions works fine except in some cases.
Like
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
So Item 4 will show as "Selected" in the browser and now you want to change the value as 3 and show "Item3" as selected instead of Item4.So as per the above solutions,if you use
jQuery("#select_selector").val(3);
You will see that Item 3 as selected in browser.But when you process the data either in php or asp , you will find the selected value as "4".The reason is that , your html will look like this.
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3" selected="selected">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
and it gets the last value as "4" in sever side language.
SO MY FINAL SOLUTION ON THIS REGARD
newselectedIndex = 3;
jQuery("#select_selector option:selected").removeAttr("selected");
jQuery("#select_selector option[value='"+newselectedIndex +"']").attr('selected', 'selected');
EDIT: Add single quote around "+newselectedIndex+" so that the same functionality can be used for non-numerical values.
So what I do is actually ,removed the selected attribute and then make the new one as selected.
I would appreciate comments on this from senior programmers like @strager , @y0mbo , @ISIK and others
function page_title($val){
include(dirname(__FILE__).'/simple_html_dom.php');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$val);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0');
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$return = curl_exec($ch);
$encot = false;
$charset = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
$html = str_get_html('"'.$return.'"');
if(strpos($charset,'charset=') !== false) {
$c = str_replace("text/html; charset=","",$charset);
$encot = true;
}
else {
$lookat=$html->find('meta[http-equiv=Content-Type]',0);
$chrst = $lookat->content;
preg_match('/charset=(.+)/', $chrst, $found);
$p = trim($found[1]);
if(!empty($p) && $p != "")
{
$c = $p;
$encot = true;
}
}
$title = $html->find('title')[0]->innertext;
if($encot == true && $c != 'utf-8' && $c != 'UTF-8') $title = mb_convert_encoding($title,'UTF-8',$c);
return $title;
}
In addition to the previous response, the best option to submit a form with different buttons without language problems is actually using a button tag.
<form>
...
<button type="submit" name="submit" value="servlet1">Go to 1st Servlet</button>
<button type="submit" name="submit" value="servlet2">Go to 2nd Servlet</button>
</form>
int cores = Runtime.getRuntime().availableProcessors();
If cores
is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.
From the error, I infer that referenceElement
is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).
>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
You probably meant either for element in referenceElement.keys()
or for element in json['referenceElement'].keys()
. With more context on what types json
and referenceElement
are and what they contain, we will be able to better help you if neither solution works.
move the System.out statement to finally block.
This may help you to reset your sa password for SQL 2008 and 2012
EXEC sp_password NULL, 'yourpassword', 'sa'
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
I had a problem with an xml file that had a broken encoding, it said it was utf-8 but it had characters that where not utf-8.
After several trials and errors with the mb_convert_encoding()
I manage to fix it with
mb_convert_encoding($text, 'Windows-1252', 'UTF-8')
If you encounter this error in GoDaddy after deploying a .Net MVC web application..And your web.config is absolutely correct... Right click your data project select settings and make sure that the correct connection strings to the GoDaddy server is in use
“JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What’s the fun in programming if everything just works?
Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.
TypeScript 0.9.0.1
enum e{
hello = 1,
somestr = 'world'
};
alert(e[1] + ' ' + e.somestr);
Try this:
let utcTime = "2017-02-02 08:00:13";
var local_date= moment.utc(utcTime ).local().format('YYYY-MM-DD HH:mm:ss');
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.
Configuring Flutter SDK is pretty straightforward. You don't have to set paths using the command line if you have already installed Dart and Flutter Plugins in Android Studio
Download the SDK and point the SDK folder path in your future projects.
There are different sources you can try
I don't understand the need because you already know the path when you create the project. However, you can get the idea from test/package folder
Avoid non-standard compiler extensions and implement it as a completely type-safe macro in pure standard C (ISO 9899:2011).
Solution
#define GENERIC_MAX(x, y) ((x) > (y) ? (x) : (y))
#define ENSURE_int(i) _Generic((i), int: (i))
#define ENSURE_float(f) _Generic((f), float: (f))
#define MAX(type, x, y) \
(type)GENERIC_MAX(ENSURE_##type(x), ENSURE_##type(y))
Usage
MAX(int, 2, 3)
Explanation
The macro MAX creates another macro based on the type
parameter. This control macro, if implemented for the given type, is used to check that both parameters are of the correct type. If the type
is not supported, there will be a compiler error.
If either x or y is not of the correct type, there will be a compiler error in the ENSURE_
macros. More such macros can be added if more types are supported. I've assumed that only arithmetic types (integers, floats, pointers etc) will be used and not structs or arrays etc.
If all types are correct, the GENERIC_MAX macro will be called. Extra parenthesis are needed around each macro parameter, as the usual standard precaution when writing C macros.
Then there's the usual problems with implicit type promotions in C. The ?:
operator balances the 2nd and 3rd operand against each other. For example, the result of GENERIC_MAX(my_char1, my_char2)
would be an int
. To prevent the macro from doing such potentially dangerous type promotions, a final type cast to the intended type was used.
Rationale
We want both parameters to the macro to be of the same type. If one of them is of a different type, the macro is no longer type safe, because an operator like ?:
will yield implicit type promotions. And because it does, we also always need to cast the final result back to the intended type as explained above.
A macro with just one parameter could have been written in a much simpler way. But with 2 or more parameters, there is a need to include an extra type parameter. Because something like this is unfortunately impossible:
// this won't work
#define MAX(x, y) \
_Generic((x), \
int: GENERIC_MAX(x, ENSURE_int(y)) \
float: GENERIC_MAX(x, ENSURE_float(y)) \
)
The problem is that if the above macro is called as MAX(1, 2)
with two int
, it will still try to macro-expand all possible scenarios of the _Generic
association list. So the ENSURE_float
macro will get expanded too, even though it isn't relevant for int
. And since that macro intentionally only contains the float
type, the code won't compile.
To solve this, I created the macro name during the pre-processor phase instead, with the ## operator, so that no macro gets accidentally expanded.
Examples
#include <stdio.h>
#define GENERIC_MAX(x, y) ((x) > (y) ? (x) : (y))
#define ENSURE_int(i) _Generic((i), int: (i))
#define ENSURE_float(f) _Generic((f), float: (f))
#define MAX(type, x, y) \
(type)GENERIC_MAX(ENSURE_##type(x), ENSURE_##type(y))
int main (void)
{
int ia = 1, ib = 2;
float fa = 3.0f, fb = 4.0f;
double da = 5.0, db = 6.0;
printf("%d\n", MAX(int, ia, ib)); // ok
printf("%f\n", MAX(float, fa, fb)); // ok
//printf("%d\n", MAX(int, ia, fa)); compiler error, one of the types is wrong
//printf("%f\n", MAX(float, fa, ib)); compiler error, one of the types is wrong
//printf("%f\n", MAX(double, fa, fb)); compiler error, the specified type is wrong
//printf("%f\n", MAX(float, da, db)); compiler error, one of the types is wrong
//printf("%d\n", MAX(unsigned int, ia, ib)); // wont get away with this either
//printf("%d\n", MAX(int32_t, ia, ib)); // wont get away with this either
return 0;
}
Disclaimer: I'm not a radioactivity professional nor worked for this kind of application. But I worked on soft errors and redundancy for long term archival of critical data, which is somewhat linked (same problem, different goals).
The main problem with radioactivity in my opinion is that radioactivity can switch bits, thus radioactivity can/will tamper any digital memory. These errors are usually called soft errors, bit rot, etc.
The question is then: how to compute reliably when your memory is unreliable?
To significantly reduce the rate of soft errors (at the expense of computational overhead since it will mostly be software-based solutions), you can either:
rely on the good old redundancy scheme, and more specifically the more efficient error correcting codes (same purpose, but cleverer algorithms so that you can recover more bits with less redundancy). This is sometimes (wrongly) also called checksumming. With this kind of solution, you will have to store the full state of your program at any moment in a master variable/class (or a struct?), compute an ECC, and check that the ECC is correct before doing anything, and if not, repair the fields. This solution however does not guarantee that your software can work (simply that it will work correctly when it can, or stops working if not, because ECC can tell you if something is wrong, and in this case you can stop your software so that you don't get fake results).
or you can use resilient algorithmic data structures, which guarantee, up to a some bound, that your program will still give correct results even in the presence of soft errors. These algorithms can be seen as a mix of common algorithmic structures with ECC schemes natively mixed in, but this is much more resilient than that, because the resiliency scheme is tightly bounded to the structure, so that you don't need to encode additional procedures to check the ECC, and usually they are a lot faster. These structures provide a way to ensure that your program will work under any condition, up to the theoretical bound of soft errors. You can also mix these resilient structures with the redundancy/ECC scheme for additional security (or encode your most important data structures as resilient, and the rest, the expendable data that you can recompute from the main data structures, as normal data structures with a bit of ECC or a parity check which is very fast to compute).
If you are interested in resilient data structures (which is a recent, but exciting, new field in algorithmics and redundancy engineering), I advise you to read the following documents:
Resilient algorithms data structures intro by Giuseppe F.Italiano, Universita di Roma "Tor Vergata"
Christiano, P., Demaine, E. D., & Kishore, S. (2011). Lossless fault-tolerant data structures with additive overhead. In Algorithms and Data Structures (pp. 243-254). Springer Berlin Heidelberg.
Ferraro-Petrillo, U., Grandoni, F., & Italiano, G. F. (2013). Data structures resilient to memory faults: an experimental study of dictionaries. Journal of Experimental Algorithmics (JEA), 18, 1-6.
Italiano, G. F. (2010). Resilient algorithms and data structures. In Algorithms and Complexity (pp. 13-24). Springer Berlin Heidelberg.
If you are interested in knowing more about the field of resilient data structures, you can checkout the works of Giuseppe F. Italiano (and work your way through the refs) and the Faulty-RAM model (introduced in Finocchi et al. 2005; Finocchi and Italiano 2008).
/EDIT: I illustrated the prevention/recovery from soft-errors mainly for RAM memory and data storage, but I didn't talk about computation (CPU) errors. Other answers already pointed at using atomic transactions like in databases, so I will propose another, simpler scheme: redundancy and majority vote.
The idea is that you simply do x times the same computation for each computation you need to do, and store the result in x different variables (with x >= 3). You can then compare your x variables:
This redundancy scheme is very fast compared to ECC (practically O(1)) and it provides you with a clear signal when you need to failsafe. The majority vote is also (almost) guaranteed to never produce corrupted output and also to recover from minor computation errors, because the probability that x computations give the same output is infinitesimal (because there is a huge amount of possible outputs, it's almost impossible to randomly get 3 times the same, even less chances if x > 3).
So with majority vote you are safe from corrupted output, and with redundancy x == 3, you can recover 1 error (with x == 4 it will be 2 errors recoverable, etc. -- the exact equation is nb_error_recoverable == (x-2)
where x is the number of calculation repetitions because you need at least 2 agreeing calculations to recover using the majority vote).
The drawback is that you need to compute x times instead of once, so you have an additional computation cost, but's linear complexity so asymptotically you don't lose much for the benefits you gain. A fast way to do a majority vote is to compute the mode on an array, but you can also use a median filter.
Also, if you want to make extra sure the calculations are conducted correctly, if you can make your own hardware you can construct your device with x CPUs, and wire the system so that calculations are automatically duplicated across the x CPUs with a majority vote done mechanically at the end (using AND/OR gates for example). This is often implemented in airplanes and mission-critical devices (see triple modular redundancy). This way, you would not have any computational overhead (since the additional calculations will be done in parallel), and you have another layer of protection from soft errors (since the calculation duplication and majority vote will be managed directly by the hardware and not by software -- which can more easily get corrupted since a program is simply bits stored in memory...).
Just assign the import to a data property
<script>
import json from './json/data.json'
export default{
data(){
return{
myJson: json
}
}
}
</script>
then loop through the myJson
property in your template using v-for
<template>
<div>
<div v-for="data in myJson">{{data}}</div>
</div>
</template>
NOTE
If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.
Vue converts all the properties in the data
option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.
So you can create a custom option as follows:
<script>
import MY_JSON from './json/data.json'
export default{
//custom option named myJson
myJson: MY_JSON
}
</script>
then loop through the custom option in your template using $options
:
<template>
<div>
<div v-for="data in $options.myJson">{{data}}</div>
</div>
</template>
What I can think of is to stretch either width or height and let it resize in ratio-aspect. There will be some white space on the sides. Something like how a Wide screen displays a resolution of 1024x768.
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
You could use the ngSwitch directive:
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.
This is just an (untested) example. It can and should be optimized:
HTML:
<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>
Directive:
app.directive('conditionalTemplate', function($http, $compile) {
return {
restrict: 'E',
require: '^ngModel',
link: function(sope, element, attrs, ctrl) {
// get template with $http
// check model via ctrl.$viewValue
// compile with $compile
// replace element with element.replaceWith()
}
};
});
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
The string method replace
does not modify the original string. It leaves the original alone and returns a modified copy.
What you want is something like: line = line.replace(char,'')
def replace_all(line, )for char in line:
if char in " ?.!/;:":
line = line.replace(char,'')
return line
However, creating a new string each and every time that a character is removed is very inefficient. I recommend the following instead:
def replace_all(line, baddies, *):
"""
The following is documentation on how to use the class,
without reference to the implementation details:
For implementation notes, please see comments begining with `#`
in the source file.
[*crickets chirp*]
"""
is_bad = lambda ch, baddies=baddies: return ch in baddies
filter_baddies = lambda ch, *, is_bad=is_bad: "" if is_bad(ch) else ch
mahp = replace_all.map(filter_baddies, line)
return replace_all.join('', join(mahp))
# -------------------------------------------------
# WHY `baddies=baddies`?!?
# `is_bad=is_bad`
# -------------------------------------------------
# Default arguments to a lambda function are evaluated
# at the same time as when a lambda function is
# **defined**.
#
# global variables of a lambda function
# are evaluated when the lambda function is
# **called**
#
# The following prints "as yellow as snow"
#
# fleece_color = "white"
# little_lamb = lambda end: return "as " + fleece_color + end
#
# # sometime later...
#
# fleece_color = "yellow"
# print(little_lamb(" as snow"))
# --------------------------------------------------
replace_all.map = map
replace_all.join = str.join
You can use preg_replace in this case;
$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
$res return 6 in this case.
If want also to include decimal separator or thousand separator check this example:
$res = preg_replace("/[^0-9.]/", "", "$ 123.099");
$res returns "123.099" in this case
Include period as decimal separator or thousand separator: "/[^0-9.]/"
Include coma as decimal separator or thousand separator: "/[^0-9,]/"
Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"
At the moment it is not possible to import a CSV (using MySQL Workbench) in all platforms, nor is advised if said file does not reside in the same host as the MySQL server host.
However, you can use mysqlimport.
Example:
mysqlimport --local --compress --user=username --password --host=hostname \
--fields-terminated-by=',' Acme sales.part_*
In this example mysqlimport
is instructed to load all of the files named "sales" with an extension starting with "part_". This is a convenient way to load all of the files created in the "split" example. Use the --compress option to minimize network traffic. The --fields-terminated-by=',' option is used for CSV files and the --local option specifies that the incoming data is located on the client. Without the --local option, MySQL will look for the data on the database host, so always specify the --local option.
There is useful information on the subject in AWS RDS documentation.
I would probably do something like this
length(which(numbers==x))
But really, a better way is
table(numbers)
You need to first create a URI like:
String urlStr = "http://www.example.com/CEREC® Materials & Accessories/IPS Empress® CAD.pdf"
URL url= new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
Then convert that Uri to ASCII string:
urlStr=uri.toASCIIString();
Now your url string is completely encoded first we did simple url encoding and then we converted it to ASCII String to make sure no character outside US-ASCII are remaining in string. This is exactly how browsers do.
Firebase listeners fire for both the initial data and any changes.
If you're looking to synchronize the data in a collection, use ChildEventListener
. If you're looking to synchronize a single object, use ValueEventListener
. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.
This is covered in Firebase's quickstart guide for Android. The relevant code and quote:
FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue()); //prints "Do you have data? You'll love Firebase."
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.
Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write
Just to reword Itai's excellent (and working!) code, here's what a sample helper class would look like, to return the year value of a given NSDate variable.
As you can see, it's easy enough to modify this code to get the month or day.
+(int)getYear:(NSDate*)date
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];
return year;
}
(I can't believe we're having to write our own basic iOS date functions like this, in 2013...)
One other thing: don't ever use < and > to compare two NSDate values.
XCode will happily accept such code (without any errors or warnings), but its results are a lottery. You must use the "compare" function to compare NSDates:
if ([date1 compare:date2] == NSOrderedDescending) {
// date1 is greater than date2
}
You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed
user_input = input("Enter Numbers\n").split(',')
#strip is used to remove the white space. Not mandatory
all_numbers = [int(x.strip()) for x in user_input]
for i in all_numbers:
print(i)
That comment looks like it is a custom version of Bootstrap v2.3.3, here is the default header in the .css, notice the last comment line:
/*!
* Bootstrap v2.3.2
*
* Copyright 2013 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @mdo and @fat.
*/
What are you trying to accomplish? If it's customization then you have a set of files to work with though that seems like a bad idea. Otherwise, I would suggest going with the full build of v4.1.x since that is the current release.
You can use Series.isin
:
df = df[~df.datecolumn.isin(a)]
While the error message suggests that all()
or any()
can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).
You can read more about this in the Gotchas.