taskschd.msc
is available in Windows Vista and later.
http://technet.microsoft.com/en-us/library/cc721871.aspx
I could have sworn I'd seen a little task scheduler GUI like you're talking about prior to Vista, but maybe I was thinking of the "Add Scheduled Task" wizard.
You might have to settle for opening the scheduled tasks explorer with this command:
control schedtasks
I couldn't find any way to launch the "Add Scheduled Task" wizard from the command line, unfortunately (there has to be a way!)
I add some more properties to the CSS. Like so:
div#over {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
-ms-align-items: center;
display: -webkit-flex;
display: -ms-flex;
display: flex;
}
If you add an AssemblyInfo class to your project and amend the AssemblyVersion
attribute to end with an asterisk, for example:
[assembly: AssemblyVersion("2.10.*")]
Visual studio will increment the final number for you according to these rules (thanks galets, I had that completely wrong!)
To reference this version in code, so you can display it to the user, you use reflection
. For example,
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
DateTime buildDate = new DateTime(2000, 1, 1)
.AddDays(version.Build).AddSeconds(version.Revision * 2);
string displayableVersion = $"{version} ({buildDate})";
It's also worth noting that if both AssemblyVersion
and AssemblyFileVersion
are specified, you won't see this on your .exe.
Setting only the 4th number to be *
can be bad, as the version won't always increment.
The 3rd number is the number of days since the year 2000, and the 4th number is the number of seconds since midnight (divided by 2) [IT IS NOT RANDOM]. So if you built the solution late in a day one day, and early in a day the next day, the later build would have an earlier version number. I recommend always using X.Y.*
instead of X.Y.Z.*
because your version number will ALWAYS increase this way.
(this thread begun in 2009)
The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation.
See this SO answer which explains how to remove determinism (https://stackoverflow.com/a/58101474/1555612)
You can do it using foreach loop.
$arrayVal = array(1,2,3,1,2,3,1,2,3,4,4,5,6,4,5,6,88);
$set_array = array();
foreach ($array as $value) {
$set_array[$value]++;
}
print_r($set_array);
Output :-
Array( [1] => 3
[2] => 3
[3] => 3
[4] => 3
[5] => 2
[6] => 2
[88] => 1
)
You are trying to link objects compiled by different versions of the compiler. That's not supported in modern versions of VS, at least not if you are using the C++ standard library. Different versions of the standard library are binary incompatible and so you need all the inputs to the linker to be compiled with the same version. Make sure you re-compile all the objects that are to be linked.
The compiler error names the objects involved so the information the the question already has the answer you are looking for. Specifically it seems that the static library that you are linking needs to be re-compiled.
So the solution is to recompile Projectname1.lib with VS2012.
Python code goes through 2 stages. First step compiles the code into .pyc files which is actually a bytecode. Then this .pyc file(bytecode) is interpreted using CPython interpreter. Please refer to this link. Here process of code compilation and execution is explained in easy terms.
Yes.
It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.
The following example will show you the use of multiple classes.
The first class makes the text color
red.
The second class makes the background-color
blue.
See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.
Result: multiple CSS statements in different classes will stack up.
You can read more about CSS Specificity.
.class1 {
color:red;
}
.class2 {
background-color:blue;
}
<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>
Try this:
import java.util.Scanner;
/* Logic: Consider first character in the string and start counting occurrence of
this character in the entire string. Now add this character to a empty
string "temp" to keep track of the already counted characters.
Next start counting from next character and start counting the character
only if it is not present in the "temp" string( which means only if it is
not counted already)
public class Counting_Occurences {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String");
String str=input.nextLine();
int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i); // take one character (c) in string
for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{
count=count+1;
}
}
if(temp.indexOf(c)==-1) // if it is not already counted
{
temp=temp+c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count=0;
}
}
}
There is number of methods to allocate an array of intrinsic type and all of these method are correct, though which one to choose, depends...
Manual initialisation of all elements in loop
int* p = new int[10];
for (int i = 0; i < 10; i++)
p[i] = 0;
Using std::memset
function from <cstring>
int* p = new int[10];
std::memset(p, 0, sizeof *p * 10);
Using std::fill_n
algorithm from <algorithm>
int* p = new int[10];
std::fill_n(p, 10, 0);
Using std::vector
container
std::vector<int> v(10); // elements zero'ed
If C++11 is available, using initializer list features
int a[] = { 1, 2, 3 }; // 3-element static size array
vector<int> v = { 1, 2, 3 }; // 3-element array but vector is resizeable in runtime
Dim sHostName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
Method Object JComboBox.getSelectedItem()
returns a value that is wrapped by Object
type so you have to cast it accordingly.
Syntax:
YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();
my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
print([l.strip() for l in my_list])
Output:
['this', 'is', 'a', 'list', 'of', 'words']
This works for me.
emoji.setBackground(null);
This crashes in runtime.
viewToUse.setImageResource(android.R.color.transparent);
@will's method is the best. Just add few lines about the details for the people didn't use ExcelDNA before like me.
Download Excel-DNA IntelliSense from https://github.com/Excel-DNA/IntelliSense/releases
There are two version, one is for 64, check your Excel version. For my case, I'm using 64 version.
Open Excel/Developer/Add-Ins/Browse and select ExcelDna.IntelliSense64.xll.
Insert a new sheet, change name to "IntelliSense", add function description, as https://github.com/Excel-DNA/IntelliSense/wiki/Getting-Started
Then enjoy! :)
You do it like this:
df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
colClasses = as.list(apply(df, 2, class))
needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
colClasses[!names(colClasses) %in% needCols] = list(NULL)
df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)
In 2019 you can use querySelector for that.
It's supported by most browsers (https://caniuse.com/#search=querySelector)
document.querySelector('body').appendChild(i);
Lets suppose you have N elements in a heap. Then its height would be Log(N)
Now you want to insert another element, then the complexity would be : Log(N), we have to compare all the way UP to the root.
Now you are having N+1 elements & height = Log(N+1)
Using induction technique it can be proved that the complexity of insertion would be ?logi.
Now using
log a + log b = log ab
This simplifies to : ?logi=log(n!)
which is actually O(NlogN)
But
we are doing something wrong here, as in all the case we do not reach at the top. Hence while executing most of the times we may find that, we are not going even half way up the tree. Whence, this bound can be optimized to have another tighter bound by using mathematics given in answers above.
This realization came to me after a detail though & experimentation on Heaps.
Based on antoinepairet's comment/example:
Using uib-collapse
attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse" uib-collapse="navCollapsed">
<ul class="nav navbar-nav">
...
</ul>
</div>
</nav>
I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:
The only variation from the official bootstrap example is the addition of ng-
attributes noted by comments, below:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- note the ng-class here -->
<div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
...
Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)
This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!
I figured it out myself with the help of someone's answer. But he deleted it for some reason.
Here's the solution:
Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact
$(function(){
var windowH = $(window).height();
var wrapperH = $('#wrapper').height();
if(windowH > wrapperH) {
$('#wrapper').css({'height':($(window).height())+'px'});
}
$(window).resize(function(){
var windowH = $(window).height();
var wrapperH = $('#wrapper').height();
var differenceH = windowH - wrapperH;
var newH = wrapperH + differenceH;
var truecontentH = $('#truecontent').height();
if(windowH > truecontentH) {
$('#wrapper').css('height', (newH)+'px');
}
})
});
There are methods like WriteAllText
in the File
class for common operations on files.
Use the MapPath
method to get the physical path for a file in your web application.
File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);
Iterations
Method 1: forEach
method
messages.forEach(function(message) {
console.log(message);
}
Method 2: for..of
method
for(let message of messages){
console.log(message);
}
Note: This method might not work with objects, such as:
let obj = { a: 'foo', b: { c: 'bar', d: 'daz' }, e: 'qux' }
Method 2: for..in
method
for(let key in messages){
console.log(messages[key]);
}
Take a look at the ISNULL function. It helps you replace NULL values for other values. http://msdn.microsoft.com/en-us/library/ms184325.aspx
Request.QueryString
returns you a collection of Key/Value pairs representing the Query String. Not a String. Don't think that would cause a Object Reference error though. The reason your getting that is because as Mauro pointed out in the comments. It's QueryString and not Querystring.
Try:
Request.QueryString.ToString();
or
<%
string URL = Request.Url.AbsoluteUri
System.Net.WebClient wc = new System.Net.WebClient();
string data = wc.DownloadString(URL);
Response.Output.Write(data);
%>
Same as your code but Request.Url.AbsoluteUri
will return the full path, including the query string.
This is what I got from the Spring 3.0.x Reference Manual :-
Tip
If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
As a specific consequence of this semantic difference, beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.
@Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.
Local to ISO 8601:
import datetime
datetime.datetime.now().isoformat()
>>> 2020-03-20T14:28:23.382748
UTC to ISO 8601:
import datetime
datetime.datetime.utcnow().isoformat()
>>> 2020-03-20T01:30:08.180856
Local to ISO 8601 without microsecond:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:30:43
UTC to ISO 8601 with TimeZone information (Python 3):
import datetime
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
>>> 2020-03-20T01:31:12.467113+00:00
UTC to ISO 8601 with Local TimeZone information without microsecond (Python 3):
import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:31:43+13:00
Local to ISO 8601 with TimeZone information (Python 3):
import datetime
datetime.datetime.now().astimezone().isoformat()
>>> 2020-03-20T14:32:16.458361+13:00
Notice there is a bug when using astimezone()
on utc time. This gives an incorrect result:
datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result
For Python 2, see and use pytz.
Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.
How about:
d = d.applymap(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)
The applymap
function applies a function to every cell of the dataframe.
This kind of logic could be implemented using EXISTS
:
CREATE TABLE tab(a INT, b VARCHAR(10));
INSERT INTO tab(a,b) VALUES(1,'a'),(1, NULL),(NULL, 'a'),(2,'b');
Query:
DECLARE @a INT;
--SET @a = 1; -- specific NOT NULL value
--SET @a = NULL; -- NULL value
--SET @a = -1; -- all values
SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1');
It could be extended to contain multiple params:
SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1')
AND EXISTS(SELECT t.b INTERSECT SELECT @b UNION SELECT @a WHERE @b = '-1');
<%!
private void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut)
{
try{ myOut.println("<div>"+Bits+"</div>"); }
catch(Exception eek) { }
}
%>
...
<%
myFunc("more difficult than it should be",out);
%>
Try this, it worked for me!
Other option is to configure the logout to be a GET instead a DELETE, you can do that adding the following line on /config/initializers/devise.rb
config.sign_out_via = :get
But as Steve Klabnik wrote on his blog (http://blog.steveklabnik.com/2011/12/11/devise-actioncontroller-routingerror-no-route-matches-get-slash-users-slash-sign-out.html) try to use DELETE because of the semantic of this method.
Skip the first section if you have already installed Miniconda successfully.
Installation of Miniconda on Raspberry Pi
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh
Accept the license agreement with yes
When asked, change the install location: /home/pi/miniconda3
Do you wish the installer to prepend the Miniconda3 install location
to PATH in your /root/.bashrc ? yes
Now add the install path to the PATH variable:
sudo nano /home/pi/.bashrc
Go to the end of the file .bashrc and add the following line:
export PATH="/home/pi/miniconda3/bin:$PATH"
Save the file and exit.
To test if the installation was successful, open a new terminal and enter
conda
If you see a list with commands you are ready to go.
But how can you use Python versions greater than 3.4 ?
Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi
After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:
First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):
conda config --add channels rpi
Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:
conda install python=3.5
conda install python=3.6
Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:
conda create --name py35 python=3.5
The new environment "py35" can now be activated:
source activate py35
Using Python 3.7 on Raspberry Pi
Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel.
If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:
Python3.7 app-that-needs-python37.py
I hope this solution will work for you too!
It is true, going forward you are expected to do all OTA deployments over https going forward with iOS7.1. Shame on Apple for not documenting this.
For those of you that are looking for a better in-house solution than relying on dropbox or having to fork out cash for a certificate you can have a solution if you follow the steps outlined in tip #5 here: http://blog.httpwatch.com/2013/12/12/five-tips-for-using-self-signed-ssl-certificates-with-ios/
The gist of it is this:
This is not the same as just doing a self-signed certificate, in this solution you are also acting as your own private Certificate Authority. If your root certificate that is installed on your Apple device is not marked as Trusted (green) then something is wrong. Do it over.
This absolutely works.
Update: 3/13/2014 - I have provided a small command line utility that simplifies this entire process. You can get it at: https://github.com/deckarep/EasyCert/releases
Within your <jre location>\lib\security\java.policy
try adding:
grant {
permission java.security.AllPermission;
};
And see if it allows you. If so, you will have to add more granular permissions.
See:
Java 8 Documentation for java.policy files
and
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html
Updated
Add &mute=1
to the end of your url.
Your new code would be:
<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?rel=0&autoplay=1&mute=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
_x000D_
You can use java.util.Arrays.binarySearch to find an element in an array or to check for its existence:
import java.util.Arrays;
...
char[] array = new char[] {'a', 'x', 'm'};
Arrays.sort(array);
if (Arrays.binarySearch(array, 'm') >= 0) {
System.out.println("Yes, m is there");
}
Be aware that for binarySearch to work correctly, the array needs to be sorted. Hence the call to Arrays.sort() in the example. If your data is already sorted, you don't need to do that. Thus, this isn't strictly a one-liner if you need to sort your array first. Unfortunately, Arrays.sort() does not return a reference to the array - thus it is not possible to combine sort and binarySearch (i.e. Arrays.binarySearch(Arrays.sort(myArray), key)) does not work).
If you can afford the extra allocation, using Arrays.asList() seems cleaner.
You can do this by writing a manifest for your jar. Have a look at the Class-Path header. Eclipse has an option for choosing your own manifest on export.
The alternative is to add the dependency to the classpath at the time you invoke the application:
win32: java.exe -cp app.jar;dependency.jar foo.MyMainClass
*nix: java -cp app.jar:dependency.jar foo.MyMainClass
If you want to ignore lines with only whitespace:
if not line.strip():
... do something
The empty string is a False value.
Or if you really want only empty lines:
if line in ['\n', '\r\n']:
... do something
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
My guess is, that the @Value
can not cope with "complex" types. You can go with a prop class like this:
@Component
@ConfigurationProperties('ignore')
class IgnoreSettings {
List<String> filenames
}
Please note: This code is Groovy - not Java - to keep the example short! See the comments for tips how to adopt.
See the complete example https://github.com/christoph-frick/so-springboot-yaml-string-list
Don't include header.php. You should not output HTML when you are going to redirect.
Make a new file, eg. "pre.php". Put this in it:
<?php
include('class.user.php');
include('class.Connection.php');
?>
Then in header.php, include that, in stead of including the two other files. In form.php, include pre.php in stead of header.php.
declare @ids nvarchar(1000)
set @ids = '100,2,3,4,5' --Parameter passed
set @ids = ',' + @ids + ','
select *
from TableName
where charindex(',' + CAST(Id as nvarchar(50)) + ',', @ids) > 0
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.
With reference to man ssh-keygen
, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.
In conclusion, a 2048 bit RSA key is currently the best choice.
Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.
To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.
I'd also like to point out that you can name each checkbox a different name, and have that name part of the actionresults parameters.
Example,
View:
<%= Html.CheckBox("Rs232CheckBox", false, new { @id = "rs232" })%>RS-232
<%= Html.CheckBox("Rs422CheckBox", false, new { @id = "rs422" })%>RS-422
Controller:
public ActionResults MyAction(bool Rs232CheckBox, bool Rs422CheckBox) {
...
}
The values from the view are passed to the action since the names are the same.
I know this solution isn't ideal for your project, but I thought I'd throw the idea out there.
If you want to get all those information, you might want to read this:
http://php.net/manual/en/function.get-browser.php
You can run the sample code and you'll see how it works:
<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
?>
The above example will output something similar to:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3
Array
(
[browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
[browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
[parent] => Firefox 0.9
[platform] => WinXP
[browser] => Firefox
[version] => 0.9
[majorver] => 0
[minorver] => 9
[cssversion] => 2
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[vbscript] =>
[javascript] => 1
[javaapplets] => 1
[activexcontrols] =>
[cdf] =>
[aol] =>
[beta] => 1
[win16] =>
[crawler] =>
[stripper] =>
[wap] =>
[netclr] =>
)
public static void showCustomAlertDialog(Context context, String name,
String id, String desc, String fromDate, String toDate,
String resions) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dialog, null);
alertDialogBuilder.setView(view);
alertDialogBuilder.setCancelable(false);
final AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
txt_empId = (TextView) view.findViewById(R.id.txt_dialog_empcode);
txt_empName = (TextView) view.findViewById(R.id.txt_dialog_empname);
txt_desc = (TextView) view.findViewById(R.id.txt_dialog_desc);
txt_startDate = (TextView) view.findViewById(R.id.txt_dialog_startDate);
txt_resions = (TextView) view.findViewById(R.id.txt_dialog_endDate);
txt_empId.setTypeface(Utils.setLightTypeface(context));
txt_empName.setTypeface(Utils.setLightTypeface(context));
txt_desc.setTypeface(Utils.setLightTypeface(context));
txt_startDate.setTypeface(Utils.setLightTypeface(context));
txt_resions.setTypeface(Utils.setLightTypeface(context));
txt_empId.setText(id);
txt_empName.setText(name);
txt_desc.setText(desc);
txt_startDate.setText(fromDate + "\t to \t" + toDate);
txt_resions.setText(resions);
btn_accept = (Button) view.findViewById(R.id.btn_dialog_accept);
btn_reject = (Button) view.findViewById(R.id.btn_dialog_reject);
btn_cancel = (Button) view.findViewById(R.id.btn_dialog_cancel);
btn_accept.setTypeface(Utils.setBoldTypeface(context));
btn_reject.setTypeface(Utils.setBoldTypeface(context));
btn_cancel.setTypeface(Utils.setBoldTypeface(context));
btn_cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
Handle should do the trick.
Ever wondered which program has a particular file or directory open? Now you can find out. Handle is a utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.
One possible solution that worked for me was simply to close the window in browser where I had the corresponding "http://localhost:3000/" script running.
Improvement to kaiser's answer:
var myEl = $document.find('#some-id');
Don't forget to inject $document
into your directive
That is correct. When you do that you are casting it it into an employee
object, so that means you cannot access anything manager specific.
Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:
if (employee is Manager)
{
Manager m = (Manager)employee;
//do something with it
}
or with the as
operator like this:
Manager m = (employee as Manager);
if (m != null)
{
//do something with it
}
If anything is unclear I'll be happy to correct it!
It's possible to utilize custom command line options in Gradle to end up with something like:
./gradlew printPet --pet="puppies!"
However, custom command line options in Gradle are an incubating feature.
To end up with something like this follow the instructions here:
import org.gradle.api.tasks.options.Option;
public class PrintPet extends DefaultTask {
private String pet;
@Option(option = "pet", description = "Name of the cute pet you would like to print out!")
public void setPet(String pet) {
this.pet = pet;
}
@Input
public String getPet() {
return pet;
}
@TaskAction
public void print() {
getLogger().quiet("'{}' are awesome!", pet);
}
}
Then register it:
task printPet(type: PrintPet)
Now you can do:
./gradlew printPet --pet="puppies"
output:
Puppies! are awesome!
open class PrintPet : DefaultTask() {
@Suppress("UnstableApiUsage")
@set:Option(option = "pet", description = "The cute pet you would like to print out")
@get:Input
var pet: String = ""
@TaskAction
fun print() {
println("$pet are awesome!")
}
}
then register the task with:
tasks.register<PrintPet>("printPet")
You don't really need a specific client, it's fairly simple with most libraries. For example in jQuery you can just call the generic $.ajax
function with the type of request you want to make:
$.ajax({
url: 'http://example.com/',
type: 'PUT',
data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
success: function() { alert('PUT completed'); }
});
You can replace PUT
with GET
/POST
/DELETE
or whatever.
If the view item performs the same operation, you can use the @+id
for each entry in any layout because during the compilation of multiple @+id/foo
the R.java
file only creates one enumeration. So for example, if I have a save button on each page that performs the same operation, I use android:id="@+id/button_save"
in each layout. The R.java file only has one entry for the button_save.
You should always include the table name in the SQL query when dealing with associations.
Indeed if another table has the user_id
column and you join both tables, you will have an ambiguous column name in the SQL query (i.e. troubles).
So, in your example:
GroupUser.where("groups_users.user_id != ?", me)
Or a bit more verbose:
GroupUser.where("#{table_name}.user_id IS NOT ?", me)
Note that if you are using a hash, you don't need to worry about that because Rails takes care of it for you:
GroupUser.where(user: me)
In Rails 4, as said by @dr4k3, the query method not
has been added:
GroupUser.where.not(user: me)
As of now, Google official Text-to-Speech service is available at https://cloud.google.com/text-to-speech/
It's free for the first 4 million characters.
I had a similar situation, and the following process worked for me:
In the terminal, type
vi ~/.profile
Then add this line in the file, and save
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home
where version is the one on your computer, such as 1.7.0_25
Exit the editor, then type the following command make it become effective
source ~/.profile
Then type java -version to check the result
java -version
What is .profile? From:http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515
.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.
Let's start from the beginning and explore this question.
So let's suppose you have two lists:
list_1=['01','98']
list_2=[['01','98']]
And we have to copy both lists, now starting from the first list:
So first let's try by setting the variable copy
to our original list, list_1
:
copy=list_1
Now if you are thinking copy copied the list_1, then you are wrong. The id
function can show us if two variables can point to the same object. Let's try this:
print(id(copy))
print(id(list_1))
The output is:
4329485320
4329485320
Both variables are the exact same argument. Are you surprised?
So as we know python doesn't store anything in a variable, Variables are just referencing to the object and object store the value. Here object is a list
but we created two references to that same object by two different variable names. This means that both variables are pointing to the same object, just with different names.
When you do copy=list_1
, it is actually doing:
Here in the image list_1 and copy are two variable names but the object is same for both variable which is list
So if you try to modify copied list then it will modify the original list too because the list is only one there, you will modify that list no matter you do from the copied list or from the original list:
copy[0]="modify"
print(copy)
print(list_1)
output:
['modify', '98']
['modify', '98']
So it modified the original list :
Now let's move onto a pythonic method for copying lists.
copy_1=list_1[:]
This method fixes the first issue we had:
print(id(copy_1))
print(id(list_1))
4338792136
4338791432
So as we can see our both list having different id and it means that both variables are pointing to different objects. So what actually going on here is:
Now let's try to modify the list and let's see if we still face the previous problem:
copy_1[0]="modify"
print(list_1)
print(copy_1)
The output is:
['01', '98']
['modify', '98']
As you can see, it only modified the copied list. That means it worked.
Do you think we're done? No. Let's try to copy our nested list.
copy_2=list_2[:]
list_2
should reference to another object which is copy of list_2
. Let's check:
print(id((list_2)),id(copy_2))
We get the output:
4330403592 4330403528
Now we can assume both lists are pointing different object, so now let's try to modify it and let's see it is giving what we want:
copy_2[0][1]="modify"
print(list_2,copy_2)
This gives us the output:
[['01', 'modify']] [['01', 'modify']]
This may seem a little bit confusing, because the same method we previously used worked. Let's try to understand this.
When you do:
copy_2=list_2[:]
You're only copying the outer list, not the inside list. We can use the id
function once again to check this.
print(id(copy_2[0]))
print(id(list_2[0]))
The output is:
4329485832
4329485832
When we do copy_2=list_2[:]
, this happens:
It creates the copy of list but only outer list copy, not the nested list copy, nested list is same for both variable, so if you try to modify the nested list then it will modify the original list too as the nested list object is same for both lists.
What is the solution? The solution is the deepcopy
function.
from copy import deepcopy
deep=deepcopy(list_2)
Let's check this:
print(id((list_2)),id(deep))
4322146056 4322148040
Both outer lists have different IDs, let's try this on the inner nested lists.
print(id(deep[0]))
print(id(list_2[0]))
The output is:
4322145992
4322145800
As you can see both IDs are different, meaning we can assume that both nested lists are pointing different object now.
This means when you do deep=deepcopy(list_2)
what actually happens:
Both nested lists are pointing different object and they have separate copy of nested list now.
Now let's try to modify the nested list and see if it solved the previous issue or not:
deep[0][1]="modify"
print(list_2,deep)
It outputs:
[['01', '98']] [['01', 'modify']]
As you can see, it didn't modify the original nested list, it only modified the copied list.
I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.
You could use the islice
from itertools to create an iterator over a smaller portion of the list. Then you can append entries to the list without impacting the items you're iterating over:
islice(myarr, 0, len(myarr)-1)
Even better, you don't even have to iterate over all the elements. You can increment a step size.
You have to pass the arguments in the terminal in order to store them in 'argv'. This variable holds the arguments you pass to your Python script when you run it. It later unpacks the arguments and store them in different variables you specify in the program e.g.
script, first, second = argv
print "Your file is:", script
print "Your first entry is:", first
print "Your second entry is:" second
Then in your command line you have to run your code like this,
$python ex14.py Hamburger Pizza
Your output will look like this:
Your file is: ex14.py
Your first entry is: Hamburger
Your second entry is: Pizza
You can check one setting in target setting Apple LLVM Compiler 4.1 Code Generation Section Generate Debug Symbol = YES
Do you want to order it?
Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;
SELECT TOP 10 * FROM TABLE_NAME ORDER BY ORDERED_UNIQUE_COLUMN DESC
ORDERED_UNIQUE_COLUMN could be your incrementing primary key or a timestamp
An alternative if the concern is to hide the real email address...If you are committing to Github you don't need a real email you can use <username>@users.noreply.github.com
Regardless of using Github or not, you probably first want change your committer details (on windows use SET GIT_...
)
GIT_COMMITTER_NAME='username'
GIT_COMMITTER_EMAIL='[email protected]'
Then set the author
git commit --author="username <[email protected]>"
https://help.github.com/articles/keeping-your-email-address-private
Like the other answers said, sp_reset_connection
indicates that connection pool is being reused. Be aware of one particular consequence!
Jimmy Mays' MSDN Blog said:
sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.
UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.
ref: SQL Server: Isolation level leaks across pooled connections
Here is some additional information:
What does sp_reset_connection do?
Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.
sp_reset_connection resets the following aspects of a connection:
All error states and numbers (like @@error)
Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query
Waits for any outstanding I/O operations that is outstanding
Frees any held buffers on the server by the connection
Unlocks any buffer resources that are used by the connection
Releases all allocated memory owned by the connection
Clears any work or temporary tables that are created by the connection
Kills all global cursors owned by the connection
Closes any open SQL-XML handles that are open
Deletes any open SQL-XML related work tables
Closes all system tables
Closes all user tables
Drops all temporary objects
Aborts open transactions
Defects from a distributed transaction when enlisted
Decrements the reference count for users in current database which releases shared database locks
Frees acquired locks
Releases any acquired handles
Resets all SET options to the default values
Resets the @@rowcount value
Resets the @@identity value
Resets any session level trace options using dbcc traceon()
Resets CONTEXT_INFO to
NULL
in SQL Server 2005 and newer [ not part of the original article ]sp_reset_connection will NOT reset:
Security context, which is why connection pooling matches connections based on the exact connection string
Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when
sp_setapprole
is executed.
Note: I am including the list here as I do not want it to be lost in the ever transient web.
If you don't see the formatting option, you can do Tools->Import and Export settings to import the missing one.
It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:
$('input', $('#mydiv')).each(function () {
console.log($(this)); //log every element found to console output
});
The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.
I use pgrep -l httpd
but not sure it is present on any platform...
Who can confirm on OSX?
Note: You can use memset with any character.
Example:
int arr[20];
memset(arr, 'A', sizeof(arr));
Also could be partially filled
int arr[20];
memset(&arr[5], 0, 10);
But be carefull. It is not limited for the array size, you could easily cause severe damage to your program doing something like this:
int arr[20];
memset(arr, 0, 200);
It is going to work (under windows) and zero memory after your array. It might cause damage to other variables values.
Yes, you can access a form in the controller (as stated in the docs).
Except when your form is not defined in the controller scope and is defined in a child scope instead.
Basically, some angular directives, such as ng-if
, ng-repeat
or ng-include
, will create an isolated child scope. So will any custom directives with a scope: {}
property defined. Probably, your foundation components are also in your way.
I had the same problem when introducing a simple ng-if
around the <form>
tag.
See these for more info:
Note: I suggest you re-write your question. The answer to your question is yes but your problem is slightly different:
Can I access a form in a child scope from the controller?
To which the answer would simply be: no.
There is no way to do so. Either use an HTML table, or put the same text on several cells.
like this:
| Can Reorder | 2nd operation |2nd operation |2nd operation |
| :---: | --- |
|1st operation|Normal Load <br/>Normal Store| Volatile Load <br/>MonitorEnter|Volatile Store<br/> MonitorExit|
|Normal Load <br/> Normal Store| | | No|
|Volatile Load <br/> MonitorEnter| No|No|No|
|Volatile store <br/> MonitorExit| | No|No|
which looks like
Syntax
print_r(variable, return);
variable Required. Specifies the variable to return information about
return Optional. When set to true, this function will return the information (not print it). Default is false
Example
error_log( print_r(<array Variable>, TRUE) );
It was requested that I add this functionality to the stackoverflow R package. Given that it is a tinyverse package (and can't depend on third party packages), here is what I came up with:
#' Bulk import data files
#'
#' Read in each file at a path and then unnest them. Defaults to csv format.
#'
#' @param path a character vector of full path names
#' @param pattern an optional \link[=regex]{regular expression}. Only file names which match the regular expression will be returned.
#' @param reader a function that can read data from a file name.
#' @param ... optional arguments to pass to the reader function (eg \code{stringsAsFactors}).
#' @param reducer a function to unnest the individual data files. Use I to retain the nested structure.
#' @param recursive logical. Should the listing recurse into directories?
#'
#' @author Neal Fultz
#' @references \url{https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once}
#'
#' @importFrom utils read.csv
#' @export
read.directory <- function(path='.', pattern=NULL, reader=read.csv, ...,
reducer=function(dfs) do.call(rbind.data.frame, dfs), recursive=FALSE) {
files <- list.files(path, pattern, full.names = TRUE, recursive = recursive)
reducer(lapply(files, reader, ...))
}
By parameterizing the reader and reducer function, people can use data.table or dplyr if they so choose, or just use the base R functions that are fine for smaller data sets.
Get the Last Segment using RegEx
str.replace(/.*\/(\w+)\/?$/, '$1');
$1 means using the capturing group. using in RegEx (\w+) create the first group then the whole string replace with the capture group.
let str = 'http://mywebsite/folder/file';
let lastSegment = str.replace(/.*\/(\w+)\/?$/, '$1');
console.log(lastSegment);
_x000D_
The best way is to use your code and then store the image in OG tags in the page you are linking to, then Facebook will pick them up.
<meta property="og:title" content="Facebook Open Graph Demo">
<meta property="og:image" content="http://example.com/main-image.png">
<meta property="og:site_name" content="Example Website">
<meta property="og:description" content="Here is a nice description">
You can find documentation to OG tags and how to use them with share buttons here
A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.
To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.
There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.
A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.
document.getElementById('drpSelectSourceLibrary').value = 'Seven';
It is more effecient to convert CString
to std::string
using the conversion where the length is specified.
CString someStr("Hello how are you");
std::string std(somStr, someStr.GetLength());
In tight loop this makes a significant performance improvement.
You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3
(and uses it as default), so switch back to a value of 2
which can be read by Python 2.
Check the protocol
parameter in pickle.dump
. Your resulting code will look like this.
pickle.dump(your_object, your_file, protocol=2)
There is no protocol
parameter in pickle.load
because pickle
can determine the protocol from the file.
StringBuilder sb= new StringBuilder();
for (int i = 0; i < tmpHash.Length; i++)
{
sb.Append(tmpHash[i].ToString("x2"));
}
The Action Bar Style Generator, suggested by Sunny, is very useful, but it generates a lot of files, most of which are irrelevant if you only want to change the background colour.
So, I dug deeper into the zip it generates, and tried to narrow down what are the parts that matter, so I can make the minimum amount of changes to my app. Below is what I found out.
In the style generator, the relevant setting is Popup color, which affects "Overflow menu, submenu and spinner panel background".
Go on and generate the zip, but out of all the files generated, you only really need one image, menu_dropdown_panel_example.9.png
, which looks something like this:
So, add the different resolution versions of it to res/drawable-*
. (And perhaps rename them to menu_dropdown_panel.9.png
.)
Then, as an example, in res/values/themes.xml
you would have the following, with android:popupMenuStyle
and android:popupBackground
being the key settings.
<resources>
<style name="MyAppActionBarTheme" parent="android:Theme.Holo.Light">
<item name="android:popupMenuStyle">@style/MyApp.PopupMenu</item>
<item name="android:actionBarStyle">@style/MyApp.ActionBar</item>
</style>
<!-- The beef: background color for Action Bar overflow menu -->
<style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
<item name="android:popupBackground">@drawable/menu_dropdown_panel</item>
</style>
<!-- Bonus: if you want to style whole Action Bar, not just the menu -->
<style name="MyApp.ActionBar" parent="android:Widget.Holo.Light.ActionBar.Solid">
<!-- Blue background color & black bottom border -->
<item name="android:background">@drawable/blue_action_bar_background</item>
</style>
</resources>
And, of course, in AndroidManifest.xml
:
<application
android:theme="@style/MyAppActionBarTheme"
... >
What you get with this setup:
Note that I'm using Theme.Holo.Light
as the base theme. If you use Theme.Holo
(Holo Dark), there's an additional step needed as this answer describes!
Also, if you (like me) wanted to style the whole Action Bar, not just the menu, put something like this in res/drawable/blue_action_bar_background.xml
:
<!-- Bonus: if you want to style whole Action Bar, not just the menu -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle">
<stroke android:width="2dp" android:color="#FF000000" />
<solid android:color="#FF2070B0" />
</shape>
</item>
<item android:bottom="2dp">
<shape android:shape="rectangle">
<stroke android:width="2dp" android:color="#FF2070B0" />
<solid android:color="#00000000" />
<padding android:bottom="2dp" />
</shape>
</item>
</layer-list>
Works great at least on Android 4.0+ (API level 14+).
None of the above worked for me. My dates were well-formatted and the date format was set properly.
The key in my case was "my data has headers
" checkbox. After I unchecked this option the ordering function just started to work fine.
This function is available under the "Custom sort
" option.
ps. I can accept that the first some row was ordered in a wrong way because of this option but I have no clue about why at the middle of my range was ordered on the wrong way. Excel makes me crazy...
SharpSSH should do the job. http://www.codeproject.com/Articles/11966/sharpSsh-A-Secure-Shell-SSH-library-for-NET
You can programmatically get the image and check the dimensions using Javascript without having to mess with the DOM at all.
var img = new Image();
img.onload = function() {
console.log(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
which allows one-to-many connections.
ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.
I'll try to give the benchmark of the three most common way (also mentioned above):
from timeit import repeat
setup = """
import numpy as np;
import random;
x = np.linspace(0,100);
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
"""
stmts = 'x[(x > lb) * (x <= ub)]', 'x[(x > lb) & (x <= ub)]', 'x[np.logical_and(x > lb, x <= ub)]'
for _ in range(3):
for stmt in stmts:
t = min(repeat(stmt, setup, number=100_000))
print('%.4f' % t, stmt)
print()
result:
0.4808 x[(x > lb) * (x <= ub)]
0.4726 x[(x > lb) & (x <= ub)]
0.4904 x[np.logical_and(x > lb, x <= ub)]
0.4725 x[(x > lb) * (x <= ub)]
0.4806 x[(x > lb) & (x <= ub)]
0.5002 x[np.logical_and(x > lb, x <= ub)]
0.4781 x[(x > lb) * (x <= ub)]
0.4336 x[(x > lb) & (x <= ub)]
0.4974 x[np.logical_and(x > lb, x <= ub)]
But, *
is not supported in Panda Series, and NumPy Array is faster than pandas data frame (arround 1000 times slower, see number):
from timeit import repeat
setup = """
import numpy as np;
import random;
import pandas as pd;
x = pd.DataFrame(np.linspace(0,100));
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
"""
stmts = 'x[(x > lb) & (x <= ub)]', 'x[np.logical_and(x > lb, x <= ub)]'
for _ in range(3):
for stmt in stmts:
t = min(repeat(stmt, setup, number=100))
print('%.4f' % t, stmt)
print()
result:
0.1964 x[(x > lb) & (x <= ub)]
0.1992 x[np.logical_and(x > lb, x <= ub)]
0.2018 x[(x > lb) & (x <= ub)]
0.1838 x[np.logical_and(x > lb, x <= ub)]
0.1871 x[(x > lb) & (x <= ub)]
0.1883 x[np.logical_and(x > lb, x <= ub)]
Note: adding one line of code x = x.to_numpy()
will need about 20 µs.
For those who prefer %timeit
:
import numpy as np
import random
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
lb, ub
x = pd.DataFrame(np.linspace(0,100))
def asterik(x):
x = x.to_numpy()
return x[(x > lb) * (x <= ub)]
def and_symbol(x):
x = x.to_numpy()
return x[(x > lb) & (x <= ub)]
def numpy_logical(x):
x = x.to_numpy()
return x[np.logical_and(x > lb, x <= ub)]
for i in range(3):
%timeit asterik(x)
%timeit and_symbol(x)
%timeit numpy_logical(x)
print('\n')
result:
23 µs ± 3.62 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
35.6 µs ± 9.53 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
31.3 µs ± 8.9 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
21.4 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
21.9 µs ± 1.02 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
21.7 µs ± 500 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
25.1 µs ± 3.71 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
36.8 µs ± 18.3 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
28.2 µs ± 5.97 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
I see that this question is missing an answer. I extend Application
because I use Bill Pugh Singleton implementation (see reference) and some of my singletons need context. The Application
class looks like this:
public class MyApplication extends Application {
private static final String TAG = MyApplication.class.getSimpleName();
private static MyApplication sInstance;
@Contract(pure = true)
@Nullable
public static Context getAppContext() {
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() called");
sInstance = this;
}
}
And the singletons look like this:
public class DataManager {
private static final String TAG = DataManager.class.getSimpleName();
@Contract(pure = true)
public static DataManager getInstance() {
return InstanceHolder.INSTANCE;
}
private DataManager() {
doStuffRequiringContext(MyApplication.getAppContext());
}
private static final class InstanceHolder {
@SuppressLint("StaticFieldLeak")
private static final DataManager INSTANCE = new DataManager();
}
}
This way I don't need to have a context every time I'm using a singleton and get lazy synchronized initialization with minimal amount of code.
Tip: updating Android Studio singleton template saves a lot of time.
It would be the former. Go by extensions as well instead of folder structure.
I.e. my example C# development ignore file:
#OS junk files
[Tt]humbs.db
*.DS_Store
#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad
#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*
#Project files
[Bb]uild/
#Subversion files
.svn
# Office Temp Files
~$*
Update
I thought I'd provide an update from the comments below. Although not directly answering the OP's question, see the following for more examples of .gitignore
syntax.
Community wiki (constantly being updated):
.gitignore for Visual Studio Projects and Solutions
More examples with specific language use can be found here (thanks to Chris McKnight's comment):
This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.
You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:
In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.
I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.
You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:
The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID
column. In the right grid, select the CustomerID
column. Close the dialog, and the next. Press Ctrl+S to save.
Having this constraint will ensure that no Order records can exist without an accompanying Customer record.
To effectively query a database like this, you might want to read up on JOINs.
You don't have to use Javascript to do this. Using plain-old css:
div.blah {
position:absolute;
top: 0; /*[wherever you want it]*/
left:0; /*[wherever you want it]*/
}
If you feel you must use javascript, or are trying to do this dynamically Using JQuery, this affects all divs of class "blah":
var blahclass = $('.blah');
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it
Alternatively, if you must use regular old-javascript you can grab by id
var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever
domElement.style.left = 0; // or whatever
If you don't have it at C:\Users\%USERNAME%\AppData\Local\Android (this is where most people have it) than it is possible you don't have it installed. Go to Tools > Android > SDK Manager and then click on "Android SDK." On the top of the SDK Manager it will list the SDK Location. Click edit. If you don't have Android SDK installed, it will give you the option to install it in certain location. Install it, and Android Studio should work!
If each file only has one sequence of aminoacids, I wouldn't use regular expressions at all. Just something like this:
def read_amino_acid_sequence(path):
with open(path) as sequence_file:
title = sequence_file.readline() # read 1st line
aminoacid_sequence = sequence_file.read() # read the rest
# some cleanup, if necessary
title = title.strip() # remove trailing white spaces and newline
aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","")
return title, aminoacid_sequence
Messing around with environment variables or hard-coded parent folder offsets is never a good idea when there is a API to get the info you want, call SHGetSpecialFolderPath(...,CSIDL_PROFILE,...)
I would really recommend to:
push only to the main repo
make sure that main repo is a bare repo, in order to never have any problem with the main repo working tree being not in sync with its .git
base. See "How to push a local git repository to another computer?"
If you do have to make modification in the main (bare) repo, clone it (on the main server), do your modification and push back to it
In other words, keep a bare repo accessible both from the main server and the local computer, in order to have a single upstream repo from/to which to pull/pull.
On Android 2.2+ use this:
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
for example:
EditText emailid = (EditText) loginView.findViewById(R.id.login_email);
String getEmailId = emailid.getText().toString();
// Check if email id is valid or not
if (!isEmailValid(getEmailId)){
new CustomToast().Show_Toast(getActivity(), loginView,
"Your Email Id is Invalid.");
}
You Also wanna put some text (placeholder) in the empty input box for the
.myClass {_x000D_
::-webkit-input-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
::-moz-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
/* firefox 19+ */_x000D_
:-ms-input-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
/* ie */_x000D_
input:-moz-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
}
_x000D_
<input type="text" class="myClass" id="fname" placeholder="Enter First Name Here!">
_x000D_
user to understand what to type.
Adding to Hobs brilliant answer, I am very new to Python and Pandas so please point out if I am wrong.
To find out which rows have NaNs:
nan_rows = df[df.isnull().any(1)]
would perform the same operation without the need for transposing by specifying the axis of any() as 1 to check if 'True' is present in rows.
You should be able to use crypt
, mcrypt
, or gpg
to meet your needs. They all support a number of algorithms. crypt
is a bit outdated though.
More info:
T-SQL
/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/
CREATE PROCEDURE GetstudentnameInOutputVariable
(
@studentid INT, --Input parameter , Studentid of the student
@studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname,
@StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END
I agree. Once it is uploaded to somewhere the user's browser can access then it is pretty easy to get the size. As you need to wait for the image to load you'll want to hook into the onload
event for img
.
var width, height;
var img = document.createElement("img");
img.onload = function() {
// `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
// The natural size is the actual image size regardless of rendering.
// The 'normal' width/height are for the **rendered** size.
width = img.naturalWidth || img.width;
height = img.naturalHeight || img.height;
// Do something with the width and height
}
// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";
That is a pretty standard use case for apply()
:
R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
start end newcol
1 1 2 1.5
2 3 6 4.5
3 5 7 6.0
4 7 9 8.0
R>
You can also use plyr
if you prefer but here is no real need to go beyond functions from base R.
Part 1 of your question:
var allChecked = true;
$("input.abc").each(function(index, element){
if(!element.checked){
allChecked = false;
return false;
}
});
EDIT:
The answer (http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480) above is probably better.
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
I just got this working. Open your ~/.ssh/config
file.
Append the following-
Host github.com
IdentityFile ~/.ssh/github_rsa
The page that gave me the hint Set up SSH for Git said that the single space indentation is important... though I had a configuration in here from Heroku that did not have that space and works properly.
Jar mismatch comes when you use library projects in your application and both projects are using same jar with different version so just check all library projects attached in your application. if some mismatch exist then remove it.
if above process is not working then just do remove project dependency from build path and again add library projects and build the application.
Set the default console colors and fonts:
http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)
Set-StrictMode -Version Latest
Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location
If the number of list items is fixed you can use the adjacent selector, e.g. if you only have three <li>
elements, you can select the last <li>
with:
#nav li+li+li {
border-bottom: 1px solid #b5b5b5;
}
<table border="1">
<tr>
<td>one</td>
<td style="border-bottom-style: hidden;">two</td>
</tr>
<tr>
<td>one</td>
<td style="border-top-style: hidden;">two</td>
</tr>
</table>
_x000D_
String extension method, easy to use:
public static bool IsPalindrome(this string str)
{
str = new Regex("[^a-zA-Z]").Replace(str, "").ToLower();
return !str.Where((t, i) => t != str[str.Length - i - 1]).Any();
}
In NASM syntax:
mov eax, var == lea eax, [var] ; i.e. mov r32, imm32
lea eax, [var+16] == mov eax, var+16
lea eax, [eax*4] == shl eax, 2 ; but without setting flags
In MASM syntax, use OFFSET var
to get a mov-immediate instead of a load.
sudo apt-get install nodejs
installs nodejs
sudo apt-get install npm
installs npm
sudo npm install bower -g
installs bower via npm
If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and try plot() again.
Moreover Execute the command
graphics.off()
I'm not sure these are the best options but they'll definitely get the job done:
declare @durations table
(
Duration int
)
Insert into @durations(Duration)
values(60),(80),(90),(150),(180),(1000)
--Option 1 - Manually concatenate the values together
select right('0' + convert(varchar,Duration / 60),2) + ':' + right('0' + convert(varchar,Duration % 60),2)
from @Durations
--Option 2 - Make use of the time variable available since SQL Server 2008
select left(convert(time,DATEADD(minute,Duration,0)),5)
from @durations
GO
One of the fast ways to create a dict from equal-length tuples:
>>> t1 = (a,b,c,d)
>>> t2 = (1,2,3,4)
>>> dict(zip(t1, t2))
{'a':1, 'b':2, 'c':3, 'd':4, }
Download "javamail1_4_5.zip" file from http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426.html#javamail-1.4.5-oth-JPR
Extract zip file and put the relevant jar file ("mail.jar") in the classpath
Declare receiver as null and then Put register and unregister methods in onResume() and onPause() of the activity respectively.
@Override
protected void onResume() {
super.onResume();
if (receiver == null) {
filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
}
}
@Override
protected void onPause() {
super.onPause();
if (receiver != null) {
unregisterReceiver(receiver);
receiver = null;
}
}
In addition to the disable cache option (which you get to via a button in the lower right corner of the developer tools window -- Tools | Developer Tools, or Ctrl + Shift + I), on the network pane of the developer tools you can now right click and choose "Clear Cache" from the popup menu.
Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html
Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.
There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices
.
I also encountered similar problem which is asked here. The issue was that some applications come with their own JRE and sometimes the installed JDK appears at lower priority level in environment path. Now there are two options:
I also removed the path as suggested by @CrazyCoder
I agree that the way to do is to redirect to the new controller in usual cases.
I came across a use case where I needed to display the same page to 2 different kind of users (backend user previewing the page of a frontend user) so in my opinion what I needed was genuinely to call the frontend controller from the backend controller.
I solved the problem by making the frontend method static and wrapping it in another method. Hope it helps!
//==========
// Frontend
//==========
function profile()
{
//Access check
//Get profile id
$id = get_user_id();
return self::_profile($id);
}
static function _profile($id)
{
$CI = &get_instance();
//Prepare page
//Load view
}
//==========
// Backend
//==========
function preview_profile($id)
{
$this->load->file('controllers/frontend.php', false);
Frontend::_profile($id);
}
You need to add a TraceListener
to see them appear on the Console.
TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(writer);
They also appear in the Visual Studio Output window when in Debug mode.
Here's my code (using search and slice methods)
let s = "I learned to play the Ukulele in Lebanon"
let sub = 0
let matchingIndex = []
let index = s.search(/le/i)
while( index >= 0 ){
matchingIndex.push(index+sub);
sub = sub + ( s.length - s.slice( index+1 ).length )
s = s.slice( index+1 )
index = s.search(/le/i)
}
console.log(matchingIndex)
_x000D_
There is an alternative if you want to use of
and not switch to in
. You can use KeyValuePipe
introduced in 6.1. You can easily iterate over an object:
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
You must use %ld
to print a long int
, and %lld
to print a long long int
.
Note that only long long int
is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).
You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99
option to gcc). This is because the long long int
type was not introduced until C99; and although many compilers implement long long int
in C90 mode as an extension, the constant 2147483648
may have a type of unsigned int
or unsigned long
in C90. If this is the case in your implementation, then the value of -2147483648
will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.
If the width of the contents changes, you'll have to use this bit of code to update each column:
private void ResizeGridViewColumn(GridViewColumn column)
{
if (double.IsNaN(column.Width))
{
column.Width = column.ActualWidth;
}
column.Width = double.NaN;
}
You'd have to fire it each time the data for that column updates.
I think all you need to display the data on an HTML page is JSON.stringify
.
For example, if your JSON is stored like this:
var jsonVar = {
text: "example",
number: 1
};
Then you need only do this to convert it to a string:
var jsonStr = JSON.stringify(jsonVar);
And then you can insert into your HTML directly, for example:
document.body.innerHTML = jsonStr;
Of course you will probably want to replace body
with some other element via getElementById
.
As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.
var jsonVar = {
text: "example",
number: 1,
obj: {
"more text": "another example"
},
obj2: {
"yet more text": "yet another example"
}
}, // THE RAW OBJECT
jsonStr = JSON.stringify(jsonVar), // THE OBJECT STRINGIFIED
regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
f = {
brace: 0
}; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
// IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)
regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
},
rtnStr = 0;
if (p1.lastIndexOf('{') === (p1.length - 1)) {
rtnStr = rtnFn();
f['brace'] += 1;
} else if (p1.indexOf('}') === 0) {
f['brace'] -= 1;
rtnStr = rtnFn();
} else {
rtnStr = rtnFn();
}
return rtnStr;
});
document.body.innerHTML += regeStr; // appends the result to the body of the HTML document
This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.
pill ${this.props.styleName}
will get "pill undefined" when you don't set the props
I prefer
className={ "pill " + ( this.props.styleName || "") }
or
className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }
In my opinion, it's important to keep your construct vocabulary to a minimum. If I can do away with breaks and continues easily, I do so.
function foo ()
{
var found = false;
for(var k = 0; (k < 4 && !found); k++){
for(var m = 0; (m < 4 && !found); m++){
if( m === 2){
found = true;
}
}
}
return found;
}
Be warned, after the loop, m and k are one larger that you might think. This is because m++ and k++ are executed before their loop conditions. However, it's still better than 'dirty' breaks.
EDIT: long comment @Dennis...
I wasn't being 100% serious about being 'dirty', but I still think that 'break' contravenes my own conception of clean code. The thought of having multi-level breaks actually makes me feel like taking a shower.
I find justifying what I mean about a feeling about code because I have coded all life. The best why I can think of it is is a combination of manners and grammar. Breaks just aren't polite. Multi level breaks are just plain rude.
When looking at a for statement, a reader knows exactly where to look. Everything you need to know about the rules of engagement are in the contract, in between the parenthesis. As a reader, breaks insult me, it feels like I've been cheated upon.
Clarity is much more respectful than cheating.
If gnupg2 and gpg-agent 2.x are used, be sure to set the environment variable GPG_TTY
.
export GPG_TTY=$(tty)
You don't need to - if the favicon is place in the root at favicon.ico, browsers will automatically pick it up.
If you don't see it working, clear your cache etc, it does work without the markup. You only need to use the code if you want to call it something else, or put it on a CDN for instance.
<?php
require_once 'PHPUnit/Framework.php';
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testException()
{
$this->expectException(InvalidArgumentException::class);
// or for PHPUnit < 5.2
// $this->setExpectedException(InvalidArgumentException::class);
//...and then add your test code that generates the exception
exampleMethod($anInvalidArgument);
}
}
expectException() PHPUnit documentation
PHPUnit author article provides detailed explanation on testing exceptions best practices.
You can use jQuery methods .hasClass()
, .addClass()
, and .removeClass()
to manipulate which classes are applied to your elements. Just define different classes and add/remove them as necessary.
As of today, Windows PowerShell 5.1 is the latest version. It can be installed as part of Windows Management Framework 5.1. It was released in January 2017.
Quoting from the official Microsoft download page here.
Some of the new and updated features in this release include:
- Constrained file copying to/from JEA endpoints
- JEA support for Group Managed Service Accounts and Conditional Access Policies
- PowerShell console support for VT100 and redirecting stdin with interactive input
- Support for catalog signed modules in PowerShell Get
- Specifying which module version to load in a script
- Package Management cmdlet support for proxy servers
- PowerShellGet cmdlet support for proxy servers
- Improvements in PowerShell Script Debugging
- Improvements in Desired State Configuration (DSC)
- Improved PowerShell usage auditing using Transcription and Logging
- New and updated cmdlets based on community feedback
During recent experience writing a JS interpreter I wrestled plenty with the inner workings of ECMA/JS dates. So, I figure I'll throw in my 2 cents here. Hopefully sharing this stuff will help others with any questions about the differences among browsers in how they handle dates.
All implementations store their date values internally as 64-bit numbers that represent the number of milliseconds (ms) since 1970-01-01 UTC (GMT is the same thing as UTC). This date is the ECMAScript epoch that is also used by other languages such as Java and POSIX systems such as UNIX. Dates occurring after the epoch are positive numbers and dates prior are negative.
The following code is interpreted as the same date in all current browsers, but with the local timezone offset:
Date.parse('1/1/1970'); // 1 January, 1970
In my timezone (EST, which is -05:00), the result is 18000000 because that's how many ms are in 5 hours (it's only 4 hours during daylight savings months). The value will be different in different time zones. This behaviour is specified in ECMA-262 so all browsers do it the same way.
While there is some variance in the input string formats that the major browsers will parse as dates, they essentially interpret them the same as far as time zones and daylight saving is concerned even though parsing is largely implementation dependent.
However, the ISO 8601 format is different. It's one of only two formats outlined in ECMAScript 2015 (ed 6) specifically that must be parsed the same way by all implementations (the other is the format specified for Date.prototype.toString).
But, even for ISO 8601 format strings, some implementations get it wrong. Here is a comparison output of Chrome and Firefox when this answer was originally written for 1/1/1970 (the epoch) on my machine using ISO 8601 format strings that should be parsed to exactly the same value in all implementations:
Date.parse('1970-01-01T00:00:00Z'); // Chrome: 0 FF: 0
Date.parse('1970-01-01T00:00:00-0500'); // Chrome: 18000000 FF: 18000000
Date.parse('1970-01-01T00:00:00'); // Chrome: 0 FF: 18000000
This difference has been fixed as of 2020, but other quirks exist between browsers when parsing ISO 8601 format strings.
But it gets worse. A quirk of ECMA-262 is that the ISO 8601 date–only format (YYYY-MM-DD) is required to be parsed as UTC, whereas ISO 8601 requires it to be parsed as local. Here is the output from FF with the long and short ISO date formats with no time zone specifier.
Date.parse('1970-01-01T00:00:00'); // 18000000
Date.parse('1970-01-01'); // 0
So the first is parsed as local because it's ISO 8601 date and time with no timezone, and the second is parsed as UTC because it's ISO 8601 date only.
So, to answer the original question directly, "YYYY-MM-DD"
is required by ECMA-262 to be interpreted as UTC, while the other is interpreted as local. That's why:
console.log(new Date(Date.parse("Jul 8, 2005")).toString()); // Local
console.log(new Date(Date.parse("2005-07-08")).toString()); // UTC
console.log(new Date(Date.parse("Jul 8, 2005")).toString());
console.log(new Date(Date.parse("2005-07-08T00:00:00")).toString());
The bottom line is this for parsing date strings. The ONLY ISO 8601 string that you can safely parse across browsers is the long form with an offset (either ±HH:mm or "Z"). If you do that you can safely go back and forth between local and UTC time.
console.log(new Date(Date.parse("2005-07-08T00:00:00Z")).toString());
Most current browsers do treat the other input formats equally, including the frequently used '1/1/1970' (M/D/YYYY) and '1/1/1970 00:00:00 AM' (M/D/YYYY hh:mm:ss ap) formats. All of the following formats (except the last) are treated as local time input in all browsers. The output of this code is the same in all browsers in my timezone. The last one is treated as -05:00 regardless of the host timezone because the offset is set in the timestamp:
console.log(Date.parse("1/1/1970"));
console.log(Date.parse("1/1/1970 12:00:00 AM"));
console.log(Date.parse("Thu Jan 01 1970"));
console.log(Date.parse("Thu Jan 01 1970 00:00:00"));
console.log(Date.parse("Thu Jan 01 1970 00:00:00 GMT-0500"));
However, since parsing of even the formats specified in ECMA-262 is not consistent, it is recommended to never rely on the built–in parser and to always manually parse strings, say using a library and provide the format to the parser.
E.g. in moment.js you might write:
let m = moment('1/1/1970', 'M/D/YYYY');
On the output side, all browsers translate time zones the same way but they handle the string formats differently. Here are the toString
functions and what they output. Notice the toUTCString
and toISOString
functions output 5:00 AM on my machine. Also, the timezone name may be an abbreviation and may be different in different implementations.
Converts from UTC to Local time before printing
- toString
- toDateString
- toTimeString
- toLocaleString
- toLocaleDateString
- toLocaleTimeString
Prints the stored UTC time directly
- toUTCString
- toISOString
In Chrome
toString Thu Jan 01 1970 00:00:00 GMT-05:00 (Eastern Standard Time)
toDateString Thu Jan 01 1970
toTimeString 00:00:00 GMT-05:00 (Eastern Standard Time)
toLocaleString 1/1/1970 12:00:00 AM
toLocaleDateString 1/1/1970
toLocaleTimeString 00:00:00 AM
toUTCString Thu, 01 Jan 1970 05:00:00 GMT
toISOString 1970-01-01T05:00:00.000Z
In Firefox
toString Thu Jan 01 1970 00:00:00 GMT-05:00 (Eastern Standard Time)
toDateString Thu Jan 01 1970
toTimeString 00:00:00 GMT-0500 (Eastern Standard Time)
toLocaleString Thursday, January 01, 1970 12:00:00 AM
toLocaleDateString Thursday, January 01, 1970
toLocaleTimeString 12:00:00 AM
toUTCString Thu, 01 Jan 1970 05:00:00 GMT
toISOString 1970-01-01T05:00:00.000Z
I normally don't use the ISO format for string input. The only time that using that format is beneficial to me is when dates need to be sorted as strings. The ISO format is sortable as-is while the others are not. If you have to have cross-browser compatibility, either specify the timezone or use a compatible string format.
The code new Date('12/4/2013').toString()
goes through the following internal pseudo-transformation:
"12/4/2013" -> toUCT -> [storage] -> toLocal -> print "12/4/2013"
I hope this answer was helpful.
For dynamic SQL use:
'IN(' ||array_to_string(some_array, ',')||')'
DO LANGUAGE PLPGSQL $$
DECLARE
some_array bigint[];
sql_statement text;
BEGIN
SELECT array[1, 2] INTO some_array;
RAISE NOTICE '%', some_array;
sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
RAISE NOTICE '%', sql_statement;
END;
$$;
Result:
NOTICE: {1,2}
NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)
One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.
Using a shebang line to invoke the appropriate interpreter is not just for BASH. You can use the shebang for any interpreted language on your system such as Perl, Python, PHP (CLI) and many others. By the way, the shebang
#!/bin/sh -
(it can also be two dashes, i.e. --
) ends bash options everything after will be treated as filenames and arguments.
Using the env
command makes your script portable and allows you to setup custom environments for your script hence portable scripts should use
#!/usr/bin/env bash
Or for whatever the language such as for Perl
#!/usr/bin/env perl
Be sure to look at the man
pages for bash
:
man bash
and env
:
man env
Note: On Debian and Debian-based systems, like Ubuntu, sh
is linked to dash
not bash
. As all system scripts use sh
. This allows bash to grow and the system to stay stable, according to Debian.
Also, to keep invocation *nix like I never use file extensions on shebang invoked scripts, as you cannot omit the extension on invocation on executables as you can on Windows. The file command can identify it as a script.
I activated the Apache module headers a2enmod headers, and the issue has been solved.
If you want the string without round you can use this RegEx (maybe is not the most efficient way... but is really easy)
(2.34567778).toString().match(/\d+\.\d{2}/)[0]
// '2.34'
A solution avoiding CASE WHEN
is to use COALESCE
.
SELECT
t1.Col2 AS t1Col2,
t2.Col2 AS t2Col2,
COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)) as NULL_IF_SAME
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID
NULL_IF_SAME
column will give NULL
for all rows where t1.col2 = t2.col2
(including NULL
).
Though this is not more readable than CASE WHEN
expression, it is ANSI SQL.
Just for the sake of fun, if one wants to have boolean bit values of 0 and 1 (though it is not very readable, hence not recommended), one can use (which works for all datatypes):
1/ISNULL(LEN(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+2,1) as BOOL_BIT_SAME.
Now if you have one of the numeric data types and want bits, in the above LEN
function converts to string first which may be problematic,so instead this should work:
1/(CAST(ISNULL(ABS(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+1,0)as bit)+1) as FAST_BOOL_BIT_SAME_NUMERIC
Above will work for Integers without CAST
.
NOTE: also in SQLServer 2012, we have IIF
function.
Use the --version
parameter (shortcut -v
):
$ gem install rails -v 0.14.1
You can also use version comparators like >=
or ~>
$ gem install rails -v '~> 0.14.0'
Or with newer versions of gem even:
$ gem install rails:0.14.4 rubyzip:'< 1'
…
Successfully installed rails-0.14.4
Successfully installed rubyzip-0.9.9
You could probably detect inactivity on your web page using the mousemove tricks listed, but that won't tell you that the user isn't on another page in another window or tab, or that the user is in Word or Photoshop, or WOW and just isn't looking at your page at this time. Generally I'd just do the prefetch and rely on the client's multi-tasking. If you really need this functionality you do something with an activex control in windows, but it's ugly at best.
This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.
For me, the most understandable way I can think of is like so:
--Users that bought from us 6 months ago and between 3 months ago.
DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
INSERT @6To3MonthsUsers
select u.ID,opd.OrderDate
from OrdersPaid opd
inner join Orders o
on opd.OrderID = o.ID
inner join Users u
on o.BuyerID = u.ID
where 1=1
and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())
--Users that bought from us in the last 3 months
DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
INSERT @Last3MonthsUsers
select u.ID,opd.OrderDate
from OrdersPaid opd
inner join Orders o
on opd.OrderID = o.ID
inner join Users u
on o.BuyerID = u.ID
where 1=1
and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()
Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.
There are 2 simple ways to achieve that:
Using Left Join:
select distinct a.UserID
from @6To3MonthsUsers a
left join @Last3MonthsUsers b
on a.UserID = b.UserID
where b.UserID is null
Not in:
select distinct a.UserID
from @6To3MonthsUsers a
where a.UserID not in (select b.UserID from @Last3MonthsUsers b)
Both ways will get me the same result, I personally prefer the second way because it's more readable.
If you are trying to get all parameters passed to Jenkins job you can use the global variable params in your groovy pipeline to fetch it.
http://jenkins_host:8080/pipeline-syntax/globals
params
Exposes all parameters defined in the build as a read-only map with variously typed values. Example:
if (params.BOOLEAN_PARAM_NAME) {doSomething()} or to supply a nontrivial default value:
if (params.get('BOOLEAN_PARAM_NAME', true)) {doSomething()} Note for multibranch (Jenkinsfile) usage: the properties step allows you to define job properties, but these take effect when the step is run, whereas build parameter definitions are generally consulted before the build begins. As a convenience, any parameters currently defined in the job which have default values will also be listed in this map. That allows you to write, for example:
properties([parameters([string(name: 'BRANCH', defaultValue: 'master')])]) git url: '…', branch: params.BRANCH and be assured that the master branch will be checked out even in the initial build of a branch project, or if the previous build did not specify parameters or used a different parameter name.
Use something like below.
def dumpParameter()
{
params.each {
println it.key + " = " + it.value
}
}
If you just want to make some modification to files or inspect processes, here's one another solution you probably want.
You could run the following command to execute a new process from the existing container:
sudo docker exec -ti [CONTAINER-ID] bash
will start a new process with bash shell, and you could escape from it by Ctrl+C directly, it won't affect the original process.
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args){
try {
DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm a");
String sDate = "22-01-2019 13:35 PM";
Date date = parseFormat.parse(sDate);
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
sDate = displayFormat.format(date);
System.out.println("The required format : " + sDate);
} catch (Exception e) {}
}
}
Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code:
comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;
or:
comm.Parameters.AddWithValue("@person", Myname);
That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype.
Hope this helps.
For Each line As String In System.IO.File.ReadAllLines("D:\abc.csv")
DataGridView1.Rows.Add(line.Split(","))
Next
To concatenate long lines without whitespace, use double quotes and escape the newlines with backslashes:
key: "Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemp\
orincididuntutlaboreetdoloremagnaaliqua."
(Thanks @Tobia)
Open Terminal and type:
pip config set global.target /Users/Bob/Library/Python/3.8/lib/python/site-packages
except instead of
/Users/Bob/Library/Python/3.8/lib/python/site-packages
you would use whatever directory you want.
Yes, use the jQuery contains
selector.
Let's use the latest fat arrow functions:
navigator.geolocation.getCurrentPosition((loc) => {
console.log('The location in lat lon format is: [', loc.coords.latitude, ',', loc.coords.longitude, ']');
})
Add following gems in your gem file
gem 'therubyracer'
gem 'execjs'
and run
bundle install
OR
Install Node.js to fix it permanently for all projects.
You can set the position like this
UIActivityIndicatorView *activityView =
[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityView.frame = CGRectMake(120, 230, 50, 50);
[self.view addSubview:activityView];
Accordingly change the frame size.....
You can configure the ObjectMapper
to convert camel case to names with an underscore:
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
Or annotate a specific model class with this annotation:
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
Before Jackson 2.7, the constant was named:
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
I suggest you to start from an existing solution and customize it to fit your needs, that's better than starting from scratch!
I was looking for the same thing and I fall on this open source solution, I hope it will help.
string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;
You can also use the matrix
command, to create a matrix with n lines and m columns, filled with zeros.
matrix(0, n, m)
Recent IntelliJ versions allows automatic creation of desktop entry. See this gist
There is a good stackoverflow answer here by Mark Rajcok:
AngularJS directive controllers requiring parent directive controllers?
with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/
<div ng-controller="MyCtrl">
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
this.componentFunction = function() {
$scope.screenCtrl.doSomethingScreeny();
}
},
link: function(scope, element, attrs, screenCtrl) {
scope.screenCtrl = screenCtrl
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
first you can do with this style:
mda="/usr/mda"
if [ ! -L "${mda}" ]; then
echo "=> File doesn't exist"
fi
if you want to do it in more advanced style you can write it like below:
#!/bin/bash
mda="$1"
if [ -e "$1" ]; then
if [ ! -L "$1" ]
then
echo "you entry is not symlink"
else
echo "your entry is symlink"
fi
else
echo "=> File doesn't exist"
fi
the result of above is like:
root@linux:~# ./sym.sh /etc/passwd
you entry is not symlink
root@linux:~# ./sym.sh /usr/mda
your entry is symlink
root@linux:~# ./sym.sh
=> File doesn't exist
All,
Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.
step1. 1st stop your databases
service mysqld stop
step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"
vi /etc/my.cnf
[mysqld] skip-grant-tables
step3. 3rd start mysql
service mysqld start
step4. select mysql default database
mysql -u root
mysql>use mysql;
step4. set a new password
mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root'
;
step5 restart mysql database
service mysqld restart
mysql -u root -p
enjoy :)
It is mentioned in the .data()
documentation
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)
This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?
The demo on my original answer below doesn't seem to work any more.
Updated answer
Again, from the .data()
documentation
The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.
So for <div data-role="page"></div>
the following is true $('div').data('role') === 'page'
I'm fairly sure that $('div').data('data-role')
worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.
Also see jQuery Data vs Attr?
HTML
<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
<tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>
JavaScript (jQuery 1.6.2+)
var $changeMe = $('#changeMe');
var $log = $('#log');
var logger;
(logger = function(setter, getter, note) {
note = note || '';
eval('$changeMe' + setter);
var result = eval('$changeMe' + getter);
$log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");
$('#changeData').click(function() {
// set data-key to new value
logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
// try and set data-key via .attr and get via some methods
logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");
// bonus points
logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");
return false;
});
$('#changeData').click();
Original answer
For this HTML:
<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>
and this JavaScript (with jQuery 1.6.2)
console.log($('#foo').data('helptext'));
$('#changeData').click(function() {
$('#foo').data('helptext', 'Testing 123');
// $('#foo').attr('data-helptext', 'Testing 123');
console.log($('#foo').data('data-helptext'));
return false;
});
Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123');
does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123');
does.
I'm not really too clear what you are asking, but using the -f
command line option just specifies a file - it doesn't tell make to change directories. If you want to do the work in another directory, you need to cd
to the directory:
clean:
cd gtest-1.4.0 && $(MAKE) clean
Note that each line in Makefile
runs in a separate shell, so there is no need to change the directory back.
I am a bit late to the party but Non of these answer helped me in my case. I was using Google map as SupportMapFragment and PlaceAutocompleteFragment both in my fragment. As all the answers pointed to the fact that the problem is with SupportMapFragment being the map to be recreated and redrawn.But after digging found out my problem was actually with PlaceAutocompleteFragment
So here is the working solution for those who are facing this problem because of SupportMapFragment and SupportMapFragment
//Global SupportMapFragment mapFragment;
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
FragmentManager fm = getChildFragmentManager();
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapFragment, mapFragment).commit();
fm.executePendingTransactions();
}
mapFragment.getMapAsync(this);
//Global PlaceAutocompleteFragment autocompleteFragment;
if (autocompleteFragment == null) {
autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autoCompleteFragment);
}
And in onDestroyView clear the SupportMapFragment and SupportMapFragment
@Override
public void onDestroyView() {
super.onDestroyView();
if (getActivity() != null) {
Log.e("res","place dlted");
android.app.FragmentManager fragmentManager = getActivity().getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(autocompleteFragment);
fragmentTransaction.commit();
//Use commitAllowingStateLoss() if getting exception
autocompleteFragment = null;
}
}
for PHP 5.3 using PDO
<?php
$staff=$dbh->prepare("SELECT count(*) FROM staff_login");
$staff->execute();
$staffrow = $staff->fetch(PDO::FETCH_NUM);
$staffcount = $staffrow[0];
echo $staffcount;
?>
In addition to @thoughtrepo's answer:
Until we do not have definitely typed events in React it might be useful to have a special target interface for input controls:
export interface FormControlEventTarget extends EventTarget{
value: string;
}
And then in your code cast to this type where is appropriate to have IntelliSense support:
import {FormControlEventTarget} from "your.helper.library"
(event.target as FormControlEventTarget).value;
File.WriteAllText(path, String.Empty);
Alternatively,
File.Create(path).Close();
You can use flexbox
with flex-grow
to push the last element to the right.
<div style="display: flex;">
<div style="flex-grow: 1;">Left</div>
<div>Right</div>
</div>
By using this code video will play in all browser in safari as well with ios devices... Go for it everyone (I have used this and working fine)
`
<video autoplay loop muted playsinline poster="video_thumbnail/thumbanil.jpg" src="video/video.mp4">_x000D_
<source src="video/video.mp4" type="video/mp4"></source>_x000D_
<source src="video/video.webm" type="video/webm"></source>_x000D_
<source src="video/video.mov" type="video/mov"></source>_x000D_
</video>
_x000D_
`
IF()
in MySQL is a ternary function, not a control structure -- if the condition in the first argument is true, it returns the second argument; otherwise, it returns the third argument. There is no corresponding ELSEIF()
function or END IF
keyword.
The closest equivalent to what you've got would be something like:
IF(qty_1<='23', price,
IF('23'>qty_1 && qty_2<='23', price_2,
IF('23'>qty_2 && qty_3<='23', price_3,
IF('23'>qty_3, price_4, 1)
)
)
)
The conditions don't all make sense to me (it looks as though some of them may be inadvertently reversed?), but without knowing what exactly you're trying to accomplish, it's hard for me to fix that.
Mine was quite straightforward if you are on a Mac try:
brew install postgres
This will tell you if you have it already install and what version or install the latest version for you if not then run
brew upgrade postgresql
This will make sure you have the latest version installed then finally
brew services start postgresql
This will start the service again. I hope this helps someone.
From google drive help pages:
To host a webpage with Drive:
- Open Drive at drive.google.com and select a file.
- Click the Share button at the top of the page.
- Click Advanced in the bottom right corner of the sharing box.
- Click Change....
- Choose On - Public on the web and click Save.
- Before closing the sharing box, copy the document ID from the URL in the field below "Link to share". The document ID is a string of uppercase and lowercase letters and numbers between slashes in the URL.
- Share the URL that looks like "www.googledrive.com/host/[doc id] where [doc id] is replaced by the document ID you copied in step 6.
Anyone can now view your webpage.
If you want to see your image in a website embed the link to pic in your html as usually:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example image from Google Drive</title>
</head>
<body>
<h1>Example image from Google Drive</h1>
<img src="https://www.googledrive.com/host/[doc id]" alt="whatever">
</body>
</html>
Note:
Beginning August 31st, 2015, web hosting in Google Drive for users and developers will be deprecated. You can continue to use this feature for a period of one year until August 31st, 2016, when we will discontinue serving content via googledrive.com/host/[doc id]. More info
I think that the answer provided by Laptop Lifts is best...but since nobody suggested the approach that I use, i figured i should chime in. I use phpMyAdmin to set up and manage my databases most of the time. In it, you can simply put checkmarks next to the rows you want, and at the bottom click "Export" and chose SQL. It will give you INSERT statements for whichever records you selected. Hope this helps.
The Object.entries()
method has been specified in ES2017 (and is supported in all modern browsers):
for (const [ key, value ] of Object.entries(dictionary)) {
// do something with `key` and `value`
}
Explanation:
Object.entries()
takes an object like { a: 1, b: 2, c: 3 }
and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
.
With for ... of
we can loop over the entries of the so created array.
Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key
and value
to its first and second item.
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
Change the following line
$(document).ready(function() {
To
jQuery.noConflict();
jQuery(document).ready(function($) {
I have something to add to Aladin's answer:
Your view controller should conform to UITextFieldDelegate
class MyViewController: UIViewController, UITextViewDelegate {
}
Set the delegate of your textfield: To set the delegate, you can control drag from the textfield to your view controller in the storyboard. I think this is preferable to setting it in code
Implement the method in your view controller : textField(_:shouldChangeCharactersInRange:replacementString:)
I got the same error the first time I wanted to install LightGBM on python (GPU version).
You can simply fix it with this command line :
sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev
the boost libraries will be installed and you'll be fine to continue your installation process.
This question might have been asked some time ago, but as I recently landed on this topic looking for client-side form validation, and as the :placeholder-shown
support is getting better, I thought the following might help others.
Using Berend idea of using this CSS4 pseudo-class, I was able to create a form validation only triggered after the user is finished filling it.
Here is ademo and explanation on CodePen: https://codepen.io/johanmouchet/pen/PKNxKQ
For me the right answer was
echo '<pre>' . var_export($var, true) . '</pre>';
Since var_dump($var)
and var_export($var)
do not return a string, you have to use var_export($var, true)
to force var_export
to return the result as a value.
Update: Corrected map rendering algorithm, added more illustrations, changed formating.
Perhaps the advantage for the "zig-zag" technique for mapping the tiles to the screen can be said that the tile's x
and y
coordinates are on the vertical and horizontal axes.
"Drawing in a diamond" approach:
By drawing an isometric map using "drawing in a diamond", which I believe refers to just rendering the map by using a nested for
-loop over the two-dimensional array, such as this example:
tile_map[][] = [[...],...]
for (cellY = 0; cellY < tile_map.size; cellY++):
for (cellX = 0; cellX < tile_map[cellY].size cellX++):
draw(
tile_map[cellX][cellY],
screenX = (cellX * tile_width / 2) + (cellY * tile_width / 2)
screenY = (cellY * tile_height / 2) - (cellX * tile_height / 2)
)
Advantage:
The advantage to the approach is that it is a simple nested for
-loop with fairly straight forward logic that works consistently throughout all tiles.
Disadvantage:
One downside to that approach is that the x
and y
coordinates of the tiles on the map will increase in diagonal lines, which might make it more difficult to visually map the location on the screen to the map represented as an array:
However, there is going to be a pitfall to implementing the above example code -- the rendering order will cause tiles that are supposed to be behind certain tiles to be drawn on top of the tiles in front:
In order to amend this problem, the inner for
-loop's order must be reversed -- starting from the highest value, and rendering toward the lower value:
tile_map[][] = [[...],...]
for (i = 0; i < tile_map.size; i++):
for (j = tile_map[i].size; j >= 0; j--): // Changed loop condition here.
draw(
tile_map[i][j],
x = (j * tile_width / 2) + (i * tile_width / 2)
y = (i * tile_height / 2) - (j * tile_height / 2)
)
With the above fix, the rendering of the map should be corrected:
"Zig-zag" approach:
Advantage:
Perhaps the advantage of the "zig-zag" approach is that the rendered map may appear to be a little more vertically compact than the "diamond" approach:
Disadvantage:
From trying to implement the zig-zag technique, the disadvantage may be that it is a little bit harder to write the rendering code because it cannot be written as simple as a nested for
-loop over each element in an array:
tile_map[][] = [[...],...]
for (i = 0; i < tile_map.size; i++):
if i is odd:
offset_x = tile_width / 2
else:
offset_x = 0
for (j = 0; j < tile_map[i].size; j++):
draw(
tile_map[i][j],
x = (j * tile_width) + offset_x,
y = i * tile_height / 2
)
Also, it may be a little bit difficult to try to figure out the coordinate of a tile due to the staggered nature of the rendering order:
Note: The illustrations included in this answer were created with a Java implementation of the tile rendering code presented, with the following int
array as the map:
tileMap = new int[][] {
{0, 1, 2, 3},
{3, 2, 1, 0},
{0, 0, 1, 1},
{2, 2, 3, 3}
};
The tile images are:
tileImage[0] ->
A box with a box inside.tileImage[1] ->
A black box.tileImage[2] ->
A white box.tileImage[3] ->
A box with a tall gray object in it.A Note on Tile Widths and Heights
The variables tile_width
and tile_height
which are used in the above code examples refer to the width and height of the ground tile in the image representing the tile:
Using the dimensions of the image will work, as long as the image dimensions and the tile dimensions match. Otherwise, the tile map could be rendered with gaps between the tiles.
var a = {"apples": 3, "oranges": 4, "bananas": 42};
var array_keys = new Array();
var array_values = new Array();
for (var key in a) {
array_keys.push(key);
array_values.push(a[key]);
}
alert(array_keys);
alert(array_values);
Google has added a new feature since the last answer was posted here.
You can now add the controlList
attribute as shown here:
<video width="512" height="380" controls controlsList="nodownload">
<source data-src="mov_bbb.ogg" type="video/mp4">
</video>
You can find all options of the controllist attribute here:
https://developers.google.com/web/updates/2017/03/chrome-58-media-updates#controlslist
Try this code, it works for me.
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.remove(position);
adapter.notifyDataSetChanged();
}
}
Here is a plotrix solution:
set.seed(0815)
x <- 1:10
F <- runif(10,1,2)
L <- runif(10,0,1)
U <- runif(10,2,3)
require(plotrix)
plotCI(x, F, ui=U, li=L)
And here is a ggplot solution:
set.seed(0815)
df <- data.frame(x =1:10,
F =runif(10,1,2),
L =runif(10,0,1),
U =runif(10,2,3))
require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
geom_point(size = 4) +
geom_errorbar(aes(ymax = U, ymin = L))
UPDATE: Here is a base solution to your edits:
set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
y = x + rnorm(20))
plot(y ~ x, data = df)
# model
mod <- lm(y ~ x, data = df)
# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx),
interval = 'confidence')
# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
If you need the difference in days accounting up to the second:
SELECT TIMESTAMPDIFF(SECOND,'2010-09-21 21:40:36','2010-10-08 18:23:13')/86400 AS diff
It will return
diff
16.8629
On an object, you can achieve this with setattr
>>> class A(object): pass
>>> a=A()
>>> setattr(a, "hello1", 5)
>>> a.hello1
5
I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:
f (a,b)
previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.
Select * from table where date > 'Today's date(mm/dd/yyyy)'
You can also add time in the single quotes(00:00:00AM)
For example:
Select * from Receipts where Sales_date > '08/28/2014 11:59:59PM'
Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed
Create a path with moveTo
and lineTo
(live demo):
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,50);
ctx.lineTo(50, 100);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fill();
How to print:
NSLog(@"Something To Print");
Or
NSString * someString = @"Something To Print";
NSLog(@"%@", someString);
For other types of variables, use:
NSLog(@"%@", someObject);
NSLog(@"%i", someInt);
NSLog(@"%f", someFloat);
/// etc...
Can you show it in phone?
Not by default, but you could set up a display to show you.
print("Print this string")
print("Print this \(variable)")
print("Print this ", variable)
print(variable)