First of all try this
sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove
If error still persists then do this
sudo apt --fix-broken install
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f
Afterwards try this again:
sudo apt-get install npm
But if it still couldn't resolve issues check for the dependencies using sudo dpkg --configure -a
and remove them one-by-one . Let's say dependencies are on npm then go for this ,
sudo apt-get remove nodejs
sudo apt-get remove npm
Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a
sudo apt-get update
Then check for the dependencies problem again using sudo dpkg --configure -a
and if it's all clear then you are done .
Later on install npm again using this
v=8 # set to 4, 5, 6, ... as needed
curl -sL https://deb.nodesource.com/setup_$v.x | sudo -E bash -
Then install the Node.js package.
sudo apt-get install -y nodejs
The answer above will work for general cases also(for dependencies on other packages like django ,etc) just after first two processes use the same process for the package you are facing dependency with.
Just to add another way:
$('form[name=' + formName + ']').find(':input')
If your email address is '[email protected]', try changing the createDirectoryEntry() as below.
XYZ is an optional parameter if it exists in mydomain directory
static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
This will basically check for com -> mydomain -> XYZ -> Users -> abcd
The main function looks as below:
try
{
username = "Firstname LastName"
DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(cn=" + username + ")";
....
document.getElementsByName("name")
will get several elements called by same name .
document.getElementsByName("name")[Number]
will get one of them.
document.getElementsByName("name")[Number].value
will get the value of paticular element.
The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.
XCode>Product>Schemes>Edit Schemes>Run>Build Configuration
I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.
Simple Key Pair JSON structure
var data = {
'XXXXXX' : '100.0',
'YYYYYYY' : '200.0',
'ZZZZZZZ' : '500.0',
}
Usage JavaScript code to access the key pairs
for (var key in data)
{ if (!data.hasOwnProperty(key))
{ continue; }
console.log(key + ' -> ' + data[key]);
};
Console output should look like this
XXXXXX -> 100.0
YYYYYYY -> 200.0
ZZZZZZZ -> 500.0
Here is a JSFiddle to show how it works.
Here's a polyfill for the Number
predicate functions:
"use strict";
Number.isNaN = Number.isNaN ||
n => n !== n; // only NaN
Number.isNumeric = Number.isNumeric ||
n => n === +n; // all numbers excluding NaN
Number.isFinite = Number.isFinite ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_VALUE // and -Infinity
&& n <= Number.MAX_VALUE; // and +Infinity
Number.isInteger = Number.isInteger ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_VALUE // and -Infinity
&& n <= Number.MAX_VALUE // and +Infinity
&& !(n % 1); // and non-whole numbers
Number.isSafeInteger = Number.isSafeInteger ||
n => n === +n // all numbers excluding NaN
&& n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
&& n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
&& !(n % 1); // and non-whole numbers
All major browsers support these functions, except isNumeric
, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:
"use strict";
Number.isNumeric = Number.isNumeric ||
n => n === +n; // all numbers excluding NaN
Alternatively, just inline the expression n === +n
manually.
Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:
public static void main(String[] args{
Thread.currentThread().setName("SomeNameIChoose");
/*...the rest of main...*/
}
After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:
if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
//do something on main thread
}
A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input>
tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
If you try set a value in datetime-local
date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));
//output : 2010-12-30T23:21
There was no information in my Console so that sent me searching for additional solutions and found these - unique to the solutions presented here. I encountered this with Eclipse Oxygen trying to run an old Ant build on a project.
Cause 1 I had configured Eclipse to use an external Ant install which was version 1.10.2 which apparently had classes in it that were compiled with JDK 9. In Eclipse I got the JNI error described above (running the Ant build at the command line gave me the reknowned 'unsupported major.minor version' error - the Java I was using on the system was JDK 8).
The solution was to rollback to the embedded Eclipse version of Ant being 1.10.1. I verified this as the correct solution by downloading Ant 1.10.1 separately and reconfiguring Eclipse to use the new 1.10.1 externally and it still worked.
Cause 2 This can also happen when you have the Ant Runtime settings configured incorrectly in Eclipse's Preferences. Depending on the version of Ant you're running you will need to add the tools.jar from the appropriate JDK to the classpath used for the Ant Runtime (Home Entries). More specifically, without a proper configuration, Eclipse will complain when launching an Ant target that the JRE version is less than a particular required version.
Essentially, 'proper configuration' means aligning each of the configuration items in Eclipse for running Ant so that they all work together. This involves the Ant Runtime Home entry (must point to an Ant version that is compatible with your chosen JDK -- you can't run Ant with JDK 8 when it was compiled against JDK 9); specifying the tools.jar
that belongs to the JDK you want to run Ant with in the Ant Runtime settings; and lastly setting the JRE environment of your build script to the JDK you want to run Ant with in the External Tools Configuration. All 3 of these settings need to agree to avoid the error described above. You'll also need to consider the attributes used in your javac
tag to ensure the JDK you're using is capable of executing as you've directed (i.e. JDK 7 can't compile code using source and target version 8).
Moreover If you're really just trying to run an Ant build script to compile code to an older JDK (e.g. less than 8 for Oxygen), this article helped gain access to run Ant against an older JDK. There are Ant plugin replacements for a handful of versions of Eclipse, the instructions are brief and getting the correct plugin version for your particular Eclipse is important.
Or more simply you can use this very good solution to do your legacy compile which doesn't require replacing your Eclipse plugin but instead changing the javac
tag in your build script (while using the latest JDK).
Sounds like you want:
var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
Without using Async and Await Use this...
funCall(){
this.setState({...this.state.jasper, name: 'someothername'});
}
If you using with Async And Await use this...
async funCall(){
await this.setState({...this.state.jasper, name: 'someothername'});
}
As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:
SELECT *
FROM (
SELECT *
ORDER BY date ASC, time ASC
LIMIT 18446744073709551615
) AS sub
GROUP BY sub.name
https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/
Building upon busylee's answer, this is how you can make a drawable
that only has one unrounded corner (top-left, in this example):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<!-- A numeric value is specified in "radius" for demonstrative purposes only,
it should be @dimen/val_name -->
<corners android:radius="10dp" />
</shape>
</item>
<!-- To keep the TOP-LEFT corner UNROUNDED set both OPPOSITE offsets (bottom+right): -->
<item
android:bottom="10dp"
android:right="10dp">
<shape android:shape="rectangle">
<solid android:color="@color/white" />
</shape>
</item>
</layer-list>
Please note that the above drawable
is not shown correctly in the Android Studio preview (2.0.0p7). To preview it anyway, create another view and use this as android:background="@drawable/..."
.
to remove all shared memory segments on FreeBSD
#!/bin/sh
for i in $(ipcs -m | awk '{ print $2 }' | sed 1,2d);
do
echo "ipcrm -m $i"
ipcrm -m $i
done
to remove all semaphores
#!/bin/sh
for i in $(ipcs -s | awk '{ print $2 }' | sed 1,2d);
do
echo "ipcrm -s $i"
ipcrm -s $i
done
I tried this, I've got something like
script type="text/javascript" src="createDiv.php?id=" script
AND In createDiv.php I Have
document getElementbyid(imgslide).appendchild(imgslide5).innerHTML = 'php echo $helloworld; ';
And I got supermad because the php at the beginning of the createDiv.php I made the $helloWorld
php variable was formatted cut and paste from the html page
But it wouldn't work cause Of whitespaces was anyone gonna tell anyone about the whitespace problem cause my real php whitespace still works but not this one.
I got around this by temporarily rewriting my function to something like this:
IF OBJECT_ID ('[dbo].[fx_dosomething]', 'TF') IS NOT NULL
drop function [dbo].[fx_dosomething];
GO
create FUNCTION dbo.fx_dosomething ( @x numeric )
returns @t table (debug varchar(100), x2 numeric)
as
begin
declare @debug varchar(100)
set @debug = 'printme';
declare @x2 numeric
set @x2 = 0.123456;
insert into @t values (@debug, @x2)
return
end
go
select * from fx_dosomething(0.1)
If you want to hide on initial opening and you are populating the dropdown via ajax call, add the following to the ajax block in your select2 declaration:
beforeSend: function ()
{
$('.select2-search--dropdown').addClass('hidden');
}
To then show it again (and focus) after your ajax request is successful:
success: function() {
$('.select2-search--dropdown').removeClass('select2-search--hide'); // show search bar then focus
$('.select2-search__field')[0].focus();
}
First, Google created the "use less secure accounts method" function:
https://myaccount.google.com/security
Then created the another permission:
https://accounts.google.com/b/0/DisplayUnlockCaptcha
Hope it helps.
I respectually disagree with the notion that link extension methods should be side-effect free (not only because they aren't, any delegate can perform side effects).
Consider the following:
public class Element {}
public Enum ProcessType
{
This = 0, That = 1, SomethingElse = 2
}
public class Class1
{
private Dictionary<ProcessType, Action<Element>> actions =
new Dictionary<ProcessType,Action<Element>>();
public Class1()
{
actions.Add( ProcessType.This, DoThis );
actions.Add( ProcessType.That, DoThat );
actions.Add( ProcessType.SomethingElse, DoSomethingElse );
}
// Element actions:
// This example defines 3 distict actions
// that can be applied to individual elements,
// But for the sake of the argument, make
// no assumption about how many distict
// actions there may, and that there could
// possibly be many more.
public void DoThis( Element element )
{
// Do something to element
}
public void DoThat( Element element )
{
// Do something to element
}
public void DoSomethingElse( Element element )
{
// Do something to element
}
public void Apply( ProcessType processType, IEnumerable<Element> elements )
{
Action<Element> action = null;
if( ! actions.TryGetValue( processType, out action ) )
throw new ArgumentException("processType");
foreach( element in elements )
action(element);
}
}
What the example shows is really just a kind of late-binding that allows one invoke one of many possible actions having side-effects on a sequence of elements, without having to write a big switch construct to decode the value that defines the action and translate it into its corresponding method.
Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.
Try Stretch="UniformToFill" on the Image
The --no-ff
option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff
.
If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.
For example, the author of this article thinks that --no-ff
option should be default and his reasoning is close to that I outlined above:
Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff
, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff
is not used], whereas it is easily done if the --no-ff
flag was used [because it's just one commit]."
Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:
LEFT OUTER JOIN or LEFT JOIN
RIGHT OUTER JOIN or RIGHT JOIN
FULL OUTER JOIN or FULL JOIN
From MSDN
The full outer join
or full join
returns all rows from both tables, matching up the rows wherever a match can be made and placing NULL
s in the places where no matching row exists.
Download your sdk file, go to Android studio: File->New->Import Module
Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"
To change the size of a button called button1
you simple call
button1.config( height = WHATEVER, width = WHATEVER2 )
If you know what size you want at initialization these options can be added to the constructor.
button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100)
You can remove the spaces before casting to int
:
(int)str_replace(' ', '', $b);
Also, if you want to strip other commonly used digit delimiters (such as ,
), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):
(int)str_replace(array(' ', ','), '', $b);
Use data type 'MultilineText':
[DataType(DataType.MultilineText)]
public string Text { get; set; }
If you just want to know how long it takes for the command to execute, you may consider using the time command. You for example use time ffmpeg -i myvideoofoneminute.aformat out.anotherformat
Just another solution
$('.checkbox_class').on('change', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
// do the magic here
}
})
For the people having this problem, please specify you .ini settings. Specifically your apc.mmap_file_mask setting.
For file-backed mmap, it should be set to something like:
apc.mmap_file_mask=/tmp/apc.XXXXXX
To mmap directly from /dev/zero, use:
apc.mmap_file_mask=/dev/zero
For POSIX-compliant shared-memory-backed mmap, use:
apc.mmap_file_mask=/apc.shm.XXXXXX
This is what I would call a classically Apple Xcode UX design bug.
The error said there is a bunch of stuff YOU DID WRONG LOCALLY.
The error actually meant "we have a new agreement you did not accept online".
After checking and unchecking the Automatic Signing button I got this agreement error to display:
Signing into the developer portal I was able to see a banner for the agreement update notice:
. Restarting Xcode 8 then cleared that error and only forced me to reselect the certificate I already had on my machine and tied to the project.
This could have been handled in a less confusing implementation, but this is how I fixed it. I am putting it here because it's way different than the steps everyone else gave.
Oh and yeah, having the pre-latest iOS 10 device and latest Xcode (I was on 7.3.1 or something) also threw errors until I updated.
In java you need to use the static Collections.sort
method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.
private static void order(List<TextComponent> roles) {
Collections.sort(roles, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
int x1 = ((CompanyRole) o1).getBegin();
int x2 = ((CompanyRole) o2).getBegin();
if (x1 != x2) {
return x1 - x2;
} else {
int y1 = ((CompanyRole) o1).getEnd();
int y2 = ((CompanyRole) o2).getEnd();
return y2 - y1;
}
}
});
}
You can save it as .txt and change it manually using a mouse click and your keyboard. OR, when saving the file:
All types(*.*)
in the Save as type
field.File name
fieldIn Ubuntu /etc/init.d has been replaced by /usr/lib/systemd. Scripts can still be started and stoped by 'service'. But the primary command is now 'systemctl'. The chkconfig command was left behind, and now you do this with systemctl.
So instead of:
chkconfig enable apache2
You should look for the service name, and then enable it
systemctl status apache2
systemctl enable apache2.service
Systemd has become more friendly about figuring out if you have a systemd script, or an /etc/init.d script, and doing the right thing.
C# 9 (released with .NET 5) includes the logical patterns and
, or
and not
, which allows us to write this more elegantly:
if (child is not IContainer) { ... }
Likewise, this pattern can be used to check for null:
if (child is not null) { ... }
In version 0.24.+ pandas has gained the ability to hold integer dtypes with missing values.
Pandas can represent integer data with possibly missing values using arrays.IntegerArray
. This is an extension types implemented within pandas. It is not the default dtype for integers, and will not be inferred; you must explicitly pass the dtype into array()
or Series
:
arr = pd.array([1, 2, np.nan], dtype=pd.Int64Dtype())
pd.Series(arr)
0 1
1 2
2 NaN
dtype: Int64
For convert column to nullable integers use:
df['myCol'] = df['myCol'].astype('Int64')
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
Ok so if an image in a table is clicked you want the data of the first row of the table this image is in.
//image click stuff here {
$(this). // our image
closest('table'). // Go upwards through our parents untill we hit the table
children('tr:first'); // Select the first row we find
var $row = $(this).closest('table').children('tr:first');
parent()
will only get the direct parent, closest
should do what we want here.
From jQuery docs: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
Not sure about older versions, but in 2016.2 removing the .key
file(s) didn't work for me.
I'm using my JetBrains account and used the 'Remove License' button found at the bottom of the registration dialog. You can find this under the Help
menu or from the startup dialog via Configure -> Manage License...
.
This is the command to use to tell Gradle to upgrade the wrapper such that it will grab the distribution versions of libraries that includes source code:
./gradlew wrapper --gradle-version <version> --distribution-type all
Specifying the distribution-type with "all" will make sure Gradle downloads source files for use by your development environment.
Pros:
Cons:
Please comment or provide another answer if you know of any command line option to tell Gradle not to download sources on a build server.
I kind of like this solution :
: `particular_script`
The command/script between the back ticks is executed and its output is fed to the command ":" (which is the equivalent of "true")
$ false
$ echo $?
1
$ : `false`
$ echo $?
0
edit: Fixed ugly typo
Map is a part of the enumerable module. Very similar to "collect" For Example:
Class Car
attr_accessor :name, :model, :year
Def initialize (make, model, year)
@make, @model, @year = make, model, year
end
end
list = []
list << Car.new("Honda", "Accord", 2016)
list << Car.new("Toyota", "Camry", 2015)
list << Car.new("Nissan", "Altima", 2014)
p list.map {|p| p.model}
Map provides values iterating through an array that are returned by the block parameters.
First simple rule: never use the String(String)
constructor, it is absolutely useless (*).
So arr.add("ss")
is just fine.
With 3
it's slightly different: 3
is an int
literal, which is not an object. Only objects can be put into a List
. So the int
will need to be converted into an Integer
object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as Integer.valueOf(3)
which can (and will) avoid creating a new Integer
instance in some cases.
So actually writing arr.add(3)
is usually a better idea than using arr.add(new Integer(3))
, because it can avoid creating a new Integer
object and instead reuse and existing one.
Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.
(*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)
$ sbt sbtVersion
This prints the sbt version used in your current project, or if it is a multi-module project for each module.
$ sbt 'inspect sbtVersion'
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.13.1
[info] Description:
[info] Provides the version of sbt. This setting should be not be modified.
[info] Provided by:
[info] */*:sbtVersion
[info] Defined at:
[info] (sbt.Defaults) Defaults.scala:68
[info] Delegates:
[info] *:sbtVersion
[info] {.}/*:sbtVersion
[info] */*:sbtVersion
[info] Related:
[info] */*:sbtVersion
You may also want to use sbt about
that (copying Mark Harrah's comment):
The about command was added recently to try to succinctly print the most relevant information, including the sbt version.
It can also be done this way:
figure(xx);
set(gcf, 'name', 'Name goes here')
gcf
gets the current figure handle.
Eight years later... Microsoft SQL Server vNext Database Engine has finally enhanced Transact-SQL to directly support grouped string concatenation. The Community Technical Preview version 1.0 added the STRING_AGG function and CTP 1.1 added the WITHIN GROUP clause for the STRING_AGG function.
Reference: https://msdn.microsoft.com/en-us/library/mt775028.aspx
Well I'm sure that this is the simplest way to populate JTable from ResultSet, without any external library. I have included comments in this method.
public void resultSetToTableModel(ResultSet rs, JTable table) throws SQLException{
//Create new table model
DefaultTableModel tableModel = new DefaultTableModel();
//Retrieve meta data from ResultSet
ResultSetMetaData metaData = rs.getMetaData();
//Get number of columns from meta data
int columnCount = metaData.getColumnCount();
//Get all column names from meta data and add columns to table model
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
tableModel.addColumn(metaData.getColumnLabel(columnIndex));
}
//Create array of Objects with size of column count from meta data
Object[] row = new Object[columnCount];
//Scroll through result set
while (rs.next()){
//Get object from column with specific index of result set to array of objects
for (int i = 0; i < columnCount; i++){
row[i] = rs.getObject(i+1);
}
//Now add row to table model with that array of objects as an argument
tableModel.addRow(row);
}
//Now add that table model to your table and you are done :D
table.setModel(tableModel);
}
var boxSummary = from b in boxes
group b by b.Owner into g
let nrBoxes = g.Count()
let totalWeight = g.Sum(w => w.Weight)
let totalVolume = g.Sum(v => v.Volume)
select new { Owner = g.Key, Boxes = nrBoxes,
TotalWeight = totalWeight,
TotalVolume = totalVolume }
Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.
Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.
However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.
I am using jQuery here to get the entered text and wrapping all code in $(document).ready(). Make sure you have your API key ready for Google Places API Web service. Replace it in the below script file.
<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>
Use script file to load the autocomplete class. Your scripts.js file will look something like this.
// scripts.js custom js file
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initialize);
});
function initialize() {
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input);
}
db.company_profile.find({ "companyName" : { "$regex" : "Nilesh" , "$options" : "i"}});
I just came across this thread while searching for an answer to why the php.ini file would be within the /wp-admin/ folder for WordPress that I have just seen in an odd setup - because it really really shouldn't be there.
WordPress by default doesn't include a php.ini file within the /wp-admin/ folder, so you should not have one there yourself. The php.ini file is designed to override the main server PHP configuration settings so that your account on the server is treated differently, within limits. As such, if you do need to use this file, please, for your own sanity (and that of others who happen to work with your systems in the future...), place the php.ini file in the root of your account, not hidden away in the /wp-admin/ folder, or any other folder for that matter.
I'm surprised to see so many others commenting that it should be in the /wp-admin/ folder to be honest. I'd love to see some official documentation from WordPress stating that this is best practice, as this is certainly something that I would completely avoid.
You can't if T is all you get. It must be injected by the provider:
Collection<T extends Comparable>
or pass in the Comparator
Collections.sort(...)
Everyone
to the user list.Basically like this,
<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>
The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.
The best way is to:
svn merge -c -RevisionToUndo ^/trunk
This will undo all files of the revision than simply revert those file you don't like to undo. Don't forget the dash (-
) as prefix for the revision.
svn revert File1 File2
Now commit the changes back.
This can be achieved using TextEditingController
.
To have an initial value you can add
TextEditingController _controller = TextEditingController(text: 'initial value');
or
If you are using TextFormField
you have a initialValue
property there. Which basically provides this initialValue
to the controller automatically.
TextEditingController _controller = TextEditingController();
TextFormField(
controller: _controller,
initialValue: 'initial value'
)
To clear the text you can use
_controller.clear()
method.
I successfully passed multiple parameters using json
data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",
For now, the best bet is probably jstz as suggested in mbayloon's answer.
For completeness, it should be mentioned that there is a standard on it's way: Intl. You can see this in Chrome already:
> Intl.DateTimeFormat().resolvedOptions().timeZone
"America/Los_Angeles"
(This doesn't actually follow the standard, which is one more reason to stick with the library)
Not a single answer here actually answers the question. The OP did not ask about a singleton/per-application DbContext design, he asked about a per-(web)request design and what potential benefits could exist.
I'll reference http://mehdi.me/ambient-dbcontext-in-ef6/ as Mehdi is a fantastic resource:
Possible performance gains.
Each DbContext instance maintains a first-level cache of all the entities its loads from the database. Whenever you query an entity by its primary key, the DbContext will first attempt to retrieve it from its first-level cache before defaulting to querying it from the database. Depending on your data query pattern, re-using the same DbContext across multiple sequential business transactions may result in a fewer database queries being made thanks to the DbContext first-level cache.
It enables lazy-loading.
If your services return persistent entities (as opposed to returning view models or other sorts of DTOs) and you'd like to take advantage of lazy-loading on those entities, the lifetime of the DbContext instance from which those entities were retrieved must extend beyond the scope of the business transaction. If the service method disposed the DbContext instance it used before returning, any attempt to lazy-load properties on the returned entities would fail (whether or not using lazy-loading is a good idea is a different debate altogether which we won't get into here). In our web application example, lazy-loading would typically be used in controller action methods on entities returned by a separate service layer. In that case, the DbContext instance that was used by the service method to load these entities would need to remain alive for the duration of the web request (or at the very least until the action method has completed).
Keep in mind there are cons as well. That link contains many other resources to read on the subject.
Just posting this in case someone else stumbles upon this question and doesn't get absorbed in answers that don't actually address the question.
I found the solution as Its problem with Android Studio 3.1 Canary 6
My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.
Now My build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.2'
defaultConfig {
applicationId "com.example.demo"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
dataBinding {
enabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.squareup.retrofit2:retrofit:2.3.0"
implementation "com.google.code.gson:gson:2.8.2"
implementation "com.android.support.constraint:constraint-layout:1.0.2"
implementation "com.squareup.retrofit2:converter-gson:2.3.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
implementation "com.squareup.picasso:picasso:2.5.2"
implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
compile 'com.github.elevenetc:badgeview:v1.0.0'
annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
testImplementation "junit:junit:4.12"
androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
exclude group: "com.android.support", module: "support-annotations"
})
}
and My gradle is:
classpath 'com.android.tools.build:gradle:3.1.0-alpha06'
and its working finally.
I think there problem in Android Studio 3.1 Canary 6
Thank you all for your time.
send a string to this function. it will first check string is empty or null, if not string will be all lower chars. then return first char of string upper rest of them lower.
string FirstUpper(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
s = s.ToLower();
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1);
}
to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php
$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");
$json_object = json_decode($unparsed_json);
then json_decode() parses JSON into a PHP object, or an array if you pass true
to the second parameter.
http://php.net/manual/en/function.json-decode.php
For example:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json)); // Object
var_dump(json_decode($json, true)); // Associative array
Just define a helper in application helper directory then call from your controller just function name like
helper name = new_helper.php
function test_method($data){
return $data
}
in controller load the helper
$this->load->new_helper();
$result = test_method('Hello world!');
if($result){
echo $result
}
output will be
Hello World!
While a set
may be what you want structure-wise, the question is what is faster. A list is faster. Your example code doesn't accurately compare set
vs list
because you're converting from a list to a set in set_loop
, and then you're creating the list
you'll be looping through in list_loop
. The set and list you iterate through should be constructed and in memory ahead of time, and simply looped through to see which data structure is faster at iterating:
ids_list = range(1000000)
ids_set = set(ids)
def f(x):
for i in x:
pass
%timeit f(ids_set)
#1 loops, best of 3: 214 ms per loop
%timeit f(ids_list)
#1 loops, best of 3: 176 ms per loop
You need to diagnosis the jvm usages like how many process is running and what about heap allocation. there exists a lot of ways to do that for example
Does the /etc/postgresql/9.6/main/postgresql.conf
show that port being assigned? On my default Xubuntu Linux install, mine showed port = 5433 for some reason as best as I can remember, but I did comment out the line in that same file that said listen_addresses = 'localhost'
and uncommented the line listen_addresses = '*'
. So maybe start and check there. Hope that helps.
$(this).parent().siblings(":first").text()
parent
gives you the <td>
around the link,
siblings
gives all the <td>
tags in that <tr>
,
:first
gives the first matched element in the set.
text()
gives the contents of the tag.
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
In a Python 2 program that I used for many years there was this line:
ocd[i].namn=unicode(a[:b], 'utf-8')
This did not work in Python 3.
However, the program turned out to work with:
ocd[i].namn=a[:b]
I don't remember why I put unicode there in the first place, but I think it was because the name can contains Swedish letters åäöÅÄÖ. But even they work without "unicode".
export
is used to set environment variables. For example:
export EDITOR=pico
Will set your default text editor to be the pico
command.
Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.
If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)
You need a mechanism which avoids busy-waiting. The old wait/notify
mechanism is fraught with pitfalls so prefer something from the java.util.concurrent
library, for example the CountDownLatch
:
public final CountDownLatch latch = new CountDownLatch(1);
public void run () {
latch.await();
...
}
And at the other side call
yourRunnableObj.latch.countDown();
However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService
to which you submit as a task the work which must be done when the condition is met.
You can simply do that:
<html>
<table>
<tr>
<td>one</td>
<td width="10px"></td>
<td>two</td>
</tr>
</table>
</html>
No CSS is required :) This 10px is your space.
One extra feature is you can also use-media queries in the media attribute of the <link>
tag.
<link href="style.css" rel="stylesheet">
<link href="justForFrint.css" rel="stylesheet" media="print">
<link href="deviceSizeDepending.css" rel="stylesheet" media="(min-width: 40em)">
With this, the browser will download all CSS resources, regardless of the media attribute. The difference is that if the media-query of the media attribute is evaluated to false then that .css file and his content will not be render-blocking.
Therefore, it is recommended to use the media attribute in the <link>
tag since it guarantees a better user experience.
Here you can read a Google article about this issue https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css
Some tools that will help you to automate the separation of your css code in different files according to your media-querys
Webpack https://www.npmjs.com/package/media-query-plugin https://www.npmjs.com/package/media-query-splitting-plugin
PostCSS https://www.npmjs.com/package/postcss-extract-media-query
There is a default text editor that will be used when Git needs you to type in a message. By default, Git uses your system’s default editor, which is generally Vi or Vim. In your case, it is Vim that Git has chosen. See How do I make Git use the editor of my choice for commits? for details of how to choose another editor. Meanwhile...
You'll want to enter a message before you leave Vim:
...will start a new line for you to type in.
To exit (g)Vim type:
It's worth getting to know Vim, as you can use it for editing text on almost any platform. I recommend the Vim Tutor
, I used it many years ago and have never looked back (barely a day goes by when I don't use Vim).
It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.
It seems like str_shuffle would be a good use for this. Seed the shuffle with whichever characters you want.
$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);
From general object oriented view:
Regarding abstract method: When you put an abstract method in the parent class actually your are saying to the child classes: Hey note that you have a method signature like this. And if you wanna to use it you should implement your own!
Regarding virtual function: When you put a virtual method in the parent class you are saying to the derived classes : Hey there is a functionality here that do something for you. If this is useful for you just use it. If not, override this and implement your code, even you can use my implementation in your code !
this is some philosophy about different between this two concept in General OO
I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.
This may not be what you are looking for but I thought you oughta know the real way to do this. You can use the java.lang.Character
class's isUpperCase()
to find aout about the case of the character. You can use isDigit()
to differentiate between the numbers and letters(This is just FYI :) ). You can then do a toUpperCase()
and then do the switch for vowels. This will improve your code quality.
I found the git command line didnt fancy my pageant generated keys (Windows 10).
See my answer on Serverfault
A ClassCastException
ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example
Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;
This works because an apple 'is a' fruit. However if we reverse this.
Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;
This will throw a ClasCastException because a Fruit is not (always) an Apple.
It is good practice to guard any explicit casts with an instanceof
check first:
if (myApple instanceof Fruit) {
Fruit myFruit = (Fruit)myApple;
}
Native way to get the mimetype:
For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()
Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.
While mime_content_type
is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).
If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.
function getMimeType($filename)
{
$mimetype = false;
if(function_exists('finfo_open')) {
// open with FileInfo
} elseif(function_exists('getimagesize')) {
// open with GD
} elseif(function_exists('exif_imagetype')) {
// open with EXIF
} elseif(function_exists('mime_content_type')) {
$mimetype = mime_content_type($filename);
}
return $mimetype;
}
I found a solution on the MSDN forums. The sample code below will remove all Click
events from button1
.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += button1_Click;
button1.Click += button1_Click2;
button2.Click += button2_Click;
}
private void button1_Click(object sender, EventArgs e) => MessageBox.Show("Hello");
private void button1_Click2(object sender, EventArgs e) => MessageBox.Show("World");
private void button2_Click(object sender, EventArgs e) => RemoveClickEvent(button1);
private void RemoveClickEvent(Button b)
{
FieldInfo f1 = typeof(Control).GetField("EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
object obj = f1.GetValue(b);
PropertyInfo pi = b.GetType().GetProperty("Events",
BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
list.RemoveHandler(obj, list[obj]);
}
}
A simple solution:
Encode the image as a jpeg and look for a substantial change in filesize.
I've implemented something similar with video thumbnails, and had a lot of success and scalability.
#include <stdint.h>
uintptr_t
standard type defined in the included standard header file.I would like to know what exactly is the difference between querySelector and querySelectorAll against getElementsByClassName and getElementById?
The syntax and the browser support.
querySelector
is more useful when you want to use more complex selectors.
e.g. All list items descended from an element that is a member of the foo class: .foo li
document.querySelector("#view:_id1:inputText1") it doesn't work. But writing document.getElementById("view:_id1:inputText1") works. Any ideas why?
The :
character has special meaning inside a selector. You have to escape it. (The selector escape character has special meaning in a JS string too, so you have to escape that too).
document.querySelector("#view\\:_id1\\:inputText1")
There's a nice way to eject webpack.config.js from angular-cli. Just run:
$ ng eject
This will generate webpack.config.js in the root folder of your project, and you're free to configure it the way you want. The downside of this is that build/start scripts in your package.json will be replaced with the new commands and instead of
$ ng serve
you would have to do something like
$ npm run build & npm run start
This method should work in all the recent versions of angular-cli (I personally tried a few, with the oldest being 1.0.0-beta.21, and the latest 1.0.0-beta.32.3)
For ubuntu 16.10 are sessions save in /var/lib/php/session/...
Building off the accepted answer, a multi-dimensional array type, that is a fixed-length array of fixed-length arrays, can't be declared with
typedef char[M] T[N]; // wrong!
instead, the intermediate 1D array type can be declared and used as in the accepted answer:
typedef char T_t[M];
typedef T_t T[N];
or, T
can be declared in a single (arguably confusing) statement:
typedef char T[N][M];
which defines a type of N
arrays of M
chars (be careful about the order, here).
You can wrap and unwrap exceptions this way.
class A {
void foo() throws Exception {
throw new Exception();
}
};
interface Task {
void run() throws Exception;
}
static class TaskException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TaskException(Exception e) {
super(e);
}
}
void bar() throws Exception {
Stream<A> as = Stream.generate(()->new A());
try {
as.forEach(a -> wrapException(() -> a.foo())); // or a::foo instead of () -> a.foo()
} catch (TaskException e) {
throw (Exception)e.getCause();
}
}
static void wrapException(Task task) {
try {
task.run();
} catch (Exception e) {
throw new TaskException(e);
}
}
In JS, we can easily return a tuple with an array or object, but do not forget! => JS is a callback
oriented language, and there is a little secret here for "returning multiple values" that nobody has yet mentioned, try this:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
becomes
var newCodes = function(fg, cb) {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
cb(null, dCodes, dCodes2);
};
:)
bam! This is simply another way of solving your problem.
document.getElementById("PdfContentArea").setAttribute('data', path);
OR
var objectEl = document.getElementById("PdfContentArea")
objectEl.outerHTML = objectEl.outerHTML.replace(/data="(.+?)"/, 'data="' + path + '"');
I think it is the autoboxing that is throwing you off.
This part of your code:
public static Integer inc(Integer i) {
i = i+1; // I think that this must be **sneakally** creating a new integer...
System.out.println("Inc: "+i);
return i;
}
Really boils down to code that looks like:
public static Integer inc(Integer i) {
i = new Integer(i) + new Integer(1);
System.out.println("Inc: "+i);
return i;
}
Which of course.. will not changes the reference passed in.
You could fix it with something like this
public static void main(String[] args) {
Integer integer = new Integer(0);
for (int i =0; i<10; i++){
integer = inc(integer);
System.out.println("main: "+integer);
}
}
ECMAScript 6 introduces String.prototype.includes
, previously named contains
.
It can be used like this:
'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false
It also accepts an optional second argument which specifies the position at which to begin searching:
'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true
It can be polyfilled to make it work on old browsers.
int i = 1;
Test val = static_cast<Test>(i);
For those who are complining about Michael Tiptop's solution not working, here is the .Net4+ way of doing it:
public static string StripTags(this string markup)
{
try
{
StringReader sr = new StringReader(markup);
XPathDocument doc;
using (XmlReader xr = XmlReader.Create(sr,
new XmlReaderSettings()
{
ConformanceLevel = ConformanceLevel.Fragment
// for multiple roots
}))
{
doc = new XPathDocument(xr);
}
return doc.CreateNavigator().Value; // .Value is similar to .InnerText of
// XmlDocument or JavaScript's innerText
}
catch
{
return string.Empty;
}
}
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
You can check if the array is empty by retrieving total elements count using JScript's VBArray()
object (works with arrays of variant type, single or multidimensional):
Sub Test()
Dim a() As Variant
Dim b As Variant
Dim c As Long
' Uninitialized array of variant
' MsgBox UBound(a) ' gives 'Subscript out of range' error
MsgBox GetElementsCount(a) ' 0
' Variant containing an empty array
b = Array()
MsgBox GetElementsCount(b) ' 0
' Any other types, eg Long or not Variant type arrays
MsgBox GetElementsCount(c) ' -1
End Sub
Function GetElementsCount(aSample) As Long
Static oHtmlfile As Object ' instantiate once
If oHtmlfile Is Nothing Then
Set oHtmlfile = CreateObject("htmlfile")
oHtmlfile.parentWindow.execScript ("function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}"), "jscript"
End If
GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)
End Function
For me it takes about 0.3 mksec for each element + 15 msec initialization, so the array of 10M elements takes about 3 sec. The same functionality could be implemented via ScriptControl
ActiveX (it is not available in 64-bit MS Office versions, so you can use workaround like this).
If you're using compass:
compass watch --output-style compressed
Check out the "--only-keep-debug" option of the strip command.
From the link:
The intention is that this option will be used in conjunction with --add-gnu-debuglink to create a two part executable. One a stripped binary which will occupy less space in RAM and in a distribution and the second a debugging information file which is only needed if debugging abilities are required.
This is the first page that shows up via Google and the security vulnerabilities in all the implementations make me cringe so I'm posting this to add information regarding encryption for others as it has been 7 Years from the original post. I hold a Masters Degree in Computer Engineering and spent a lot of time studying and learning Cryptography so I'm throwing my two cents to make the internet a safer place.
Also, do note that a lot of implementation might be secure for a given situation, but why use those and potentially accidentally make a mistake? Use the strongest tools you have available unless you have a specific reason not to. Overall I highly advise using a library and staying away from the nitty gritty details if you can.
UPDATE 4/5/18: I rewrote some parts to make them simpler to understand and changed the recommended library from Jasypt to Google's new library Tink, I would recommend completely removing Jasypt from an existing setup.
Foreword
I will outline the basics of secure symmetric cryptography below and point out common mistakes I see online when people implement crypto on their own with the standard Java library. If you want to just skip all the details run over to Google's new library Tink import that into your project and use AES-GCM mode for all your encryptions and you shall be secure.
Now if you want to learn the nitty gritty details on how to encrypt in java read on :)
Block Ciphers
First thing first you need to pick a symmetric key Block Cipher. A Block Cipher is a computer function/program used to create Pseudo-Randomness. Pseudo-Randomness is fake randomness that no computer other than a Quantum Computer would be able to tell the difference between it and real randomness. The Block Cipher is like the building block to cryptography, and when used with different modes or schemes we can create encryptions.
Now regarding Block Cipher Algorithms available today, Make sure to NEVER, I repeat NEVER use DES, I would even say NEVER use 3DES. The only Block Cipher that even Snowden's NSA release was able to verify being truly as close to Pseudo-Random as possible is AES 256. There also exists AES 128; the difference is AES 256 works in 256-bit blocks, while AES 128 works in 128 blocks. All in all, AES 128 is considered secure although some weaknesses have been discovered, but 256 is as solid as it gets.
Fun fact DES was broken by the NSA back when it was initially founded and actually kept a secret for a few years. Although some people still claim 3DES is secure, there are quite a few research papers that have found and analyzed weaknesses in 3DES.
Encryption Modes
Encryption is created when you take a block cipher and use a specific scheme so that the randomness is combined with a key to creating something that is reversible as long as you know the key. This is referred to as an Encryption Mode.
Here is an example of an encryption mode and the simplest mode known as ECB just so you can visually understand what is happening:
The encryption modes you will see most commonly online are the following:
ECB CTR, CBC, GCM
There exist other modes outside of the ones listed and researchers are always working toward new modes to improve existing problems.
Now let's move on to implementations and what is secure. NEVER use ECB this is bad at hiding repeating data as shown by the famous Linux penguin.
When implementing in Java, note that if you use the following code, ECB mode is set by default:
Cipher cipher = Cipher.getInstance("AES");
... DANGER THIS IS A VULNERABILITY! and unfortunately, this is seen all over StackOverflow and online in tutorials and examples.
Nonces and IVs
In response to the issue found with ECB mode nounces also known as IVs were created. The idea is that we generate a new random variable and attach it to every encryption so that when you encrypt two messages that are the same they come out different. The beauty behind this is that an IV or nonce is public knowledge. That means an attacker can have access to this but as long as they don't have your key, they cant do anything with that knowledge.
Common issues I will see is that people will set the IV as a static value as in the same fixed value in their code. and here is the pitfall to IVs the moment you repeat one you actually compromise the entire security of your encryption.
Generating A Random IV
SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
Note: SHA1 is broken but I couldn't find how to implement SHA256 into this use case properly, so if anyone wants to take a crack at this and update it would be awesome! Also SHA1 attacks still are unconventional as it can take a few years on a huge cluster to crack. Check out details here.
CTR Implementation
No padding is required for CTR mode.
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
CBC Implementation
If you choose to implement CBC Mode do so with PKCS7Padding as follows:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
CBC and CTR Vulnerability and Why You Should Use GCM
Although some other modes such as CBC and CTR are secure they run into the issue where an attacker can flip the encrypted data, changing its value when decrypted. So let's say you encrypt an imaginary bank message "Sell 100", your encrypted message looks like this "eu23ng" the attacker changes one bit to "eu53ng" and all of a sudden when decrypted your message, it reads as "Sell 900".
To avoid this the majority of the internet uses GCM, and every time you see HTTPS they are probably using GCM. GCM signs the encrypted message with a hash and checks to verify that the message has not been changed using this signature.
I would avoid implementing GCM because of its complexity. You are better off using Googles new library Tink because here again if you accidentally repeat an IV you are compromising the key in the case with GCM, which is the ultimate security flaw. New researchers are working towards IV repeat resistant encryption modes where even if you repeat the IV the key is not in danger but this has yet to come mainstream.
Now if you do want to implement GCM, here is a link to a nice GCM implementation. However, I can not ensure the security or if its properly implemented but it gets the basis down. Also note with GCM there is no padding.
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
Keys vs Passwords
Another very important note, is that when it comes to cryptography a Key and a Password are not the same things. A Key in cryptography needs to have a certain amount of entropy and randomness to be considered secure. This is why you need to make sure to use the proper cryptographic libraries to generate the key for you.
So you really have two implementations you can do here, the first is to use the code found on this StackOverflow thread for Random Key Generation. This solution uses a secure random number generator to create a key from scratch that you can the use.
The other less secure option is to use, user input such as a password. The issue as we discussed is that the password doesn't have enough entropy, so we would have to use PBKDF2, an algorithm that takes the password and strengthens it. Here is a StackOverflow implementation I liked. However Google Tink library has all this built in and you should take advantage of it.
Android Developers
One important point to point out here is know that your android code is reverse engineerable and most cases most java code is too. That means if you store the password in plain text in your code. A hacker can easily retrieve it. Usually, for these type of encryption, you want to use Asymmetric Cryptography and so on. This is outside the scope of this post so I will avoid diving into it.
An interesting reading from 2013: Points out that 88% of Crypto implementations in Android were done improperly.
Final Thoughts
Once again I would suggest avoid implementing the java library for crypto directly and use Google Tink, it will save you the headache as they have really done a good job of implementing all the algorithms properly. And even then make sure you check up on issues brought up on the Tink github, vulnerabilities popup here and there.
If you have any questions or feedback feel free to comment! Security is always changing and you need to do your best to keep up with it :)
Not very clear what you mean by
"I cant find any examples to help me understand how I can use this to run 2 different statements:"
. Is it using CASE
like a SWITCH
you are after?
select case when totalCount >= 0 and totalCount < 11 then '0-10'
when tatalCount > 10 and totalCount < 101 then '10-100'
else '>100' end as newColumn
from (
SELECT [Some Column], COUNT(*) TotalCount
FROM INCIDENTS
WHERE [Some Column] = 'Target Data'
GROUP BY [Some Column]
) A
md5sum binary1 binary2
If the md5sum is same, binaries are same
E.g
md5sum new*
89c60189c3fa7ab5c96ae121ec43bd4a new.txt
89c60189c3fa7ab5c96ae121ec43bd4a new1.txt
root@TinyDistro:~# cat new*
aa55 aa55 0000 8010 7738
aa55 aa55 0000 8010 7738
root@TinyDistro:~# cat new*
aa55 aa55 000 8010 7738
aa55 aa55 0000 8010 7738
root@TinyDistro:~# md5sum new*
4a7f86919d4ac00c6206e11fca462c6f new.txt
89c60189c3fa7ab5c96ae121ec43bd4a new1.txt
var array3 = array1 === array2
That will compare whether array1 and array2 are the same array object in memory, which is not what you want.
In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.
Assuming your array is filled with primitives—numbers and or strings—something like this should do
function arraysAreIdentical(arr1, arr2){
if (arr1.length !== arr2.length) return false;
for (var i = 0, len = arr1.length; i < len; i++){
if (arr1[i] !== arr2[i]){
return false;
}
}
return true;
}
This is an updated solution for HTML 5 if anyone is interested & not fond of "floating".
Table works great in this case as you can set the fixed width to the table & table-cell.
.content-container{
display: table;
width: 300px;
}
.content .right{
display: table-cell;
background-color:green;
width: 100px;
}
http://jsfiddle.net/EAEKc/596/ original source code from @merkuro
Most likely, an error occurred when the daemon attempted to cleanup the container, and he is now stuck in this "zombie" state.
I'm afraid your only option here is to manually clean it up:
$ sudo rm -rf /var/lib/docker/<storage_driver>/11667ef16239.../
Where <storage_driver>
is the name of your driver (aufs
, overlay
, btrfs
, or devicemapper
).
notify()
needs to be synchronized as well
Must it be mutable? Use a list. Must it not be mutable? Use a tuple.
Otherwise, it's a question of choice.
For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.
Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.
It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).
Do NOT have trailing commas in your OBJECT (JSON is a string notation)
UPDATE: you need to use array.splice and not delete if you want to remove items from the array in the object. Alternatively filter the array for undefined after removing
var data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.
data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.
_x000D_
To use the hex
encoding in Python 3, use
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
In legacy Python, there are several other ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'
Right click on the .svc file in Solution Explorer and click View Markup
<%@ ServiceHost Language="C#" Debug="true"
Service="MyService.**GetHistoryInfo**"
CodeBehind="GetHistoryInfo.svc.cs" %>
Update the service reference where you are referring to.
You can use git show
with a path from the root of the repository (./
or ../
for relative pathing):
$ git show REVISION:path/to/file
Replace REVISION
with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)
For example, to view the version of file <repository-root>/src/main.c
from 4 commits ago, use:
$ git show HEAD~4:src/main.c
Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show
.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
Use .val()
to get value of textarea and use $.trim()
to empty spaces.
$(document).ready(function () {
if ($.trim($("textarea").val()) != "") {
alert($("textarea").val());
}
});
Or, Here's what I would do for clean code,
$(document).ready(function () {
var val = $.trim($("textarea").val());
if (val != "") {
alert(val);
}
});
I would suggest you to have a look at RSHD
You do not need to bother for a client, Windows has it by default.
The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script>
tags at the end of the document body so they don't block rendering of the page.
But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:
There are some great slides by Steve Souders (client-side performance expert) about:
- Different techniques to load external JavaScript files in parallel
- their effect on loading time and page rendering
- what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).
use the JavaScript Date()
object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)
function myFunction() {
var d = new Date();
var timeStamp = d.getTime(); // Number of ms since Jan 1, 1970
// OR:
var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}
@WoooHaaaa some third party packages use 'django.middleware.csrf.CsrfViewMiddleware' middleware. for example i use django-rest-oauth and i have problem like you even after disabling those things. maybe these packages responded to your request like my case, because you use authentication decorator and something like this.
Pong doesn't mean web service on the server is running; it merely means that server is replying to ICMP echo. I would recommend using curl and check its return value.
If you don't need to display exact result "running" / "not runnuning", you could simply:
ps notepad -ErrorAction SilentlyContinue | kill -PassThru
If the process was not running, you'll get no results. If it was running, you'll receive get-process
output, and the process will be stopped.
As I see it there are really three choices here and the solution depends on the context. You can choose to implement the construction of the name in the method that produces the list. This is the choice you've chosen, but I don't think it is the best one. You are creating a coupling in the producer method to the consuming method that doesn't need to exist. Other callers may not need the extra information and you would be calculating extra information for these callers.
Alternatively, you could have the calling method calculate the name. If there is only one caller that needs this information, you can stop there. You have no extra dependencies and while there is a little extra calculation involved, you've avoided making your construction method too specific. This is a good trade-off.
Lastly, you could have the list itself be responsible for creating the name. This is the route I would go if the calculation needs to be done by more than one caller. I think this puts the responsibility for the creation of the names with the class that is most closely related to the objects themselves.
In the latter case, my solution would be to create a specialized List class that returns a comma-separated string of the names of objects that it contains. Make the class smart enough that it constructs the name string on the fly as objects are added and removed from it. Then return an instance of this list and call the name generation method as needed. Although it may be almost as efficient (and simpler) to simply delay calculation of the names until the first time the method is called and store it then (lazy loading). If you add/remove an object, you need only remove the calculated value and have it get recalculated on the next call.
A lot of the code here was very helpful, but I cleaned it up for my purposes and added some tests. Here's what I ended up with:
using System;
using System.Linq;
using System.Net;
using System.Web;
public class RequestHelpers
{
public static string GetClientIpAddress(HttpRequestBase request)
{
try
{
var userHostAddress = request.UserHostAddress;
// Attempt to parse. If it fails, we catch below and return "0.0.0.0"
// Could use TryParse instead, but I wanted to catch all exceptions
IPAddress.Parse(userHostAddress);
var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(xForwardedFor))
return userHostAddress;
// Get a list of public ip addresses in the X_FORWARDED_FOR variable
var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();
// If we found any, return the last one, otherwise return the user host address
return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
}
catch (Exception)
{
// Always return all zeroes for any failure (my calling code expects it)
return "0.0.0.0";
}
}
private static bool IsPrivateIpAddress(string ipAddress)
{
// http://en.wikipedia.org/wiki/Private_network
// Private IP Addresses are:
// 24-bit block: 10.0.0.0 through 10.255.255.255
// 20-bit block: 172.16.0.0 through 172.31.255.255
// 16-bit block: 192.168.0.0 through 192.168.255.255
// Link-local addresses: 169.254.0.0 through 169.254.255.255 (http://en.wikipedia.org/wiki/Link-local_address)
var ip = IPAddress.Parse(ipAddress);
var octets = ip.GetAddressBytes();
var is24BitBlock = octets[0] == 10;
if (is24BitBlock) return true; // Return to prevent further processing
var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
if (is20BitBlock) return true; // Return to prevent further processing
var is16BitBlock = octets[0] == 192 && octets[1] == 168;
if (is16BitBlock) return true; // Return to prevent further processing
var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
return isLinkLocalAddress;
}
}
And here are some NUnit tests against that code (I'm using Rhino Mocks to mock the HttpRequestBase, which is the M<HttpRequestBase> call below):
using System.Web;
using NUnit.Framework;
using Rhino.Mocks;
using Should;
[TestFixture]
public class HelpersTests : TestBase
{
HttpRequestBase _httpRequest;
private const string XForwardedFor = "X_FORWARDED_FOR";
private const string MalformedIpAddress = "MALFORMED";
private const string DefaultIpAddress = "0.0.0.0";
private const string GoogleIpAddress = "74.125.224.224";
private const string MicrosoftIpAddress = "65.55.58.201";
private const string Private24Bit = "10.0.0.0";
private const string Private20Bit = "172.16.0.0";
private const string Private16Bit = "192.168.0.0";
private const string PrivateLinkLocal = "169.254.0.0";
[SetUp]
public void Setup()
{
_httpRequest = M<HttpRequestBase>();
}
[TearDown]
public void Teardown()
{
_httpRequest = null;
}
[Test]
public void PublicIpAndNullXForwardedFor_Returns_CorrectIp()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(GoogleIpAddress);
}
[Test]
public void PublicIpAndEmptyXForwardedFor_Returns_CorrectIp()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(string.Empty);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(GoogleIpAddress);
}
[Test]
public void MalformedUserHostAddress_Returns_DefaultIpAddress()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(MalformedIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(DefaultIpAddress);
}
[Test]
public void MalformedXForwardedFor_Returns_DefaultIpAddress()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MalformedIpAddress);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(DefaultIpAddress);
}
[Test]
public void SingleValidPublicXForwardedFor_Returns_XForwardedFor()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MicrosoftIpAddress);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(MicrosoftIpAddress);
}
[Test]
public void MultipleValidPublicXForwardedFor_Returns_LastXForwardedFor()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(GoogleIpAddress + "," + MicrosoftIpAddress);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(MicrosoftIpAddress);
}
[Test]
public void SinglePrivateXForwardedFor_Returns_UserHostAddress()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(Private24Bit);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(GoogleIpAddress);
}
[Test]
public void MultiplePrivateXForwardedFor_Returns_UserHostAddress()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
const string privateIpList = Private24Bit + "," + Private20Bit + "," + Private16Bit + "," + PrivateLinkLocal;
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(GoogleIpAddress);
}
[Test]
public void MultiplePublicXForwardedForWithPrivateLast_Returns_LastPublic()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
const string privateIpList = Private24Bit + "," + Private20Bit + "," + MicrosoftIpAddress + "," + PrivateLinkLocal;
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(MicrosoftIpAddress);
}
}
Make the dictionary:
let dic = [
"username":u,
"password":p,
"gems":g ]
Assemble it like this:
var jsonData:Data?
do {
jsonData = try JSONSerialization.data(
withJSONObject: dic,
options: .prettyPrinted)
} catch {
print(error.localizedDescription)
}
Create the request exactly like this, notice it is a "post"
let url = URL(string: "https://blah.com/server/dudes/decide/this")!
var request = URLRequest(url: url)
request.setValue("application/json; charset=utf-8",
forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8",
forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.httpBody = jsonData
Then send, checking for either a networking error (so, no bandwidth etc) or an error response from the server:
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("fundamental networking error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
Fortunately it's now that easy.
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
You have atleast 2 options
Use perl:
perl -e '@T=localtime(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],$T[5]+1900)'
Install GNU date (it's in the sh_utils
package if I remember correctly)
date --date yesterday "+%a %d/%m/%Y" | read dt
echo ${dt}
Not sure if this works, but you might be able to use a negative timezone. If you use a timezone that's 24 hours before your current timezone than you can simply use date
.
From @Jon Skeet comment, really the String
value is "null"
. Following code solved it
if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null"))
I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.
public static void RemoveEverythingButUserInfo()
{
foreach (String o in HttpContext.Current.Session.Keys)
{
if (o != "UserInfoIDontWantToAskForAgain")
keys.Add(o);
}
}
Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple. you can save most of the commonly used objects with it like arrays, integer, strings lists etc
As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
Demo: https://ideone.com/rMF2XA
Note that any of the quoting mechanisms -- \____HERE
or "____HERE"
or '____HERE'
-- will disable all variable interpolation, and turn the here-document into a piece of literal text.
A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
:
I would have thought this would be the most bootstrap-esque way of doing things:
<button type='button' class='btn btn-success col-xs-12'> First buttton baby </button>
All I'm doing is adding the class col-xs-12
to the button.
Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind
. This is an unsafe option, but helpful when testing.
Example from the AngularJS documentation on $sce
:
angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects.
$sceProvider.enabled(false);
});
Attaching the above config section to your app will allow you inject html into ng-html-bind
, but as the doc remarks:
SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.
The answer already given of using find and sed
find -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;
is probably the standard answer. Or you could use perl -pi -e s/foo/bar/g'
instead of the sed
command.
For most quick uses, you may find the command rpl is easier to remember. Here is replacement (foo -> bar), recursively on all files in the current directory:
rpl -R foo bar .
It's not available by default on most Linux distros but is quick to install (apt-get install rpl
or similar).
However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:
Check the README for examples.
More elegant approach using kotlin's extension function
/**
* Converts dp to pixel
*/
val Int.dpToPx: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt()
/**
* Converts pixel to dp
*/
val Int.pxToDp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt()
Usage:
println("16 dp in pixel: ${16.dpToPx}")
println("16 px in dp: ${16.pxToDp}")
If you have the test
binary installed or ksh
has a matching built-in function, you could use it to perform your checks. Usually /bin/[
is a symbolic link to test
:
if [ -e "$file_name" ]; then
echo "File exists"
fi
if [ -z "$used_var" ]; then
echo "Variable is empty"
fi
Try: "\r\n"
Java 7 example:
// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true)))
{
output.printf("%s\r\n", "NEWLINE");
}
catch (Exception e) {}
(this question is a duplicate of In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?) They added the option, 2.1.4 (and maybe a little earlier) has it
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
ticks: {
display: false
}
}]
}
}
}
for large numbers that display with scientific notation set format to just '#'
Following are major difference between HashMap and TreeMap
HashMap does not maintain any order. In other words , HashMap does not provide any guarantee that the element inserted first will be printed first, where as Just like TreeSet , TreeMap elements are also sorted according to the natural ordering of its elements
Internal HashMap implementation use Hashing and TreeMap internally uses Red-Black tree implementation.
HashMap can store one null key and many null values.TreeMap can not contain null keys but may contain many null values.
HashMap take constant time performance for the basic operations like get and put i.e O(1).According to Oracle docs , TreeMap provides guaranteed log(n) time cost for the get and put method.
HashMap is much faster than TreeMap, as performance time of HashMap is constant against the log time TreeMap for most operations.
HashMap uses equals() method in comparison while TreeMap uses compareTo() method for maintaining ordering.
HashMap implements Map interface while TreeMap implements NavigableMap interface.
For Eclipse compiler to work properly you need to remove final/src from the source path and add final/src/main/java instead. This may also solve your problem as now the build directory won't be inside the Java source folder.
Create a temp file first.
File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
return tempFile;
It's a bit of a guess but could the quotes around happy be the problem? There have been some problems in the past where Android would either add or not recognize quotes around an SSID. Try setting up the hosted network connection again, but without the quotes that we see in the output for netsh wlan show hostednetwork
.
For Fedora use:
yum install libstdc++44.i686
You can find out which versions are supported by running:
yum list all | grep libstdc | grep i686
Why do you need to state both 'x' and 'y' before the ':'?
Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to
def f(x, y) : return x + y
just without binding it to a name like f
.
Also how do you make it return multiple arguments?
The same way like with a function. Preferably, you return a tuple:
lambda x, y: (x+y, x-y)
Or a list, or a class, or whatever.
The thing with self.entry_1.bind
should be answered by Demosthenex.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
If you deal with .xlsm
file instead of .xls
you can use the old method. I was trying to modify vbaProject.bin
in .xlsm
several times using DBP->DBx
method by it didn't work, also changing value of DBP
didn't. So I was very suprised that following worked :
1. Save .xlsm
as .xls
.
2. Use DBP->DBx
method on .xls
.
3. Unfortunately some erros may occur when using modified .xls
file, I had to save .xls
as .xlsx
and add modules, then save as .xlsm
.
Surround that select with parentheses.
SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;
this is an out of topic answer, but, for those who are interested, it maybe valuable.
As in @John Kugelman's answer, % is related to job specification. how to efficiently find that? use less's &pattern command, seems man use less pager (not that sure), in man bash type &% then type Enter will only show lines that containing '%', to reshow all, type &. then Enter.
You can use filterfalse function from itertools module
Example
import random
from itertools import filterfalse
random.seed(42)
data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")
clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")
Output:
Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]
Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]
In case of using Firebase, if it doesn't work by putting at the end of import
statements then you can try to put that inside one of the life-cycle method, that is, you can put it inside componentWillMount()
.
componentWillMount() {
const firebase = require('firebase');
firebase.initializeApp({
//Credentials
});
}
Use print("use this bracket -sample text")
In Python 3 print "Hello world"
gives invalid syntax error.
To display string content in Python3 have to use this ("Hello world")
brackets.
I know this is old but you should also try Zombie.js. A headless browser which is insanely fast and ideal for testing !
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
echo "echo "we are now going to work with ${ser}" " >> $servfile
Escape all " within quotes with \. Do this with variables like \$servicetest too:
echo "echo \"we are now going to work with \${ser}\" " >> $servfile
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile
For downloading pdf from server , add below code in your service class. Hope this is helpful for you.
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName + ".pdf");
intent = new Intent(Intent.ACTION_VIEW);
//Log.e("pathOpen", file.getPath());
Uri contentUri;
contentUri = Uri.fromFile(file);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 24) {
Uri apkURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
intent.setDataAndType(apkURI, "application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
intent.setDataAndType(contentUri, "application/pdf");
}
And yes , don't forget to add permissions and provider in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>
For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.
The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval]
(string or int) which then allows you to refer to an existing record.
Few ways of declaring a typed array in TypeScript
are
const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];
// or, if you have values to initialize
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];
On *nix, unlike Windows, the current directory is usually not in your $PATH
variable. So the current directory is not searched when executing commands. You don't need ./
for running applications because these applications are in your $PATH; most likely they are in /bin
or /usr/bin
.
As per documentation:
Your workaround would be to create a view for each of your subqueries.
Then access those views from within your view view_credit_status
In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.
Another thing which might be causing this is a 'weird' symbol in your file and directory names. All umlaut (äöå) and other (éóâ etc) characters should be removed from the file and folder names. I've had this same issue sometimes because of these characters.
Here is my method for that: Loading Custom UITableViewCells from XIB Files… Yet Another Method
The idea is to create a SampleCell subclass of the UITableViewCell
with a IBOutlet UIView *content
property and a property for each custom subview you need to configure from the code. Then to create a SampleCell.xib file. In this nib file, change the file owner to SampleCell. Add a content UIView
sized to fit your needs. Add and configure all the subviews (label, image views, buttons, etc) you want. Finally, link the content view and the subviews to the file owner.
Well, timing to the rescue again. It seems switch
is generally faster than if
statements.
So that, and the fact that the code is shorter/neater with a switch
statement leans in favor of switch
:
# Simplified to only measure the overhead of switch vs if
test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}
test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}
system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:
> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202
> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430
Final Update Here's showing how versatile switch
is:
switch(type, case1=1, case2=, case3=2.5, 99)
This maps case2
and case3
to 2.5
and the (unnamed) default to 99
. For more information, try ?switch
I'd recommend reading that PEP the error gives you. The problem is that your code is trying to use the ASCII encoding, but the pound symbol is not an ASCII character. Try using UTF-8 encoding. You can start by putting # -*- coding: utf-8 -*-
at the top of your .py file. To get more advanced, you can also define encodings on a string by string basis in your code. However, if you are trying to put the pound sign literal in to your code, you'll need an encoding that supports it for the entire file.
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
Here's a good example. I use it to rename the variable because the JSON is coming from a .Net
environment where properties start with an upper-case letter.
public class Parameter {
@JsonProperty("Name")
public String name;
@JsonProperty("Value")
public String value;
}
This correctly parses to/from the JSON:
"Parameter":{
"Name":"Parameter-Name",
"Value":"Parameter-Value"
}
you can simply use onBackPressed();
or if you are using fragment you can use getActivity().onBackPressed()
And with Prototype:
$('yourDivId').setStyle({top: '100px', left:'80px'});
I also deleted my eclipse console by mistake, however what worked best for me was to type "console" in the "Quick Access" box to the right of the menu and that brought it right back! I'm running version 4.2.1, not sure if this Quick Accessbox is available in other versions.
This is old, just update new tidyverse workflow not mentioned above.
library(tidyverse)
jobsAFAM1 <- tibble(
date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
Percent.Change = runif(5, 0,1)
) %>%
mutate(serial='jobsAFAM1')
jobsAFAM2 <- tibble(
date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
Percent.Change = runif(5, 0,1)
) %>%
mutate(serial='jobsAFAM2')
jobsAFAM <- bind_rows(jobsAFAM1, jobsAFAM2)
ggplot(jobsAFAM, aes(x=date, y=Percent.Change, col=serial)) + geom_line()
@Chris Njuguna
tidyr::gather() is the one in tidyverse workflow to turn wide dataframe to long tidy layout, then ggplot could plot multiple serials.
// Safari uses pre-calculated pixels, so use this feature to detect Safari
var canva = document.createElement('canvas');
var ctx = canva.getContext("2d");
var img = ctx.getImageData(0, 0, 1, 1);
var pix = img.data; // byte array, rgba
var isSafari = (pix[3] != 0); // alpha in Safari is not zero
Yes it is, and you can also use it like this
<button>Click here to<br/> start playing</button>
if you want to make the break yourself.
Try with Shadow( Like border ) + Border
border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;
I have quite similar problem. And I came up with following solution.
Using notifyDataSetChanged
is a bad idea. You should be more specific, then RecyclerView
will save scroll state for you.
For example, if you only need to refresh, or in other words, you want each view to be rebinded, just do this:
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
I had the same problem, but I also wanted ".25" to be a valid decimal number. Here is my solution using JavaScript:
function isNumber(v) {
// [0-9]* Zero or more digits between 0 and 9 (This allows .25 to be considered valid.)
// ()? Matches 0 or 1 things in the parentheses. (Allows for an optional decimal point)
// Decimal point escaped with \.
// If a decimal point does exist, it must be followed by 1 or more digits [0-9]
// \d and [0-9] are equivalent
// ^ and $ anchor the endpoints so tthe whole string must match.
return v.trim().length > 0 && v.trim().match(/^[0-9]*(\.[0-9]+)?$/);
}
Where my trim() method is
String.prototype.trim = function() {
return this.replace(/(^\s*|\s*$)/g, "");
};
Matthew DesVoigne
There is a file in your git root directory named .gitignore
. It's a file, not a command. You just need to insert the names of the files that you want to ignore, and they will automatically be ignored. For example, if you wanted to ignore all emacs autosave files, which end in ~
, then you could add this line:
*~
If you want to remove the unwanted files from your branch, you can use git add -A
, which "removes files that are no longer in the working tree".
Note: What I called the "git root directory" is simply the directory in which you used git init
for the first time. It is also where you can find the .git
directory.
extension UILabel{
func setSubTextColor(pSubString : String, pColor : UIColor){
let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!);
let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
if range.location != NSNotFound {
attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
}
self.attributedText = attributedString
}
}
apk
file in our mobile, it is comprised of
multiple useful blocks such as, Activity
s, Service
s and
others.Application
regardless of
the Activity
the user is using,Application
,Cursor
and closing it again and
again is not good on performance,Intent
s to pass the data but it's clumsy and activity
itself may not exist at a certain scenario depending on the memory-availability.Application
,Application
to start certain things like analytics
etc. since the application class is started before Activity
s or
Services
s are being run,Press Ctrl + Alt + S then choose Keymap
and finally find the keyboard shortcut by type back
word in search bar at the top right corner.
The CSPROJ
file, saved in XML format, stores all the references for your project including your compilation options. There is also an SLN file, which stores information about projects that make up your solution.
If you are using Visual Studio and you have the need to view or edit your CSPROJ
file, while in Visual Studio, you can do so by following these simple steps:
Deleting directly from file system is not safe. You can run the below script to delete all builds from all jobs ( recursively ).
def numberOfBuildsToKeep = 10
Jenkins.instance.getAllItems(AbstractItem.class).each {
if( it.class.toString() != "class com.cloudbees.hudson.plugins.folder.Folder" && it.class.toString() != "class org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject") {
println it.name
builds = it.getBuilds()
for(int i = numberOfBuildsToKeep; i < builds.size(); i++) {
builds.get(i).delete()
println "Deleted" + builds.get(i)
}
}
}
If you try using:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))
and receive an error :
"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"
This means the DATE_FIELD
is not specified in seconds.
In my case, it was milli seconds - EPOCH time
.
The conversion worked using below:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms'))
The problem is that the DIV that should center your tables has no width defined. By default, DIVs are block elements and take up the entire width of their parent - in this case the entire document (propagating through the #outer DIV), so the automatic margin style has no effect.
For this technique to work, you simply have to set the width of the div that has margin:auto to anything but "auto" or "inherit" (either a fixed pixel value or a percentage).
If optimal performance is not a requirement and you just want something dead simple, you can define a basic function to test each character using the string class's built in "isspace" method:
def remove_space(input_string):
no_white_space = ''
for c in input_string:
if not c.isspace():
no_white_space += c
return no_white_space
Building the no_white_space
string this way will not have ideal performance, but the solution is easy to understand.
>>> remove_space('strip my spaces')
'stripmyspaces'
If you don't want to define a function, you can convert this into something vaguely similar with list comprehension. Borrowing from the top answer's join
solution:
>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'
The second (assuming you means CONTAINS
, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.
The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.
The CONTAINS
query should be:
SELECT * FROM table WHERE CONTAINS(Column, 'test');
jEdit:
With the keyboard: press Alt-\ (Opt-\ in Mac OS X) to toggle between rectangular and normal selection mode; then use Shift plus arrow keys to extend selection. You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.
With the mouse: Either use Alt-\ (Opt-\ in Mac OS X) as above to toggle rectangular selection mode, then drag as usual; or Ctrl-drag (Cmd-drag in Mac OS X). You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.
Actually, you can even make a non-rectangular selection the normal way and then hit Alt-\ (Opt-\ in Mac OS X) to convert it into a rectangular one.
You want "rbind".
b$b <- NA
new <- rbind(a, b)
rbind requires the data frames to have the same columns.
The first line adds column b to data frame b.
Results
> a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
> a
a b c
1 0 3 6
2 1 4 7
3 2 5 8
> b <- data.frame(a=c(9,10,11), c=c(12,13,14))
> b
a c
1 9 12
2 10 13
3 11 14
> b$b <- NA
> b
a c b
1 9 12 NA
2 10 13 NA
3 11 14 NA
> new <- rbind(a,b)
> new
a b c
1 0 3 6
2 1 4 7
3 2 5 8
4 9 NA 12
5 10 NA 13
6 11 NA 14
the squeel
gem provides an incredibly easy way to accomplish this (prior to this I used something like @coloradoblue's method):
names = ["Kroger", "Walmart", "Target", "Aldi"]
matching_stores = Grocery.where{name.like_any(names)}
Now a days .Net is run in multiple platforms,like linux ,Mac os etc. but mono is not fully platform independent ,Because to deploy .NET in another OS required third party software.so it is not like java platform independent.
Mono is running in different platform ,because of JIT is there in different os.
Mono is not fully success in moonlight(silver light in .NET) .Not only Research is going on.
Mono uses XSP2 server or apache . some of the big companies are using this project,Some of the robotic project are also running on mono.
For more details http://www.mono-project.com/Main_Page.
underscore.js provides the following method to find out if something is really an object:
_.isObject = function(obj) {
return obj === Object(obj);
};
UPDATE
Because of a previous bug in V8 and minor micro speed optimization, the method looks as follows since underscore.js 1.7.0 (August 2014):
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
From MySQL 5.7 Reference Manual.
Syntax :
ALTER TABLE t1 CHANGE a b DATATYPE;
e.g. : for Customer TABLE having COLUMN customer_name, customer_street, customercity.
And we want to change customercity TO customer_city :
alter table customer change customercity customer_city VARCHAR(225);
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});