You are using .net 4? - Maybe on the clients there is only the ".net framework 4 client profile" installed. Try to install full package!! Download here
Reset identity column with new id...
DECLARE @MAX INT
SELECT @MAX=ISNULL(MAX(Id),0) FROM [TestTable]
DBCC CHECKIDENT ('[TestTable]', RESEED,@MAX)
You can very easily use this to re-use the value of the variable in another function.
// Use this in source window.var1= oEvent.getSource().getBindingContext();
// Get value of var1 in destination var var2= window.var1;
I have run into this issue before and found that sometimes padding is the issue.
By removing padding from the ul, any li's set to inline-block will be nicely centred:
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
ul {_x000D_
width: 120px;_x000D_
margin: auto;_x000D_
text-align: center;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
li {_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
ul.no_pad {_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
p {_x000D_
margin: auto;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.break {_x000D_
margin: 50px 10px;_x000D_
}
_x000D_
<div> _x000D_
<p>With Padding (Default Style)</p>_x000D_
<ul class="with_pad">_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
</ul>_x000D_
<div class="break"></div>_x000D_
<p>No Padding (Padding: 0)</p>_x000D_
<ul class="no_pad">_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
<li>x</li>_x000D_
</ul>_x000D_
<div>
_x000D_
Hope that helps anyone running into this same issue :)
Cheers,
Jake
Try this:
Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw.WriteLine( _
IIf(fileExists, _
"Error Message in Occured at-- " & DateTime.Now, _
"Start Error Log for today"))
End Using
Simple Solution
Here is a simple solution. No additional for loop required.
HTML part
<table ng-init="ResetTotalAmt()">
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr ng-repeat="product in cart.products">
<td ng-init="CalculateSum(product)">{{product.name}}</td>
<td>{{product.quantity}}</td>
<td>{{product.price * product.quantity}} €</td>
</tr>
<tr>
<td></td>
<td>Total :</td>
<td>{{cart.TotalAmt}}</td> // Here is the total value of my cart
</tr>
</table>
Script Part
$scope.cart.TotalAmt = 0;
$scope.CalculateSum= function (product) {
$scope.cart.TotalAmt += (product.price * product.quantity);
}
//It is enough to Write code $scope.cart.TotalAmt =0; in the function where the cart.products get allocated value.
$scope.ResetTotalAmt = function (product) {
$scope.cart.TotalAmt =0;
}
Just use matrix
:
matrix(vec,nrow = 7,ncol = 7)
One advantage of using matrix
rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow
argument in matrix
.
The C++ way would be to use a std::stringstream
object as:
std::stringstream fmt;
fmt << a << " " << b << " > " << c;
The C way would be to use sprintf
.
The C way is difficult to get right since:
Of course, you may want to fall back on the C way if performance is an issue (imagine you are creating fixed-size million little stringstream
objects and then throwing them away).
Use Comparator
and then put objects into Collection
, then Collections.sort();
class Person {
String fname;
String lname;
int age;
public Person() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Person(String fname, String lname, int age) {
this.fname = fname;
this.lname = lname;
this.age = age;
}
@Override
public String toString() {
return fname + "," + lname + "," + age;
}
}
public class Main{
public static void main(String[] args) {
List<Person> persons = new java.util.ArrayList<Person>();
persons.add(new Person("abc3", "def3", 10));
persons.add(new Person("abc2", "def2", 32));
persons.add(new Person("abc1", "def1", 65));
persons.add(new Person("abc4", "def4", 10));
System.out.println(persons);
Collections.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person t, Person t1) {
return t.getAge() - t1.getAge();
}
});
System.out.println(persons);
}
}
You can find another simpler option in a thread here: Match Against.. with a more detail help in 11.9.2. Boolean Full-Text Searches
This is just in case someone need a more compact option. This will require to create an Index FULLTEXT in the table, which can be accomplish easily.
Information on how to create Indexes (MySQL): MySQL FULLTEXT Indexing and Searching
In the FULLTEXT
Index you can have more than one column listed, the result would be an SQL Statement with an index named search
:
SELECT *,MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*') as relevance FROM `documents`USE INDEX(search) WHERE MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*' IN BOOLEAN MODE) ORDER BY relevance;
I tried with multiple columns, with no luck. Even though multiple columns are allowed in indexes, you still need an index for each column to use with Match/Against Statement.
Depending in your criterias you can use either options.
When you say multiple queries do you mean multiple SQL statements as in:
UPDATE table1 SET a=b WHERE c;
UPDATE table2 SET a=b WHERE d;
UPDATE table3 SET a=b WHERE e;
Or multiple query function calls as in:
mySqlQuery(UPDATE table1 SET a=b WHERE c;)
mySqlQuery(UPDATE table2 SET a=b WHERE d;)
mySqlQuery(UPDATE table3 SET a=b WHERE e;)
The former can all be done using a single mySqlQuery call if that is what you wanted to achieve, simply call the mySqlQuery function in the following manner:
mySqlQuery(UPDATE table1 SET a=b WHERE c; UPDATE table2 SET a=b WHERE d; UPDATE table3 SET a=b WHERE e;)
This will execute all three queries with one mySqlQuery() call.
SELECT
GROUP_CONCAT(DISTINCT (category))
FROM (
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
FROM
numbers INNER JOIN tableName
ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
) s;
This will return distinct values like: test1,test2,test4,test3
Here is variant of @juraj-blahunka's lightweight approach. This function does not assume the container is the document and only scrolls if the item is out of view. Animation queuing is also disabled to avoid unnecessary bouncing.
$.fn.scrollToView = function () {
return $.each(this, function () {
if ($(this).position().top < 0 ||
$(this).position().top + $(this).height() > $(this).parent().height()) {
$(this).parent().animate({
scrollTop: $(this).parent().scrollTop() + $(this).position().top
}, {
duration: 300,
queue: false
});
}
});
};
Here is my version:
List<object> list = new List<object>(new object[]{ "test", 0, "hello", 1, "world" });
foreach(var x in list)
{
Console.WriteLine("x: {0}", x);
}
Here is a functional ES6 way of iterating over a NodeList
. This method uses the Array
's forEach
like so:
Array.prototype.forEach.call(element.childNodes, f)
Where f
is the iterator function that receives a child nodes as it's first parameter and the index as the second.
If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:
const forEach = f => x => Array.prototype.forEach.call(x, f);
// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)
// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)
(You can do the same trick for map()
and other Array functions.)
Here is my Implementation of Stacks.
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.length = length;
}
function push(element) {
this.dataStore[this.top++] = element;
}
function peek() {
return this.dataStore[this.top-1];
}
function pop() {
return this.dataStore[--this.top];
}
function clear() {
this.top = 0;
}
function length() {
return this.top;
}
var s = new Stack();
s.push("David");
s.push("Raymond");
s.push("Bryan");
console.log("length: " + s.length());
console.log(s.peek());
You are missing router exports module and that is the reason why this error is present.
use module.exports = router;
and that would work
As Ennui mentioned, IE 10 supports the -ms
prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:
display: -ms-flexbox
instead of display: -ms-flex
flex
values, like flex: 0 1 auto
to avoid ambiguitySo the final updated code is...
.flexbox form {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flexbox;
display: -o-flex;
display: flex;
/* Direction defaults to 'row', so not really necessary to specify */
-webkit-flex-direction: row;
-moz-flex-direction: row;
-ms-flex-direction: row;
-o-flex-direction: row;
flex-direction: row;
}
.flexbox form input[type=submit] {
width: 31px;
}
.flexbox form input[type=text] {
width: auto;
/* Flex should have 3 values which is shorthand for
<flex-grow> <flex-shrink> <flex-basis> */
-webkit-flex: 1 1 auto;
-moz-flex: 1 1 auto;
-ms-flex: 1 1 auto;
-o-flex: 1 1 auto;
flex: 1 1 auto;
/* I don't think you need 'display: flex' on child elements * /
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
/**/
}
For people who find this via search engines, you do not need VBA. You can just:
1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.
I can think of doing it in two ways:
Storing the file in file system in any directory (say dir1
) and renaming it which ensures that the name is unique for every file (may be a timestamp) (say xyz123.jpg
), and then storing this name in some DataBase. Then while generating the JSON you pull this filename and generate a complete URL (which will be http://example.com/dir1/xyz123.png
)and insert it in the JSON.
Base 64 Encoding, It's basically a way of encoding arbitrary binary data in ASCII text. It takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end. Essentially each 6 bits of the input is encoded in a 64-character alphabet. The "standard" alphabet uses A-Z, a-z, 0-9 and + and /, with = as a padding character. There are URL-safe variants. So this approach will allow you to put your image directly in the MongoDB, while storing it Encode the image and decode while fetching it, it has some of its own drawbacks:
A.) Canvas
Load the image into an Image-Object, paint it to a canvas and convert the canvas back to a dataURL.
function convertToDataURLviaCanvas(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
Usage
convertToDataURLviaCanvas('http://bit.ly/18g0VNp', function(base64Img){
// Base64DataURL
});
Supported input formats
image/png
, image/jpeg
, image/jpg
, image/gif
, image/bmp
, image/tiff
, image/x-icon
, image/svg+xml
, image/webp
, image/xxx
B.) FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a data URL.
function convertFileToBase64viaFileReader(url, callback){
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
This approach
Usage
convertFileToBase64viaFileReader('http://bit.ly/18g0VNp', function(base64Img){
// Base64DataURL
});
In addition to the very great answer above I want to mention application wide events which can be very useful in an MVC setup to enable communication between controllers. (extjs4.1)
Lets say we have a controller Station (Sencha MVC examples) with a select box:
Ext.define('Pandora.controller.Station', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'stationslist': {
selectionchange: this.onStationSelect
},
...
});
},
...
onStationSelect: function(selModel, selection) {
this.application.fireEvent('stationstart', selection[0]);
},
...
});
When the select box triggers a change event, the function onStationSelect
is fired.
Within that function we see:
this.application.fireEvent('stationstart', selection[0]);
This creates and fires an application wide event that we can listen to from any other controller.
Thus in another controller we can now know when the station select box has been changed. This is done through listening to this.application.on
as follows:
Ext.define('Pandora.controller.Song', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'recentlyplayedscroller': {
selectionchange: this.onSongSelect
}
});
// Listen for an application wide event
this.application.on({
stationstart: this.onStationStart,
scope: this
});
},
....
onStationStart: function(station) {
console.info('I called to inform you that the Station controller select box just has been changed');
console.info('Now what do you want to do next?');
},
}
If the selectbox has been changed we now fire the function onStationStart
in the controller Song
also ...
From the Sencha docs:
Application events are extremely useful for events that have many controllers. Instead of listening for the same view event in each of these controllers, only one controller listens for the view event and fires an application-wide event that the others can listen for. This also allows controllers to communicate with one another without knowing about or depending on each other’s existence.
In my case: Clicking on a tree node to update data in a grid panel.
Update 2016 thanks to @gm2008 from the comments below:
In terms of firing application-wide custom events, there is a new method now after ExtJS V5.1 is published, which is using Ext.GlobalEvents
.
When you fire events, you can call: Ext.GlobalEvents.fireEvent('custom_event');
When you register a handler of the event, you call: Ext.GlobalEvents.on('custom_event', function(arguments){/* handler codes*/}, scope);
This method is not limited to controllers. Any component can handle a custom event through putting the component object as the input parameter scope.
my_hash = {:a => 5}
my_hash[:key] = "value"
You have a pointer to a char
. So as your system knows, on that memory address there is a char
value on sizeof(char)
space. When you cast it up to int*
, you will work with data of sizeof(int)
, so you will print your char and some memory-garbage after it as an integer.
I had the same problem when trying to load Hadoop project in eclipse. I tried the solutions above, and I believe it might have worked in Eclipse Kepler... not even sure anymore (tried too many things).
With all the problems I was having, I decided to move on to Eclipse Luna, and the solutions above did not work for me.
There was another post that recommended changing the ... tag to package. I started doing that, and it would "clear" the errors... However, I start to think that the changes would bite me later - I am not an expert on Maven.
Fortunately, I found out how to remove all the errors. Go to Window->Preferences->Maven-> Error/Warnings and change "Plugin execution not covered by lifecycle..." option to "Ignore". Hope it helps.
you can do this.
//Create IEnumerable
IEnumerable<T> items = new T[]{new T("msg")};
//Convert to list.
List<T> list = items.ToList();
//Add new item to list.
list.add(new T("msg2"));
//Cast list to IEnumerable
items = (IEnumerable<T>)items;
// you can get current date/time with the following code:
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
formatter.timeZone = destinationTimeZone;
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setDateFormat:@"MM/dd/yyyy hh:mma"];
NSString* dateString = [formatter stringFromDate:date];
in Developer options,
(if there is no a Developer option menu, you have to click 3 times build number of Phone State menu to be developer. you can sse a developer option menu.)
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
Note that your conversion function should ideally be returning a const char *.
If you can afford to put your enums in their separate header files, you could perhaps do something like this with macros (oh, this will be ugly):
#include "enum_def.h"
#include "colour.h"
#include "enum_conv.h"
#include "colour.h"
Where enum_def.h has:
#undef ENUM_START
#undef ENUM_ADD
#undef ENUM_END
#define ENUM_START(NAME) enum NAME {
#define ENUM_ADD(NAME, VALUE) NAME = VALUE,
#define ENUM_END };
And enum_conv.h has:
#undef ENUM_START
#undef ENUM_ADD
#undef ENUM_END
#define ENUM_START(NAME) const char *##NAME##_to_string(NAME val) { switch (val) {
#define ENUM_ADD(NAME, VALUE) case NAME: return #NAME;
#define ENUM_END default: return "Invalid value"; } }
And finally, colour.h has:
ENUM_START(colour)
ENUM_ADD(red, 0xff0000)
ENUM_ADD(green, 0x00ff00)
ENUM_ADD(blue, 0x0000ff)
ENUM_END
And you can use the conversion function as:
printf("%s", colour_to_string(colour::red));
This is ugly, but it's the only way (at the preprocessor level) that lets you define your enum just in a single place in your code. Your code is therefore not prone to errors due to modifications to the enum. Your enum definition and the conversion function will always be in sync. However, I repeat, this is ugly :)
I have a GitHub Gist with a Java like UUID implementation in C#: https://gist.github.com/rickbeerendonk/13655dd24ec574954366
The UUID can be created from the least and most significant bits, just like in Java. It also exposes them. The implementation has an explicit conversion to a GUID and an implicit conversion from a GUID.
A solution that keeps no traces of the "undo".
NOTE: don't do this if someone allready pulled your change (I would use this only on my personal repo)
do:
git reset <previous label or sha1>
this will re-checkout all the updates locally (so git status will list all updated files)
then you "do your work" and re-commit your changes (Note: this step is optional)
git commit -am "blabla"
At this moment your local tree differs from the remote
git push -f <remote-name> <branch-name>
will push and force remote to consider this push and remove the previous one (specifying remote-name and branch-name is not mandatory but is recommended to avoid updating all branches with update flag).
!! watch-out some tags may still be pointing removed commit !! how-to-delete-a-remote-tag
I Would suggest the following:
var="any given string"
N=${#var}
G=${var//g/}
G=${#G}
(( G = N - G ))
echo "$G"
No call to any other program
I think this is the best approach. Using generic ArrayAdapter class and extends your own Object adapter is as simple as follows:
public abstract class GenericArrayAdapter<T> extends ArrayAdapter<T> {
// Vars
private LayoutInflater mInflater;
public GenericArrayAdapter(Context context, ArrayList<T> objects) {
super(context, 0, objects);
init(context);
}
// Headers
public abstract void drawText(TextView textView, T object);
private void init(Context context) {
this.mInflater = LayoutInflater.from(context);
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
vh = new ViewHolder(convertView);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
drawText(vh.textView, getItem(position));
return convertView;
}
static class ViewHolder {
TextView textView;
private ViewHolder(View rootView) {
textView = (TextView) rootView.findViewById(android.R.id.text1);
}
}
}
and here your adapter (example):
public class SizeArrayAdapter extends GenericArrayAdapter<Size> {
public SizeArrayAdapter(Context context, ArrayList<Size> objects) {
super(context, objects);
}
@Override public void drawText(TextView textView, Size object) {
textView.setText(object.getName());
}
}
and finally, how to initialize it:
ArrayList<Size> sizes = getArguments().getParcelableArrayList(Constants.ARG_PRODUCT_SIZES);
SizeArrayAdapter sizeArrayAdapter = new SizeArrayAdapter(getActivity(), sizes);
listView.setAdapter(sizeArrayAdapter);
I've created a Gist with TextView layout gravity customizable ArrayAdapter:
If I were you I would not use either of them.
The disadvantage of the first one is that the parameter names might collide if there are same values in the list.
The disadvantage of the second one is that you are creating command and parameters for each entity.
The best way is to have the command text and parameters constructed once (use Parameters.Add
to add the parameters) change their values in the loop and execute the command. That way the statement will be prepared only once. You should also open the connection before you start the loop and close it after it.
For anyone learning this stuff, comments are more important, so drawing on Xak Tacit's idea
(from User500099's link) for Single Property comments, add this to the top of the XAML code block:
<!--Comments Allowed With Markup Compatibility (mc) In XAML!
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
Usage in property:
ØignoreØ:AttributeToIgnore="Text Of AttributeToIgnore"-->
Then in the code block
<Application FooApp:Class="Foo.App"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
...
AttributeNotToIgnore="TextNotToIgnore"
...
...
ØignoreØ:IgnoreThisAttribute="IgnoreThatText"
...
>
</Application>
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
Note that from MS SQL 2012 onwards you can use FORMAT(value,'format')
e.g. WHERE FORMAT(YourDatetime,'HH:mm') = '17:00'
This thread is a bit old but the information should be updated.
To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
$("#radiobutt input[type=radio]").each(function(i){
$(this).click(function () {
if(i==2) { //3rd radiobutton
$("#textbox1").prop("disabled", true);
$("#checkbox1").prop("disabled", true);
}
else {
$("#textbox1").prop("disabled", false);
$("#checkbox1").prop("disabled", false);
}
});
});
As explained in here: https://css-tricks.com/centering-in-the-unknown/.
As tested in the real practice, the most reliable yet elegant solution is to insert an assistent inline element into the
<li />
element as the 1st child, which height should be set to 100% (of its parent’s height, the<li />
), and itsvertical-align
set to middle. To achieve this, you can put a<span />
, but the most convenient way is to useli:after
pseudo class.
Screenshot:
ul.menu-horizontal {
list-style-type: none;
margin: 0;
padding: 0;
display: inline-block;
vertical-align: middle;
}
ul.menu-horizontal:after {
content: '';
clear: both;
float: none;
display: block;
}
ul.menu-horizontal li {
padding: 5px 10px;
box-sizing: border-box;
height: 100%;
cursor: pointer;
display: inline-block;
vertical-align: middle;
float: left;
}
/* The magic happens here! */
ul.menu-horizontal li:before {
content: '';
display: inline;
height: 100%;
vertical-align: middle;
}
Width value doesn't take into account border or padding:
http://www.htmldog.com/reference/cssproperties/width/
You get 2px of padding in each side, plus 1px of border in each side.
100% + 2*(2px +1px) = 100% + 6px, which is more than the 100% child-content the parent td has.
You have the option of:
box-sizing: border-box;
as per @pricco's answer;position()
. E.G.:
<countNo><xsl:value-of select="position()" /></countNo>
Just a helpful hint, there is a company called Yodlee.com who provides this data. They do charge for the API. Companies like Mint.com use this API to gather bank and financial account data.
Also, checkout https://plaid.com/, they are a similar company Yodlee.com and provide both authentication API for several banks and REST-based transaction fetching endpoints.
You're not saying how exactly putdata()
is not behaving. I'm assuming you're doing
>>> pic.putdata(a)
Traceback (most recent call last):
File "...blablabla.../PIL/Image.py", line 1185, in putdata
self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple
This is because putdata
expects a sequence of tuples and you're giving it a numpy array. This
>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)
will work but it is very slow.
As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply
>>> pix = numpy.array(pic)
although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).
Then, after you make your changes to the array, you should be able to do either pic.putdata(pix)
or create a new image with Image.fromarray(pix)
.
Assuming the column is set to support NULL as a value:
UPDATE YOUR_TABLE
SET column = NULL
Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:
UPDATE YOUR_TABLE
SET column = CAST(NULL AS DATETIME)
...assuming column
is a DATETIME data type in the example above.
Another way to understand those concept is as follow: Depth: Draw a horizontal line at the root position and treat this line as ground. So the depth of the root is 0, and all its children are grow downward so each level of nodes has the current depth + 1.
Height: Same horizontal line but this time the ground position is external nodes, which is the leaf of tree and count upward.
Try this code:
[self.navigationController presentViewController:controller animated:YES completion:nil];
There is also a way to add an attribute to an XmlNode
object, that can be useful in some cases.
I found this other method on msdn.microsoft.com.
using System.Xml;
[...]
//Assuming you have an XmlNode called node
XmlNode node;
[...]
//Get the document object
XmlDocument doc = node.OwnerDocument;
//Create a new attribute
XmlAttribute attr = doc.CreateAttribute("attributeName");
attr.Value = "valueOfTheAttribute";
//Add the attribute to the node
node.Attributes.SetNamedItem(attr);
[...]
You want a check constraint.
CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.
You want something like:
ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.
0 - Right click on the Solution and clean solution
1 - Close VS
2 - Delete project's .suo file
3 - Open VS
4 - Build solution
Also see this related question's answer.
The gist is: Try unzipping it again with a solid unzip tool. Sometimes unzipping goes wrong, especially with the built-in Windows Explorer tool.
if you have repository for entity Foo
and need to select all entries with exact string value boo
(also works for other primitive types or entity types). Put this into your repository interface:
List<Foo> findByBoo(String boo);
if you need to order results:
List<Foo> findByBooOrderById(String boo);
See more at reference.
If you want "tag_name" with associated "blogTags_id" use: (PHP > 5.5)
$blogDatas = array_column($your_multi_dim_array, 'tag_name', 'blogTags_id');
echo implode(', ', array_map(function ($k, $v) { return "$k: $v"; }, array_keys($blogDatas), array_values($blogDatas)));
sys.argv
is the list of arguments passed to the Python program. The first argument, sys.argv[0]
, is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason sys.argv[0]
exists is so you can change your program's behaviour depending on how it was invoked. sys.argv[1]
is thus the first argument you actually pass to the program.
Because lists (like most sequences) in Python start indexing at 0, and because indexing past the end of the list is an error, you need to check if the list has length 2 or longer before you can access sys.argv[1]
.
You can use CSS:
p.capitalize {text-transform:capitalize;}
Based on Kamal Reddy's comment:
document.getElementById("myP").style.textTransform = "capitalize";
Playing with the tsconfig.json You can also targeting es5 like this :
{
"compilerOptions": {
"experimentalDecorators": true,
"module": "commonjs",
"target": "es5"
}
...
You can use jquery for create element on the fly
$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');
or other way
$('<input>').attr({
type: 'hidden',
id: 'fieldId',
name: 'fieldname'
}).appendTo('form')
Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want
x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)
WORD.C <- function(WORDS){
require(wordcloud)
L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))
# Takes a dataframe and the text you want to display
FUN <- function(X, text){
windows()
wordcloud(X[, 1], X[, 2], min.freq=1)
mtext(text, 3, padj=-4.5, col="red") #what I'm trying that isn't working
}
# Now creates the sequence 1,...,length(L2)
# Loops over that and then create an anonymous function
# to send in the information you want to use.
lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})
# Since you asked about loops
# you could use i in seq_along(L2)
# instead of 1:length(L2) if you wanted to
#for(i in 1:length(L2)){
# FUN(L2[[i]], names(L2)[i])
#}
}
WORD.C(list.xy)
For a 64-bit OS, the path would be:
HKEY_LOCAL_MACHINE\SOFTWARE\wow6432Node\Microsoft\NET Framework Setup\NDP\
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
Considering a part of a Comment made by @SSilk my end goal has really been to get everything to the right of that last occurence an alternative approach with a very simple formula is to copy a column (say A
) of strings and on the copy (say ColumnB) apply Find and Replace. For instance taking the example: Drive:\Folder\SubFolder\Filename.ext
This returns what remains (here Filename.ext
) after the last instance of whatever character is chosen (here \
) which is sometimes the objective anyway and facilitates finding the position of the last such character with a short formula such as:
=FIND(B1,A1)-1
To iterate through the keys of an object, use a for .. in
loop:
for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}
To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.
Removing a property of an object can be done by using the delete
keyword:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
Documentation:
Just Follow this to Insert values into database
//Connection String
con.Open();
sqlQuery = "INSERT INTO [dbo].[Client] ([Client_ID],[Client_Name],[Phone],[Address],[Image]) VALUES('" + txtClientID.Text + "','" + txtClientName.Text + "','" + txtPhoneno.Text + "','" + txtaddress.Text + "',@image)";
cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.Add("@image", SqlDbType.Image);
cmd.Parameters["@image"].Value = img;
//img is a byte object
** /*MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms,pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();*/**
cmd.ExecuteNonQuery();
con.Close();
SELECT Emp_cd, Val1, Val2, Val3, SUM(Val1 + Val2 + Val3) AS TOTAL
FROM Emp
GROUP BY Emp_cd, Val1, Val2, Val3
For example, you can invoke a private constructor inside a friend class or a friend function.
Singleton pattern usually uses it to make sure that nobody creates more instances of the intended type.
append
actually changes the list. Also, it takes an item, not a list. Hence, all you need is
for i in range(n):
list1.append(i)
(By the way, note that you can use range(n)
, in this case.)
I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more pythonic for this:
list1 = [i for i in range(n)]
Or, in this case, in Python 2.x range(n)
in fact creates the list that you want already, although in Python 3.x, you need list(range(n))
.
I wrote this pattern:
Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
And use it in this method:
String escapeSpecialRegexChars(String str) {
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}
Then you can use it like this, for example:
Pattern toSafePattern(String text)
{
return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}
We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q
and \E
:
Pattern toSafePattern(String text)
{
return Pattern.compile(".*\\Q" + text + "\\E.*")
}
Have a look here, this has a proof-of-concept page and demo you can use to get anything from the drop-down: asp:DropDownList Control Tutorial Page
Asus Nexus 7 on my Windows 7 64 bits computer for development purposes :
I tried to install the driver for the nexus 7 manually like explained in the official tutorial of Asus
Unfortunately, I had an error, Windows couldn't recognize the driver.
I tried to change the USB connection mode to PTP or MTP by going in the storage menu and clicking on the top right menu . In both cases, windows recognize the devices but it still didn't work in debugging mode.
The only way it worked for me is by installing : adb universal installer . I scanned it before clicking on the executable, it seems to be fine.
Here is a great screen-cast on the topic by Ryan Bates of railscasts. At the end he simply disables the ajax functionality if the history.pushState method is not available:
I just learned this trick from a friend. Put your code inside these 2 statements and it will be commented out.
#if false
#endif
I just found my self with this Exception, I was trying to consume a JAX-WS, with a custom URL like this:
String WSDL_URL= <get value from properties file>;
Customer service = new Customer(new URL(WSDL_URL));
ExecutePtt port = service.getExecutePt();
return port.createMantainCustomers(part);
and Java threw:
XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,63]
Message: White spaces are required between publicId and systemId.
Turns out that the URL string used to construct the service was missing the "?wsdl" at the end. For instance:
Bad:
http://www.host.org/service/Customer
Good:
http://www.host.org/service/Customer?wsdl
!
I like to think of this as an explosive change that destroys all that has gone before it. Bang or exclamation mark means that you are making a permanent saved change in your code.
If you use for example Ruby's method for global substitutiongsub!
the substitution you make is permanent.
Another way you can imagine it, is opening a text file and doing find and replace, followed by saving. !
does the same in your code.
Another useful reminder if you come from the bash world is sed -i
has this similar effect of making permanent saved change.
Sorry for digging out an old thread, but I think sunetos' answer isn't correct (or isn't the full answer). I've done some experiments (using ProcessStartInfo in c#) and it seems that the 'arguments' string for a commandline command is limited to 2048 characters in XP and 32768 characters in Win7. I'm not sure what the 8191 limit refers to, but I haven't found any evidence of it yet.
Basically you shouldn't do exact comparisons, you should do something like this:
double a = 1.000001;
double b = 0.000001;
double c = a-b;
if (Math.abs(c-1.0) <= 0.000001) {...}
Using axes objects is a great approach for this. It helps if you want to interact with multiple figures and sub-plots. To add and manipulate the axes objects directly:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,9))
signal_axes = fig.add_subplot(211)
signal_axes.plot(xs,rawsignal)
fft_axes = fig.add_subplot(212)
fft_axes.set_title("FFT")
fft_axes.set_autoscaley_on(False)
fft_axes.set_ylim([0,1000])
fft = scipy.fft(rawsignal)
fft_axes.plot(abs(fft))
plt.show()
I think style no. 111 (Japan) should work:
SELECT CONVERT(DATETIME, '2012-08-17', 111)
And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD
) which works for any language and date format setting in SQL Server:
SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)
I had to include -lmysqlcppconn to my build in order to get it to work.
In the case you need to remove line breaks from the begin or end of the string, you may use this:
UPDATE table
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );
Have in mind that the hat ^
means the begin of the string and the dollar sign $
means the end of the string.
Hope it help someone.
I realized if we just ensure a trailing delimiter exists, it works. So in my case I have comma and whitespace delimiters. I add a space at the end;
$ ans="a, b"
$ ans+=" "; echo ${ans} | tr ',' ' ' | tr -s ' ' | cut -d' ' -f2
b
- Import project folders into the eclipse workspace.(when projects use different Jre).
- Update or Reinstall eclipse
- Change Jre or Build related Settings.
- Or by there is a configuration mismatch.
You get two errors for each misconfigured files.
- The project cannot be built until build path errors are resolved.
- Unbound classpath container: 'JRE System Library.
- Select each project and apply Quick fix(Ctrl+1)
- Either Replace the project's JRE with default JRE or Specify Alternate JRE (or JDK).
You can do the same by right-click project-->Properties(from context menu)-->Java Build Path-->Libraries-->select current unbound library -->Remove-->Add Libraries-->Jre System library-->select default or alternate Jre.
Or directly choose Build Path-->Add libraries in project's context menu.
EITHER
- Open the current workspace (in which your project is) in File Explorer.
- Delete all org.eclipse.jdt.core.prefs file present in .settings folder of your imported projects.(Be careful while deleting. Don't delete any files or folders inside .metadata folder.)**
- Now,Select the .classpath files of projects (those with errors) and open them in a powerful text editor(such as Notepad++).
- Find the line similar to
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
and replace it with<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- Save all the files. And Refresh or restart Eclipse IDE. All the problems are gone.
OR
Get the JRE used by the projects and install on your computer and then specify it..
Many embedded systems have a limited snprintf function that doesn't handle floats. I wrote this, and it does the trick fairly efficiently. I chose to use 64-bit unsigned integers to be able to handle large floats, so feel free to reduce them down to 16-bit or whatever needs you may have with limited resources.
#include <stdio.h> // for uint64_t support.
int snprintf_fp( char destination[], size_t available_chars, int decimal_digits,
char tail[], float source_number )
{
int chars_used = 0; // This will be returned.
if ( available_chars > 0 )
{
// Handle a negative sign.
if ( source_number < 0 )
{
// Make it positive
source_number = 0 - source_number;
destination[ 0 ] = '-';
++chars_used;
}
// Handle rounding
uint64_t zeros = 1;
for ( int i = decimal_digits; i > 0; --i )
zeros *= 10;
uint64_t source_num = (uint64_t)( ( source_number * (float)zeros ) + 0.5f );
// Determine sliding divider max position.
uint64_t div_amount = zeros; // Give it a head start
while ( ( div_amount * 10 ) <= source_num )
div_amount *= 10;
// Process the digits
while ( div_amount > 0 )
{
uint64_t whole_number = source_num / div_amount;
if ( chars_used < (int)available_chars )
{
destination[ chars_used ] = '0' + (char)whole_number;
++chars_used;
if ( ( div_amount == zeros ) && ( zeros > 1 ) )
{
destination[ chars_used ] = '.';
++chars_used;
}
}
source_num -= ( whole_number * div_amount );
div_amount /= 10;
}
// Store the zero.
destination[ chars_used ] = 0;
// See if a tail was specified.
size_t tail_len = strlen( tail );
if ( ( tail_len > 0 ) && ( tail_len + chars_used < available_chars ) )
{
for ( size_t i = 0; i <= tail_len; ++i )
destination[ chars_used + i ] = tail[ i ];
chars_used += tail_len;
}
}
return chars_used;
}
main()
{
#define TEMP_BUFFER_SIZE 30
char temp_buffer[ TEMP_BUFFER_SIZE ];
char degrees_c[] = { (char)248, 'C', 0 };
float float_temperature = 26.845f;
int len = snprintf_fp( temp_buffer, TEMP_BUFFER_SIZE, 2, degrees_c, float_temperature );
}
Update: I'm doing this with date.toISOString().substr(0, 10)
. Gives the same result as the accepted answer and has good support.
You can check the Ascii value by e.keychar on KeyPress event of TextBox.
By checking the AscII value you can check for number or character.
Similarly you can write logic to check the Email ID.
Implementing the SearchView without the use of the menu.xml
file and open through button
In your Activity
we need to use the method of the onCreateOptionsMenu
method in which we will programmatically inflate the SearchView
private MenuItem searchMenu;
private String mSearchString="";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
mSearchView.setMaxWidth(Integer.MAX_VALUE);
searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
assert searchManager != null;
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
mSearchString = newText;
return true;
}
public boolean onQueryTextSubmit(String query) {
mSearchString = query;
searchMenu.collapseActionView();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
return true;
}
And in your Activity class, you can open the SearchView
on any button click on toolbar like below
YOUR_BUTTON.setOnClickListener(view -> {
searchMenu.expandActionView();
});
Simple
var a=[{a:4}], b=[{b:5}]
angular.merge(a,b) // [{a:4, b:5}]
Tested on angular 1.4.1
Then, in your javascript:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
Now you can look at the console, click on the statement and see what is inside blah
As far as I know, a forced update like this is not directly possible. You might be able to reduce the DNS downtime by reducing the TTL (Time-To-Live) value of the entries before changing them, if your name server service provider allows that.
Here's a guide for less painful DNS changes.
A fair warning, though - not all name servers between your client and the authoritative (origin) name server will enforce your TTL, they might have their own caching time.
You can do this with a single call, like so:
scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);
In short, phpunit supresses STDOUT. It writes to STDERR by default, unless you add --verbose
or --debug
. You can do one of those things:
var_dump
your debug as usual but add --verbose
to the phpunit command linevar_dump
your debug as usual but add a line ob_flush();
beneath itObviously, the last thing is the Good Thing to do, and the rest are quick temporary hacks.
Pylint message control is documented in the Pylint manual:
Is it possible to locally disable a particular message?
Yes, this feature has been added in Pylint 0.11. This may be done by adding
# pylint: disable=some-message,another-one
at the desired block level or at the end of the desired line of code.
You can use the message code or the symbolic names.
For example,
def test():
# Disable all the no-member violations in this function
# pylint: disable=no-member
...
global VAR # pylint: disable=global-statement
The manual also has further examples.
There is a wiki that documents all Pylint messages and their codes.
I had the same problem at hands while i was attempting to load some hadoop configurations from resources packed in the jar... on both the IDE and on jar (release version).
I found java.nio.file.DirectoryStream
to work the best to iterate over directory contents over both local filesystem and jar.
String fooFolder = "/foo/folder";
....
ClassLoader classLoader = foofClass.class.getClassLoader();
try {
uri = classLoader.getResource(fooFolder).toURI();
} catch (URISyntaxException e) {
throw new FooException(e.getMessage());
} catch (NullPointerException e){
throw new FooException(e.getMessage());
}
if(uri == null){
throw new FooException("something is wrong directory or files missing");
}
/** i want to know if i am inside the jar or working on the IDE*/
if(uri.getScheme().contains("jar")){
/** jar case */
try{
URL jar = FooClass.class.getProtectionDomain().getCodeSource().getLocation();
//jar.toString() begins with file:
//i want to trim it out...
Path jarFile = Paths.get(jar.toString().substring("file:".length()));
FileSystem fs = FileSystems.newFileSystem(jarFile, null);
DirectoryStream<Path> directoryStream = Files.newDirectoryStream(fs.getPath(fooFolder));
for(Path p: directoryStream){
InputStream is = FooClass.class.getResourceAsStream(p.toString()) ;
performFooOverInputStream(is);
/** your logic here **/
}
}catch(IOException e) {
throw new FooException(e.getMessage());
}
}
else{
/** IDE case */
Path path = Paths.get(uri);
try {
DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path);
for(Path p : directoryStream){
InputStream is = new FileInputStream(p.toFile());
performFooOverInputStream(is);
}
} catch (IOException _e) {
throw new FooException(_e.getMessage());
}
}
Well, no. Why there should be? Just discard the string if you don't need it anymore.
&str
is more useful than String
when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String
, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String
, you can pass it to where an &str
is expected, but if you have &str
, you can only pass it to functions expecting String
if you make a new allocation.
You can find more on the differences between these two and when to use them in the official strings guide.
You can create an autofield. Here is the documentation for the same
Please remember Django won't allow to have more than one AutoField in a model, In your model you already have one for your primary key (which is default). So you'll have to override model's save method and will probably fetch the last inserted record from the table and accordingly increment the counter and add the new record.
Please make that code thread safe because in case of multiple requests you might end up trying to insert same value for different new records.
If you just want to disable App Transport Policy for local dev servers then the following solutions work well. It's useful when you're unable, or it's impractical, to set up HTTPS (e.g. when using the Google App Engine dev server).
As others have said though, ATP should definitely not be turned off for production apps.
Copy your Plist file and NSAllowsArbitraryLoads. Use this Plist for debugging.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Alternatively, you can use a single plist file and exclude specific servers. However, it doesn't look like you can exclude IP 4 addresses so you might need to use the server name instead (found in System Preferences -> Sharing, or configured in your local DNS).
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>server.local</key>
<dict/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
For Swift use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "ImageName.png")?.draw(in: self.view.bounds)
if let image = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
}else{
UIGraphicsEndImageContext()
debugPrint("Image not available")
}
Another solution is to user axios:
npm install axios
Code will be like:
const url = `${this.env.someMicroservice.address}/v1/my-end-point`;
const { data } = await axios.get<MyInterface>(url, {
auth: {
username: this.env.auth.user,
password: this.env.auth.pass
}
});
return data;
Here is an ubuntu+mac os x compatible version:
#!/bin/sh
#
# A git hook script to find and fix trailing whitespace
# in your commits. Bypass it with the --no-verify option
# to git-commit
#
if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | (sed -r 's/:[0-9]+:.*//' > /dev/null 2>&1 || sed -E 's/:[0-9]+:.*//') | uniq` ; do
# Fix them!
(sed -i 's/[[:space:]]*$//' "$FILE" > /dev/null 2>&1 || sed -i '' -E 's/[[:space:]]*$//' "$FILE")
git add "$FILE"
done
# Now we can commit
exit
Have fun
You can also do:
tree | grep filename
This pipes the output of the tree command to grep for a search. This will only tell you whether the file exists though.
Try this, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
String[] name = {"amit", "rahul", "surya"};
public static String arrayToString(String array[])
{
if (array.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; ++i)
{
sb.append(",'").append(array[i]).append("'");
}
return sb.substring(1);
}
add this css
body.disable-scroll {
overflow: hidden;
}
and when to disable run this code
$("body").addClass("disable-scroll");
and when to enabled run this code
$("body").removeClass("disable-scroll")
Use the Responsive Design Tool using Ctrl + Shift + M.
Try this one:
echo "$(ps -ceo pid=,comm= | awk '/firefox/ { print $1; exit }')"
The ps
command produces output like this, with the PID in the first column and the executable name (only) in the second column:
bookworm% ps -ceo pid=,comm=
1 launchd
10 kextd
11 UserEventAgent
12 mDNSResponder
13 opendirectoryd
14 notifyd
15 configd
...which awk
processes, printing the first column (pid) and exiting after the first match.
Well, speaking from quarantine, the complete()
in $.ajax is like finally
in try catch block.
If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.
Same goes for complete()
in $.ajax, whether you get success()
response or error()
the complete()
function always will be called once the execution has been done.
You can open a command prompt (Start -> Run -> cmd
, use the cd
command to change directories) and call your program from there, or add a getchar()
call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause")
, which will display a "Press enter to continue..." (or something like that) message.
Defining array with multiple types in TypeScript
Use a union type (string|number)[]
demo:
const foo: (string|number)[] = [ 1, "message" ];
I have an array of the form: [ 1, "message" ].
If you are sure that there are always only two elements [number, string]
then you can declare it as a tuple:
const foo: [number, string] = [ 1, "message" ];
You need a json serializer to parse your content, probably you already have it, for your initial question on how to make a request, this might be an idea:
var baseAddress = "http://www.example.com/1.0/service/action";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
hope it helps,
Also after React v 16.8+ you have an ability to use hooks
import React, {useState} from 'react';
const ControlledInputs = () => {
const [firstName, setFirstName] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
if (firstName) {
console.log('firstName :>> ', firstName);
}
};
return (
<>
<form onSubmit={handleSubmit}>
<label htmlFor="firstName">Name: </label>
<input
type="text"
id="firstName"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
<button type="submit">add person</button>
</form>
</>
);
};
Here's the formula used by Android:
px = dp * (dpi / 160)
Where dpi is one of the following screen densities. For a list of all possible densities go here
It defines the "DENSITY_*" constants.
Taken from here.
This will sort out a lot of the confusion when translating between px and dp, if you know your screen dpi.
So, let's say you want an image of 60 dp for an hdpi screen then the physical pixel size of 60 dp is:
px = 60 * (240 / 160)
I found that running the npm install
command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.
Specifically, I was trying to use ng2-completer
$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.
I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.
cd foo/foo_app
$ npm install ng2-completer --save
An alternative way without the [<-
function:
A sample data frame dat
(shamelessly copied from @Chase's answer):
dat
x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0
Zeroes can be replaced with NA
by the is.na<-
function:
is.na(dat) <- !dat
dat
x y
1 NA 2
2 1 2
3 1 1
4 2 1
5 NA NA
Try running this as a TSQL Script
SELECT 1
RETURN
SELECT 2
SELECT 3
The return ends the execution.
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.
Although this is the accepted answer, toto_tico's answer below is better :)
Try making the onclick js use 'return' to ensure the desired return value gets used...
<button type="button" value="click me" onclick="return check_me();" />
Here is the solution for index variable
Let's say, you have found 5 elements with same locator and you would like to perform action on each element by providing index number (here, variable is used for index as "i")
for(int i=1; i<=5; i++)
{
string xPathWithVariable = "(//div[@class='className'])" + "[" + i + "]";
driver.FindElement(By.XPath(xPathWithVariable)).Click();
}
It takes XPath :
(//div[@class='className'])[1]
(//div[@class='className'])[2]
(//div[@class='className'])[3]
(//div[@class='className'])[4]
(//div[@class='className'])[5]
I just tested this, it works sweet and doesn't require a lookup table. rand_alnum() sort of forces out alphanumerics but because it selects 62 out of a possible 256 chars it isn't a big deal.
#include <cstdlib> // for rand()
#include <cctype> // for isalnum()
#include <algorithm> // for back_inserter
#include <string>
char
rand_alnum()
{
char c;
while (!std::isalnum(c = static_cast<char>(std::rand())))
;
return c;
}
std::string
rand_alnum_str (std::string::size_type sz)
{
std::string s;
s.reserve (sz);
generate_n (std::back_inserter(s), sz, rand_alnum);
return s;
}
String.valueOf
(
Character.toChars(int)
)
Assuming the integer is, as you say, between 0 and 255, you'll get an array with a single character back from Character.toChars
, which will become a single-character string when passed to String.valueOf
.
Using Character.toChars
is preferable to methods involving a cast from int
to char
(i.e. (char) i
) for a number of reasons, including that Character.toChars
will throw an IllegalArgumentException
if you fail to properly validate the integer while the cast will swallow the error (per the narrowing primitive conversions specification), potentially giving an output other than what you intended.
Pass the decode pattern to ParseExact
Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)
ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string
There are several reasons this can happen. Some of these I found here, others I discovered on my own.
Id
, you need to add the [Key]
attribute to it.public
uint
, ulong
etc. are not allowed.It does not return an Array
, it returns a NodeList.
I just fixed this issue after struggling for a few days. Here's what worked for me:
First, check your Apache error_log
file and look at the most recent error message.
If it says something like:
access to /mySite denied (filesystem path
'/Users/myusername/Sites/mySite') because search permissions
are missing on a component of the path
then there is a problem with your file permissions. You can fix them by running these commands from the terminal:
$ cd /Users/myusername/Sites/mySite
$ find . -type f -exec chmod 644 {} \;
$ find . -type d -exec chmod 755 {} \;
Then, refresh the URL where your website should be (such as http://localhost/mySite
).
If you're still getting a 403 error, and if your Apache error_log
still says the same thing, then progressively move up your directory tree, adjusting the directory permissions as you go. You can do this from the terminal by:
$ cd ..
$ chmod 755 mySite
If necessary, continue with:
$ cd ..
$ chmod Sites
and, if necessary,
$ cd ..
$ chmod myusername
DO NOT go up farther than that. You could royally mess up your system.
If you still get the error that says search permissions are missing on a component of the path
, I don't know what you should do. However, I encountered a different error (the one below) which I fixed as follows:
If your error_log
says something like:
client denied by server configuration:
/Users/myusername/Sites/mySite
then your problem is not with your file permissions, but instead with your Apache configuration.
Notice that in your httpd.conf
file, you will see a default configuration like this (Apache 2.4+):
<Directory />
AllowOverride none
Require all denied
</Directory>
or like this (Apache 2.2):
<Directory />
Order deny,allow
Deny from all
</Directory>
DO NOT change this! We will not override these permissions globally, but instead in your httpd-vhosts.conf
file.
First, however, make sure that your vhost Include
line in httpd.conf
is uncommented. It should look like this. (Your exact path may be different.)
# Virtual hosts
Include etc/extra/httpd-vhosts.conf
Now, open the httpd-vhosts.conf
file that you just Include
d. Add an entry for your webpage if you don't already have one. It should look something like this. The DocumentRoot
and Directory
paths should be identical, and should point to wherever your index.html
or index.php
file is located. For me, that's within the public
subdirectory.
For Apache 2.2:
<VirtualHost *:80>
# ServerAdmin [email protected]
DocumentRoot "/Users/myusername/Sites/mySite/public"
ServerName mysite
# ErrorLog "logs/dummy-host2.example.com-error_log"
# CustomLog "logs/dummy-host2.example.com-access_log" common
<Directory "/Users/myusername/Sites/mySite/public">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
Require all granted
</Directory>
</VirtualHost>
The lines saying
AllowOverride All
Require all granted
are critical for Apache 2.4+. Without these, you will not be overriding the default Apache settings specified in httpd.conf
. Note that if you are using Apache 2.2, these lines should instead say
Order allow,deny
Allow from all
This change has been a major source of confusion for googlers of this problem, such as I, because copy-pasting these Apache 2.2 lines will not work in Apache 2.4+, and the Apache 2.2 lines are still commonly found on older help threads.
Once you have saved your changes, restart Apache. The command for this will depend on your OS and installation, so google that separately if you need help with it.
I hope this helps someone else!
PS: If you are having trouble finding these .conf
files, try running the find
command, such as:
$ find / -name httpd.conf
As defined in the MySQL Glossary:
In MySQL, physically, a schema is synonymous with a database. You can substitute the keyword
SCHEMA
instead ofDATABASE
in MySQL SQL syntax, for example usingCREATE SCHEMA
instead ofCREATE DATABASE
.Some other database products draw a distinction. For example, in the Oracle Database product, a schema represents only a part of a database: the tables and other objects owned by a single user.
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
As the 64bit version is an x86
architecture and was accordingly first called x86-64
, that would be the most appropriate name, IMO. Also, x32
is a thing (as mentioned before)—‘x64’, however, is not a continuation of that, so is (theoretically) missleading (even though many people will know what you are talking about) and should thus only be recognised as a marketing thing, not an ‘official’ architecture (again, IMO–obviously, others disagree).
One option would be to create a symbolic link between a subfolder in your storage directory and public directory.
For example
ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars
This is also the method used by Envoyer, a deployment manager built by Taylor Otwell, the developer of Laravel.
For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes
instead of yAxes
. Note that an array (and plural) is used for yAxes
(or xAxes
), because you may as well have multiple axes.
The correct way to apply a filter to a JTable is through the RowFilter interface added to a TableRowSorter. Using this interface, the view of a model can be changed without changing the underlying model. This strategy preserves the Model-View-Controller paradigm, whereas removing the rows you wish hidden from the model itself breaks the paradigm by confusing your separation of concerns.
While other answers are all correct, you can never know if the iPhone/iPad that is running your application has the Apple's Mail app installed or not as it can be deleted by the user.
It is better to support multiple email clients. Following code handles the email sending in a more graceful way. The flow of the code is:
mailto:..
that prompts the user to install Apple's Mail app.Code is written in Swift 5:
import MessageUI
import UIKit
class SendEmailViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBAction func sendEmail(_ sender: UIButton) {
// Modify following variables with your text / recipient
let recipientEmail = "[email protected]"
let subject = "Multi client email support"
let body = "This code supports sending email via multiple different email apps on iOS! :)"
// Show default mail composer
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([recipientEmail])
mail.setSubject(subject)
mail.setMessageBody(body, isHTML: false)
present(mail, animated: true)
// Show third party email composer if default Mail app is not present
} else if let emailUrl = createEmailUrl(to: recipientEmail, subject: subject, body: body) {
UIApplication.shared.open(emailUrl)
}
}
private func createEmailUrl(to: String, subject: String, body: String) -> URL? {
let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let gmailUrl = URL(string: "googlegmail://co?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let outlookUrl = URL(string: "ms-outlook://compose?to=\(to)&subject=\(subjectEncoded)")
let yahooMail = URL(string: "ymail://mail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")
if let gmailUrl = gmailUrl, UIApplication.shared.canOpenURL(gmailUrl) {
return gmailUrl
} else if let outlookUrl = outlookUrl, UIApplication.shared.canOpenURL(outlookUrl) {
return outlookUrl
} else if let yahooMail = yahooMail, UIApplication.shared.canOpenURL(yahooMail) {
return yahooMail
} else if let sparkUrl = sparkUrl, UIApplication.shared.canOpenURL(sparkUrl) {
return sparkUrl
}
return defaultUrl
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}
Please note that I intentionally missed out the body for the Outlook app, as it is not able to parse it.
You also have to add following code to Info.plist
file that whitelists the URl query schemes that are used.
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlegmail</string>
<string>ms-outlook</string>
<string>readdle-spark</string>
<string>ymail</string>
</array>
You may use Socket for this like
String host = "www.yourhost.com";
Socket socket = new Socket(host, 80);
String request = "GET / HTTP/1.0\r\n\r\n";
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();
InputStream is = socket.getInputStream();
int ch;
while( (ch=is.read())!= -1)
System.out.print((char)ch);
socket.close();
You can use Cloudmersive native Java library. It is free for up to 50,000 conversions/month and is much higher fidelity in my experience than other things like iText or Apache POI-based methods. The documents actually look the same as they do in Microsoft Word which for me is the key. Incidentally it can also do XLSX, PPTX, and the legacy DOC, XLS and PPT conversion to PDF.
Here is what the code looks like, first add your imports:
import com.cloudmersive.client.invoker.ApiClient;
import com.cloudmersive.client.invoker.ApiException;
import com.cloudmersive.client.invoker.Configuration;
import com.cloudmersive.client.invoker.auth.*;
import com.cloudmersive.client.ConvertDocumentApi;
Then convert a file:
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
ConvertDocumentApi apiInstance = new ConvertDocumentApi();
File inputFile = new File("/path/to/input.docx"); // File to perform the operation on.
try {
byte[] result = apiInstance.convertDocumentDocxToPdf(inputFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertDocumentApi#convertDocumentDocxToPdf");
e.printStackTrace();
}
You can get an document conversion API key for free from the portal.
The image needs to be in the same folder that your html page is in, then create a href to that folder with the picture name at the end. Example:
<img src="C:\users\home\pictures\picture.png"/>
The other answers are not wrong, but I found this to be the fastest way.
Results contain all font formats: woff, svg, ttf, eot.
AND as an added bonus they generate the css file for you too!
Execute these commands in the terminal (excluding the lines with hashtags - they're comments):
# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*
If you would like to delete all projects:
rm -Rf ~/AndroidStudioProjects
To remove gradle related files (caches & wrapper)
rm -Rf ~/.gradle
Use the below command to delete all Android Virtual Devices(AVDs) and keystores.
Note: This folder is used by other Android IDEs as well, so if you still using other IDE you may not want to delete this folder)
rm -Rf ~/.android
To delete Android SDK tools
rm -Rf ~/Library/Android*
Emulator Console Auth Token
rm -Rf ~/.emulator_console_auth_token
Thanks to those who commented/improved on this answer!
rm
are case-sensitive1 (as with most other commands), which means that the f
flag must be in lower case. However, the r
flag can also be capitalised.rm
can be either combined together or separated. They don't have to be combined.r
flag indicates that the rm
command should-
attempt to remove the file hierarchy rooted in each file argument. - DESCRIPTION section on the manpage for
rm
(Seeman rm
for more info)
f
flag indicates that the rm
command should-
attempt to remove the files without prompting for confirmation, regardless of the file's permissions. - DESCRIPTION section on the manpage for
rm
(Seeman rm
for more info)
HashSet
is O(1) to access elements, so it certainly does matter. But maintaining order of the objects in the set isn't possible.
TreeSet
is useful if maintaining an order(In terms of values and not the insertion order) matters to you. But, as you've noted, you're trading order for slower time to access an element: O(log n) for basic operations.
From the javadocs for TreeSet
:
This implementation provides guaranteed log(n) time cost for the basic operations (
add
,remove
andcontains
).
You can use enum and refer that enum in annotation field
I used this code:
ws.Range("A:A").FormulaR1C1 = "=DATEVALUE(RC[1])"
column A will be mm/dd/yyyy
RC[1] is column B, the TEXT string, eg, 01/30/12, THIS IS NOT DATE TYPE
Uninstall tensorflow and install only tensorflow-gpu; this should be sufficient. By default, this should run on the GPU and not the CPU. However, further you can do the following to specify which GPU you want it to run on.
If you have an nvidia GPU, find out your GPU id using the command nvidia-smi
on the terminal. After that, add these lines in your script:
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = #GPU_ID from earlier
config = tf.ConfigProto()
sess = tf.Session(config=config)
For the functions where you wish to use GPUs, write something like the following:
with tf.device(tf.DeviceSpec(device_type="GPU", device_index=gpu_id)):
This work for me...
@Html.TextBoxFor(model => model.RIF, new { value = @Model.RIF, @readonly = "readonly" })
[[ ]]
has more features - I suggest you take a look at the Advanced Bash Scripting Guide for more info, specifically the extended test command section in Chapter 7. Tests.
Incidentally, as the guide notes, [[ ]]
was introduced in ksh88 (the 1988 version of the Korn shell).
According to :https://anaconda.org/intel/tensorflow
To install this package with conda run:
conda install -c intel tensorflow
pip install To install this package with pip:
pip install -i https://pypi.anaconda.org/intel/simple tensorflow
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
If you have more then one UITextField
s and you need to do something when (or before) keyboard appears or disappears, you can implement this approach.
Add UITextFieldDelegate
to your class. Assign integer counter, let's say:
NSInteger editCounter;
Set this counter to zero somewhere in viewDidLoad
.
Then, implement textFieldShouldBeginEditing
and textFieldShouldEndEditing
delegate methods.
In the first one add 1 to editCounter. If value of editCounter becomes 1 - this means that keyboard will appear (in case if you return YES). If editCounter > 1 - this means that keyboard is already visible and another UITextField holds the focus.
In textFieldShouldEndEditing
subtract 1 from editCounter. If you get zero - keyboard will be dismissed, otherwise it will remain on the screen.
With jQuery UI just do this!
$( "#draggable" ).draggable({
start: function() {
},
drag: function() {
},
stop: function() {
}
});
I just got my beta invitation today and tried Atom right away. The GUI feels like Sublime, and yes, there some shortcuts adopted from Sublime.
Besides everything mentioned above, here are some differences I have noticed so far:
Vim mode is not as good as the Vintage mode on Sublime (which is not a fully featured vim either) because the vim package is in an early stage of development. See https://atom.io/packages/vim-mode for detail.
As James mention, Atom is written using web tools, so you have access to the stylesheet of the text editor (styles.less) to do whatever appearance changes you want using CSS. There is also an option to change the startup CoffeeScript.
Again, because Atom is still in the beta stage, Sublime has much more native plugin packages. However, since Atom is written in Node.js, the Atom official site said you can "choose from over 50 thousand in Node's package repository." (Because I am not a Node.js pro, I haven't look into this feature though)
Atom has better Github support out of the box, but Sublime has a several Git packages.
Sublime is a paid application unlimited evaluation period. Atom is free at the beta stage but we don't know whether Github wants to charge it or not.
So the bottom line is Atom is a text editor built with web technology at beta stage. By contrast, Sublime has evolved through many different iterations. Atom is still missing a lot of packages that Sublime supports, so the question is will Atom catch up with Sublime or become some better? Github seems to be confident about the future of this text edit because of its popular underlying technologies, and Atom is probably going to be a good alternative to Sublime in the long run.
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
For me, what worked was:
BeautifulSoup(html_text,from_encoding="utf-8")
Hope this helps someone.
//Try this if you can't use -std=c++11:-
int number=55;
char tempStr[32] = {0};
sprintf(tempStr, "%d", number);
Now you can change the primary dns (index=1), assuming that your interface is static (not using dhcp)
You can set your DNS servers statically even if you use DHCP to obtain your IP address.
Example under Windows 7 to add two DN servers, the command is as follows:
netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=1
netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=2
Resolved.
This problem could be solved by the below mentioned 4 steps
1) Remove .lock file
sudo rm /var/lib/mongodb/mongod.lock
2) repair the mongodb
mongod -–repair
3) start the mongod server
sudo service mongod start
4) start the mongo client
mongo
For more details take a look at http://shakthydoss.com/error-couldnt-connect-to-server-127-0-0-127017-srcmongoshellmongo-js-exception-connect-failed/
Is this what you're looking for?
SELECT * FROM NOTES ORDER BY UPPER(title)
You can create a new table using the following code.
SELECT IDENTITY (int, 1, 1) AS id, column1, column2
INTO dbo.NewTable
FROM dbo.OldTable
Then delete the old db, and rename the new db to the old db's name. Note: that column1 and column2 represent all the columns in your old table that you want to keep in your new table.
Should it be LIBRARY_PATH
instead of LD_LIBRARY_PATH
.
gcc checks for LIBRARY_PATH
which can be seen with -v
option
The accepted answer helped me but I got tripped up while doing concatenation of varchars involving case statements. I know the OP's question does not involve case statements but I thought this would be helpful to post here for others like me who ended up here while struggling to build long dynamic SQL statements involving case statements.
When using case statements with string concatenation the rules mentioned in the accepted answer apply to each section of the case statement independently.
declare @l_sql varchar(max) = ''
set @l_sql = @l_sql +
case when 1=1 then
--without this correction the result is truncated
--CONVERT(VARCHAR(MAX), '')
+REPLICATE('1', 8000)
+REPLICATE('1', 8000)
end
print len(@l_sql)
hostName == null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
{
while (interfaces.hasMoreElements()) {
NetworkInterface nic = interfaces.nextElement();
Enumeration<InetAddress> addresses = nic.getInetAddresses();
while (hostName == null && addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLoopbackAddress()) {
hostName = address.getHostName();
}
}
}
}
You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?
this.Controls.Add(dataGridView1);
By the way the code is a bit confused
String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql = "SELECT Clients FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
conn.Open();
DataSet ds = new DataSet();
DataGridView dataGridView1 = new DataGridView();
using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
// Of course, before addint the datagrid to the hosting form you need to
// set position, location and other useful properties.
// Why don't you create the DataGrid with the designer and use that instance instead?
this.Controls.Add(dataGridView1);
}
}
EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as
SELECT field_names_list FROM _tablename_
so the correct syntax to use for retrieving all the clients data is
string sql = "SELECT * FROM Clients";
where the *
means -> all the fields present in the table
login into container with the following command:
docker exec -it <container> bash
Then , run the following command .
apt-get update
apt-get install vim
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
You should probably use NOT EXISTS
for multiple columns.
It's part of the ES6 module system, described here. There is a helpful example in that documentation, also:
If a module defines a default export:
export default function() { console.log("hello!") }
then you can import that default export by omitting the curly braces:
import foo from "foo"; foo(); // hello!
Update: As of June 2015, the module system is defined in §15.2 and the export
syntax in particular is defined in §15.2.3 of the ECMAScript 2015 specification.
I've fixed that problem by creating test rails project and install all gems then I've replaced my current Gemfile.lock with the test and all thing works fine.
I think that this problem from bundler
versions with hosting, so please make sure that hosting bundler is the same version with your project.
I bumped into this page "Download #VisualStudio 2015 (ISO + Web Installer)" (http://www.kunal-chowdhury.com/2015/07/download-visualstudio-2015.html) and the ISO link (https://go.microsoft.com/fwlink/?LinkId=615448&clcid=0x409) provided in this page seems to be valid.
I am downloading the ISO at this very moment.
Edit:
Was able to download the ISO and burned into a DVD. Also tried installing (only C/C++) on a 64-bit Windows 10 laptop and everything seems to work except that the installer couldn't find and had to go to Internet to download packages\vcRedistD12\1033\vcredist_x64.exe (although this file does exist in DVD and runnable).
You're right, no API at all that I'm aware to export PrivateKey marked as non-exportable. But if you patch (in memory) normal APIs, you can use the normal way to export :)
There is a new version of mimikatz that also support CNG Export (Windows Vista / 7 / 2008 ...)
Run it and enter the following commands in its prompt:
privilege::debug
(unless you already have it or target only CryptoApi)crypto::patchcng
(nt 6) and/or crypto::patchcapi
(nt 5 & 6)crypto::exportCertificates
and/or crypto::exportCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE
The exported .pfx files are password protected with the password "mimikatz"
Simple Steps:
-Open Eclipse.
Try this:
select nextval('my_seq_name'); // Returns next value
If this return 1 (or whatever is the start_value for your sequence), then reset the sequence back to the original value, passing the false flag:
select setval('my_seq_name', 1, false);
Otherwise,
select setval('my_seq_name', nextValue - 1, true);
This will restore the sequence value to the original state and "setval" will return with the sequence value you are looking for.
Line by line
int [] v = Stream.of(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
While working with AsyncTask, it is necessary to create a class-successor and in it to register the implementation of methods necessary for us. In this lesson we will look at three methods:
doInBackground - will be executed in a new thread, and here we solve all our difficult tasks. Because a non-primary thread does not have access to the UI.
onPreExecute - executed before doInBackground and has access to the UI
onPostExecute - executed after doInBackground (does not work if AsyncTask was canceled - about this in the next lessons) and has access to the UI.
This is the MyAsyncTask class:
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Start");
}
@Override
protected Void doInBackground(Void... params) {
// Your background method
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
tvInfo.setText("Finish");
}
}
And this is how to call in your Activity or Fragment:
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
There is also subset
which might be useful sometimes:
a <- sample(1:10)
bad <- c(2, 3, 5)
> subset(a, !(a %in% bad))
[1] 9 7 10 6 8 1 4
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
is just going to look for a div with class="outer inner", is that correct?
No, '.outer .inner'
will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner'
(no space) would give the results you're thinking of.
'.outer > .inner'
will look for immediate children of an element with the .outer class for elements with the .inner class.
Both '.outer .inner'
and '.outer > .inner'
should work for your example, although the selectors are fundamentally different and you should be wary of this.
To just get everything done goto Window>Preferences>General and goto theme menu and change it... Then re-start to apply...
If you don't mind using twitter bootstrap I suggest you simply use the link class.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">_x000D_
<button type="button" class="btn btn-link">Link</button>
_x000D_
I hope this helps somebody :) Have a nice day!
What you are doing, you are executing test1
$(test1)
in a sub-shell( child shell ) and Child shells cannot modify anything in parent.
You can find it in bash manual
Please Check: Things results in a subshell here
f=0
sum=0
for i in range(1,101):
for j in range(1,i+1):
if(i%j==0):
f=f+1
if(f==2):
sum=sum+i
print i
f=0
print sum
response.statusCode
is a number, e.g. response.statusCode === 200
, not '200'
. As the error message says, write
expects a string
or Buffer
object, so you must convert it.
res.write(response.statusCode.toString());
You are also correct about your callback comment though. res.end();
should be inside the callback, just below your write
calls.
int i;
int j;
int * const ptr1 = &i;
The compiler will stop you changing ptr1
.
const int * ptr2 = &i;
The compiler will stop you changing *ptr2
.
ptr1 = &j; // error
*ptr1 = 7; // ok
ptr2 = &j; // ok
*ptr2 = 7; // error
Note that you can still change *ptr2
, just not by literally typing *ptr2
:
i = 4;
printf("before: %d\n", *ptr2); // prints 4
i = 5;
printf("after: %d\n", *ptr2); // prints 5
*ptr2 = 6; // still an error
You can also have a pointer with both features:
const int * const ptr3 = &i;
ptr3 = &j; // error
*ptr3 = 7; // error
Want to center an image? Very easy, Bootstrap comes with two classes, .center-block
and text-center
.
Use the former in the case of your image being a BLOCK
element, for example, adding img-responsive
class to your img
makes the img
a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.
Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.
// In case you're dealing with a block element apply this to the element itself
.center-block {
margin-left:auto;
margin-right:auto;
display:block;
}
// In case you're dealing with a inline element apply this to the parent
.text-center {
text-align:center
}
This site had a simple solution that worked with my Django 1.7 configuration.
FIRST: Make a symlink named admin_src in your project's template/ directory to your installed Django templates. For me on Dreamhost using a virtualenv, my "source" Django admin templates were in:
~/virtualenvs/mydomain/lib/python2.7/site-packages/django/contrib/admin/templates/admin
SECOND: Create an admin directory in templates/
So my project's template/ directory now looked like this:
/templates/
admin
admin_src -> [to django source]
base.html
index.html
sitemap.xml
etc...
THIRD: In your new template/admin/ directory create a base.html file with this content:
{% extends "admin_src/base.html" %}
{% block extrahead %}
<link rel='shortcut icon' href='{{ STATIC_URL }}img/favicon-admin.ico' />
{% endblock %}
FOURTH: Add your admin favicon-admin.ico into your static root img folder.
Done. Easy.
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
Add .hide-text class to your span that has the text
.hide-text{
display:none;
}
or make the text transparent
.hide-text{
color:rgba(0,0,0,0);
}
use according to your use case.
It was very useful for me i have used in the following way to add user in active directory:
:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "
cls
:while1
if %x% leq %lent% (
dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
echo User %Uname%%x% with DC %DcName% is created
set /a "x = x + 1"
goto :while1
)
endlocal
You say that you already tried onStatusChanged(), but that does work for me.
Here's the method I use (I let the class itself handle the onStatusChanged):
private void startLocationTracking() {
final int updateTime = 2000; // ms
final int updateDistance = 10; // meter
final Criteria criteria = new Criteria();
criteria.setCostAllowed(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
final String p = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(p, updateTime, updateDistance,
this);
}
And I handle the onStatusChanged as follows:
void onStatusChanged(final String provider, final int status,
final Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
if (location == null || location.getProvider().equals(provider)) {
statusString = "No Service";
location = null;
}
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
if (location == null || location.getProvider().equals(provider)) {
statusString = "no fix";
}
break;
case LocationProvider.AVAILABLE:
statusString = "fix";
break;
}
}
Note that the onProvider{Dis,En}abled() methods are about enabling and disabling GPS tracking by the user; not what you're looking for.
From here and here: (after i googled your title)
- Alternate key - An alternate key is any candidate key which is not selected to be the primary key
- Candidate key - A candidate key is a field or combination of fields that can act as a primary key field for that table to uniquely identify each record in that table.
- Compound key - compound key (also called a composite key or concatenated key) is a key that consists of 2 or more attributes.
- Primary key - a primary key is a value that can be used to identify a unique row in a table. Attributes are associated with it. Examples of primary keys are Social Security numbers (associated to a specific person) or ISBNs (associated to a specific book). In the relational model of data, a primary key is a candidate key chosen as the main method of uniquely identifying a tuple in a relation.
- Superkey - A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a superkey can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.
- Foreign key - a foreign key (FK) is a field or group of fields in a database record that points to a key field or group of fields forming a key of another database record in some (usually different) table. Usually a foreign key in one table refers to the primary key (PK) of another table. This way references can be made to link information together and it is an essential part of database normalization
Nothing special. Just as same as common Java Class Instance.
But those class are Synthetic proxy classes
created by java.lang.reflect.Proxy#newProxyInstance
Introduced in 1.3
http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection
It is a part of Java. so each JVM should support it.
In short : they are created using JVM ASM tech ( defining javabyte code at runtime )
something using same tech:
java.lang.reflect.Proxy#newProxyInstance
getProxyClass0
to obtain a `Class
`
ProxyGenerator.generateProxyClass
which return a byte[]define class
to load the generated $Proxy
Class (the classname you have seen)each method is build with same bytecode like
invocation handler
's invoke()
invocation handler
's invoke()
the class(bytecode) represent in form of byte[]
How to draw a class
Thinking your java codes are compiled into bytecodes, just do this at runtime
core method in sun/misc/ProxyGenerator.java
generateClassFile
/**
* Generate a class file for the proxy class. This method drives the
* class file generation process.
*/
private byte[] generateClassFile() {
/* ============================================================
* Step 1: Assemble ProxyMethod objects for all methods to
* generate proxy dispatching code for.
*/
/*
* Record that proxy methods are needed for the hashCode, equals,
* and toString methods of java.lang.Object. This is done before
* the methods from the proxy interfaces so that the methods from
* java.lang.Object take precedence over duplicate methods in the
* proxy interfaces.
*/
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
/*
* Now record all of the methods from the proxy interfaces, giving
* earlier interfaces precedence over later ones with duplicate
* methods.
*/
for (int i = 0; i < interfaces.length; i++) {
Method[] methods = interfaces[i].getMethods();
for (int j = 0; j < methods.length; j++) {
addProxyMethod(methods[j], interfaces[i]);
}
}
/*
* For each set of proxy methods with the same signature,
* verify that the methods' return types are compatible.
*/
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/* ============================================================
* Step 2: Assemble FieldInfo and MethodInfo structs for all of
* fields and methods in the class we are generating.
*/
try {
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName,
"Ljava/lang/reflect/Method;",
ACC_PRIVATE | ACC_STATIC));
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
methods.add(generateStaticInitializer());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception");
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/* ============================================================
* Step 3: Write the final class file.
*/
/*
* Make sure that constant pool indexes are reserved for the
* following items before starting to write the final class file.
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (int i = 0; i < interfaces.length; i++) {
cp.getClass(dotToSlash(interfaces[i].getName()));
}
/*
* Disallow new constant pool additions beyond this point, since
* we are about to write the final constant pool table.
*/
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
/*
* Write all the items of the "ClassFile" structure.
* See JVMS section 4.1.
*/
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 minor_version;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 major_version;
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 access_flags;
dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
// u2 this_class;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 super_class;
dout.writeShort(cp.getClass(superclassName));
// u2 interfaces_count;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (int i = 0; i < interfaces.length; i++) {
dout.writeShort(cp.getClass(
dotToSlash(interfaces[i].getName())));
}
// u2 fields_count;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 methods_count;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 attributes_count;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception");
}
return bout.toByteArray();
}
addProxyMethod
/**
* Add another method to be proxied, either by creating a new
* ProxyMethod object or augmenting an old one for a duplicate
* method.
*
* "fromClass" indicates the proxy interface that the method was
* found through, which may be different from (a subinterface of)
* the method's "declaring class". Note that the first Method
* object passed for a given name and descriptor identifies the
* Method object (and thus the declaring class) that will be
* passed to the invocation handler's "invoke" method for a given
* set of duplicate methods.
*/
private void addProxyMethod(Method m, Class fromClass) {
String name = m.getName();
Class[] parameterTypes = m.getParameterTypes();
Class returnType = m.getReturnType();
Class[] exceptionTypes = m.getExceptionTypes();
String sig = name + getParameterDescriptors(parameterTypes);
List<ProxyMethod> sigmethods = proxyMethods.get(sig);
if (sigmethods != null) {
for (ProxyMethod pm : sigmethods) {
if (returnType == pm.returnType) {
/*
* Found a match: reduce exception types to the
* greatest set of exceptions that can thrown
* compatibly with the throws clauses of both
* overridden methods.
*/
List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
collectCompatibleTypes(
exceptionTypes, pm.exceptionTypes, legalExceptions);
collectCompatibleTypes(
pm.exceptionTypes, exceptionTypes, legalExceptions);
pm.exceptionTypes = new Class[legalExceptions.size()];
pm.exceptionTypes =
legalExceptions.toArray(pm.exceptionTypes);
return;
}
}
} else {
sigmethods = new ArrayList<ProxyMethod>(3);
proxyMethods.put(sig, sigmethods);
}
sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
exceptionTypes, fromClass));
}
Full code about gen the proxy method
private MethodInfo generateMethod() throws IOException {
String desc = getMethodDescriptor(parameterTypes, returnType);
MethodInfo minfo = new MethodInfo(methodName, desc,
ACC_PUBLIC | ACC_FINAL);
int[] parameterSlot = new int[parameterTypes.length];
int nextSlot = 1;
for (int i = 0; i < parameterSlot.length; i++) {
parameterSlot[i] = nextSlot;
nextSlot += getWordsPerType(parameterTypes[i]);
}
int localSlot0 = nextSlot;
short pc, tryBegin = 0, tryEnd;
DataOutputStream out = new DataOutputStream(minfo.code);
code_aload(0, out);
out.writeByte(opc_getfield);
out.writeShort(cp.getFieldRef(
superclassName,
handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));
code_aload(0, out);
out.writeByte(opc_getstatic);
out.writeShort(cp.getFieldRef(
dotToSlash(className),
methodFieldName, "Ljava/lang/reflect/Method;"));
if (parameterTypes.length > 0) {
code_ipush(parameterTypes.length, out);
out.writeByte(opc_anewarray);
out.writeShort(cp.getClass("java/lang/Object"));
for (int i = 0; i < parameterTypes.length; i++) {
out.writeByte(opc_dup);
code_ipush(i, out);
codeWrapArgument(parameterTypes[i], parameterSlot[i], out);
out.writeByte(opc_aastore);
}
} else {
out.writeByte(opc_aconst_null);
}
out.writeByte(opc_invokeinterface);
out.writeShort(cp.getInterfaceMethodRef(
"java/lang/reflect/InvocationHandler",
"invoke",
"(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
"[Ljava/lang/Object;)Ljava/lang/Object;"));
out.writeByte(4);
out.writeByte(0);
if (returnType == void.class) {
out.writeByte(opc_pop);
out.writeByte(opc_return);
} else {
codeUnwrapReturnValue(returnType, out);
}
tryEnd = pc = (short) minfo.code.size();
List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
if (catchList.size() > 0) {
for (Class<?> ex : catchList) {
minfo.exceptionTable.add(new ExceptionTableEntry(
tryBegin, tryEnd, pc,
cp.getClass(dotToSlash(ex.getName()))));
}
out.writeByte(opc_athrow);
pc = (short) minfo.code.size();
minfo.exceptionTable.add(new ExceptionTableEntry(
tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));
code_astore(localSlot0, out);
out.writeByte(opc_new);
out.writeShort(cp.getClass(
"java/lang/reflect/UndeclaredThrowableException"));
out.writeByte(opc_dup);
code_aload(localSlot0, out);
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef(
"java/lang/reflect/UndeclaredThrowableException",
"<init>", "(Ljava/lang/Throwable;)V"));
out.writeByte(opc_athrow);
}
You can have as many branches you want, just as a regular git repository, but according to heroku docs, any branch other than master
will be ignored.
http://devcenter.heroku.com/articles/git
Branches pushed to Heroku other than master will be ignored. If you’re working out of another branch locally, you can either merge to master before pushing, or specify that you want to push your local branch to a remote master.
This means that you can push anything you want, but you app at heroku will always point to the master branch.
But, if you question regards how to create branches and to work with git you should check this other question
I made a program that cleared and refilled my listview multiple times. For some reason whenever I added columns with width = -2 I encountered a problem with the first column being way too long. What I did to fix this was create this method.
private void ResizeListViewColumns(ListView lv)
{
foreach(ColumnHeader column in lv.Columns)
{
column.Width = -2;
}
}
The great thing about this method is that you can pretty much put this anywhere to resize all your columns. Just pass in your ListView
.
Optimized (but less readable) implementation:
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Have you checked Arrays.asList()
; see API
The money-back guaranteed, reinforced-concrete-solid way to force a view to draw synchronously (before returning to the calling code) is to configure the CALayer
's interactions with your UIView
subclass.
In your UIView subclass, create a displayNow()
method that tells the layer to “set course for display” then to “make it so”:
Swift
/// Redraws the view's contents immediately.
/// Serves the same purpose as the display method in GLKView.
public func displayNow()
{
let layer = self.layer
layer.setNeedsDisplay()
layer.displayIfNeeded()
}
Objective-C
/// Redraws the view's contents immediately.
/// Serves the same purpose as the display method in GLKView.
- (void)displayNow
{
CALayer *layer = self.layer;
[layer setNeedsDisplay];
[layer displayIfNeeded];
}
Also implement a draw(_: CALayer, in: CGContext)
method that'll call your private/internal drawing method (which works since every UIView
is a CALayerDelegate
):
Swift
/// Called by our CALayer when it wants us to draw
/// (in compliance with the CALayerDelegate protocol).
override func draw(_ layer: CALayer, in context: CGContext)
{
UIGraphicsPushContext(context)
internalDraw(self.bounds)
UIGraphicsPopContext()
}
Objective-C
/// Called by our CALayer when it wants us to draw
/// (in compliance with the CALayerDelegate protocol).
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
UIGraphicsPushContext(context);
[self internalDrawWithRect:self.bounds];
UIGraphicsPopContext();
}
And create your custom internalDraw(_: CGRect)
method, along with fail-safe draw(_: CGRect)
:
Swift
/// Internal drawing method; naming's up to you.
func internalDraw(_ rect: CGRect)
{
// @FILLIN: Custom drawing code goes here.
// (Use `UIGraphicsGetCurrentContext()` where necessary.)
}
/// For compatibility, if something besides our display method asks for draw.
override func draw(_ rect: CGRect) {
internalDraw(rect)
}
Objective-C
/// Internal drawing method; naming's up to you.
- (void)internalDrawWithRect:(CGRect)rect
{
// @FILLIN: Custom drawing code goes here.
// (Use `UIGraphicsGetCurrentContext()` where necessary.)
}
/// For compatibility, if something besides our display method asks for draw.
- (void)drawRect:(CGRect)rect {
[self internalDrawWithRect:rect];
}
And now just call myView.displayNow()
whenever you really-really need it to draw (such as from a CADisplayLink
callback). Our displayNow()
method will tell the CALayer
to displayIfNeeded()
, which will synchronously call back into our draw(_:,in:)
and do the drawing in internalDraw(_:)
, updating the visual with what's drawn into the context before moving on.
This approach is similar to @RobNapier's above, but has the advantage of calling displayIfNeeded()
in addition to setNeedsDisplay()
, which makes it synchronous.
This is possible because CALayer
s expose more drawing functionality than UIView
s do— layers are lower-level than views and designed explicitly for the purpose of highly-configurable drawing within the layout, and (like many things in Cocoa) are designed to be used flexibly (as a parent class, or as a delegator, or as a bridge to other drawing systems, or just on their own). Proper usage of the CALayerDelegate
protocol makes all this possible.
More information about the configurability of CALayer
s can be found in the Setting Up Layer Objects section of the Core Animation Programming Guide.
Personally I think it's not good, that your function "hides" invalid values as false
and - depending on your use cases - doesn't return true
for "1"
.
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0"
and "1"
.
(Maybe there is a way to compare only once against "true"
, but I couldn't think of something right now.)
What I did to solve the problem was:
git pull origin [branch]
git push origin [branch]
Also make sure that you are pointing to the right branch by running:
git remote set-url origin [url]
I am not an expert, but I got this debug message when I wanted to send data from my android application to a web server. Though I used AsyncTask class and did the data transfer in background, for getting the result data back from server I used get() method of the AsyncTask class which makes the UI synchronous which means that your UI will be waiting for too long. So my advice is to make your app do every network oriented tasks on a separate thread.
If you like 'Mike Sherrill' solution but don't want to use psql, I used this query to get the missing information:
select column_name,
case
when domain_name is not null then domain_name
when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
else data_type
end as myType
from information_schema.columns
where table_name='test'
with result:
column_name | myType
-------------+-------------------
test_id | test_domain
test_vc | varchar(15)
test_n | numeric(15,3)
big_n | bigint
ip_addr | inet
This works for me under Excel and a big JSON files using JSON query translated in to native form. https://github.com/VBA-tools/VBA-JSON I am able parse node like "item.something" and get value using simple command:
MsgBox Json("item")("something")
What's nice.
The short answer is:
int nBits = ceil(log2(N));
That's simply because pow(2, nBits) is slightly bigger than N.
To avoid memory leaks you may use smart pointers whenever you can. There are basically 2 different types of smart pointers in C++
The main difference is that reference counted smart pointers can be copied (and used in std:: containers) while scoped_ptr cannot. Non reference counted pointers have almost no overhead or no overhead at all. Reference counting always introduces some kind of overhead.
(I suggest to avoid auto_ptr, it has some serious flaws if used incorrectly)
Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.
String string="";
for (int i = 0; i<array.length; i++){
for (int j = 0; j<array[i].length; j++){
string = string.concat(array[j][i]);
}
}
System.out.println(string)
I would recommend the approach mentioned by Stefan (i.e. follow the guidelines in Improved Persistent Login Cookie Best Practice) and also recommend that you make sure your cookies are HttpOnly cookies so they are not accessible to, potentially malicious, JavaScript.