Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
Didn't see any answers correctly using DATE_ADD
or DATE_SUB
:
Subtract 1 day from NOW()
...WHERE DATE_FIELD >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Add 1 day from NOW()
...WHERE DATE_FIELD >= DATE_ADD(NOW(), INTERVAL 1 DAY)
From the docs ...
A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.
It seems that in the debug log for Java 6
the request is send in SSLv2
format.
main, WRITE: SSLv2 client hello message, length = 110
This is not mentioned as enabled by default in Java 7.
Change the client to use SSLv3 and above to avoid such interoperability issues.
I've had a similar problem when building Clang from source (but not with sudo apt-get install
. This might depend on the version of Ubuntu which you're running).
It might be worth checking if clang++
can find the correct locations of your C++ libraries:
Compare the results of g++ -v <filename.cpp>
and clang++ -v <filename.cpp>
, under "#include < ... > search starts here:".
If nothing else seems to work, double-check the path in git config core.worktree
. If that path doesn't point to your working directory, you may need to update it.
The way I got this error was that I created a Git repository on a network drive. It worked fine on one computer but returned this error on another. It turned out that I had the drive mapped to a Windows drive letter on the computer where I created it, but not on the other computer, and Git saved the path to the work tree as the mapped path and not the UNC path.
The arrow module will steer you around and away from subtle mistakes, and it's easier to use that older products.
import arrow
def cleanWay(oneDate):
if currentDate.date().day > 25:
return currentDate.replace(months=+1,day=1)
else:
return currentDate.replace(day=1)
currentDate = arrow.get('25-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))
currentDate = arrow.get('28-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))
In this case there is no need for you to consider the varying lengths of months, for instance. Here's the output from this script.
25-Feb-2017 01-Feb-2017
28-Feb-2017 01-Mar-2017
You can always take a look at the .size
attribute. It is defined as an integer, and is zero (0
) when there are no elements in the array:
import numpy as np
a = np.array([])
if a.size == 0:
# Do something when `a` is empty
You could implement a JavaScript block which contains a function with your needs.
<div style="position: absolute; left: 10px; top: 40px;">
<img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>
Apple has provided an extension for the UIImage class called UIImage+ImageEffects.h. In this class you have the desired methods for blurring your view
I don't like my switch
statements to fall through - it's far too error prone and hard to read. The only exception is when multiple case
statements all do exactly the same thing.
If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.
See adeneo's answer, but don't forget encodeURIComponent
!
a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvString);
Also, I needed to do "\r\n" not just "\n" for the row delimiter.
var csvString = csvRows.join("\r\n");
Revised fiddle: http://jsfiddle.net/7Q3c6/
The simple example of using a property in an interface:
using System;
interface IName
{
string Name { get; set; }
}
class Employee : IName
{
public string Name { get; set; }
}
class Company : IName
{
private string _company { get; set; }
public string Name
{
get
{
return _company;
}
set
{
_company = value;
}
}
}
class Client
{
static void Main(string[] args)
{
IName e = new Employee();
e.Name = "Tim Bridges";
IName c = new Company();
c.Name = "Inforsoft";
Console.WriteLine("{0} from {1}.", e.Name, c.Name);
Console.ReadKey();
}
}
/*output:
Tim Bridges from Inforsoft.
*/
I will show you 2 ways to accomplish what you want:
First way: Decorate your field with JsonProperty attribute in order to skip the serialization of that field if it is null.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<Something> Somethings { get; set; }
}
Second way: If you are negotiation with some complex scenarios then you could use the Web Api convention ("ShouldSerialize") in order to skip serialization of that field depending of some specific logic.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public List<Something> Somethings { get; set; }
public bool ShouldSerializeSomethings() {
var resultOfSomeLogic = false;
return resultOfSomeLogic;
}
}
WebApi uses JSON.Net and it use reflection to serialization so when it has detected (for instance) the ShouldSerializeFieldX() method the field with name FieldX will not be serialized.
I see two options here
var link = $('a').attr('href');
var equalPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(equalPosition + 1); //Split the string and get the number.
I dont know if you're gonna use it for paging and have the text in the <a>
-tag as you have it, but if you should you can also do
var number = $('a').text();
Very simple way (Tested) :-
PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();
Add bellow line in build.gradle :-
compile 'com.commit451:PhotoView:1.2.4'
SELECT text
FROM all_source
where name = 'FGETALGOGROUPKEY'
order by line
alternatively:
select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY')
from dual;
namespace Software_Info_v1._0
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop;
public class MS_Office
{
public string GetOfficeVersion()
{
string sVersion = string.Empty;
Microsoft.Office.Interop.Word.Application appVersion = new Microsoft.Office.Interop.Word.Application();
appVersion.Visible = false;
switch (appVersion.Version.ToString())
{
case "7.0":
sVersion = "95";
break;
case "8.0":
sVersion = "97";
break;
case "9.0":
sVersion = "2000";
break;
case "10.0":
sVersion = "2002";
break;
case "11.0":
sVersion = "2003";
break;
case "12.0":
sVersion = "2007";
break;
case "14.0":
sVersion = "2010";
break;
default:
sVersion = "Too Old!";
break;
}
Console.WriteLine("MS office version: " + sVersion);
return null;
}
}
}
Well, if I understand you correctly. You can do something like the following.
To show it, I first create a data.frame
with your example
df <-
scan(what = character(), sep = ",", text =
"001, 34, 3, aa.com
002, 4, 4, aa.com
034, 3, 3, aa.com
001, 12, 4, bb.com
002, 1, 3, bb.com
034, 2, 2, cc.com")
df <- as.data.frame(matrix(df, 6, 4, byrow = TRUE))
colnames(df) <- c("user_id", "number_of_logins", "number_of_images", "web")
You can then run one of the following lines to add a column (at the end of the data.frame
) with the row number as the generated user id. The second lines simply adds leading zeros.
df$generated_uid <- 1:nrow(df)
df$generated_uid2 <- sprintf("%03d", 1:nrow(df))
If you absolutely want the generated user id to be the first column, you can add the column like so:
df <- cbind("generated_uid3" = sprintf("%03d", 1:nrow(df)), df)
or simply rearrage the columns.
php artisan dump-autoload
was deprecated on Laravel 5, so you need to use composer dump-autoload
Since JavaScript doesn't have function overload options object can be used instead. If there are one or two required arguments, it's better to keep them separate from the options object. Here is an example on how to use options object and populated values to default value in case if value was not passed in options object.
function optionsObjectTest(x, y, opts) {
opts = opts || {}; // default to an empty options object
var stringValue = opts.stringValue || "string default value";
var boolValue = !!opts.boolValue; // coerces value to boolean with a double negation pattern
var numericValue = opts.numericValue === undefined ? 123 : opts.numericValue;
return "{x:" + x + ", y:" + y + ", stringValue:'" + stringValue + "', boolValue:" + boolValue + ", numericValue:" + numericValue + "}";
}
here is an example on how to use options object
I use a library called ExcelDataReader, you can find it on NuGet. Be sure to install both ExcelDataReader and the ExcelDataReader.DataSet extension (the latter provides the required AsDataSet method referenced below).
I encapsulated everything in one function, you can copy it in your code directly. Give it a path to CSV file, it gets you a dataset with one table.
public static DataSet GetDataSet(string filepath)
{
var stream = File.OpenRead(filepath);
try
{
var reader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration()
{
LeaveOpen = false
});
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
// Gets or sets a value indicating whether to set the DataColumn.DataType
// property in a second pass.
UseColumnDataType = true,
// Gets or sets a callback to determine whether to include the current sheet
// in the DataSet. Called once per sheet before ConfigureDataTable.
FilterSheet = (tableReader, sheetIndex) => true,
// Gets or sets a callback to obtain configuration options for a DataTable.
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
// Gets or sets a value indicating the prefix of generated column names.
EmptyColumnNamePrefix = "Column",
// Gets or sets a value indicating whether to use a row from the
// data as column names.
UseHeaderRow = true,
// Gets or sets a callback to determine which row is the header row.
// Only called when UseHeaderRow = true.
ReadHeaderRow = (rowReader) =>
{
// F.ex skip the first row and use the 2nd row as column headers:
//rowReader.Read();
},
// Gets or sets a callback to determine whether to include the
// current row in the DataTable.
FilterRow = (rowReader) =>
{
return true;
},
// Gets or sets a callback to determine whether to include the specific
// column in the DataTable. Called once per column after reading the
// headers.
FilterColumn = (rowReader, columnIndex) =>
{
return true;
}
}
});
return result;
}
catch (Exception ex)
{
return null;
}
finally
{
stream.Close();
stream.Dispose();
}
}
not() is a function in xpath (as opposed to an operator), so
//a[not(contains(@id, 'xx'))]
from within the git bash shell type:
>cd /bin
>ls -l
You will then see a long listing of all the unix-like commands available. There are lots of goodies in there.
This is based on the other answers, but is exactly what I was after:
(Get-Command C:\Path\YourFile.Dll).FileVersionInfo.FileVersion
By default, the query log is disabled in Laravel 5: https://github.com/laravel/framework/commit/e0abfe5c49d225567cb4dfd56df9ef05cc297448
You will need to enable the query log by calling:
DB::enableQueryLog();
// and then you can get query log
dd(DB::getQueryLog());
or register an event listener:
DB::listen(
function ($sql, $bindings, $time) {
// $sql - select * from `ncv_users` where `ncv_users`.`id` = ? limit 1
// $bindings - [5]
// $time(in milliseconds) - 0.38
}
);
If you have more than one DB connection you must specify which connection to log
To enables query log for my_connection
:
DB::connection('my_connection')->enableQueryLog();
To get query log for my_connection
:
print_r(
DB::connection('my_connection')->getQueryLog()
);
class BeforeAnyDbQueryMiddleware
{
public function handle($request, Closure $next)
{
DB::enableQueryLog();
return $next($request);
}
public function terminate($request, $response)
{
// Store or dump the log data...
dd(
DB::getQueryLog()
);
}
}
A middleware's chain will not run for artisan commands, so for CLI execution you can enable query log in the artisan.start
event listener.
For example you can put it in the bootstrap/app.php
file
$app['events']->listen('artisan.start', function(){
\DB::enableQueryLog();
});
Laravel keeps all queries in memory. So in some cases, such as when inserting a large number of rows, or having a long running job with a lot of queries, this can cause the application to use excess memory.
In most cases you will need the query log only for debugging, and if that is the case I would recommend you enable it only for development.
if (App::environment('local')) {
// The environment is local
DB::enableQueryLog();
}
References
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
Use bind_rows()
from the dplyr package:
bind_rows(list_of_dataframes, .id = "column_label")
Going off the accepted answer, an alternative solution that doesn't require a custom hook:
const Component = ({ receiveAmount, sendAmount }) => {
const prevAmount = useRef({ receiveAmount, sendAmount }).current;
useEffect(() => {
if (prevAmount.receiveAmount !== receiveAmount) {
// process here
}
if (prevAmount.sendAmount !== sendAmount) {
// process here
}
return () => {
prevAmount.receiveAmount = receiveAmount;
prevAmount.sendAmount = sendAmount;
};
}, [receiveAmount, sendAmount]);
};
This assumes you actually need reference to the previous values for anything in the "process here" bits. Otherwise unless your conditionals are beyond a straight !==
comparison, the simplest solution here would just be:
const Component = ({ receiveAmount, sendAmount }) => {
useEffect(() => {
// process here
}, [receiveAmount]);
useEffect(() => {
// process here
}, [sendAmount]);
};
No need for custom middleware?! In express:
//you probably have something like this already
app.use("/public", express.static('public'));
Then put your favicon in public and add the following line in your html's head:
<link rel="icon" href="/public/favicon.ico">
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend
statement is called before the complete
statement i
will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
Your example:
{
"items":
[
{
"WR":"qwe",
"QU":"asd",
"QA":"end",
"WO":"hasd",
"NO":"qwer"
},
...
]
}
add an element "itemorder"
{
"items":
[
{
"WR":"qwe",
"QU":"asd",
"QA":"end",
"WO":"hasd",
"NO":"qwer"
},
...
],
"itemorder":["WR","QU","QA","WO","NO"]
}
This code generates the desired output without the column title line:
JSONObject output = new JSONObject(json);
JSONArray docs = output.getJSONArray("data");
JSONArray names = output.getJSONArray("itemOrder");
String csv = CDL.toString(names,docs);
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
Boolean is the object wrapper class for the primitive boolean. This class, as any class, can indeed be null. For performance and memory reasons it is always best to use the primitive.
The wrapper classes in the Java API serve two primary purposes:
The trick is to create subclasses of ViewHolder and then cast them.
public class GroupViewHolder extends RecyclerView.ViewHolder {
TextView mTitle;
TextView mContent;
public GroupViewHolder(View itemView) {
super (itemView);
// init views...
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
ImageView mImage;
public ImageViewHolder(View itemView) {
super (itemView);
// init views...
}
}
private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;
And then, at runtime do something like this:
@Override
public int getItemViewType(int position) {
// here your custom logic to choose the view type
return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
}
@Override
public void onBindViewHolder (ViewHolder viewHolder, int i) {
switch (viewHolder.getItemViewType()) {
case TYPE_IMAGE:
ImageViewHolder imageViewHolder = (ImageViewHolder) viewHolder;
imageViewHolder.mImage.setImageResource(...);
break;
case TYPE_GROUP:
GroupViewHolder groupViewHolder = (GroupViewHolder) viewHolder;
groupViewHolder.mContent.setText(...)
groupViewHolder.mTitle.setText(...);
break;
}
}
Hope it helps.
I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:
//store the element
var $cache = $('.my-sticky-element');
//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= vTop) {
// if so, ad the fixed class
$cache.addClass('stuck');
} else {
// otherwise remove it
$cache.removeClass('stuck');
}
});
.my-sticky-element.stuck {
position:fixed;
top:0;
box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}
You create an interface first, then define a method, which would act as a callback. In this example we would have two classes, one classA and another classB
Interface:
public interface OnCustomEventListener{
public void onEvent(); //method, which can have parameters
}
the listener itself in classB (we only set the listener in classB)
private OnCustomEventListener mListener; //listener field
//setting the listener
public void setCustomEventListener(OnCustomEventListener eventListener) {
this.mListener=eventListener;
}
in classA, how we start listening for whatever classB has to tell
classB.setCustomEventListener(new OnCustomEventListener(){
public void onEvent(){
//do whatever you want to do when the event is performed.
}
});
how do we trigger an event from classB (for example on button pressed)
if(this.mListener!=null){
this.mListener.onEvent();
}
P.S. Your custom listener may have as many parameters as you want
import java.util.*;
public class matrixcecil {
public static void main(String args[]){
List<Integer> k1=new ArrayList<Integer>(10);
k1.add(23);
k1.add(10);
k1.add(20);
k1.add(24);
int i=0;
while(k1.size()<10){
if(i==(k1.get(k1.size()-1))){
}
i=k1.get(k1.size()-1);
k1.add(30);
i++;
break;
}
System.out.println(k1);
}
}
I think this example will help you for better solution.
This will work completely fine. Simple short. If you want to count the number of files present in a folder.
ls | wc -l
This is not valid TypeScript code. You can not have method invocations in the body of a class.
// INVALID CODE
export class AppComponent {
public n: number = 1;
setTimeout(function() {
n = n + 10;
}, 1000);
}
Instead move the setTimeout
call to the constructor
of the class. Additionally, use the arrow function =>
to gain access to this
.
export class AppComponent {
public n: number = 1;
constructor() {
setTimeout(() => {
this.n = this.n + 10;
}, 1000);
}
}
In TypeScript, you can only refer to class properties or methods via this
. That's why the arrow function =>
is important.
Use ROW_NUMBER()
instead. ROWNUM
is a pseudocolumn and ROW_NUMBER()
is a function. You can read about difference between them and see the difference in output of below queries:
SELECT * FROM (SELECT rownum, deptno, ename
FROM scott.emp
ORDER BY deptno
)
WHERE rownum <= 3
/
ROWNUM DEPTNO ENAME
---------------------------
7 10 CLARK
14 10 MILLER
9 10 KING
SELECT * FROM
(
SELECT deptno, ename
, ROW_NUMBER() OVER (ORDER BY deptno) rno
FROM scott.emp
ORDER BY deptno
)
WHERE rno <= 3
/
DEPTNO ENAME RNO
-------------------------
10 CLARK 1
10 MILLER 2
10 KING 3
browser.waitForAngular();
btnLoginEl.click().then(function() { Do Something });
to solve the promise.
use the spread value...
box-shadow has the following values
box-shadow: x y blur spread color;
so you could use something like..
box-shadow: 0px -10px 10px -10px black;
UPDATE: i'm adding a jsfiddle
If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;
If the data is a local variable or a heap-allocated zone, clear it with memset
like:
memset(&m, 0, sizeof(myStruct));
Current compilers (e.g. recent versions of gcc
) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).
You could perhaps code myStruct m = {};
or myStruct m = {0};
(even if the first member of myStruct
is not a scalar).
My feeling is that using memset
for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).
Here is a solution I came up with for myself. This is ready to run as a command prompt project. You need to clean some stuff if not. Hope this helps. It accepts several input formats like: 1.234.567,89 1,234,567.89 etc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Linq;
namespace ConvertStringDecimal
{
class Program
{
static void Main(string[] args)
{
while(true)
{
// reads input number from keyboard
string input = Console.ReadLine();
double result = 0;
// remove empty spaces
input = input.Replace(" ", "");
// checks if the string is empty
if (string.IsNullOrEmpty(input) == false)
{
// check if input has , and . for thousands separator and decimal place
if (input.Contains(",") && input.Contains("."))
{
// find the decimal separator, might be , or .
int decimalpos = input.LastIndexOf(',') > input.LastIndexOf('.') ? input.LastIndexOf(',') : input.LastIndexOf('.');
// uses | as a temporary decimal separator
input = input.Substring(0, decimalpos) + "|" + input.Substring(decimalpos + 1);
// formats the output removing the , and . and replacing the temporary | with .
input = input.Replace(".", "").Replace(",", "").Replace("|", ".");
}
// replaces , with .
if (input.Contains(","))
{
input = input.Replace(',', '.');
}
// checks if the input number has thousands separator and no decimal places
if(input.Count(item => item == '.') > 1)
{
input = input.Replace(".", "");
}
// tries to convert input to double
if (double.TryParse(input, out result) == true)
{
result = Double.Parse(input, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture);
}
}
// outputs the result
Console.WriteLine(result.ToString());
Console.WriteLine("----------------");
}
}
}
}
The accepted answer still threw a Javascript error in IE for me (for Angular 1.2 at least). It is a bug but the workaround is to use ngAttr detailed on https://docs.angularjs.org/guide/interpolation
<input type="text" ng-model="inputText" ng-attr-placeholder="{{somePlaceholder}}" />
You can use INFORMATION_SCHEMA.TABLES
to retrieve information about your database tables.
As mentioned in the Microsoft Tables Documentation:
INFORMATION_SCHEMA.TABLES
returns one row for each table in the current database for which the current user has permissions.
The following query, therefore, will return the number of tables in the specified database:
USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
As of SQL Server 2008, you can also use sys.tables
to count the the number of tables.
From the Microsoft sys.tables Documentation:
sys.tables
returns a row for each user table in SQL Server.
The following query will also return the number of table in your database:
SELECT COUNT(*)
FROM sys.tables
input
element, of type file
<input id="fileInput" type="file" />
On your input
change use the FileReader
object and read your input
file property:
$('#fileInput').on('change', function () {
var fileReader = new FileReader();
fileReader.onload = function () {
var data = fileReader.result; // data <-- in this var you have the file data in Base64 format
};
fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});
FileReader will load your file and in fileReader.result
you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)
In simple words.
In Python you should add self
argument as the first argument to all defined methods in classes:
class MyClass:
def method(self, arg):
print(arg)
Then you can use your method according to your intuition:
>>> my_object = MyClass()
>>> my_object.method("foo")
foo
This should solve your problem :)
For a better understanding, you can also read the answers to this question: What is the purpose of self?
Go to the top of your View code and do it like this :
<?php
$this->load->model('MyModelName');
$MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>
<div class="row">
Your HTML CODE
</div>
You could decorate the property you wish controlling its name with the [JsonProperty]
attribute which allows you to specify a different name:
using Newtonsoft.Json;
// ...
[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }
Documentation: Serialization Attributes
The better solution is the one that is the most simple, and the one that does less modification in your code behaviour.
What if you can solve this problem only with 2 Properties on your TextView
?
Instead of needing to change your LinearLayout
Properties that maybe can alter the behaviour of LinearLayout
childs?
Using this way, you do not need to change LinearLayout
properties and behaviour, you only need to add the two following properties to your target TextView
:
android:gravity="right"
android:textAlignment="gravity"
What would be better to change only your target to solve your solution instead of having a chance to cause another problem in the future, modifying your target father? think about it :)
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
In this case, you might get some differences. Consider a line like:
"foo\tbar "
In this case, if you strip
, then you'll get {"foo":"bar"}
as the dictionary entry. If you don't strip, you'll get {"foo":"bar "}
(note the extra space at the end)
Note that if you use line.split()
instead of line.split('\t')
, you'll split on every whitespace character and the "strip
ing" will be done during splitting automatically. In other words:
line.strip().split()
is always identical to:
line.split()
but:
line.strip().split(delimiter)
Is not necessarily equivalent to:
line.split(delimiter)
From Dive Into Python:
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5
try this
bool focus = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (focus)
{
textBox1.BorderStyle = BorderStyle.None;
Pen p = new Pen(Color.Red);
Graphics g = e.Graphics;
int variance = 3;
g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height +variance ));
}
else
{
textBox1.BorderStyle = BorderStyle.FixedSingle;
}
}
private void textBox1_Enter(object sender, EventArgs e)
{
focus = true;
this.Refresh();
}
private void textBox1_Leave(object sender, EventArgs e)
{
focus = false;
this.Refresh();
}
Check out DBGhost http://www.innovartis.co.uk/. I have used in an automated fashion for 2 years now and it works great. It allows our DB builds to happen much like a Java or C build happens, except for the database. You know what I mean.
Check if the project having HRESULT: 0x80131040 error is being used/referenced by any project. If yes, kindly check if these project have similar .dll being referenced and the version is the same. If they're are not of same version number, then it is causing the said error.
If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.
$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!
if (file_exists($vid)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $vid); // check mime type
finfo_close($finfo);
if (preg_match('/video\/*/', $mime_type)) {
$video_attributes = _get_video_attributes($vid, $ffmpeg_path);
print_r('Codec: ' . $video_attributes['codec'] . '<br/>');
print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');
print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
. $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');
print_r('Size: ' . _human_filesize(filesize($vid)));
} else {
print_r('File is not a video.');
}
} else {
print_r('File does not exist.');
}
function _get_video_attributes($video, $ffmpeg) {
$command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
$output = shell_exec($command);
$regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
if (preg_match($regex_sizes, $output, $regs)) {
$codec = $regs [1] ? $regs [1] : null;
$width = $regs [3] ? $regs [3] : null;
$height = $regs [4] ? $regs [4] : null;
}
$regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
if (preg_match($regex_duration, $output, $regs)) {
$hours = $regs [1] ? $regs [1] : null;
$mins = $regs [2] ? $regs [2] : null;
$secs = $regs [3] ? $regs [3] : null;
$ms = $regs [4] ? $regs [4] : null;
}
return array('codec' => $codec,
'width' => $width,
'height' => $height,
'hours' => $hours,
'mins' => $mins,
'secs' => $secs,
'ms' => $ms
);
}
function _human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
For those of you interested in PySpark version (actually it's same in Scala - see comment below) :
merchants_df_renamed = merchants_df.toDF(
'merchant_id', 'category', 'subcategory', 'merchant')
merchants_df_renamed.printSchema()
Result:
root
|-- merchant_id: integer (nullable = true)
|-- category: string (nullable = true)
|-- subcategory: string (nullable = true)
|-- merchant: string (nullable = true)
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
This is actually a multi-step process. First you'll need to add all your files to the current stage:
git add .
You can verify that your files will be added when you commit by checking the status of the current stage:
git status
The console should display a message that lists all of the files that are currently staged, like this:
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: README
# new file: src/somefile.js
#
If it all looks good then you're ready to commit. Note that the commit action only commits to your local repository.
git commit -m "some message goes here"
If you haven't connected your local repository to a remote one yet, you'll have to do that now. Assuming your remote repository is hosted on GitHub and named "Some-Awesome-Project", your command is going to look something like this:
git remote add origin [email protected]:username/Some-Awesome-Project
It's a bit confusing, but by convention we refer to the remote repository as 'origin' and the initial local repository as 'master'. When you're ready to push your commits to the remote repository (origin), you'll need to use the 'push' command:
git push origin master
For more information check out the tutorial on GitHub: http://learn.github.com/p/intro.html
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
For anyone using Api Gateway's HTTP API and the proxy route ANY /{proxy+}
You will need to explicitly define your route methods in order for CORS to work.
Wish this was more explicit in the AWS Docs for Configuring CORS for an HTTP API
Was on a 2 hour call with AWS Support and they looped in one of their senior HTTP API developers, who made this recommendation.
Hopefully this post can save some time and effort for those who are working with Api Gateway HTTP API.
If you have access to server's JMX interface, the start & end offsets are present at:
kafka.log:type=Log,name=LogStartOffset,topic=TOPICNAME,partition=PARTITIONNUMBER
kafka.log:type=Log,name=LogEndOffset,topic=TOPICNAME,partition=PARTITIONNUMBER
(you need to replace TOPICNAME
& PARTITIONNUMBER
).
Bear in mind you need to check for each of the replicas of given partition, or you need to find out which one of the brokers is the leader for a given partition (and this can change over time).
Alternatively, you can use Kafka Consumer methods beginningOffsets
and endOffsets
.
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .Destructive, title: "Delete") { (action, indexPath) in
// delete item at indexPath
}
let share = UITableViewRowAction(style: .Normal, title: "Disable") { (action, indexPath) in
// share item at indexPath
}
share.backgroundColor = UIColor.blueColor()
return [delete, share]
}
The above code shows how to create to custom buttons when your swipe on the row.
Beginning with AngularJS 1.1.4 you can use $watchCollection
:
$scope.$watchCollection('[item1, item2]', function(newValues, oldValues){
// do stuff here
// newValues and oldValues contain the new and respectively old value
// of the observed collection array
});
Plunker example here
Documentation here
Just a little tip:
I prefer to use the variant RLIKE (exactly the same command as REGEXP) as it sounds more like natural language, and is shorter; well, just 1 char.
The "R" prefix is for Reg. Exp., of course.
I would grab date.js or else you will need to roll your own formatting function.
Add
import {withRouter} from 'react-router-dom';
Then change your component export
export default withRouter(ComponentName)
Then you can access the route directly within the component itself (without touching anything else in your project) using:
window.location.pathname
Tested March 2020 with: "version": "5.1.2"
For SQL query generating scripts, or anything that does a different action for the first or last elements, it is much faster (almost twice as fast) to avoid using unneccessary variable checks.
The current accepted solution uses a loop and a check within the loop that will be made every_single_iteration, the correct (fast) way to do this is the following :
$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
$some_item=$arr[$i];
$i++;
}
$last_item=$arr[$i];
$i++;
A little homemade benchmark showed the following:
test1: 100000 runs of model morg
time: 1869.3430423737 milliseconds
test2: 100000 runs of model if last
time: 3235.6359958649 milliseconds
And it's thus quite clear that the check costs a lot, and of course it gets even worse the more variable checks you add ;)
While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.
The identity table:
CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED
(
[intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
and the insert trigger:
-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS
BEGIN
DECLARE @intTrackerMessageId INT
DECLARE @intRowCount INT
SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)
SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1
INSERT INTO tblsysTrackerMessages(
[intTrackerMessageId],
[intTrackerId],
[strMessage],
[intTrackerMessageTypeId],
[datCreated],
[strCreatedBy])
SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId],
[intTrackerId],
[strMessage],
[intTrackerMessageTypeId],
[datCreated],
[strCreatedBy] FROM INSERTED;
SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END
Option 1a: While loop: Single line at a time: Input redirection
#!/bin/bash
filename='peptides.txt'
echo Start
while read p; do
echo $p
done < $filename
Option 1b: While loop: Single line at a time:
Open the file, read from a file descriptor (in this case file descriptor #4).
#!/bin/bash
filename='peptides.txt'
exec 4<$filename
echo Start
while read -u4 p ; do
echo $p
done
Using dblink would be more convenient!
truncate table tableA;
insert into tableA
select *
from dblink('hostaddr=xxx.xxx.xxx.xxx dbname=mydb user=postgres',
'select a,b from tableA')
as t1(a text,b text);
If you are getting "Not a working copy" error message then try selecting a directory from TortoiseMerge dialog box which is a working directory of SVN.
I happened to run into this problem because of an Ant build.
That Ant build took files and applied filterchain expandproperties
to it. During this file filtering, my Windows machine's implicit default non-UTF-8 character encoding was used to generate the filtered files - therefore characters outside of its character set could not be mapped correctly.
One solution was to provide Ant with an explicit environment variable for UTF-8.
In Cygwin, before launching Ant: export ANT_OPTS="-Dfile.encoding=UTF-8"
.
String str = "to";
str.replace("to", "xyz");
Just try it :)
you can try this "KeyValuePair"
private KeyValuePair<int, int> GetNumbers()
{
return new KeyValuePair<int, int>(1, 2);
}
var numbers = GetNumbers();
Console.WriteLine("Output : {0}, {1}",numbers.Key, numbers.Value);
Output :
Output : 1, 2
Wrap your ScrollView
around your a plainLinearLayout
with layout_height="max_height", this will do a perfect job. In fact, I have this code in production from last 5 years with zero issues.
<LinearLayout
android:id="@+id/subsParent"
android:layout_width="match_parent"
android:layout_height="150dp"
android:gravity="bottom|center_horizontal"
android:orientation="vertical">
<ScrollView
android:id="@+id/subsScroll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginEnd="15dp"
android:layout_marginStart="15dp">
<TextView
android:id="@+id/subsTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/longText"
android:visibility="visible" />
</ScrollView>
</LinearLayout>
Something I did recently, hope it helps. I have a list of dictionaries and wanted to add a value to some existing documents.
for item in my_list:
my_collection.update({"_id" : item[key] }, {"$set" : {"New_col_name" :item[value]}})
This worked for me - just changed INSERT to UPDATE for my table.
INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))
Access-Engine does not support
SELECT count(DISTINCT....) FROM ...
You have to do it like this:
SELECT count(*)
FROM
(SELECT DISTINCT Name FROM table1)
Its a little workaround... you're counting a DISTINCT selection.
I'm using Rails 4.2, and could not get the footable icons to show up. Little boxes were showing, instead of the (+) on collapsed rows and the little sorting arrows I expected. After studying the information here, I made one simple change to my code: remove the font directory in css. That is, change all the css entries like this:
src:url('fonts/footable.eot');
to look like this:
src:url('footable.eot');
It worked. I think Rails 4.2 already assumes the font directory, so specifying it again in the css code makes the font files not get found. Hope this helps.
Take a look on life cycle of Activity
Where
***onCreate()***
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
***onStart()***
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
And you can write your simple class to take a look when these methods call
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private final static String TAG = "TestActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "On Create .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
}
Hope this will clear your confusion.
And take a look here for details.
Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.
AFAIK, you can't do it with CSS alone. CSS has content
rule but even that can be used to insert content before or after an element using pseudo selectors. You need to resort to javascript for that OR use placeholder
attribute if you are using HTML5 as pointed out by @Blender.
In My Case
I have deleted
android -> .idea Folder
android -> appname.iml file
android -> app -> app.iml file
Open project in Android Studio and no need to File -> Invalidate Caches/Restart
You can do Invalidate Caches / Restart for your case.
yes, we can declare an abstract class without any abstract method. the purpose of declaring a class as abstract is not to instantiate the class.
so two cases
1) abstract class with abstract methods.
these type of classes, we must inherit a class from this abstract class and must override the abstract methods in our class, ex: GenricServlet class
2) abstract class without abstract methods.
these type of classes, we must inherit a class from this abstract class, ex: HttpServlet class purpose of doing is although you if you don't implement your logic in child class you can get the parent logic
Easiest way to find address path in Excel 2010:
File - info - properties (on right) - (drop-down menu) - advanced properties - general tab
You will get to the same properties box that was so simple to find in Excel 2003.
There is actually special command for this job
npm ci
It will delete node_modules
directory and will install packages with respect your package-lock.json
file
More info: https://docs.npmjs.com/cli/ci.html
You need to delete your old db folder and recreate new one. It will resolve your issue.
You just need to find out where is your PHP folder.
cd \xampp\php (FOR XAMPP)
cd \wamp\php (FOR WAMP)
php -v
PHP 5.6.11 (cli) (built: Jul 9 2015 20:55:40) Copyright (c) 1997-2015 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
FileOutputStream fos = openFileOutput("/*file name like --> one.txt*/", MODE_PRIVATE);
FileWriter fw = new FileWriter(fos.getFD());
fw.write("");
Here is the version to extract the specific columns by name (modified from @coreyward):
$row = 0;
$headers = [];
$filepath = "input.csv";
if (($handle = fopen($filepath, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if (++$row == 1) {
$headers = array_flip($data); // Get the column names from the header.
continue;
} else {
$col1 = $data[$headers['Col1Name']]; // Read row by the column name.
$col2 = $data[$headers['Col2Name']];
print "Row $row: $col1, $col2\n";
}
}
fclose($handle);
}
The accepted answer will not return files prefix with a . To do that use
for entry in "$search_dir"/* "$search_dir"/.[!.]* "$search_dir"/..?*
do
echo "$entry"
done
select count(*),sum(decode(status, 'ACTIVE',1,0)) from v$session where type= 'USER'
Simplest way to replace (all files, directory, recursive)
find . -type f -not -path '*/\.*' -exec sed -i 's/foo/bar/g' {} +
Note: Sometimes you might need to ignore some hidden files i.e. .git
, you can use above command.
If you want to include hidden files use,
find . -type f -exec sed -i 's/foo/bar/g' {} +
In both case the string foo
will be replaced with new string bar
Translation of the accepted answer by Chris into Kotlin:
val checkBox: CheckBox = findViewById(R.id.chk)
checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
// Code here
}
Minor change in iTunes Connect,
Try something like the following in your script:
set_time_limit(1200);
Really not understanding why there are lots of wrong answers and even the accepted is not quite accurate making things hard to understand. The truth is always simple and clean.
As @Schneider commented in @Mark Harrison's answer, please just read Martin Fowler's post discussing IoC.
https://martinfowler.com/bliki/InversionOfControl.html
One of the most I love is:
This phenomenon is Inversion of Control (also known as the Hollywood Principle - "Don't call us, we'll call you").
Why?
Wiki for IoC, I might quote a snippet.
Inversion of control is used to increase modularity of the program and make it extensible ... then further popularized in 2004 by Robert C. Martin and Martin Fowler.
Robert C. Martin: the author of <<Clean Code: A Handbook of Agile Software Craftsmanship>>
.
Martin Fowler: the author of <<Refactoring: Improving the Design of Existing Code>>
.
I had the same issue and none of the other answers worked. It seems to occur frequently when you connect to the device using the wifi mode (running command 'adb tcpip 5555'). I found this solution, its sort of a workaround but it does work.
This process is a little lengthy but its the only one that has worked everytime for me.
I am from .net background. However, java/c# are more/less same.
If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.
It will be null
, when you don't new
it up.
e.g.
int[] numbers = null; // changed as per @Joachim's suggestion.
if (numbers == null)
{
System.out.println("yes, it is null. Please new it up");
}
I'd recommend using toString().
Ex. alert(array.toString())
, or console.log(array.toString())
In my case, the issue was that I had another element in the center of the div with a conflicting z-index.
.wrapper {_x000D_
color: white;_x000D_
width: 320px;_x000D_
position: relative;_x000D_
border: 1px dashed gray;_x000D_
height: 40px_x000D_
}_x000D_
_x000D_
.parent {_x000D_
position: absolute;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
top: 20px;_x000D_
left: 0;_x000D_
right: 0;_x000D_
/* This z-index override is needed to display on top of the other_x000D_
div. Or, just swap the order of the HTML tags. */_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.child {_x000D_
background: green;_x000D_
}_x000D_
_x000D_
.conflicting {_x000D_
position: absolute;_x000D_
left: 120px;_x000D_
height: 40px;_x000D_
background: red;_x000D_
margin: 0 auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
Centered_x000D_
</div>_x000D_
</div>_x000D_
<div class="conflicting">_x000D_
Conflicting_x000D_
</div>_x000D_
</div>
_x000D_
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
The API only works during user interaction, so it cannot be used maliciously. Try the following code:
addEventListener("click", function() {
var el = document.documentElement,
rfs = el.requestFullscreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen
|| el.msRequestFullscreen
;
rfs.call(el);
});
I tried the option: Tools > Preferences > Syntax coloring > dark spyder is not working.
You should rather use the path: Tools > Preferences > Syntax coloring > spyder then begin modifications as you want your editor to appear
I think you need to push a revert commit. So pull
from github again, including the commit you want to revert, then use git revert
and push the result.
If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset
: git push origin :master
.
For red lines an points
plt.plot(dates, values, '.r-')
or for x markers and blue lines
plt.plot(dates, values, 'xb-')
I have resolved this one by creating the POJO class (Student.class) of the JSON and Main Class is used for read the values from the JSON in the problem.
**Main Class**
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException {
String jsonStr = "[ \r\n" + " {\r\n" + " \"firstName\" : \"abc\",\r\n"
+ " \"lastName\" : \"xyz\"\r\n" + " }, \r\n" + " {\r\n"
+ " \"firstName\" : \"pqr\",\r\n" + " \"lastName\" : \"str\"\r\n" + " } \r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
List<Student> details = mapper.readValue(jsonStr, new
TypeReference<List<Student>>() { });
for (Student itr : details) {
System.out.println("Value for getFirstName is: " +
itr.getFirstName());
System.out.println("Value for getLastName is: " +
itr.getLastName());
}
}
**RESULT:**
Value for getFirstName is: abc
Value for getLastName is: xyz
Value for getFirstName is: pqr
Value for getLastName is: str
**Student.class:**
public class Student {
private String lastName;
private String firstName;
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
} }
Consider the below figure and program to understand this concept better.
As per the figure, ptr1 is a single pointer which is having address of variable num.
ptr1 = #
Similarly ptr2 is a pointer to pointer(double pointer) which is having the address of pointer ptr1.
ptr2 = &ptr1;
A pointer which points to another pointer is known as double pointer. In this example ptr2 is a double pointer.
Values from above diagram :
Address of variable num has : 1000
Address of Pointer ptr1 is: 2000
Address of Pointer ptr2 is: 3000
Example:
#include <stdio.h>
int main ()
{
int num = 10;
int *ptr1;
int **ptr2;
// Take the address of var
ptr1 = #
// Take the address of ptr1 using address of operator &
ptr2 = &ptr1;
// Print the value
printf("Value of num = %d\n", num );
printf("Value available at *ptr1 = %d\n", *ptr1 );
printf("Value available at **ptr2 = %d\n", **ptr2);
}
Output:
Value of num = 10
Value available at *ptr1 = 10
Value available at **ptr2 = 10
I had this error and was explicitly setting the blocksize: aesManaged.BlockSize = 128;
Once I removed that, it worked.
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts
) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf
files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.
In my case google-play-services_lib are integrate as module (External Libs) for Google map & GCM in my project.
Now, these time require to implement Google Places Autocomplete API but problem is that's code are new and my libs are old so some class not found:
following these steps...
1> Update Google play service into SDK Manager
2> select new .jar file of google play service (Sdk/extras/google/google_play_services/libproject/google-play-services_lib/libs) replace with old one
i got success...!!!
Below code is perfectly workd for me:
$(document).ready(function(){_x000D_
$('input[type="radio"]').click(function(){_x000D_
var inputValue = $(this).attr("value");_x000D_
var targetBox = $("." + inputValue);_x000D_
$(".box").not(targetBox).hide();_x000D_
$(targetBox).show();_x000D_
});_x000D_
});
_x000D_
.box{_x000D_
color: #fff;_x000D_
padding: 20px;_x000D_
display: none;_x000D_
margin-top: 20px;_x000D_
}_x000D_
.red{ background: #ff0000; }_x000D_
.green{ background: #228B22; }_x000D_
.blue{ background: #0000ff; }_x000D_
label{ margin-right: 15px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<label><input type="radio" name="colorRadio" value="red"> red</label>_x000D_
<label><input type="radio" name="colorRadio" value="green"> green</label>_x000D_
<label><input type="radio" name="colorRadio" value="blue"> blue</label>_x000D_
</div>_x000D_
<div class="red box">You have selected <strong>red radio button</strong> so i am here</div>_x000D_
<div class="green box">You have selected <strong>green radio button</strong> so i am here</div>_x000D_
<div class="blue box">You have selected <strong>blue radio button</strong> so i am here</div>
_x000D_
You will to have to set header content type in your php like this:
<?php
header('Content-type:application/json');
?>
Watch these Video for better understanding....
Reference: http://www.youtube.com/watch?v=EvFXWqEqh6o
Swift 3, with extension:
extension UIView{
var globalPoint :CGPoint? {
return self.superview?.convert(self.frame.origin, to: nil)
}
var globalFrame :CGRect? {
return self.superview?.convert(self.frame, to: nil)
}
}
As noted in the answer provided by Tim Cooper, java.awt.Desktop
has provided this capability since Java version 6 (1.6), but with the following caveat:
For platforms which do not support or provide java.awt.Desktop
, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.
Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:
This code is Copyright 1999-2001 by Eric Albert ([email protected]) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.
Credits: Steven Spencer, JavaWorld magazine (Java Tip 66) Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.
The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?
link_to
can also produce links with anchors or query strings:
link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>
link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
You don't see any compression happening for your String, As you atleast require couple of hundred bytes to have real compression using GZIPOutputStream or ZIPOutputStream. Your String is too small.(I don't understand why you require compression for same)
Check Conclusion from this article:
The article also shows how to compress and decompress data on the fly in order to reduce network traffic and improve the performance of your client/server applications. Compressing data on the fly, however, improves the performance of client/server applications only when the objects being compressed are more than a couple of hundred bytes. You would not be able to observe improvement in performance if the objects being compressed and transferred are simple String objects, for example.
MaxMind GeoIP is a good service. They also have a free city-level lookup service.
I created this Function after researching on the internet since I wanted to print an XML string when you select a row from a data grid view.
static void HighlightPhrase(RichTextBox box, string StartTag, string EndTag, string ControlTag, Color color1, Color color2)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ; )
{
int jx = s.IndexOf(StartTag, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
int ex = s.IndexOf(EndTag, ix, StringComparison.CurrentCultureIgnoreCase);
box.SelectionStart = jx;
box.SelectionLength = ex - jx + 1;
box.SelectionColor = color1;
int bx = s.IndexOf(ControlTag, ix, StringComparison.CurrentCultureIgnoreCase);
int bxtest = s.IndexOf(StartTag, (ex + 1), StringComparison.CurrentCultureIgnoreCase);
if (bx == bxtest)
{
box.SelectionStart = ex + 1;
box.SelectionLength = bx - ex + 1;
box.SelectionColor = color2;
}
ix = ex + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
and this is how you call it
HighlightPhrase(richTextBox1, "<", ">","</", Color.Red, Color.Black);
Addition to what @KennyTM said:
-ms
-moz
-webkit
1) On February 12 2013 Opera (version 15+) announces they moving away from their own engine Presto to WebKit named Blink.
2) On April 3 2013 Google (Chrome version 28+) announces they are going to use the WebKit-based Blink engine.
3) On December 6 2018 Microsoft (Microsoft Edge 79+ stable) announces they are going to use the WebKit-based Blink engine.
select * from sales where salesDate between '11/11/2010' and '12/11/2010' --if using dd/mm/yyyy
The more correct way to do it:
DECLARE @myDate datetime
SET @myDate = '11/11/2010'
select * from sales where salesDate>=@myDate and salesDate<dateadd(dd,1,@myDate)
If only the date is specified, it means total midnight. If you want to make sure intervals don't overlap, switch the between with a pair of >=
and <
you can do it within one single statement, but it's just that the value is used twice.
Opera will soon start having builds available with gradient support, as well as other CSS features.
The W3C CSS Working Group is not even finished with CSS 2.1, y'all know that, right? We intend to be finished very soon. CSS3 is modularized precisely so we can move modules through to implementation faster rather than an entire spec.
Every browser company uses a different software cycle methodology, testing, and so on. So the process takes time.
I'm sure many, many readers well know that if you're using anything in CSS3, you're doing what's called "progressive enhancement" - the browsers with the most support get the best experience. The other part of that is "graceful degradation" meaning the experience will be agreeable but perhaps not the best or most attractive until that browser has implemented the module, or parts of the module that are relevant to what you want to do.
This creates quite an odd situation that unfortunately front-end devs get extremely frustrated by: inconsistent timing on implementations. So it's a real challenge on either side - do you blame the browser companies, the W3C, or worse yet - yourself (goodness knows we can't know it all!) Do those of us who are working for a browser company and W3C group members blame ourselves? You?
Of course not. It's always a game of balance, and as of yet, we've not as an industry figured out where that point of balance really is. That's the joy of working in evolutionary technology :)
This is solved in my case.
JS
$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
options.async = true;
});
This answer was inserted in this link
https://stackoverflow.com/questions/28322636/synchronous-xmlhttprequest-warning-and-script
You can go with inserting data push, this is going to be doing in order
var arr = Array();
function arrAdd(value){
arr.push(value);
}
Run this command to change .cert
file to .p12
:
openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt
Where server.key
is the server key and server.cert
is a CA issue cert or a self sign cert file.
A quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("color","yellow");
That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:
var DOMeles = $eles.get();
see http://api.jquery.com/attribute-starts-with-selector/
In pure DOM, you could use getElementsByTagName
to grab all input elements, and loop through the resulting array. Elements with name
starting with 'q1_' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('q1_') == 0) {
eles.push(inputs[i]);
}
}
It's caused by the table-responsive
class giving the table a property of display:block
, which is strange because this overwrites the table
classes original display:table
and is why the table shrinks when you add table-responsive
.
Most likely its down to bootstrap 4 still being in dev. You are safe to overwrite this property with your own class that sets display:table
and it won't effect the responsiveness of the table.
e.g.
.table-responsive-fix{
display:table;
}
You can use .find()
:
map<string,string>::iterator i = m.find("f");
if (i == m.end()) { /* Not found */ }
else { /* Found, i->first is f, i->second is ++-- */ }
function Update(key, value)
{
for (var i = 0; i < array.length; i++) {
if (array[i].Key == key) {
array[i].Value = value;
break;
}
}
}
Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).
ParentNode.insertBefore(<your element>, ParentNode.firstChild);
Actually both do look somewhat similar but are quite different it depends on your usage or intention what you want to achieve ,
.html()
to operate on containers having html elements..text()
to modify text of elements usually having separate open and
closing tags.text()
method cannot be used on form inputs or scripts.
.val()
for input or textarea elements..html()
for value of a script element.Picking up html content from .text()
will convert the html tags into html entities.
.text()
can be used in both XML and HTML documents..html()
is only for html documents.Check this example on jsfiddle to see the differences in action
this method also encounter a deprecate warning:
org.junit.Assert.assertEquals(float expected,float actual) //deprecated
It is because currently junit prefer a third parameter rather than just two float variables input.
The third parameter is delta:
public static void assertEquals(double expected,double actual,double delta) //replacement
this is mostly used to deal with inaccurate Floating point calculations
for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values
The problem was that I needed to have both minGW and MSYS installed and added to PATH.
The problem is now fixed.
The selected answer is absolutely correct, however it did not leave me with the latest commit/pushes ...
So for me:
git reset --hard dev/jobmanager-tools
git pull ( did not work as git was not sure what branch i wanted)
Since I know I want to temporarily set my upstream branch for a few weeks to a specific branch ( same as the one i switched to / checked out earlier and did a hard reset on )
So AFTER reset
git branch --set-upstream-to=origin/dev/jobmanager-tools
git pull
git status ( says--> on branch dev/jobmanager-tools
if you are using google chrome you can fix the problem via , trying any one of the steps mentioned on this page but you need to clear your whole browsing history .... clear all the data that chrome saved onto your computer by pressing ctrl+h and the clearing all the browsing data select all the fields now restart php my admin and all will work
Check out startOfDay([offset]). That gets what you are looking for without the pesky time constraints and its built in as of 4.3.x. It also has variants like endOfDay, startOfWeek, startOfMonth, etc.
The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max
key (as opposed to the dict
key) you can easily extract the highest value and its associated key.
mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)
An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.
Add the jar files to your library(if using netbeans) and modify your manifest's file classpath
as follows:
Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar
a similar answer exists here
I had the same problem in Aptana, all of a sudden my projects were gone. Solved it by going to the drop-down menu in Project Explorer and going Top Level Elements -> Projects.
.navbar-default .navbar-nav > li > a{_x000D_
color: #e9b846;_x000D_
}_x000D_
.navbar-default .navbar-nav > li > a:hover{_x000D_
background-color: #e9b846;_x000D_
color: #FFFFFF;_x000D_
}
_x000D_
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
use SimpleDateFormat
to first parse()
String
to Date
and then format()
Date
to String
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
return Browser.msgBox("something");
}
}
This way you not only exit the function, but show a message saying why it stopped. Hope it helps.
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
You can use the strip()
function to remove trailing (and leading) whitespace; passing it an argument will let you specify which whitespace:
for i in range(len(lists)):
grades.append(lists[i].strip('\n'))
It looks like you can just simplify the whole block though, since if your file stores one ID per line grades
is just lists
with newlines stripped:
lists = files.readlines()
grades = []
for i in range(len(lists)):
grades.append(lists[i].split(","))
grades = [x.strip() for x in files.readlines()]
(the above is a list comprehension)
Finally, you can loop over a list directly, instead of using an index:
for i in range(len(grades)):
# do something with grades[i]
for thisGrade in grades:
# do something with thisGrade
First you check your table id (aka object_id)
SELECT * FROM sys.objects WHERE type = 'U' ORDER BY name
then you can get the column's names. For example assuming you obtained from previous query the number 4 as object_id
SELECT c.name
FROM sys.index_columns ic
INNER JOIN sys.columns c ON c.column_id = ic.column_id
WHERE ic.object_id = 4
AND c.object_id = 4
I was facing the same problem and i solved this issue by changing the fireabseStorage version the same as the Firebase database version
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-storage:17.0.0'
to
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'
Alternatively
with Pool() as pool:
pool.map(fits.open, [name + '.fits' for name in datainput])
Dont write with stability stable
in the command ,
in your composer.json file, put
"minimum-stability": "stable"
before the closing curly bracket.
AssertJ 3.9.1 supports direct predicate usage in anyMatch
method.
assertThat(collection).anyMatch(element -> element.someProperty.satisfiesSomeCondition())
This is generally suitable use case for arbitrarily complex condition.
For simple conditions I prefer using extracting
method (see above) because resulting iterable-under-test might support value verification with better readability.
Example: it can provide specialized API such as contains
method in Frank Neblung's answer. Or you can call anyMatch
on it later anyway and use method reference such as "searchedvalue"::equals
. Also multiple extractors can be put into extracting
method, result subsequently verified using tuple()
.
You may need to restart your adb via Android Studio (do it twice for good measure).
For me, it helped to count the number of values per group. Copy the count table into a new object. Then filter for the max of the group based on the first grouping characteristic. For example:
count_table <- df %>%
group_by(A, B) %>%
count() %>%
arrange(A, desc(n))
count_table %>%
group_by(A) %>%
filter(n == max(n))
or
count_table %>%
group_by(A) %>%
top_n(1, n)
William Jockusch's answer solve this problem with easy trick.
-(void) viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
// back button was pressed. We know this is true because self is no longer
// in the navigation stack.
}
[super viewWillDisappear:animated];
}
Quote, which summarizes from this article:
- SET is the ANSI standard for variable assignment, SELECT is not.
- SET can only assign one variable at a time, SELECT can make multiple assignments at once.
- If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
- When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
- As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
You can use just:
Declare @pass2 binary(32)
Set @pass2 =0x4D006A00450034004E0071006B00350000000000000000000000000000000000
SELECT CONVERT(NVARCHAR(16), @pass2)
then after encoding you'll receive text 'MjE4Nqk5'
The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time
resize()
not only allocates memory, it also creates as many instances as the desired size which you pass to resize()
as argument. But reserve()
only allocates memory, it doesn't create instances. That is,
std::vector<int> v1;
v1.resize(1000); //allocation + instance creation
cout <<(v1.size() == 1000)<< endl; //prints 1
cout <<(v1.capacity()==1000)<< endl; //prints 1
std::vector<int> v2;
v2.reserve(1000); //only allocation
cout <<(v2.size() == 1000)<< endl; //prints 0
cout <<(v2.capacity()==1000)<< endl; //prints 1
Output (online demo):
1
1
0
1
So resize()
may not be desirable, if you don't want the default-created objects. It will be slow as well. Besides, if you push_back()
new elements to it, the size()
of the vector will further increase by allocating new memory (which also means moving the existing elements to the newly allocated memory space). If you have used reserve()
at the start to ensure there is already enough allocated memory, the size()
of the vector will increase when you push_back()
to it, but it will not allocate new memory again until it runs out of the space you reserved for it.
Name2 is a field. WPF binds only to properties. Change it to:
public string Name2 { get; set; }
Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:
partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _name2;
public string Name2
{
get { return _name2; }
set
{
if (value != _name2)
{
_name2 = value;
OnPropertyChanged("Name2");
}
}
}
}
You should consider moving this to a separate data object rather than on your Window class.
I had this issue but my problem was that I by mistake added a space before the name of the input like so:
<input type="text" name=" evening_time_phone">
When it shpuld be like this:
<input type="text" name="evening_time_phone">
A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:
var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));
Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:
var $a = $('#demoTable td'); var inner = ''; $a.children.html().each(function() { inner = inner + this.outerHTML; }); $a.html('New text' + inner);
I created a working demo of a landscape/portrait layout but the zoom must be disabled for it to work without JavaScript:
http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes
The following methods can be used to solve your problem:
CSS alpha transparency method (doesn't work in Internet Explorer 8):
#div{background-color:rgba(255,0,0,0.5);}
Use a transparent PNG image according to your choice as background.
Use the following CSS code snippet to create a cross-browser alpha-transparent background. Here is an example with #000000
@ 0.4% opacity
.div {
background:rgb(0,0,0);
background: transparent\9;
background:rgba(0,0,0,0.4);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#66000000,endColorstr=#66000000);
zoom: 1;
}
.div:nth-child(n) {
filter: none;
}
For more details regarding this technique, see this, which has an online CSS generator.
There's no isNumeric()
type of function, but you could add your own:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
NOTE: Since parseInt()
is not a proper way to check for numeric it should NOT be used.
In Windows the macros are saved at %AppData%\Notepad++\shortcuts.xml
(Windows logo key + E and copy&paste %AppData%\Notepad++\
)
Or:
C:\Documents and
Settings\%username%\Application Data\Notepad++\shortcuts.xml
C:\Users\%username%\AppData\Roaming\Notepad++\shortcuts.xml
Note: You will need to close Notepad++ if you have any new macros you want to 'export'.
Here is an example:
<NotepadPlus>
<InternalCommands />
<Macros>
<Macro name="Trim Trailing and save" Ctrl="no" Alt="yes" Shift="yes" Key="83">
<Action type="2" message="0" wParam="42024" lParam="0" sParam="" />
<Action type="2" message="0" wParam="41006" lParam="0" sParam="" />
</Macro>
<Macro name="abc" Ctrl="no" Alt="no" Shift="no" Key="0">
<Action type="1" message="2170" wParam="0" lParam="0" sParam="a" />
<Action type="1" message="2170" wParam="0" lParam="0" sParam="b" />
<Action type="1" message="2170" wParam="0" lParam="0" sParam="c" />
</Macro>
</Macros>
<UserDefinedCommands>....
I added the 'abc' macro as a proof-of-concept.
I had a similiar post here, addEventListener load on ajax load WITHOUT jquery
How I solved it was to insert calls to functions within my stateChange function. The page I had setup was 3 buttons that would load 3 different pages into the contentArea. Because I had to know which button was being pressed to load page 1, 2 or 3, I could easily use if/else statements to determine which page is being loaded and then which function to run. What I was trying to do was register different button listeners that would only work when the specific page was loaded because of element IDs..
so...
if (page1 is being loaded, pageload = 1) run function registerListeners1
then the same for page 2 or 3.
I believe that this answer is more correct than the other answers here:
from sklearn.tree import _tree
def tree_to_code(tree, feature_names):
tree_ = tree.tree_
feature_name = [
feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature
]
print "def tree({}):".format(", ".join(feature_names))
def recurse(node, depth):
indent = " " * depth
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
print "{}if {} <= {}:".format(indent, name, threshold)
recurse(tree_.children_left[node], depth + 1)
print "{}else: # if {} > {}".format(indent, name, threshold)
recurse(tree_.children_right[node], depth + 1)
else:
print "{}return {}".format(indent, tree_.value[node])
recurse(0, 1)
This prints out a valid Python function. Here's an example output for a tree that is trying to return its input, a number between 0 and 10.
def tree(f0):
if f0 <= 6.0:
if f0 <= 1.5:
return [[ 0.]]
else: # if f0 > 1.5
if f0 <= 4.5:
if f0 <= 3.5:
return [[ 3.]]
else: # if f0 > 3.5
return [[ 4.]]
else: # if f0 > 4.5
return [[ 5.]]
else: # if f0 > 6.0
if f0 <= 8.5:
if f0 <= 7.5:
return [[ 7.]]
else: # if f0 > 7.5
return [[ 8.]]
else: # if f0 > 8.5
return [[ 9.]]
Here are some stumbling blocks that I see in other answers:
tree_.threshold == -2
to decide whether a node is a leaf isn't a good idea. What if it's a real decision node with a threshold of -2? Instead, you should look at tree.feature
or tree.children_*
.features = [feature_names[i] for i in tree_.feature]
crashes with my version of sklearn, because some values of tree.tree_.feature
are -2 (specifically for leaf nodes).You could use the json
module for this. The dumps
function in this module converts a JSON object into a properly formatted string which you can then print.
import json
cars = {'A':{'speed':70, 'color':2},
'B':{'speed':60, 'color':3}}
print(json.dumps(cars, indent = 4))
The output looks like
{ "A": { "color": 2, "speed": 70 }, "B": { "color": 3, "speed": 60 } }
The documentation also specifies a bunch of useful options for this method.
The issue is with
At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?
Many people consider module.exports = ...
to be equivalent to export default ...
and exports.foo ...
to be equivalent to export const foo = ...
. That's not quite true though, or at least not how Babel does it.
ES6 default
exports are actually also named exports, except that default
is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:
// input
export const foo = 42;
export default 21;
// output
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var foo = exports.foo = 42;
exports.default = 21;
Here we can see that the default export becomes a property on the exports
object, just like foo
.
We can import the module in two ways: Either using CommonJS or using ES6 import
syntax.
Your issue: I believe you are doing something like:
var bar = require('./input');
new bar();
expecting that bar
is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default
property!
So in order to access the default export we actually have to do
var bar = require('./input').default;
If we use ES6 module syntax, namely
import bar from './input';
console.log(bar);
Babel will transform it to
'use strict';
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
console.log(_input2.default);
You can see that every access to bar
is converted to access .default
.
If g++
still gives error Try using:
g++ file.c -lstdc++
Look at this post: What is __gxx_personality_v0 for?
Make sure -lstdc++
is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.
Went away...
I have created this library for android where you can validate a material design EditText inside and EditTextLayout easily like this:
compile 'com.github.TeleClinic:SmartEditText:0.1.0'
then you can use it like this:
<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
android:id="@+id/passwordSmartEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:setLabel="Password"
app:setMandatoryErrorMsg="Mandatory field"
app:setPasswordField="true"
app:setRegexErrorMsg="Weak password"
app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />
<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
android:id="@+id/ageSmartEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:setLabel="Age"
app:setMandatoryErrorMsg="Mandatory field"
app:setRegexErrorMsg="Is that really your age :D?"
app:setRegexString=".*\\d.*" />
Then you can check if it is valid like this:
ageSmartEditText.check()
For more examples and customization check the repository https://github.com/TeleClinic/SmartEditText
It can be done this way as well:
$('input', '#div').each(function () {
console.log($(this)); //log every element found to console output
});
The sleep man page says it is declared in <unistd.h>
.
Synopsis:
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
We now finally have IDENTITY
columns like many other databases, in case of which a sequence is auto-generated behind the scenes. This solution is much faster than a trigger-based one as can be seen in this blog post.
So, your table creation would look like this:
CREATE TABLE qname
(
qname_id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL PRIMARY KEY,
qname VARCHAR2(4000) NOT NULL -- CONSTRAINT qname_uk UNIQUE
);
According to the documentation, you cannot do that:
Restriction on Default Column Values A DEFAULT expression cannot contain references to PL/SQL functions or to other columns, the pseudocolumns CURRVAL, NEXTVAL, LEVEL, PRIOR, and ROWNUM, or date constants that are not fully specified.
The standard way to have "auto increment" columns in Oracle is to use triggers, e.g.
CREATE OR REPLACE TRIGGER my_trigger
BEFORE INSERT
ON qname
FOR EACH ROW
-- Optionally restrict this trigger to fire only when really needed
WHEN (new.qname_id is null)
DECLARE
v_id qname.qname_id%TYPE;
BEGIN
-- Select a new value from the sequence into a local variable. As David
-- commented, this step is optional. You can directly select into :new.qname_id
SELECT qname_id_seq.nextval INTO v_id FROM DUAL;
-- :new references the record that you are about to insert into qname. Hence,
-- you can overwrite the value of :new.qname_id (qname.qname_id) with the value
-- obtained from your sequence, before inserting
:new.qname_id := v_id;
END my_trigger;
Read more about Oracle TRIGGERs in the documentation
Use Character.isWhitespace() rather than creating your own.
In Java how does one turn a String into a char or a char into a String?
$keys = array_keys($arr);
$keys = rsort($keys);
print $keys[0];
should print "10"
The optional SECOND argument is the index, starting at 0. So to output the index and total length of an array called 'some_list':
<div>Total Length: {{some_list.length}}</div>
<div v-for="(each, i) in some_list">
{{i + 1}} : {{each}}
</div>
If instead of a list, you were looping through an object, then the second argument is key of the key/value pair. So for the object 'my_object':
var an_id = new Vue({
el: '#an_id',
data: {
my_object: {
one: 'valueA',
two: 'valueB'
}
}
})
The following would print out the key : value pairs. (you can name 'each' and 'i' whatever you want)
<div id="an_id">
<span v-for="(each, i) in my_object">
{{i}} : {{each}}<br/>
</span>
</div>
For more info on Vue list rendering: https://vuejs.org/v2/guide/list.html
This works for both float
and double
:
double NAN = 0.0/0.0;
double POS_INF = 1.0 /0.0;
double NEG_INF = -1.0/0.0;
Edit: As someone already said, the old IEEE standard said that such values should raise traps. But the new compilers almost always switch the traps off and return the given values because trapping interferes with error handling.
Simply type source ~/.bash_profile
Alternatively, if you like saving keystrokes you can type . ~/.bash_profile
If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.
List<BigDecimal> list = mList(
BigDecimal.valueOf(0.1),
BigDecimal.valueOf(1.1),
BigDecimal.valueOf(2.1),
BigDecimal.valueOf(0.1));
BigDecimal sum =
list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);
BigDecimalSummaryStatistics statistics =
list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());
Note: I am a committer for Eclipse Collections.
For Spring Users , Spring Security has a Base64 class in the org.springframework.security.crypto.codec
package that can also be used for encoding and decoding of Base64.
Ex.
public static String base64Encode(String token) {
byte[] encodedBytes = Base64.encode(token.getBytes());
return new String(encodedBytes, Charset.forName("UTF-8"));
}
public static String base64Decode(String token) {
byte[] decodedBytes = Base64.decode(token.getBytes());
return new String(decodedBytes, Charset.forName("UTF-8"));
}
Ideally you shouldn't be splitting strings in T-SQL at all.
Barring that change, on older versions before SQL Server 2016, create a split function:
CREATE FUNCTION dbo.SplitStrings
(
@List nvarchar(max),
@Delimiter nvarchar(2)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN ( WITH x(x) AS
(
SELECT CONVERT(xml, N'<root><i>'
+ REPLACE(@List, @Delimiter, N'</i><i>')
+ N'</i></root>')
)
SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
);
GO
Now you can say:
DECLARE @Values varchar(1000);
SET @Values = 'A, B, C';
SELECT blah
FROM dbo.foo
INNER JOIN dbo.SplitStrings(@Values, ',') AS s
ON s.Item = foo.myField;
On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM()
to take away any leading spaces:
DECLARE @Values varchar(1000) = 'A, B, C';
SELECT blah
FROM dbo.foo
INNER JOIN STRING_SPLIT(@Values, ',') AS s
ON LTRIM(s.value) = foo.myField;
I asked one angle of this question here, and the answers will lead you to all the token-based timing-out cookie links you need.
Basically, you do not store the userId in the cookie. You store a one-time token (huge string) which the user uses to pick-up their old login session. Then to make it really secure, you ask for a password for heavy operations (like changing the password itself).
(This is for posts, not pages - the principle is same. The permalink hook is different by exact use case)
I just had the same issue and created a more convenient way to do that - where you don't have to re-edit your functions.php
all the time, or fiddle around with your server settings on each addition (I do not like both).
TLTR
You can add a filter on the actual WP permalink function you need (for me it was post_link
, because I needed that page alias in an archive/category list), and dynamically read the referenced ID from the alias post itself.
This is ok, because the post is an alias, so you won't need the content anyways.
First step is to open the alias post and put the ID of the referenced post as content (and nothing else):
Next, open your functions.php
and add:
function prefix_filter_post_permalink($url, $post) {
// if the content of the post to get the permalink for is just a number...
if (is_numeric($post->post_content)) {
// instead, return the permalink for the post that has this ID
return get_the_permalink((int)$post->post_content);
}
return $url;
}
add_filter('post_link', 'prefix_filter_post_permalink', 10, 2 );
That's it
Now, each time you need to create an alias post, just put the ID of the referenced post as the content, and you're done.
This will just change the permalink. Title, excerpt and so on will be shown as-is, which is usually desired. More tweaking to your needs is on you, also, the "is it a number" part in the PHP
code is far from ideal, but like this for making the point readable.
Here is an example of concatenation operator:
architecture EXAMPLE of CONCATENATION is
signal Z_BUS : bit_vector (3 downto 0);
signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;
Use JQuery keydown event.
$(document).keypress(function(){
if(event.which == 70){ //f
console.log("You have payed respect");
}
});
In JS; keyboard keys are identified by Javascript keycodes
Use:
import color
class Color(color.Color):
...
If this were Python 2.x, you would also want to derive color.Color
from object
, to make it a new-style class:
class Color(object):
...
This is not necessary in Python 3.x.
See the relevant documentation in general and specifically
from matplotlib.ticker import FormatStrFormatter
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
Just had the same problem. Client-side wasn't appropriate because the button was posting back information from a listview.
Saw same solution as Amaranth's on way2coding but this didn't work for me.
However, in the comments, someone posted a similar solution that does work
OnClientClick="document.getElementById('form1').target ='_blank';"
where form1 is the id of your asp.net form.
As you say, you don't need to request the file twice. Pass it from your controller to your directive. Assuming you use the directive inside the scope of the controller:
.controller('MyController', ['$scope', '$http', function($scope, $http) {
$http.get('locations/locations.json').success(function(data) {
$scope.locations = data;
});
}
Then in your HTML (where you call upon the directive).
Note: locations
is a reference to your controllers $scope.locations
.
<div my-directive location-data="locations"></div>
And finally in your directive
...
scope: {
locationData: '=locationData'
},
controller: ['$scope', function($scope){
// And here you can access your data
$scope.locationData
}]
...
This is just an outline to point you in the right direction, so it's incomplete and not tested.
AntiforgeryToken is still a pain, none of the examples above worked word for word for me. Too many for's there. So I combined them all. Need a @Html.AntiforgeryToken in a form hanging around iirc
Solved as so:
function Forgizzle(eggs) {
eggs.__RequestVerificationToken = $($("input[name=__RequestVerificationToken]")[0]).val();
return eggs;
}
$.ajax({
url: url,
type: 'post',
data: Forgizzle({ id: id, sweets: milkway }),
});
When in doubt, add more $ signs
I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:
Option1:
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
Option2:
SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson();
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();
Option 2 is twice quicker than option 1
The option 2 inconvenience is that you have to make specific code for read:
Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);
If you wanna add dynamic width and height based on your device frame, you can do these calculations and assign the height and width.
AlertDialog.Builder builderSingle = new
AlertDialog.Builder(getActivity());
builderSingle.setTitle("Title");
final AlertDialog alertDialog = builderSingle.create();
alertDialog.show();
Rect displayRectangle = new Rect();
Window window = getActivity().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
alertDialog.getWindow().setLayout((int)(displayRectangle.width() *
0.8f), (int)(displayRectangle.height() * 0.8f));
P.S : Show the dialog first and then try to modify the window's layout attributes