On Windows add following lines to _vimrc
" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//
When working on an important code update, if you really need an intermediate safepoint you might just do:
git commit -am'.'
or shorter:
git commit -am.
INSERT INTO table
SELECT 'jonny', NULL
FROM dual -- Not Oracle? No need for dual, drop that line
WHERE NOT EXISTS (SELECT NULL -- canonical way, but you can select
-- anything as EXISTS only checks existence
FROM table
WHERE name = 'jonny'
)
Yes is posible:
List<Integer> myArrayList = new ArrayList<>(100);
now, the initial capacity of myArrayList will be 100
nodeName will give you the tag name in uppercase, while localName will give you the lower case.
$("yourelement")[0].localName
will give you : yourelement instead of YOURELEMENT
I found an up-to-date & unparalleled solution: https://www.npmjs.com/package/ts-mixer
You are welcome :)
Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.
Please take a look at the following JavaScript libraries:
I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.
moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a'); // 08/20/2014 3:30 pm
You can write one liner using DataRow.Add(params object[] values) instead of four lines.
dt.Rows.Add("Ravi", "500");
As you create new DataTable
object, there seems no need to Clear
DataTable
in very next statement. You can also use DataTable.Columns.AddRange
to add columns with on statement. Complete code would be.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });
dt.Rows.Add("Ravi", "500");
The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.
For example:
var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}
//that will not work.
delete myObj.test.keyToDelete
instead you would need to use:
delete myObj.test[keyToDelete];
Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.
This is the solution I came up with if anyone is interested.
https://kellyschronicles.wordpress.com/2017/12/16/dynamic-predicate-for-a-linq-query/
First we identify the single element type we need to use ( Of TRow As DataRow) and then identify the “source” we are using and tie the identifier to that source ((source As TypedTableBase(Of TRow)). Then we must specify the predicate, or the WHERE clause that is going to be passed (predicate As Func(Of TRow, Boolean)) which will either be returned as true or false. Then we identify how we want the returned information ordered (OrderByField As String). Our function will then return a EnumerableRowCollection(Of TRow), our collection of datarows that have met the conditions of our predicate(EnumerableRowCollection(Of TRow)). This is a basic example. Of course you must make sure your order field doesn’t contain nulls, or have handled that situation properly and make sure your column names (if you are using a strongly typed datasource never mind this, it will rename the columns for you) are standard.
I had exactly the same issue and it was not cross domain but the same domain. I just added this line to the php file which was handling the ajax request.
<?php header('Access-Control-Allow-Origin: *'); ?>
It worked like a charm. Thanks to the poster
You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:
In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file"
field, ostensibly for backward compatibility reasons.
So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.
My original answer was written in 2009. While it still works, I'd like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it's not necessary to include the entire library. In the jQuery source, the relevant portion is found on line 37 of dimensions.js. Here it is extracted and modified to work standalone:
function getWidth() {_x000D_
return Math.max(_x000D_
document.body.scrollWidth,_x000D_
document.documentElement.scrollWidth,_x000D_
document.body.offsetWidth,_x000D_
document.documentElement.offsetWidth,_x000D_
document.documentElement.clientWidth_x000D_
);_x000D_
}_x000D_
_x000D_
function getHeight() {_x000D_
return Math.max(_x000D_
document.body.scrollHeight,_x000D_
document.documentElement.scrollHeight,_x000D_
document.body.offsetHeight,_x000D_
document.documentElement.offsetHeight,_x000D_
document.documentElement.clientHeight_x000D_
);_x000D_
}_x000D_
_x000D_
console.log('Width: ' + getWidth() );_x000D_
console.log('Height: ' + getHeight() );
_x000D_
Since all browsers behave differently, you'll need to test for values first, and then use the correct one. Here's a function that does this for you:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
if (document.body) {
return document.body.clientWidth;
}
}
and similarly for height:
function getHeight() {
if (self.innerHeight) {
return self.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
if (document.body) {
return document.body.clientHeight;
}
}
Call both of these in your scripts using getWidth()
or getHeight()
. If none of the browser's native properties are defined, it will return undefined
.
In my case, using JSX a parent component was calling other components without the "<>"
<ComponentA someProp={someCheck ? ComponentX : ComponentY} />
fix
<ComponentA someProp={someCheck ? <ComponentX /> : <ComponentY />} />
Google's Guava library provides a nice helper method to do this: Doubles.tryParse(String)
. You use it like Double.parseDouble
but it returns null
rather than throwing an exception if the string does not parse to a double.
A quicker way is this:
public static String execCmd(String cmd) throws java.io.IOException {
java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
Which is basically a condensed version of this:
public static String execCmd(String cmd) throws java.io.IOException {
Process proc = Runtime.getRuntime().exec(cmd);
java.io.InputStream is = proc.getInputStream();
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
String val = "";
if (s.hasNext()) {
val = s.next();
}
else {
val = "";
}
return val;
}
I know this question is old but I am posting this answer because I think this may be quicker.
Edit (For Java 7 and above)
Need to close Streams and Scanners. Using AutoCloseable for neat code:
public static String execCmd(String cmd) {
String result = null;
try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
result = s.hasNext() ? s.next() : null;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you switch from Web to Express you will no longer be able to use the SQL Server Agent service so you need to set up a different scheduler for maintenance and backups.
There is no 100% solution to delete browser cookies.
The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".
Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie
. It's not available through the HTTP Cookie header either!
However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:
function clearCookie(name, domain, path){
var domain = domain || document.domain;
var path = path || "/";
document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
select CONCAT(Name, '(',substr(occupation, 1, 1), ')') AS f1
from OCCUPATIONS
union
select temp.str AS f1 from
(select count(occupation) AS counts, occupation, concat('There are a total of ' ,count(occupation) ,' ', lower(occupation),'s.') As str from OCCUPATIONS group by occupation order by counts ASC, occupation ASC
) As temp
order by f1
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
This is actually very simple, and that worked for me :)
if (id == "DK")
{
string longurl = "selectServer.aspx?country=";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["country"] = "DK";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
}
Access requires parentheses in the FROM
clause for queries which include more than one join. Try it this way ...
FROM
((tbl_employee
INNER JOIN tbl_netpay
ON tbl_employee.emp_id = tbl_netpay.emp_id)
INNER JOIN tbl_gross
ON tbl_employee.emp_id = tbl_gross.emp_ID)
INNER JOIN tbl_tax
ON tbl_employee.emp_id = tbl_tax.emp_ID;
If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.
To add global include path use custom command for qmake in Projects/Build/Build Steps section in "Additional arguments" like this:
"QT+=your_qt_modules" "DEFINES+=your_defines"
I think that you can use any command from *.pro files in that way.
The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
This works perfectly when used with onload as:
window.onload = function () {
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
console.log('Page load time is '+ loadTime);
}
Edit 1: Added some context to answer
Note: loadTime
is in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik
The typical answer is this:
In Excel, File/Save As, select CSV, save your current sheet.
transfer to a holding directory on the Pg server the postgres user can access
in PostgreSQL:
COPY mytable FROM '/path/to/csv/file' WITH CSV HEADER; -- must be superuser
But there are other ways to do this too. PostgreSQL is an amazingly programmable database. These include:
Write a module in pl/javaU, pl/perlU, or other untrusted language to access file, parse it, and manage the structure.
Use CSV and the fdw_file to access it as a pseudo-table
Use DBILink and DBD::Excel
Write your own foreign data wrapper for reading Excel files.
The possibilities are literally endless....
The position :fixed
is differ from the other layout.
Once you fixed
the position
for your header
, keep in mind that you have to set the margin-top
for the content
div.
Based on the above mentioned answers, I managed to compare my custom Class Objects like this:
ArrayList<Item> itemList = new ArrayList<>();
...
Collections.sort(itemList, new Comparator<Item>() {
@Override
public int compare(Item item, Item t1) {
String s1 = item.getTitle();
String s2 = t1.getTitle();
return s1.compareToIgnoreCase(s2);
}
});
Since hidden input does not trigger "change" event on change, I used MutationObserver to trigger this instead.
(Sometimes hidden input value changes are done by some other scripts you can't modify)
This does not work in IE10 and below
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var trackChange = function(element) {
var observer = new MutationObserver(function(mutations, observer) {
if(mutations[0].attributeName == "value") {
$(element).trigger("change");
}
});
observer.observe(element, {
attributes: true
});
}
// Just pass an element to the function to start tracking
trackChange( $("input[name=foo]")[0] );
Easiest way:
private String millisToDate(long millis){
return DateFormat.getDateInstance(DateFormat.SHORT).format(millis);
//You can use DateFormat.LONG instead of SHORT
}
For swift 4
@IBOutlet weak var someView: UIView!
let gesture = UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:)))
self.someView.addGestureRecognizer(gesture)
@objc func someAction(_ sender:UITapGestureRecognizer){
print("view was clicked")
}
Here's a a couple of useful link that I found when I started with JNI
http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html
concerning your problem you can use this
JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)
{
const char *nativeString = env->GetStringUTFChars(javaString, 0);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
}
I just copied tools.jar file from JDK\lib folder to JRE\lib folder. Since then it worked like a champ.
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
Check if inside the object there's an array of objects. I had a similar issue with a JSON:
"terms": {
"category": [
{
"ID": 4,
"name": "Cirugia",
"slug": "cirugia",
"description": "",
"taxonomy": "category",
"parent": null,
"count": 68,
"link": "http://distritocuatro.mx/enarm/category/cirugia/"
}
]
}
I tried to access the 'name' key from 'category' and I got the undefined error, because I was using:
var_name = obj_array.terms.category.name
Then I realised it has got square brackets, that means that it has an array of objects inside the category key, because it can have more than one category object. So, in order to get the 'name' key I used this:
var_name = obj_array.terms.category[0].name
And That does the trick.
Maybe it's too late for this answer, but I hope someone with the same problem will find this as I did before finding the Solution :)
Yes to both questions. The using statement gets compiled into a try/finally block
using (SqlConnection connection = new SqlConnection(connectionString))
{
}
is the same as
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
}
finally
{
if(connection != null)
((IDisposable)connection).Dispose();
}
Edit: Fixing the cast to Disposable http://msdn.microsoft.com/en-us/library/yh598w02.aspx
You should do it with getActivity().startActivity(myIntent)
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
Here is a simplistic example of streaming a file:
using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
var path = "<Get the file path using the ID>";
var stream = File.OpenRead(path);
return new FileStreamResult(stream, "application/octet-stream");
}
Note:
Be sure to use FileStreamResult
from Microsoft.AspNetCore.Mvc
and not from System.Web.Mvc
.
This is the simplest way I found for doing this:
byte[] byteArray = ...
InputStream is = new BufferedInputStream(new ByteArrayInputStream(byteArray));
String mimeType = URLConnection.guessContentTypeFromStream(is);
There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.
Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!
You can also use EXIT_SUCCESS
instead of return 0;
. The macro EXIT_SUCCESS
is actually defined as zero, but makes your program more readable.
To see all commands that are being executed by the script, add the -x
flag to your shabang line, and execute the command normally:
#! /bin/bash -x
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include="$include" server::team_l_start="${teamAComm}" server::team_r_start="${teamBComm}" CSVSaver::save='true' CSVSaver::filename='out.csv'
Then if you sometimes want to ignore the debug output, redirect stderr
somewhere.
try it like this
StringBuilder sb = new StringBuilder();
foreach (ListItem item in ddlAge.Items)
{
if (item.Selected)
{
string sqlCommand = "SELECT * from TableA WHERE Age IN (@Age)";
SqlConnection sqlCon = new SqlConnection(connectString);
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = sqlCon;
sqlComm.CommandType = System.Data.CommandType.Text;
sqlComm.CommandText = sqlCommand;
sqlComm.CommandTimeout = 300;
sqlComm.Parameters.Add("@Age", SqlDbType.NVarChar);
sb.Append(item.Text + ",");
sqlComm.Parameters["@Age"].Value = sb.ToString().TrimEnd(',');
}
}
I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.
If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.
For enable, the generic looks to be the following:
update-rc.d <service> enable
Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers
I created blog post on the topic. It contains also link to Github repository with working example.
The trick is using test configuration, where you override original spring bean with fake one. You can use @Primary
and @Profile
annotations for this trick.
Actually Boost does have such adaptor: boost::adaptors::reverse
.
#include <list>
#include <iostream>
#include <boost/range/adaptor/reversed.hpp>
int main()
{
std::list<int> x { 2, 3, 5, 7, 11, 13, 17, 19 };
for (auto i : boost::adaptors::reverse(x))
std::cout << i << '\n';
for (auto i : x)
std::cout << i << '\n';
}
use this code
test.remove(test.indexOf(obj));
test is your ArrayList and obj is the Object, first you find the index of obj in ArrayList and then you remove it from the ArrayList.
Here is a simple solution put this CSS
@media print{
.noprint{
display:none;
}
}
and here is the HTML
<div class="noprint">
element that need to be hidden when printing
</div>
This works fine
@echo off
set word=table
set str=jump over the chair
set rpl=%str:chair=%%word%
echo %rpl%
It could be something like
var myvar = from a in context.MyEntity
join b in context.MyEntity2 on a.key equals b.key
select new { prop1 = a.prop1, prop2= b.prop1};
You can use like this.
when: condition1 == "condition1" or condition2 == "condition2"
Link to official docs: The When Statement.
Also Please refer to this gist: https://gist.github.com/marcusphi/6791404
class1 item = lst[index];
item.foo = bar;
Something like this:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
];
var results = [];
var toSearch = "lo";
for(var i=0; i<objects.length; i++) {
for(key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
results.push(objects[i]);
}
}
}
The results array will contain all matched objects.
If you search for 'lo', the result will be like:
[{ foo="lorem", bar="ipsum"}, { foo="dolor", bar="amet"}]
NEW VERSION - Added trim code, code to ensure no duplicates in result set.
function trimString(s) {
var l=0, r=s.length -1;
while(l < s.length && s[l] == ' ') l++;
while(r > l && s[r] == ' ') r-=1;
return s.substring(l, r+1);
}
function compareObjects(o1, o2) {
var k = '';
for(k in o1) if(o1[k] != o2[k]) return false;
for(k in o2) if(o1[k] != o2[k]) return false;
return true;
}
function itemExists(haystack, needle) {
for(var i=0; i<haystack.length; i++) if(compareObjects(haystack[i], needle)) return true;
return false;
}
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor blor",
"bar" : "amet blo"
}
];
function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('lo '));
It ought to be possible to pack the 'cannot be a perfect square if the last X digits are N' much more efficiently than that! I'll use java 32 bit ints, and produce enough data to check the last 16 bits of the number - that's 2048 hexadecimal int values.
...
Ok. Either I have run into some number theory that is a little beyond me, or there is a bug in my code. In any case, here is the code:
public static void main(String[] args) {
final int BITS = 16;
BitSet foo = new BitSet();
for(int i = 0; i< (1<<BITS); i++) {
int sq = (i*i);
sq = sq & ((1<<BITS)-1);
foo.set(sq);
}
System.out.println("int[] mayBeASquare = {");
for(int i = 0; i< 1<<(BITS-5); i++) {
int kk = 0;
for(int j = 0; j<32; j++) {
if(foo.get((i << 5) | j)) {
kk |= 1<<j;
}
}
System.out.print("0x" + Integer.toHexString(kk) + ", ");
if(i%8 == 7) System.out.println();
}
System.out.println("};");
}
and here are the results:
(ed: elided for poor performance in prettify.js; view revision history to see.)
"A call stack is composed of stack frames..." — Wikipedia
A stack frame is a thing that you put on the stack. They are data structures that contain information about subroutines to call.
If any one get error "failed-to-resolve-junitjunit4-12" then go to HTTP PRoxy setting check your internet connection. if you are using any proxy server at school / college then set your proxy setting and test connect if it successful then apply setting and run again gradle you will get resolve all error. I try this and i resolve all errors. Note : no need to remove Junit....!! Umair
Seems to me that you're asking about static variables but you also point out static methods in your examples.
Static variables are not evil - they have its adoption as global variables like constants in most cases combined with final modifier, but as it said don't overuse them.
Static methods aka utility method. It isn't generally a bad practice to use them but major concern is that they might obstruct testing.
As a example of great java project that use a lot of statics and do it right way please look at Play! framework. There is also discussion about it in SO.
Static variables/methods combined with static import are also widely used in libraries that facilitate declarative programming in java like: make it easy or Hamcrest. It wouldn't be possible without a lot of static variables and methods.
So static variables (and methods) are good but use them wisely!
git push origin --delete <branch name>
Referenced from: http://www.gitguys.com/topics/adding-and-removing-remote-branches/
If you want to serialize the ArrayList object to a file so you can read it back in again later use ObjectOuputStream/ObjectInputStream writeObject()/readObject() since ArrayList implements Serializable. It's not clear to me from your question if you want to do this or just write each individual item. If so then Andrey's answer will do that.
With current latest python 3.6.5
pip3 install PyQt5
works fine
My solution was to create an attribute to validate strings, it does a bunch of extra common features, including regex validation that you can use to check for numbers only and then later I convert to integers as needed...
This is how you use:
public class MustBeListAndContainAttribute : ValidationAttribute
{
private Regex regex = null;
public bool RemoveDuplicates { get; }
public string Separator { get; }
public int MinimumItems { get; }
public int MaximumItems { get; }
public MustBeListAndContainAttribute(string regexEachItem,
int minimumItems = 1,
int maximumItems = 0,
string separator = ",",
bool removeDuplicates = false) : base()
{
this.MinimumItems = minimumItems;
this.MaximumItems = maximumItems;
this.Separator = separator;
this.RemoveDuplicates = removeDuplicates;
if (!string.IsNullOrEmpty(regexEachItem))
regex = new Regex(regexEachItem, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var listOfdValues = (value as List<string>)?[0];
if (string.IsNullOrWhiteSpace(listOfdValues))
{
if (MinimumItems > 0)
return new ValidationResult(this.ErrorMessage);
else
return null;
};
var list = new List<string>();
list.AddRange(listOfdValues.Split(new[] { Separator }, System.StringSplitOptions.RemoveEmptyEntries));
if (RemoveDuplicates) list = list.Distinct().ToList();
var prop = validationContext.ObjectType.GetProperty(validationContext.MemberName);
prop.SetValue(validationContext.ObjectInstance, list);
value = list;
if (regex != null)
if (list.Any(c => string.IsNullOrWhiteSpace(c) || !regex.IsMatch(c)))
return new ValidationResult(this.ErrorMessage);
return null;
}
}
To check if a folder exists or not, you can simply use the exists()
method:
// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )
// If it doesn't exist
if( !folder.exists() ) {
// Create all folders up-to and including B
folder.mkdirs()
}
// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
w << "Some text\n"
}
git reset HEAD^
then the modified files should show up.
You could move the modified files into a new branch
use,
git checkout -b newbranch
git checkout commit -m "files modified"
git push origin newbranch
git checkout master
then you should be on a clean branch, and your changes should be stored in newbranch. You could later just merge this change into the master branch
Call below method just after calling the method for opening new window, this will close the current window.
private void close(){
WindowEvent windowEventClosing = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowEventClosing);
}
Also in properties of JFrame, make sure defaultCloseOperation is set as DISPOSE.
For complete cross browser, use:
cursor: pointer;
cursor: hand;
First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,
C:\Python34\Scripts
Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd
will pop up. Write the below code in that cmd
window,
pip install PySerial
and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.
after successfully installed the module open python IDLE and write down the bellow code and run it.
import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
You can do this:
CSS:
#container {
height:175px;
}
#container h3{
position:absolute;
bottom:0;
left:0;
}
Then in HTML:
<div class="row">
<div class="col-sm-6">
<img src="//placehold.it/600x300" alt="Logo" />
</div>
<div id="container" class="col-sm-6">
<h3>Some Text</h3>
</div>
</div>
EDIT: add the <
Try width: max-content
to adjust the width of the div by it's content.
<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
width:500px;
margin: auto;
border: 3px solid #73AD21;
}
div.ex2 {
width: max-content;
margin: auto;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="ex1">This div element has width 500px;</div>
<br>
<div class="ex2">Width by content size</div>
</body>
</html>
I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.
I assume it was something to do with iostream manipulations in the constructor.
Here is the fix:
// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
cout << "Some text I was printing.." << endl;
};
// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
};
Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.
serialize()
is the function you are looking for. It will return a string representation of its input array or object in a PHP-specific internal format. The string may be converted back to its original form with unserialize()
.
But beware, that not all objects are serializable, or some may be only partially serializable and unable to be completely restored with unserialize()
.
$array = array(1,2,3,'foo');
echo serialize($array);
// Prints
a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;s:3:"foo";}
I've googled around also and found this solution:
You have a variable Project
somewhere that is not a function. Then the new
operator will complain about it. Try console.log(Project)
at the place where you would have used it as a construcotr, and you will find it.
Another option to include_once or require_once is to use class autoloading. http://php.net/manual/en/language.oop5.autoload.php
This code is correct but if you entered a lot of space (' ') instead of null or empty string return false.
To correct this use regular expresion (this code below check if the variable is null or empty or blank the same as org.apache.commons.lang.StringUtils.isNotBlank) :
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${not empty description}">
<c:set var="description" value="${fn:replace(description, ' ', '')}" />
<c:if test="${not empty description}">
The description is not blank.
</c:if>
</c:if>
Instead of
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
Use
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
I would suggest you try the html tag <br>
, in case your marketing application will recognize it.
I use %0D%0A
. This should work as long as the email is HTML formatted.
<a href="mailto:[email protected]?subject=Subscribe&body=Lastame%20%3A%0D%0AFirstname%20%3A"><img alt="Subscribe" class="center" height="50" src="subscribe.png" style="width: 137px; height: 50px; color: #4da6f7; font-size: 20px; display: block;" width="137"></a>
You will likely want to take out the %20 before Firstname, otherwise you will have a space as the first character on the next line.
A note, when I tested this with your code, it worked (along with some extra spacing). Are you using a mail client that doesn't allow HTML formatting?
Or, just add your binary path into the PATH. At the end of the bashrc:
...
export PATH=$PATH:/home/user/.local/bin/
save the file and run:
source .bashrc
and the command will work.
The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.
plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) ) )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
}
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))
Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;
MySQL – Temporarily disable Foreign Key Checks or Constraints
Assuming you are coming from Python and accept this as the same thing:
def setLinkerAt(value, rowIndex):
isEnough = lambda i: return i < dataColLinker.count()
while (not isEnough(rowIndex)):
dataColLinker.append(value)
else:
dataColLinker[rowIndex] = value
The most similar I could come up with was:
public void setLinkerAt( int value, int rowIndex) {
isEnough = (i) -> { return i < dataColLine.size; }
if(isEnough()){
dataColLinker.set(rowIndex, value);
}
else while(!isEnough(rowInex)) {
dataColLinker.add(value);
}
Note the need for the logic, and the reverse logic. I'm not sure this is a great solution (duplication of the logic), but the braceless else
is the closest syntax I could think of, while maintaining the same act of not executing the logic more than required.
Don't reinvent the wheel!
There's a Google Code library that does this for you: Hamcrest
[Hamcrest] Provides a library of matcher objects (also known as constraints or predicates) allowing 'match' rules to be defined declaratively, to be used in other frameworks. Typical scenarios include testing frameworks, mocking libraries and UI validation rules.
Just to share my idea...
I created a custom class to inherit the Label class. I added a private variable assigned as a Tooltip class and a public property, TooltipText. Then, gave it a MouseEnter delegate method. This is an easy way to work with multiple Label controls and not have to worry about assigning your Tooltip control for each Label control.
public partial class ucLabel : Label
{
private ToolTip _tt = new ToolTip();
public string TooltipText { get; set; }
public ucLabel() : base() {
_tt.AutoPopDelay = 1500;
_tt.InitialDelay = 400;
// _tt.IsBalloon = true;
_tt.UseAnimation = true;
_tt.UseFading = true;
_tt.Active = true;
this.MouseEnter += new EventHandler(this.ucLabel_MouseEnter);
}
private void ucLabel_MouseEnter(object sender, EventArgs ea)
{
if (!string.IsNullOrEmpty(this.TooltipText))
{
_tt.SetToolTip(this, this.TooltipText);
_tt.Show(this.TooltipText, this.Parent);
}
}
}
In the form or user control's InitializeComponent method (the Designer code), reassign your Label control to the custom class:
this.lblMyLabel = new ucLabel();
Also, change the private variable reference in the Designer code:
private ucLabel lblMyLabel;
On the Mac:
Instead of JAVA_OPTS
and MAVEN_OPTS
, use _JAVA_OPTIONS instead. This works!
Does it have to be gray? You could just set the opacity of the image lower (to dull it). Alternatively, you could create a <div>
overlay and set that to be gray (change the alpha to get the effect).
html:
<div id="wrapper">
<img id="myImage" src="something.jpg" />
</div>
css:
#myImage {
opacity: 0.4;
filter: alpha(opacity=40); /* msie */
}
/* or */
#wrapper {
opacity: 0.4;
filter: alpha(opacity=40); /* msie */
background-color: #000;
}
public class Main {
public static void main(String[] args) throws Exception{
int N = 100;
PrintingThread oddNumberThread = new PrintingThread(N - 1);
PrintingThread evenNumberThread = new PrintingThread(N);
oddNumberThread.start();
// make sure that even thread only start after odd thread
while (!evenNumberThread.isAlive()) {
if(oddNumberThread.isAlive()) {
evenNumberThread.start();
} else {
Thread.sleep(100);
}
}
}
}
class PrintingThread extends Thread {
private static final Object object = new Object(); // lock for both threads
final int N;
// N determines whether given thread is even or odd
PrintingThread(int N) {
this.N = N;
}
@Override
public void run() {
synchronized (object) {
int start = N % 2 == 0 ? 2 : 1; // if N is odd start from 1 else start from 0
for (int i = start; i <= N; i = i + 2) {
System.out.println(i);
try {
object.notify(); // will notify waiting thread
object.wait(); // will make current thread wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
The answer to the above question is "none of the above". When you download new STS it won't support the old Spring Boot parent version. Just update parent version with latest comes with STS it will work.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
If you have problem getting the latest, just create a new Spring Starter Project. Go to File->New->Spring Start Project and create a demo project you will get the latest parent version, change your version with that all will work. I do this every time I change STS.
If you need to investigate which Parcel is causing your crash, you should consider trying TooLargeTool.
(I found this as a comment from @Max Spencer under the accepted answer and it was helpful in my case.)
If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest
android:exported="true"
Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.
finish();
The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class
in the code, so compile will fail.
I searched on the web and found something like this below, and it works well.
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);
You can also use the setClassName method:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();
You can also pass the values from one app to another app :
Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
launchIntent.putExtra("AppID", "MY-CHILD-APP1");
launchIntent.putExtra("UserID", "MY-APP");
launchIntent.putExtra("Password", "MY-PASSWORD");
startActivity(launchIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}
Just download the apk from talkback website
Drag the downloaded apk to the started emulator, Go to settings on emulator > Search for talkback, you will now find it there
I got a easy solution which will select from database table and let you do easily.
SELECT b.FirstName + b.LastName FROM tbl_Users b WHERE b.Id='11'
You can easily add a space there if you try
SELECT b.FirstName +' '+ b.LastName FROM Users b WHERE b.Id='23'
Here you can combine as much as your table have.
If you want to format the JSON and also do some syntax highlighting, you can use the ng-prettyjson
directive. See the npm package.
Here is how to use it: <pre pretty-json="jsonObject"></pre>
in my system it was
nano /usr/local/etc/my.cnf.default
as template and
nano /usr/local/etc/my.cnf
as working.
As written before, but for beginner like me don't forget to include the return.
$this->response->statusCode(200);
return $this->response;
You can simply use setInterval
to create such timer in Angular, Use this Code for timer -
timeLeft: number = 60;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{timeLeft}} Seconds Left....</p>
import { timer } from 'rxjs';
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.timeLeft - val;
});
}
<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}
For more information read here
Some points:
X
or X&
or X const
&
) the compiler will generate the
default copy-constructor. T const &
or T
or T&
then the
compiler will nevertheless generate a
default non-templated
copy-constructor, even though you may think that it shouldn't because when T = X the declaration matches the copy-constructor declaration.HTH
If you want to add 10 items to your ArrayList
you may try that:
for (int i = 0; i < 10; i++)
arr.add(i);
If you have already declare an array size variable you would use the variable size
instead of number '10'
If you want to merge changes in SubBranch to MainBranch
git checkout MainBranch
git merge SubBranch
//means deviation in c++
/A deviation that is a difference between an observed value and the true value of a quantity of interest (such as a population mean) is an error and a deviation that is the difference between the observed value and an estimate of the true value (such an estimate may be a sample mean) is a residual. These concepts are applicable for data at the interval and ratio levels of measurement./
#include <iostream>
#include <conio.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv)
{
int i,cnt;
cout<<"please inter count:\t";
cin>>cnt;
float *num=new float [cnt];
float *s=new float [cnt];
float sum=0,ave,M,M_D;
for(i=0;i<cnt;i++)
{
cin>>num[i];
sum+=num[i];
}
ave=sum/cnt;
for(i=0;i<cnt;i++)
{
s[i]=ave-num[i];
if(s[i]<0)
{
s[i]=s[i]*(-1);
}
cout<<"\n|ave - number| = "<<s[i];
M+=s[i];
}
M_D=M/cnt;
cout<<"\n\n Average: "<<ave;
cout<<"\n M.D(Mean Deviation): "<<M_D;
getch();
return 0;
}
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
Well, the problem was that, somehow, the path was not recognized when was inserted in src
by a variable. I had to create a variable like this:
path:any = require("../../img/myImage.png");
and then I can use it in src
. Thanks everyone!
Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.
Improved version of answer from Jurrie
$('#myRadio').off('click').on('click', function() {
if ($(this).data('checked')) {
$(this).removeAttr('checked');
$(this).data('checked', false);
} else {
$(this).data('checked', true);
}
});
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
In my particular case, I had a similar error on a legacy website used in my organization. To solve the issue, I had to list the website a a "Trusted site".
To do so:
I'm leaving this here in the remote case it will help someone.
android:imeActionLabel="Done"
android:singleLine="true"
In the XML file works just fine. But this will also cause the editText
to keep typing in a single line which you may not want. So adding following to your code will make sure that you won't end up typing everything on a single line.
mainText.setHorizontallyScrolling(false);
mainText.setMaxLines("Maximum integer value that you want to provide");
There can be more than one main method in a single program. Others are Overloaded method. This overloaded method works fine under a single main method
public class MainMultiple{
public static void main(String args[]){
main(122);
main('f');
main("hello java");
}
public static void main(int i){
System.out.println("Overloaded main()"+i);
}
public static void main(char i){
System.out.println("Overloaded main()"+i);
}
public static void main(String str){
System.out.println("Overloaded main()"+str);
}
}
this make me success!
prefix: classpath:/templates/
check your application.yml
A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above.
With PYTHONPATH set as in your example, you should be able to do
python -m gmbx
-m
option will make Python search for your module in paths Python usually searches modules in, including what you added to PYTHONPATH. When you run interpreter like python gmbx.py
, it looks for particular file and PYTHONPATH does not apply.
You can use pragma related commands in sqlite like below
pragma table_info("table_name")
--Alternatively
select * from pragma_table_info("table_name")
If you require column names like id|foo|bar|age|street|address
, basically your answer is in below query.
select group_concat(name,'|') from pragma_table_info("table_name")
class PushObjects {
testMethod(): Array<number> {
//declaration and initialisation of array onject
var objs: number[] = [1,2,3,4,5,7];
//push the elements into the array object
objs.push(100);
//pop the elements from the array
objs.pop();
return objs;
}
}
let pushObj = new PushObjects();
//create the button element from the dom object
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () {
alert(pushObj.testMethod());
}
document.body.appendChild(btn);
The following code is based on Brandon Tilley's answer :
var http = require('http'),
fs = require('fs');
var request = http.get("http://example12345.com/yourfile.html", function(response) {
if (response.statusCode === 200) {
var file = fs.createWriteStream("copy.html");
response.pipe(file);
}
// Add timeout.
request.setTimeout(12000, function () {
request.abort();
});
});
Don't make file when you get an error, and prefere to use timeout to close your request after X secondes.
JDK: The complete package which you need to write and run java code
OpenJDK: An independent implementation of JDK for making it much better
JVM: Converts Java code into bytecode and provides the specifications which tells how should a Java code be compiled, loaded, verified, checked for errors and executed.
JRE: Implementation of the JVM with which some Java libraries are used to Run the program
This works for me:
var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]
Your issue could be with how you're declaring your array to begin with.
EDIT:
To fix your function, you have to cast your Slice
to an array:
func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
var newNumbers = Array(numbers[0..<position])
return newNumbers
}
// test
aFunction([1, 2, 3], 2) // returns [1, 2]
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<meta name="description" content="">_x000D_
<meta name="author" content="">_x000D_
_x000D_
<title>3 Col Portfolio - Start Bootstrap Template</title>_x000D_
_x000D_
<!-- Bootstrap Core CSS -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>_x000D_
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<!-- Navigation -->_x000D_
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
<div class="container">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Start Bootstrap</a>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav">_x000D_
<li>_x000D_
<a href="#">About</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Services</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Contact</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="navbar-form navbar-right">_x000D_
<div class="input-group">_x000D_
<input type="text" name="keyword" placeholder="search..." class="form-control">_x000D_
<span class="input-group-btn">_x000D_
<button class="btn btn-default">Go</button>_x000D_
</span>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container -->_x000D_
</nav>_x000D_
_x000D_
<!-- Page Content -->_x000D_
<div class="container">_x000D_
_x000D_
<!-- Page Header -->_x000D_
<div class="row">_x000D_
<div class="col-lg-12">_x000D_
<h1 class="page-header">Page Heading_x000D_
<small>Secondary Text</small>_x000D_
</h1>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<hr>_x000D_
_x000D_
<!-- Pagination -->_x000D_
<div class="row text-center">_x000D_
<div class="col-lg-12">_x000D_
<ul class="pagination">_x000D_
<li>_x000D_
<a href="#">«</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#">1</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">2</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">3</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">4</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">5</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">»</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
</div>_x000D_
<!-- Footer -->_x000D_
<footer>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>About</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-home"></i> Your company address here_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-earphone"></i> 0982.808.065_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-envelope"></i> [email protected]_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-flag"></i> <a href="#">Fan page</a>_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-time"></i> 08:00-18:00 Monday to Friday_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>Support</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#" class="link">Terms of Service</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Privacy policy</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Warranty commitment</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Site map</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>Other</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod_x000D_
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo_x000D_
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse_x000D_
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
</footer>_x000D_
_x000D_
<!-- /.container -->_x000D_
_x000D_
<!-- jQuery -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Bootstrap Core JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Try:
$counter = 0;
foreach ($Contents as $item) {
something
your code ...
$counter++;
}
$total_count=$counter-1;
So if the insert time is what you need, it's already there:
Login to mongodb shell
ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test
Create your database by inserting items
> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
>
Lets make that database the one we are on now
> use penguins
switched to db penguins
Get the rows back:
> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }
Get each row in yyyy-MM-dd HH:mm:ss format:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53
If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131
You can try this:
public String ConnectionQuality() {
NetworkInfo info = getInfo(context);
if (info == null || !info.isConnected()) {
return "UNKNOWN";
}
if(info.getType() == ConnectivityManager.TYPE_WIFI) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int numberOfLevels = 5;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);
if(level == 2 )
return "POOR";
else if(level == 3 )
return "MODERATE";
else if(level == 4 )
return "GOOD";
else if(level == 5 )
return "EXCELLENT";
else
return "UNKNOWN";
}else if(info.getType() == ConnectivityManager.TYPE_MOBILE) {
int networkClass = getNetworkClass(getNetworkType(context));
if(networkClass == 1)
return "POOR";
else if(networkClass == 2 )
return "GOOD";
else if(networkClass == 3 )
return "EXCELLENT";
else
return "UNKNOWN";
}else
return "UNKNOWN";
}
public NetworkInfo getInfo(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
}
public int getNetworkClass(int networkType) {
try {
return getNetworkClassReflect(networkType);
}catch (Exception ignored) {
}
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case 16: // TelephonyManager.NETWORK_TYPE_GSM:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return 1;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
case 17: // TelephonyManager.NETWORK_TYPE_TD_SCDMA:
return 2;
case TelephonyManager.NETWORK_TYPE_LTE:
case 18: // TelephonyManager.NETWORK_TYPE_IWLAN:
return 3;
default:
return 0;
}
}
private int getNetworkClassReflect(int networkType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method getNetworkClass = TelephonyManager.class.getDeclaredMethod("getNetworkClass", int.class);
if (!getNetworkClass.isAccessible()) {
getNetworkClass.setAccessible(true);
}
return (Integer) getNetworkClass.invoke(null, networkType);
}
public static int getNetworkType(Context context) {
return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkType();
}
Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is obj
and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.
In VB like this:
Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")
Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True
Using ms As New MemoryStream(), _
sw As XmlWriter = XmlWriter.Create(ms, settings), _
sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using
in C# like this:
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);
after you created the RSA key pair, you must to add it to SSH using:
ssh-add ~/.ssh/id_rsa
or wherever you created your rsa key pair.
.arrow {_x000D_
display : inline-block;_x000D_
font-size: 10px; /* adjust size */_x000D_
line-height: 1em; /* adjust vertical positioning */_x000D_
border: 3px solid #000000;_x000D_
border-left: transparent;_x000D_
border-bottom: transparent;_x000D_
width: 1em; /* use font-size to change overall size */_x000D_
height: 1em; /* use font-size to change overall size */_x000D_
}_x000D_
_x000D_
.arrow:before {_x000D_
content: "\00a0"; /* needed to hook line-height to "something" */_x000D_
}_x000D_
_x000D_
.arrow.left {_x000D_
margin-left: 0.5em;_x000D_
-webkit-transform: rotate(225deg);_x000D_
-moz-transform: rotate(225deg);_x000D_
-o-transform: rotate(225deg);_x000D_
-ms-transform: rotate(225deg);_x000D_
transform: rotate(225deg);_x000D_
}_x000D_
_x000D_
.arrow.right {_x000D_
margin-right: 0.5em;_x000D_
-webkit-transform: rotate(45deg);_x000D_
-moz-transform: rotate(45deg);_x000D_
-o-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
}_x000D_
_x000D_
.arrow.top {_x000D_
line-height: 0.5em; /* use this to adjust vertical positioning */_x000D_
margin-left: 0.5em;_x000D_
margin-right: 0.5em;_x000D_
-webkit-transform: rotate(-45deg);_x000D_
-moz-transform: rotate(-45deg);_x000D_
-o-transform: rotate(-45deg);_x000D_
-ms-transform: rotate(-45deg);_x000D_
transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.arrow.bottom {_x000D_
line-height: 2em;_x000D_
/* use this to adjust vertical positioning */_x000D_
margin-left: 0.5em;_x000D_
margin-right: 0.5em;_x000D_
-webkit-transform: rotate(135deg);_x000D_
-moz-transform: rotate(135deg);_x000D_
-o-transform: rotate(135deg);_x000D_
-ms-transform: rotate(135deg);_x000D_
transform: rotate(135deg);_x000D_
}
_x000D_
<div>_x000D_
here are some arrows_x000D_
<div class='arrow left'></div> space_x000D_
<div class='arrow right'></div> space_x000D_
<div class='arrow top'></div> space_x000D_
<div class='arrow bottom'></div> space with proper spacing?_x000D_
</div>
_x000D_
Similar to Roko C, but a little more control over size and placement.
Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:
par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels
#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"
end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)
barplot(mtcars$qsec, col = "grey50",
main = "",
ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
xlab = "",
space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25,
srt = 60, adj = 1, xpd = TRUE,
labels = paste(rownames(mtcars)), cex = 0.65)
Why dont you use?:
string[] ssizes = myStr.Split(' ', '\t');
In ubuntu you can simply use color codes:
var sys = require('sys');
process.stdout.write("x1B[31m" + your_message_in_red + "\x1B[0m\r\n");
multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.
The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).
The payload passed looks something like this:
Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”file”; filename=”captcha”
Content-Type:
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”action”
submit
-----WebKitFormBoundary7MA4YWxkTrZu0gW--
On the webservice side, it's consumed in @Consumes("multipart/form-data") form.
Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.
The way to do this using the Extention Methods, instead of the linq query syntax would be like this:
var results = workOrders.Join(plans,
wo => wo.WorkOrderNumber,
p => p.WorkOrderNumber,
(order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);
The answer is in the current spec:
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.
Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.
Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.
The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.
Reference:
Also see:
It looks like there's been a lot of confusion about this element's purpose, but the one thing that's agreed upon is that it is not a generic wrapper, like <div>
is. It should be used for semantic purposes, and not a CSS or JavaScript hook (although it certainly can be styled or "scripted").
A better example, from my understanding, might look something like this:
<div id="content">
<article>
<h2>How to use the section tag</h2>
<section id="disclaimer">
<h3>Disclaimer</h3>
<p>Don't take my word for it...</p>
</section>
<section id="examples">
<h3>Examples</h3>
<p>But here's how I would do it...</p>
</section>
<section id="closing_notes">
<h3>Closing Notes</h3>
<p>Well that was fun. I wonder if the spec will change next week?</p>
</section>
</article>
</div>
Note that <div>
, being completely non-semantic, can be used anywhere in the document that the HTML spec allows it, but is not necessary.
You can use pseudoelements. E.g.
div {_x000D_
width : 200px;_x000D_
height : 50px; _x000D_
position: relative;_x000D_
z-index : 1;_x000D_
background: #eee;_x000D_
}_x000D_
_x000D_
div:before {_x000D_
content : "";_x000D_
position: absolute;_x000D_
left : 0;_x000D_
bottom : 0;_x000D_
height : 1px;_x000D_
width : 50%; /* or 100px */_x000D_
border-bottom:1px solid magenta;_x000D_
}
_x000D_
<div>Item 1</div>_x000D_
<div>Item 2</div>
_x000D_
No need to use extra markup for presentational purpose. :after is also supported from IE8.
edit:
if you need a right-aligned border, just change left: 0
with right: 0
if you need a center-aligned border just simply set left: 50px;
Stuff them into a map
(pseudocode)
map[string -> int] $m
foreach($word in $array)
{
if(!$m.contains($word))
$m[$word] = 0;
$m[$word] += 1;
}
So it's throwing up that error message because you have apache2
running on port 80.
If this is for development, I would just leave it as it is on port 5000.
If it's for production either:
Not Recommended
apache2
first; Not recommended as it states in the documentation:
You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)
Recommended
HTTP
traffic through apache2
to Flask.This way, apache2
can handle all your static files (which it's very good at - much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.
Here's a link to the official documentation about setting up Flask with Apache + mod_wsgi.
Edit 1 - Clarification for @Djack
Proxy HTTP traffic to Flask through apache2
When a request comes to the server on port 80 (HTTP
) or port 443 (HTTPS
) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the "dynamic" part.
reverse proxy for dynamic content
There are a few advantages to configuring your web server like the above;
The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.
This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.
If you still want to use ad-hoc transactions, you can always execute
BEGIN TRANSACTION
within SSMS, and than the system waits for you to commit the data.
If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in
Tools -> Options -> Query Execution -> SQL Server -> ANSI
The thing you are missing is which encoding scheme is being used. There are different ways to encode binary numbers. Look into signed number representations. For 9 bits, the ranges and the amount of numbers that can be represented will differ depending on the system used.
You set the CSS to :
#elementID {
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
height: 200px;
}
It centers the image, but does not scale it.
In newer browsers you can use the background-size
property and do:
#elementID {
height: 200px;
width: 100%;
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
background-size: 100% 100%;
}
Other than that, a regular image is one way to do it, but then it's not really a background image.
?
This works with everything with background:
Textview, Button...
TextView text = (TextView) View.findViewById(R.id.MyText);
text.setBackgroundResource(Icon);
text.getBackground().setColorFilter(getResources().getColor(Color), PorterDuff.Mode.SRC_ATOP);
When you open a transaction nothing gets locked by itself. But if you execute some queries inside that transaction, depending on the isolation level, some rows, tables or pages get locked so it will affect other queries that try to access them from other transactions.
There are limitations in PUT over PATCH while making updates. Using PUT requires us to specify all attributes even if we want to change only one attribute. But if we use the PATCH method we can update only the fields we need and there is no need to mention all the fields. PATCH does not allow us to modify a value in an array, or remove an attribute or array entry.
With the code you provided, you cannot expect anything to happen. I second @mashappslabs : first add an event handler :
$("selector").click(function() {
console.log("element was clicked"); // or alert("click");
});
then trigger your event :
$("selector").click(); //or
$("selector").trigger("click");
and you should see the message in your console.
For your interest, to do the same with double
double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75
or just
double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n", doubleVal);
System.out.printf("bdTest1: %.2f%n", doubleVal2);
both print
bdTest: 1.75
bdTest1: 0.75
I prefer to keep code as simple as possible. ;)
As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335
are a little less than they appear.
An easy way to serialize Enum is using @JsonFormat annotation. @JsonFormat can configure the serialization of a Enum in three ways.
@JsonFormat.Shape.STRING
public Enum OrderType {...}
uses OrderType::name as the serialization method. Serialization of OrderType.TypeA is “TYPEA”
@JsonFormat.Shape.NUMBER
Public Enum OrderTYpe{...}
uses OrderType::ordinal as the serialization method. Serialization of OrderType.TypeA is 1
@JsonFormat.Shape.OBJECT
Public Enum OrderType{...}
treats OrderType as a POJO. Serialization of OrderType.TypeA is {"id":1,"name":"Type A"}
JsonFormat.Shape.OBJECT is what you need in your case.
A little more complicated way is your solution, specifying a serializer for the Enum.
Check out this reference: https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.html
Press F9 two times in less than 2 seconds = Normal view 0/360º
Press F10 two times in less than 2 seconds = Rotate 180º.
Press F11 two times in less than 2 seconds = Rotate 90º to the RiGHT.
Press F12 two times in less than 2 seconds = Rotate 90º to the LEFT.
Mine is installed under /usr/share/jenkins I thought it was installed via apt-get so might want to check there as well.
Ubuntu 12.04.1
It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.
The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.
The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).
I wrote a blog describing the pros/cons of DinD vs DooD here.
Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
Double quotes can be achieved using VBA in one of two ways
First one is often the best
"...text..." & Chr(34) & "...text..."
Or the second one, which is more literal
"...text..." & """" & "...text..."
For me creating a python file named template_filters.py
in my App with below content did the job
# coding=utf-8
from django.template.base import Library
register = Library()
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
usage is like what culebrón said :
{{ mydict|get_item:item.NAME }}
This was driving me bonkers as the .astype()
solution above didn't work for me. But I found another way. Haven't timed it or anything, but might work for others out there:
t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')
print pd.Timedelta(t2 - t1).seconds / 3600.0
...if you want hours. Or:
print pd.Timedelta(t2 - t1).seconds / 60.0
...if you want minutes.
Give them a trivial pom with these jars listed as dependencies and instructions to run:
mvn dependency:go-offline
This will pull the dependencies to the local repo.
A more direct solution is dependency:get, but it's a lot of arguments to type:
mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version
Seems like you are running it not as "root". Only root can bind to this port (80). Check your configuration in the conf/httpd.conf file, Listen line and change the port to higher one.
Absolute path routing
There are 2 methods for navigation, .navigate()
and .navigateByUrl()
You can use the method .navigateByUrl()
for absolute path routing:
import {Router} from '@angular/router';
constructor(private router: Router) {}
navigateToLogin() {
this.router.navigateByUrl('/login');
}
You put the absolute path to the URL of the component you want to navigate to.
Note: Always specify the complete absolute path when calling router's navigateByUrl
method. Absolute paths must start with a leading /
// Absolute route - Goes up to root level
this.router.navigate(['/root/child/child']);
// Absolute route - Goes up to root level with route params
this.router.navigate(['/root/child', crisis.id]);
Relative path routing
If you want to use relative path routing, use the .navigate()
method.
NOTE: It's a little unintuitive how the routing works, particularly parent, sibling, and child routes:
// Parent route - Goes up one level
// (notice the how it seems like you're going up 2 levels)
this.router.navigate(['../../parent'], { relativeTo: this.route });
// Sibling route - Stays at the current level and moves laterally,
// (looks like up to parent then down to sibling)
this.router.navigate(['../sibling'], { relativeTo: this.route });
// Child route - Moves down one level
this.router.navigate(['./child'], { relativeTo: this.route });
// Moves laterally, and also add route parameters
// if you are at the root and crisis.id = 15, will result in '/sibling/15'
this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route });
// Moves laterally, and also add multiple route parameters
// will result in '/sibling;id=15;foo=foo'.
// Note: this does not produce query string URL notation with ? and & ... instead it
// produces a matrix URL notation, an alternative way to pass parameters in a URL.
this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route });
Or if you just need to navigate within the current route path, but to a different route parameter:
// If crisis.id has a value of '15'
// This will take you from `/hero` to `/hero/15`
this.router.navigate([crisis.id], { relativeTo: this.route });
Link parameters array
A link parameters array holds the following ingredients for router navigation:
['/hero']
['/hero', hero.id]
or ['/hero', { id: hero.id, foo: baa }]
Directory-like syntax
The router supports directory-like syntax in a link parameters list to help guide route name lookup:
./
or no leading slash is relative to the current level.
../
to go up one level in the route path.
You can combine relative navigation syntax with an ancestor path. If you must navigate to a sibling route, you could use the ../<sibling>
convention to go up one level, then over and down the sibling route path.
Important notes about relative nagivation
To navigate a relative path with the Router.navigate
method, you must supply the ActivatedRoute
to give the router knowledge of where you are in the current route tree.
After the link parameters array, add an object with a relativeTo
property set to the ActivatedRoute
. The router then calculates the target URL based on the active route's location.
From official Angular Router Documentation
Does the -verbose
flag to your java
command yield any useful info? If not, maybe java -X
reveals something specific to your version that might help?
You need to pass optimized: false
.
E.g.
var img = { url: 'img/puff.svg', scaledSide: new google.maps.Size(5, 5) };
new google.maps.Marker({position: this.mapOptions.center, map: this.map, icon: img, optimized: false,});
Without passing optimized: false
, my svg appeared as a static image.
Here's yet another alternative:
template<typename T>
void Remove( std::basic_string<T> & Str, const T * CharsToRemove )
{
std::basic_string<T>::size_type pos = 0;
while (( pos = Str.find_first_of( CharsToRemove, pos )) != std::basic_string<T>::npos )
{
Str.erase( pos, 1 );
}
}
std::string a ("(555) 555-5555");
Remove( a, "()-");
Works with std::string and std::wstring
For my case, I have a dropdown list in my div container, so I can not use overflow: hidden
or my dropdown list will be hidden.
Inspired by this discussion: https://twitter.com/siddharthkp/status/1094821277452234752
I use border-bottom-left-radius
and border-bottom-right-radius
in the child element to fix this issue.
make sure you add it the correct value for each child separately
I prefer fork + execlp for "more fine-grade" control as doron mentioned. Example code shown below.
Store you command in a char array parameters, and malloc space for the result.
int fd[2];
pipe(fd);
if ( (childpid = fork() ) == -1){
fprintf(stderr, "FORK failed");
return 1;
} else if( childpid == 0) {
close(1);
dup2(fd[1], 1);
close(fd[0]);
execlp("/bin/sh","/bin/sh","-c",parameters,NULL);
}
wait(NULL);
read(fd[0], result, RESULT_SIZE);
printf("%s\n",result);
Underscore and Lodash have the _.last(Array)
method, that returns the last element in an Array. They both work about the same
_.last([5, 4, 3, 2, 1]);
=> 1
Ramda also has a _.last
function
R.last(['fi', 'fo', 'fum']); //=> 'fum'
Try this batch :
@echo off
Title List of connected external devices by Hackoo
Mode con cols=100 lines=20 & Color 9E
wmic LOGICALDISK where driveType=2 get deviceID > wmic.txt
for /f "skip=1" %%b IN ('type wmic.txt') DO (echo %%b & pause & Dir %%b)
Del wmic.txt
pause
You could try to extract columns as list, massage this as you want, and reindex your dataframe:
>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...
>>> df.reindex(columns=['n']+df.columns[:-1].tolist())
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
This seems to be due to a problem in the UITableViewController
subclass template. It comes with a version of the prepareForSegue
method that would require you to unwrap the segue.
Replace your current prepareForSegue
function with:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "Load View") {
// pass data to next view
}
}
This version implicitly unwraps the parameters, so you should be fine.
You cannot store arrays in a vector
or any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.
You can, however, use an array
class template, like the one provided by Boost, TR1, and C++0x:
std::vector<std::array<double, 4> >
(You'll want to replace std::array
with std::tr1::array
to use the template included in C++ TR1, or boost::array
to use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)
From my experience I'm telling you that BIT has problems on linux OS types(Ubuntu for ex). I developped my db on windows and after I deployed everything on linux, I had problems with queries that inserted or selected from tables that had BIT DATA TYPE.
Bit is not safe for now. I changed to tinyint(1) and worked perfectly. I mean that you only need a value to diferentiate if it's 1 or 0 and tinyint(1) it's ok for that
I tried this on the command line using
D:\>xcopy myfile.dat xcopytest\test\
and the target directory was properly created.
If not you can create the target dir using the mkdir
command with cmd
's command extensions enabled like
cmd /x /c mkdir "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\"
('/x' enables command extensions in case they're not enabled by default on your system, I'm not that familiar with cmd
)
use
cmd /?
mkdir /?
xcopy /?
for further information :)
I was missing a dependency somewhere else along the line, so I installed the other requirements for the project like this:
pip install --user -r requirements.txt
The solution in my situation was similar answer to Charles Burns; and the problem was related to SQL code comments.
I was building (or updating, rather) an already-functioning SSRS report with Oracle datasource. I added some more parameters to the report, tested it in Visual Studio, it works great, so I deployed it to the report server, and then when the report is executed the report on the server I got the error message:
"ORA-01008: not all variables bound"
I tried quite a few different things (TNSNames.ora file installed on the server, Removed single line comments, Validate dataset query mapping). What it came down to was I had to remove a comment block directly after the WHERE keyword
. The error message was resolved after moving the comment block after the WHERE CLAUSE conditions
. I have other comments in the code also. It was just the one after the WHERE keyword causing the error.
SQL with error: "ORA-01008: not all variables bound"...
WHERE
/*
OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')
AND OHH.STATUS_CODE<>'DL'
AND OHH.BILL_COMP_CODE=100
AND OHH.MASTER_ORDER_NBR IS NULL
*/
OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
AND OHH.STATUS_CODE<>'DL'
AND OHH.BILL_COMP_CODE IN (:paramCompany)
AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse)
AND OHH.MASTER_ORDER_NBR IS NULL
AND LOAD.CLASS_CODE IN (:paramClassCode)
AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto)
SQL executes successfully on the report server...
WHERE
OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
AND OHH.STATUS_CODE<>'DL'
AND OHH.BILL_COMP_CODE IN (:paramCompany)
AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse)
AND OHH.MASTER_ORDER_NBR IS NULL
AND LOAD.CLASS_CODE IN (:paramClassCode)
AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto)
/*
OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')
AND OHH.STATUS_CODE<>'DL'
AND OHH.BILL_COMP_CODE=100
AND OHH.MASTER_ORDER_NBR IS NULL
*/
Here is what the dataset parameter mapping screen looks like.
Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string. You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code. read the comments to understand better how the conversion is done.
// Here Im creating my variable as a string
var str = "258";
// here im printing the string variable: str
console.log ( str );
// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);
// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);
Double escaping is required when presented as a string.
Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html
That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.
(function() {_x000D_
"use strict";_x000D_
_x000D_
Array.prototype.unique = function unique() {_x000D_
var self = this;_x000D_
return self.filter(function(a) {_x000D_
var that = this;_x000D_
// console.log(that);_x000D_
return !that[a] ? that[a] = true : false;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
var sampleArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];_x000D_
var distinctArray = sampleArray.unique();_x000D_
console.log(distinctArray);_x000D_
})();
_x000D_
Here is the simple way to solve this problem...
_x000D_
There is a quirk with this that might be relevant for some people... From the PHP docs comments.
If you want cURL to timeout in less than one second, you can use
CURLOPT_TIMEOUT_MS
, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."
What this means to PHP developers is "You can't use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"
The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.
The solution is to disable signals using CURLOPT_NOSIGNAL. Here's an example script that requests itself causing a 10-second delay so you can test timeouts:
if (!isset($_GET['foo'])) {
// Client
$ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0) {
echo "cURL Error ($curl_errno): $curl_error\n";
} else {
echo "Data received: $data\n";
}
} else {
// Server
sleep(10);
echo "Done.";
}
From http://www.php.net/manual/en/function.curl-setopt.php#104597
You can also use this function,
function optionDisable(selectId, optionIndices)
{
for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
{
document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
}
}
You can use the .hide()
function bound to a click
handler:
$('#Comanda').click(function() {
$(this).hide();
});
There are two possible reasons for that problem:
did not install aclocal.
solution:install libtool
sudo apt-get install libtool
sudo yum install libtool
the path to LIBTOOL.m4 is error.
solution:
aclocal --print-ac-dir
to check current path to aclocal.(It's usually should be "/usr/share/aclocal" or "/usr/share/aclocal")cp /usr/share/aclocal/*.m4 /usr/local/share/aclocal/
or cp /usr/local/share/aclocal/*.m4 /usr/share/aclocal/
)Hope it helps
Just grep:
echo 'abcdef' | grep -Po "^.." # ab
Today, in Office 365, Excel has so called 'array functions'.
The filter
function does exactly what you want. No need to use CTRL+SHIFT+ENTER
anymore, a simple enter
will suffice.
In Office 365, your problem would be simply solved by using:
=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)
And if you want to add a row, you can use a dictionary:
df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)
which gives you:
age height name
0 9 2 Zed
This can be helpful:
<input type="text" name="username" value="admin" >
<style type="text/css">
input[name=username] {
pointer-events: none;
}
</style>
Update:
and if want to disable from tab index you can use it this way:
<input type="text" name="username" value="admin" tabindex="-1" >
<style type="text/css">
input[name=username] {
pointer-events: none;
}
</style>
There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/
There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...
You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery
to get defined.
// Immediately-invoked function expression
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
script.onload = function() {
var $ = window.jQuery;
// Use $ here...
};
document.getElementsByTagName("head")[0].appendChild(script);
})();
Just remember that if you need to support really old browsers, like IE8, load
event handlers do not execute. In that case, you would need to poll for the existance of window.jQuery
using repeated window.setTimeout
. There is a working JSFiddle with that method here: http://jsfiddle.net/9N7Z2/3/
There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:
I'm a bit of a beginner and struggled getting this to work today.
Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!
public class HighScore {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, "highscore.txt");
private int highScore = 0;
public int readHighScore() {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
highScore = Integer.parseInt(br.readLine());
br.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return highScore;
}
public void writeHighScore(int highestScore) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(highestScore));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Neer to specify exit code here so php not execute further
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit(0); // require to exit here
}
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
Use this one. It will fix it.
#ibox_footer {
padding-top: 3px;
position: absolute;
height: 20px;
margin-bottom: 0;
bottom: 0;
width: 100%;
}
The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.
try
echo date('F d Y', strtotime('2010-01-19 00:00:00'));
will output:
January 19 2010
you should change format time to see other output
The answer is that older apps run in 2208 x 1242 Zoomed Mode. But when an app is built for the new phones the resolutions available are: Super Retina HD 5.8 (iPhone X) 1125 x 2436 (458ppi), Retina HD 5.5 (iPhone 6, 7, 8 Plus) 1242 x 2208 and Retina HD 4.7 (iPhone 6) 750 x 1334. This is causing the confusion mentioned in the question. To build apps that use the full screen size of the new phones add LaunchImages in the sizes: 1125 x 2436, 1242 x 2208, 2208 x 1242 and 750 x 1334.
Size for iPhone 12 Pro Max with @3x scaling, coordinate space: 428 x 926 points and 1284 x 2778 pixels, 458 ppi, device physical size is 3.07 x 6.33 in or 78.1 x 160.8 mm. 6.7" Super Retina XDR display.
Size for iPhone 12 Pro with @3x scaling, coordinate space: 390 x 844 points and 1170 x 2532 pixels, 460 ppi, device physical size is 2.82 x 5.78 in or 71.5 x 146.7 mm. 6.1" Super Retina XDR display.
Size for iPhone 12 with @2x scaling, coordinate space: 585 x 1266 points and 1170 x 2532 pixels, 460 ppi, device physical size is 2.82 x 5.78 in or 71.5 x 146.7 mm. 6.1" Super Retina XDR display.
Size for iPhone 12 mini with @2x scaling, coordinate space: 540 x 1170 points and 1080 x 2340 pixels, 476 ppi, device physical size is 2.53 x 5.18 in or 64.2 x 131.5 mm. 5.4" Super Retina XDR display.
Size for iPhone 11 Pro Max with @3x scaling, coordinate space: 414 x 896 points and 1242 x 2688 pixels, 458 ppi, device physical size is 3.06 x 6.22 in or 77.8 x 158.0 mm. 6.5" Super Retina XDR display.
Size for iPhone 11 Pro with @3x scaling, coordinate space: 375 x 812 points and 1125 x 2436 pixels, 458 ppi, device physical size is 2.81 x 5.67 in or 71.4 x 144.0 mm. 5.8" Super Retina XDR display.
Size for iPhone 11 with @2x scaling, coordinate space: 414 x 896 points and 828 x 1792 pixels, 326 ppi, device physical size is 2.98 x 5.94 in or 75.7 x 150.9 mm. 6.1" Liquid Retina HD display.
Size for iPhone X Max with @3x scaling (Apple name: Super Retina HD 6.5 display"), coordinate space: 414 x 896 points and 1242 x 2688 pixels, 458 ppi, device physical size is 3.05 x 6.20 in or 77.4 x 157.5 mm.
let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X Max Screen bounds: (0.0, 0.0, 414.0, 896.0), Screen resolution: (0.0, 0.0, 1242.0, 2688.0), scale: 3.0
Size for iPhone X with @2x scaling (Apple name: Super Retina HD 6.1" display), coordinate space: 414 x 896 points and 828 x 1792 pixels, 326 ppi, device physical size is 2.98 x 5.94 in or 75.7 x 150.9 mm.
let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X Screen bounds: (0.0, 0.0, 414.0, 896.0), Screen resolution: (0.0, 0.0, 828.0, 1792.0), scale: 2.0
Size for iPhone X and iPhone X with @3x scaling (Apple name: Super Retina HD 5.8" display), coordinate space: 375 x 812 points and 1125 x 2436 pixels, 458 ppi, device physical size is 2.79 x 5.65 in or 70.9 x 143.6 mm.
let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X and X Screen bounds: (0.0, 0.0, 375.0, 812.0), Screen resolution: (0.0, 0.0, 1125.0, 2436.0), scale: 3.0
Size for iPhone 6, 6S, 7 and 8 with @3x scaling (Apple name: Retina HD 5.5), coordinate space: 414 x 736 points and 1242 x 2208 pixels, 401 ppi, screen physical size is 2.7 x 4.8 in or 68 x 122 mm. When running in Zoomed Mode, i.e. without the new LaunchImages or choosen in Setup on iPhone 6 Plus, the native scale is 2.88 and the screen is 320 x 568 points, which is the iPhone 5 native size:
Screen bounds: {{0, 0}, {414, 736}}, Screen resolution: <UIScreen: 0x7f97fad330b0; bounds = {{0, 0}, {414, 736}};
mode = <UIScreenMode: 0x7f97fae1ce00; size = 1242.000000 x 2208.000000>>, scale: 3.000000, nativeScale: 3.000000
Size for iPhone 6 and iPhone 6S with @2x scaling (Apple name: Retina HD 4.7), coordinate space: 375 x 667 points and 750 x 1334 pixels, 326 ppi, screen physical size is 2.3 x 4.1 in or 58 x 104 mm. When running in Zoomed Mode, i.e. without the new LaunchImages, the screen is 320 x 568 points, which is the iPhone 5 native size:
Screen bounds: {{0, 0}, {375, 667}}, Screen resolution: <UIScreen: 0x7fa01b5182d0; bounds = {{0, 0}, {375, 667}};
mode = <UIScreenMode: 0x7fa01b711760; size = 750.000000 x 1334.000000>>, scale: 2.000000, nativeScale: 2.000000
And iPhone 5 for comparison is 640 x 1136, iPhone 4 640 x 960.
Here is the code I used to check this out (note that nativeScale only runs on iOS 8):
UIScreen *mainScreen = [UIScreen mainScreen];
NSLog(@"Screen bounds: %@, Screen resolution: %@, scale: %f, nativeScale: %f",
NSStringFromCGRect(mainScreen.bounds), mainScreen.coordinateSpace, mainScreen.scale, mainScreen.nativeScale);
Note: Upload LaunchImages otherwise the app will run in Zoomed Mode and not show the correct scaling, or screen sizes. In Zoomed Mode the nativeScale
and scale
will not be the same. On an actual device the scale can be 2.608 on the iPhone 6 Plus, even when it is not running in Zoomed Mode, but it will show scale of 3.0 when running on the simulator.
The error as reported appears when the variables are null (or empty):
$ unset var3 var4; var5=$(($var4-$var3))
bash: -: syntax error: operand expected (error token is "-")
That could happen because the value given to bc was incorrect. That might well be that bc needs UPPERcase values. It needs BFCA3000
, not bfca3000
. That is easily fixed in bash, just use the ^^
expansion:
var3=bfca3000; var3=`echo "ibase=16; ${var1^^}" | bc`
That will change the script to this:
#!/bin/bash
var1="bfca3000"
var2="efca3250"
var3="$(echo "ibase=16; ${var1^^}" | bc)"
var4="$(echo "ibase=16; ${var2^^}" | bc)"
var5="$(($var4-$var3))"
echo "Diference $var5"
But there is no need to use bc [1], as bash could perform the translation and substraction directly:
#!/bin/bash
var1="bfca3000"
var2="efca3250"
var5="$(( 16#$var2 - 16#$var1 ))"
echo "Diference $var5"
[1]Note: I am assuming the values could be represented in 64 bit math, as the difference was calculated in bash in your original script. Bash is limited to integers less than ((2**63)-1) if compiled in 64 bits. That will be the only difference with bc which does not have such limit.
Call JObject's ToString(Formatting.None)
method.
Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.
Documentation: Write JSON text with JToken.ToString
i have alreay 2 situations where directives and services/factories didnt play well.
the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).
in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.
i even tried to make a directive with a controller and an isolated-scope
only when i moved everything to a controller and it worked like magic.
example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:
SELECT
Flights.*,fromAirports.*,toAirports.*
FROM
Flights
INNER JOIN
Airports fromAirports on Flights.fairport = fromAirports.code
INNER JOIN
Airports toAirports on Flights.tairport = toAirports.code
WHERE
...
i have tried this article Code Project, it is working fine for me. I have used the code too. article is excellent in explanation with screenshot.
I am adding necessary explanation to this scenario
You have just booted up your computer and are about to log on. When you log on, the system assigns you a unique Session ID. In Windows Vista, the first User to log on to the computer is assigned a Session ID of 1 by the OS. The next User to log on will be assigned a Session ID of 2. And so on and so forth. You can view the Session ID assigned to each logged on User from the Users tab in Task Manager.
But your windows service is brought under session ID of 0. This session is isolated from other sessions. This ultimately prevent the windows service to invoke the application running under user session's like 1 or 2.
In order to invoke the application from windows service you need to copy the control from winlogon.exe which acts as present logged user as shown in below screenshot.
Important codes
// obtain the process id of the winlogon process that
// is running within the currently active session
Process[] processes = Process.GetProcessesByName("winlogon");
foreach (Process p in processes)
{
if ((uint)p.SessionId == dwSessionId)
{
winlogonPid = (uint)p.Id;
}
}
// obtain a handle to the winlogon process
hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);
// obtain a handle to the access token of the winlogon process
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
{
CloseHandle(hProcess);
return false;
}
// Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
// I would prefer to not have to use a security attribute variable and to just
// simply pass null and inherit (by default) the security attributes
// of the existing token. However, in C# structures are value types and therefore
// cannot be assigned the null value.
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
// copy the access token of the winlogon process;
// the newly created token will be a primary token
if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
{
CloseHandle(hProcess);
CloseHandle(hPToken);
return false;
}
STARTUPINFO si = new STARTUPINFO();
si.cb = (int)Marshal.SizeOf(si);
// interactive window station parameter; basically this indicates
// that the process created can display a GUI on the desktop
si.lpDesktop = @"winsta0\default";
// flags that specify the priority and creation method of the process
int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
// create a new process in the current User's logon session
bool result = CreateProcessAsUser(hUserTokenDup, // client's access token
null, // file to execute
applicationName, // command line
ref sa, // pointer to process SECURITY_ATTRIBUTES
ref sa, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
dwCreationFlags, // creation flags
IntPtr.Zero, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out procInfo // receives information about new process
);
No it won't, Java will short-circuit and stop evaluating once it knows the result.
If a machine is byte-addressable and a word is the smallest unit that can be addressed on memory then I guess a word would be a byte!
I use date.js. It handles this easily and takes care of all the leap-year nastiness.
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
Old question, but here's my go-to for this operation.
If browser.Document IsNot Nothing Then
browser.Document.OpenNew(True)
browser.Document.Write(My.Resources.htmlTemplate)
Else
browser.DocumentText = My.Resources.htmlTemplate
End If
And be sure that any browser.Navigating
event DOES NOT cancel "about:blank" URLs. Example event below for full control of WebBrowser
navigating.
Private Sub browser_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles browser.Navigating
Try
Me.Cursor = Cursors.WaitCursor
Select Case e.Url.Scheme
Case Constants.App_Url_Scheme
Dim query As Specialized.NameValueCollection = System.Web.HttpUtility.ParseQueryString(e.Url.Query)
Select Case e.Url.Host
Case Constants.Navigation.URLs.ToggleExpander.Host
Dim nodeID As String = query.Item(Constants.Navigation.URLs.ToggleExpander.Parameters.NodeID)
:
:
<other operations here>
:
:
End Select
Case Else
e.Cancel = (e.Url.ToString() <> "about:blank")
End Select
Catch ex As Exception
ExceptionBox.Show(ex, "Operation failed.")
Finally
Me.Cursor = Cursors.Default
End Try
End Sub
To get the Unix timestamp in seconds in MySQL:
select UNIX_TIMESTAMP();
Details: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp
Not tested PostgreSQL, but according to this site it should work: http://www.raditha.com/postgres/timestamp.php
select round( date_part( 'epoch', now() ) );
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
1) Article.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent{
protected $table = 'articles';
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
}
2) Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent
{
protected $table = "categories";
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
3) User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent
{
protected $table = 'users';
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
and you can use this like so:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
You can learn more at http://laravel.com/docs/5.0/eloquent
In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
Cascade will work when you delete something on table Courses
. Any record on table BookCourses
that has reference to table Courses
will be deleted automatically.
But when you try to delete on table BookCourses
only the table itself is affected and not on the Courses
follow-up question: why do you have CourseID
on table Category?
Maybe you should restructure your schema into this,
CREATE TABLE Categories
(
Code CHAR(4) NOT NULL PRIMARY KEY,
CategoryName VARCHAR(63) NOT NULL UNIQUE
);
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
BookID INT NOT NULL,
CatCode CHAR(4) NOT NULL,
CourseNum CHAR(3) NOT NULL,
CourseSec CHAR(1) NOT NULL,
);
ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;
Since the code sample is a bit outdated I thought I'd share a more recent approach, using Angular 4.3 and the new(er) HttpClient API, @angular/common/http
export class FileUpload {
@ViewChild('selectedFile') selectedFileEl;
uploadFile() {
let params = new HttpParams();
let formData = new FormData();
formData.append('upload', this.selectedFileEl.nativeElement.files[0])
const options = {
headers: new HttpHeaders().set('Authorization', this.loopBackAuth.accessTokenId),
params: params,
reportProgress: true,
withCredentials: true,
}
this.http.post('http://localhost:3000/api/FileUploads/fileupload', formData, options)
.subscribe(
data => {
console.log("Subscribe data", data);
},
(err: HttpErrorResponse) => {
console.log(err.message, JSON.parse(err.error).error.message);
}
)
.add(() => this.uploadBtn.nativeElement.disabled = false);//teardown
}
When you declare a variable in javascript, it is assigned the value undefined
. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.
Now you can explicitly assign a variable null
. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.
Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined
. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null
, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.
The simplest solution I've found that doesn't require a plugin:
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;
var yDown = null;
function handleTouchStart(evt) {
xDown = evt.touches[0].clientX;
yDown = evt.touches[0].clientY;
};
function handleTouchMove(evt) {
if ( ! xDown || ! yDown ) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
if ( xDiff > 0 ) {
/* left swipe */
} else {
/* right swipe */
}
} else {
if ( yDiff > 0 ) {
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
xDown = null;
yDown = null;
};