Wow, this had me tearing my hair out, banging my head against walls, tables and other things. I had the same or a similar issue as the OP where it was either missing / not downloading the jar files or downloading them, but not including them in the Maven dependencies with the same error message. My limited knowledge of java packaging and maven probably didn't help.
For me the problem seems to have been caused by the Dependency Type "bundle" (but I don't know how or why). I was using the Add Dependency dialog in Eclipse Mars on the pom.xml, which allows you to search and browse the central repository. I was searching and adding a dependency to jackson-core libraries, picking the latest version, available as a bundle. This kept failing.
So finally, I changed the dependency properties form bundle to jar (again using the dependency properties window), which finally downloaded and referenced the dependencies properly after saving the changes.
All answers here provide good and working code. But someone would be dissatisfied that they all use ContentType
as return type and not JsonResult
.
Unfortunately JsonResult
is using JavaScriptSerializer
without option to disable it. The best way to get around this is to inherit JsonResult
.
I copied most of the code from original JsonResult
and created JsonStringResult
class that returns passed string as application/json
. Code for this class is below
public class JsonStringResult : JsonResult
{
public JsonStringResult(string data)
{
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
Data = data;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Get request is not allowed!");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
response.Write(Data);
}
}
}
Example usage:
var json = JsonConvert.SerializeObject(data);
return new JsonStringResult(json);
On mine, I was using Cocoapods for an Augmented Reality project and what I found out was that when you implement cocoapods and open your project's .workspace, you end up with the Xcode Project target and those Pods target you implemented inside the same file. What was happening was that some of the .m were being used by both. After I removed the duplicated ones for the Xcode target at Build Phases >> Compile Sources, it worked fine.
Example of how to perform a INSERT INTO SELECT with a WHERE clause.
INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2
You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.
As I mentioned in the comment, having to use the dot()
function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.
Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @
infix-operator for matrix multiplication, thanks to pep 465.
Edit: Regarding your comment:
Yes. The whole of numpy is based on arrays.
Yes. linalg.norm(v)
is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.
To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.
An example in ipython:
In [1]: import math
In [2]: import numpy as np
In [3]: a = np.array([4,2,7])
In [4]: np.linalg.norm(a)
Out[4]: 8.3066238629180749
In [5]: math.sqrt(sum([n**2 for n in a]))
Out[5]: 8.306623862918075
In [6]: b = a/np.linalg.norm(a)
In [7]: np.linalg.norm(b)
Out[7]: 1.0
Note that In [5]
is an alternative way to calculate the length. In [6]
shows normalizing the vector.
let myArr = [_x000D_
{ name: "john", age: 23 },_x000D_
{ name: "john", age: 43 },_x000D_
{ name: "jim", age: 101 },_x000D_
{ name: "bob", age: 67 },_x000D_
];_x000D_
_x000D_
// this will return old object (myArr) with items named 'john'_x000D_
let list = _.filter(myArr, item => item.name === 'jhon');_x000D_
_x000D_
// this will return new object referenc (new Object) with items named 'john' _x000D_
let list = _.map(myArr, item => item.name === 'jhon').filter(item => item.name);
_x000D_
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie
, readCookie
and eraseCookie
. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Set the SelectedPath property before you call ShowDialog ...
folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();
Will start them at C:\Temp
Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it on a componentDidMount()
in a React class.
For you edit, you may want to try something like this:
class Component extends React.Component {
constructor(props) {
super(props);
this.onAddBucket = this.onAddBucket.bind(this);
}
componentWillMount() {
this.setState({
buckets: {},
})
}
componentDidMount() {
this.onAddBucket();
}
onAddBucket() {
let self = this;
let getToken = localStorage.getItem('myToken');
var apiBaseUrl = "...";
let input = {
"name" : this.state.fields["bucket_name"]
}
axios.defaults.headers.common['Authorization'] = getToken;
axios.post(apiBaseUrl+'...',input)
.then(function (response) {
if (response.data.status == 200) {
this.setState({
buckets: this.state.buckets.concat(response.data.buckets),
});
} else {
alert(response.data.message);
}
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
{this.state.bucket}
);
}
}
The --download-cache
option should do what you want:
pip install --download-cache="/pth/to/downloaded/files" package
However, when I tested this, the main package downloaded, saved and installed ok, but the the dependencies were saved with their full url path as the name - a bit annoying, but all the tar.gz
files were there.
The --download
option downloads the main package and its dependencies and does not install any of them. (Note that prior to version 1.1 the --download
option did not download dependencies.)
pip install package --download="/pth/to/downloaded/files"
The pip
documentation outlines using --download
for fast & local installs.
If you have only these regular shapes, there is a simple procedure as follows :
approxPolyDP
function.Below is my example in Python:
import numpy as np
import cv2
img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,2)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
print len(approx)
if len(approx)==5:
print "pentagon"
cv2.drawContours(img,[cnt],0,255,-1)
elif len(approx)==3:
print "triangle"
cv2.drawContours(img,[cnt],0,(0,255,0),-1)
elif len(approx)==4:
print "square"
cv2.drawContours(img,[cnt],0,(0,0,255),-1)
elif len(approx) == 9:
print "half-circle"
cv2.drawContours(img,[cnt],0,(255,255,0),-1)
elif len(approx) > 15:
print "circle"
cv2.drawContours(img,[cnt],0,(0,255,255),-1)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Below is the output:
Remember, it works only for regular shapes.
Alternatively to find circles, you can use houghcircles
. You can find a tutorial here.
Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.
You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf
Adding a tiny bit more syntax detail to Mark Rushakoff's highest rank answer.
The expression
$HOST == node*
Can also be written as
$HOST == "node"*
The effect is the same. Just make sure the wildcard is outside the quoted text. If the wildcard is inside the quotes it will be interpreted literally (i.e. not as a wildcard).
As per hobodave's post: "Set to a non-empty value if the script was queried through the HTTPS protocol."
if (!empty($_SERVER['HTTPS']))
{
$secure_connection = true;
}
I think @Zack properly answered the question but just to cover all the bases:
Update myTable set MyColumn = NULL
This would set the entire column to null as the Question Title asks.
To set a specific row on a specific column to null use:
Update myTable set MyColumn = NULL where Field = Condition.
This would set a specific cell to null as the inner question asks.
Run This Query:
*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
>
> -- --------------------------------------------------------
>
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
>
> -- --------------------------------------------------------
>
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> -- 'pma'@localhost;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__bookmark`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__bookmark` ( `id` int(10) unsigned
> NOT NULL auto_increment, `dbase` varchar(255) NOT NULL default '',
> `user` varchar(255) NOT NULL default '', `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '', `query` text NOT NULL,
> PRIMARY KEY (`id`) ) COMMENT='Bookmarks' DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__column_info`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__column_info` ( `id` int(5) unsigned
> NOT NULL auto_increment, `db_name` varchar(64) NOT NULL default '',
> `table_name` varchar(64) NOT NULL default '', `column_name`
> varchar(64) NOT NULL default '', `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '', `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '', `transformation` varchar(255)
> NOT NULL default '', `transformation_options` varchar(255) NOT NULL
> default '', `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',
> PRIMARY KEY (`id`), UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) ) COMMENT='Column information
> for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__history`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__history` ( `id` bigint(20) unsigned
> NOT NULL auto_increment, `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '', `table` varchar(64) NOT NULL
> default '', `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP, `sqlquery` text NOT NULL, PRIMARY KEY (`id`),
> KEY `username` (`username`,`db`,`table`,`timevalue`) ) COMMENT='SQL
> history for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__pdf_pages`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` ( `db_name` varchar(64)
> NOT NULL default '', `page_nr` int(10) unsigned NOT NULL
> auto_increment, `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '', PRIMARY KEY (`page_nr`), KEY `db_name`
> (`db_name`) ) COMMENT='PDF relation pages for phpMyAdmin' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__recent`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__recent` ( `username` varchar(64)
> NOT NULL, `tables` text NOT NULL, PRIMARY KEY (`username`) )
> COMMENT='Recently accessed tables' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__favorite`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__favorite` ( `username` varchar(64)
> NOT NULL, `tables` text NOT NULL, PRIMARY KEY (`username`) )
> COMMENT='Favorite tables' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_uiprefs`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` ( `username`
> varchar(64) NOT NULL, `db_name` varchar(64) NOT NULL, `table_name`
> varchar(64) NOT NULL, `prefs` text NOT NULL, `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP, PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__relation`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__relation` ( `master_db` varchar(64)
> NOT NULL default '', `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '', `foreign_db`
> varchar(64) NOT NULL default '', `foreign_table` varchar(64) NOT
> NULL default '', `foreign_field` varchar(64) NOT NULL default '',
> PRIMARY KEY (`master_db`,`master_table`,`master_field`), KEY
> `foreign_field` (`foreign_db`,`foreign_table`) ) COMMENT='Relation
> table' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_coords`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_coords` ( `db_name`
> varchar(64) NOT NULL default '', `table_name` varchar(64) NOT NULL
> default '', `pdf_page_number` int(11) NOT NULL default '0', `x`
> float unsigned NOT NULL default '0', `y` float unsigned NOT NULL
> default '0', PRIMARY KEY (`db_name`,`table_name`,`pdf_page_number`)
> ) COMMENT='Table coordinates for phpMyAdmin PDF output' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_info`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_info` ( `db_name` varchar(64)
> NOT NULL default '', `table_name` varchar(64) NOT NULL default '',
> `display_field` varchar(64) NOT NULL default '', PRIMARY KEY
> (`db_name`,`table_name`) ) COMMENT='Table information for
> phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__tracking`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__tracking` ( `db_name` varchar(64)
> NOT NULL, `table_name` varchar(64) NOT NULL, `version` int(10)
> unsigned NOT NULL, `date_created` datetime NOT NULL,
> `date_updated` datetime NOT NULL, `schema_snapshot` text NOT NULL,
> `schema_sql` text, `data_sql` longtext, `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL, `tracking_active`
> int(1) unsigned NOT NULL default '1', PRIMARY KEY
> (`db_name`,`table_name`,`version`) ) COMMENT='Database changes
> tracking for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__userconfig`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__userconfig` ( `username`
> varchar(64) NOT NULL, `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `config_data` text
> NOT NULL, PRIMARY KEY (`username`) ) COMMENT='User preferences
> storage for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__users`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__users` ( `username` varchar(64) NOT
> NULL, `usergroup` varchar(64) NOT NULL, PRIMARY KEY
> (`username`,`usergroup`) ) COMMENT='Users and their assignments to
> user groups' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__usergroups`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__usergroups` ( `usergroup`
> varchar(64) NOT NULL, `tab` varchar(64) NOT NULL, `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N', PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) ) COMMENT='User groups with configured
> menu items' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__navigationhiding`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` ( `username`
> varchar(64) NOT NULL, `item_name` varchar(64) NOT NULL,
> `item_type` varchar(64) NOT NULL, `db_name` varchar(64) NOT NULL,
> `table_name` varchar(64) NOT NULL, PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )
> COMMENT='Hidden items of navigation tree' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__savedsearches`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` ( `id` int(5)
> unsigned NOT NULL auto_increment, `username` varchar(64) NOT NULL
> default '', `db_name` varchar(64) NOT NULL default '',
> `search_name` varchar(64) NOT NULL default '', `search_data` text
> NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> ) COMMENT='Saved searches' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__central_columns`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__central_columns` ( `db_name`
> varchar(64) NOT NULL, `col_name` varchar(64) NOT NULL, `col_type`
> varchar(64) NOT NULL, `col_length` text, `col_collation`
> varchar(64) NOT NULL, `col_isNull` boolean NOT NULL, `col_extra`
> varchar(255) default '', `col_default` text, PRIMARY KEY
> (`db_name`,`col_name`) ) COMMENT='Central list of columns' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__designer_settings`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` ( `username`
> varchar(64) NOT NULL, `settings_data` text NOT NULL, PRIMARY KEY
> (`username`) ) COMMENT='Settings related to Designer' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__export_templates`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__export_templates` ( `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT, `username` varchar(64) NOT NULL,
> `export_type` varchar(10) NOT NULL, `template_name` varchar(64) NOT
> NULL, `template_data` text NOT NULL, PRIMARY KEY (`id`), UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> ) COMMENT='Saved export templates' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*
Open This File :
C:\xampp\phpMyAdmin\config.inc.php
Clear and Past this Code :
> --------------------------------------------------------- <?php /** * Debian local configuration file * * This file overrides the settings
> made by phpMyAdmin interactive setup * utility. * * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz * * NOTE:
> do not add security sensitive data to this file (like passwords) *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still * want to do this, make sure to properly secure the access to
> this file * (also on the filesystem level). */ /** * Server(s)
> configuration */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1]. Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
> /* Authentication type */
> $cfg['Servers'][$i]['auth_type'] = 'cookie';
> /* Server parameters */
> if (empty($dbserver)) $dbserver = 'localhost';
> $cfg['Servers'][$i]['host'] = $dbserver;
> if (!empty($dbport)) {
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> $cfg['Servers'][$i]['port'] = $dbport;
> }
> //$cfg['Servers'][$i]['compress'] = false;
> /* Select mysqli if your server has it */
> $cfg['Servers'][$i]['extension'] = 'mysqli';
> /* Optional: User for advanced features */
> $cfg['Servers'][$i]['controluser'] = $dbuser;
> $cfg['Servers'][$i]['controlpass'] = $dbpass;
> /* Optional: Advanced phpMyAdmin features */
> $cfg['Servers'][$i]['pmadb'] = $dbname;
> $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
> $cfg['Servers'][$i]['relation'] = 'pma_relation';
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
> $cfg['Servers'][$i]['history'] = 'pma_history';
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
> /* Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */
> // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
> /* Advance to next server for rest of config */
> $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* * End of servers
> configuration */ /* * Directories for saving/loading files from
> server */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';
------------------------------------------
i Solve My Problem Through this Method
The PGOPTIONS
environment variable may be used to achieve this in a flexible way.
In an Unix shell:
PGOPTIONS="--search_path=my_schema_01" psql -d myDataBase -a -f myInsertFile.sql
If there are several invocations in the script or sub-shells that need the same options, it's simpler to set PGOPTIONS
only once and export it.
PGOPTIONS="--search_path=my_schema_01"
export PGOPTIONS
psql -d somebase
psql -d someotherbase
...
or invoke the top-level shell script with PGOPTIONS
set from the outside
PGOPTIONS="--search_path=my_schema_01" ./my-upgrade-script.sh
In Windows CMD environment, set PGOPTIONS=value
should work the same.
I found it very annoying that ggplot2
doesn't offer an 'automatic' solution for this. That's why I created the bar_chart()
function in ggcharts
.
ggcharts::bar_chart(theTable, Position)
By default bar_chart()
sorts the bars and displays a horizontal plot. To change that set horizontal = FALSE
. In addition, bar_chart()
removes the unsightly 'gap' between the bars and the axis.
Just simply 'export' variable and 'import' in your class
export var GOOGLE_API_URL = 'https://www.googleapis.com/admin/directory/v1';
// default err string message
export var errStringMsg = 'Something went wrong';
Now use it as,
import appConstants = require('../core/AppSettings');
console.log(appConstants.errStringMsg);
console.log(appConstants.GOOGLE_API_URL);
Modernizr can detect CSS 3D transforms, yeah. The truthiness of Modernizr.csstransforms3d
will tell you if the browser supports them.
The above link lets you select which tests to include in a Modernizr build, and the option you're looking for is available there.
Alternatively, as user356990 answered, you can use conditional comments if you're searching for IE and IE alone. Rather than creating a global variable, you can use HTML5 Boilerplate's <html>
conditional comments trick to assign a class:
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
If you already have jQuery initialised, you can just check with $('html').hasClass('lt-ie9')
. If you need to check which IE version you're in so you can conditionally load either jQuery 1.x or 2.x, you can do something like this:
myChecks.ltIE9 = (function(){
var htmlElemClasses = document.querySelector('html').className.split(' ');
if (!htmlElemClasses){return false;}
for (var i = 0; i < htmlElemClasses.length; i += 1 ){
var klass = htmlElemClasses[i];
if (klass === 'lt-ie9'){
return true;
}
}
return false;
}());
N.B. IE conditional comments are only supported up to IE9 inclusive. From IE10 onwards, Microsoft encourages using feature detection rather than browser detection.
Whichever method you choose, you'd then test with
if ( myChecks.ltIE9 || Modernizr.csstransforms3d ){
// iframe or flash fallback
}
Don't take that ||
literally, of course.
Having 2 files like you suggested would be the easiest solution.
For instance:
(.. your html ..)
<form action="script.php" method="get">
<input type="submit" value="Run me now!">
</form>
(...)
<?php
echo "Hello world!"; // Your code here
?>
<?php
if (!empty($_GET['act'])) {
echo "Hello world!"; //Your code here
} else {
?>
(.. your html ..)
<form action="index.php" method="get">
<input type="hidden" name="act" value="run">
<input type="submit" value="Run me now!">
</form>
<?php
}
?>
This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Easier method is window.location.href = "http://example.com/new_url";
But what if you want to check if username and password whether empty or not using JavaScript and send it to the php to check whether user in the database. You can do this easily following this code.
html form -
<form name="myForm" onsubmit="return validateForm()" method="POST" action="login.php" >
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="submit" name="submitBt"value="LogIn" />
</form>
javascript validation-
function validateForm(){
var uname = document.forms["myForm"]["username"].value;
var pass = document.forms["myForm"]["password"].value;
if((!isEmpty(uname, "Log In")) && (!isEmpty(pass, "Password"))){
return true;
}else{
return false;
}
}
function isEmpty(elemValue, field){
if((elemValue == "") || (elemValue == null)){
alert("you can not have "+field+" field empty");
return true;
}else{
return false;
}
}
check if user in the database using php
<?php
$con = mysqli_connect("localhost","root","1234","users");
if(mysqli_connect_errno()){
echo "Couldn't connect ".mysqli_connect_error();
}else{
//echo "connection successful <br />";
}
$uname_tb = $_POST['username'];
$pass_tb = $_POST['password'];
$query ="SELECT * FROM user";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
if(($row['username'] == $uname_tb) && ($row['password'] == $pass_tb)){
echo "Login Successful";
header('Location: dashbord.php');
exit();
}else{
echo "You are not in our database".mysqli_connect_error();
}
}
mysqli_close($con);
?>
(Windows 7) My solution to this was to find the device in Device Manager, uninstall the existing driver and install a new one from the android folder in your user account using the include subdirectories option.
All the best.
Try this its worked for me
SELECT * from bookedroom
WHERE UNIX_TIMESTAMP('2020-8-07 5:31')
between UNIX_TIMESTAMP('2020-8-07 5:30') and
UNIX_TIMESTAMP('2020-8-09 5:30')
To set a class completely, instead of adding one or removing one, use this:
$(this).attr("class","newclass");
Advantage of this is that you'll remove any class that might be set in there and reset it to how you like. At least this worked for me in one situation.
Right click the database itself, Tasks -> Generate Scripts...
Then follow the wizard.
For SSMS2008+, if you want to also export the data, on the "Set Scripting Options" step, select the "Advanced" button and change "Types of data to script" from "Schema Only" to "Data Only" or "Schema and Data".
SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID()
For add to first position with key
and value
$newAarray = [newIndexname => newIndexValue] ;
$yourArray = $newAarray + $yourArray ;
Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(mystring));
In addition to fedorqui's correct answer, I would like to show the difference between string length and byte length:
myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
LANG=$oLang LC_ALL=$oLcAll
printf "%s is %d char len, but %d bytes len.\n" "${myvar}" $chrlen $bytlen
will render:
Généralités is 11 char len, but 14 bytes len.
you could even have a look at stored chars:
myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
printf -v myreal "%q" "$myvar"
LANG=$oLang LC_ALL=$oLcAll
printf "%s has %d chars, %d bytes: (%s).\n" "${myvar}" $chrlen $bytlen "$myreal"
will answer:
Généralités has 11 chars, 14 bytes: ($'G\303\251n\303\251ralit\303\251s').
Nota: According to Isabell Cowan's comment, I've added setting to $LC_ALL
along with $LANG
.
Argument work same as regular variables
strLen() {
local bytlen sreal oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#1}
printf -v sreal %q "$1"
LANG=$oLang LC_ALL=$oLcAll
printf "String '%s' is %d bytes, but %d chars len: %s.\n" "$1" $bytlen ${#1} "$sreal"
}
will work as
strLen théorème
String 'théorème' is 10 bytes, but 8 chars len: $'th\303\251or\303\250me'
printf
correction tool:If you:
for string in Généralités Language Théorème Février "Left: ?" "Yin Yang ?";do
printf " - %-14s is %2d char length\n" "'$string'" ${#string}
done
- 'Généralités' is 11 char length
- 'Language' is 8 char length
- 'Théorème' is 8 char length
- 'Février' is 7 char length
- 'Left: ?' is 7 char length
- 'Yin Yang ?' is 10 char length
Not really pretty... For this, there is a little function:
strU8DiffLen () {
local bytlen oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#1}
LANG=$oLang LC_ALL=$oLcAll
return $(( bytlen - ${#1} ))
}
Then now:
for string in Généralités Language Théorème Février "Left: ?" "Yin Yang ?";do
strU8DiffLen "$string"
printf " - %-$((14+$?))s is %2d chars length, but uses %2d bytes\n" \
"'$string'" ${#string} $((${#string}+$?))
done
- 'Généralités' is 11 chars length, but uses 14 bytes
- 'Language' is 8 chars length, but uses 8 bytes
- 'Théorème' is 8 chars length, but uses 10 bytes
- 'Février' is 7 chars length, but uses 8 bytes
- 'Left: ?' is 7 chars length, but uses 9 bytes
- 'Yin Yang ?' is 10 chars length, but uses 12 bytes
But there left some strange UTF-8 behaviour, like double-spaced chars, zero spaced chars, reverse deplacement and other that could not be as simple...
Have a look at diffU8test.sh or diffU8test.sh.txt for more limitations.
You can simply use the zoom property:
#myContainer{
zoom: 0.5;
-moz-transform: scale(0.5);
}
Where myContainer contains all the elements you're editing. This is supported in all major browsers.
Followed by @Andy's answer, you can do following to solve your second question:
In [56]: df.groupby(['col5','col2']).size().reset_index().groupby('col2')[[0]].max()
Out[56]:
0
col2
A 3
B 2
C 1
D 3
I recommend the accepted answer above. If you are in a pinch, however, you could declare the object as a global within the page_properties function.
$objPage = new PageAtrributes;
function page_properties() {
global $objPage;
$objPage->set_page_title($myrow['title']);
}
This work for me
<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>
I understand that there is a 4000 max set for
NVARCHAR(MAX)
Your understanding is wrong. nvarchar(max)
can store up to (and beyond sometimes) 2GB of data (1 billion double byte characters).
From nchar and nvarchar in Books online the grammar is
nvarchar [ ( n | max ) ]
The |
character means these are alternatives. i.e. you specify either n
or the literal max
.
If you choose to specify a specific n
then this must be between 1 and 4,000 but using max
defines it as a large object datatype (replacement for ntext
which is deprecated).
In fact in SQL Server 2008 it seems that for a variable the 2GB limit can be exceeded indefinitely subject to sufficient space in tempdb
(Shown here)
Regarding the other parts of your question
varchar(n) + varchar(n)
will truncate at 8,000 characters.nvarchar(n) + nvarchar(n)
will truncate at 4,000 characters.varchar(n) + nvarchar(n)
will truncate at 4,000 characters. nvarchar
has higher precedence so the result is nvarchar(4,000)
[n]varchar(max)
+ [n]varchar(max)
won't truncate (for < 2GB).varchar(max)
+ varchar(n)
won't truncate (for < 2GB) and the result will be typed as varchar(max)
.varchar(max)
+ nvarchar(n)
won't truncate (for < 2GB) and the result will be typed as nvarchar(max)
.nvarchar(max)
+ varchar(n)
will first convert the varchar(n)
input to nvarchar(n)
and then do the concatenation. If the length of the varchar(n)
string is greater than 4,000 characters the cast will be to nvarchar(4000)
and truncation will occur.If you use the N
prefix and the string is <= 4,000 characters long it will be typed as nvarchar(n)
where n
is the length of the string. So N'Foo'
will be treated as nvarchar(3)
for example. If the string is longer than 4,000 characters it will be treated as nvarchar(max)
If you don't use the N
prefix and the string is <= 8,000 characters long it will be typed as varchar(n)
where n
is the length of the string. If longer as varchar(max)
For both of the above if the length of the string is zero then n
is set to 1.
1. The CONCAT
function doesn't help here
DECLARE @A5000 VARCHAR(5000) = REPLICATE('A',5000);
SELECT DATALENGTH(@A5000 + @A5000),
DATALENGTH(CONCAT(@A5000,@A5000));
The above returns 8000 for both methods of concatenation.
2. Be careful with +=
DECLARE @A VARCHAR(MAX) = '';
SET @A+= REPLICATE('A',5000) + REPLICATE('A',5000)
DECLARE @B VARCHAR(MAX) = '';
SET @B = @B + REPLICATE('A',5000) + REPLICATE('A',5000)
SELECT DATALENGTH(@A),
DATALENGTH(@B);`
Returns
-------------------- --------------------
8000 10000
Note that @A
encountered truncation.
You are getting truncation either because you are concatenating two non max
datatypes together or because you are concatenating a varchar(4001 - 8000)
string to an nvarchar
typed string (even nvarchar(max)
).
To avoid the second issue simply make sure that all string literals (or at least those with lengths in the 4001 - 8000 range) are prefaced with N
.
To avoid the first issue change the assignment from
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = 'Foo' + 'Bar' + ...;
To
DECLARE @SQL NVARCHAR(MAX) = '';
SET @SQL = @SQL + N'Foo' + N'Bar'
so that an NVARCHAR(MAX)
is involved in the concatenation from the beginning (as the result of each concatenation will also be NVARCHAR(MAX)
this will propagate)
Make sure you have "results to grid" mode selected then you can use
select @SQL as [processing-instruction(x)] FOR XML PATH
The SSMS options allow you to set unlimited length for XML
results. The processing-instruction
bit avoids issues with characters such as <
showing up as <
.
Bitwise solution normally is weird. But in this case I guess that is more elegant
function hexToRGB(hexColor){
return {
red: (hexColor >> 16) & 0xFF,
green: (hexColor >> 8) & 0xFF,
blue: hexColor & 0xFF,
}
}
Usage:
const {red, green, blue } = hexToRGB(0xFF00FF)
console.log(red) // 255
console.log(green) // 0
console.log(blue) // 255
Here is a minor improvement to CMS's solution:
if(!String.prototype.startsWith){
String.prototype.startsWith = function (str) {
return !this.indexOf(str);
}
}
"Hello World!".startsWith("He"); // true
var data = "Hello world";
var input = 'He';
data.startsWith(input); // true
Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.
Using !
is slightly faster and more concise than === 0
though not as readable.
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
I had this same error. I had everything written in correctly, including the Listing 10.13 from the tutorial.
Rails.application.configure do
.
.
.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delevery_method :test
host = 'example.com'
config.action_mailer.default_url_options = { host: host }
.
.
.
end
obviously with "example.com" replaced with my server url.
What I had glossed over in the tutorial was this line:
After restarting the development server to activate the configuration...
So the answer for me was to turn the server off and back on again.
[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)
Its not especially Hamcrest, but I think it worth to mention here. What I use quite often in Java8 is something like:
assertTrue(myClass.getMyItems().stream().anyMatch(item -> "foo".equals(item.getName())));
(Edited to Rodrigo Manyari's slight improvement. It's a little less verbose. See comments.)
It may be a little bit harder to read, but I like the type and refactoring safety. Its also cool for testing multiple bean properties in combination. e.g. with a java-like && expression in the filter lambda.
For me, the most frequent cause is an omitted } character, so that a function or if statement block is not terminated. I fix this by inserting a } character after my recent edits and moving it around from there. I use an editor that can locate opening brackets corresponding to a closing bracket, so that feature helps, too (it locates the function that was not terminated correctly).
We can hope that someday language interpreters and compilers will do some work to generate better error messages, since it is so easy to omit a closing bracket.
If this helps anyone, please vote the answer up.
.show-grid [class*="span"]
It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.
Our js-programmer asked me to return the exact JSON format data instead of a json-encoded string to her.
Below is the solution.(This will return an object that can be used/viewed straightly in the browser)
import json
from xxx.models import alert
from django.core import serializers
def test(request):
alert_list = alert.objects.all()
tmpJson = serializers.serialize("json",alert_list)
tmpObj = json.loads(tmpJson)
return HttpResponse(json.dumps(tmpObj))
If you are using OpenLDAP (i.e. slapd) which is common on Linux servers, then you must enable the memberof overlay to be able to match against a filter using the (memberOf=XXX) attribute.
Also, once you enable the overlay, it does not update the memberOf attributes for existing groups (you will need to delete out the existing groups and add them back in again). If you enabled the overlay to start with, when the database was empty then you should be OK.
Double check your manifest, your first activity should have tag
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
inside of activity tag.
If that doesn't work, look for target build, which located in the left of run button (green-colored play button), it should be targeting "app" folder, not a particular activity. if it doesn't targeting "app", just click it and choose "app" from drop down list.
Hope it helps!
Best example for dynamic linking is, when the library is dependent on the used hardware. In ancient times the C math library was decided to be dynamic, so that each platform can use all processor capabilities to optimize it.
An even better example might be OpenGL. OpenGl is an API that is implemented differently by AMD and NVidia. And you are not able to use an NVidia implementation on an AMD card, because the hardware is different. You cannot link OpenGL statically into your program, because of that. Dynamic linking is used here to let the API be optimized for all platforms.
Some languages use short-circuit, and others use full Boolean evaluation (if you know, this is similar to the directive $B
in Pascal).
Explanations:
function A(){
...Do something..
return true;
}
function B(){
...Do something..
return true;
}
if ( A() OR B() ) { .....
In this example the function B()
will never be executed. Since the function A()
returns TRUE, the result of the OR statement is known from the first part without it being necessary to evaluate the second part of the expression.
However with ( A() || B() )
, the second part is always evaluated regardless of the value of the first.
For optimized programming, you should always use OR
which is faster (except for the case when the first part returns false
and second part actually needs to be evaluated).
Most of the answers are using SystemChrome
which only works for Android. My solution is to combine both AnnotatedRegion
and SafeArea
into new Widget so it also works in iOS. And I can use it with or without AppBar
.
class ColoredStatusBar extends StatelessWidget {
const ColoredStatusBar({
Key key,
this.color,
this.child,
this.brightness = Brightness.dark,
}) : super(key: key);
final Color color;
final Widget child;
final Brightness brightness;
@override
Widget build(BuildContext context) {
final defaultColor = Colors.blue;
final androidIconBrightness =
brightness == Brightness.dark ? Brightness.light : Brightness.dark;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: color ?? defaultColor,
statusBarIconBrightness: androidIconBrightness,
statusBarBrightness: brightness,
),
child: Container(
color: color ?? defaultColor,
child: SafeArea(
bottom: false,
child: Container(
child: child,
),
),
),
);
}
}
Usage: Place it to top of page's widget.
@override
Widget build(BuildContext context) {
return ColoredStatusBar(
child: /* your child here */,
);
}
Those do both mean non-breaking space, yes.  
is another synonym, in hex.
I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site
package javasandbox;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {
private static String sURL;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws MalformedURLException, IOException {
sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
System.out.println(sURL);
URL url = new URL(sURL);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//set http request headers
httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
httpCon.addRequestProperty("Connection", "keep-alive");
httpCon.addRequestProperty("Cache-Control", "max-age=0");
httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
//httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
HttpURLConnection.setFollowRedirects(false);
httpCon.setInstanceFollowRedirects(false);
httpCon.setDoOutput(true);
httpCon.setUseCaches(true);
httpCon.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
System.out.println(a.toString());
httpCon.disconnect();
}
}
I recently experienced the error, and none of the solutions worked for me. What resolved the error for me was adding the Application pool user to the Power Users group in computer management. I couldn't use the Administrator group due to a company policy.
Just for completeness: Xlib - But it's somewhat slow when capturing the whole screen:
from Xlib import display, X
import Image #PIL
W,H = 200,200
dsp = display.Display()
try:
root = dsp.screen().root
raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)
image = Image.fromstring("RGB", (W, H), raw.data, "raw", "BGRX")
image.show()
finally:
dsp.close()
One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.
Edit: We can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:
#include <stdio.h>
#include <X11/X.h>
#include <X11/Xlib.h>
//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c
void getScreen(const int, const int, const int, const int, unsigned char *);
void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data)
{
Display *display = XOpenDisplay(NULL);
Window root = DefaultRootWindow(display);
XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);
unsigned long red_mask = image->red_mask;
unsigned long green_mask = image->green_mask;
unsigned long blue_mask = image->blue_mask;
int x, y;
int ii = 0;
for (y = 0; y < H; y++) {
for (x = 0; x < W; x++) {
unsigned long pixel = XGetPixel(image,x,y);
unsigned char blue = (pixel & blue_mask);
unsigned char green = (pixel & green_mask) >> 8;
unsigned char red = (pixel & red_mask) >> 16;
data[ii + 2] = blue;
data[ii + 1] = green;
data[ii + 0] = red;
ii += 3;
}
}
XDestroyImage(image);
XDestroyWindow(display, root);
XCloseDisplay(display);
}
And then the python-file:
import ctypes
import os
from PIL import Image
LibName = 'prtscn.so'
AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName
grab = ctypes.CDLL(AbsLibPath)
def grab_screen(x1,y1,x2,y2):
w, h = x2-x1, y2-y1
size = w * h
objlength = size * 3
grab.getScreen.argtypes = []
result = (ctypes.c_ubyte*objlength)()
grab.getScreen(x1,y1, w, h, result)
return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)
if __name__ == '__main__':
im = grab_screen(0,0,1440,900)
im.show()
You would want to use CSS to achieve that.
say you have a table with the attribute id="my_table"
You would want to write the following in your css file
#my_table{
margin-top:10px //moves your table 10pixels down
margin-left:10px //moves your table 10pixels right
}
if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px
to the style attribute in your table element like so
<table style="margin-top:10px; margin-left:10px;">
....
</table>
There are a lot of resources on the net describing CSS and HTML in detail
using date method, we should be able to get the result. ie; date('N/D/l', mktime(0, 0, 0, month, day, year));
For Example
echo date('N', mktime(0, 0, 0, 7, 1, 2017)); // will return 6
echo date('D', mktime(0, 0, 0, 7, 1, 2017)); // will return Sat
echo date('l', mktime(0, 0, 0, 7, 1, 2017)); // will return Saturday
If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:
# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
# dimensions of our images
img_width, img_height = 320, 240
# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes
# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)
# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)
# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]
Just leave out the "dot-slash" ./
:
D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"
Though, if you wanted to, you could use .\
and it would work.
D:\Gesture Recognition\Gesture Recognition\Debug>.\"Gesture Recognition.exe"
I know this is an old post, but a good time to use PrimaryKeyColumn
would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.
In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn
.
Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.
You can use pandas.DataFrame.fillna
with the method='ffill'
option. 'ffill'
stands for 'forward fill' and will propagate last valid observation forward. The alternative is 'bfill'
which works the same way, but backwards.
import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
df = df.fillna(method='ffill')
print(df)
# 0 1 2
#0 1 2 3
#1 4 2 3
#2 4 2 9
There is also a direct synonym function for this, pandas.DataFrame.ffill
, to make things simpler.
There are three approaches
Use SublimeCodeIntel plug-in
Use CTags plug-in
Generate .sublime-completion file manually
Approaches are described in detail in this blog post (of mine): http://opensourcehacker.com/2013/03/04/javascript-autocompletions-and-having-one-for-sublime-text-2/
/* cellpadding */
th, td { padding: 5px; }
/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; } /* cellspacing="0" */
/* valign */
th, td { vertical-align: top; }
/* align (center) */
table { margin: 0 auto; }
Here's a simple function that lets you do what you are looking for:
- (NSString *)getSubstring:(NSString *)value betweenString:(NSString *)separator
{
NSRange firstInstance = [value rangeOfString:separator];
NSRange secondInstance = [[value substringFromIndex:firstInstance.location + firstInstance.length] rangeOfString:separator];
NSRange finalRange = NSMakeRange(firstInstance.location + separator.length, secondInstance.location);
return [value substringWithRange:finalRange];
}
Usage:
NSString *myName = [self getSubstring:@"This is my :name:, woo!!" betweenString:@":"];
I'm using cdn boostrap, the solution that I found was: First include the cdn bootstrap, then you include the file .css where you are editing the default styles of bootstrap.
The following adds elements to a list in a loop.
l<-c()
i=1
while(i<100) {
b<-i
l<-c(l,b)
i=i+1
}
Here is my code for disabling all scrolling in webview:
// disable scroll on touch
webview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
To only hide the scrollbars, but not disable scrolling:
WebView.setVerticalScrollBarEnabled(false);
WebView.setHorizontalScrollBarEnabled(false);
or you can try using single column layout but this only works with simple pages and it disables horizontal scrolling:
//Only disabled the horizontal scrolling:
webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
You can also try to wrap your webview with vertically scrolling scrollview and disable all scrolling on the webview:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical" >
<WebView
android:id="@+id/mywebview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none" />
</ScrollView>
And set
webview.setScrollContainer(false);
Don't forget to add the webview.setOnTouchListener(...)
code above to disable all scrolling in the webview. The vertical ScrollView will allow for scrolling of the WebView's content.
This worked for me endDate: "today"
$('#datepicker').datepicker({
format: "dd/mm/yyyy",
autoclose: true,
orientation: "top",
endDate: "today"
});
Main page
<a href="/sample.htm#page1">page1</a>
<a href="/sample.htm#page2">page2</a>
sample pages
<div id='page1'><a name="page1"></a></div>
<div id='page2'><a name="page2"></a></div>
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
I really like grep() and grepl() for this purpose.
grep() returns a vector of integers, which indicate where matches are.
yo <- c("a", "a", "b", "b", "c", "c")
grep("b", yo)
[1] 3 4
grepl() returns a logical vector, with "TRUE" at the location of matches.
yo <- c("a", "a", "b", "b", "c", "c")
grepl("b", yo)
[1] FALSE FALSE TRUE TRUE FALSE FALSE
These functions are case-sensitive.
content = `cat file`
I think this method is the most "uncommon" one. Maybe it is kind of tricky, but it works if cat
is installed.
From MSDN:
To maximize productivity, the Windows Forms Designer shadows the
AutoSize
property for theForm
class. At design time, the form behaves as though theAutoSize
property is set to false, regardless of its actual setting. At runtime, no special accommodation is made, and theAutoSize
property is applied as specified by the property setting.
Using seeds.rb
file or FactoryBot
is great, but these are respectively great for fixed data structures and testing.
The seedbank
gem might give you more control and modularity to your seeds. It inserts rake tasks and you can also define dependencies between your seeds. Your rake task list will have these additions (e.g.):
rake db:seed # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/ENVIRONMENT/*.seeds.rb. ENVIRONMENT is the current environment in Rails.env.
rake db:seed:bar # Load the seed data from db/seeds/bar.seeds.rb
rake db:seed:common # Load the seed data from db/seeds.rb and db/seeds/*.seeds.rb.
rake db:seed:development # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/development/*.seeds.rb.
rake db:seed:development:users # Load the seed data from db/seeds/development/users.seeds.rb
rake db:seed:foo # Load the seed data from db/seeds/foo.seeds.rb
rake db:seed:original # Load the seed data from db/seeds.rb
If anyone else is stuck with this, here's what helped me. Changing the Anchor settings did not work for me. I am using datagridviews within groupboxes in a form which is inside a parent form.
Handling the form resize event was the only thing that worked for me.
private void Form1_Resize(object sender, EventArgs e)
{
groupBoxSampleQueue.MinimumSize = new Size((this as OperatingForm).Width - 22, 167);
groupBoxMachineStatus.MinimumSize = new Size((this as OperatingForm).Width - 22, 167);
}
I added some raw numbers as buffers.
Delegate :- Create
@protocol addToCartDelegate <NSObject>
-(void)addToCartAction:(ItemsModel *)itemsModel isAdded:(BOOL)added;
@end
Send and please assign delegate to view you are sending data
[self.delegate addToCartAction:itemsModel isAdded:YES];
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
npm init
It is all you need. It will create the package.json file on the fly for you.
Short answer: java -classpath lib/*:. my.package.Program
Oracle provides documentation on using wildcards in classpaths here for Java 6 and here for Java 7, under the section heading Understanding class path wildcards. (As I write this, the two pages contain the same information.) Here's a summary of the highlights:
In general, to include all of the JARs in a given directory, you can use the wildcard *
(not *.jar
).
The wildcard only matches JARs, not class files; to get all classes in a directory, just end the classpath entry at the directory name.
The above two options can be combined to include all JAR and class files in a directory, and the usual classpath precedence rules apply. E.g. -cp /classes;/jars/*
The wildcard will not search for JARs in subdirectories.
The above bullet points are true if you use the CLASSPATH
system property or the -cp
or -classpath
command line flags. However, if you use the Class-Path
JAR manifest header (as you might do with an ant build file), wildcards will not be honored.
Yes, my first link is the same one provided in the top-scoring answer (which I have no hope of overtaking), but that answer doesn't provide much explanation beyond the link. Since that sort of behavior is discouraged on Stack Overflow these days, I thought I'd expand on it.
Search in jspdf.js this:
if(type == 'datauri') {
document.location.href ='data:application/pdf;base64,' + Base64.encode(buffer);
}
Add :
if(type == 'datauriNew') {
window.open('data:application/pdf;base64,' + Base64.encode(buffer));
}
If the servers are clustered and there is a clustered DTC you have to disable security on the clustered DTC not the local DTC.
HTTP_CLIENT_IP is the most reliable way of getting the user's IP address. Next is HTTP_X_FORWARDED_FOR, followed by REMOTE_ADDR. Check all three, in that order, assuming that the first one that is set (isset($_SERVER['HTTP_CLIENT_IP'])
returns true if that variable is set) is correct. You can independently check if the user is using a proxy using various methods. Check this out.
The warning is generated because you are using a full URL for the file that you are including. This is NOT the right way because this way you are going to get some HTML from the webserver. Use:
require_once('../web/a.php');
so that webserver could EXECUTE the script and deliver its output, instead of just serving up the source code (your current case which leads to the warning).
From PostreSQL 9.2 Range Types are supported. So you can write this like:
SELECT user_id
FROM user_logs
WHERE '[2014-02-01, 2014-03-01]'::daterange @> login_date
this should be more efficient than the string comparison
If you need to check whether the elements of one vector are in another, the best solution is ismember
as mentioned in the other answers.
ismember([15 17],primes(20))
However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf
It gives a very practical example:
[tf, loc]=ismember(0.3, 0:0.1:1) % returns false
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true
Though the default tolerance should normally be sufficient, it gives you more flexibility
ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true
My suggestion would be to use a StringIO
object. They emulate files, but reside in memory. So you could do something like this:
# get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo'
import zipfile
from StringIO import StringIO
zipdata = StringIO()
zipdata.write(get_zip_data())
myzipfile = zipfile.ZipFile(zipdata)
foofile = myzipfile.open('foo.txt')
print foofile.read()
# output: "hey, foo"
Or more simply (apologies to Vishal):
myzipfile = zipfile.ZipFile(StringIO(get_zip_data()))
for name in myzipfile.namelist():
[ ... ]
In Python 3 use BytesIO instead of StringIO:
import zipfile
from io import BytesIO
filebytes = BytesIO(get_zip_data())
myzipfile = zipfile.ZipFile(filebytes)
for name in myzipfile.namelist():
[ ... ]
the first command is correct but change from convert to export to csv, as below,
Get-ADUser -Filter * -Properties * `
| Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
| Sort-Object -Property Name `
| Export-Csv -path C:\Users\*\Desktop\file1.csv
Edit: The bitset stuff below is maybe an interesting read, but the answer itself is a bit dated. Some of this functionality is changing around in 2.x. Also Slawek points out in another answer that the terms
query is an easy way to DRY up the search in this case. Refactored at the end for current best practices. —nz
You'll probably want a Bool Query (or more likely Filter alongside another query), with a should
clause.
The bool query has three main properties: must
, should
, and must_not
. Each of these accepts another query, or array of queries. The clause names are fairly self-explanatory; in your case, the should
clause may specify a list filters, a match against any one of which will return the document you're looking for.
From the docs:
In a boolean query with no
must
clauses, one or moreshould
clauses must match a document. The minimum number of should clauses to match can be set using theminimum_should_match
parameter.
Here's an example of what that Bool query might look like in isolation:
{
"bool": {
"should": [
{ "term": { "tag": "c" }},
{ "term": { "tag": "d" }}
]
}
}
And here's another example of that Bool query as a filter within a more general-purpose Filtered Query:
{
"filtered": {
"query": {
"match": { "title": "hello world" }
},
"filter": {
"bool": {
"should": [
{ "term": { "tag": "c" }},
{ "term": { "tag": "d" }}
]
}
}
}
}
Whether you use Bool as a query (e.g., to influence the score of matches), or as a filter (e.g., to reduce the hits that are then being scored or post-filtered) is subjective, depending on your requirements.
It is generally preferable to use Bool in favor of an Or Filter, unless you have a reason to use And/Or/Not (such reasons do exist). The Elasticsearch blog has more information about the different implementations of each, and good examples of when you might prefer Bool over And/Or/Not, and vice-versa.
Elasticsearch blog: All About Elasticsearch Filter Bitsets
Update with a refactored query...
Now, with all of that out of the way, the terms
query is a DRYer version of all of the above. It does the right thing with respect to the type of query under the hood, it behaves the same as the bool
+ should
using the minimum_should_match
options, and overall is a bit more terse.
Here's that last query refactored a bit:
{
"filtered": {
"query": {
"match": { "title": "hello world" }
},
"filter": {
"terms": {
"tag": [ "c", "d" ],
"minimum_should_match": 1
}
}
}
}
Please use dataset
var article = document.querySelector('#electriccars'),
data = article.dataset;
// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"
so in your case for setting data:
getElementById('item1').dataset.icon = "base2.gif";
When using this safari-only filter I could target Safari (iOS and Mac), but exclude Chrome (and other browsers):
@supports (-webkit-backdrop-filter: blur(1px)) {
.safari-only {
background-color: rgb(76,80,84);
}
}
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
Quoted from https://developer.mozilla.org/en/DOM/element.click
The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.
Non–Gecko DOMs may behave differently.
Unfortunately it sounds like you have already discovered the best solution to your problem.
As a side note, I agree that your solution seems less than ideal, but if you encapsulate the functionality inside a method (much like JQuery would do) it is not so bad.
First of all, what you have is a fully compiled program, not an object file, so drop the .o
extension. Now, pay attention to what the error message says, it tells you exactly how to fix your problem: "No symbol table is loaded. Use the "file" command."
(gdb) exec-file test
(gdb) b 2
No symbol table is loaded. Use the "file" command.
(gdb) file test
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb)
Or just pass the program on the command line.
$ gdb test
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb)
Task Passwordless authentication for suer.
Error : Host key verification failed.
Source :10.13.1.11 Target : 10.13.1.35
Temporary workaround :
[user@server~]$ ssh [email protected] The authenticity of host '10.13.1.35 (10.13.1.35)' can't be established. RSA key fingerprint is b8:ba:30:46:a9:ab:70:12:1a:f2:f1:61:69:73:0a:19. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '10.13.1.35' (RSA) to the list of known hosts.
Try to authenticate user again...it will work.
You can set using SelectedIndex
comboBox1.SelectedIndex= 1;
OR
SelectedItem
comboBox1.SelectedItem = "your value"; //
The latter won't throw an exception if the value is not available in the combobox
EDIT
If the value to be selected is not specific then you would be better off with this
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
In case you have one of the following cases:
InvalidArgumentError: input_X:Y is both fed and fetched
You need to do the following changes:
outputs
variablefunctors
loopMinimum example:
from keras.engine.input_layer import InputLayer
inp = model.input
outputs = [layer.output for layer in model.layers if not isinstance(layer, InputLayer)]
functors = [K.function(inp + [K.learning_phase()], [x]) for x in outputs]
layer_outputs = [fun([x1, x2, xn, 1]) for fun in functors]
xargs --arg-file inputfile cat
This will output the filename followed by the file's contents:
xargs --arg-file inputfile -I % sh -c "echo %; cat %"
We can hide close button on form by setting this.ControlBox=false;
Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.
I needed to convert a timeval struct (seconds, microseconds) containing UNIX time
to DateTime
without losing precision and haven't found an answer here so I thought I just might add mine:
DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private DateTime UnixTimeToDateTime(Timeval unixTime)
{
return _epochTime.AddTicks(
unixTime.Seconds * TimeSpan.TicksPerSecond +
unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);
}
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
By default, the update() method updates a single document. Set the Multi Parameter to update all documents that match the query criteria.
Changed in version 3.6. Syntax :
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
Example :
db.getCollection('products').update({},{$unset: {translate:1, qordoba_translation_version:1}}, {multi: true})
In your example :
db.getCollection('products').update({},{$unset: {'tags.words' :1}}, {multi: true})
Suggested method gave me error on Ubuntu 16.04: E: Unable to locate package mingw32
===========================================================================
To install this package on Ubuntu please use following:
sudo apt-get install mingw-w64
After install you can use it:
x86_64-w64-mingw32-g++
Please note!
For 64-bit use: x86_64-w64-mingw32-g++
For 32-bit use: i686-w64-mingw32-g++
Just do one thing
open skype > tools > advance or advance settings Change port 80 to something else 7395
Restart your system then start Apache
Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:
#container {
min-width:800px;
width: auto !important;
width:800px;
}
That will effectively give you 800px min-width in IE6 and any up-to-date browsers.
You can set your hash directly to URL too.
window.location.hash = "YourHash";
The result : http://url#YourHash
No this is not possible, SVG elements do not have background-...
presentation attributes.
To simulate this effect you could draw a rectangle behind the text attribute with fill="green"
or something similar (filters). Using JavaScript you could do the following:
var ctx = document.getElementById("the-svg"),
textElm = ctx.getElementById("the-text"),
SVGRect = textElm.getBBox();
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", SVGRect.x);
rect.setAttribute("y", SVGRect.y);
rect.setAttribute("width", SVGRect.width);
rect.setAttribute("height", SVGRect.height);
rect.setAttribute("fill", "yellow");
ctx.insertBefore(rect, textElm);
(scrollWidth/Height - clientWidth/Height) is a good indicator for the presence of a scrollbar, but it will give you a "false positive" answer on many occasions. if you need to be accurate i would suggest using the following function. instead of trying to guess if the element is scrollable - you can scroll it...
function isScrollable( el ){_x000D_
var y1 = el.scrollTop;_x000D_
el.scrollTop += 1;_x000D_
var y2 = el.scrollTop;_x000D_
el.scrollTop -= 1;_x000D_
var y3 = el.scrollTop;_x000D_
el.scrollTop = y1;_x000D_
var x1 = el.scrollLeft;_x000D_
el.scrollLeft += 1;_x000D_
var x2 = el.scrollLeft;_x000D_
el.scrollLeft -= 1;_x000D_
var x3 = el.scrollLeft;_x000D_
el.scrollLeft = x1;_x000D_
return {_x000D_
horizontallyScrollable: x1 !== x2 || x2 !== x3,_x000D_
verticallyScrollable: y1 !== y2 || y2 !== y3_x000D_
}_x000D_
}_x000D_
function check( id ){_x000D_
alert( JSON.stringify( isScrollable( document.getElementById( id ))));_x000D_
}
_x000D_
#outer1, #outer2, #outer3 {_x000D_
background-color: pink;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
}_x000D_
#inner {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
}_x000D_
button { margin: 2em 0 0 1em; }
_x000D_
<div id="outer1" style="width: 100px; height: 100px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer1')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>_x000D_
<div id="outer2" style="width: 200px; height: 100px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer2')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>_x000D_
<div id="outer3" style="width: 100px; height: 180px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer3')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>
_x000D_
Technically, to repair your statement, you can add LIMIT 1
to the subquery to ensure that at most 1 row is returned. That would remove the error, your code would still be nonsense.
... 'SELECT store_key FROM store LIMIT 1' ...
Practically, you want to match rows somehow instead of picking an arbitrary row from the remote table store
to update every row of your local table customer
.
Your rudimentary question doesn't provide enough details, so I am assuming a text column match_name
in both tables (and UNIQUE
in store
) for the sake of this example:
... 'SELECT store_key FROM store
WHERE match_name = ' || quote_literal(customer.match_name) ...
But that's an extremely expensive way of doing things.
Ideally, you should completely rewrite the statement.
UPDATE customer c
SET customer_id = s.store_key
FROM dblink('port=5432, dbname=SERVER1 user=postgres password=309245'
,'SELECT match_name, store_key FROM store')
AS s(match_name text, store_key integer)
WHERE c.match_name = s.match_name
AND c.customer_id IS DISTINCT FROM s.store_key;
This remedies a number of problems in your original statement.
Obviously, the basic problem leading to your error is fixed.
It's almost always better to join in additional relations in the FROM
clause of an UPDATE
statement than to run correlated subqueries for every individual row.
When using dblink, the above becomes a thousand times more important. You do not want to call dblink()
for every single row, that's extremely expensive. Call it once to retrieve all rows you need.
With correlated subqueries, if no row is found in the subquery, the column gets updated to NULL, which is almost always not what you want.
In my updated form, the row only gets updated if a matching row is found. Else, the row is not touched.
Normally, you wouldn't want to update rows, when nothing actually changes. That's expensively doing nothing (but still produces dead rows). The last expression in the WHERE
clause prevents such empty updates:
AND c.customer_id IS DISTINCT FROM sub.store_key
Instead of Googling for %02d
you should have been searching for sprintf()
function.
%02d
means "format the integer with 2 digits, left padding it with zeroes", so:
Format Data Result %02d 1 01 %02d 11 11
values can be : [a-z],[A-Z],[0-9],[* _ : -]
it is use for HTML5 ...
we can add id with any tag.
Once an update is committed you can't rollback just the single update. Your best bet is to roll back to a previous backup of the database.
Here is the regex for Ethiopian Phone Number. For my fellow Ethiopian developers ;)
phoneExp = /^(^\+251|^251|^0)?9\d{8}$/;
It matches the following (restrict any unwanted character in start and end position)
You can test it on this site regexr.
Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^
// Stores UserManager
private readonly UserManager<ApplicationUser> _manager;
// Inject UserManager using dependency injection.
// Works only if you choose "Individual user accounts" during project creation.
public DemoController(UserManager<ApplicationUser> manager)
{
_manager = manager;
}
// You can also just take part after return and use it in async methods.
private async Task<ApplicationUser> GetCurrentUser()
{
return await _manager.GetUserAsync(HttpContext.User);
}
// Generic demo method.
public async Task DemoMethod()
{
var user = await GetCurrentUser();
string userEmail = user.Email; // Here you gets user email
string userId = user.Id;
}
That code goes to controller named DemoController. Won't work without both await (won't compile) ;)
I had a similar problem:
module cv2 has no attribute "cv2.TrackerCSRT_create"
My Python version is 3.8.0 under Windows 10. The problem was the opencv version installation.
So I fixed this way (cmd prompt with administrator privileges):
pip uninstall opencv-python
pip install opencv-contrib-python
Anyway you can read the following guide:
The most easy option should be to use a rounding routine:
import numpy as np
x=[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print('standard:')
print(x)
print("\nhuman readable:")
print(np.around(x,decimals=2))
This produces the output:
standard:
[9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.0793303]
human readable:
[ 9. 0.05 0.03 0.01 0.06 0.08]
Here is how to calculate the text height in Swift. You can then get the height from the rect and set the constraint height of the label or textView, etc.
let font = UIFont(name: "HelveticaNeue", size: 25)!
let text = "This is some really long text just to test how it works for calculating heights in swift of string sizes. What if I add a couple lines of text?"
let textString = text as NSString
let textAttributes = [NSFontAttributeName: font]
let textRect = textString.boundingRectWithSize(CGSizeMake(320, 2000), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
I spent several hours on such case. I saw only touch keys logs. Nothing more. Problem was... smarthphone. After restarting was OK. Disconnecting cable caused problem returned. Had to restart it again. Looks like the Android USB communication is not well designed.
In most cases it could be better to pad the columns only on the right so just the spacing between the columns gets padded, and the first column is still aligned with the table.
CSS:
.padding-table-columns td
{
padding:0 5px 0 0; /* Only right padding*/
}
HTML:
<table className="padding-table-columns">
<tr>
<td>Cell one</td>
<!-- There will be a 5px space here-->
<td>Cell two</td>
<!-- There will be an invisible 5px space here-->
</tr>
</table>
chmod u+x program_name
. Then execute it.
If that does not work, copy the program from the USB device to a native volume on the system. Then chmod u+x program_name
on the local copy and execute that.
Unix and Unix-like systems generally will not execute a program unless it is marked with permission to execute. The way you copied the file from one system to another (or mounted an external volume) may have turned off execute permission (as a safety feature). The command chmod u+x name
adds permission for the user that owns the file to execute it.
That command only changes the permissions associated with the file; it does not change the security controls associated with the entire volume. If it is security controls on the volume that are interfering with execution (for example, a noexec
option may be specified for a volume in the Unix fstab
file, which says not to allow execute permission for files on the volume), then you can remount the volume with options to allow execution. However, copying the file to a local volume may be a quicker and easier solution.
I found that using the Common Event described above works well and you could have the common event set up like this:
private void checkChanged(object sender, EventArgs e)
{
foreach (RadioButton r in yourPanel.Controls)
{
if (r.Checked)
textBox.Text = r.Text;
}
}
Of course, then you can't have other controls in your panel that you use, but it's useful if you just have a separate panel for all your radio buttons (such as using a sub panel inside a group box or however you prefer to organize your controls)
ArrayList: ArrayList has a structure like an array, it has a direct reference to every element. So rendom access is fast in ArrayList.
LinkedList: In LinkedList for getting nth elemnt you have to traverse whole list, takes time as compared to ArrayList. Every element has a link to its previous & nest element, so deletion is fast.
After reading the article from Marc Cliament's comment above, I've now changed my all-purpose cross-browser console.log function to look like this:
function log()
{
"use strict";
if (typeof(console) !== "undefined" && console.log !== undefined)
{
try
{
console.log.apply(console, arguments);
}
catch (e)
{
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
}
}
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
Goes to the right and can be used the same way for the left
.yourComponent
{
float: right;
bottom: 0;
}
Found this while working with Epicycles - clearly works - where 'p' is invisible to my eyes.
/** Convert a set of picture points to a set of Cartesian coordinates */
function toCartesian(points, scale) {
const x_max = Math.max(...points.map(p=>p[0])),
y_max = Math.max(...points.map(p=>p[1])),
x_min = Math.min(...points.map(p=>p[0])),
y_min = Math.min(...points.map(p=>p[1])),
signed_x_max = Math.floor((x_max - x_min + 1) / 2),
signed_y_max = Math.floor((y_max - y_min + 1) / 2);
return points.map(p=>
[ -scale * (signed_x_max - p[0] + x_min),
scale * (signed_y_max - p[1] + y_min) ] );
}
os.system('command')
returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.
Refer my answer for more detail in What is the return value of os.system() in Python?
Here's a cleaner way using the PackageManager
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
// the getLaunchIntentForPackage returns an intent that you can use with startActivity()
More info here http://qtcstation.com/2011/02/how-to-launch-another-app-from-your-app/
[ngClass]=...
instead of *ngClass
.
*
is only for the shorthand syntax for structural directives where you can for example use
<div *ngFor="let item of items">{{item}}</div>
instead of the longer equivalent version
<template ngFor let-item [ngForOf]="items">
<div>{{item}}</div>
</template>
See also https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
<some-element [ngClass]="'first second'">...</some-element> <some-element [ngClass]="['first', 'second']">...</some-element> <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element> <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element> <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
See also https://angular.io/docs/ts/latest/guide/template-syntax.html
<!-- toggle the "special" class on/off with a property --> <div [class.special]="isSpecial">The class binding is special</div> <!-- binding to `class.special` trumps the class attribute --> <div class="special" [class.special]="!isSpecial">This one is not so special</div>
<!-- reset/override all class names with a binding --> <div class="bad curly special" [class]="badCurly">Bad curly</div>
Another issue that you might run into if you're running RHEL (I ran into it) is that there is a default welcome page configured with the httpd package that will override your settings, even if you put Options Indexes. The file is in /etc/httpd/conf.d/welcome.conf. See the following link for more info: http://wpapi.com/solved-issue-directory-index-forbidden-by-options-directive/
Elements()
will only check direct children - which in the first case is the root element, in the second case children of the root element, hence you get a match in the second case. If you just want any matching descendant use Descendants()
instead:
var query = from c in xmlFile.Descendants("Band") select c;
Also I would suggest you re-structure your Xml: The band name should be an attribute or element value, not the element name itself - this makes querying (and schema validation for that matter) much harder, i.e. something like this:
<Band>
<BandProperties Name ="Doors" ID="222" started="1968" />
<Description>regular Band<![CDATA[lalala]]></Description>
<Last>1</Last>
<Salary>2</Salary>
</Band>
FrostWire Team over here.
All the selector crap api doesn't work as expected. After trying all the solutions presented in this thread to no good, we just solved the problem at the moment of inflating the ListView Item.
Make sure your item keeps it's state, we did it as a member variable of the MenuItem (boolean selected)
When you inflate, ask if the underlying item is selected, if so, just set the drawable resource that you want as the background (be it a 9patch or whatever). Make sure your adapter is aware of this and that it calls notifyDataChanged() when something has been selected.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = act.getLayoutInflater();
rowView = inflater.inflate(R.layout.slidemenu_listitem, null);
MenuItemHolder viewHolder = new MenuItemHolder();
viewHolder.label = (TextView) rowView.findViewById(R.id.slidemenu_item_label);
viewHolder.icon = (ImageView) rowView.findViewById(R.id.slidemenu_item_icon);
rowView.setTag(viewHolder);
}
MenuItemHolder holder = (MenuItemHolder) rowView.getTag();
String s = items[position].label;
holder.label.setText(s);
holder.icon.setImageDrawable(items[position].icon);
//Here comes the magic
rowView.setSelected(items[position].selected);
rowView.setBackgroundResource((rowView.isSelected()) ? R.drawable.slidemenu_item_background_selected : R.drawable.slidemenu_item_background);
return rowView;
}
It'd be really nice if the selectors would actually work, in theory it's a nice and elegant solution, but it seems like it's broken. KISS.
My solution:
$(window).resize(function() {
$('#div_to_occupy_the_rest').height(
$(window).height() - $('#div_to_occupy_the_rest').offset().top
);
});
Using .on()
you can define your function once, and it will execute for any dynamically added elements.
for example
$('#staticDiv').on('click', 'yourSelector', function() {
//do something
});
Yes, I just hit my first 'PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM'
. My bad, I had a $instance::method()
that should have been $instance->method()
. Silly me.
The odd thing is that this still works just fine on my local machine (running PHP 5.3.8) - nothing, not even a warning with error_reporting = E_ALL - but not at all on the test server, there it just explodes with a syntax error and a white screen in the browser. Since PHP logging was turned off at the test machine, and the hosting company was too busy to turn it on, it was not too obvious.
So, word of warning: apparently, some PHP installations will let you use a $instance::method(), while others don't.
If anybody can expand on why that is, please do.
I know this is not a solution for OP, but since I'm sure there are many other use cases here, I thought I would share.
I've had problems with all the code examples in these answers but then I found : http://www.robotronic.de/runasspcEn.html
It not only allows you to run as admin, it checks the file to make sure it has not been tampered with and stores the needed information securely. I'll admit it's not the most obvious tool to figure out how to use but for those of us writing code it should be simple enough.
You are missing the selector in the .on
function:
.on(eventType, selector, function)
This selector is very important!
If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler
See jQuery 1.9 .live() is not a function for more details.
Let the number be n
then the number of digits in n
is given by:
math.floor(math.log10(n))+1
Note that this will give correct answers for +ve integers < 10e15. Beyond that the precision limits of the return type of math.log10
kicks in and the answer may be off by 1. I would simply use len(str(n))
beyond that; this requires O(log(n))
time which is same as iterating over powers of 10.
Thanks to @SetiVolkylany for bringing my attenstion to this limitation. Its amazing how seemingly correct solutions have caveats in implementation details.
This is how its working for me. The redirection used will redirect all the normal http as well.
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('certificates/private.key'),
cert: fs.readFileSync('certificates/certificate.crt'),
ca: fs.readFileSync('certificates/ca_bundle.crt')
};
// API file for interacting with MongoDB
const api = require('./server/routes/api');
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));
// API location
app.use('/api', api);
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function(req,resp,next){
if (req.headers['x-forwarded-proto'] == 'http') {
return resp.redirect(301, 'https://' + req.headers.host + '/');
} else {
return next();
}
});
http.createServer(app).listen(80)
https.createServer(options, app).listen(443);
Your include paths indicate that you should be compiling against the system's OpenSSL installation. You shouldn't have the .h
files in your package directory - it should be picking them up from /usr/include/openssl
.
The plain OpenSSL package (libssl
) doesn't include the .h
files - you need to install the development package as well. This is named libssl-dev
on Debian, Ubuntu and similar distributions, and libssl-devel
on CentOS, Fedora, Red Hat and similar.
Don't use height property in input field.
Example:
.heighttext{
display:inline-block;
padding:15px 10px;
line-height:140%;
}
Always use padding and line-height css property. Its work perfect for all mobile device and all browser.
It's 2015. I had to go to find a blog post that would explain how to do it for the latest version of iOS and XCode with Swift so that it would work with multiple lines.
Source: http://beckyhansmeyer.com/2015/04/09/autoshrinking-text-in-a-multiline-uilabel/
The answer posted by Y. Shoham (using absolute positioning) seems to be the simplest solution in most cases where the container is a fixed height, but if the parent DIV has to contain multiple DIVs and auto adjust it's height based on dynamic content, then there can be a problem. I needed to have two blocks of dynamic content; one aligned to the top of the container and one to the bottom and although I could get the container to adjust to the size of the top DIV, if the DIV aligned to the bottom was taller, it would not resize the container but would extend outside. The method outlined above by romiem using table style positioning, although a bit more complicated, is more robust in this respect and allowed alignment to the bottom and correct auto height of the container.
CSS
#container {
display: table;
height: auto;
}
#top {
display: table-cell;
width:50%;
height: 100%;
}
#bottom {
display: table-cell;
width:50%;
vertical-align: bottom;
height: 100%;
}
HTML
<div id=“container”>
<div id=“top”>Dynamic content aligned to top of #container</div>
<div id=“bottom”>Dynamic content aligned to botttom of #container</div>
</div>
I realise this is not a new answer but I wanted to comment on this approach as it lead me to find my solution but as a newbie I was not allowed to comment, only post.
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
So, I've really tried to understand this, but it seems that Django still doesn't make this very straightforward. I'm not all that dumb, but I just can't see any (somewhat) simple solution.
I find it generally pretty ugly to have to override the Admin views for this sort of thing, and every example I find never fully applies to the Admin views.
This is such a common circumstance with the models I make that I find it appalling that there's no obvious solution to this...
I've got these classes:
# models.py
class Company(models.Model):
# ...
class Contract(models.Model):
company = models.ForeignKey(Company)
locations = models.ManyToManyField('Location')
class Location(models.Model):
company = models.ForeignKey(Company)
This creates a problem when setting up the Admin for Company, because it has inlines for both Contract and Location, and Contract's m2m options for Location are not properly filtered according to the Company that you're currently editing.
In short, I would need some admin option to do something like this:
# admin.py
class LocationInline(admin.TabularInline):
model = Location
class ContractInline(admin.TabularInline):
model = Contract
class CompanyAdmin(admin.ModelAdmin):
inlines = (ContractInline, LocationInline)
inline_filter = dict(Location__company='self')
Ultimately I wouldn't care if the filtering process was placed on the base CompanyAdmin, or if it was placed on the ContractInline. (Placing it on the inline makes more sense, but it makes it hard to reference the base Contract as 'self'.)
Is there anyone out there who knows of something as straightforward as this badly needed shortcut? Back when I made PHP admins for this sort of thing, this was considered basic functionality! In fact, it was always automatic, and had to be disabled if you really didn't want it!
For Windows 8:
Control Panel -> (Search for) Credentials Manager -> Check Web Credentials
this worked for me...
In addition to nexe, browserify can be used to bundle up all your dependencies as a single .js
file. This does not bundle the actual node executable, just handles the javascript side. It too does not handle native modules. The command line options for pure node compilation would be browserify --output bundle.js --bare --dg false input.js
.
We use Immer https://github.com/mweststrate/immer to handle these kinds of issues.
Just replaced this code in one of our components
this.setState(prevState => ({
...prevState,
preferences: {
...prevState.preferences,
[key]: newValue
}
}));
With this
import produce from 'immer';
this.setState(produce(draft => {
draft.preferences[key] = newValue;
}));
With immer you handle your state as a "normal object". The magic happens behind the scene with proxy objects.
Using MySQL I usually do it that way:
SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;
Or in the same idea, if you need to output the date/hour:
SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM your_table
GROUP BY my_date
order by your_date_column desc;
If you specify an index on your date column, MySQL should be able to use it to speed up things a little.
numpy.ndarray
can contain any type of element, e.g. int
, float
, string
etc. Check the type an do a conversion if neccessary.
As of this writing, it was necessary to:
I don't know what qualifies as best but zxing has a qr code generator for java, is actively developed, and is liberally licensed.
If you enable
<application android:debuggable="true">
</application>
In the application manifest.xml make sure you disable it when generating the final signed apk since this can serve as a security loop hole for attackers. Only use it if only one of your applications does not show the logs. However before considering that option try this:
Navigate to tools in the android studio
Tools==>android==>disable adb integration and again enable it
If all you're trying to do is select the first blank cell in a given column, you can give this a try:
Range("A1").End(xlDown).Offset(1, 0).Select
If you're using it relative to a column you've selected this works:
Selection.End(xlDown).Offset(1, 0).Select
There is one more property JavaScript function has. If you want to call same anonymous function recursively.
(function forInternalOnly(){
//you can use forInternalOnly to call this anonymous function
/// forInternalOnly can be used inside function only, like
var result = forInternalOnly();
})();
//this will not work
forInternalOnly();// no such a method exist
You should dismiss you Dialog
in onPause()
so override it.
Also before dismissing you can check for null
and is showing like below snippet:
@Override
protected void onPause() {
super.onPause();
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
The ?
character signifies that the preceding group should be matched zero or one times. The group (-|\s)
will match either a -
or a |
character.
# Save the script arguments
SCRIPT_NAME=$0
ARG_1=$1
ARGS_ALL=$*
function stuff {
# use script args via the variables you saved
# or the function args via $
echo $0 $*
}
# Call the function with arguments
stuff 1 2 3 4
olivierg's answer worked for me and is the best solution if creating a custom Dialog class is the route you want to go. However, it bothered me that I couldn't use the AlertDialog class. I wanted to be able to use the default system AlertDialog style. Creating a custom dialog class would not have this style.
So I found a solution (hack) that will work without having to create a custom class, you can use the existing builders.
The AlertDialog puts a View above your content view as a placeholder for the title. If you find the view and set the height to 0, the space goes away.
I have tested this on 2.3 and 3.0 so far, it is possible it doesn't work on every version yet.
Here are two helper methods for doing it:
/**
* Show a Dialog with the extra title/top padding collapsed.
*
* @param customView The custom view that you added to the dialog
* @param dialog The dialog to display without top spacing
* @param show Whether or not to call dialog.show() at the end.
*/
public static void showDialogWithNoTopSpace(final View customView, final Dialog dialog, boolean show) {
// Now we setup a listener to detect as soon as the dialog has shown.
customView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Check if your view has been laid out yet
if (customView.getHeight() > 0) {
// If it has been, we will search the view hierarchy for the view that is responsible for the extra space.
LinearLayout dialogLayout = findDialogLinearLayout(customView);
if (dialogLayout == null) {
// Could find it. Unexpected.
} else {
// Found it, now remove the height of the title area
View child = dialogLayout.getChildAt(0);
if (child != customView) {
// remove height
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
lp.height = 0;
child.setLayoutParams(lp);
} else {
// Could find it. Unexpected.
}
}
// Done with the listener
customView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
// Show the dialog
if (show)
dialog.show();
}
/**
* Searches parents for a LinearLayout
*
* @param view to search the search from
* @return the first parent view that is a LinearLayout or null if none was found
*/
public static LinearLayout findDialogLinearLayout(View view) {
ViewParent parent = (ViewParent) view.getParent();
if (parent != null) {
if (parent instanceof LinearLayout) {
// Found it
return (LinearLayout) parent;
} else if (parent instanceof View) {
// Keep looking
return findDialogLinearLayout((View) parent);
}
}
// Couldn't find it
return null;
}
Here is an example of how it is used:
Dialog dialog = new AlertDialog.Builder(this)
.setView(yourCustomView)
.create();
showDialogWithNoTopSpace(yourCustomView, dialog, true);
If you are using this with a DialogFragment, override the DialogFragment's onCreateDialog
method. Then create and return your dialog like the first example above. The only change is that you should pass false as the 3rd parameter (show) so that it doesn't call show() on the dialog. The DialogFragment will handle that later.
Example:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new AlertDialog.Builder(getContext())
.setView(yourCustomView)
.create();
showDialogWithNoTopSpace(yourCustomView, dialog, false);
return dialog;
}
As I test this further I'll be sure to update with any additional tweaks needed.
Kotlin version with infix function
infix fun View.below(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}
Then you can write:
view1 below view2
Or you can call it as a normal function:
view1.below(view2)
I'm not sure if I understand your question correctly. It is a bit unclear. However, what might be confusing you is the following:
When passing by reference, a reference to the same object is passed to the function being called. Any changes to the object will be reflected in the original object and hence the caller will see it.
When passing by value, the copy constructor will be called. The default copy constructor will only do a shallow copy, hence, if the called function modifies an integer in the object, this will not be seen by the calling function, but if the function changes a data structure pointed to by a pointer within the object, then this will be seen by the caller due to the shallow copy.
I might have mis-understood your question, but I thought I would give it a stab anyway.
I have come to share an solution. The error happened to me after forcing the notbook to hang up. possible solution clean preject
.
In TypeScript 1.6, user-defined type guard will do the job.
interface Foo {
fooProperty: string;
}
interface Bar {
barProperty: string;
}
function isFoo(object: any): object is Foo {
return 'fooProperty' in object;
}
let object: Foo | Bar;
if (isFoo(object)) {
// `object` has type `Foo`.
object.fooProperty;
} else {
// `object` has type `Bar`.
object.barProperty;
}
And just as Joe Yang mentioned: since TypeScript 2.0, you can even take the advantage of tagged union type.
interface Foo {
type: 'foo';
fooProperty: string;
}
interface Bar {
type: 'bar';
barProperty: number;
}
let object: Foo | Bar;
// You will see errors if `strictNullChecks` is enabled.
if (object.type === 'foo') {
// object has type `Foo`.
object.fooProperty;
} else {
// object has type `Bar`.
object.barProperty;
}
And it works with switch
too.
function pad(value) {
return value.tostring().padstart(2, 0);
}
let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);
API level is basically the Android version. Instead of using the Android version name (eg 2.0, 2.3, 3.0, etc) an integer number is used. This number is increased with each version. Android 1.6 is API Level 4, Android 2.0 is API Level 5, Android 2.0.1 is API Level 6, and so on.
If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.
e.g.
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);
Delete the supplier, and it will delate all products for that supplier
For DataTables 1.9
Use bPaginate
option to disable pagination.
$('#example').dataTable({
"bPaginate": false
});
For DataTables 1.10+
Use paging
option to disable pagination.
$('#example').dataTable({
"paging": false
});
See this jsFiddle for code and demonstration.
For DataTables 1.9
Use sDom
option to configure which control elements appear on the page.
$('#example').dataTable({
"sDom": "lfrti"
});
For DataTables 1.10+
Use dom
option to configure which control elements appear on the page.
$('#example').dataTable({
"dom": "lfrti"
});
See this jsFiddle for code and demonstration.
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
If the file size is not big, then it is faster to read the entire file and split it afterwards
var filestreams = sr.ReadToEnd().Split(Environment.NewLine,
StringSplitOptions.RemoveEmptyEntries);
I have found something that Actually works in both FireFox and IE, on Elizabeth Castro's site (thanks to the link on this site) - I have tried all other versions here, but could not make them work in both the browsers
<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"
id="player" width="320" height="260">
<param name="url"
value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
<param name="src"
value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
<param name="showcontrols" value="true" />
<param name="autostart" value="true" />
<!--[if !IE]>-->
<object type="video/x-ms-wmv"
data="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv"
width="320" height="260">
<param name="src"
value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
<param name="autostart" value="true" />
<param name="controller" value="true" />
</object>
<!--<![endif]-->
</object>
Check her site out: http://www.alistapart.com/articles/byebyeembed/ and the version with the classid in the initial object tag
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
html, body {
height: 100%;
width: 100%;
}
html {
display: table;
margin: auto;
}
body {
padding-top: 50px;
display: table-cell;
}
div {
margin: auto;
}
This will center align objects and then also center align the items within them to center align multiple objects with different widths.
I've found the following combination that works fine for positive and negative numbers (43787200020 is transformed to 43.787.200,02 K)
[>=1000] #.##0,#0. "K";#.##0,#0. "K"
Adding my solution for Net Framework and NetCore.
I used this for my Net Framework implementation:
public static class EnumerationExtension
{
public static string Description( this Enum value )
{
// get attributes
var field = value.GetType().GetField( value.ToString() );
var attributes = field.GetCustomAttributes( typeof( DescriptionAttribute ), false );
// return description
return attributes.Any() ? ( (DescriptionAttribute)attributes.ElementAt( 0 ) ).Description : "Description Not Found";
}
}
This doesn't work for NetCore so I modified it to do this:
public static class EnumerationExtension
{
public static string Description( this Enum value )
{
// get attributes
var field = value.GetType().GetField( value.ToString() );
var attributes = field.GetCustomAttributes( false );
// Description is in a hidden Attribute class called DisplayAttribute
// Not to be confused with DisplayNameAttribute
dynamic displayAttribute = null;
if (attributes.Any())
{
displayAttribute = attributes.ElementAt( 0 );
}
// return description
return displayAttribute?.Description ?? "Description Not Found";
}
}
Enumeration Example:
public enum ExportTypes
{
[Display( Name = "csv", Description = "text/csv" )]
CSV = 0
}
Sample Usage for either static added:
var myDescription = myEnum.Description();
Use the map
method:
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
I'm using SSMS 2008 version 10.0.5500.0. In this version as part of the Generate Scripts wizard, instead of an Advanced button, there is the screen below. In this case, I wanted just the data inserted and no create statements, so I had to change the two circled properties
I find the solution in spring.io,like this:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
Workable solution:
downloadCSV(data){
const newBlob = new Blob([decodeURIComponent(encodeURI(data))], { type: 'text/csv;charset=utf-8;' });
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const fileData = window.URL.createObjectURL(newBlob);
const link = document.createElement('a');
link.href = fileData;
link.download = `Usecase-Unprocessed.csv`;
// this is necessary as link.click() does not work on the latest firefox
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(fileData);
link.remove();
}, 5000);
}
new File(context.getFilesDir(), fileName).delete();
I can delete file in shared preferences with it
First of all, you shouldn't rebuild all your views to fit a new screen, nor use different views for different screen sizes.
Use the auto-resizing capabilities of iOS, so your views can adjust, and adapt any screen size.
That's not very hard, read some documentation about that. It will save you a lot of time.
iOS 6 also offers new features about this.
Be sure to read the iOS 6 API changelog on Apple Developer website.
And check the new iOS 6 AutoLayout capabilities.
That said, if you really need to detect the iPhone 5, you can simply rely on the screen size.
[ [ UIScreen mainScreen ] bounds ].size.height
The iPhone 5's screen has a height of 568.
You can imagine a macro, to simplify all of this:
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
The use of fabs
with the epsilon is here to prevent precision errors, when comparing floating points, as pointed in the comments by H2CO3.
So from now on you can use it in standard if/else statements:
if( IS_IPHONE_5 )
{}
else
{}
Edit - Better detection
As stated by some people, this does only detect a widescreen, not an actual iPhone 5.
Next versions of the iPod touch will maybe also have such a screen, so we may use another set of macros.
Let's rename the original macro IS_WIDESCREEN
:
#define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
And let's add model detection macros:
#define IS_IPHONE ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone" ] )
#define IS_IPOD ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPod touch" ] )
This way, we can ensure we have an iPhone model AND a widescreen, and we can redefine the IS_IPHONE_5
macro:
#define IS_IPHONE_5 ( IS_IPHONE && IS_WIDESCREEN )
Also note that, as stated by @LearnCocos2D, this macros won't work if the application is not optimised for the iPhone 5 screen (missing the [email protected] image), as the screen size will still be 320x480 in such a case.
I don't think this may be an issue, as I don't see why we would want to detect an iPhone 5 in a non-optimized app.
IMPORTANT - iOS 8 support
On iOS 8, the bounds
property of the UIScreen
class now reflects the device orientation.
So obviously, the previous code won't work out of the box.
In order to fix this, you can simply use the new nativeBounds
property, instead of bounds
, as it won't change with the orientation, and as it's based on a portrait-up mode.
Note that dimensions of nativeBounds
is measured in pixels, so for an iPhone 5 the height will be 1136 instead of 568.
If you're also targeting iOS 7 or lower, be sure to use feature detection, as calling nativeBounds
prior to iOS 8 will crash your app:
if( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] )
{
/* Detect using nativeBounds - iOS 8 and greater */
}
else
{
/* Detect using bounds - iOS 7 and lower */
}
You can adapt the previous macros the following way:
#define IS_WIDESCREEN_IOS7 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define IS_WIDESCREEN_IOS8 ( fabs( ( double )[ [ UIScreen mainScreen ] nativeBounds ].size.height - ( double )1136 ) < DBL_EPSILON )
#define IS_WIDESCREEN ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_WIDESCREEN_IOS8 : IS_WIDESCREEN_IOS7 )
And obviously, if you need to detect an iPhone 6 or 6 Plus, use the corresponding screen sizes.
I tried out solution suggested by Russ Bateman Here in the post
http://localhost:8080/Myapp
to http://localhost:8080/somepath/Myapp
But Didnt worked for me as I needed to have a *.war file that can hold the config and not the individual instance of server on my localmachine.
In order to do that I need jboss-web.xml placed in WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2008 Object Computing, Inc.
All rights reserved.
-->
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 4.2//EN"
"http://www.jboss.org/j2ee/dtd/jboss-web_4_2.dtd">
<jboss-web>
<context-root>somepath/Myapp</context-root>
</jboss-web>
When filtering a DataFrame with string values, I find that the pyspark.sql.functions
lower
and upper
come in handy, if your data could have column entries like "foo" and "Foo":
import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))
From now onwards after API 24, Uri.parse(filePath)
won't work. You need to use this
final File videoFile = new File("path to your video file");
Uri fileUri = FileProvider.getUriForFile(mContext, "{yourpackagename}.fileprovider", videoFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(fileUri, "video/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//DO NOT FORGET THIS EVER
startActivity(intent);
But before using this you need to understand how file provider works. Go to official document link to understand file provider better.
I see we have the same problem here, I have the same error. I want to write this for the future user who will experience the same error. After making changes to your class Snippet model like @Burhan Khalid said, you must migrate tables:
python manage.py makemigrations snippets
python manage.py migrate
And that should resolve the error. Enjoy.
I faced the same problem and I've found a pretty clean solution: After Html.fromHtml() you can run an AsyncTask that iterates over all the tags, fetches the images and then displays them.
Here you can find some code that you can use (but it needs some customization): https://gist.github.com/1190397
You can do it on a per file basis. Use the path attribute to include the filename
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="YourFileNameHere.xml">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>
\b
matches a word-boundary. \B
matches non-word-boundaries, and is equivalent to [^\b]
(?!\b)
(thanks to @Alan Moore for the correction!). Both are zero-width.
See http://www.regular-expressions.info/wordboundaries.html for details. The site is extremely useful for many basic regex questions.
Through Configuration, you can do this:
Model1
{
int fk_one,
int fk_two
}
Model2
{
int pk_one,
int pk_two,
}
then in the context config
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Model1>()
.HasRequired(e => e.Model2)
.WithMany(e => e.Model1s)
.HasForeignKey(e => new { e.fk_one, e.fk_two })
.WillCascadeOnDelete(false);
}
}
The answer provided by @Matthias Herlitzius is mostly correct. Just for further clarity.
The servlet-api jar is best left up to the server to manage see here for detail
With that said, the dependency to add may vary according to your server/container. For example in Wildfly the dependency would be
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.1_spec</artifactId>
<scope>provided</scope>
</dependency>
So becareful to check how your container has provided the servlet implementation.
console.debug("");
Using this method prints out the text in a bright blue color in the console.
I have installed both Smultron and Textwrangler, but find myself using Smultron most of the time.
The only thing that helped me was to use the system gradle instead of Android Studio's built-in:
SETTINGS -> Build, Execution, Deployment -> Gradle
Select Use local gradle distribution. To find the path, you can do which gradle
where the which
program is supported. It might be /usr/bin/gradle
.
See also Error:Could not initialize class com.android.sdklib.repositoryv2.AndroidSdkHandler for another possible cause.
Looks like a regular expression is the way to go:
var isInt = /^\+?\d+$/.test('the string');
Just read the rabbitmq tutorial. You publish message to exchange, not to queue; it is then routed to appropriate queues. In your case, you should bind separate queue for each consumer. That way, they can consume messages completely independently.
I'm not absolutely sure I got your question correctly, but it seems you want something like this:
Class c = null;
try {
c = Class.forName("com.path.to.ImplementationType");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
T interfaceType = null;
try {
interfaceType = (T) c.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Where T can be defined in method level or in class level, i.e. <T extends InterfaceType>
I observed this issue while using Eclipse. I needed to add encoding in my pom.xml file and it resolved. http://ctrlaltsolve.blogspot.in/2015/11/encoding-properties-in-maven.html
I've found the answer (by further examining the Sublime 2 config files structure):
I was to open
~/.config/sublime-text-2/Packages/Scala/Scala.tmLanguage
And edit it to add sbt
(the extension of files I want to be opened as Scala code files) to the array after the fileTypes
key:
<dict>
<key>bundleUUID</key>
<string>452017E8-0065-49EF-AB9D-7849B27D9367</string>
<key>fileTypes</key>
<array>
<string>scala</string>
<string>sbt</string>
<array>
...
PS: May there be a better way, something like a right place to put my customizations (insted of modifying packages themselves), I'd still like to know.
By following @Gabriel Lidenor answer, initializing app with context is not work in my case. What if you are trying to create firebase-app without google-service.json ? So before initializing any number of firebase app, first need to initialize as;
FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("APP_ID")
.setGcmSenderId("SENDER_ID").build();
FirebaseApp.initializeApp(context, options, "[DEFAULT]");
There may be 2 spaces after the text, please confirm. You can use LTRIM
and RTRIM
functions also right?
LTRIM(RTRIM(ProductAlternateKey))
Maybe the extra space isn't ordinary spaces (ASCII 32, soft space)? Maybe they are "hard space", ASCII 160?
ltrim(rtrim(replace(ProductAlternateKey, char(160), char(32))))
if you use the resource the Colors.xml
int[] colors = new int[] {
getResources().getColor(R.color.ColorVerificaLunes),
getResources().getColor(R.color.ColorVerificaMartes),
getResources().getColor(R.color.ColorVerificaMiercoles),
getResources().getColor(R.color.ColorVerificaJueves),
getResources().getColor(R.color.ColorVerificaViernes)
};
ColorStateList csl = new ColorStateList(new int[][]{new int[0]}, new int[]{colors[0]});
example.setBackgroundTintList(csl);
Take a look at the write.csv
or the write.table
functions. You just have to supply the file name the user selects to the file
parameter, and the dataframe to the x
parameter:
write.csv(x=df, file="myFileName")