If we are talking about class types - not primitives, the following trick has to be done:
Integer someInt;
Character someChar;
someChar = (char)Integer.parseInt(String.valueOf(someInt));
You can get the output of that command and put it in a variable. then use heredoc
. for example:
nc -l -p 80 <<< "tested like a charm";
can be written like:
nc -l -p 80 <<EOF
tested like a charm
EOF
and like this (this is what you want):
text="tested like a charm"
nc -l -p 80 <<EOF
$text
EOF
Practical example in busybox
under docker
container:
kasra@ubuntu:~$ docker run --rm -it busybox
/ # nc -l -p 80 <<< "tested like a charm";
sh: syntax error: unexpected redirection
/ # nc -l -p 80 <<EOL
> tested like a charm
> EOL
^Cpunt! => socket listening, no errors. ^Cpunt! is result of CTRL+C signal.
/ # text="tested like a charm"
/ # nc -l -p 80 <<EOF
> $text
> EOF
^Cpunt!
Deleting the .git
folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:
Checkout
git checkout --orphan latest_branch
Add all the files
git add -A
Commit the changes
git commit -am "commit message"
Delete the branch
git branch -D master
Rename the current branch to master
git branch -m master
Finally, force update your repository
git push -f origin master
PS: this will not keep your old commit history around
IntelliJ IDEA seems to have reorganized the configurations panel. Now one should go to Editor -> Color Scheme and click on the gears icon to import the theme they want from external .jar
files.
Here is a solution to make an accessible audio player with valid xHTML and non-intrusive javascript thanks to W3C Web Audio API :
What to do :
First of all, we check if the browser implements Web Audio API:
if (typeof Audio === 'undefined') {
// abort
}
Then we instanciate an Audio
object:
var player = new Audio('mysong.ogg');
Then we can check if the browser is able to decode this type of file :
if(!player.canPlayType('audio/ogg')) {
// abort
}
Or even if it can play the codec :
if(!player.canPlayType('audio/ogg; codecs="vorbis"')) {
// abort
}
Then we can use player.play()
, player.pause()
;
I have done a tiny JQuery plugin that I called nanodio to test this.
You can check how it works on my demo page (sorry, but text is in french :p )
Just click on a link to play, and click again to pause. If the browser can read it natively, it will. If it can't, it should download the file.
This is just a little example, but you can improve it to use any element of your page as a control button or generate ones on the fly with javascript... Whatever you want.
In the header file write it with extern
.
And at the global scope of one of the c files declare it without extern
.
Try this:
hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)
If you don't like the 0x
in the beginning, replace the last line with
print hex(new_int)[2:]
__FUNCTION__
is non standard, __func__
exists in C99 / C++11. The others (__LINE__
and __FILE__
) are just fine.
It will always report the right file and line (and function if you choose to use __FUNCTION__
/__func__
). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performance in any way.
Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).
I resolved this issue in my linux enviroment updating the IP of my machine in /etc/hosts file.
You can verify your network IP (inet end.) with:
$ifconfig
See if your IP matches with /etc/hosts file:
$cat /etc/hosts
Edit your /etc/hosts file, if nedded:
$sudo gedit /etc/hosts
Bye.
I use this class to handle database.I hope it will help some one in future.
Happy coding.
public class Database {
private static class DBHelper extends SQLiteOpenHelper {
/**
* Database name
*/
private static final String DB_NAME = "db_name";
/**
* Table Names
*/
public static final String TABLE_CART = "DB_CART";
/**
* Cart Table Columns
*/
public static final String CART_ID_PK = "_id";// Primary key
public static final String CART_DISH_NAME = "dish_name";
public static final String CART_DISH_ID = "menu_item_id";
public static final String CART_DISH_QTY = "dish_qty";
public static final String CART_DISH_PRICE = "dish_price";
/**
* String to create reservation tabs table
*/
private final String CREATE_TABLE_CART = "CREATE TABLE IF NOT EXISTS "
+ TABLE_CART + " ( "
+ CART_ID_PK + " INTEGER PRIMARY KEY, "
+ CART_DISH_NAME + " TEXT , "
+ CART_DISH_ID + " TEXT , "
+ CART_DISH_QTY + " TEXT , "
+ CART_DISH_PRICE + " TEXT);";
public DBHelper(Context context) {
super(context, DB_NAME, null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_CART);
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CART);
onCreate(db);
}
}
/**
* CART handler
*/
public static class Cart {
/**
* Check if Cart is available or not
*
* @param context
* @return
*/
public static boolean isCartAvailable(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
boolean exists = false;
try {
String query = "SELECT * FROM " + DBHelper.TABLE_CART;
Cursor cursor = db.rawQuery(query, null);
exists = (cursor.getCount() > 0);
cursor.close();
db.close();
} catch (SQLiteException e) {
db.close();
}
return exists;
}
/**
* Insert values in cart table
*
* @param context
* @param dishName
* @param dishPrice
* @param dishQty
* @return
*/
public static boolean insertItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.CART_DISH_ID, "" + itemId);
values.put(DBHelper.CART_DISH_NAME, "" + dishName);
values.put(DBHelper.CART_DISH_PRICE, "" + dishPrice);
values.put(DBHelper.CART_DISH_QTY, "" + dishQty);
try {
db.insert(DBHelper.TABLE_CART, null, values);
db.close();
return true;
} catch (SQLiteException e) {
db.close();
return false;
}
}
/**
* Check for specific record by name
*
* @param context
* @param dishName
* @return
*/
public static boolean isItemAvailable(Context context, String dishName) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
boolean exists = false;
String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE "
+ DBHelper.CART_DISH_NAME + " = '" + String.valueOf(dishName) + "'";
try {
Cursor cursor = db.rawQuery(query, null);
exists = (cursor.getCount() > 0);
cursor.close();
} catch (SQLiteException e) {
e.printStackTrace();
db.close();
}
return exists;
}
/**
* Update cart item by item name
*
* @param context
* @param dishName
* @param dishPrice
* @param dishQty
* @return
*/
public static boolean updateItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.CART_DISH_ID, itemId);
values.put(DBHelper.CART_DISH_NAME, dishName);
values.put(DBHelper.CART_DISH_PRICE, dishPrice);
values.put(DBHelper.CART_DISH_QTY, dishQty);
try {
String[] args = new String[]{dishName};
db.update(DBHelper.TABLE_CART, values, DBHelper.CART_DISH_NAME + "=?", args);
db.close();
return true;
} catch (SQLiteException e) {
db.close();
return false;
}
}
/**
* Get cart list
*
* @param context
* @return
*/
public static ArrayList<CartModel> getCartList(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
ArrayList<CartModel> cartList = new ArrayList<>();
try {
String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";
Cursor cursor = db.rawQuery(query, null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
cartList.add(new CartModel(
cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_ID)),
cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_NAME)),
cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)),
Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE)))
));
}
db.close();
} catch (SQLiteException e) {
db.close();
}
return cartList;
}
/**
* Get total amount of cart items
*
* @param context
* @return
*/
public static String getTotalAmount(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
double totalAmount = 0.0;
try {
String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";
Cursor cursor = db.rawQuery(query, null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
totalAmount = totalAmount + Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE))) *
Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)));
}
db.close();
} catch (SQLiteException e) {
db.close();
}
if (totalAmount == 0.0)
return "";
else
return "" + totalAmount;
}
/**
* Get item quantity
*
* @param context
* @param dishName
* @return
*/
public static String getItemQty(Context context, String dishName) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = null;
String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE " + DBHelper.CART_DISH_NAME + " = '" + dishName + "';";
String quantity = "0";
try {
cursor = db.rawQuery(query, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
quantity = cursor.getString(cursor
.getColumnIndex(DBHelper.CART_DISH_QTY));
return quantity;
}
} catch (SQLiteException e) {
e.printStackTrace();
}
return quantity;
}
/**
* Delete cart item by name
*
* @param context
* @param dishName
*/
public static void deleteCartItem(Context context, String dishName) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
try {
String[] args = new String[]{dishName};
db.delete(DBHelper.TABLE_CART, DBHelper.CART_DISH_NAME + "=?", args);
db.close();
} catch (SQLiteException e) {
db.close();
e.printStackTrace();
}
}
}//End of cart class
/**
* Delete database table
*
* @param context
*/
public static void deleteCart(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
try {
db.execSQL("DELETE FROM " + DBHelper.TABLE_CART);
} catch (SQLiteException e) {
e.printStackTrace();
}
}
}
Usage:
if(Database.Cart.isCartAvailable(context)){
Database.deleteCart(context);
}
Cool feature. I just want to point out the emphasis on why this is better than string.format if it is not apparent to some people.
I read someone saying order string.format to "{0} {1} {2}" to match the parameters. You are not forced to order "{0} {1} {2}" in string.format, you can also do "{2} {0} {1}". However, if you have a lot of parameters, like 20, you really want to sequence the string to "{0} {1} {2} ... {19}". If it is a shuffled mess, you will have a hard time lining up your parameters.
With $, you can add parameter inline without counting your parameters. This makes the code much easier to read and maintain.
The downside of $ is, you cannot repeat the parameter in the string easily, you have to type it. For example, if you are tired of typing System.Environment.NewLine, you can do string.format("...{0}...{0}...{0}", System.Environment.NewLine), but, in $, you have to repeat it. You cannot do $"{0}" and pass it to string.format because $"{0}" returns "0".
On the side note, I have read a comment in another duplicated tpoic. I couldn't comment, so, here it is. He said that
string msg = n + " sheep, " + m + " chickens";
creates more than one string objects. This is not true actually. If you do this in a single line, it only creates one string and placed in the string cache.
1) string + string + string + string;
2) string.format()
3) stringBuilder.ToString()
4) $""
All of them return a string and only creates one value in the cache.
On the other hand:
string+= string2;
string+= string2;
string+= string2;
string+= string2;
Creates 4 different values in the cache because there are 4 ";".
Thus, it will be easier to write code like the following, but you would create five interpolated string as Carlos Muñoz corrected:
string msg = $"Hello this is {myName}, " +
$"My phone number {myPhone}, " +
$"My email {myEmail}, " +
$"My address {myAddress}, and " +
$"My preference {myPreference}.";
This creates one single string in the cache while you have very easy to read code. I am not sure about the performance, but, I am sure MS will optimize it if not already doing it.
In addition to David Sacks answer, you may also need to go to the Build
tab of the Project Properties
and set Platform Target
to x86
for the project that is giving you these warnings. Though you might expect it to be, this setting does not seem to be perfectly synchronized with the setting in the configuration manager.
Change your directive definition from app.module
to app.directive
. Apart from that everything looks fine.
Btw, very rarely do you have to inject a service into a directive. If you are injecting a service ( which usually is a data source or model ) into your directive ( which is kind of part of a view ), you are creating a direct coupling between your view and model. You need to separate them out by wiring them together using a controller.
It does work fine. I am not sure what you are doing which is wrong. Here is a plunk of it working.
Try like
HTML in PHP :
echo "<a href='".$link_address."'>Link</a>";
Or even you can try like
echo "<a href='$link_address'>Link</a>";
Or you can use PHP in HTML like
PHP in HTML :
<a href="<?php echo $link_address;?>"> Link </a>
I got the same error message (Eclipse Enterprise 2020-06, Tomcat 8.5, dynamic web project), even after I downloaded version 1.2.5 of the jst library (here), dropped it into the "WEB-INF/lib" folder and added <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
to the very top of the jsp file.
Using version 1.2 (here) instead fixed it.
It would be easier to make suggestions if you provided example code and data.
Accessing the dictionary is unlikely to be a problem as that operation is O(1) on average, and O(N) amortized worst case. It's possible that the built-in hashing functions are experiencing collisions for your data. If you're having problems with has the built-in hashing function, you can provide your own.
Python's dictionary implementation reduces the average complexity of dictionary lookups to O(1) by requiring that key objects provide a "hash" function. Such a hash function takes the information in a key object and uses it to produce an integer, called a hash value. This hash value is then used to determine which "bucket" this (key, value) pair should be placed into.
You can overwrite the __hash__ method in your class to implement a custom hash function like this:
def __hash__(self):
return hash(str(self))
Depending on what your data actually looks like, you might be able to come up with a faster hash function that has fewer collisions than the standard function. However, this is unlikely. See the Python Wiki page on Dictionary Keys for more information.
Edit: Advise: This answer is old and a better solution can be found in this same page. This answer referred to MySQL Workbench 6.3 and is outdated. If you are using a new version (8.0 as today) look for @VSingh comment in this very page.
Original answer:
Just a copy of Gaston's answer, but with Monokai theme colors.
<!--
dark-gray: #282828;
brown-gray: #49483E;
gray: #888888;
light-gray: #CCCCCC;
ghost-white: #F8F8F0;
light-ghost-white: #F8F8F2;
yellow: #E6DB74;
blue: #66D9EF;
pink: #F92672;
purple: #AE81FF;
brown: #75715E;
orange: #FD971F;
light-orange: #FFD569;
green: #A6E22E;
sea-green: #529B2F;
-->
<style id="32" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- STYLE_DEFAULT !BACKGROUND! -->
<style id="33" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- STYLE_LINENUMBER -->
<style id= "0" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DEFAULT -->
<style id= "1" fore-color="#999999" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id= "2" fore-color="#999999" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id= "3" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id= "4" fore-color="#66D9EF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id= "5" fore-color="#66D9EF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id= "6" fore-color="#AE81FF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id= "7" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id= "8" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id= "9" fore-color="#9B859D" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="10" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="11" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="12" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="13" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="14" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="15" fore-color="#9B859D" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="16" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="17" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="18" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="19" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="20" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="21" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="22" fore-color="#909090" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
<!-- All styles again in their variant in a hidden command -->
<style id="65" fore-color="#999999" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id="66" fore-color="#999999" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id="67" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id="68" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id="69" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id="70" fore-color="#AE81FF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id="71" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id="72" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id="73" fore-color="#9B859D" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="74" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="75" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="76" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="77" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="78" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="79" fore-color="#9B859D" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="80" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="81" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="82" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="83" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="84" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="85" fore-color="#66D9EF" back-color="#888888" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="86" fore-color="#AAAAAA" back-color="#888888" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
FWIW I just hit this on a slightly different use case. I scoured and scoured my code looking for where I might've used a 'str' variable, but could not find it. I started to suspect that maybe one of the modules I imported was the culprit... but alas, it was a missing '%' character in a formatted print statement.
Here's an example:
x=5
y=6
print("x as a string is: %s. y as a string is: %s" (str(x) , str(y)) )
This will result in the output:
TypeError: 'str' object is not callable
The correction is:
x=5
y=6
print("x as a string is: %s. y as a string is: %s" % (str(x) , str(y)) )
Resulting in our expected output:
x as a string is: 5. y as a string is: 6
This way you don't need to add the CSS outside of the component:
@Component({
selector: 'body',
template: 'app-element',
// prefer decorators (see below)
// host: {'[class.someClass]':'someField'}
})
export class App implements OnInit {
constructor(private cdRef:ChangeDetectorRef) {}
someField: boolean = false;
// alternatively also the host parameter in the @Component()` decorator can be used
@HostBinding('class.someClass') someField: boolean = false;
ngOnInit() {
this.someField = true; // set class `someClass` on `<body>`
//this.cdRef.detectChanges();
}
}
This CSS is defined inside the component and the selector is only applied if the class someClass
is set on the host element (from outside):
:host(.someClass) {
background-color: red;
}
CSS only (no icon sets) Codepen
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
<!-- <a class="navbar-brand" href="#">_x000D_
<img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
Bootstrap_x000D_
</a> -->_x000D_
<!-- https://stackoverflow.com/questions/26317679 -->_x000D_
<a class="nav-link" href="#">_x000D_
<div id="navBars">_x000D_
<input type="checkbox" /><span></span>_x000D_
<span></span>_x000D_
<span></span>_x000D_
</div>_x000D_
</a>_x000D_
<!-- /26317679 -->_x000D_
<div class="collapse navbar-collapse" id="navbarNav">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
<li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
suggestions of solving this problem is, If you already had installed app in your phone before downloading from google play.(obviously run from your code ) then first uninstal it. and then download and install app from google play . it worked for me .Thanks and regards.
There's a set_ticks()
function for axis objects.
When you specify:
psql -U user
it connects via UNIX Socket, which by default uses peer
authentication, unless specified in pg_hba.conf
otherwise.
You can specify:
host database user 127.0.0.1/32 md5
host database user ::1/128 md5
to get TCP/IP connection on loopback interface (both IPv4 and IPv6) for specified database
and user
.
After changes you have to restart postgres or reload it's configuration. Restart that should work in modern RHEL/Debian based distros:
service postgresql restart
Reload should work in following way:
pg_ctl reload
but the command may differ depending of PATH configuration - you may have to specify absolute path, which may be different, depending on way the postgres was installed.
Then you can use:
psql -h localhost -U user -d database
to login with that user
to specified database
over TCP/IP.
md5
stands for encrypted password, while you can also specify password
for plain text passwords during authorisation. These 2 options shouldn't be of a great matter as long as database server is only locally accessible, with no network access.
Important note:
Definition order in pg_hba.conf
matters - rules are read from top to bottom, like iptables, so you probably want to add proposed rules above the rule:
host all all 127.0.0.1/32 ident
You use goto in C for similar error handling situations.
That is the closest equivalent of exceptions you can get in C.
Pass a ref
if you want to change what the object is:
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);
void DoSomething(ref TestRef t)
{
t = new TestRef();
t.Something = "Not just a changed t, but a completely different TestRef object";
}
After calling DoSomething, t
does not refer to the original new TestRef
, but refers to a completely different object.
This may be useful too if you want to change the value of an immutable object, e.g. a string
. You cannot change the value of a string
once it has been created. But by using a ref
, you could create a function that changes the string for another one that has a different value.
It is not a good idea to use ref
unless it is needed. Using ref
gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.
Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref
keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. int
), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:
int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10
void Change(ref int x)
{
x = 5;
}
void WillNotChange(int x)
{
x = 10;
}
Using 'now()' as default value automatically generates time-stamp.
For those wondering, @edward-coast
If you want to set the keep alive for the server, add this to /etc/ssh/sshd_config
:
ClientAliveInterval 60
ClientAliveCountMax 2
ClientAliveInterval: Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client.
ClientAliveCountMax: Sets the number of client alive messages (see below) which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session.
Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:
(octal=$(echo -n ? | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")
Output is the following.
Octal representation is following \0342\0230\0240
?
Remove this.requests
from
ngOnInit(){
this.requests=this._http.getRequest().subscribe(res=>this.requests=res);
}
to
ngOnInit(){
this._http.getRequest().subscribe(res=>this.requests=res);
}
this._http.getRequest()
returns a subscription, not the response value.
The response value is assigned by the callback passed to subscribe(...)
Ruby 2.4 introduced the method Hash#transform_values!
, which you could use.
{ :a=>'a' , :b=>'b' }.transform_values! { |v| "%#{v}%" }
# => {:a=>"%a%", :b=>"%b%"}
How to insert table values from one server/database to another database?
1 Creating Linked Servers {if needs} (SQL server 2008 R2 - 2012) http://technet.microsoft.com/en-us/library/ff772782.aspx#SSMSProcedure
2 configure the linked server to use Credentials a) http://technet.microsoft.com/es-es/library/ms189811(v=sql.105).aspx
EXEC sp_addlinkedsrvlogin 'NAMEOFLINKEDSERVER', 'false', null, 'REMOTEUSERNAME', 'REMOTEUSERPASSWORD'
-- CHECK SERVERS
SELECT * FROM sys.servers
-- TEST LINKED SERVERS
EXEC sp_testlinkedserver N'NAMEOFLINKEDSERVER'
INSERT INTO NEW LOCAL TABLE
SELECT * INTO NEWTABLE
FROM [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
OR
INSERT AS NEW VALUES IN REMOTE TABLE
INSERT
INTO [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
SELECT *
FROM localTABLE
INSERT AS NEW LOCAL TABLE VALUES
INSERT
INTO localTABLE
SELECT *
FROM [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
You can drop the range(len())
:
weights_h = [[random.random() for e in inputs[0]] for e in range(hiden_neurons)]
But really, you should probably use numpy.
In [9]: numpy.random.random((3, 3))
Out[9]:
array([[ 0.37052381, 0.03463207, 0.10669077],
[ 0.05862909, 0.8515325 , 0.79809676],
[ 0.43203632, 0.54633635, 0.09076408]])
Assuming you want a default button checked.
<div class="row">
<h1>Radio Group #2</h1>
<label for="year" class="control-label input-group">Year</label>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" name="year" value="2011">2011
</label>
<label class="btn btn-default">
<input type="radio" name="year" value="2012">2012
</label>
<label class="btn btn-default active">
<input type="radio" name="year" value="2013" checked="">2013
</label>
</div>
</div>
Add the active
class to the button (label
tag) you want defaulted and checked=""
to its input
tag so it gets submitted in the form by default.
Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the encodedBytes
variable is a byte[]
and not a String
value. If you pass the byte[]
to a new String()
as below, the code snippet works perfectly.
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);
This will not work correctly, e.g. abcÑxyz
will pass thru this as it has a,b,c... you need to work with Collate or check each byte.
I was added following code segment to setting.xml and it was resolved the issue,
<mirrors>
<mirror>
<id>maven-mirror</id>
<name>Maven Mirror</name>
<url>https://repo.maven.apache.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
Here's what I put together. It works on the select mobile device I needed it for, but I'm not sure how universal the solution is
<a href="mailto:[email protected]?subject=Me&body=%3Chtml%20xmlns%3D%22http:%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%3C%2Fhead%3E%3Cbody%3EPlease%20%3Ca%20href%3D%22http:%2F%2Fwww.w3.org%22%3Eclick%3C%2Fa%3E%20me%3C%2Fbody%3E%3C%2Fhtml%3E">
In my experience, with VS2010, when include files can't be found at compile time, doing a clean, then build usually fixes the problem. It's not that rare for the editor to be able to open an include file and then the compiler to announce that it can't find that very file, even when it is open on the screen!
<nav>
<a href="#section1">1</a>
<a href="#section2">2</a>
<a href="#section3">3</a>
</nav>
<section id="section1">1</section>
<section id="section2" class="fifty">2</section>
<section id="section3">3</section>
<style>
* {padding: 0; margin: 0;}
nav {
background: black;
position: fixed;
}
a {
color: #fff;
display: inline-block;
padding: 0 1em;
height: 50px;
}
section {
background: red;
height: 100vh;
text-align: center;
font-size: 5em;
}
html {
scroll-behavior: smooth;
}
#section1{
background-color:green;
}
#section3{
background-color:yellow;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" >
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
</script>
_x000D_
Go to this link and wait for a while to load.
http://www.java.com/en/download/testjava.jsp
You will see the below image:
You can alternatively open command window and type java -version
Locate the following file
C:\Users\
[your name]\.android\adb_usb.ini
And make the following changes:
# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x2207
I added 0x2207
to the file. This number is part of the hardware id, which can be found under the device's hardware information.
Mine was:
USB\VID_2207&PID_0010&MI_01
(I tried executing android update adb
, but it did nothing.)
Your idea with the SequenceGenerator fake entity is good.
@Id
@GenericGenerator(name = "my_seq", strategy = "sequence", parameters = {
@org.hibernate.annotations.Parameter(name = "sequence_name", value = "MY_CUSTOM_NAMED_SQN"),
})
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")
It is important to use the parameter with the key name "sequence_name". Run a debugging session on the hibernate class SequenceStyleGenerator, the configure(...) method at the line final QualifiedName sequenceName = determineSequenceName( params, dialect, jdbcEnvironment ); to see more details about how the sequence name is computed by Hibernate. There are some defaults in there you could also use.
After the fake entity, I created a CrudRepository:
public interface SequenceRepository extends CrudRepository<SequenceGenerator, Long> {}
In the Junit, I call the save method of the SequenceRepository.
SequenceGenerator sequenceObject = new SequenceGenerator(); SequenceGenerator result = sequenceRepository.save(sequenceObject);
If there is a better way to do this (maybe support for a generator on any type of field instead of just Id), I would be more than happy to use it instead of this "trick".
To get the timedelta()
, you should subtract 1900-01-01
:
>>> from datetime import datetime
>>> datetime.strptime('01:01:09,000', '%H:%M:%S,%f')
datetime.datetime(1900, 1, 1, 1, 1, 9)
>>> td = datetime.strptime('01:01:09,000', '%H:%M:%S,%f') - datetime(1900,1,1)
>>> td
datetime.timedelta(0, 3669)
>>> td.total_seconds() # 2.7+
3669.0
%H
above implies the input is less than a day, to support the time difference more than a day:
>>> import re
>>> from datetime import timedelta
>>> td = timedelta(**dict(zip("hours minutes seconds milliseconds".split(),
... map(int, re.findall('\d+', '31:01:09,000')))))
>>> td
datetime.timedelta(1, 25269)
>>> td.total_seconds()
111669.0
To emulate .total_seconds()
on Python 2.6:
>>> from __future__ import division
>>> ((td.days * 86400 + td.seconds) * 10**6 + td.microseconds) / 10**6
111669.0
import java.math.*;
public class TestRound11 {
public static void main(String args[]){
double d = 3.1537;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
}
public static double round(double d, int decimalPlace){
// see the Javadoc about why we use a String in the constructor
// http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
}
type
?Generic Transformations
Use the type
when you are transforming multiple types into a single generic type.
Example:
type Nullable<T> = T | null | undefined
type NonNull<T> = T extends (null | undefined) ? never : T
Type Aliasing
We can use the type
for creating the aliases for long or complicated types that are hard to read as well as inconvenient to type again and again.
Example:
type Primitive = number | string | boolean | null | undefined
Creating an alias like this makes the code more concise and readable.
Type Capturing
Use the type
to capture the type of an object when the type is unknown.
Example:
const orange = { color: "Orange", vitamin: "C"}
type Fruit = typeof orange
let apple: Fruit
Here, we get the unknown type of orange
, call it a Fruit
and then use the Fruit
to create a new type-safe object apple
.
interface
?Polymorphism
An interface
is a contract to implement a shape of the data. Use the interface to make it clear that it is intended to be implemented and used as a contract about how the object will be used.
Example:
interface Bird {
size: number
fly(): void
sleep(): void
}
class Hummingbird implements Bird { ... }
class Bellbird implements Bird { ... }
Though you can use the type
to achieve this, the Typescript is seen more as an object oriented language and the interface
has a special place in object oriented languages. It's easier to read the code with interface
when you are working in a team environment or contributing to the open source community. It's easy on the new programmers coming from the other object oriented languages too.
The official Typescript documentation also says:
... we recommend using an
interface
over atype
alias when possible.
This also suggests that the type
is more intended for creating type aliases than creating the types themselves.
Declaration Merging
You can use the declaration merging feature of the interface
for adding new properties and methods to an already declared interface
. This is useful for the ambient type declarations of third party libraries. When some declarations are missing for a third party library, you can declare the interface again with the same name and add new properties and methods.
Example:
We can extend the above Bird
interface to include new declarations.
interface Bird {
color: string
eat(): void
}
That's it! It's easier to remember when to use what than getting lost in subtle differences between the two.
You can use in Content-security-policy add "img-src 'self' data:;" And Use outline CSS.Don't use Inline CSS.It's secure from attackers.
You can use json2csharp.com to Convert your json to object model
var model = JsonConvert.DeserializeObject<RootObject>(json);
using NewtonJsonHere, It will generate something like this:
public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}
public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}
public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}
public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}
Then you can deserialize as:
var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY
#include<iostream>
using namespace std;
int main()
{
int input,rem,res,count=0,i=0;
cout<<"Input number: ";
cin>>input;`enter code here`
int num=input;
while(input > 0)
{
input=input/2;
count++;
}
int arr[count];
while(num > 0)
{
arr[i]=num%2;
num=num/2;
i++;
}
for(int i=count-1 ; i>=0 ; i--)
{
cout<<" " << arr[i]<<" ";
}
return 0;
}
If you know the index that the object has within the array then you can use splice(), as others have mentioned, ie:
var removedObject = myArray.splice(index,1);
removedObject = null;
If you don't know the index then you need to search the array for it, ie:
for (var n = 0 ; n < myArray.length ; n++) {
if (myArray[n].name == 'serdar') {
var removedObject = myArray.splice(n,1);
removedObject = null;
break;
}
}
Marcelo
b''.fromhex('7061756c')
use it without delimiter
Have a wrapper around your program that does the following.
import sys
req_version = (2,5)
cur_version = sys.version_info
if cur_version >= req_version:
import myApp
myApp.run()
else:
print "Your Python interpreter is too old. Please consider upgrading."
You can also consider using sys.version()
, if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.
And there might be more elegant ways to do this.
If your code is dealing with XmlElements
objects (rather than XmlNodes
) then there is the method XmlElement.HasAttribute(string name).
So if you are only looking for attributes on elements (which it looks like from the OP) then it may be more robust to cast as an element, check for null, and then use the HasAttribute method.
foreach (XmlNode xNode in nodeListName)
{
XmlElement xParentEle = xNode.ParentNode as XmlElement;
if((xParentEle != null) && xParentEle.HasAttribute("split"))
{
parentSplit = xParentEle.Attributes["split"].Value;
}
}
The Proxy pattern might help you:
(function() {
// log all calls to setArray
var proxied = jQuery.fn.setArray;
jQuery.fn.setArray = function() {
console.log( this, arguments );
return proxied.apply( this, arguments );
};
})();
The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.
If your Postgres was working and suddenly you encountered with this error, my problem was resolved just by restarting Postgres service or container.
If you would like to continue using the original auto-prefixed controller routing, you can simply set the value of the $namespace property within your RouteServiceProvider and update the route registrations within the boot method to use the $namespace property:
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
});
}
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
Uncomment this line (in /conf/logging.properties
)
org.apache.jasper.compiler.TldLocationsCache.level = FINE
Work's for me in tomcat 7.0.53!
I'm sure someone can do better, but this works:
sapply(as.character(q.data$string), function(x, letter = "a"){
sum(unlist(strsplit(x, split = "")) == letter)
})
greatgreat magic not
2 1 0
or in a function:
countLetter <- function(charvec, letter){
sapply(charvec, function(x, letter){
sum(unlist(strsplit(x, split = "")) == letter)
}, letter = letter)
}
countLetter(as.character(q.data$string),"a")
Just try this first. It is my personal experience.
I had the same problem. What i had done is just permanently disable the antivirus (Mine was Avast Security 2015). Just after disabling the antivirus , thing gone well. the gradle finished successfully. From now within seconds the gradle is finishing ( Only taking 5-10 secs).
Following command
docker-compose restart worker
will just STOP and START the container. i.e without loading any changes from the docker-compose.xml
STOP is similar to hibernating in PC . Hence stop/start will not look for any changes made in configuration file . To reload from the recipe of container (docker-compose.xml) we need to remove and create the container (Similar analogy to rebooting the PC )
So commands will be as following
docker-compose stop worker // go to hibernate
docker-compose rm worker // shutdown the PC
docker-compose create worker // create the container from image and put it in hibernate
docker-compose start worker //bring container to life from hibernation
Enough explanation about each parameter is given by other answers; However you asked for a real world example, here is the one that clarifies the purpose of different propagation options:
Suppose you're in charge of implementing a signup service in which a confirmation e-mail is sent to the user. You come up with two service objects, one for enrolling the user and one for sending e-mails, which the latter is called inside the first one. For example something like this:/* Sign Up service */
@Service
@Transactional(Propagation=REQUIRED)
class SignUpService{
...
void SignUp(User user){
...
emailService.sendMail(User);
}
}
/* E-Mail Service */
@Service
@Transactional(Propagation=REQUIRES_NEW)
class EmailService{
...
void sendMail(User user){
try{
... // Trying to send the e-mail
}catch( Exception)
}
}
You may have noticed that the second service is of propagation type REQUIRES_NEW and moreover chances are it throws an exception (SMTP server down ,invalid e-mail or other reasons).You probably don't want the whole process to roll-back, like removing the user information from database or other things; therefore you call the second service in a separate transaction.
Back to our example, this time you are concerned about the database security, so you define your DAO classes this way:/* User DAO */
@Transactional(Propagation=MANDATORY)
class UserDAO{
// some CRUD methods
}
Meaning that whenever a DAO object, and hence a potential access to db, is created, we need to reassure that the call was made from inside one of our services, implying that a live transaction should exist; otherwise an exception occurs.Therefore the propagation is of type MANDATORY.
why not just declare that function inside the cshtml file?
@functions{
public string GetSomeString(){
return string.Empty;
}
}
<h2>index</h2>
@GetSomeString()
I know it's too late but I'd like to add this update:
I'm using the Conventional Model Metadata Provider which presented by Phil Haacked it's more powerful and easy to apply take look at it : ConventionalModelMetadataProvider
Here if you wanna support many types of resources:
public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
private readonly PropertyInfo nameProperty;
public LocalizedDisplayNameAttribute(string displayNameKey, Type resourceType = null)
: base(displayNameKey)
{
if (resourceType != null)
{
nameProperty = resourceType.GetProperty(base.DisplayName,
BindingFlags.Static | BindingFlags.Public);
}
}
public override string DisplayName
{
get
{
if (nameProperty == null)
{
return base.DisplayName;
}
return (string)nameProperty.GetValue(nameProperty.DeclaringType, null);
}
}
}
Then use it like this:
[LocalizedDisplayName("Password", typeof(Res.Model.Shared.ModelProperties))]
public string Password { get; set; }
For the full localization tutorial see this page.
In the OpenGL ES 2.0/3.0 you can also combining OGL View and Android's UI-elements:
public class GameActivity extends AppCompatActivity {
private SurfaceView surfaceView;
@Override
protected void onCreate(Bundle state) {
setContentView(R.layout.activity_gl);
surfaceView = findViewById(R.id.oglView);
surfaceView.init(this.getApplicationContext());
...
}
}
public class SurfaceView extends GLSurfaceView {
private SceneRenderer renderer;
public SurfaceView(Context context) {
super(context);
}
public SurfaceView(Context context, AttributeSet attributes) {
super(context, attributes);
}
public void init(Context context) {
renderer = new SceneRenderer(context);
setRenderer(renderer);
...
}
}
Create layout activity_gl.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
tools:context=".activities.GameActivity">
<com.app.SurfaceView
android:id="@+id/oglView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView ... />
<TextView ... />
<TextView ... />
</androidx.constraintlayout.widget.ConstraintLayout>
To update elements from the render thread, can use Handler/Looper.
Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on reStructuredText (reST). You can get some information about the main formats in this blog post.
Note that the reST is recommended by the PEP 287
There follows the main used formats for docstrings.
Historically a javadoc like style was prevalent, so it was taken as a base for Epydoc (with the called Epytext
format) to generate documentation.
Example:
"""
This is a javadoc style.
@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""
Nowadays, the probably more prevalent format is the reStructuredText (reST) format that is used by Sphinx to generate documentation. Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). It is also used by default as output format in Pyment.
Example:
"""
This is a reST style.
:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""
Google has their own format that is often used. It also can be interpreted by Sphinx (ie. using Napoleon plugin).
Example:
"""
This is an example of Google style.
Args:
param1: This is the first param.
param2: This is a second param.
Returns:
This is a description of what is returned.
Raises:
KeyError: Raises an exception.
"""
Even more examples
Note that Numpy recommend to follow their own numpydoc based on Google format and usable by Sphinx.
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.
Parameters
----------
first : array_like
the 1st param name `first`
second :
the 2nd param
third : {'value', 'other'}, optional
the 3rd param, by default 'value'
Returns
-------
string
a value in a string
Raises
------
KeyError
when a key error
OtherError
when an other error
"""
It is possible to use a tool like Pyment to automatically generate docstrings to a Python project not yet documented, or to convert existing docstrings (can be mixing several formats) from a format to an other one.
Note: The examples are taken from the Pyment documentation
I've implemented cross-browser compatible page to test browser's refresh behavior (here is the source code) and get results similar to @some, but for modern browsers:
For the sake of completion: if you want to convert fixed point representation to its binary equivalent you can perform the following operations:
Get the integer and fractional part.
from decimal import *
a = Decimal(3.625)
a_split = (int(a//1),a%1)
Convert the fractional part in its binary representation. To achieve this multiply successively by 2.
fr = a_split[1]
str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...
You can read the explanation here.
if (dtCustomers.Columns[j - 1].DataType != typeof(decimal) && dtCustomers.Columns[j - 1].DataType != typeof(int))
{
myWorksheet.Cells[i + 2, j].NumberFormat = "@";
}
I was struggling with the same thing, running a shell script that set variables, then wanting to use the variables in the shared-pom. The goal was to have environment variables replace strings in my project files using the com.google.code.maven-replacer-plugin.
Using ${env.foo}
or ${env.FOO}
didn't work for me. Maven just wasn't finding the variable. What worked was passing the variable in as a command-line parameter in Maven. Here's the setup:
Set the variable in the shell script. If you're launching Maven in a sub-script, make sure the variable is getting set, e.g. using source ./maven_script.sh
to call it from the parent script.
In shared-pom, create a command-line param that grabs the environment variable:
<plugin> ... <executions> <executions> ... <execution> ... <configuration> <param>${foo}</param> <!-- Note this is *not* ${env.foo} --> </configuration>
In com.google.code.maven-replacer-plugin, make the replacement value ${foo}
.
In my shell script that calls maven, add this to the command: -Dfoo=$foo
You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates
subfolder):
@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)
Or if this is not the case simply:
@Html.Partial("nameOfPartial", Model)
Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.
Using your CountryData class, you would define a service method like this:
getCountries() {
return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}
Then when you need it, define an array like this:
countries:CountryData[] = [];
and subscribe to it like this:
this.countryService.getCountries().subscribe(countries => this.countries = countries);
A complete setup answer is posted here also.
var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);
This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:
prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _
param_cls_shift.Start_Date (string property of my class)
maybe you can try using
SELECT user_name
FROM user_master
WHERE upper(user_name) LIKE '%ME%'
Send a SIGTERM or a SIGKILL to it:
http://en.wikipedia.org/wiki/SIGKILL
http://en.wikipedia.org/wiki/SIGTERM
SIGTERM is polite and lets the process clean up before it goes, whereas, SIGKILL is for when it won't listen >:)
Example from the shell (man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?kill )
kill -9 pid
In C, you can do the same thing using the kill syscall:
kill(pid, SIGKILL);
See the following man page: http://linux.die.net/man/2/kill
Try as below:
var dt = new Date();
dt.setMinutes( dt.getMinutes() - 20 );
console.log('#####',dt);
It is just a matter of changing the port user by mysql:3308 to 3306
Just right click on wamp-> select tools
under Port Used By mysql:3308 clcik on "use a port other than 3308
In the text port text box appear : type 3306 and save. Wait until the wampserver restarts and get green.
Now run your PHP code, It will work. That's it - Good Luck
//XAML Code
// ViewModel code
private CategoryModel _SelectedCategory;
public CategoryModel SelectedCategory
{
get { return _SelectedCategory; }
set
{
_SelectedCategory = value;
OnPropertyChanged("SelectedCategory");
}
}
private ObservableCollection<CategoryModel> _Categories;
public ObservableCollection<CategoryModel> Categories
{
get { return _Categories; }
set
{
_Categories = value;
_Categories.Insert(0, new CategoryModel()
{
CategoryId = 0,
CategoryName = " -- Select Category -- "
});
SelectedCategory = _Categories[0];
OnPropertyChanged("Categories");
}
}
If you are just experimenting you can use babel-node
command line tool to try out the new JavaScript features
Install babel-cli
into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc
in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
I like ThomasA's answer, but wanted a more realistic context with the wave being used to separate two divs. So I created a more complete demo where the separator SVG gets positioned perfectly between the two divs.
Now I thought it would be cool to take it further. What if we could do this all in CSS without the need for the inline SVG? The point being to avoid extra markup. Here's how I did it:
Two simple <div>
:
/** CSS using pseudo-elements: **/_x000D_
_x000D_
#A {_x000D_
background: #0074D9;_x000D_
}_x000D_
_x000D_
#B {_x000D_
background: #7FDBFF;_x000D_
}_x000D_
_x000D_
#A::after {_x000D_
content: "";_x000D_
position: relative;_x000D_
left: -3rem;_x000D_
/* padding * -1 */_x000D_
top: calc( 3rem - 4rem / 2);_x000D_
/* padding - height/2 */_x000D_
float: left;_x000D_
display: block;_x000D_
height: 4rem;_x000D_
width: 100vw;_x000D_
background: hsla(0, 0%, 100%, 0.5);_x000D_
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 70 500 60' preserveAspectRatio='none'%3E%3Crect x='0' y='0' width='500' height='500' style='stroke: none; fill: %237FDBFF;' /%3E%3Cpath d='M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z' style='stroke: none; fill: %230074D9;'%3E%3C/path%3E%3C/svg%3E");_x000D_
background-size: 100% 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/** Cosmetics **/_x000D_
_x000D_
* {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
#A,_x000D_
#B {_x000D_
padding: 3rem;_x000D_
}_x000D_
_x000D_
div {_x000D_
font-family: monospace;_x000D_
font-size: 1.2rem;_x000D_
line-height: 1.2;_x000D_
}_x000D_
_x000D_
#A {_x000D_
color: white;_x000D_
}
_x000D_
<div id="A">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec quam tincidunt, iaculis mi non, hendrerit felis. Nulla pretium lectus et arcu tempus, quis luctus ex imperdiet. In facilisis nulla suscipit ornare finibus. …_x000D_
</div>_x000D_
_x000D_
<div id="B" class="wavy">… In iaculis fermentum lacus vel porttitor. Vestibulum congue elementum neque eget feugiat. Donec suscipit diam ligula, aliquam consequat tellus sagittis porttitor. Sed sodales leo nisl, ut consequat est ornare eleifend. Cras et semper mi, in porta nunc.</div>
_x000D_
Demo Wavy divider (with CSS pseudo-elements to avoid extra markup)
It was a bit trickier to position than with an inline SVG but works just as well. (Could use CSS custom properties or pre-processor variables to keep the height and padding easy to read.)
To edit the colors, you need to edit the URL-encoded SVG itself.
Pay attention (like in the first demo) to a change in the viewBox
to get rid of unwanted spaces in the SVG. (Another option would be to draw a different SVG.)
Another thing to pay attention to here is the background-size
set to 100% 100%
to get it to stretch in both directions.
Yes by using spring-boot with hibernate configuration files we can persist the data to the database. keep hibernating .cfg.xml in your src/main/resources folder for reading the configurations related to database.
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
Short answer: There's no way to do it using CSS only.
Long(er) answer: Why? Because when you do position: absolute;
, that takes your element out of the document's regular flow, so there's no way for the text to have any positional-relationship with it, unfortunately.
One of the possible alternatives is to float: right;
your div
, but if that doesn't achieve what you want, you'll have to use JavaScript/jQuery, or just come up with a better layout.
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
This is not only a 'newbie' scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.
The bottom line seems to be this: If the compiler can't match the definition's signature to the declaration's signature it thinks the definition is not a constructor and then doesn't know how to parse the code and displays this error. Which is also what happened for the OP: std::string
is not the same type as string
so the declaration's signature differed from the definition's and this message was spit out.
As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn't match rather than giving this message.
Column(children: <Widget>[
Container(margin: EdgeInsets.only(top:12, child: yourWidget)),
Container(margin: EdgeInsets.only(top:12, child: yourWidget))
]);
You can have a look at Eclipse color theme, also which has a hell of a lot of options for customizing font, background color, etc.
You need to include the protocol scheme:
'http://192.168.1.61:8080/api/call'
Without the http://
part, requests
has no idea how to connect to the remote server.
Note that the protocol scheme must be all lowercase; if your URL starts with HTTP://
for example, it won’t find the http://
connection adapter either.
Better solutions for furthering:
https://blog.madisonhub.org/setting-up-a-mongodb-server-with-auth-on-docker/ https://docs.mongodb.com/v2.6/tutorial/add-user-administrator/
Here's what I did for the same problem, and it worked.
Run the mongo docker instance on your server
docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo
Open bash on the running docker instance.
docker ps
CONTAINER IDIMAGE COMMAND CREATED STATUS PORTS NAMES
b07599e429fb mongo "docker-entrypoint..." 35 minutes ago Up 35 minutes 0.0.0.0:27017->27017/tcp musing_stallman
docker exec -it b07599e429fb bash
root@b07599e429fb:/#
Enter the mongo shell by typing mongo.
root@b07599e429fb:/# mongo
For this example, I will set up a user named ian and give that user read & write access to the cool_db database.
> use cool_db
> db.createUser({
user: 'ian',
pwd: 'secretPassword',
roles: [{ role: 'readWrite', db:'cool_db'}]
})
Reference: https://ianlondon.github.io/blog/mongodb-auth/ (First point only)
Exit from mongod shell and bash.
Stop the docker instance using the below command.
docker stop mongo
Now run the mongo docker with auth enabled.
docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo mongod --auth
Reference: How to enable authentication on MongoDB through Docker? (Usman Ismail's answer to this question)
I was able to connect to the instance running on a Google Cloud server from my local windows laptop using the below command.
mongo <ip>:27017/cool_db -u ian -p secretPassword
Reference: how can I connect to a remote mongo server from Mac OS terminal
You can not put
$connection = sqlite_open("[path]/data/users.sqlite", 0666);
outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.
I solved the problem by deleting reference to the file and adding it again in project. In my case it works.
I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:
struct Object {
int i;
};
void sample(Object* o) { // 1
o->i++;
}
void sample(Object const& o) { // 2
// nothing useful here :)
}
void sample(Object & o) { // 3
o.i++;
}
void sample1(Object o) { // 4
o.i++;
}
int main() {
Object obj = { 10 };
Object const obj_c = { 10 };
sample(&obj); // calls 1
sample(obj) // calls 3
sample(obj_c); // calls 2
sample1(obj); // calls 4
}
Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.
I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:
sample(&obj);
// yields a `Object*`. Passes a *pointer* to the object by value.
// The caller can change the pointer (the parameter), but that
// won't change the temporary pointer created on the call side (the argument).
sample(obj)
// passes the object by *reference*. It denotes the object itself. The callee
// has got a reference parameter.
sample(obj_c);
// also passes *by reference*. the reference parameter references the
// same object like the argument expression.
sample1(obj);
// pass by value. The parameter object denotes a different object than the
// one passed in.
I vote for the following definition:
An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.
That means that the following is pass by value:
void f1(Object const& o);
f1(Object()); // 1
void f2(int const& i);
f2(42); // 2
void f3(Object o);
f3(Object()); // 3
Object o1; f3(o1); // 4
void f4(Object *o);
Object o1; f4(&o1); // 5
1
is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2
is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3
is pass by value, because the parameter has not reference type. 4
is pass by value for the same reason. 5
is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):
void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1
void f2(Object const& op);
Object b; f2(b); // 2
struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference
If your <input>
or <textarea>
has attribute id=mytext
then use
mytext.focus();
function setFocusToTextBox() {_x000D_
mytext.focus();_x000D_
}
_x000D_
<body onload='setFocusToTextBox()'>_x000D_
<form>_x000D_
<input type="text" id="mytext"/>_x000D_
</form>_x000D_
</body>
_x000D_
If the table is compressed this will work:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES move nocompress;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
alter table EVAPP_FEES compress;
I am just using the java.net
package.
Here you can do the following:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
I can't claim credit for this image, but it matches everything I know on this subject and offers a bit of humor at the same time.
"A comment for a column can be specified with the COMMENT
option. The comment is displayed by the SHOW CREATE TABLE
and SHOW FULL COLUMNS
statements. This option is operational as of MySQL 4.1. (It is allowed but ignored in earlier versions.)"
As an example
--
-- Table structure for table 'accesslog'
--
CREATE TABLE accesslog (
aid int(10) NOT NULL auto_increment COMMENT 'unique ID for each access entry',
title varchar(255) default NULL COMMENT 'the title of the page being accessed',
path varchar(255) default NULL COMMENT 'the local path of teh page being accessed',
....
) TYPE=MyISAM;
After many fruitful hours of exploring OCR libraries, bounding boxes and clustering algorithms - I found a solution so simple it makes you want to cry!
I hope you are using Linux;
pdftotext -layout NAME_OF_PDF.pdf
AMAZING!!
Now you have a nice text file with all the information lined up in nice columns, now it is trivial to format into a csv etc..
It is for times like this that I love Linux, these guys came up with AMAZING solutions to everything, and put it there for FREE!
Spring 2 introduced ResponseStatusException using this you can return String, different HTTP status code, DTO at the same time.
@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
if(userDto.getId() != null) {
throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE,"A new user cannot already have an ID");
}
return ResponseEntity.ok(userService.saveUser(userDto));
}
You're right in your assumption about Spring vs. Quartz instantiating the class. However, Spring provides some classes that let you do some primitive dependency injection in Quartz. Check out SchedulerFactoryBean.setJobFactory() along with the SpringBeanJobFactory. Essentially, by using the SpringBeanJobFactory, you enable dependency injection on all Job properties, but only for values that are in the Quartz scheduler context or the job data map. I don't know what all DI styles it supports (constructor, annotation, setter...) but I do know it supports setter injection.
I just used the event input and it worked fine as follows:
in .html file :
<input type="text" class="form-control" (input)="onSearchChange($event.target.value)">
in .ts file :
onSearchChange(searchValue: string): void {
console.log(searchValue);
}
First you need to find a row with id == 2 then change the name so:
foreach(DataRow dr in table.Rows) // search whole table
{
if(dr["Product_id"] == 2) // if id==2
{
dr["Product_name"] = "cde"; //change the name
//break; break or not depending on you
}
}
You could also try these solutions:
table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
Or:
DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any
if(dr != null)
{
dr["Product_name"] = "cde"; //changes the Product_name
}
System.IO.File.Create(@"C:\Temp.txt");
As others have pointed out, you should dispose of this object or wrap it in an empty using statement.
using (System.IO.File.Create(@"C:\Temp.txt"));
In my case, I was on CentOS 7 and my php installation was pointing to a certificate that was being generated through update-ca-trust
. The symlink was /etc/pki/tls/cert.pem
pointing to /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
. This was just a test server and I wanted my self signed cert to work properly. So in my case...
# My root ca-trust folder was here. I coped the .crt file to this location
# and renamed it to a .pem
/etc/pki/ca-trust/source/anchors/self-signed-cert.pem
# Then run this command and it will regenerate the certs for you and
# include your self signed cert file.
update-ca-trust
Then some of my api calls started working as my cert was now trusted. Also if your ca-trust gets updated through yum or something, this will rebuild your root certificates and still include your self signed cert. Run man update-ca-trust
for more info on what to do and how to do it. :)
The simplest way is using slice. You pipe the slice and mention the start index and end index for the part of the data you wish to display. Here is the code:
HTML
<table>
<thead>
...
</thead>
<tbody>
<tr *ngFor="let row of rowData | slice:startIndex:endIndex">
...
</tr>
</tbody>
</table>
<nav *ngIf="rowData" aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link" (click)="updateIndex(0)" aria-label="Previous">
<span aria-hidden="true">First</span>
</a>
</li>
<li *ngFor="let i of getArrayFromNumber(rowData.length)" class="page-item">
<a class="page-link" (click)="updateIndex(i)">{{i+1}}</a></li>
<li class="page-item">
<a class="page-link" (click)="updateIndex(pageNumberArray.length-1)" aria-label="Next">
<span aria-hidden="true">Last</span>
</a>
</li>
</ul>
</nav>
TypeScript
...
public rowData = data // data you want to display in table
public paginationRowCount = 100 //number of records in a page
...
getArrayFromNumber(length) {
if (length % this.paginationRowCount === 0) {
this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount)).keys());
} else {
this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount) + 1).keys());
}
return this.pageNumberArray;
}
updateIndex(pageIndex) {
this.startIndex = pageIndex * this.paginationRowCount;
if (this.rowData.length > this.startIndex + this.paginationRowCount) {
this.endIndex = this.startIndex + this.paginationRowCount;
} else {
this.endIndex = this.rowData.length;
}
}
Refence for tutorial: https://www.youtube.com/watch?v=Q0jPfb9iyE0
When you are dealing with objects, you want to ignore simple id's as much as convenient.
If you change the click line to this, I think you will be well on your way:
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(tutorial)" ng-repeat="tutorial in section.tutorials">
Also, I think you may need to change
class="tutorial_title {{tutorial.active}}"
to something like
ng-class="tutorial_title {{tutorial.active}}"
See http://docs.angularjs.org/misc/faq and look for ng-class.
There are many different sytles/conventions that people use when coding C++. For example, some people prefer separating words using capitals (myVar or MyVar), or using underscores (my_var). Typically, variables that use underscores are in all lowercase (from my experience).
There is also a coding style called hungarian, which I believe is used by microsoft. I personally believe that it is a waste of time, but it may prove useful. This is were variable names are given short prefixes such as i, or f to hint the variables type. For example: int iVarname, char* strVarname.
It is accepted that you end a struct/class name with _t, to differentiate it from a variable name. E.g.:
class cat_t {
...
};
cat_t myCat;
It is also generally accepted to add a affix to indicate pointers, such as pVariable or variable_p.
In all, there really isn't any single standard, but many. The choices you make about naming your variables doesn't matter, so long as it is understandable, and above all, consistent. Consistency, consistency, CONSISTENCY! (try typing that thrice!)
And if all else fails, google it.
another way is to provide no cache headers from serverside in the code that generates the response to ajax call:
response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
just run the following command in the node project
npm install
its worked for me
EDIT Ignore this answer. There are now better answers. See the comments. Use + theme_classic()
EDIT
This is a better version. The bug mentioned below in the original post remains (I think). But the axis line is drawn under the panel. Therefore, remove both the panel.border
and panel.background
to see the axis lines.
library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
ggplot(df, aes(x = a, y = b)) + geom_point() +
theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Original post
This gets close. There was a bug with axis.line
not working on the y-axis (see here), that appears not to be fixed yet. Therefore, after removing the panel border, the y-axis has to be drawn in separately using geom_vline
.
library(ggplot2)
library(grid)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
p = ggplot(df, aes(x = a, y = b)) + geom_point() +
scale_y_continuous(expand = c(0,0)) +
scale_x_continuous(expand = c(0,0)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
p
The extreme points are clipped, but the clipping can be undone using code by baptiste.
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Or use limits
to move the boundaries of the panel.
ggplot(df, aes(x = a, y = b)) + geom_point() +
xlim(0,22) + ylim(.95, 2.1) +
scale_x_continuous(expand = c(0,0), limits = c(0,22)) +
scale_y_continuous(expand = c(0,0), limits = c(.95, 2.2)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
If you are using the new Navigation Component, is simple as
findNavController().popBackStack()
It will do all the FragmentTransaction in behind for you.
I have used this before and I think in order to make sure credential persist and in a best secure way is
ConfigurationManager
classSecureString
classCryptography
namespace.This link will be of great help I hope : Click here
If you don't want to use a module you have to install like requests
, and your use case is very basic, then you can use urllib2
urllib2.urlopen(url, body)
See the documentation for urllib2
here: https://docs.python.org/2/library/urllib2.html.
You need not to use even the package "tcltk". You can simply do as shown below:
write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)
Give your path inspite of "c:\myname\yourfile.csv".
All the answers here either allow URLs with other schemes (e.g., file://
, ftp://
) or reject human-readable URLs that don't start with http://
or https://
(e.g., www.google.com
) which is not good when dealing with user inputs.
Here's how I do it:
public static bool ValidHttpURL(string s, out Uri resultURI)
{
if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
s = "http://" + s;
if (Uri.TryCreate(s, UriKind.Absolute, out resultURI))
return (resultURI.Scheme == Uri.UriSchemeHttp ||
resultURI.Scheme == Uri.UriSchemeHttps);
return false;
}
Usage:
string[] inputs = new[] {
"https://www.google.com",
"http://www.google.com",
"www.google.com",
"google.com",
"javascript:alert('Hack me!')"
};
foreach (string s in inputs)
{
Uri uriResult;
bool result = ValidHttpURL(s, out uriResult);
Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri);
}
Output:
True https://www.google.com/
True http://www.google.com/
True http://www.google.com/
True http://google.com/
False
My problem was that my company proxy was getting in the way. The solution here was to identify the Root CA / certificate chain of our proxy, (on mac) export it from the keychain in .pem format, then export a variable for node to use.
export NODE_EXTRA_CA_CERTS=/path/to/your/CA/cert.pem
You can use Gson for this.
GSON
is a Java library that can be used to convert Java Objects into their JSON
representation. It can also be used to convert a JSON
string to an equivalent Java object.
Take a look of this Converting JSON to Java
Merge squash merges a tree (a sequence of commits) into a single commit. That is, it squashes all changes made in n commits into a single commit.
Rebasing is re-basing, that is, choosing a new base (parent commit) for a tree. Maybe the mercurial term for this is more clear: they call it transplant because it's just that: picking a new ground (parent commit, root) for a tree.
When doing an interactive rebase, you're given the option to either squash, pick, edit or skip the commits you are going to rebase.
Hope that was clear!
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
Here is a simple alternative:
1/ Suppose we have two css files, say my1.css and my2.css. In the html document head type a link to one of them, within an element with an ID, say "demo":
2/ In the html document head body define two buttons calling two JS functions:
select css1
select css2
3/ Finally, in the JS file type the two functions as follows:
function select_css1() {
document.getElementById("demo").innerHTML = '';
}
function select_css2() {
document.getElementById("demo").innerHTML = '';
}
Use sys.getsizeof
to get the size of an object, in bytes.
>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>
Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.
This is to do with the encoding of your terminal not being set to UTF-8. Here is my terminal
$ echo $LANG
en_GB.UTF-8
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
(?????)?
>>>
On my terminal the example works with the above, but if I get rid of the LANG
setting then it won't work
$ unset LANG
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)
>>>
Consult the docs for your linux variant to discover how to make this change permanent.
with open('x.py') as f: s = f.read()
***grins***
You can not give order by
because order by
does a "full scan" on a table.
The following query is better:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);
webpack 4 now offers a version property that can be used!
$("#person_IsCurrentAddressSame").change(function ()
{
debugger
if ($("#person_IsCurrentAddressSame").checked) {
debugger
}
else {
}
})
If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:
/**
* The interface defines all abstract methods and extends the concrete base class
*/
interface IAnimal extends Animal {
speak() : void;
}
/**
* The abstract base class only defines concrete methods & properties.
*/
class Animal {
private _impl : IAnimal;
public name : string;
/**
* Here comes the clever part: by letting the constructor take an
* implementation of IAnimal as argument Animal cannot be instantiated
* without a valid implementation of the abstract methods.
*/
constructor(impl : IAnimal, name : string) {
this.name = name;
this._impl = impl;
// The `impl` object can be used to delegate functionality to the
// implementation class.
console.log(this.name + " is born!");
this._impl.speak();
}
}
class Dog extends Animal implements IAnimal {
constructor(name : string) {
// The child class simply passes itself to Animal
super(this, name);
}
public speak() {
console.log("bark");
}
}
var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"
Since the Animal
class requires an implementation of IAnimal
it's impossible to construct an object of type Animal
without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal
, not Animal
. E.g.:
//This works
function letTheIAnimalSpeak(animal: IAnimal) {
console.log(animal.name + " says:");
animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
console.log(animal.name + " says:");
animal.speak();
}
The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.
you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend
//making array of book object
var books = [];
var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
books.push(new_book);
new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
books.push(new_book);
console.log(books[0].id);
console.log(books[0].name);
console.log(books[0].category);
console.log(books[0].price);
// also we have array of albums
var albums = []
var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
albums.push(new_album);
new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);
console.log(my_albums[0].name);
console.log(my_albums[1].name);
This Example Works with me. Snapshot for the Output on Browser Console
with UnionTable as
(
SELECT a.id, a.time FROM dbo.a
UNION
SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id
The easiest way to do it, at least for me, is:
Conditional format-> Add new rule->Set your own formula:
=ISNA(MATCH(A2;$B:$B;0))
Where A2 is the first element in column A to be compared and B is the column where A's element will be searched.
Once you have set the formula and picked the format, apply this rule to all elements in the column.
Hope this helps
The best option now is to install the Microsoft Visual Studio add on called Productivity Power Tools.
With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits) - which then you can use to filter the files to only show "Open". You can even filter files to show "Edited" and "Unsaved".
Update:
Separate the event and property bindings:
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
You could also use
<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">
and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.
Old answer, before they fixed a bug in beta.1:
Create a local template variable and attach a (change)
event:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
See also How can I get new selection in "select" in Angular 2?
Here is my code, it is working perfectly, you can try with give below demo:
$(document).ready(function() {_x000D_
//EST_x000D_
setInterval( function() {_x000D_
var estTime = new Date();_x000D_
var currentDateTimeCentralTimeZone = new Date(estTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));_x000D_
var seconds = currentDateTimeCentralTimeZone.getSeconds();_x000D_
var minutes = currentDateTimeCentralTimeZone.getMinutes();_x000D_
var hours = currentDateTimeCentralTimeZone.getHours()+1;//new Date().getHours();_x000D_
var am_pm = currentDateTimeCentralTimeZone.getHours() >= 12 ? "PM" : "AM";_x000D_
_x000D_
if (hours < 10){_x000D_
hours = "0" + hours;_x000D_
}_x000D_
_x000D_
if (minutes < 10){_x000D_
minutes = "0" + minutes;_x000D_
}_x000D_
if (seconds < 10){_x000D_
seconds = "0" + seconds;_x000D_
}_x000D_
var mid='PM';_x000D_
if(hours==0){ //At 00 hours we need to show 12 am_x000D_
hours=12;_x000D_
}_x000D_
else if(hours>12)_x000D_
{_x000D_
hours=hours%12;_x000D_
mid='AM';_x000D_
}_x000D_
var x3 = hours+':'+minutes+':'+seconds +' '+am_pm_x000D_
// Add a leading zero to seconds value_x000D_
$("#sec").html(x3);_x000D_
},1000);_x000D_
_x000D_
_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<p class="date_time"><strong id="sec"></strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
background-image: url(/images/poster.png);
background-position: center;
background-position-y: 50px;
background-repeat: no-repeat;
I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):
Sub getData()
Dim Movie As Object
Dim scriptControl As Object
Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
scriptControl.Language = "JScript"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
.send
Set Movie = scriptControl.Eval("(" + .responsetext + ")")
.abort
With Sheets(2)
.Cells(1, 1).Value = Movie.Title
.Cells(1, 2).Value = Movie.Year
.Cells(1, 3).Value = Movie.Rated
.Cells(1, 4).Value = Movie.Released
.Cells(1, 5).Value = Movie.Runtime
.Cells(1, 6).Value = Movie.Director
.Cells(1, 7).Value = Movie.Writer
.Cells(1, 8).Value = Movie.Actors
.Cells(1, 9).Value = Movie.Plot
.Cells(1, 10).Value = Movie.Language
.Cells(1, 11).Value = Movie.Country
.Cells(1, 12).Value = Movie.imdbRating
End With
End With
End Sub
Multiple column search with dataframe:
frame[frame.filename.str.match('*.'+MetaData+'.*') & frame.file_path.str.match('C:\test\test.txt')]
GUI-driven approach: Open the docker desktop tool (that usually comes with Docker):
If both of your servers are using WHM, I think we can reduce the time to nil. Create your domain in the new server and set everything ready. Go to the previous server and delete the account corresponding to that domain. Until now I have got no errors by doing this and felt the update instantaneous. FYI I used hostgator hosting (both dedicated servers). And I really dont know why it is so. It's supposed to be not like that until the TTL is over.
May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..
JSON.parse("\"'\"")
I would advise against restricting the SecurityProtocol to TLS 1.1.
The recommended solution is to use
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls
Another option is add the following Registry key:
Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319
Value: SchUseStrongCrypto
It is worth noting that .NET 4.6 will use the correct protocol by default and does not require either solution.
It means that the algorithm is both big-O and big-Omega in the given function.
For example, if it is ?(n)
, then there is some constant k
, such that your function (run-time, whatever), is larger than n*k
for sufficiently large n
, and some other constant K
such that your function is smaller than n*K
for sufficiently large n
.
In other words, for sufficiently large n
, it is sandwiched between two linear functions :
For k < K
and n
sufficiently large, n*k < f(n) < n*K
If you still cannot solve the problem after you turn on the less secure apps
.
The other possible reason which might cause this error is you are not using gmail account.
- : user_name => '[email protected]' , # It can not be used since it is not a gmail address
+ : user_name => '[email protected]' , # since it's a gmail address
Refer to here.
Also, bear in mind that it might take some times to enable the less secure apps
. I have to do it several times (before it works, every time I access the link it will shows that it is off
) and wait for a while until it really work.
Using white-space: pre-line
allows you to input the text directly in the HTML with line breaks without having to use \n
If you use the innerText
property of the element via JavaScript on a non-pre element e.g. a <div>
, the \n
values will be replaced with <br>
in the DOM by default
innerText
: replaces \n
with <br>
innerHTML
, textContent
: require the use of styling white-space
It depends on how your applying the text, but there are a number of options
const node = document.createElement('div');
node.innerText = '\n Test \n One '
Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.
HTML:
<h1>Hello world!</h1>
Javascript (jQuery):
$(document).ready(function(){
$('h1').css({ 'width':'100%', 'text-align':'center' });
var h1 = $('h1').height();
var h = h1/2;
var w1 = $(window).height();
var w = w1/2;
var m = w - h
$('h1').css("margin-top",m + "px")
});
This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top
of the h1. The beauty of this method is that it works on multiple-line h1
s.
EDIT: I modified it so that it centered it every time the window is resized.
You can't refer to a property of an object before you have initialized that object; use an external variable.
var key1 = "it";
var obj = {
key1 : key1,
key2 : key1 + " works!"
};
Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).
Converting to unix timestamps makes doing date math easier in php:
$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );
// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
$thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}
When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.
Just building on what others have said. I found that the following works quite well.
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> input, string queryString)
{
if (string.IsNullOrEmpty(queryString))
return input;
int i = 0;
foreach (string propname in queryString.Split(','))
{
var subContent = propname.Split('|');
if (Convert.ToInt32(subContent[1].Trim()) == 0)
{
if (i == 0)
input = input.OrderBy(x => GetPropertyValue(x, subContent[0].Trim()));
else
input = ((IOrderedEnumerable<T>)input).ThenBy(x => GetPropertyValue(x, subContent[0].Trim()));
}
else
{
if (i == 0)
input = input.OrderByDescending(x => GetPropertyValue(x, subContent[0].Trim()));
else
input = ((IOrderedEnumerable<T>)input).ThenByDescending(x => GetPropertyValue(x, subContent[0].Trim()));
}
i++;
}
return input;
}
In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows. The database will supply a value for you.
INSERT INTO test.authors (
instance_id,host_object_id,check_type,is_raw_check,
current_check_attempt,max_check_attempts,state,state_type,
start_time,start_time_usec,end_time,end_time_usec,command_object_id,
command_args,command_line,timeout,early_timeout,execution_time,
latency,return_code,output,long_output,perfdata
) VALUES (
'1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
'2012-01-03 12:50:59','198963','21','',
'/usr/local/nagios/libexec/check_ping 5','30','0','4.04159',
'0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
'','rta=2.860000m=0%;80;100;0'
);
I found this workaround in the Android issue tracker: https://code.google.com/p/android/issues/detail?id=55863#c21
The trick (not a fix) is to isolating your .aar files into a subproject and adding your libs as artifacts:
configurations.create("default")
artifacts.add("default", file('somelib.jar'))
artifacts.add("default", file('someaar.aar'))
More info: Handling-transitive-dependencies-for-local-artifacts-jars-and-aar
printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).
So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.
For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.
(This goes for everyone else reading this too.)
http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/ shows that this works well:
var str = "abcd"
str = str.substringToIndex(1)
Renaming a column in MySQL :
ALTER TABLE mytable CHANGE current_column_name new_column_name DATATYPE;
display: block;
text-align: center;
If you are talking about an actual database (an mdf file) you would Attach
it
.sql
files are typically run using SQL Server Management Studio. They are basically saved SQL statements, so could be anything. You don't "import" them. More precisely, you "execute" them. Even though the script may indeed insert data.
Also, to expand on Jamie F's answer, don't run a SQL file against your database unless you know what it is doing. SQL scripts can be as dangerous as unchecked exe's
In that case, it's not needed. No extra threads will have been started up, you're not changing the exit code (which defaults to 0) - basically it's pointless.
When the docs say the method never returns normally, it means the subsequent line of code is effectively unreachable, even though the compiler doesn't know that:
System.exit(0);
System.out.println("This line will never be reached");
Either an exception will be thrown, or the VM will terminate before returning. It will never "just return".
It's very rare to be worth calling System.exit()
IME. It can make sense if you're writing a command line tool, and you want to indicate an error via the exit code rather than just throwing an exception... but I can't remember the last time I used it in normal production code.
In Toad 10.1.1.8 I use:
variable salida refcursor
exec MY_PKG.MY_PRC(1, 2, 3, :salida) -- 1, 2, 3 are params
print salida
Then, Execute as Script.
Today old-school include guards are as fast as a #pragma once. Even if the compiler doesn't treat them specially, it will still stop when it sees #ifndef WHATEVER and WHATEVER is defined. Opening a file is dirt cheap today. Even if there were to be an improvement, it would be in the order of miliseconds.
I simply just don't use #pragma once, as it has no benefit. To avoid clashing with other include guards I use something like: CI_APP_MODULE_FILE_H --> CI = Company Initials; APP = Application name; the rest is self-explanatory.
I tried everything on this page, I ended up using this solution:
brew uninstall --force brew-cask; brew untap $tap_name; brew update; brew cleanup; brew cask cleanup;
My situation was similar to the OP, however my issue was specifically caused by running sudo with brew cask, and then getting my password incorrect. After this, I was stuck with permissions preventing the installation.
Today date:
$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });
15 days from today:
$( ".selector" ).datepicker( "setDate", 15);
// Or on the init
$( ".selector" ).datepicker({ defaultDate: 15 });
In my case, this was the best solution I found:
snprintf(str, sizeof str, "%s%c", str, c);
To submit the timezone offset as an HTTP header on AJAX requests with jQuery
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-TZ-Offset", -new Date().getTimezoneOffset()/60);
}
});
You can also do something similar to get the actual time zone name by using moment.tz.guess();
from http://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/
BSTR
to std::wstring
:
// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));
std::wstring
to BSTR
:
// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());
Doc refs:
You can use System.Windows.Forms.Clipboard.SetText(...)
.
I finally went for a similar solution to the one that Sascha provided, however with some little adjusting, since I'm setting the cookies explicitly in PHP:
// excecute this code if user has not authorized the application yet
// $facebook object must have been created before
$accessToken = $_COOKIE['access_token']
if ( empty($accessToken) && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') ) {
$accessToken = $facebook->getAccessToken();
$redirectUri = 'https://URL_WHERE_APP_IS_LOCATED?access_token=' . $accessToken;
} else {
$redirectUri = 'https://apps.facebook.com/APP_NAMESPACE/';
}
// generate link to auth dialog
$linkToOauthDialog = $facebook->getLoginUrl(
array(
'scope' => SCOPE_PARAMS,
'redirect_uri' => $redirectUri
)
);
echo '<script>window.top.location.href="' . $linkToOauthDialog . '";</script>';
What this does is check if the cookie is available when the browser is safari. In the next step, we are on the application domain, namely the URI provided as URL_WHERE_APP_IS_LOCATED above.
if (isset($_GET['accessToken'])) {
// cookie has a lifetime of only 10 seconds, so that after
// authorization it will disappear
setcookie("access_token", $_GET['accessToken'], 10);
} else {
// depending on your application specific requirements
// redirect, call or execute authorization code again
// with the cookie now set, this should return FB Graph results
}
So after being redirecting to the application domain, a cookie is set explicitly, and I redirect the user to the authorization process.
In my case (since I'm using CakePHP but it should work fine with any other MVC framework) I'm calling the login action again where the FB authorization is executed another time, and this time it succeeds due to the existing cookie.
After having authorized the app once, I didn't have any more problems using the app with Safari (5.1.6)
Hope that might help anyone.
You could alternatively use jstack (Included with JDK) to take a thread dump and write the output wherever you want. Is that not available in a unix environment?
jstack PID > outfile
I see we have the same problem here, I have the same error. I want to write this for the future user who will experience the same error. After making changes to your class Snippet model like @Burhan Khalid said, you must migrate tables:
python manage.py makemigrations snippets
python manage.py migrate
And that should resolve the error. Enjoy.
Another option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.
em is the typography unit of font width. one em in a 16-point typeface is 16 points
This is how I did it.
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SAP Multiple Entries");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(10,10,10,10));
frame.setLayout(new FlowLayout());
frame.setSize(512, 512);
JButton button = new JButton("Select File");
button.setPreferredSize(new Dimension(256, 256));
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
keep = selectedFile.getAbsolutePath();
// System.out.println(keep);
//out.println(file.flag);
if(file.flag==true) {
JOptionPane.showMessageDialog(null, "It is done! \nLocation: " + file.path , "Success Message", JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "failure", "not okay", JOptionPane.INFORMATION_MESSAGE);
}
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
You have to do a result.next() before you can access the result. It's a very common idiom to do
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
int foo = rs.getInt(1);
...
}
Maybe you can use pandas crosstab function
test5 = pd.crosstab(index=faultdf['Site Name'], columns=faultdf[''Abuse/NFF''])
test5.plot(kind='bar', stacked=True)
You can pass lists just like other types:
l = [1,2,3]
def stuff(a):
for x in a:
print a
stuff(l)
This prints the list l. Keep in mind lists are passed as references not as a deep copy.
Use boost::filesystem, that will give you a portable way of doing those kinds of things and abstract away all ugly details for you.
Other methods were mentioned so let us please acknowledge that, at the time of writing, we are in the 21st century. Let's park the local bus browser opening, and fly with an XMLHTTP GET request (XHR GET for short).
XHR is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser's JavaScript environment
It's a fast method for retrieving data that doesn't require opening a browser. The server response can be read into an HTMLDocument and the process of grabbing the table continued from there.
Note that javascript rendered/dynamically added content will not be retrieved as there is no javascript engine running (which there is in a browser).
In the below code, the table is grabbed by its id cr1
.
In the helper sub, WriteTable
, we loop the columns (td
tags) and then the table rows (tr
tags), and finally traverse the length of each table row, table cell by table cell. As we only want data from columns 1 and 8, a Select Case
statement is used specify what is written out to the sheet.
Sample webpage view:
Sample code output:
VBA:
Option Explicit
Public Sub GetRates()
Dim html As HTMLDocument, hTable As HTMLTable '<== Tools > References > Microsoft HTML Object Library
Set html = New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://uk.investing.com/rates-bonds/financial-futures", False
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" 'to deal with potential caching
.send
html.body.innerHTML = .responseText
End With
Application.ScreenUpdating = False
Set hTable = html.getElementById("cr1")
WriteTable hTable, 1, ThisWorkbook.Worksheets("Sheet1")
Application.ScreenUpdating = True
End Sub
Public Sub WriteTable(ByVal hTable As HTMLTable, Optional ByVal startRow As Long = 1, Optional ByVal ws As Worksheet)
Dim tSection As Object, tRow As Object, tCell As Object, tr As Object, td As Object, r As Long, C As Long, tBody As Object
r = startRow: If ws Is Nothing Then Set ws = ActiveSheet
With ws
Dim headers As Object, header As Object, columnCounter As Long
Set headers = hTable.getElementsByTagName("th")
For Each header In headers
columnCounter = columnCounter + 1
Select Case columnCounter
Case 2
.Cells(startRow, 1) = header.innerText
Case 8
.Cells(startRow, 2) = header.innerText
End Select
Next header
startRow = startRow + 1
Set tBody = hTable.getElementsByTagName("tbody")
For Each tSection In tBody
Set tRow = tSection.getElementsByTagName("tr")
For Each tr In tRow
r = r + 1
Set tCell = tr.getElementsByTagName("td")
C = 1
For Each td In tCell
Select Case C
Case 2
.Cells(r, 1).Value = td.innerText
Case 8
.Cells(r, 2).Value = td.innerText
End Select
C = C + 1
Next td
Next tr
Next tSection
End With
End Sub
One more difference that I can figure out is:
We can not use Dictionary<KT,VT> (generics) with web services. The reason is no web service standard supports the generics standard.
The problem is not in Django settings, but in the date passed to the model. Here's how a timezone-aware object looks like:
>>> from django.utils import timezone
>>> import pytz
>>> timezone.now()
datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=pytz.UTC)
And here's a naive object:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2013, 11, 20, 20, 9, 26, 423063)
So if you are passing email date anywhere (and it eventually gets to some model), just use Django's now()
. If not, then it's probably an issue with an existing package that fetches date without timezone and you can patch the package, ignore the warning or set USE_TZ to False.
From Python Documentation:
An except clause may name multiple exceptions as a parenthesized tuple, for example
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
Or, for Python 2 only:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as
.
This video shows how to update a fork directly from GitHub
Steps:
Pull Requests
.New Pull Request
. By default, GitHub will compare the original with your fork, and there shouldn’t be anything to compare if you didn’t make any changes.switching the base
. Now GitHub will compare your fork with the original, and you should see all the latest changes.Create a pull request
for this comparison and assign a predictable name to your pull request (e.g., Update from original).Create pull request
.Merge pull request
and finally Confirm
merge. If your fork didn’t have any changes, you will be able to merge it automatically.Can you set the password to the phpmyadmin here
http://localhost/security/index.php
One way
// join type can be inner, left, right, fullouter
val mergedDf = df1.join(df2, Seq("keyCol"), "inner")
// keyCol can be multiple column names seperated by comma
val mergedDf = df1.join(df2, Seq("keyCol1", "keyCol2"), "left")
Another way
import spark.implicits._
val mergedDf = df1.as("d1").join(df2.as("d2"), ($"d1.colName" === $"d2.colName"))
// to select specific columns as output
val mergedDf = df1.as("d1").join(df2.as("d2"), ($"d1.colName" === $"d2.colName")).select($"d1.*", $"d2.anotherColName")
Make a state machine that operates on one basic principle: is the current character a number.
Optimizations are possible.
npx should come with npm 5.2+, and you have node 5.6 .. I found that when I install node using nvm for Windows, it doesn't download npx. so just install npx globally:
npm i -g npx
In Linux or Mac OS, if you found any permission related errors use sudo before it.
sudo npm i -g npx
The accepted answer doesn't seem to work if you unplug the network cable. Or the server crashes. Or your router crashes. Or if you forget to pay your internet bill. Set the TCP keep-alive options for better reliability.
public static class SocketExtensions
{
public static void SetSocketKeepAliveValues(this Socket instance, int KeepAliveTime, int KeepAliveInterval)
{
//KeepAliveTime: default value is 2hr
//KeepAliveInterval: default value is 1s and Detect 5 times
//the native structure
//struct tcp_keepalive {
//ULONG onoff;
//ULONG keepalivetime;
//ULONG keepaliveinterval;
//};
int size = Marshal.SizeOf(new uint());
byte[] inOptionValues = new byte[size * 3]; // 4 * 3 = 12
bool OnOff = true;
BitConverter.GetBytes((uint)(OnOff ? 1 : 0)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)KeepAliveTime).CopyTo(inOptionValues, size);
BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo(inOptionValues, size * 2);
instance.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
}
// ...
Socket sock;
sock.SetSocketKeepAliveValues(2000, 1000);
The time value sets the timeout since data was last sent. Then it attempts to send and receive a keep-alive packet. If it fails it retries 10 times (number hardcoded since Vista AFAIK) in the interval specified before deciding the connection is dead.
So the above values would result in 2+10*1 = 12 second detection. After that any read / wrtie / poll operations should fail on the socket.
If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:
old:
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"
new:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
pre-android x:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
For more information, it's updated documentation is located here.
For adding background icon always before text when length of text is not known in advance.
.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}
You can't get the text after the hash mark. It is not sent to the server in a request.
you could use an onchange event to trigger a validation and then you can display a toast if this is enough for you
This has been fixed
http://guides.rubygems.org/ssl-certificate-update/
Now that RubyGems 2.6.x has been released, you can manually update to this version.
Download https://rubygems.org/downloads/rubygems-update-2.6.7.gem
Please download the file in a directory that you can later point to (eg. the root of your harddrive C:)
Now, using your Command Prompt:
C:\>gem install --local C:\rubygems-update-2.6.7.gem
C:\>update_rubygems --no-ri --no-rdoc
After this, gem --version should report the new update version.
You can now safely uninstall rubygems-update gem:
C:\>gem uninstall rubygems-update -x
Another answer for this would be
^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{2}|)$
This will match a string of:
Each or which can have a decimal place which must be followed by 2 numbers (.\d{2}|)
var form = $("<form/>",
{ action:'/myaction' }
);
form.append(
$("<input>",
{ type:'text',
placeholder:'Keywords',
name:'keyword',
style:'width:65%' }
)
);
form.append(
$("<input>",
{ type:'submit',
value:'Search',
style:'width:30%' }
)
);
$("#someDivId").append(form);
Actually it's quite different. DOUBLE causes rounding issues. And if you do something like 0.1 + 0.2
it gives you something like 0.30000000000000004
. I personally would not trust financial data that uses floating point math. The impact may be small, but who knows. I would rather have what I know is reliable data than data that were approximated, especially when you are dealing with money values.
You could also use a session for passing small bits of info. You will need to have session_start(); at the top of the PHP pages that use the session else the variables will not be accessable
page1.php
<?php
session_start();
$_SESSION['superhero'] = "batman";
?>
<a href="page2.php" title="">Go to the other page</a>
page2.php
<?php
session_start(); // this NEEDS TO BE AT THE TOP of the page before any output etc
echo $_SESSION['superhero'];
?>
In ~/Views/ViewStart.cshtml
:
@{
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}
and in the controller:
public ActionResult Index()
{
return View();
}