Just export you view and you will have all SQL need to make some change on it.
Just need to add your change in SQL query for the view and change :
CREATE for CREATE OR REPLACE
What is happening is that stock_list.toArray()
is creating an Object[]
rather than a String[]
and hence the typecast is failing1.
The correct code would be:
String [] stockArr = stockList.toArray(new String[stockList.size()]);
or even
String [] stockArr = stockList.toArray(new String[0]);
For more details, refer to the javadocs for the two overloads of List.toArray
.
The latter version uses the zero-length array to determine the type of the result array. (Surprisingly, it is faster to do this than to preallocate ... at least, for recent Java releases. See https://stackoverflow.com/a/4042464/139985 for details.)
From a technical perspective, the reason for this API behavior / design is that an implementation of the List<T>.toArray()
method has no information of what the <T>
is at runtime. All it knows is that the raw element type is Object
. By contrast, in the other case, the array parameter gives the base type of the array. (If the supplied array is big enough to hold the list elements, it is used. Otherwise a new array of the same type and a larger size is allocated and returned as the result.)
1 - In Java, an Object[]
is not assignment compatible with a String[]
. If it was, then you could do this:
Object[] objects = new Object[]{new Cat("fluffy")};
Dog[] dogs = (Dog[]) objects;
Dog d = dogs[0]; // Huh???
This is clearly nonsense, and that is why array types are not generally assignment compatible.
The Apache iBatis solution worked like a charm.
The script example I used was exactly the script I was running from MySql workbench.
There is an article with examples here: https://www.tutorialspoint.com/how-to-run-sql-script-using-jdbc#:~:text=You%20can%20execute%20.,to%20pass%20a%20connection%20object.&text=Register%20the%20MySQL%20JDBC%20Driver,method%20of%20the%20DriverManager%20class.
This is what I did:
pom.xml dependency
<!-- IBATIS SQL Script runner from Apache (https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-core) -->
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-core</artifactId>
<version>3.0</version>
</dependency>
Code to execute script:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.jdbc.ScriptRunner;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SqlScriptExecutor {
public static void executeSqlScript(File file, Connection conn) throws Exception {
Reader reader = new BufferedReader(new FileReader(file));
log.info("Running script from file: " + file.getCanonicalPath());
ScriptRunner sr = new ScriptRunner(conn);
sr.setAutoCommit(true);
sr.setStopOnError(true);
sr.runScript(reader);
log.info("Done.");
}
}
For the <tr>
's just set
tr {
line-height: 25px;
min-height: 25px;
height: 25px;
}
It works with bootstrap also. For the 100%
height, 100%
must be 100% of something. Therefore, you must define a fixed height for one of the containers, or the body. I guess you want the entire page to be 100%, so (example) :
body {
height: 700px;
}
.table100, .row, .container, .table-responsive, .table-bordered {
height: 100%;
}
A workaround not to set a static height is by forcing the height in code according to the viewport :
$('body').height(document.documentElement.clientHeight);
all the above in this fiddle -> http://jsfiddle.net/LZuJt/
Note : I do not care that you have 25%
height on #description
, and 100%
height on table. Guess it is just an example. And notice that clientHeight
is not right since the documentElement is an iframe, but you'll get the picture in your own projekt :)
Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;
my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length
Or, you can iterate over this array by adding the following script:
for element in "${my_array[@]}"
do
echo "${element}"
done
Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).
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);
}
Yes, you can do that like this:
BEGIN
DECLARE @Results TABLE (Tid INT PRIMARY KEY);
INSERT @Results
EXEC Procedure2 [parameters];
SET @total 1;
END
SELECT @total
When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:
GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1
Host: stackoverflow.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate,sdch
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: <cookie data removed>
Pragma: no-cache
Cache-Control: no-cache
These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.
In PHP, all this information is stored in the $_SERVER
array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.
<pre><?php print_r($_SERVER); ?></pre>
This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT']
to get the operating system and browser.
One thing you should know is $ prefix refers to an Angular Method, $$ prefixes refers to angular methods that you should avoid using.
below is an example template and its controllers, we'll explore how $broadcast/$on can help us achieve what we want.
<div ng-controller="FirstCtrl">
<input ng-model="name"/>
<button ng-click="register()">Register </button>
</div>
<div ng-controller="SecondCtrl">
Registered Name: <input ng-model="name"/>
</div>
The controllers are
app.controller('FirstCtrl', function($scope){
$scope.register = function(){
}
});
app.controller('SecondCtrl', function($scope){
});
My question to you is how do you pass the name to the second controller when a user clicks register? You may come up with multiple solutions but the one we're going to use is using $broadcast and $on.
$broadcast vs $emit
Which should we use? $broadcast will channel down to all the children dom elements and $emit will channel the opposite direction to all the ancestor dom elements.
The best way to avoid deciding between $emit or $broadcast is to channel from the $rootScope and use $broadcast to all its children. Which makes our case much easier since our dom elements are siblings.
Adding $rootScope and lets $broadcast
app.controller('FirstCtrl', function($rootScope, $scope){
$scope.register = function(){
$rootScope.$broadcast('BOOM!', $scope.name)
}
});
Note we added $rootScope and now we're using $broadcast(broadcastName, arguments). For broadcastName, we want to give it a unique name so we can catch that name in our secondCtrl. I've chosen BOOM! just for fun. The second arguments 'arguments' allows us to pass values to the listeners.
Receiving our broadcast
In our second controller, we need to set up code to listen to our broadcast
app.controller('SecondCtrl', function($scope){
$scope.$on('BOOM!', function(events, args){
console.log(args);
$scope.name = args; //now we've registered!
})
});
It's really that simple. Live Example
Other ways to achieve similar results
Try to avoid using this suite of methods as it is neither efficient nor easy to maintain but it's a simple way to fix issues you might have.
You can usually do the same thing by using a service or by simplifying your controllers. We won't discuss this in detail but I thought I'd just mention it for completeness.
Lastly, keep in mind a really useful broadcast to listen to is '$destroy' again you can see the $ means it's a method or object created by the vendor codes. Anyways $destroy is broadcasted when a controller gets destroyed, you may want to listen to this to know when your controller is removed.
From the @Tgr's comment, there is an online tool : https://codetabs.com/count-loc/count-loc-online.html
Use:
dt.Columns["Name"].ColumnName = "xyz";
dt.AcceptChanges();
or
dt.Columns[0].ColumnName = "xyz";
dt.AcceptChanges();
The short answer is no. The long answer is yes. :-)
Markdown was designed to allow people to write simple, readable text that could be easily converted to a simple HTML markup. It doesn't really do document layout. For example, there's no real way to align an image to the right or left. As to your question, there's no markdown command to include a single link from one file to another in any version of markdown (so far as I know).
The closest you could come to this functionality is Pandoc. Pandoc allows you to merge files as a part of the transformation, which allows you to easily render multiple files into a single output. For example, if you were creating a book, then you could have chapters like this:
01_preface.md
02_introduction.md
03_why_markdown_is_useful.md
04_limitations_of_markdown.md
05_conclusions.md
You can merge them by doing executing this command within the same directory:
pandoc *.md > markdown_book.html
Since pandoc will merge all the files prior to doing the translation, you can include your links in the last file like this:
01_preface.md
02_introduction.md
03_why_markdown_is_useful.md
04_limitations_of_markdown.md
05_conclusions.md
06_links.md
So part of your 01_preface.md
could look like this:
I always wanted to write a book with [markdown][mkdnlink].
And part of your 02_introduction.md
could look like this:
Let's start digging into [the best text-based syntax][mkdnlink] available.
As long as your last file includes the line:
[mkdnlink]: http://daringfireball.net/projects/markdown
...the same command used before will perform the merge and conversion while including that link throughout. Just make sure you leave a blank line or two at the beginning of that file. The pandoc documentation says that it adds a blank line between files that are merged this way, but this didn't work for me without the blank line.
This question has an open bounty worth +100 reputation from Hidden Hobbes ending in 6 days. Inventive use of viewport units to obtain a flexible CSS only solution.
You opened a bounty on this question for a CSS only solution, so I will give it a try. My solution to a problem like this is to use a fixed ratio to decide the height and width of the video. I usually use Bootstrap, but I extracted the necessary CSS from there to make it work without. This is a code I have used earlier to among other things center an embeded video with the correct ratio. It should work for <video>
and <img>
elements too It's the top one that is relevant here, but I gave you the other two as well since I already had them laying around. Best of luck! :)
.embeddedContent.centeredContent {_x000D_
margin: 0px auto;_x000D_
}_x000D_
.embeddedContent.rightAlignedContent {_x000D_
margin: auto 0px auto auto;_x000D_
}_x000D_
.embeddedContent > .embeddedInnerWrapper {_x000D_
position:relative;_x000D_
display: block;_x000D_
padding: 0;_x000D_
padding-top: 42.8571%; /* 21:9 ratio */_x000D_
}_x000D_
.embeddedContent > .embeddedInnerWrapper > iframe {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
border: 0;_x000D_
}_x000D_
.embeddedContent {_x000D_
max-width: 300px;_x000D_
}_x000D_
.box1text {_x000D_
background-color: red;_x000D_
}_x000D_
/* snippet from Bootstrap */_x000D_
.container {_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
}_x000D_
.col-md-12 {_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
Testing ratio AND left/right/center align:<br />_x000D_
<div class="box1text">_x000D_
<div class="embeddedContent centeredContent">_x000D_
<div class="embeddedInnerWrapper">_x000D_
<iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&jqoemcache=eE9xf" width="425"></iframe>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
Testing ratio AND left/right/center align:<br />_x000D_
<div class="box1text">_x000D_
<div class="embeddedContent rightAlignedContent">_x000D_
<div class="embeddedInnerWrapper">_x000D_
<iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&jqoemcache=eE9xf" width="425"></iframe>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
Testing ratio AND left/right/center align:<br />_x000D_
<div class="box1text">_x000D_
<div class="embeddedContent">_x000D_
<div class="embeddedInnerWrapper">_x000D_
<iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&jqoemcache=eE9xf" width="425"></iframe>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
You can use the decompose method in bs4:
soup = bs4.BeautifulSoup('<body><a href="http://example.com/">I linked to <i>example.com</i></a></body>')
for a in soup.find('a').children:
if isinstance(a,bs4.element.Tag):
a.decompose()
print soup
Out: <html><body><a href="http://example.com/">I linked to </a></body></html>
This is an important question. The SSL 3 protocol (1996) is irreparably broken by the Poodle attack published 2014. The IETF have published "SSLv3 MUST NOT be used". Web browsers are ditching it. Mozilla Firefox and Google Chrome have already done so.
Two excellent tools for checking protocol support in browsers are SSL Lab's client test and https://www.howsmyssl.com/ . The latter does not require Javascript, so you can try it from .NET's HttpClient:
// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");
File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);
// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");
The result is damning:
Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.
That's concerning. It's comparable to 2006's Internet Explorer 7.
To list exactly which protocols a HTTP client supports, you can try the version-specific test servers below:
var test_servers = new Dictionary<string, string>();
test_servers["SSL 2"] = "https://www.ssllabs.com:10200";
test_servers["SSL 3"] = "https://www.ssllabs.com:10300";
test_servers["TLS 1.0"] = "https://www.ssllabs.com:10301";
test_servers["TLS 1.1"] = "https://www.ssllabs.com:10302";
test_servers["TLS 1.2"] = "https://www.ssllabs.com:10303";
var supported = new Func<string, bool>(url =>
{
try { return new HttpClient().GetAsync(url).Result.IsSuccessStatusCode; }
catch { return false; }
});
var supported_protocols = test_servers.Where(server => supported(server.Value));
Console.WriteLine(string.Join(", ", supported_protocols.Select(x => x.Key)));
I'm using .NET Framework 4.6.2. I found HttpClient supports only SSL 3 and TLS 1.0. That's concerning. This is comparable to 2006's Internet Explorer 7.
Update: It turns HttpClient does support TLS 1.1 and 1.2, but you have to turn them on manually at System.Net.ServicePointManager.SecurityProtocol
. See https://stackoverflow.com/a/26392698/284795
I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?
You can use this simple loop to get all the element names and their values.
var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
var fieldName = document.FormName.elements[i].name;
var fieldValue = document.FormName.elements[i].value;
// use the fields, put them in a array, etc.
// or, add them to a key-value pair strings,
// as in regular POST
params += fieldName + '=' + fieldValue + '&';
}
// send the 'params' variable to web service, GET request, ...
// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]
Other more useful commands here with explanation: Git Guide
Define your own parse format string to use.
string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
In case you got a datetime having milliseconds, use the following formatString
string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);
Thanks
For example to execute from terminal (Ubuntu Linux) or even (Windows console) a java file called filex.jar use this command:
java -jar filex.jar
The file will execute in terminal.
in your main layout put this in the head at the bottom of everything
@stack('styles')
and in your view put this
@push('styles')
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
@endpush
basically a placeholder so the links will appear on your main layout, and you can see custom css files on different pages
As far as I know, Apache supports SNI since Version 2.2.12 Sadly the documentation does not yet reflect that change.
Go for http://wiki.apache.org/httpd/NameBasedSSLVHostsWithSNI until that is finished
Try writting the lambda with the same conditions as the delegate. like this:
List<AnalysisObject> analysisObjects =
analysisObjectRepository.FindAll().Where(
(x =>
(x.ID == packageId)
|| (x.Parent != null && x.Parent.ID == packageId)
|| (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
).ToList();
My answer does not require Javascript and only relies on CSS3 (available in most modern browsers). I personally like it very much if design is not relying on Javascript too much.
My answer is a "pure CSS3 , no Javascript required"-solution:
The solution as can be seen here (http://jsfiddle.net/uNF3Z/16/) uses the following additions to the CSS styles (which make use of the @media
query of CSS3 which)
@media all and (min-width: 50px) { body { font-size:0.1em; } }
@media all and (min-width: 100px) { body { font-size:0.2em; } }
@media all and (min-width: 200px) { body { font-size:0.4em; } }
@media all and (min-width: 300px) { body { font-size:0.6em; } }
@media all and (min-width: 400px) { body { font-size:0.8em; } }
@media all and (min-width: 500px) { body { font-size:1.0em; } }
@media all and (min-width: 600px) { body { font-size:1.2em; } }
@media all and (min-width: 700px) { body { font-size:1.4em; } }
@media all and (min-width: 800px) { body { font-size:1.6em; } }
@media all and (min-width: 900px) { body { font-size:1.8em; } }
@media all and (min-width: 1000px) { body { font-size:2.0em; } }
@media all and (min-width: 1100px) { body { font-size:2.2em; } }
@media all and (min-width: 1200px) { body { font-size:2.4em; } }
@media all and (min-width: 1300px) { body { font-size:2.6em; } }
@media all and (min-width: 1400px) { body { font-size:2.8em; } }
@media all and (min-width: 1500px) { body { font-size:3.0em; } }
@media all and (min-width: 1500px) { body { font-size:3.2em; } }
@media all and (min-width: 1600px) { body { font-size:3.4em; } }
@media all and (min-width: 1700px) { body { font-size:3.6em; } }
What this in effect causes is that the font-size is adjusted to the available screen width. This adjustment is done in steps of 100px (which is finegrained enough for most purposes) and covers a maximum screen width of 1700px which I reckon to be amply (2013) and can by adding further lines be further improved.
A side benefit is that the adjustment of the font-size is occuring at each resize. This dynamic adjustment (because for instance the browser windows is resized) might not yet be covered by the Javascript based solution.
Use the Distinct operator:
var idList = yourList.Select(x=> x.ID).Distinct();
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
I think that the the align="center"
aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.
text-align
is doing a similar sort of thing.
left:50%
is ignored unless you set the div's position to be something like relative or absolute.
The generally accepted methods is to use the following properties
width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;
the margins being auto means they grow/shrink to match the browser window (or parent div)
UPDATE
Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.
margin:0 auto;
this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.
You need to tell scp
where to send the file. In your command that is not working:
scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~
You have not mentioned a remote server. scp
uses :
to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c
from the host C
to your local home directory.
The correct upload command, based on your comments, should be something like:
C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:
If you are running the command from your home directory, you can use a relative path:
C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:
You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:
C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/
The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203
We had the same error even though the user was properly mapped to the login.
After trying to delete the user it was discovered that a few SPs contained "with execute as" that user.
The issue was solved by dropping those SPs, dropping the user, recreating the user linked to login, and recreating the SPs.
Possibly it got in this state from restoring from backup (during a time when the related login didn't exist) or bulk schema syncing (if its possible to create an SP with execute as even though the user doesn't exist. Could also have been related to this answer.
Based on this questions answer I implemented a class you can use to read a file synchronously line-by-line with fs.readSync()
. You can make this "pause" and "resume" by using a Q
promise (jQuery
seems to require a DOM so cant run it with nodejs
):
var fs = require('fs');
var Q = require('q');
var lr = new LineReader(filenameToLoad);
lr.open();
var promise;
workOnLine = function () {
var line = lr.readNextLine();
promise = complexLineTransformation(line).then(
function() {console.log('ok');workOnLine();},
function() {console.log('error');}
);
}
workOnLine();
complexLineTransformation = function (line) {
var deferred = Q.defer();
// ... async call goes here, in callback: deferred.resolve('done ok'); or deferred.reject(new Error(error));
return deferred.promise;
}
function LineReader (filename) {
this.moreLinesAvailable = true;
this.fd = undefined;
this.bufferSize = 1024*1024;
this.buffer = new Buffer(this.bufferSize);
this.leftOver = '';
this.read = undefined;
this.idxStart = undefined;
this.idx = undefined;
this.lineNumber = 0;
this._bundleOfLines = [];
this.open = function() {
this.fd = fs.openSync(filename, 'r');
};
this.readNextLine = function () {
if (this._bundleOfLines.length === 0) {
this._readNextBundleOfLines();
}
this.lineNumber++;
var lineToReturn = this._bundleOfLines[0];
this._bundleOfLines.splice(0, 1); // remove first element (pos, howmany)
return lineToReturn;
};
this.getLineNumber = function() {
return this.lineNumber;
};
this._readNextBundleOfLines = function() {
var line = "";
while ((this.read = fs.readSync(this.fd, this.buffer, 0, this.bufferSize, null)) !== 0) { // read next bytes until end of file
this.leftOver += this.buffer.toString('utf8', 0, this.read); // append to leftOver
this.idxStart = 0
while ((this.idx = this.leftOver.indexOf("\n", this.idxStart)) !== -1) { // as long as there is a newline-char in leftOver
line = this.leftOver.substring(this.idxStart, this.idx);
this._bundleOfLines.push(line);
this.idxStart = this.idx + 1;
}
this.leftOver = this.leftOver.substring(this.idxStart);
if (line !== "") {
break;
}
}
};
}
Right now, there is no option to select the parent of an element in CSS (not even CSS3). But with CSS4, the most important news in the current W3C draft is the support for the parent selector.
$ul li:hover{
background: #fff;
}
Using the above, when hovering an list element, the whole unordered list will be highlighted by adding a white background to it.
Official documentation: https://www.w3.org/TR/2011/WD-selectors4-20110929/#overview (last row).
if you install putty on win32 you get an pscp (putty scp).
so you can use the os.system hack on win32 too.
(and you can use the putty-agent for key-managment)
sorry it is only a hack (but you can wrap it in a python class)
You can also use DOM to do so. Say you have a function you call like this:
function disable_scroll() {
document.body.style.overflow="hidden";
}
And that's all there is to it! Hope this helps in addition to all the other answers!
I had the same problem just now. I've fixed mine by adding a namespace on the app name. Hope someone find this helpful.
apps.py
from django.apps import AppConfig
class SalesClientConfig(AppConfig):
name = 'portal.sales_client'
verbose_name = 'Sales Client'
If you are using React, then with latest version of react hooks, you could use this.
// Usage
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
This method is easy to understand and works fine. The argument to the script ($1
) is a reference (tag, hash, ...) to the commit starting from which you want to keep your history.
#!/bin/bash
git checkout --orphan temp $1 # create a new branch without parent history
git commit -m "Truncated history" # create a first commit on this branch
git rebase --onto temp $1 master # now rebase the part of master branch that we want to keep onto this branch
git branch -D temp # delete the temp branch
# The following 2 commands are optional - they keep your git repo in good shape.
git prune --progress # delete all the objects w/o references
git gc --aggressive # aggressively collect garbage; may take a lot of time on large repos
NOTE that old tags will still remain present; so you might need to remove them manually
remark: I know this is almost the same aswer as @yoyodin, but there are some important extra commands and informations here. I tried to edit the answer, but since it is a substantial change to @yoyodin's answer, my edit was rejected, so here's the information!
Watch for filenames in italic
Note that, the file name on the tab is formatted in italic if it has been opened in Preview Mode
.
Quickly take a file out of Preview Mode
To keep the file always available in VSCode editor (that is, to take it out of Preview Mode
into normal mode), you can double-click on the tab. Then, you will notice the name becomes non-italic.
Feature or bug?
I believe Preview Mode is helpful especially when you have limited screen space and need to check many files.
A char can hold a single character only, a character literal is a single character in single quote, i.e. '&'
- if you have more characters than one you want to use a string, for that you have to use double quotes:
case "&&":
If you are a intellij IDE user, you can use shortcut key Alt+Enter
and then choose Wrap with Center
and then add textAlign: TextAlign.center
You can have a look at my library here. Under the documentation section, you will find how to import a data table.
You just have to write
using (var doc = new SpreadsheetDocument(@"C:\OpenXmlPackaging.xlsx")) {
Worksheet sheet1 = doc.Worksheets.Add("My Sheet");
sheet1.ImportDataTable(ds.Tables[0], "A1", true);
}
Hope it helps!
You might be best starting with reading this post by Dan Abramov where he discusses various implementations of Flux and their trade-offs at the time he was writing redux: The Evolution of Flux Frameworks
Secondly that motivations page you link to does not really discuss the motivations of Redux so much as the motivations behind Flux (and React). The Three Principles is more Redux specific though still does not deal with the implementation differences from the standard Flux architecture.
Basically, Flux has multiple stores that compute state change in response to UI/API interactions with components and broadcast these changes as events that components can subscribe to. In Redux, there is only one store that every component subscribes to. IMO it feels at least like Redux further simplifies and unifies the flow of data by unifying (or reducing, as Redux would say) the flow of data back to the components - whereas Flux concentrates on unifying the other side of the data flow - view to model.
My 'idiomatic one-liner' solution:
int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();
Have no idea why a solution that uses StringUtils is accepted.
you can redirect stderr.
more explanation here, but having a command like:
MyCommand >log.txt 2>errors.txt
should grab the data you are looking for.
Also, as a trick, Windows bypasses that limitation if the path is prefixed with \\?\
(msdn)
Another trick if you have a root or destination that starts with a long path, perhaps SUBST
will help:
SUBST Q: "C:\Documents and Settings\MyLoginName\My Documents\MyStuffToBeCopied"
Xcopy Q:\ "d:\Where it needs to go" /s /e
SUBST Q: /D
If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:
Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)
Hope that helps someone.
I tried CancellationTokenSource
but i can't do this. And i did do this with my own way. And it works.
namespace Blokick.Provider
{
public class SignalRConnectProvider
{
public SignalRConnectProvider()
{
}
public bool IsStopRequested { get; set; } = false; //1-)This is important and default `false`.
public async Task<string> ConnectTab()
{
string messageText = "";
for (int count = 1; count < 20; count++)
{
if (count == 1)
{
//Do stuff.
}
try
{
//Do stuff.
}
catch (Exception ex)
{
//Do stuff.
}
if (IsStopRequested) //3-)This is important. The control of the task stopping request. Must be true and in inside.
{
return messageText = "Task stopped."; //4-) And so return and exit the code and task.
}
if (Connected)
{
//Do stuff.
}
if (count == 19)
{
//Do stuff.
}
}
return messageText;
}
}
}
And another class of the calling the method:
namespace Blokick.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MessagePerson : ContentPage
{
SignalRConnectProvider signalR = new SignalRConnectProvider();
public MessagePerson()
{
InitializeComponent();
signalR.IsStopRequested = true; // 2-) And this. Make true if running the task and go inside if statement of the IsStopRequested property.
if (signalR.ChatHubProxy != null)
{
signalR.Disconnect();
}
LoadSignalRMessage();
}
}
}
The accepted answer works well and one can also just use the
If Exists (...) Then ... End If;
syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert
One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!
It is useful to think of MIME in the context of the client-server model. Clients and servers communicate over what is known as the HTTP protocol. In a http request or response, we can have a body. The Content-type or MIME type specifies what is the type of the body, like text/javascript
or something else like audio, video, etc.
However, MIME types are not limited just to HTTP.
As the name suggests, MIME stands for Multipurpose Internet Mail Extensions. Originally, SMTP only supported ascii-encodings. However, there as a need for more. We could use MIME to slap a label on the content being transmitted or received.
Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE
in your AndroidManifest.xml for this to work.
_ how could I have found myself the information I needed in the online documentation?
You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.
Don't use NULL
, C++ allows you to use the unadorned 0
instead:
previous = 0;
next = 0;
And, as at C++11, you generally shouldn't be using either NULL
or 0
since it provides you with nullptr
of type std::nullptr_t
, which is better suited to the task.
easy:
launching activity (onclick handler)
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
on the new activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
and add your new activity in the AndroidManifest.xml:
<activity android:label="@string/app_name" android:name="NextActivity"/>
I suggest reading the git man page to fully understand how ignore work, and in the future you'll thank me ;)
Relevant to your problem:
Two consecutive asterisks ("**") in patterns matched against full pathname may have special meaning:
A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".
A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the location of the . gitignore file, with infinite depth.
A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
Other consecutive asterisks are considered invalid.
Unlike the other answers, return false
is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...
html
<form onsubmit="return mySubmitFunction(event)">
...
</form>
script
function mySubmitFunction()
{
someBug()
return false;
}
returning false
here won't be executed and the form will be submitted either way. You should also call preventDefault
to prevent the default form action for Ajax form submissions.
function mySubmitFunction(e) {
e.preventDefault();
someBug();
return false;
}
In this case, even with the bug the form won't submit!
Alternatively, a try...catch
block could be used.
function mySubmit(e) {
e.preventDefault();
try {
someBug();
} catch (e) {
throw new Error(e.message);
}
return false;
}
Initiate the NodeList inside the for loop and you will get the desired output.
ArrayList<String> nodes = new ArrayList<String>();
ArrayList list=new ArrayList();
for(int i=0;i<PropertyNode.getLength()-1;i++){
ArrayList NodeList=new ArrayList();
Node childNode = PropertyNode.item(i);
NodeList Children = childNode.getChildNodes();
if(Children!=null){
nodes.clear();
nodes.add("PropertyStart");
nodes.add(Children.item(3).getTextContent());
nodes.add(Children.item(7).getTextContent());
nodes.add(Children.item(9).getTextContent());
nodes.add(Children.item(11).getTextContent());
nodes.add(Children.item(13).getTextContent());
nodes.add("PropertyEnd");
}
NodeList.addAll(nodes);
list.add(NodeList);
}
Explanation: NodeList is an object which remains same throughout the loop so adding same variable to list in a loop will actually add it only once. The loop is only adding its variables in single NodeList array hence you must be seeing
[/*list*/ [ /*NodeList*/ ] ]
and NodeList contains [prostart, a,b,c,proend,prostart,d,e,f,proend ...]
I needed some formatting logic to be shared across multiple components and as an Angular developer also naturally leaned towards a service.
I shared the logic by putting it in a separate file
function format(input) {
//convert input to output
return output;
}
module.exports = {
format: format
};
and then imported it as a module
import formatter from '../services/formatter.service';
//then in component
render() {
return formatter.format(this.props.data);
}
String 1:
$input =~ /'^\S+'/;
$s1 = $&;
String 2:
$input =~ /\(.*\)/;
$s2 = $&;
String 3:
$input =~ /\*?$/;
$s3 = $&;
I uninstalled it on Genymotion. Then run react-native run-android
to build the app. And it worked. Do try this first before running sudo ./gradlew clean
, it will save you a lot of time.
What you need is called attribute selector. An example, using your html structure, is the following:
div[class^="tocolor-"], div[class*=" tocolor-"] {
color:red
}
In the place of div
you can add any element or remove it altogether, and in the place of class
you can add any attribute of the specified element.
[class^="tocolor-"]
— starts with "tocolor-".
[class*=" tocolor-"]
— contains the substring "tocolor-" occurring directly after a space character.
Demo: http://jsfiddle.net/K3693/1/
More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs
You can use it like this in jinja template
{{ row.session_start_date_time.strftime('%d-%m-%Y %H:%M:%S')}}
In this code the field name is row.session_start_date_time
.
function printResult() {
var DocumentContainer = document.getElementById('your_div_id');
var WindowObject = window.open('', "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
This is not an error, it is a warning from your Microsoft compiler.
Select your project and click "Properties" in the context menu.
In the dialog, chose Configuration Properties
-> C/C++
-> Preprocessor
In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS
to turn those warnings off.
Getting the Id is pretty straight forward and you've solved that.
Your second question though is a little more involved.
So, this is all prerelease stuff right now, but the common problem you're facing is where you're extending the user with new properties ( or an Items collection in you're question).
Out of the box you'll get a file called IdentityModel
under the Models folder (at the time of writing). In there you have a couple of classes; ApplicationUser
and ApplicationDbContext
. To add your collection of Items
you'll want to modify the ApplicationUser
class, just like you would if this were a normal class you were using with Entity Framework. In fact, if you take a quick look under the hood you'll find that all the identity related classes (User, Role etc...) are just POCOs now with the appropriate data annotations so they play nice with EF6.
Next, you'll need to make some changes to the AccountController
constructor so that it knows to use your DbContext.
public AccountController()
{
IdentityManager = new AuthenticationIdentityManager(
new IdentityStore(new ApplicationDbContext()));
}
Now getting the whole user object for your logged in user is a little esoteric to be honest.
var userWithItems = (ApplicationUser)await IdentityManager.Store.Users
.FindAsync(User.Identity.GetUserId(), CancellationToken.None);
That line will get the job done and you'll be able to access userWithItems.Items
like you want.
HTH
Use this class for 30 min
class Session{
public static function init(){
ini_set('session.gc_maxlifetime', 1800) ;
session_start();
}
public static function set($key, $val){
$_SESSION[$key] =$val;
}
public static function get($key){
if(isset($_SESSION[$key])){
return $_SESSION[$key];
} else{
return false;
}
}
public static function checkSession(){
self::init();
if(self::get("adminlogin")==false){
self::destroy();
header("Location:login.php");
}
}
public static function checkLogin(){
self::init();
if(self::get("adminlogin")==true){
header("Location:index.php");
}
}
public static function destroy(){
session_destroy();
header("Location:login.php");
}
}
You can create an array of pointers.
Car** mycars = new Car*[userInput];
for (int i=0; i<userInput; i++){
mycars[i] = new Car(...);
}
...
for (int i=0; i<userInput; i++){
delete mycars[i];
}
delete [] mycars;
or
Car() constructor does not need to be public. Add a static method to your class that builds an array:
static Car* makeArray(int length){
return new Car[length];
}
I asked in #machomebrew and learned that you can switch between versions using brew switch.
$ brew switch libfoo mycopy
to get version mycopy of libfoo.
I was able to get it to work in IE and FF with jQuery's:
$(window).bind('beforeunload', function(){
});
instead of: unload, onunload, or onbeforeunload
If you use jquery, it can be done by using $(window).height();
<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>
<script type="text/javascript" language="javascript">
$('.myIframe').css('height', $(window).height()+'px');
</script>
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
This is using the :hover
pseudoelement in CSS3.
HTML:
<div id="wrapper">
<img src="http://placehold.it/300x200" class="hover" />
<p class="text">text</p>
</div>?
CSS:
#wrapper .text {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}
#wrapper:hover .text {
visibility:visible;
}
?Demo HERE.
This instead is a way of achieving the same result by using jquery:
HTML:
<div id="wrapper">
<img src="http://placehold.it/300x200" class="hover" />
<p class="text">text</p>
</div>?
CSS:
#wrapper p {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}
jquery code:
$('.hover').mouseover(function() {
$('.text').css("visibility","visible");
});
$('.hover').mouseout(function() {
$('.text').css("visibility","hidden");
});
You can put the jquery code where you want, in the body of the HTML page, then you need to include the jquery library in the head like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
You can see the demo HERE.
When you want to use it on your website, just change the <img src />
value and you can add multiple images and captions, just copy the format i used: insert image with class="hover"
and p with class="text"
In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)
Meaning the first answer was correct actually char ch = (char) yourInt;
if in yourint=49 (or 0x31), ch will be '1'
From this answer, you get a readable and efficient representation: https://stackoverflow.com/a/65939892/3746632
Output looks like this. X is 1d vector to represent a single instance's features.
from numba import jit,njit
@njit
def predict(X):
ret = 0
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
pass
else: # if w_mexico > 0.5
ret += 1
else: # if w_pizza > 0.5
pass
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
pass
else: # if w_mexico > 0.5
pass
else: # if w_pizza > 0.5
ret += 1
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
ret += 1
else: # if w_mexico > 0.5
ret += 1
else: # if w_pizza > 0.5
pass
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
ret += 1
else: # if w_mexico > 0.5
pass
else: # if w_pizza > 0.5
ret += 1
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
pass
else: # if w_mexico > 0.5
pass
else: # if w_pizza > 0.5
pass
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
pass
else: # if w_mexico > 0.5
ret += 1
else: # if w_pizza > 0.5
ret += 1
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
pass
else: # if w_mexico > 0.5
pass
else: # if w_pizza > 0.5
ret += 1
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
pass
else: # if w_mexico > 0.5
pass
else: # if w_pizza > 0.5
pass
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
pass
else: # if w_mexico > 0.5
pass
else: # if w_pizza > 0.5
pass
if X[0] <= 0.5: # if w_pizza <= 0.5
if X[1] <= 0.5: # if w_mexico <= 0.5
if X[2] <= 0.5: # if w_reusable <= 0.5
ret += 1
else: # if w_reusable > 0.5
pass
else: # if w_mexico > 0.5
pass
else: # if w_pizza > 0.5
pass
return ret/10
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
mysql -u root -p -D dbname < tablename.sql
Well I had the same exact requirement, and Robot class is perfectly fine for me. It works on windows 7 and XP (tried java 6 & 7).
public static void click(int x, int y) throws AWTException{
Robot bot = new Robot();
bot.mouseMove(x, y);
bot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
bot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
May be you could share the name of the program that is rejecting your click?
There is DiffMerge from SourceGear. It's pretty good. Araxis Merge is one of the programs I miss from Windows. I wonder if it works under Wine ;) Might have to give it a try
We can use following code
textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
Where
"Text"
– the property of textbox model
– the model object enter code here "Name"
– the value of model which to bind the textbox.Using Bootstrap 3.3.5 and .container-fluid
, this is how I get full width with no gutters or horizontal scrolling on mobile. Note that .container-fluid
was re-introduced in 3.1.
Full width on mobile/tablet, 1/4 screen on desktop
<div class="container-fluid"> <!-- Adds 15px left/right padding -->
<div class="row"> <!-- Adds -15px left/right margins -->
<div class="col-md-4 col-md-offset-4" style="padding-left: 0, padding-right: 0"> <!-- col classes adds 15px padding, so remove the same amount -->
<!-- Full-width for mobile -->
<!-- 1/4 screen width for desktop -->
</div>
</div>
</div>
Full width on all resolutions (mobile, table, desktop)
<div class="container-fluid"> <!-- Adds 15px left/right padding -->
<div class="row"> <!-- Adds -15px left/right margins -->
<div>
<!-- Full-width content -->
</div>
</div>
</div>
To build on @dyslexicanaboko's answer for dotnet core, here is a client console application:
Create a helper class:
using System;
using Microsoft.AspNetCore.SignalR.Client;
namespace com.stackoverflow.SignalRClientConsoleApp
{
public class SignalRConnection
{
public async void Start()
{
var url = "http://signalr-server-url/hubname";
var connection = new HubConnectionBuilder()
.WithUrl(url)
.WithAutomaticReconnect()
.Build();
// receive a message from the hub
connection.On<string, string>("ReceiveMessage", (user, message) => OnReceiveMessage(user, message));
var t = connection.StartAsync();
t.Wait();
// send a message to the hub
await connection.InvokeAsync("SendMessage", "ConsoleApp", "Message from the console app");
}
private void OnReceiveMessage(string user, string message)
{
Console.WriteLine($"{user}: {message}");
}
}
}
Then implement in your console app's entry point:
using System;
namespace com.stackoverflow.SignalRClientConsoleApp
{
class Program
{
static void Main(string[] args)
{
var signalRConnection = new SignalRConnection();
signalRConnection.Start();
Console.Read();
}
}
}
HTML select elements have a selectedIndex
property that can be written to in order to select a particular option:
$('select').prop('selectedIndex', 3); // select 4th option
Using plain JavaScript this can be achieved by:
// use first select element
var el = document.getElementsByTagName('select')[0];
// assuming el is not null, select 4th option
el.selectedIndex = 3;
You can try this methods
window.open(location, '_self').close();
worked for me
let returnPayments = [ ...this.payments ];
returnPayments[this.payments.findIndex(x => x.id == this.payment.id)] = this.payment;
To delete the folder, this is code using Text box and a button using System.IO;
:
private void Deletebt_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text);
foreach (FileInfo file in myDirInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
dir.Delete(true);
}
}
To people using Codeigniter (i'm on C3):
The index.php file overwrite php.ini configuration, so on index.php file, line 68:
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
You can change this option to set what you need. Here's the complete list:
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
6143 E_ALL
2048 E_STRICT
4096 E_RECOVERABLE_ERROR
Hope it helps.
I use Chrome dev tools' Timeline tab, instantiate increasingly large amounts of objects, and get good estimates like that. You can use html like this one below, as boilerplate, and modify it to better simulate the characteristics of your objects (number and types of properties, etc...). You may want to click the trash bit icon at the bottom of that dev tools tab, before and after a run.
<html>
<script>
var size = 1000*100
window.onload = function() {
document.getElementById("quantifier").value = size
}
function scaffold()
{
console.log("processing Scaffold...");
a = new Array
}
function start()
{
size = document.getElementById("quantifier").value
console.log("Starting... quantifier is " + size);
console.log("starting test")
for (i=0; i<size; i++){
a[i]={"some" : "thing"}
}
console.log("done...")
}
function tearDown()
{
console.log("processing teardown");
a.length=0
}
</script>
<body>
<span style="color:green;">Quantifier:</span>
<input id="quantifier" style="color:green;" type="text"></input>
<button onclick="scaffold()">Scaffold</button>
<button onclick="start()">Start</button>
<button onclick="tearDown()">Clean</button>
<br/>
</body>
</html>
Instantiating 2 million objects of just one property each (as in this code above) leads to a rough calculation of 50 bytes per object, on my Chromium, right now. Changing the code to create a random string per object adds some 30 bytes per object, etc. Hope this helps.
For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.
So when I ran
rails generate scaffold User name:string email:string
the console showed
Usage:
rails new APP_PATH [options]
So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed
rails generate scaffold User name:string email:string
and it worked
Anything that is part of Outer should have access to all of Outer's members, public or private.
Edit: your compiler is correct, var is not a member of Inner. But if you have a reference or pointer to an instance of Outer, it could access that.
Have you tried:
eval $cmd
For the follow-on question of how to escape *
since it has special meaning when it's naked or in double quoted strings: use single quotes.
MYSQL='mysql AMORE -u username -ppassword -h localhost -e'
QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double"
eval $MYSQL "'$QUERY'"
Bonus: It also reads nice: eval mysql query ;-)
string constr = @"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();
Closing and re-opening VS2015 resolves the issue.
It seems that in some cases, simply reloading the affected project will work.
The method you're using to read the http body response returns a byte slice:
func ReadAll(r io.Reader) ([]byte, error)
You can convert []byte
to a string by using
body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)
When you inherit from Super this is what in reality happens:
public class Son extends Super{
// If you dont declare a constructor of any type, adefault one will appear.
public Son(){
// If you dont call any other constructor in the first line a call to super() will be placed instead.
super();
}
}
So, that is the reason, because you have to call your unique constructor, since"Super" doesn't have a default one.
Now, trying to guess why Java doesn't support constructor inheritance, probably because a constructor only makes sense if it's talking about concrete instances, and you shouldn't be able to create an instance of something when you don't know how it's defined (by polymorphism).
If scope resolution :: had to be used outside the class then the respective function or variable should be declared as static
class Foo {
//Static variable
public static $static_var = 'static variable';
//Static function
static function staticValue() { return 'static function'; }
//function
function Value() { return 'Object'; }
}
echo Foo::$static_var . "<br/>"; echo Foo::staticValue(). "<br/>"; $foo = new Foo(); echo $foo->Value();
Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]
If tsStart > tsFinish Then
' Take Hours difference and adjust accordingly
tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)
' Add Minutes to Difference
tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))
' Add Seonds to Difference
tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))
The simplest way in laravel 5 is:
$listings=Listing::take(10)->get();
return view('view.name',compact('listings'));
You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.
XAML:
<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...
Code behind:
private void listView_Click(object sender, RoutedEventArgs e)
{
var item = (sender as ListView).SelectedItem;
if (item != null)
{
...
}
}
You can check if the Google Play Store app is installed and, if this is the case, you can use the "market://" protocol.
final String my_package_name = "........." // <- HERE YOUR PACKAGE NAME!!
String url = "";
try {
//Check whether Google Play store is installed or not:
this.getPackageManager().getPackageInfo("com.android.vending", 0);
url = "market://details?id=" + my_package_name;
} catch ( final Exception e ) {
url = "https://play.google.com/store/apps/details?id=" + my_package_name;
}
//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
{
"rules": {
".read": true,
".write": true
}
}
It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12
.
[note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]
keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:
Re-enter new password:
Enter source keystore password:
[Storing myp12file.p12]
Now the file myp12file.p12
contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12
command. For example,
openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
friendlyName: mykey
localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----
Prints out the private key unencrypted.
Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.
You should take a look the reference documentation. It's well explained.
In your case, I think you cannot use between because you need to pass two parameters
Between - findByStartDateBetween … where x.startDate between ?1 and ?2
In your case take a look to use a combination of LessThan
or LessThanEqual
with GreaterThan
or GreaterThanEqual
LessThan - findByEndLessThan … where x.start< ?1
LessThanEqual findByEndLessThanEqual … where x.start <= ?1
GreaterThan - findByStartGreaterThan … where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1
You can use the operator And
and Or
to combine both.
In my case the crucial thing was to set in 'scrollwheel':false
in init. Notice: I am using jQuery UI Map
. Below is my CoffeeScript init function heading:
$("#map_canvas").gmap({'scrollwheel':false}).bind "init", (evt, map) ->
A bit late but may also help to someone who looks for answers...
Between rows/row_number example - recursive query that may be used in any SQL:
WITH data(row_num, some_val) AS
(
SELECT 1 row_num, 1 some_val FROM any_table --dual in Oracle
UNION ALL
SELECT row_num+1, some_val+row_num FROM data WHERE row_num < 20 -- any number
)
SELECT * FROM data
WHERE row_num BETWEEN 5 AND 10
/
ROW_NUM SOME_VAL
-------------------
5 11
6 16
7 22
8 29
9 37
10 46
.star-light::after {
content: "\f005";
font-family: "FontAwesome";
font-size: 3.2rem;
color: #fff;
font-weight: 900;
background-color: red;
}
~ $ hciconfig noauth
This should do the trick (I'm using bluez 5.23 and there's no more simple-egent and blue-utils). However, I'm trying to look for a way to make changes hciconfig permanent because after power out and then power on, authentication is needed again. So far, the changes in hciconfig still stays the same when you reboot it. it reverts back only when power out. If anybody has found a way to make hciconfig permanent, do let me know!
np.newaxis
?The np.newaxis
is just an alias for the Python constant None
, which means that wherever you use np.newaxis
you could also use None
:
>>> np.newaxis is None
True
It's just more descriptive if you read code that uses np.newaxis
instead of None
.
np.newaxis
?The np.newaxis
is generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxis
represents where I want to add dimensions.
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)
In the first example I use all elements from the first dimension and add a second dimension:
>>> a[:, np.newaxis]
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
>>> a[:, np.newaxis].shape
(10, 1)
The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:
>>> a[np.newaxis, :] # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)
Similarly you can use multiple np.newaxis
to add multiple dimensions:
>>> a[np.newaxis, :, np.newaxis] # note the 3 [] pairs in the output
array([[[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)
np.newaxis
?There is another very similar functionality in NumPy: np.expand_dims
, which can also be used to insert one dimension:
>>> np.expand_dims(a, 1) # like a[:, np.newaxis]
>>> np.expand_dims(a, 0) # like a[np.newaxis, :]
But given that it just inserts 1
s in the shape
you could also reshape
the array to add these dimensions:
>>> a.reshape(a.shape + (1,)) # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape) # like a[np.newaxis, :]
Most of the times np.newaxis
is the easiest way to add dimensions, but it's good to know the alternatives.
np.newaxis
?In several contexts is adding dimensions useful:
If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshow
to display a 1D array.
If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]
. This works because NumPy operations broadcast starting with the last dimension 1.
To add a necessary dimension so that NumPy can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.
1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with np.newaxis
:
>>> a = np.array([0.0, 10.0, 20.0, 30.0]) >>> b = np.array([1.0, 2.0, 3.0]) >>> a[:, np.newaxis] + b array([[ 1., 2., 3.], [ 11., 12., 13.], [ 21., 22., 23.], [ 31., 32., 33.]])
You can also use a lambda expression
public string Type
{
get => _type;
set => _type = value;
}
if you wish to hide URL from the user, Show an AlertDialog as below.
myWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(TAG, "onJsAlert url: " + url + "; message: " + message);
AlertDialog.Builder builder = new AlertDialog.Builder(
mContext);
builder.setMessage(message)
.setNeutralButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
}).show();
result.cancel();
return true;
}
}
Today I was looking for this and Mr Brandon Rude gave an excellent answer. Unfortunately, AsyncTask
is now depricated, you can still use it, but it gives you a warning which is very annoying. So an alternative is to use Executors
like this way (in kotlin
):
val someRunnable = object : Runnable{
override fun run() {
// todo: do your background tasks
requireActivity().runOnUiThread{
// update views / ui if you are in a fragment
};
/*
runOnUiThread {
// update ui if you are in an activity
}
* */
}
};
Executors.newSingleThreadExecutor().execute(someRunnable);
And in java
it looks like this:
Runnable someRunnable = new Runnable() {
@Override
public void run() {
// todo: background tasks
runOnUiThread(new Runnable() {
@Override
public void run() {
// todo: update your ui / view in activity
}
});
/*
requireActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// todo: update your ui / view in Fragment
}
});*/
}
};
Executors.newSingleThreadExecutor().execute(someRunnable);
List is interface and ArrayList is implemented concrete class. It is always recommended to use.
List<String> arrayList = new ArrayList<String>();
Because here list reference is flexible. It can also hold LinkedList or Vector
object.
My version:
json_encode(self::toArray($ob))
Implementation:
private static function toArray($object) {
$reflectionClass = new \ReflectionClass($object);
$properties = $reflectionClass->getProperties();
$array = [];
foreach ($properties as $property) {
$property->setAccessible(true);
$value = $property->getValue($object);
if (is_object($value)) {
$array[$property->getName()] = self::toArray($value);
} else {
$array[$property->getName()] = $value;
}
}
return $array;
}
JsonUtils : GitHub
from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
f = open(file_to_open)
print(f.read())
Brute Force is the only way!
Here is a script that helped me out:
https://code.google.com/p/android-keystore-password-recover/wiki/HowTo
Using a list of 5-10 possible words from memory, it recovered my password in <1 sec.
typeof(BaseClass).IsAssignableFrom(unknownType);
Here is an example that will prove useful when there are many enumerations. It uses structures in Golang, and draws upon Object Oriented Principles to tie them all together in a neat little bundle. None of the underlying code will change when a new enumeration is added or deleted. The process is:
enumeration items
: EnumItem. It has an integer and string type.enumeration
as a list of enumeration items
: Enumenum.Name(index int)
: returns the name for the given index.enum.Index(name string)
: returns the name for the given index.enum.Last()
: returns the index and name of the last enumerationHere is some code:
type EnumItem struct {
index int
name string
}
type Enum struct {
items []EnumItem
}
func (enum Enum) Name(findIndex int) string {
for _, item := range enum.items {
if item.index == findIndex {
return item.name
}
}
return "ID not found"
}
func (enum Enum) Index(findName string) int {
for idx, item := range enum.items {
if findName == item.name {
return idx
}
}
return -1
}
func (enum Enum) Last() (int, string) {
n := len(enum.items)
return n - 1, enum.items[n-1].name
}
var AgentTypes = Enum{[]EnumItem{{0, "StaffMember"}, {1, "Organization"}, {1, "Automated"}}}
var AccountTypes = Enum{[]EnumItem{{0, "Basic"}, {1, "Advanced"}}}
var FlagTypes = Enum{[]EnumItem{{0, "Custom"}, {1, "System"}}}
var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]
Worked for me. But the first var should be var url = window.location.href
Your function worked for me after changing its declaration to this ...
Function processArr(Arr As Variant) As String
You could also consider a ParamArray
like this ...
Function processArr(ParamArray Arr() As Variant) As String
'Dim N As Variant
Dim N As Long
Dim finalStr As String
For N = LBound(Arr) To UBound(Arr)
finalStr = finalStr & Arr(N)
Next N
processArr = finalStr
End Function
And then call the function like this ...
processArr("foo", "bar")
Is it proper to "reach into" an object and use its dict property?
In general, I would say "no". However Namespace
has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.
On the other hand, Namespace
does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__
, but the limits of my imagination are not the same as yours.
As other answers explain Memory in Java is divided into two portions
1. Stack: One stack is created per thread and it stores stack frames which again stores local variables and if a variable is a reference type then that variable refers to a memory location in heap for the actual object.
2. Heap: All kinds of objects will be created in heap only.
Heap memory is again divided into 3 portions
1. Young Generation: Stores objects which have a short life, Young Generation itself can be divided into two categories Eden Space and Survivor Space.
2. Old Generation: Store objects which have survived many garbage collection cycles and still being referenced.
3. Permanent Generation: Stores metadata about the program e.g. runtime constant pool.
String constant pool belongs to the permanent generation area of Heap memory.
We can see the runtime constant pool for our code in the bytecode by using javap -verbose class_name
which will show us method references (#Methodref), Class objects ( #Class ), string literals ( #String )
You can read more about it on my article How Does JVM Handle Method Overloading and Overriding Internally.
Perhaps the best two browser techs for this are Canvas, with Flash as a back up.
We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.
With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.
If you are running the command from a POSIX-compliant shell, like bash
, you can set the environment variable like this:
PYTHONPATH="/path/to" python somescript.py somecommand
If it's all on one line, the PYTHONPATH environment value applies only to that one command.
$ echo $PYTHONPATH
$ python -c 'import sys;print("/tmp/pydir" in sys.path)'
False
$ PYTHONPATH=/tmp/pydir python -c 'import sys;print("/tmp/pydir" in sys.path)'
True
$ echo $PYTHONPATH
If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.
Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.
FYI, I just did some test using the method above and if we use multi ping (10 requests)
ping -c10 8.8.8.8 &> /dev/null ; echo $?
the result of multi ping command will be "0" if at least one of ping result reachable, and "1" in case where all ping requests are unreachable.
import re
expression = "Nov 05 20:10:09 2020"
reg_ex = r'((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-2][0-9]|(3)[0-1]) (([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])) (\d{4}))'
assert re.fullmatch(reg_ex, expression), True
Expaination with respect to given Example
A group of possible months i.e. (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
A group of valid days i.e. ([0-2][0-9]|(3)[0-1])
A group for getting valid Hours : ([0-1][0-9]|2[0-3]), Minutes : ([0-5][0-9]) and Seconds : ([0-5][0-9])
A group for getting year i.e (\d{4}))
By using synchronized on a static method lock you will synchronize the class methods and attributes ( as opposed to instance methods and attributes )
So your assumption is correct.
I am wondering if making the method synchronized is the right approach to ensure thread-safety.
Not really. You should let your RDBMS do that work instead. They are good at this kind of stuff.
The only thing you will get by synchronizing the access to the database is to make your application terribly slow. Further more, in the code you posted you're building a Session Factory each time, that way, your application will spend more time accessing the DB than performing the actual job.
Imagine the following scenario:
Client A and B attempt to insert different information into record X of table T.
With your approach the only thing you're getting is to make sure one is called after the other, when this would happen anyway in the DB, because the RDBMS will prevent them from inserting half information from A and half from B at the same time. The result will be the same but only 5 times ( or more ) slower.
Probably it could be better to take a look at the "Transactions and Concurrency" chapter in the Hibernate documentation. Most of the times the problems you're trying to solve, have been solved already and a much better way.
Even though its not directly related. But I found that the CALC code won't work if you do not put spaces properly.
So this did not work for me calc(#{$a}+7px)
But this worked calc(#{$a} + 7px)
Took me sometime to figure this out.
This code works too:
$("input[reference=12345].myclass").css('border', '#000 solid 1px');
When you want a relative path from your home directory (on any UNIX) you use this strange syntax:
ssh://[user@]host.xz[:port]/~[user]/path/to/repo
For Example, if the repo is in /home/jack/projects/jillweb
on the server jill.com
and you are logging in as jack
with sshd
listening on port 4242:
ssh://[email protected]:4242/~/projects/jillweb
And when logging in as jill
(presuming you have file permissions):
ssh://[email protected]:4242/~jack/projects/jillweb
This question should be on Server Fault. Nevertheless, the following should do the trick, assuming you're talking about TCP and the IP you want to allow is 1.2.3.4:
iptables -A INPUT -p tcp --dport 8000 -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 8000 -j DROP
In the interest of adding another idea to the wiki pool, but what about AngularJS' value
and constant
modules? I'm only just starting to use them myself, but it sounds to me like these are probably the best options here.
Note: as of the time of writing, Angular 1.3.7 is the latest stable, I believe these were added in 1.2.0, haven't confirmed this with the changelog though.
Depending on how many you need to define, you might want to create a separate file for them. But I generally define these just before my app's .config()
block for easy access. Because these are still effectively modules, you'll need to rely on dependency injection to use them, but they are considered "global" to your app module.
For example:
angular.module('myApp', [])
.value('debug', true)
.constant('ENVIRONMENT', 'development')
.config({...})
Then inside any controller:
angular.module('myApp')
.controller('MainCtrl', function(debug, ENVIRONMENT), {
// here you can access `debug` and `ENVIRONMENT` as straight variables
})
From the initial question is actually sounds like static properties are required here anyway, either as mutable (value) or final (constant). It's more my personal opinion than anything else, but I find placing runtime configuration items on the $rootScope
gets too messy, too quickly.
Note if you are using https.request
do not directly use the body from res.on('data',..
. This will fail if you have a large data coming in chunks. So you need to concatenate all the data and then process the response in res.on('end'
. Example -
var options = {
hostname: "www.google.com",
port: 443,
path: "/upload",
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(post_data)
}
};
//change to http for local testing
var req = https.request(options, function (res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function (chunk) {
body = body + chunk;
});
res.on('end',function(){
console.log("Body :" + body);
if (res.statusCode != 200) {
callback("Api call failed with response code " + res.statusCode);
} else {
callback(null);
}
});
});
req.on('error', function (e) {
console.log("Error : " + e.message);
callback(e);
});
// write data to request body
req.write(post_data);
req.end();
In most browsers, the title attribute will render as a tooltip, and is generally flexible as to what sorts of elements it'll work with.
<span title="This will show as a tooltip">Mouse over for a tooltip!</span>
<a href="http://www.stackoverflow.com" title="Link to stackoverflow.com">stackoverflow.com</a>
<img src="something.png" alt="Something" title="Something">
All of those will render tooltips in most every browser.
Normalization is your best friend in comment/rank/vote system. Learn it. A lot of sites are now moving to PDO ... learn that as well.
there are no right , right-er, or wrong (well there is) ways of doing it, you need to know the basic concepts and take them from there. IF you don't feel like learning, then perhaps invest in a framework like cakephp or zend framework, or a ready made system like wordpress or joomla.
I'd also recommend the book wicked cool php scripts as it has a comment system example in it.
public IEnumerable<string> Appender(IEnumerable<string> strings)
{
List<string> myList = new List<string>();
foreach(string str in strings)
{
myList.Add(str + "roxxors");
}
return myList;
}
or
public IEnumerable<string> Appender(IEnumerable<string> strings)
{
foreach(string str in strings)
{
yield return str + "roxxors";
}
}
using the yield construct, or simply
var newCollection = strings.Select(str => str + "roxxors"); //(*)
or
var newCollection = from str in strings select str + "roxxors"; //(**)
where the two latter use LINQ and (**)
is just syntactic sugar for (*)
.
select isnull(nullif(CAR_OWNER_TEL, ''), 'NULLLLL') PHONE from TABLE
will replace CAR_OWNER_TEL if empty by NULLLLL (MS SQL)
If you want to add a new record in the form
newRecord = [4L, 1L, u'DDD', 1689544L, datetime.datetime(2010, 9, 21, 21, 45), u'jhhjjh']
to messageName
where messageName
in the form X_somemessage
can, but does not have to be in your dictionary, then do it this way:
myDict.setdefault(messageName, []).append(newRecord)
This way it will be appended to an existing messageName
or a new list will be created for a new messageName
.
I had the same issue, fixed it. Create the missing folder directly in your file system (Using windows explorer for example) . And then, refresh your project under eclipse.
Here is what seems simplest and works in python 3.7
from collections import OrderedDict
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d) # Now a normal dict
Now to check this:
>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True
NOTE: This also works, and gives same result -
>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True
As well as this -
>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True
Cheers
Try Following
DECLARE @formatted_datetime char(23)
SET @formatted_datetime = CONVERT(char(23), GETDATE(), 121)
print @formatted_datetime
simply don't cast to int
switch(operator)
{
case Operator.Plus:
//todo
You can use tmux hooks to execute commands when a new session is created. Specifically, this is achieved using the session-created
hook.
For example, to split the screen three ways with htop running in the lower right you can add the following line to your ~/.tmux.conf
file:
set-hook -g session-created 'split -h ; split -v top'
The advantage of this method is that you don't have to run tmux in any special way (i.e., shell script or alias) to get the desired result. You can also combine this with tmux new-session -A -s mysession
described in this other answer such that the hook commands are only run when you first create the session and not on subsequent attachments.
This feature was added by d15d54c2c back in 2016. The first release to include it is is 2.4.
since my post above, I have moved to a Generic Factory Class
Usage
services.AddFactory<IProcessor, string>()
.Add<ProcessorA>("A")
.Add<ProcessorB>("B");
public MyClass(IFactory<IProcessor, string> processorFactory)
{
var x = "A"; //some runtime variable to select which object to create
var processor = processorFactory.Create(x);
}
Implementation
public class FactoryBuilder<I, P> where I : class
{
private readonly IServiceCollection _services;
private readonly FactoryTypes<I, P> _factoryTypes;
public FactoryBuilder(IServiceCollection services)
{
_services = services;
_factoryTypes = new FactoryTypes<I, P>();
}
public FactoryBuilder<I, P> Add<T>(P p)
where T : class, I
{
_factoryTypes.ServiceList.Add(p, typeof(T));
_services.AddSingleton(_factoryTypes);
_services.AddTransient<T>();
return this;
}
}
public class FactoryTypes<I, P> where I : class
{
public Dictionary<P, Type> ServiceList { get; set; } = new Dictionary<P, Type>();
}
public interface IFactory<I, P>
{
I Create(P p);
}
public class Factory<I, P> : IFactory<I, P> where I : class
{
private readonly IServiceProvider _serviceProvider;
private readonly FactoryTypes<I, P> _factoryTypes;
public Factory(IServiceProvider serviceProvider, FactoryTypes<I, P> factoryTypes)
{
_serviceProvider = serviceProvider;
_factoryTypes = factoryTypes;
}
public I Create(P p)
{
return (I)_serviceProvider.GetService(_factoryTypes.ServiceList[p]);
}
}
Extension
namespace Microsoft.Extensions.DependencyInjection
{
public static class DependencyExtensions
{
public static FactoryBuilder<I, P> AddFactory<I, P>(this IServiceCollection services)
where I : class
{
services.AddTransient<IFactory<I, P>, Factory<I, P>>();
return new FactoryBuilder<I, P>(services);
}
}
}
From other stackoverflow thread:
"Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter's classpath. If you don't - download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter's /lib folder. JMeter restart will be required to pick the library up"
Please be sure that .jar file is added directly to the lib folder.
The action occurs when you attempt to call an object which is not a function, as with ()
. For instance, this will produce the error:
>>> a = 5
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Class instances can also be called if they define a method __call__
One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0)
instead of [0]
Delete the Migrations
Folder, Clean
then Rebuild
the project. This worked for me. Before Clean and Rebuild it was saying the Migration already exists since in its cached memory, it's not yet deleted.
NSPredicate
is nextstep's way of constructing condition to filter a collection (NSArray
, NSSet
, NSDictionary
).
For example consider two arrays arr
and filteredarr
:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",@"c"];
filteredarr = [NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];
the filteredarr will surely have the items that contains the character c alone.
to make it easy to remember those who little sql background it is
*--select * from tbl where column1 like '%a%'--*
1)select * from tbl --> collection
2)column1 like '%a%' --> NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",@"c"];
3)select * from tbl where column1 like '%a%' -->
[NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];
I hope this helps
For some reason my push and pull origin was changed to HTTPS-url in stead of SSH-url (probably a copy-paste error on my end), but trying to push would give me the following error after trying to login:
Username for 'https://github.com': xxx
Password for 'https://[email protected]':
remote: Invalid username or password.
Updating the remote origin with the SSH url, solved the problem:
git remote set-url origin [email protected]:<username>/<repo>.git
Hope this helps!
Ed: phpMyAdmin is for MySQL, but the asker needs something for Microsoft SQL Server.
Most solutions that I found involve using an ODBC Driver and then whatever client application you use. For example, Gorilla SQL claims to be able to do that, even though the project seems abandoned.
Most good solutions are either using Remote Desktop or VMware/Parallels.
For 2.7, try the following:
fh = logging.handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)
First of all, you can't pass to alert
second argument, use concatenation instead
alert("Input is " + inputValue);
However in order to get values from input better to use states like this
var MyComponent = React.createClass({_x000D_
getInitialState: function () {_x000D_
return { input: '' };_x000D_
},_x000D_
_x000D_
handleChange: function(e) {_x000D_
this.setState({ input: e.target.value });_x000D_
},_x000D_
_x000D_
handleClick: function() {_x000D_
console.log(this.state.input);_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<input type="text" onChange={ this.handleChange } />_x000D_
<input_x000D_
type="button"_x000D_
value="Alert the text input"_x000D_
onClick={this.handleClick}_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
<MyComponent />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
Reminder: If you do combine multiple contexts make sure you cut n paste all the functionality in your various RealContexts.OnModelCreating()
into your single CombinedContext.OnModelCreating()
.
I just wasted time hunting down why my cascade delete relationships weren't being preserved only to discover that I hadn't ported the modelBuilder.Entity<T>()....WillCascadeOnDelete();
code from my real context into my combined context.
The problem is that $this->input->post()
does not support getting all POST data, only specific data, for example $this->input->post('my_post_var').
This is why var_dump($this->input->post());
is empty.
A few solutions, stick to $_POST for retrieving all POST data, or assign variables from each POST item that you need, for example:
// variables will be false if not post data exists
$var_1 = $this->input->post('my_post_var_1');
$var_2 = $this->input->post('my_post_var_2');
$var_3 = $this->input->post('my_post_var_3');
However, since the above code is not very DRY, I like to do the following:
if(!empty($_POST))
{
// get all post data in one nice array
foreach ($_POST as $key => $value)
{
$insert[$key] = $value;
}
}
else
{
// user hasen't submitted anything yet!
}
If you are running your code against a sqlserver database then
use this command
string sqlTrunc = "TRUNCATE TABLE " + yourTableName
SqlCommand cmd = new SqlCommand(sqlTrunc, conn);
cmd.ExecuteNonQuery();
this will be the fastest method and will delete everything from your table and reset the identity counter to zero.
The TRUNCATE keyword is supported also by other RDBMS.
5 years later:
Looking back at this answer I need to add something. The answer above is good only if you are absolutely sure about the source of the value in the yourTableName variable. This means that you shouldn't get this value from your user because he can type anything and this leads to Sql Injection problems well described in this famous comic strip. Always present your user a choice between hard coded names (tables or other symbolic values) using a non editable UI.
As per https://msdn.microsoft.com/en-us/library/ms180065.aspx, "DBCC USEROPTIONS reports an isolation level of 'read committed snapshot' when the database option READ_COMMITTED_SNAPSHOT is set to ON and the transaction isolation level is set to 'read committed'. The actual isolation level is read committed."
Also in SQL Server Management Studio, in database properties under Options->Miscellaneous there is "Is Read Committed Snapshot On" option status
The typical way this is handled in C# as stephen mentioned is to overload the method. By creating multiple versions of the method with different parameters you effectively create optional parameters. In the forms with fewer parameters you would typically call the form of the method with all of the parameters setting your default values in the call to that method.
Usually in ruby when you are looking for "type" you are actually wanting the "duck-type" or "does is quack like a duck?". You would see if it responds to a certain method:
@some_var.respond_to?(:each)
You can iterate over @some_var because it responds to :each
If you really want to know the type and if it is Hash or Array then you can do:
["Hash", "Array"].include?(@some_var.class) #=> check both through instance class
@some_var.kind_of?(Hash) #=> to check each at once
@some_var.is_a?(Array) #=> same as kind_of
Date
, SimpleDateFormat
and whatever classes are required on the I/O side of things (there are many possibilities).
The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.
printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);
> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234
Open is an access level, was introduced to impose limitations on class inheritance on Swift.
This means that the open access level can only be applied to classes and class members.
In Classes
An open class can be subclassed in the module it is defined in and in modules that import the module in which the class is defined.
In Class members
The same applies to class members. An open method can be overridden by subclasses in the module it is defined in and in modules that import the module in which the method is defined.
THE NEED FOR THIS UPDATE
Some classes of libraries and frameworks are not designed to be subclassed and doing so may result in unexpected behavior. Native Apple library also won't allow overriding the same methods and classes,
So after this addition they will apply public and private access levels accordingly.
For more details have look at Apple Documentation on Access Control
Try this I It's working.
<form>_x000D_
<input type="text" name="mobile" pattern="[1-9]{1}[0-9]{9}" title="Enter 10 digit mobile number" placeholder="Mobile number" required>_x000D_
<button>_x000D_
Save_x000D_
</button>_x000D_
</form>_x000D_
_x000D_
Based on a previous answer that helped me, but different directory:
cd /Applications/Eclipse.app/Contents/MacOS
./eclipse &
Thanks
I could not understand those 3 rules in the specs too well -- hope to have something that is more plain English -- but here is what I gathered from JavaScript: The Definitive Guide, 6th Edition, David Flanagan, O'Reilly, 2011:
Quote:
JavaScript does not treat every line break as a semicolon: it usually treats line breaks as semicolons only if it can’t parse the code without the semicolons.
Another quote: for the code
var a
a
=
3 console.log(a)
JavaScript does not treat the second line break as a semicolon because it can continue parsing the longer statement a = 3;
and:
two exceptions to the general rule that JavaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement on the first line. The first exception involves the return, break, and continue statements
... If a line break appears after any of these words ... JavaScript will always interpret that line break as a semicolon.
... The second exception involves the ++ and -- operators ... If you want to use either of these operators as postfix operators, they must appear on the same line as the expression they apply to. Otherwise, the line break will be treated as a semicolon, and the ++ or -- will be parsed as a prefix operator applied to the code that follows. Consider this code, for example:
x
++
y
It is parsed as
x; ++y;
, not asx++; y
So I think to simplify it, that means:
In general, JavaScript will treat it as continuation of code as long as it makes sense -- except 2 cases: (1) after some keywords like return
, break
, continue
, and (2) if it sees ++
or --
on a new line, then it will add the ;
at the end of the previous line.
The part about "treat it as continuation of code as long as it makes sense" makes it feel like regular expression's greedy matching.
With the above said, that means for return
with a line break, the JavaScript interpreter will insert a ;
(quoted again: If a line break appears after any of these words [such as return
] ... JavaScript will always interpret that line break as a semicolon)
and due to this reason, the classic example of
return
{
foo: 1
}
will not work as expected, because the JavaScript interpreter will treat it as:
return; // returning nothing
{
foo: 1
}
There has to be no line-break immediately after the return
:
return {
foo: 1
}
for it to work properly. And you may insert a ;
yourself if you were to follow the rule of using a ;
after any statement:
return {
foo: 1
};
If you're sure that your script runs and that it is a false alarm, Go to Preferences > PyDev > Editor > Code Analysis. Demote the errors to warnings.
The same problem observed on my side while looking for uiautomatorviewer.bat. After installing Android studio 3.6.2 (at Win10) I was looking for Android SDK Tools section at SDK Manager. Currently, this section is Hidden as Obsolete. Fix: uncheck Hide Obsolete Packages, then check the mentioned package and install it - C:\Users..\AppData\Local\Android\Sdk\tools\bin is created.
When you have replace: true
you get the following piece of DOM:
<div ng-controller="Ctrl" class="ng-scope">
<div class="ng-binding">hello</div>
</div>
whereas, with replace: false
you get this:
<div ng-controller="Ctrl" class="ng-scope">
<my-dir>
<div class="ng-binding">hello</div>
</my-dir>
</div>
So the replace
property in directives refer to whether the element to which the directive is being applied (<my-dir>
in that case) should remain (replace: false
) and the directive's template should be appended as its child,
OR
the element to which the directive is being applied should be replaced (replace: true
) by the directive's template.
In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:
.directive('myDir', function() {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<div>{{title}}<div ng-transclude></div></div>'
};
});
In that case if in the directive's template you have an element (or elements) with attribute ng-transclude
, its content will be replaced by the element's (to which the directive is being applied) original content.
See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview
See this to read more about translusion.
There is another way,
j3 = j2 > 4; print(j2[j3])
tested in 3.x
The .cpp
file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".
If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.
One considerable difference is about porting Python2 to Python3. urllib2 does not exist for python3 and its methods ported to urllib. So you are using that heavily and want to migrate to Python3 in future, consider using urllib. However 2to3 tool will automatically do most of the work for you.
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Table1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Sl", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
Copy this in web config
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html
If using httplib.HTTPSConnection:
Please take a look at:
This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter. You can use:
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
You can use Reflections framework for this
import static org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation));
To simply put a line in the server's error log, use PHP's error_log() function. However, that method will not send an e-mail.
First, to trigger an error:
trigger_error("Error message here", E_USER_ERROR);
By default, this will go in the server's error log file. See the ErrorLog directive for Apache. To set your own log file:
ini_set('error_log', 'path/to/log/file');
Note that the log file you choose must already exist and be writable by the server process. The simplest way to make the file writable is to make the server user the owner of the file. (The server user may be nobody, _www, apache, or something else, depending on your OS distribution.)
To e-mail the error, you need to set up a custom error handler:
function mail_error($errno, $errstr, $errfile, $errline) {
$message = "[Error $errno] $errstr - Error on line $errline in file $errfile";
error_log($message); // writes the error to the log file
mail('[email protected]', 'I have an error', $message);
}
set_error_handler('mail_error', E_ALL^E_NOTICE);
Please see the relevant PHP documentation for more info.
Well,
The container div is very good to have, because if You want the site centered, You just can't do it just with body or html... But You can, with divs. Why container? Its usually used, just because the code itselve has to be clean and readable. So that is container... It contains all website, in case You want to mess with it around :)
Good luck
Thread class defines several methods that can be overriden
by the the extending class. But to create a thread we must override the run()
method. Same applies to Runnable
as well.
However Runnable
is a preferred method of creating a thread. The primary reasons are:
Since Runnable is an interface, you can extend other classes. But if you extend Thread then that option is gone.
If you are not modifying or enhancing a whole lot of Thread
functionalities and extending the Thread
class is not a preferred way.
Based on what you provided, it is pretty simple for what you need to do and you even have a number of ways to go about doing it. You'll need something that'll let you post a body with your request. Almost any programming language can do this as well as command line tools like cURL.
One you have your tool decided, you'll need to create your JSON body and submit it to the server.
An example using cURL would be (all in one line, minus the \
at the end of the first line):
curl -v -H "Content-Type: application/json" -X POST \
-d '{"name":"your name","phonenumber":"111-111"}' http://www.abc.com/details
The above command will create a request that should look like the following:
POST /details HTTP/1.1
Host: www.abc.com
Content-Type: application/json
Content-Length: 44
{"name":"your name","phonenumber":"111-111"}
you really don't need quotes if let say use are using the image from your css file it can be
{background-image: url(your image.png/jpg etc);}
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
you dont insert into identity fields. You need to specify the field names and use the Values clause
insert into #tmp (AssignedTo, field2, field3) values (value, value, value)
If you use do a insert into... select field field field
it will insert the first field into that identity field and will bomb
ogdate
is itself a string, why are you trying to access it's value
property that it doesn't have ?
console.log(og_date.split('-'));
for simple tasks, we can use http://flower.readthedocs.io/en/latest/screenshots.html and http://policystat.github.io/jobtastic/ to do the monitoring.
and for complicated tasks, say a task which deals with a lot other modules. We recommend manually record the progress and message on the specific task unit.
Let's test 3 methods:
1)
public static double round1(double value, int scale) {
return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);
}
2)
public static float round2(float number, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++)
pow *= 10;
float tmp = number * pow;
return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
3)
public static float round3(float d, int decimalPlace) {
return BigDecimal.valueOf(d).setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).floatValue();
}
Number is 0.23453f
We'll test 100,000 iterations each method.
Results:
Time 1 - 18 ms
Time 2 - 1 ms
Time 3 - 378 ms
Tested on laptop
Intel i3-3310M CPU 2.4GHz
Check out James Padolsey's animateToSelector
Intro: This jQuery plugin will allow you to animate any element to styles specified in your stylesheet. All you have to do is pass a selector and the plugin will look for that selector in your StyleSheet and will then apply it as an animation.
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
This will give the output:
2017-07-14 08:10:00
I had a similar problem, simply running a trivial ruby script that just required the gem i wanted...got that error message. When I changed the incantation from:
ruby test.rb
to
ruby -rubygems test.rb
Seemed to work.
Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:
.text
.globl __start
__start:
la $a0,str1 #Load and print string asking for string
li $v0,4
syscall
li $v0,8 #take in input
la $a0, buffer #load byte space into address
li $a1, 20 # allot the byte space for string
move $t0,$a0 #save string to t0
syscall
la $a0,str2 #load and print "you wrote" string
li $v0,4
syscall
la $a0, buffer #reload byte space to primary address
move $a0,$t0 # primary address = t0 address (load pointer)
li $v0,4 # print string
syscall
li $v0,10 #end program
syscall
.data
buffer: .space 20
str1: .asciiz "Enter string(max 20 chars): "
str2: .asciiz "You wrote:\n"
###############################
#Output:
#Enter string(max 20 chars): qwerty 123
#You wrote:
#qwerty 123
#Enter string(max 20 chars): new world oreddeYou wrote:
# new world oredde //lol special character
###############################
Here is:
var array : [String] = ["One", "Two", "Three"]
let userDefault = UserDefaults.standard
// set
userDefault.set(array, forKey: "array")
// retrieve
if let fetchArray = userDefault.array(forKey: "array") as? [String] {
// code
}
CSS:
.container {
position: relative;
width: 500px;
}
.container div {
height: 300px;
}
.column-left {
width: 33%;
left: 0;
background: #00F;
position: absolute;
}
.column-center {
width: 34%;
background: #933;
margin-left: 33%;
position: absolute;
}
.column-right {
width: 33%;
right: 0;
position: absolute;
background: #999;
}
HTML:
<div class="container">
<div class="column-center">Column center</div>
<div class="column-left">Column left</div>
<div class="column-right">Column right</div>
</div>
Here is the Demo : http://jsfiddle.net/nyitsol/f0dv3q3z/
The size of a pointer is the size required by your system to hold a unique memory address (since a pointer just holds the address it points to)
I like the simplicity of gilly3's answer, but users will probably be surprised that a month before March 31 is March 3. I chose to implement a version that sticks to the end of the month, so a month before March 28, 29, 30, and 31 will all be Feb 28 when it's not a leap year.
function addMonths(date, months) {_x000D_
var result = new Date(date),_x000D_
expectedMonth = ((date.getMonth() + months) % 12 + 12) % 12;_x000D_
result.setMonth(result.getMonth() + months);_x000D_
if (result.getMonth() !== expectedMonth) {_x000D_
result.setDate(0);_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
var dt2004_05_31 = new Date("2004-05-31 0:00"),_x000D_
dt2001_05_31 = new Date("2001-05-31 0:00"),_x000D_
dt2001_03_31 = new Date("2001-03-31 0:00"),_x000D_
dt2001_02_28 = new Date("2001-02-28 0:00"),_x000D_
result = addMonths(dt2001_05_31, -2);_x000D_
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2001_05_31, -3);_x000D_
console.assert(dt2001_02_28.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2001_05_31, 36);_x000D_
console.assert(dt2004_05_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2004_05_31, -38);_x000D_
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
console.log('Done.');
_x000D_
For git <= 2.13 these two commands combined should reset your repos with recursive submodules:
git submodule foreach --recursive git reset --hard
git submodule update --recursive --init
First you need to now that you can use the implicit intent, android documentation provide us with a very detailed common intents for implementing the map intent you need to create a new intent with two parameters
For action we can use Intent.ACTION_VIEW
and for Uri we should Build it ,below i attached a sample code to create,build,start the activity.
String addressString = "1600 Amphitheatre Parkway, CA";
/*
Build the uri
*/
Uri.Builder builder = new Uri.Builder();
builder.scheme("geo")
.path("0,0")
.query(addressString);
Uri addressUri = builder.build();
/*
Intent to open the map
*/
Intent intent = new Intent(Intent.ACTION_VIEW, addressUri);
/*
verify if the devise can launch the map intent
*/
if (intent.resolveActivity(getPackageManager()) != null) {
/*
launch the intent
*/
startActivity(intent);
}
for i=1:length(list)
elm = list(i);
//do something with elm.
I had a similar problem to the OP when upgrading php5 from an older version, to 5.5.9, which is the version installed with Mint 17.
I'm running a LAMP setup on a machine on my local network, which I use to preview changes to websites before I upload those changes to the actual live server. So I maintain a perfect local mirror of the actual site.
After the upgrade, files which run and display perfectly on the actual site would not display, or would only display html on the local machine. PHP was not parsed. The phpinfo() command worked, so I knew php was otherwise working. The log generated no errors. Viewing the page source showed me the actual php code.
I had constructed a test.php page that contained the following code:
<?php
phpinfo();
?>
This worked. Then I discovered when I changed <?php
to <?
the command no longer worked. All my php sites use <?
instead of <?php
which might not be ideal, but it's the reality. I fixed the problem by going to /etc/php5/apache2 , searching for "short_open_tag" and changing the value from Off to On.
you can save the model in json and weights in a hdf5 file format.
# keras library import for Saving and loading model and weights
from keras.models import model_from_json
from keras.models import load_model
# serialize model to JSON
# the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()
with open("model_num.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model_num.h5")
files "model_num.h5" and "model_num.json" are created which contain our model and weights
To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.
# load json and create model
json_file = open('model_num.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")
loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')
To predict for different data you can use this
loaded_model.predict_classes("your_test_data here")
object.setForeground(Color.green);
*any colour you wish *object being declared earlier
Just use os.path.dirname(os.path.abspath(__file__))
and examine very carefully whether there is a real need for the case where exec
is used. It could be a sign of troubled design if you are not able to use your script as a module.
Keep in mind Zen of Python #8, and if you believe there is a good argument for a use-case where it must work for exec
, then please let us know some more details about the background of the problem.
just cut the string using split (the easy way):
var myString = "http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235"
var mySplitResult = myString.split("?");
alert(mySplitResult[0]);
blur event: when the element loses focus.
focusout event: when the element, or any element inside of it, loses focus.
As there is nothing inside the filter element, both blur and focusout will work in this case.
$(function() {
$('#filter').blur(function() {
$('#options').hide();
});
})
jsfiddle with blur: http://jsfiddle.net/yznhb8pc/
$(function() {
$('#filter').focusout(function() {
$('#options').hide();
});
})
jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/
See this IEEE_754_types.h
header for the union types to extract: float
, double
and long double
, (endianness handled). Here is an extract:
/*
** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
** Single Precision (float) -- Standard IEEE 754 Floating-point Specification
*/
# define IEEE_754_FLOAT_MANTISSA_BITS (23)
# define IEEE_754_FLOAT_EXPONENT_BITS (8)
# define IEEE_754_FLOAT_SIGN_BITS (1)
.
.
.
# if (IS_BIG_ENDIAN == 1)
typedef union {
float value;
struct {
__int8_t sign : IEEE_754_FLOAT_SIGN_BITS;
__int8_t exponent : IEEE_754_FLOAT_EXPONENT_BITS;
__uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
};
} IEEE_754_float;
# else
typedef union {
float value;
struct {
__uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
__int8_t exponent : IEEE_754_FLOAT_EXPONENT_BITS;
__int8_t sign : IEEE_754_FLOAT_SIGN_BITS;
};
} IEEE_754_float;
# endif
And see dtoa_base.c
for a demonstration of how to convert a double
value to string form.
Furthermore, check out section 1.2.1.1.4.2 - Floating-Point Type Memory Layout of the C/CPP Reference Book, it explains super well and in simple terms the memory representation/layout of all the floating-point types and how to decode them (w/ illustrations) following the actually IEEE 754 Floating-Point specification.
It also has links to really really good ressources that explain even deeper.
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526