From memory, you call stringstream::str()
to get the std::string
value out.
git reset --hard && git clean -dfx
or, zsh provides a 'gpristine' alias:
alias gpristine='git reset --hard && git clean -dfx'
Which is really handy. (warning: The "-x" will also delete 'git ignored' files, so remove this if it is not what you want)
If working on a forked repo, make sure to fetch and reset from the correct repo/branch, for example:
git fetch upstream && git reset --hard upstream/master && git clean -df
This is an old post but...
You can reference the working directory (the folder the .html file is located in) with ./
, and the directory above that with ../
Example directory structure:
/html/public/
- index.html
- script2.js
- js/
- script.js
To load script.js from inside index.html:
<script type="text/javascript" src="./js/script.js">
This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.
You could also specify ../
to go one directory above the working directory, to load things from there. But that is unusual.
The only reason is that Unix historically had a convention of all human-readable text files ending in a newline. At the time, this avoided extra processing when displaying or joining text files, and avoided treating text files differently to files containing other kinds of data (eg raw binary data which isn't human-readable).
Because of this convention, many tools from that era expect the ending newline, including text editors, diffing tools, and other text processing tools. Mac OS X was built on BSD Unix, and Linux was developed to be Unix-compatible, so both operating systems have inherited the same convention, behaviour and tools.
Windows wasn't developed to be Unix-compatible, so it doesn't have the same convention, and most Windows software will deal just fine with no trailing newline.
But, since Git was developed for Linux first, and a lot of open-source software is built on Unix-compatible systems like Linux, Mac OS X, FreeBSD, etc, most open-source communities and their tools (including programming languages) continue to follow these conventions.
There are technical reasons which made sense in 1971, but in this era it's mostly convention and maintaining compatibility with existing tools.
To update a single local package:
First find out your outdated packages:
npm outdated
Then update the package or packages that you want manually as:
npm update --save package_name
This way it is not necessary to update your local package.json
file.
Note that this will update your package to the latest version.
If you write some version in your package.json
file and do:
npm update package_name
In this case you will get just the next stable version (wanted) regarding the version that you wrote in your package.json
file.
And with npm list (package_name)
you can find out the current version of your local packages.
What about that?
HTML
<div class="chart" id="graph" data-percent="88"></div>
Javascript
var el = document.getElementById('graph'); // get canvas
var options = {
percent: el.getAttribute('data-percent') || 25,
size: el.getAttribute('data-size') || 220,
lineWidth: el.getAttribute('data-line') || 15,
rotate: el.getAttribute('data-rotate') || 0
}
var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';
if (typeof(G_vmlCanvasManager) !== 'undefined') {
G_vmlCanvasManager.initElement(canvas);
}
var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;
el.appendChild(span);
el.appendChild(canvas);
ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg
//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;
var drawCircle = function(color, lineWidth, percent) {
percent = Math.min(Math.max(0, percent || 1), 1);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
ctx.strokeStyle = color;
ctx.lineCap = 'round'; // butt, round or square
ctx.lineWidth = lineWidth
ctx.stroke();
};
drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);
and CSS
div {
position:relative;
margin:80px;
width:220px; height:220px;
}
canvas {
display: block;
position:absolute;
top:0;
left:0;
}
span {
color:#555;
display:block;
line-height:220px;
text-align:center;
width:220px;
font-family:sans-serif;
font-size:40px;
font-weight:100;
margin-left:5px;
}
http://jsfiddle.net/Aapn8/3410/
Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/
Enums are just classes in disguise, so for the most part, anything you can do with a class you can do with an enum.
I cannot think of a reason that an enum should not be able to implement an interface, at the same time I cannot think of a good reason for them to either.
I would say once you start adding thing like interfaces, or method to an enum you should really consider making it a class instead. Of course I am sure there are valid cases for doing non-traditional enum things, and since the limit would be an artificial one, I am in favour of letting people do what they want there.
Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.
You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.
angular.element('*[ng-app]').injector()
In chrome, however, you can point to target ng-app as shown below. and use the $0
hack and issue angular.element($0).injector()
Once you have the injector, get any dependency injected service as below
injector = angular.element($0).injector();
injector.get('$mdToast');
Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.
The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git
For example, cloning a repository on a machine to which you have SSH access using the "dev" user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:
git clone ssh://[email protected]/srv/repositories/awesomeproject.git
Create-react-app Version 2+ answer
For recent (> v2) versions of create-react-app (and possible older as well), add the following line to your package.json, then rebuild.
"homepage": "./"
You should now see the build/index.html will have relative links ./static/...
instead of links to the server root: /static/...
.
From where did you get the idea that you need to free(token)
and free(tk)
? You don't. strsep()
doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc()
(or similar), so free()
ing them is undefined behavior. You only need to free(s)
when you are done with the entire string.
Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup()
and free()
altogether by simply writing char *s = p;
.
if you want to remove all elements with matching ID parts, for example:
<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>
try this:
$("span[id*=myID]").remove();
don't forget the '*' - this will remove them all at once - cheers
Try this:
<?php
# Init the MySQL Connection
if( !( $db = mysql_connect( 'localhost' , 'root' , '' ) ) )
die( 'Failed to connect to MySQL Database Server - #'.mysql_errno().': '.mysql_error();
if( !mysql_select_db( 'ram' ) )
die( 'Connected to Server, but Failed to Connect to Database - #'.mysql_errno().': '.mysql_error();
# Prepare the INSERT Query
$insertTPL = 'INSERT INTO `name` VALUES( "%s" , "%s" , "%s" , "%s" )';
$insertSQL = sprintf( $insertTPL ,
mysql_real_escape_string( $name ) ,
mysql_real_escape_string( $add1 ) ,
mysql_real_escape_string( $add2 ) ,
mysql_real_escape_string( $mail ) );
# Execute the INSERT Query
if( !( $insertRes = mysql_query( $insertSQL ) ) ){
echo '<p>Insert of Row into Database Failed - #'.mysql_errno().': '.mysql_error().'</p>';
}else{
echo '<p>Person\'s Information Inserted</p>'
}
# Prepare the SELECT Query
$selectSQL = 'SELECT * FROM `names`';
# Execute the SELECT Query
if( !( $selectRes = mysql_query( $selectSQL ) ) ){
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}else{
?>
<table border="2">
<thead>
<tr>
<th>Name</th>
<th>Address Line 1</th>
<th>Address Line 2</th>
<th>Email Id</th>
</tr>
</thead>
<tbody>
<?php
if( mysql_num_rows( $selectRes )==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysql_fetch_assoc( $selectRes ) ){
echo "<tr><td>{$row['name']}</td><td>{$row['addr1']}</td><td>{$row['addr2']}</td><td>{$row['mail']}</td></tr>\n";
}
}
?>
</tbody>
</table>
<?php
}
?>
Your initial solution did not show any obvious santisation of the values before passing them into the Database. This is how SQL Injection attacks (or even un-intentional errors being passed through SQL) occur. Don't do it!
Your database does not seem to have a Primary Key. Whilst these are not, technically, necessary in all usage, they are a good practice, and make for a much more reliable way of referring to a specific row in a table, whether for adding related tables, or for making changes within that table.
You need to check every action, at every stage, for errors. Most PHP functions are nice enough to have a response they will return under an error condition. It is your job to check for those conditions as you go - never assume that PHP will do what you expect, how you expect, and in the order you expect. This is how accident happen...
My provided code above contains alot of points where, if an error has occured, a message will be returned. Try it, see if any error messages are reported, look at the Error Message, and, if applicable, the Error Code returned and do some research.
Good luck.
This question is confusing. A regular object, {}
doesn't have a length
property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in
statement on the object, since length
is not set, and increment a counter.
I'm confused as to why you need the length
. Are you manually setting 0
on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';
. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length
is already set.
From Java8:
import java.time.Instant;
import java.util.Date;
Date date = Date.from(Instant.parse("2000-01-01T00:00:00.000Z"))
The only way to retrieve the correct value in your context is to run $.ajax()
function synchronously (what actually contradicts to main AJAX idea). There is the special configuration attribute async
you should set to false
. In that case the main scope which actually contains $.ajax()
function call is paused until the synchronous function is done, so, the return
is called only after $.ajax()
.
function doSomething() {
var status = 0;
$.ajax({
url: 'action.php',
type: 'POST',
data: dataString,
async: false,
success: function (txtBack) {
if (txtBack == 1)
status = 1;
}
});
return status;
}
var response = doSomething();
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)
Explanation:
ABC: # match literal characters 'ABC:'
* # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses
* # zero or more spaces
(.+) # capture one or more of any character (except newlines)
To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+)
No value is considered false, only the absence of the attribute. There are plenty of invalid values though, and some implementations might consider certain invalid values as false.
HTML5 spec
http://www.w3.org/TR/html5/forms.html#attr-input-checked :
The disabled content attribute is a boolean attribute.
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion
The following are valid, equivalent and true:
<input type="checkbox" checked />
<input type="checkbox" checked="" />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="ChEcKeD" />
The following are invalid:
<input type="checkbox" checked="0" />
<input type="checkbox" checked="1" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />
The absence of the attribute is the only valid syntax for false:
<input type="checkbox" />
Recommendation
If you care about writing valid XHTML, use checked="checked"
, since <input checked>
is invalid and other alternatives are less readable. Else, just use <input checked>
as it is shorter.
Quoting Mr Initial Man from here:
Instead of this:
<div id="Top" class="info"></div><a href="#" class="a_info"></a>
Use this:
<span id="Top" class="info"></span><a href="#" class="a_info"></a>
Also, you could use this:
<div id="Top" class="info"><a href="#" class="a_info"></a></div>
And gostbustaz:
If you absoultely must use a
<div>
, you can setdiv { display: inline; }
in your stylesheet.
Of course, that essentially makes the
<div>
a<span>
.
Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:
The following program would determine that:
#include <stdio.h>
#include <stdint.h>
int is_big_endian(void)
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
int main(void)
{
printf("System is %s-endian.\n",
is_big_endian() ? "big" : "little");
return 0;
}
You also have this approach; from Quake II:
byte swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
bigendien = false;
And !is_big_endian()
is not 100% to be little as it can be mixed/middle.
Believe this can be checked using same approach only change value from 0x01000000
to i.e. 0x01020304
giving:
switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE
But not entirely sure about that one ...
The other option for using PHP scripts sans extension is
Options +MultiViews
Or even just following in the directories .htaccess
:
DefaultType application/x-httpd-php
The latter allows having all filenames without extension script
being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
Best would be not using LinkedList
at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)
Use ArrayList
, and iterate with
int len = list.size();
for (int i = 0; i < len; i++) {
Element ele = list.get(i);
}
Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:
iter = list.listIterator();
(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
HTML input number type allows "e/E" because "e" stands for exponential which is a numeric symbol.
Example 200000 can also be written as 2e5. I hope this helps thank you for the question.
Here is another simple answer, but without using classes.
from tkinter import *
def raise_frame(frame):
frame.tkraise()
root = Tk()
f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)
for frame in (f1, f2, f3, f4):
frame.grid(row=0, column=0, sticky='news')
Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()
Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()
Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')
Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()
raise_frame(f1)
root.mainloop()
I needed to do the same thing, so have written some JavaScript to enable this, using the onSelect
and beforeShowDay
events. It maintains its own array of selected dates, so unfortunately doesn't integrate with a textbox showing the current date, etc. I'm just using it as an inline control, and I can then query the array for the currently selected dates.
I used this code as a basis.
<script type="text/javascript">
// Maintain array of dates
var dates = new Array();
function addDate(date) {
if (jQuery.inArray(date, dates) < 0)
dates.push(date);
}
function removeDate(index) {
dates.splice(index, 1);
}
// Adds a date if we don't have it yet, else remove it
function addOrRemoveDate(date) {
var index = jQuery.inArray(date, dates);
if (index >= 0)
removeDate(index);
else
addDate(date);
}
// Takes a 1-digit number and inserts a zero before it
function padNumber(number) {
var ret = new String(number);
if (ret.length == 1)
ret = "0" + ret;
return ret;
}
jQuery(function () {
jQuery("#datepicker").datepicker({
onSelect: function (dateText, inst) {
addOrRemoveDate(dateText);
},
beforeShowDay: function (date) {
var year = date.getFullYear();
// months and days are inserted into the array in the form, e.g "01/01/2009", but here the format is "1/1/2009"
var month = padNumber(date.getMonth() + 1);
var day = padNumber(date.getDate());
// This depends on the datepicker's date format
var dateString = month + "/" + day + "/" + year;
var gotDate = jQuery.inArray(dateString, dates);
if (gotDate >= 0) {
// Enable date so it can be deselected. Set style to be highlighted
return [true, "ui-state-highlight"];
}
// Dates not in the array are left enabled, but with no extra style
return [true, ""];
}
});
});
</script>
You can also easily pass parameters to modal controller by added a new property with instance of modal and get it to modal controller. For example:
Following is my click event on which i want to open modal view.
$scope.openMyModalView = function() {
var modalInstance = $modal.open({
templateUrl: 'app/userDetailView.html',
controller: 'UserDetailCtrl as userDetail'
});
// add your parameter with modal instance
modalInstance.userName = 'xyz';
};
Modal Controller:
angular.module('myApp').controller('UserDetailCtrl', ['$modalInstance',
function ($modalInstance) {
// get your parameter from modal instance
var currentUser = $modalInstance.userName;
// do your work...
}]);
In newer versions of Qt Creator (Currently using 4.4.1), you can follow these simple steps:
Tools > Options > Environment > Interface
Here you can change the theme to Flat Dark
.
It will change the whole Qt Creator theme, not just the editor window.
To store another value in select options:
$("#select").append('<option value="4">another</option>')
You can flush hosts local MySQL using following command:
mysqladmin -u [username] -p flush-hosts
**** [MySQL password]
or
mysqladmin flush-hosts -u [username] -p
**** [MySQL password]
Though Amazon RDS database server is on network then use the following command as like as flush network MySQL server:
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts
In additional suggestion you can permanently solve blocked of many connections error problem by editing my.ini file[Mysql configuration file]
change variables max_connections = 10000;
or
login into MySQL using command line -
mysql -u [username] -p
**** [MySQL password]
put the below command into MySQL window
SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;
check veritable using command-
show variables like "max_connections";
show variables like "max_connect_errors";
First of all, finish()
doesn't destroy your process and free up the memory. It just removes the activity from the activity stack. You'd need to kill the process, which is answered in a bunch of questions (since this is being asked several times).
But the proper answer is - Don't do it. the Android OS will automatically free up memory when it needs memory. By not freeing up memory, your app will start up faster if the user gets back to it.
Please see here for a great write-up on the topic.
If you want to use Python and SVN to download a specific GitHub directory, here is the code that you would use:
import validators
from svn.remote import RemoteClient
def download_folder(url):
if 'tree/master' in url:
url = url.replace('tree/master', 'trunk')
r = RemoteClient(url)
r.export('output')
if __name__ == '__main__':
url = input('Enter folder URL: ')
if not validators.url(url):
print('Invalid url')
else:
download_folder(url)
You can check more details about this code and other GitHub search and download tips in this tutorial: https://python.gotrained.com/search-github-api/
If you are having pre built data base than copy it in asset folder and create an new class as DataBaseHelper which implements SQLiteOpenHelper Than use following code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelperClass extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/package_name/databases/";
// Data Base Name.
private static final String DATABASE_NAME = "DBName.sqlite";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name = "tableName";
public Context context;
static SQLiteDatabase sqliteDataBase;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
* Parameters of super() are 1. Context
* 2. Data Base Name.
* 3. Cursor Factory.
* 4. Data Base Version.
*/
public DataBaseHelperClass(Context context) {
super(context, DATABASE_NAME, null ,DATABASE_VERSION);
this.context = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* By calling this method and empty database will be created into the default system path
* of your application so we are gonna be able to overwrite that database with our database.
* */
public void createDataBase() throws IOException{
//check if the database exists
boolean databaseExist = checkDataBase();
if(databaseExist){
// Do Nothing.
}else{
this.getWritableDatabase();
copyDataBase();
}// end if else dbExist
} // end createDataBase().
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(){
File databaseFile = new File(DB_PATH + DATABASE_NAME);
return databaseFile.exists();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transferring byte stream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DATABASE_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/**
* This method opens the data base connection.
* First it create the path up till data base of the device.
* Then create connection with data base.
*/
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* This Method is used to close the data base connection.
*/
@Override
public synchronized void close() {
if(sqliteDataBase != null)
sqliteDataBase.close();
super.close();
}
/**
* Apply your methods and class to fetch data using raw or queries on data base using
* following demo example code as:
*/
public String getUserNameFromDB(){
String query = "select User_First_Name From "+TABLE_USER_DETAILS;
Cursor cursor = sqliteDataBase.rawQuery(query, null);
String userName = null;
if(cursor.getCount()>0){
if(cursor.moveToFirst()){
do{
userName = cursor.getString(0);
}while (cursor.moveToNext());
}
}
return userName;
}
@Override
public void onCreate(SQLiteDatabase db) {
// No need to write the create table query.
// As we are using Pre built data base.
// Which is ReadOnly.
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// No need to write the update table query.
// As we are using Pre built data base.
// Which is ReadOnly.
// We should not update it as requirements of application.
}
}
Hope this will help you...
Try the following:-
ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.
YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")
Example:-
$(document).ready(function() {
$("#date").datepicker({
changeYear:true,
yearRange: "2005:2015"
});
});
Have you looked at the DateUtils truncate method in Apache Commons Lang?
Date truncatedDate = DateUtils.truncate(new Date(), Calendar.DATE);
will remove the time element.
SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname,
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE
Lname END AS LnameTrue FROM dbo.____Fname_Lname
import MySQLdb
class Database:
host = 'localhost'
user = 'root'
password = '123'
db = 'test'
def __init__(self):
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(query)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)
# Data Insert into the table
query = """
INSERT INTO basic_python_database
(`name`, `age`)
VALUES
('Mike', 21),
('Michael', 21),
('Imran', 21)
"""
# db.query(query)
db.insert(query)
# Data retrieved from the table
select_query = """
SELECT * FROM basic_python_database
WHERE age = 21
"""
people = db.query(select_query)
for person in people:
print "Found %s " % person['name']
Edit: @WickyNilliams has noted that setting display: block on a table body will strip the table of semantics and thus is not a good solution due to accessibility issues.
I had good success with the solution proposed by @Serge Stroobandt, but I encountered the problem @Shevy had with the cells then not filling the full width of the table. I was able to fix this by adding some styles to the tbody
.
table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
table tbody {
display: table;
width: 100%;
}
This worked for me in Firefox, Chrome, and Safari on Mac.
You can use a simple "null function" for this, for example:
func Use(vals ...interface{}) {
for _, val := range vals {
_ = val
}
}
Which you can use like so:
package main
func main() {
a := "declared and not used"
b := "another declared and not used"
c := 123
Use(a, b, c)
}
There's also a package for this so you don't have to define the Use
function every time:
import (
"github.com/lunux2008/xulu"
)
func main() {
// [..]
xulu.Use(a, b, c)
}
For any Single File Component users, here is how I set up global variable(s)
Declare your variable(s) in somewhere variable.js
const shallWeUseVuex = false;
Export it in variable.js
module.exports = { shallWeUseVuex : shallWeUseVuex };
Require
and assign it in your vue file
export default {
data() {
return {
shallWeUseVuex: require('../../variable.js')
};
}
}
Ref: https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch
The Mockito javadoc seems to tell why use doReturn()
instead of when()
Use doReturn() in those rare occasions when you cannot use Mockito.when(Object).
Beware that Mockito.when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).
Here are those rare occasions when doReturn() comes handy:
1. When spying real objects and calling real methods on a spy brings side effects
List list = new LinkedList(); List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing:
doReturn("foo").when(spy).get(0);
2. Overriding a previous exception-stubbing:
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar");
//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();
Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.
Worked for me in VS2003 and VS2017 on Windows 8
Run the command in CMD with admin rights
netsh http add iplisten ipaddress=::
Then go to regedit path [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters]
and check if the value has been added.
For more details check https://www.c-sharpcorner.com/blogs/iis-express-failed-to-register-url-access-is-denied
Follow the code below exactly matched with your case.
ie for
<div class="facetContainerDiv">
<div>
</div>
</div>
2. Create an IList with all the elements inside the second div i.e for,
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
3. Access each check boxes using the index
Please find the code below
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTests
{
class ChechBoxClickWthIndex
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("file:///C:/Users/chery/Desktop/CheckBox.html");
// Create an interface WebElement of the div under div with **class as facetContainerDiv**
IWebElement WebElement = driver.FindElement(By.XPath("//div[@class='facetContainerDiv']/div"));
// Create an IList and intialize it with all the elements of div under div with **class as facetContainerDiv**
IList<IWebElement> AllCheckBoxes = WebElement.FindElements(By.XPath("//label/input"));
int RowCount = AllCheckBoxes.Count;
for (int i = 0; i < RowCount; i++)
{
// Check the check boxes based on index
AllCheckBoxes[i].Click();
}
Console.WriteLine(RowCount);
Console.ReadLine();
}
}
}
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "
Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).
app.py
:
from flask import Flask
from celery import Celery
broker_url = 'amqp://guest@localhost' # Broker URL for RabbitMQ task queue
app = Flask(__name__)
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig') # Your celery configurations in a celeryconfig.py
@celery.task(bind=True)
def some_long_task(self, x, y):
# Do some long task
...
@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
...
data = json.loads(request.data)
text_list = data.get('text_list')
final_file = audio_class.render_audio(data=text_list)
some_long_task.delay(x, y) # Call your async task and pass whatever necessary variables
return Response(
mimetype='application/json',
status=200
)
Run your Flask app, and start another process to run your celery worker.
$ celery worker -A app.celery --loglevel=debug
I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.
This is impossible as you cannot return from an asynchronous call inside a synchronous method.
In this case you need to pass a callback to foo that will receive the return value
function foo(address, fn){
geocoder.geocode( { 'address': address}, function(results, status) {
fn(results[0].geometry.location);
});
}
foo("address", function(location){
alert(location); // this is where you get the return value
});
The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.
If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.
I think you can use the nrows
parameter. From the docs:
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):
In [1]: import pandas as pd
In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s
In [3]: len(z)
Out[3]: 20
In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s
you can disable via css:
pointer-events: none;
Doesn't work everywhere though.
I had the same problem and this code solves it. I got this solution from this article but I had to adjust the time on the interval for it to work.
setTimeout(function(){
oTable.fnAdjustColumnSizing();
},50);
I came up with the same problem and I'm sharing how I fixed it. It may help some people.
First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :
**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**
<application ...>
...
</application>
Then, request that the user approve each permission at runtime
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// here, Permission is not granted
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
}
For more information, have a look at the API documentation here
List
has the method add(int, E)
, so you can use:
list.add(0, yourObject);
Afterwards you can delete the last element with:
if(list.size() > 10)
list.remove(list.size() - 1);
However, you might want to rethink your requirements or use a different data structure, like a Queue
EDIT
Maybe have a look at Apache's CircularFifoQueue
:
CircularFifoQueue
is a first-in first-out queue with a fixed size that replaces its oldest element if full.
Just initialize it with you maximum size:
CircularFifoQueue queue = new CircularFifoQueue(10);
I looked for the answer to a similar question on this page, I wrote the answers to several similar questions that may help people who enter this page.
List < T > class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists.
Class with property:
class TestClss
{
public string id { set; get; }
public string cell1 { set; get; }
public string cell2 { set; get; }
}
var MyArray = new List<TestClss> {
new TestClss() { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
new TestClss() { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
new TestClss() { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data" }
};
foreach (object Item in MyArray)
{
Console.WriteLine("Row Start");
foreach (PropertyInfo property in Item.GetType().GetProperties())
{
var Key = property.Name;
var Value = property.GetValue(Item, null);
Console.WriteLine("{0}={1}", Key, Value);
}
}
OR, Class with field:
class TestClss
{
public string id = "";
public string cell1 = "";
public string cell2 = "";
}
var MyArray = new List<TestClss> {
new TestClss() { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
new TestClss() { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
new TestClss() { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data" }
};
foreach (object Item in MyArray)
{
Console.WriteLine("Row Start");
foreach (var fieldInfo in Item.GetType().GetFields())
{
var Key = fieldInfo.Name;
var Value = fieldInfo.GetValue(Item);
}
}
OR, List of objects (without same cells):
var MyArray = new List<object> {
new { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
new { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
new { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data", anotherCell = "" }
};
foreach (object Item in MyArray)
{
Console.WriteLine("Row Start");
foreach (var props in Item.GetType().GetProperties())
{
var Key = props.Name;
var Value = props.GetMethod.Invoke(Item, null).ToString();
Console.WriteLine("{0}={1}", Key, Value);
}
}
OR, List of objects (It must have the same cells):
var MyArray = new[] {
new { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
new { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
new { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data" }
};
foreach (object Item in MyArray)
{
Console.WriteLine("Row Start");
foreach (var props in Item.GetType().GetProperties())
{
var Key = props.Name;
var Value = props.GetMethod.Invoke(Item, null).ToString();
Console.WriteLine("{0}={1}", Key, Value);
}
}
OR, List of objects (with key):
var MyArray = new {
row1 = new { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
row2 = new { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
row3 = new { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data" }
};
// using System.ComponentModel; for TypeDescriptor
foreach (PropertyDescriptor Item in TypeDescriptor.GetProperties(MyArray))
{
string Rowkey = Item.Name;
object RowValue = Item.GetValue(MyArray);
Console.WriteLine("Row key is: {0}", Rowkey);
foreach (var props in RowValue.GetType().GetProperties())
{
var Key = props.Name;
var Value = props.GetMethod.Invoke(RowValue, null).ToString();
Console.WriteLine("{0}={1}", Key, Value);
}
}
OR, List of Dictionary
var MyArray = new List<Dictionary<string, string>>() {
new Dictionary<string, string>() { { "id", "1" }, { "cell1", "cell 1 row 1 Data" }, { "cell2", "cell 2 row 1 Data" } },
new Dictionary<string, string>() { { "id", "2" }, { "cell1", "cell 1 row 2 Data" }, { "cell2", "cell 2 row 2 Data" } },
new Dictionary<string, string>() { { "id", "3" }, { "cell1", "cell 1 row 3 Data" }, { "cell2", "cell 2 row 3 Data" } }
};
foreach (Dictionary<string, string> Item in MyArray)
{
Console.WriteLine("Row Start");
foreach (KeyValuePair<string, string> props in Item)
{
var Key = props.Key;
var Value = props.Value;
Console.WriteLine("{0}={1}", Key, Value);
}
}
Good luck..
To temporarily set an environment variable without having to copy the os.envrion object etc, I do this:
process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', \
'rsync://[email protected]::'], stdout=subprocess.PIPE)
Use @media
queries. They serve this exact purpose. Here's an example how they work:
@media (max-width: 800px) {
/* CSS that should be displayed if width is equal to or less than 800px goes here */
}
This would work only on devices whose width is equal to or less than 800px.
Read up more about media queries on the Mozilla Developer Network.
Generally, I agree with @kgrittn's advice. Go for it.
But to address your basic question about concat()
: The new function concat()
is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.
If you can rule out null values, the good old (SQL standard) concatenation operator ||
is still the best choice, and @luis' answer is just fine:
SELECT col_a || col_b;
If either of your columns can be null, the result would be null in that case. You could defend with COALESCE
:
SELECT COALESCE(col_a, '') || COALESCE(col_b, '');
But that get tedious quickly with more arguments. That's where concat()
comes in, which never returns null, not even if all arguments are null. Per documentation:
NULL arguments are ignored.
SELECT concat(col_a, col_b);
The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string ''
, but one might want null instead (at least I would). One possible way:
SELECT CASE
WHEN col_a IS NULL THEN col_b
WHEN col_b IS NULL THEN col_a
ELSE col_a || col_b
END;
This gets more complex with more columns quickly. Again, use concat()
but add a check for the special condition:
SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
ELSE concat(col_a, col_b) END;
How does this work?
(col_a, col_b)
is shorthand notation for a row type expression ROW (col_a, col_b)
. And a row type is only null if all columns are null. Detailed explanation:
Also, use concat_ws()
to add separators between elements (ws
for "with separator").
An expression like the one in Kevin's answer:
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
is tedious to prepare for null values in PostgreSQL 8.3 (without concat()
). One way (of many):
SELECT COALESCE(
CASE
WHEN $1.zipcode IS NULL THEN $1.city
WHEN $1.city IS NULL THEN $1.zipcode
ELSE $1.zipcode || ' - ' || $1.city
END, '')
|| COALESCE(', ' || $1.state, '');
STABLE
concat()
and concat_ws()
are STABLE
functions, not IMMUTABLE
because they can invoke datatype output functions (like timestamptz_out
) that depend on locale settings.
Explanation by Tom Lane.
This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE
function wrapper. Example here:
Added streaming support based on the answer of @dunes:
import re
from json import JSONDecoder, JSONDecodeError
NOT_WHITESPACE = re.compile(r"[^\s]")
def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
buf = ""
ex = None
while True:
block = file_obj.read(buf_size)
if not block:
break
buf += block
pos = 0
while True:
match = NOT_WHITESPACE.search(buf, pos)
if not match:
break
pos = match.start()
try:
obj, pos = decoder.raw_decode(buf, pos)
except JSONDecodeError as e:
ex = e
break
else:
ex = None
yield obj
buf = buf[pos:]
if ex is not None:
raise ex
On the mac I followed the steps of the user Tree but still received the answer "flutter: command not found". What I did next was, go to the folder flutter/bin and inside this folder ctrl+click on flutter executable and in the popup i clicked open. After that the mac already recognized this as an exception and the flutter commands already work.
below html5 versions
iframe {
overflow:hidden;
}
In html5
<iframe seamless="seamless" ....>
iframe[seamless]{
overflow: hidden;
}
but not supported correctly yet
On Centos 6.5/PostgreSQL 9.3:
Change the value of "PGDATA=/var/lib/pgsql/data"
to whatever location you want in the initial script file /etc/init.d/postgresql
.
Remember to chmod 700
and chown postgres:postgres
to the new location and you're the boss.
append()
& prepend()
are for inserting content inside an element (making the content its child) while after()
& before()
insert content outside an element (making the content its sibling).
I'm writing common function for change window
this code can be used parallel in all type of project
function changewindow(url,userdata){
$.ajax({
type: "POST",
url: url,
data: userdata,
dataType: "html",
success: function(html){
$("#bodycontent").html(html);
},
error: function(html){
alert(html);
}
});
}
You're reading the entire file into memory (line = u.readlines()
) which will fail of course if the file is too large (and you say that some are up to 20 GB), so that's your problem right there.
Better iterate over each line:
for current_line in u:
do_something_with(current_line)
is the recommended approach.
Later in your script, you're doing some very strange things like first counting all the items in a list, then constructing a for
loop over the range of that count. Why not iterate over the list directly? What is the purpose of your script? I have the impression that this could be done much easier.
This is one of the advantages of high-level languages like Python (as opposed to C where you do have to do these housekeeping tasks yourself): Allow Python to handle iteration for you, and only collect in memory what you actually need to have in memory at any given time.
Also, as it seems that you're processing TSV files (tabulator-separated values), you should take a look at the csv
module which will handle all the splitting, removing of \n
s etc. for you.
I think this can also works for you select count(*) as anc,(select count(*) from Patient where sex='F')as patientF,(select count(*) from Patient where sex='M') as patientM from anc
and also you can select and count related tables like this select count(*) as anc,(select count(*) from Patient where Patient.Id=anc.PatientId)as patientF,(select count(*) from Patient where sex='M') as patientM from anc
Arrays in @RequestParam
are used for binding several parameters of the same name:
myparam=myValue1&myparam=myValue2&myparam=myValue3
If you need to bind @ModelAttribute
-style indexed parameters, I guess you need @ModelAttribute
anyway.
You can specify a Python version for pip
to use:
pip3.4 install requests
Python 3.4 has pip support built-in, so you can also use:
python3.4 -m pip install
If you're running Ubuntu (or probably Debian as well), you'll need to install the system pip3
separately:
sudo apt-get install python3-pip
This will install the pip3
executable, so you can use it, as well as the earlier mentioned python3.4 -m pip
:
pip3 install requests
class A{
public void methodA(){
new B().methodB();
//or
B.methodB1();
}
}
class B{
//instance method
public void methodB(){
}
//static method
public static void methodB1(){
}
}
Or, you can make Java Groovy and just overload these functions to achieve what you want
//plus() => for the + operator
//multiply() => for the * operator
//leftShift() = for the << operator
// ... and so on ...
class Fish {
def leftShift(Fish fish) {
print "You just << (left shifted) some fish "
}
}
def fish = new Fish()
def fish2 = new Fish()
fish << fish2
Who doesnt want to be/use groovy? :D
No you cannot use the compiled groovy JARs in Java the same way. It still is a compiler error for Java.
I had the same problem yesterday :-)
$("#SelectedCountryId option:selected").text()
I also read that this is slow, if you want to use it often you should probably use something else.
I don't know why yours is not working, this one is for me, maybe someone else can help...
Confirm in API documentation http://api.jquery.com/jQuery.each/ say:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
and this is my example http://jsfiddle.net/r6jqP/
(function($){
$('#go').on('click',function(){
var i=0,
all=0;
$('li').each(function(){
all++;
if($('#mytext').val()=='continue')return true;
i++;
if($('#mytext').val()==$(this).html()){
return false;
}
});
alert('Iterazione : '+i+' to '+all);
});
}(jQuery));
The only reason we store images in our tables is because each table (or set of tables per range of work) is temporary and dropped at the end of the workflow. If there was any sort of long term storage we'd definitely opt for storing file paths.
It should also be noted that we work with a client/server application internally so there's no web interface to worry about.
Something like that
Function imgTo64(ByVal thePath As String) As String
Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
Dim m As IO.MemoryStream = New IO.MemoryStream()
img.Save(m, img.RawFormat)
Dim imageBytes As Byte() = m.ToArray
img.Dispose()
Dim str64 = Convert.ToBase64String(imageBytes)
Return str64
End Function
In the specific case of react-router
, using context
is a valid case scenario, e.g.
class MyComponent extends React.Component {
props: PropsType;
static contextTypes = {
router: PropTypes.object
};
render () {
this.context.router;
}
}
You can access an instance of the history via the router context, e.g. this.context.router.history
.
It has already been mentioned that hashmaps are O(n/m)
in average, if n
is the number of items and m
is the size. It has also been mentioned that in principle the whole thing could collapse into a singly linked list with O(n)
query time. (This all assumes that calculating the hash is constant time).
However what isn't often mentioned is, that with probability at least 1-1/n
(so for 1000 items that's a 99.9% chance) the largest bucket won't be filled more than O(logn)
! Hence matching the average complexity of binary search trees. (And the constant is good, a tighter bound is (log n)*(m/n) + O(1)
).
All that's required for this theoretical bound is that you use a reasonably good hash function (see Wikipedia: Universal Hashing. It can be as simple as a*x>>m
). And of course that the person giving you the values to hash doesn't know how you have chosen your random constants.
TL;DR: With Very High Probability the worst case get/put complexity of a hashmap is O(logn)
.
int arr[] = new int[15];
The variable arr
holds a memory address. At the memory address, there are 15 consecutive ints in a row. They can be referenced with index 0 to 14 inclusive.
In php i can just do this arr[]=22; this will automatically add 22 to the next empty index of array.
There is no concept of 'next' when dealing with arrays.
One important thing that I think you are missing is that as soon as the array is created, all elements of the array already exist. They are uninitialized, but they all do exist already. So you aren't 'filling' the elements of the array as you go, they are already filled, just with uninitialized values. There is no way to test for an uninitialized element in an array.
It sounds like you want to use a data structure such as a queue or stack or vector.
You should use
import Dan.Vik;
This makes the class visible and the its public methods available.
Java 8 solution (like this but a bit simpler):
public static List<String> partition(String string, int partSize) {
List<String> parts = IntStream.range(0, string.length() / partSize)
.mapToObj(i -> string.substring(i * partSize, (i + 1) * partSize))
.collect(toList());
if ((string.length() % partSize) != 0)
parts.add(string.substring(string.length() / partSize * partSize));
return parts;
}
As always in python, there are of course several ways to do it, but there is one obvious way to do it.
tmpdict["ONE"]["TWO"]["THREE"]
is the obvious way to do it.
When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem.
If you just want to just save you repetative typing, you can of course alias a subset of the dict:
>>> two_dict = tmpdict['ONE']['TWO'] # now you can just write two_dict for tmpdict['ONE']['TWO']
>>> two_dict["spam"] = 23
>>> tmpdict
{'ONE': {'TWO': {'THREE': 10, 'spam': 23}}}
My Theme plugin provide full featured customization for Eclipse 4. Try it. Visit Plugin Page
You can try out this implementation for running Swift 5 on XCode 11
class CustomView: UIView {
var customParam: customType
var container = UIView()
required init(customParamArg: customType) {
self.customParam = customParamArg
super.init(frame: .zero)
// Setting up the view can be done here
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
// Can do the setup of the view, including adding subviews
setupConstraints()
}
func setupConstraints() {
// setup custom constraints as you wish
}
}
is there a smarter way to do this in Python
This hasn't been mentioned, so I'll go ahead - there is a merge stdlib function in the heapq module of python 2.6+. If all you're looking to do is getting things done, this might be a better idea. Of course, if you want to implement your own, the merge of merge-sort is the way to go.
>>> list1 = [1, 5, 8, 10, 50]
>>> list2 = [3, 4, 29, 41, 45, 49]
>>> from heapq import merge
>>> list(merge(list1, list2))
[1, 3, 4, 5, 8, 10, 29, 41, 45, 49, 50]
Here's the documentation.
I haven't been able to get it to work without specifying a width but the following css worked
.wrapper {
background: #DDD;
padding: 10px;
display: inline-block;
height: 20px;
width: auto;
}
.contents {
background: #c3c;
overflow: hidden;
white-space: nowrap;
display: inline-block;
visibility: hidden;
width: 1px;
-webkit-transition: width 1s ease-in-out, visibility 1s linear;
-moz-transition: width 1s ease-in-out, visibility 1s linear;
-o-transition: width 1s ease-in-out, visibility 1s linear;
transition: width 1s ease-in-out, visibility 1s linear;
}
.wrapper:hover .contents {
width: 200px;
visibility: visible;
}
I'm not sure you will be able to get it working without setting a width on it.
I had this problem when using java 9+ modules. I had to open
the module in order for the com.fasterxml.jackson.databind
to access the objects with reflection. Alternatively you could only open the package where the models are located if you have one.
If working with Basic4Android and looking for an easy fix to the problem, try this it works both Google maps and Openstreet even though OSM creates a bit of a messy result and thanx to [yndolok] for the google marker
GooglemLoc="https://www.google.com/maps/place/"&[Latitude]&"+"&[Longitude]&"/@"&[Latitude]&","&[Longitude]&",15z"
GooglemRute="https://www.google.co.ls/maps/dir/"&[FrmLatt]&","&[FrmLong]&"/"&[ToLatt]&","&[FrmLong]&"/@"&[ScreenX]&","&[ScreenY]&",14z/data=!3m1!4b1!4m2!4m1!3e0?hl=en" 'route ?hl=en
OpenStreetLoc="https://www.openstreetmap.org/#map=16/"&[Latitude]&"/"&[Longitude]&"&layers=N"
OpenStreetRute="https://www.openstreetmap.org/directions?engine=osrm_car&route="&[FrmLatt]&"%2C"&[FrmLong]&"%3B"&[ToLatt]&"%2C"&[ToLong]&"#Map=15/"&[ScreenX]&"/"&[Screeny]&"&layers=N"
Supplier with a one-to-many relationship with Product. One Supplier has (supplies) many Products.
***** Table: Supplier *****
+-----+-------------------+
| ID | NAME |
+-----+-------------------+
| 1 | Supplier Name 1 |
| 2 | Supplier Name 2 |
| 3 | Supplier Name 3 |
| 4 | Supplier Name 4 |
+-----+-------------------+
***** Table: Product *****
+-----+-----------+--------------------+-------+------------+
| ID | NAME | DESCRIPTION | PRICE | SUPPLIERID |
+-----+-----------+--------------------+-------+------------+
|1 | Product 1 | Name for Product 1 | 2.0 | 1 |
|2 | Product 2 | Name for Product 2 | 22.0 | 1 |
|3 | Product 3 | Name for Product 3 | 30.0 | 2 |
|4 | Product 4 | Name for Product 4 | 7.0 | 3 |
+-----+-----------+--------------------+-------+------------+
Factors:
Lazy mode for Supplier set to “true” (default)
Fetch mode used for querying on Product is Select
Fetch mode (default): Supplier information is accessed
Caching does not play a role for the first time the
Supplier is accessed
Fetch mode is Select Fetch (default)
// It takes Select fetch mode as a default
Query query = session.createQuery( "from Product p");
List list = query.list();
// Supplier is being accessed
displayProductsListWithSupplierName(results);
select ... various field names ... from PRODUCT
select ... various field names ... from SUPPLIER where SUPPLIER.id=?
select ... various field names ... from SUPPLIER where SUPPLIER.id=?
select ... various field names ... from SUPPLIER where SUPPLIER.id=?
Result:
This is N+1 select problem!
Since none have mentioned, there is just another variable called hasnans
.
df[i].hasnans
will output to True
if one or more of the values in the pandas Series is NaN, False
if not. Note that its not a function.
pandas version '0.19.2' and '0.20.2'
Integer.toBinaryString((byteValue & 0xFF) + 256).substring(1)
Try jquery debugger plugin if you're using chrome: https://chrome.google.com/webstore/detail/jquery-debugger/dbhhnnnpaeobfddmlalhnehgclcmjimi?hl=en
check value by ID:
var CheckedValues = ($("#r1").is(':checked')) ? 1 : 0;
This is worked for me.
#_account_id{
display: none;
}
label[for="_account_id"] { display: none !important; }
In the documentation it's stated: Use the prefix option together with the global option:
The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.
When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.
(Emphasis by them)
So in your root directory you could install with
npm install --prefix <path/to/prefix_folder> -g
and it will install the node_modules
folder into the folder
<path/to/prefix_folder>/lib/node_modules
Wow, everyone's answer is so long. I simply used a pandas dataframe, masking, and the duplicated function (keep=False
markes all duplicates as True
, not just first or last):
import pandas as pd
import numpy as np
np.random.seed(42) # make results reproducible
int_df = pd.DataFrame({'int_list': np.random.randint(1, 20, size=10)})
dupes = int_df['int_list'].duplicated(keep=False)
print(int_df['int_list'][dupes].index)
This should return Int64Index([0, 2, 3, 4, 6, 7, 9], dtype='int64')
.
if anyone gets in here again this worked for me...
"aoColumnDefs": [{ "bVisible": false, "aTargets": [0] }]
You can pass plt.scatter
a c
argument which will allow you to select the colors. The code below defines a colors
dictionary to map your diamond colors to the plotting colors.
import matplotlib.pyplot as plt
import pandas as pd
carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]
df = pd.DataFrame(dict(carat=carat, price=price, color=color))
fig, ax = plt.subplots()
colors = {'D':'red', 'E':'blue', 'F':'green', 'G':'black'}
ax.scatter(df['carat'], df['price'], c=df['color'].apply(lambda x: colors[x]))
plt.show()
df['color'].apply(lambda x: colors[x])
effectively maps the colours from "diamond" to "plotting".
(Forgive me for not putting another example image up, I think 2 is enough :P)
seaborn
You can use seaborn
which is a wrapper around matplotlib
that makes it look prettier by default (rather opinion-based, I know :P) but also adds some plotting functions.
For this you could use seaborn.lmplot
with fit_reg=False
(which prevents it from automatically doing some regression).
The code below uses an example dataset. By selecting hue='color'
you tell seaborn to split your dataframe up based on your colours and then plot each one.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]
df = pd.DataFrame(dict(carat=carat, price=price, color=color))
sns.lmplot('carat', 'price', data=df, hue='color', fit_reg=False)
plt.show()
seaborn
using pandas.groupby
If you don't want to use seaborn then you can use pandas.groupby
to get the colors alone and then plot them using just matplotlib, but you'll have to manually assign colors as you go, I've added an example below:
fig, ax = plt.subplots()
colors = {'D':'red', 'E':'blue', 'F':'green', 'G':'black'}
grouped = df.groupby('color')
for key, group in grouped:
group.plot(ax=ax, kind='scatter', x='carat', y='price', label=key, color=colors[key])
plt.show()
This code assumes the same DataFrame as above and then groups it based on color
. It then iterates over these groups, plotting for each one. To select a color I've created a colors
dictionary which can map the diamond color (for instance D
) to a real color (for instance red
).
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
In simple terms, inside a then
handler function:
A) When x
is a value (number, string, etc):
return x
is equivalent to return Promise.resolve(x)
throw x
is equivalent to return Promise.reject(x)
B) When x
is a Promise that is already settled (not pending anymore):
return x
is equivalent to return Promise.resolve(x)
, if the Promise was already resolved.return x
is equivalent to return Promise.reject(x)
, if the Promise was already rejected.C) When x
is a Promise that is pending:
return x
will return a pending Promise, and it will be evaluated on the subsequent then
. Read more on this topic on the Promise.prototype.then() docs.
I have used a tool in my work its LDRA tool suite
It is used for testing the c/c++ code but it also can check against coding standards such as MISRA etc.
"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull
or git push
without arguments. A little bit down, this article explains and demonstrates this concept.
Kotlin version with update for deprication of RequestBody.create
:
Retrofit interface
@Multipart
@POST("uploadPhoto")
fun uploadFile(@Part file: MultipartBody.Part): Call<FileResponse>
and to Upload
fun uploadFile(fileUrl: String){
val file = File(fileUrl)
val fileUploadService = RetrofitClientInstance.retrofitInstance.create(FileUploadService::class.java)
val requestBody = file.asRequestBody(file.extension.toMediaTypeOrNull())
val filePart = MultipartBody.Part.createFormData(
"blob",file.name,requestBody
)
val call = fileUploadService.uploadFile(filePart)
call.enqueue(object: Callback<FileResponse>{
override fun onFailure(call: Call<FileResponse>, t: Throwable) {
Log.d(TAG,"Fckd")
}
override fun onResponse(call: Call<FileResponse>, response: Response<FileResponse>) {
Log.d(TAG,"success"+response.toString()+" "+response.body().toString()+" "+response.body()?.status)
}
})
}
Thanks to @jimmy0251
UTF-8 is prepared for world domination, Latin1 isn't.
If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).
Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4
.
I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install
. When I changed to the directory that had my makefile it worked.
So possibly you aren't in the right directory.
Try this it will work --
if($('#EventStartTimeMin').val() === " ") {
alert("Please enter start time!");
}
So if you are simply using the unsophisticated API, like I often am (I use it in ipython a lot), then this is simply
yscale('log')
plot(...)
Hope this helps someone looking for a simple answer! :).
No, a view consists of a single SELECT
statement. You cannot create or drop tables in a view.
Maybe a common table expression (CTE) can solve your problem. CTEs are temporary result sets that are defined within the execution scope of a single statement and they can be used in views.
Example (taken from here) - you can think of the SalesBySalesPerson
CTE as a temporary table:
CREATE VIEW vSalesStaffQuickStats
AS
WITH SalesBySalesPerson (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS
(
SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT E.EmployeeID,
EmployeeOrders = OS.NumberOfOrders,
EmployeeLastOrderDate = OS.MostRecentOrderDate,
E.ManagerID,
ManagerOrders = OM.NumberOfOrders,
ManagerLastOrderDate = OM.MostRecentOrderDate
FROM HumanResources.Employee AS E
INNER JOIN SalesBySalesPerson AS OS ON E.EmployeeID = OS.SalesPersonID
LEFT JOIN SalesBySalesPerson AS OM ON E.ManagerID = OM.SalesPersonID
GO
In HTML <br>
and in XHTML <br/>
.
I will suggest you to use <br/>
.
I'm new to stack overflow and new to front end development. This is what worked for me. So I did not want list items to be displayed.
.hidden {_x000D_
display:none;_x000D_
} _x000D_
_x000D_
#loginButton{_x000D_
_x000D_
margin-right:2px;_x000D_
_x000D_
}
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">NavBar</a>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active hidden">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item hidden">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item hidden">_x000D_
<a class="nav-link disabled" href="#">Disabled</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="form-inline my-2 my-lg-0">_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="loginButton"><a href="#">Log In</a></button>_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit"><a href="#">Register</a></button>_x000D_
</form>_x000D_
</div>_x000D_
</nav>
_x000D_
I'd like to note that it's usually preferable to change the class of the node instead of it's style and let CSS handle what that means.
If rooted:
Runtime.getRuntime().exec("su -c service call activity 42 s16 com.example.your_app");
You can just use an a
selector in your stylesheet to define all states of an anchor/hyperlink. For example:
a {
color: blue;
}
Would override all link styles and make all the states the colour blue.
A common way to achieve this is by string slicing.
MyString[a:b]
gives you a substring from index a to (b - 1).
Why you are using PHP for the conversion. Now, there are so many front end languages available, Why you are still including a server? You can convert the password into the binary number in the front-end and send the converted string in the Database. According to my point of view, this would be convenient.
var bintext, textresult="", binlength;
this.aaa = this.text_value;
bintext = this.aaa.replace(/[^01]/g, "");
binlength = bintext.length-(bintext.length%8);
for(var z=0; z<binlength; z=z+8) {
textresult += String.fromCharCode(parseInt(bintext.substr(z,8),2));
this.ans = textresult;
This is a Javascript code which I have found here: http://binarytotext.net/, they have used this code with Vue.js. In the code, this.aaa is the v-model dynamic value. To convert the binary into the text values, they have used big numbers. You need to install an additional package and convert it back into the text field. In my point of view, it would be easy.
Try GRANT ADMINISTER BULK OPERATIONS TO [server_login]
. It is a server level permission, not a database level. This has fixed a similar issue for me in that past (using OPENROWSET I believe).
I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.
For a massive speed increase, use NumPy's where function.
Create a two-column DataFrame with 100,000 rows with some zeros.
df = pd.DataFrame(np.random.randint(0,3, (100000,2)), columns=list('ab'))
numpy.where
df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
%timeit df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
685 µs ± 6.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit df.loc[df['a'] == 0, 'b'] = np.nan
3.11 ms ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Numpy's where
is about 4x faster
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: It combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
WE can take each first four joins in Details :
We have two tables with the following values.
TableA
id firstName lastName
.......................................
1 arun prasanth
2 ann antony
3 sruthy abc
6 new abc
TableB
id2 age Place
................
1 24 kerala
2 24 usa
3 25 ekm
5 24 chennai
....................................................................
INNER JOIN
Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB
Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
INNER JOIN TableB
ON TableA.id = TableB.id2;
Result Will Be
firstName lastName age Place
..............................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
LEFT JOIN
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
LEFT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
RIGHT JOIN
Note : will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
RIGHT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
NULL NULL 24 chennai
FULL JOIN
Note :It will return all selected values from both tables.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
FULL JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
NULL NULL 24 chennai
Interesting Fact
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Better to go check this Link it will give you interesting details about join order
JScript is Microsoft's implementation of the ECMAScript specification. JavaScript is the Mozilla implementation of the specification.
No need for the specificity .navbar-default
in your CSS. Background color requires background-color:#cc333333
(or just background:#cc3333
). Finally, probably best to consolidate all your customizations into a single class, as below:
.navbar-custom {
color: #FFFFFF;
background-color: #CC3333;
}
..
<div id="menu" class="navbar navbar-default navbar-custom">
Example: http://www.bootply.com/OusJAAvFqR#
Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.
The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.
Let's say you have:
<a></a>
<(.*)>
would match a></a
where as <(.*?)>
would match a
.
The latter stops after the first match of >
. It checks for one
or 0 matches of .*
followed by the next expression.
The first expression <(.*)>
doesn't stop when matching the first >
. It will continue until the last match of >
.
Four fewer characters, but 2 more ms
%%timeit
df.isna().T.any()
# 52.4 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
df.isna().any(axis=1)
# 50 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
I'd probably use axis=1
No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng
is producing the same result as Joe's code.
If you need to switch sheets for some reasons, use Application.ScreenUpdating = False
at the beginning of your macro (and Application.ScreenUpdating=True
at the end). This will remove the screenflickering - and speed up the execution.
SELECT 12 * (YEAR(end_date) - YEAR(start_date)) +
((MONTH(end_date) - MONTH(start_date))) +
SIGN(DAY(end_date) / DAY(start_date));
This works fine for me on SQL SERVER 2000.
The map you using here, is not the .map()
in javascript, it's Rxjs map function which working on Observables
in Angular...
So in that case you need to import it if you'd like to use map on the result data...
map(project: function(value: T, index: number): R, thisArg: any): Observable<R>
Applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable.
So simply import it like this:
import 'rxjs/add/operator/map';
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345
You may try to put the right database name in connection url in the configuration file. As I had the same error while run the POJO class file and it has been solved by this.
Running ./gradlew assembleDebug command on Android Studio Terminal had solved my problem.
The best way to do this is using the change event like this:
$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999
$(this).val( first + '-' + lastfour );
}
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
I also had to do this myself. I did it via the --parents argument for cp:
find SOURCEPATH -name filename*.txt -exec cp --parents {} DESTPATH \;
import datetime
Current Date and time
print(datetime.datetime.now())
#2019-09-08 09:12:12.473393
Current date only
print(datetime.date.today())
#2019-09-08
Current year only
print(datetime.date.today().year)
#2019
Current month only
print(datetime.date.today().month)
#9
Current day only
print(datetime.date.today().day)
#8
Run Sublime Text.
Select Preferences ? Package Control.
Or
Use ctrl+shift+p shortcut for (Win, Linux) or cmd+shift+p for (OS X).
Select Remove Package. Package Control: Remove Package
Start typing name of the package you want to remove and select it from the list of installed packages.
Wait for the uninstallation to complete.
volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1; int geti1() {return i1;} volatile int i2; int geti2() {return i2;} int i3; synchronized int geti3() {return i3;}
geti1()
accesses the value currently stored ini1
in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads.In particular, another thread may have updatedi1
in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 fori1
, for thread1 to have a value of 2 fori1
and for thread2 to have a value of 3 fori1
if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.On the other hand,
geti2()
effectively accesses the value ofi2
from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables. Generally threads are allowed to have their own copy of data is for better efficiency.There are two differences between volitile and synchronized.
Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block. That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing
geti3()
does the following:
- The thread acquires the lock on the monitor for object this .
- The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory .
- The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
- (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
- The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
http://javaexp.blogspot.com/2007/12/difference-between-volatile-and.html
I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:
find . -type d -exec chmod 755 {} \+
but this also does the same thing:
chmod 755 `find . -type d`
and so does this:
chmod 755 $(find . -type d)
The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.
So I think in your case that the following will do what you want.
chmod 777 $(find "/Users/Test/Desktop/PATH")
Moignans answer here works fine. Here is another peace of info in case it helps,
#if DEBUG
let a = 2
#else
let a = 3
#endif
You can negate the macros like below,
#if !RELEASE
let a = 2
#else
let a = 3
#endif
Assuming you have people is List of object
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Now you need two steps :
1)
people =removeDuplicate(people);
2)
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Here is method to remove duplicate
public static List removeDuplicate(Collection<Person> list) {
if(list ==null || list.isEmpty()){
return null;
}
Object removedDuplicateList =
list.stream()
.distinct()
.collect(Collectors.toList());
return (List) removedDuplicateList;
}
Adding full example here
package com.example.khan.vaquar;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class RemovedDuplicate {
public static void main(String[] args) {
Person vaquar = new Person(1, "Vaquar", "Khan");
Person zidan = new Person(2, "Zidan", "Khan");
Person zerina = new Person(3, "Zerina", "Khan");
// Add some random persons
Collection<Person> duplicateList = Arrays.asList(vaquar, zidan, zerina, vaquar, zidan, vaquar);
//
System.out.println("Before removed duplicate list" + duplicateList);
//
Collection<Person> nonDuplicateList = removeDuplicate(duplicateList);
//
System.out.println("");
System.out.println("After removed duplicate list" + nonDuplicateList);
;
// 1) solution Working code
Map<Object, Object> k = nonDuplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 1 using method_______________________________________________");
System.out.println("k" + k);
System.out.println("_____________________________________________________________________");
// 2) solution using inline distinct()
Map<Object, Object> k1 = duplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 2 using inline_______________________________________________");
System.out.println("k1" + k1);
System.out.println("_____________________________________________________________________");
//breacking code
System.out.println("");
System.out.println("Throwing exception _______________________________________________");
Map<Object, Object> k2 = duplicateList.stream()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("k2" + k2);
System.out.println("_____________________________________________________________________");
}
public static List removeDuplicate(Collection<Person> list) {
if (list == null || list.isEmpty()) {
return null;
}
Object removedDuplicateList = list.stream().distinct().collect(Collectors.toList());
return (List) removedDuplicateList;
}
}
// Model class
class Person {
public Person(Integer id, String fname, String lname) {
super();
this.id = id;
this.fname = fname;
this.lname = lname;
}
private Integer id;
private String fname;
private String lname;
// Getters and Setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
@Override
public String toString() {
return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
}
}
Results :
Before removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan]]
After removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan]]
Result 1 using method_______________________________________________
k{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Result 2 using inline_______________________________________________
k1{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Throwing exception _______________________________________________
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person [id=1, fname=Vaquar, lname=Khan]
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1253)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.example.khan.vaquar.RemovedDuplicate.main(RemovedDuplicate.java:48)
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.tridenthyundai.ains" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
even simpler, adding up to String[]
,
use built-in filter filter(StringUtils::isNotEmpty)
of org.apache.commons.lang3
import org.apache.commons.lang3.StringUtils;
String test = "a\nb\n\nc\n";
String[] lines = test.split("\\n", -1);
String[] result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
System.out.println(Arrays.toString(lines));
System.out.println(Arrays.toString(result));
and output:
[a, b, , c, ]
[a, b, c]
I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/"
, for example, I kept getting "This localhost page can't be found"
in the browser.
I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/"
as changing it to appBase="C:/Java Project/ROOT"
will cause "This localhost page can't be found"
to be displayed again.
Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.
just seperate the class name with a comma.
.a,.b{
your styles
}
The content inside strings in Golang can be compared using ==
operator. If the results are not as expected there may be some hidden characters like \n
, \r
, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings
package in golang.
For Instance, spaces can be removed using strings.TrimSpace
function. You can also define a custom function to remove any character you need. strings.TrimFunc
function can give you more power.
If this is your own server application then i suggest using the following header
Content-disposition: attachment; filename=fname.ext
This will force any browser to download the file and not render it in the browser window.
In Python 3, we use the bytes
object, also known as str
in Python 2.
# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
I find it more convenient to use the base64
module...
# Python 3
key = base64.b16decode(b'130000000800')
# Python 2
key = base64.b16decode('130000000800')
You can also use literals...
# Python 3
key = b'\x13\0\0\0\x08\0'
# Python 2
key = '\x13\0\0\0\x08\0'
these both are working nicely:
select round(<maxNumber>*rand())
FLOOR(RAND() * (<max> - <min> + 1)) + <min> // generates a number
between <min> and <max> inclusive.
Problem is that you seed the random generator again. Every time you seed it the initial state of the random number generator gets reset and the first random number you generate will be the first random number after the initial state
You can try the following one-statement:
if (($x-$min)*($x-$max) < 0)
or:
if (max(min($x, $max), $min) == $x)
You could use a List<T>
and when T
is a value type it will be allocated in contiguous memory which would not be the case if T
is a reference type.
Example:
List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);
int someElement = integers[1];
You can use the text editing controller to manipulate the value inside a textfield.
var textController = new TextEditingController();
Now, create a new textfield and set textController
as the controller for the textfield as shown below.
new TextField(controller: textController)
Now, create a RaisedButton
anywhere in your code and set the desired text in the onPressed
method of the RaisedButton
.
new RaisedButton(
onPressed: () {
textController.text = "New text";
}
),
The first <img />
is invalid - src
is a required attribute. data-src
is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.
Brief syntax lesson
Cells(Row, Column)
identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)
.Cells(Row, Column)
identifies a cell within a sheet identified in a earlier With statement:
With ActiveSheet
:
.Cells(Row,Column)
:
End With
If you omit the dot, Cells(Row,Column)
is within the active worksheet. So wsh = ActiveWorkbook
wsh.Range
is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:
With ActiveSheet
:
.Range.
:
End With
Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:
With Sheets("xxxx")
:
.Range.
:
End With
because my code only works on sheet xxxx.
Cells(Row,Column)
identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value
is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value
is good.
Cells(Row,Column) like "*Miami*"
will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.
Cells(Row,Column).Value = "Miami"
will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:
Lcase(Cells(Row,Column).Value) = "miami"
My suggestions
Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami"
when I started typing this.
Use
If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
Cells(i, "C").Value = "BA"
if you want to accept, for example, "South Miami" and "Miami, North".
Use
If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
Cells(i, "C").Value = "BA"
if you want to accept, exactly, "Miami" and "Florida".
Use
If Lcase(Cells(i, "A").Value) = "miami" And _
Lcase(Cells(i, "D").Value) = "florida" Then
Cells(i, "C").Value = "BA"
if you don't care about case.
Object.values() method is now supported. This will give you an array of values of an object.
Object.values(dataObject)
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
Below is supported since gson 2.8.0
public static Type getMapType(Class keyType, Class valueType){
return TypeToken.getParameterized(HashMap.class, keyType, valueType).getType();
}
public static <K,V> HashMap<K,V> fromMap(String json, Class<K> keyType, Class<V> valueType){
return gson.fromJson(json, getMapType(keyType,valueType));
}
No, this is not supported in MySQL stored routine syntax.
Feel free to submit a feature request at bugs.mysql.com.
You can use @Value("${property-name}")
from the
application.properties if your class is annotated with
@Configuration
or @Component
.
There's one more way I tried out was making a Utility class to read properties in the following way -
protected PropertiesUtility () throws IOException {
properties = new Properties();
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("application.properties");
properties.load(inputStream);
}
You can make use of static method to get the value of the key passed as the parameter.
This is the format of /etc/crontab:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.
To run something every minute:
* * * * * username /var/www/html/a.php
To run something at midnight of every day:
0 0 * * * username /var/www/html/reset.php
You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:
chmod +x file.php
Start your php file with a shebang so that your shell knows which interpreter to use:
#!/usr/bin/php
<?php
// your code here
Use vscode-solution-explorer
extension:
This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.
https://github.com/fernandoescolar/vscode-solution-explorer
Thanks @fernandoescolar
I found this to be working from jquery site
$.getJSON( "/Admin/GetFolderList/", function( data ) {
var options = $("#dropdownID");
$.each( data, function(key, val) {
options.append(new Option(key, val));
});
});
Simple extension for UIApplication
in Swift:
NOTE:
It cares about moreNavigationController
within UITabBarController
extension UIApplication {
class func topViewController(baseViewController: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = baseViewController as? UINavigationController {
return topViewController(navigationController.visibleViewController)
}
if let tabBarViewController = baseViewController as? UITabBarController {
let moreNavigationController = tabBarViewController.moreNavigationController
if let topViewController = moreNavigationController.topViewController where topViewController.view.window != nil {
return topViewController(topViewController)
} else if let selectedViewController = tabBarViewController.selectedViewController {
return topViewController(selectedViewController)
}
}
if let splitViewController = baseViewController as? UISplitViewController where splitViewController.viewControllers.count == 1 {
return topViewController(splitViewController.viewControllers[0])
}
if let presentedViewController = baseViewController?.presentedViewController {
return topViewController(presentedViewController)
}
return baseViewController
}
}
Simple usage:
if let topViewController = UIApplication.topViewController() {
//do sth with top view controller
}
Just add this one-line class in your CSS, and use the bootstrap label
component.
.label-as-badge {
border-radius: 1em;
}
Compare this label
and badge
side by side:
<span class="label label-default label-as-badge">hello</span>
<span class="badge">world</span>
They appear the same. But in the CSS, label
uses em
so it scales nicely, and it still has all the "-color" classes. So the label will scale to bigger font sizes better, and can be colored with label-success, label-warning, etc. Here are two examples:
<span class="label label-success label-as-badge">Yay! Rah!</span>
Or where things are bigger:
<div style="font-size: 36px"><!-- pretend an enclosing class has big font size -->
<span class="label label-success label-as-badge">Yay! Rah!</span>
</div>
11/16/2015: Looking at how we'll do this in Bootstrap 4
Looks like .badge
classes are completely gone. But there's a built-in .label-pill
class (here) that looks like what we want.
.label-pill {
padding-right: .6em;
padding-left: .6em;
border-radius: 10rem;
}
In use it looks like this:
<span class="label label-pill label-default">Default</span>
<span class="label label-pill label-primary">Primary</span>
<span class="label label-pill label-success">Success</span>
<span class="label label-pill label-info">Info</span>
<span class="label label-pill label-warning">Warning</span>
<span class="label label-pill label-danger">Danger</span>
11/04/2014: Here's an update on why cross-pollinating alert classes with .badge
is not so great. I think this picture sums it up:
Those alert classes were not designed to go with badges. It renders them with a "hint" of the intended colors, but in the end consistency is thrown out the window and readability is questionable. Those alert-hacked badges are not visually cohesive.
The .label-as-badge
solution is only extending the bootstrap design. We are keeping intact all the decision making made by the bootstrap designers, namely the consideration they gave for readability and cohesion across all the possible colors, as well as the color choices themselves. The .label-as-badge
class only adds rounded corners, and nothing else. There are no color definitions introduced. Thus, a single line of CSS.
Yep, it is easier to just hack away and drop in those .alert-xxxxx
classes -- you don't have to add any lines of CSS. Or you could care more about the little things and add one line.
<input type="checkbox" onclick="return false" />
will work for you , I am using this
xlrd.xldate_as_tuple
is nice, but there's xlrd.xldate.xldate_as_datetime
that converts to datetime as well.
import xlrd
wb = xlrd.open_workbook(filename)
xlrd.xldate.xldate_as_datetime(41889, wb.datemode)
=> datetime.datetime(2014, 9, 7, 0, 0)
Try the following code with an added request property:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class SocketConnection
{
public static String getURLSource(String url) throws IOException
{
URL urlObject = new URL(url);
URLConnection urlConnection = urlObject.openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
return toString(urlConnection.getInputStream());
}
private static String toString(InputStream inputStream) throws IOException
{
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
{
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine);
}
return stringBuilder.toString();
}
}
}
To expand on previous answers, the following one-liner exports a single table as a tab-separated file. It's suitable for automation, exporting the database every day or so.
mysql -B -D mydatabase -e 'select * from mytable'
Conveniently, we can use the same technique to list out MySQL's tables, and to describe the fields on a single table:
mysql -B -D mydatabase -e 'show tables'
mysql -B -D mydatabase -e 'desc users'
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
email varchar(128) NO UNI NULL
lastName varchar(100) YES NULL
title varchar(128) YES UNI NULL
userName varchar(128) YES UNI NULL
firstName varchar(100) YES NULL
This will replace all ?
with '
:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
WHERE city LIKE '%?%'
If you need to update more than one column, you can either change city
each time you execute to a different column name, or list the columns like so:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'
With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.
import { Router } from 'react-router';
export default class Foo extends Component {
static get contextTypes() {
return {
router: React.PropTypes.object.isRequired,
};
}
handleClick() {
this.context.router.push('/some-path');
}
}
See Apple’s Info.plist reference for full details (thanks @gnasher729).
You can add exceptions for specific domains in your Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>testdomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<false/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSRequiresCertificateTransparency</key>
<false/>
</dict>
</dict>
</dict>
All the keys for each excepted domain are optional. The speaker did not elaborate on any of the keys, but I think they’re all reasonably obvious.
(Source: WWDC 2015 session 703, “Privacy and Your App”, 30:18)
You can also ignore all app transport security restrictions with a single key, if your app has a good reason to do so:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
If your app does not have a good reason, you may risk rejection:
Setting NSAllowsArbitraryLoads to true will allow it to work, but Apple was very clear in that they intend to reject apps who use this flag without a specific reason. The main reason to use NSAllowsArbitraryLoads I can think of would be user created content (link sharing, custom web browser, etc). And in this case, Apple still expects you to include exceptions that enforce the ATS for the URLs you are in control of.
If you do need access to specific URLs that are not served over TLS 1.2, you need to write specific exceptions for those domains, not use NSAllowsArbitraryLoads set to yes. You can find more info in the NSURLSesssion WWDC session.
Please be careful in sharing the NSAllowsArbitraryLoads solution. It is not the recommended fix from Apple.
— kcharwood (thanks @marco-tolman)
If you are reading this because you are getting error while updating from the "Install new Software" menu, then you need to do this
please note: add the suffix file:/// to the location
ex. file:///C:/Users/harry/Downloads/eclox/
Maybe not the best solution but this gets the work done :)
This is how I do it.. I create the hash and store it using the ProtectedData
api:
public static string GenerateKeyHash(string Password)
{
if (string.IsNullOrEmpty(Password)) return null;
if (Password.Length < 1) return null;
byte[] salt = new byte[20];
byte[] key = new byte[20];
byte[] ret = new byte[40];
try
{
using (RNGCryptoServiceProvider randomBytes = new RNGCryptoServiceProvider())
{
randomBytes.GetBytes(salt);
using (var hashBytes = new Rfc2898DeriveBytes(Password, salt, 10000))
{
key = hashBytes.GetBytes(20);
Buffer.BlockCopy(salt, 0, ret, 0, 20);
Buffer.BlockCopy(key, 0, ret, 20, 20);
}
}
// returns salt/key pair
return Convert.ToBase64String(ret);
}
finally
{
if (salt != null)
Array.Clear(salt, 0, salt.Length);
if (key != null)
Array.Clear(key, 0, key.Length);
if (ret != null)
Array.Clear(ret, 0, ret.Length);
}
}
public static bool ComparePasswords(string PasswordHash, string Password)
{
if (string.IsNullOrEmpty(PasswordHash) || string.IsNullOrEmpty(Password)) return false;
if (PasswordHash.Length < 40 || Password.Length < 1) return false;
byte[] salt = new byte[20];
byte[] key = new byte[20];
byte[] hash = Convert.FromBase64String(PasswordHash);
try
{
Buffer.BlockCopy(hash, 0, salt, 0, 20);
Buffer.BlockCopy(hash, 20, key, 0, 20);
using (var hashBytes = new Rfc2898DeriveBytes(Password, salt, 10000))
{
byte[] newKey = hashBytes.GetBytes(20);
if (newKey != null)
if (newKey.SequenceEqual(key))
return true;
}
return false;
}
finally
{
if (salt != null)
Array.Clear(salt, 0, salt.Length);
if (key != null)
Array.Clear(key, 0, key.Length);
if (hash != null)
Array.Clear(hash, 0, hash.Length);
}
}
public static byte[] DecryptData(string Data, byte[] Salt)
{
if (string.IsNullOrEmpty(Data)) return null;
byte[] btData = Convert.FromBase64String(Data);
try
{
return ProtectedData.Unprotect(btData, Salt, DataProtectionScope.CurrentUser);
}
finally
{
if (btData != null)
Array.Clear(btData, 0, btData.Length);
}
}
public static string EncryptData(byte[] Data, byte[] Salt)
{
if (Data == null) return null;
if (Data.Length < 1) return null;
byte[] buffer = new byte[Data.Length];
try
{
Buffer.BlockCopy(Data, 0, buffer, 0, Data.Length);
return System.Convert.ToBase64String(ProtectedData.Protect(buffer, Salt, DataProtectionScope.CurrentUser));
}
finally
{
if (buffer != null)
Array.Clear(buffer, 0, buffer.Length);
}
}
Instead of void you can also use:
<a href="javascript:;">this link is disabled</a>
var x = '301.474.4062';_x000D_
_x000D_
x = x.replace(/\D+/g, '')_x000D_
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');_x000D_
_x000D_
alert(x);
_x000D_
You can use http_response_code()
to set HTTP response code.
If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.
http_response_code(201); // Set response status code to 201
For Laravel(Reference from: https://stackoverflow.com/a/14717895/2025923):
return Response::json([
'hello' => $value
], 201); // Status code here
What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full
svn resolve --accept base
Alternatively if you enable developer mode and (ADB) is still needed you can use connect to the device.
To enable developer Mode you go to Phone Settings > About Phone > tap buildnumber 7 times
once you have it enabled and have the device connected you can start seeing the device in VSCode
Since this answer is tagged with r-faq, I felt it would be useful to share another alternative from base R: stack
.
Note, however, that stack
does not work with factor
s--it only works if is.vector
is TRUE
, and from the documentation for is.vector
, we find that:
is.vector
returnsTRUE
if x is a vector of the specified mode having no attributes other than names. It returnsFALSE
otherwise.
I'm using the sample data from @Jaap's answer, where the values in the year columns are factor
s.
Here's the stack
approach:
cbind(wide[1:2], stack(lapply(wide[-c(1, 2)], as.character)))
## Code Country values ind
## 1 AFG Afghanistan 20,249 1950
## 2 ALB Albania 8,097 1950
## 3 AFG Afghanistan 21,352 1951
## 4 ALB Albania 8,986 1951
## 5 AFG Afghanistan 22,532 1952
## 6 ALB Albania 10,058 1952
## 7 AFG Afghanistan 23,557 1953
## 8 ALB Albania 11,123 1953
## 9 AFG Afghanistan 24,555 1954
## 10 ALB Albania 12,246 1954
This code works perfect if you need to see the brand centered and with auto width in toolbar. It contains the Wordpress function to get the image file from right path:
<a class="navbar-brand page-scroll" rel="home"
href="#page-top" title="Title">
<img style="height: 100%; width: auto;"
src="<?php echo get_template_directory_uri();?>/img/logo.png">
I think this is the "set it and forget it" solution:
options(repos='http://cran.rstudio.com/')
Note that this isn't https. I was on a Linux machine, ssh'ing in. If I used https, it didn't work.
You can use download.js (https://github.com/rndme/download and http://danml.com/download.html). If the file is in an external URL, you must make an Ajax request, but if it is not, then you can use the function:
download(Path, name, mime)
Read their documentation for more details in the GitHub.
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
so do the following edit my.cnf:
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';
thats it make sure your iptables allow connection from 3306 if not put the following:
iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT
i was looking for changing second row html and you can do cascading selector
$('#tbox1 tr:nth-child(2) td').html(11111)
format
supports a percentage floating point precision type:
>>> print "{0:.0%}".format(1./3)
33%
If you don't want integer division, you can import Python3's division from __future__
:
>>> from __future__ import division
>>> 1 / 3
0.3333333333333333
# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%
# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%
Your BlockID
function uses the undefined variable images
, which will lead to an error. Also, you should not use an Array
here - JavaScripts key-value-maps are plain objects:
function BlockID() {
return {
"s": "Images/Block_01.png",
"g": "Images/Block_02.png",
"C": "Images/Block_03.png",
"d": "Images/Block_04.png"
};
}
Try it with Mysqldump
#mysqldump --host=the.remotedatabase.com -u yourusername -p yourdatabasename > /User/backups/adump.sql
In the example you link to, they are changing it to Day/Night by using android:textOn
and android:textOff
1. Choose project, right click, in context menu, choose Show in Explorer
(on Mac, select Reveal in Finder
).
2. Choose menu File \ Close Project
3. In Windows Explorer, press Del or Shift+Del for permanent delete.
4. At IntelliJ IDEA startup windows, hover cursor on old project name (what has been deleted) press Del for delelte.
Last or next date, week, month & year calculation. It might be helpful for anyone.
Current Date:
select curdate();
Yesterday:
select subdate(curdate(), 1)
Tomorrow:
select adddate(curdate(), 1)
Last 1 week:
select between subdate(curdate(), 7) and subdate(curdate(), 1)
Next 1 week:
between adddate(curdate(), 7) and adddate(curdate(), 1)
Last 1 month:
between subdate(curdate(), 30) and subdate(curdate(), 1)
Next 1 month:
between adddate(curdate(), 30) and adddate(curdate(), 1)
Current month:
subdate(curdate(),day(curdate())-1) and last_day(curdate());
Last 1 year:
between subdate(curdate(), 365) and subdate(curdate(), 1)
Next 1 year:
between adddate(curdate(), 365) and adddate(curdate(), 1)
IOError: [Errno 13] Permission denied: 'juliodantas2015.json'
tells you everything you need to know: though you successfully made your python program executable with your chmod
, python can't open that juliodantas2015.json'
file for writing. You probably don't have the rights to create new files in the folder you're currently in.
You may want to check out Rhino.
The Rhino Shell provides a way to run JavaScript scripts in batch mode:
java org.mozilla.javascript.tools.shell.Main my_javascript_code.js [args]
You have mentioned Wrong id
alert(document.getElementById("name").value);
if you want to use name
attribute then
alert(document.getElementsByName("username")[0].value);
Updates:
input type="text" id="name" name="username"
id is different from name
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
I know this question was already answered, but this is what I use:
using (FileStream fStream = File.OpenRead(filename)) {
return GetHash<MD5>(fStream)
}
Where GetHash:
public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
StringBuilder sb = new StringBuilder();
MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
using (T crypt = (T) create.Invoke(null, null)) {
byte[] hashBytes = crypt.ComputeHash(stream);
foreach (byte bt in hashBytes) {
sb.Append(bt.ToString("x2"));
}
}
return sb.ToString();
}
Probably not the best way, but it can be handy.
see for your js path that may be the causing issue...because You only get this error if jQuery is not correctly loaded.
You need to login to your mysql terminal first using
mysql -u username -p password
Then use this:
SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;
output will be like this:
STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB
You can also set sql mode by this:
SET GLOBAL sql_mode=TRADITIONAL;
Explicitly specifying the max_iter
resolves the warning as the default max_iter
is 100. [For Logistic Regression].
logreg = LogisticRegression(max_iter=1000)
If you dont want your local changes, then do below command to ignore(delete permanently) the local changes.
git checkout <filename>
or git checkout -- .
)git reset <filename>
or git reset
) and then do checkout (git checkout <filename>
or git checkout -- .
)git clean -fd
)If you dont want to loose your local changes, then stash it and do pull or rebase. Later merge your changes from stash.
git stash
, and then get latest changes from repo git pull orign master
or git rebase origin/master
, and then merge your changes from stash git stash pop stash@{0}
There's no direct support for LIKE operator against DATETIME variables, but you can always cast the DATETIME to a VARCHAR:
SELECT (list of fields) FROM YourTable
WHERE CONVERT(VARCHAR(25), register_date, 126) LIKE '2009-10-10%'
Check the MSDN docs for a complete list of available "styles" in the CONVERT function.
Marc
To get checkbox work you should follow all these steps:
FormsModule
in your moduleform
tagyour input should be like this:
<input name="mpf" type="checkbox" [(ngModel)]="value" />
Note: do not forget to put name in your input.
from Tkinter import *
app = Tk()
# Text Widget + Font Size
txt = Text(app, font=('Verdana',8))
txt.pack()
# Delete Button
btn = Button(app, text='Delete', command=lambda: txt.delete(1.0,END))
btn.pack()
app.mainloop()
Here's an example of txt.delete(1.0,END)
as mentioned.
The use of lambda
makes us able to delete the contents without defining an actual function.
Here is an option if you are using pandas
:
import pandas as pd
d = dict.fromkeys(['a', 'b', 'c', 'd'])
d['b'] = 'not null'
d['c'] = '' # empty string
print(d)
# convert `dict` to `Series` and replace any blank strings with `None`;
# use the `.dropna()` method and
# then convert back to a `dict`
d_ = pd.Series(d).replace('', None).dropna().to_dict()
print(d_)
With WinForms you can use the ErrorProvider in conjunction with the Validating
event to handle the validation of user input. The Validating
event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx