The Windows solution is the same as the Linux sudo answer. Run the npm start (or whatever) as Administrator. I had added a new module to my project. Worked on some machines but on others that were more locked down, not so much. Took a while to figure it out but the new module needed access to "something" that wasn't available without administrator permissions.
Use dict.items(); it can be as simple as following:
ship = collections.OrderedDict(ship.items())
I was searching for this very same thing. I had read that this was available in Bootstrap 3.0, but I was having no luck in actually implementing it. This is what I came up with and it works great. Very simple jQuery and Javascript.
Here is the JSFiddle to play around with... http://jsfiddle.net/CriddleCraddle/Wj9dD/
The solution is very similar to other solutions on the web and StackOverflow. If you do not find this one useful, search for what you need. Goodluck!
Here is the HTML...
<div id="banner">
<h2>put what you want here</h2>
<p>just adjust javascript size to match this window</p>
</div>
<nav id='nav_bar'>
<ul class='nav_links'>
<li><a href="url">Sign In</a></li>
<li><a href="url">Blog</a></li>
<li><a href="url">About</a></li>
</ul>
</nav>
<div id='body_div'>
<p style='margin: 0; padding-top: 50px;'>and more stuff to continue scrolling here</p>
</div>
Here is the CSS...
html, body {
height: 4000px;
}
.navbar-fixed {
top: 0;
z-index: 100;
position: fixed;
width: 100%;
}
#body_div {
top: 0;
position: relative;
height: 200px;
background-color: green;
}
#banner {
width: 100%;
height: 273px;
background-color: gray;
overflow: hidden;
}
#nav_bar {
border: 0;
background-color: #202020;
border-radius: 0px;
margin-bottom: 0;
height: 30px;
}
//the below css are for the links, not needed for sticky nav
.nav_links {
margin: 0;
}
.nav_links li {
display: inline-block;
margin-top: 4px;
}
.nav_links li a {
padding: 0 15.5px;
color: #3498db;
text-decoration: none;
}
Now, just add the javacript to add and remove the fix class based on the scroll position.
$(document).ready(function() {
//change the integers below to match the height of your upper div, which I called
//banner. Just add a 1 to the last number. console.log($(window).scrollTop())
//to figure out what the scroll position is when exactly you want to fix the nav
//bar or div or whatever. I stuck in the console.log for you. Just remove when
//you know the position.
$(window).scroll(function () {
console.log($(window).scrollTop());
if ($(window).scrollTop() > 550) {
$('#nav_bar').addClass('navbar-fixed-top');
}
if ($(window).scrollTop() < 551) {
$('#nav_bar').removeClass('navbar-fixed-top');
}
});
});
It's a standard, ordinary SOAP web service. SSH has nothing to do here. I just called it with curl (one-liner):
$ curl -X POST -H "Content-Type: text/xml" \
-H 'SOAPAction: "http://api.eyeblaster.com/IAuthenticationService/ClientLogin"' \
--data-binary @request.xml \
https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc
Where request.xml
file has the following contents:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://api.eyeblaster.com/">
<soapenv:Header/>
<soapenv:Body>
<api:ClientLogin>
<api:username>user</api:username>
<api:password>password</api:password>
<api:applicationKey>key</api:applicationKey>
</api:ClientLogin>
</soapenv:Body>
</soapenv:Envelope>
I get this beautiful 500:
<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode>s:Security.Authentication.UserPassIncorrect</faultcode>
<faultstring xml:lang="en-US">The username, password or application key is incorrect.</faultstring>
</s:Fault>
</s:Body>
</s:Envelope>
Have you tried soapui?
Example: Getting app_name string:
Resources.getSystem().getString( R.string.app_name )
@Zordid @Iambda answer is great, but I found that if I put
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
in the run() method and
mHandler.postDelayed(mUpdateUITimerTask, 0);
in the onCreate method make the thing keep updating.
I was working on a dataframe and having no luck with the provided answers, it always returned 0 rows, so I found and used grepl:
df = df[grepl("downlink",df$Transmit.direction),]
Which basically trimmed my dataframe to only the rows that contained "downlink" in the Transmit direction column. P.S. If anyone can guess as to why I'm not seeing the expected behavior, please leave a comment.
Specifically to the original question:
expr[grepl("hesc",expr$cell_type),]
expr[grepl("bj fibroblast|hesc",expr$cell_type),]
It is a sort of format specifier for formatting numeric results. There are additional specifiers on the link.
What N
does is that it separates numbers into thousand decimal places according to your CultureInfo and represents only 2 decimal digits in floating part as is N2
by rounding right-most digit if necessary.
N0
does not represent any decimal place but rounding is applied to it.
Let's exemplify.
using System;
using System.Globalization;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
double x = 567892.98789;
CultureInfo someCulture = new CultureInfo("da-DK", false);
// 10 means left-padded = right-alignment
Console.WriteLine(String.Format(someCulture, "{0:N} denmark", x));
Console.WriteLine("{0,10:N} us", x);
// watch out rounding 567,893
Console.WriteLine(String.Format(someCulture, "{0,10:N0}", x));
Console.WriteLine("{0,10:N0}", x);
Console.WriteLine(String.Format(someCulture, "{0,10:N5}", x));
Console.WriteLine("{0,10:N5}", x);
Console.ReadKey();
}
}
}
It yields,
567.892,99 denmark
567,892.99 us
567.893
567,893
567.892,98789
567,892.98789
Another way is with Arrays.setAll
, or Arrays.fill
:
String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]
Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]
This is more usefull for initializing (possibly large) arrays where you can compute each element from its index.
With Node.js v6 (and above) there is a dedicated os
module, which provides a number of operating system-related utility methods.
On my Windows 10 machine it reports the following:
var os = require('os');
console.log(os.type()); // "Windows_NT"
console.log(os.release()); // "10.0.14393"
console.log(os.platform()); // "win32"
You can read it's full documentation here: https://nodejs.org/api/os.html#os_os_type
Just handle the form submission on the submit event, and return false:
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
You don't need any more the onclick event on the submit button:
<input class="submit" type="submit" value="Send" />
The fundamental difference in most programming languages is that unless the unexpected happens a for
loop will always repeat n
times or until a break statement, (which may be conditional), is met then finish with a while
loop it may repeat 0 times, 1, more or even forever
, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while
loop, (or repeat until
), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).
It is worth noting that in Python a for
or while
statement can have break
, continue
and else
statements where:
break
- terminates the loopcontinue
- moves on to the next time around the loop without executing following code this time aroundelse
- is executed if the loop completed without any break
statements being executed.N.B. In the now unsupported Python 2 range
produced a list of integers but you could use xrange
to use an iterator. In Python 3 range
returns an iterator.
So the answer to your question is 'it all depends on what you are trying to do'!
With the example class you posted it doesn't seem to make much sense to test getFuel()
and getSpeed()
since they can only return 0 (there are no setters).
However, assuming that this was just a simplified example for illustrative purposes, and that you have legitimate reasons to test methods in the abstract base class (others have already pointed out the implications), you could setup your test code so that it creates an anonymous subclass of the base class that just provides dummy (no-op) implementations for the abstract methods.
For example, in your TestCase
you could do this:
c = new Car() {
void drive() { };
};
Then test the rest of the methods, e.g.:
public class CarTest extends TestCase
{
private Car c;
public void setUp()
{
c = new Car() {
void drive() { };
};
}
public void testGetFuel()
{
assertEquals(c.getFuel(), 0);
}
[...]
}
(This example is based on JUnit3 syntax. For JUnit4, the code would be slightly different, but the idea is the same.)
You can use DHP to do this. It is absolutely simple and it is fast than script.
Just write alert('something');
It is not programing language it is something like a lit bit jquery. You need require dhp.php in the top and in the bottom require dhpjs.php.
For now it is not open source but when it is you can use it. It is our programing language ;)
If you're using MySQL you could try
SHOW COLUMNS FROM `tbl_name`;
Otherwise you should be able to do
DESCRIBE `tbl_name`;
Correct me if I'm wrong, but this seems like the simplest way (for one argument, anyway):
function myFunction(Required,Optional)
{
if (arguments.length<2) Optional = "Default";
//Your code
}
After stumbling around, this worked for me:
df = df.astype(object).where(pd.notnull(df),None)
Also, it has to be noted that if you're using your_tensor.assign()
, then the tf.global_variables_initializer
need not be called explicitly since the assign operation does it for you in the background.
Example:
In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)
In [214]: with tf.Session() as sess:
...: sess.run(w_new)
...: print(w_new.eval())
# output
34
However, this will not initialize all variables, but it will only initialize the variable on which assign
was executed on.
Modern, clean and shortest
fetch('https://www.randomtext.me/api/lorem')
let url = 'https://www.randomtext.me/api/lorem';
// to only send GET request without waiting for response just call
fetch(url);
// to wait for results use 'then'
fetch(url).then(r=> r.json().then(j=> console.log('\nREQUEST 2',j)));
// or async/await
(async()=>
console.log('\nREQUEST 3', await(await fetch(url)).json())
)();
_x000D_
Open Chrome console network tab to see request
_x000D_
You perhaps use the wrong username.
I had a similar error. Ensure you're not using uppercase while logging into server.
Example: [email protected]
If you use ->setUsername('JacekPL')
, this can cause an error. Use ->setUsername('jacekpl')
instead. This solved my problem.
Use this inside of query, no need to create extra variables.
CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN '' ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'
Works like a charm.
I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.
Also, the project is mostly dormant... the last release was in 2004.
For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.
Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).
function parseQueryString () {
var parsedParameters = {},
uriParameters = location.search.substr(1).split('&');
for (var i = 0; i < uriParameters.length; i++) {
var parameter = uriParameters[i].split('=');
parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
}
return parsedParameters;
}
SELECT json_agg(t) FROM t
for a JSON array of objects, and
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
for a JSON object of arrays.
This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:
[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]
The json_agg
function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.
SELECT json_agg(t) FROM t
There is no jsonb
(introduced in 9.4) version of json_agg
. You can either aggregate the rows into an array and then convert them:
SELECT to_jsonb(array_agg(t)) FROM t
or combine json_agg
with a cast:
SELECT json_agg(t)::jsonb FROM t
My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.
9.2 does not have the json_agg
or to_json
functions, so you need to use the older array_to_json
:
SELECT array_to_json(array_agg(t)) FROM t
You can optionally include a row_to_json
call in the query:
SELECT array_to_json(array_agg(row_to_json(t))) FROM t
This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.
I wasn't able to discern any significant performance difference between the two.
This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:
{"a":[1,2,3], "b":["value1","value2","value3"]}
We can leverage the json_build_object
function:
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
You can also aggregate the columns, creating a single row, and then convert that into an object:
SELECT to_json(r)
FROM (
SELECT
json_agg(t.a) AS a,
json_agg(t.b) AS b
FROM t
) r
Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.
Which one is clearer is a matter of opinion. If using the json_build_object
function, I highly recommend putting one key/value pair on a line to improve readability.
You could also use array_agg
in place of json_agg
, but my testing indicates that json_agg
is slightly faster.
There is no jsonb
version of the json_build_object
function. You can aggregate into a single row and convert:
SELECT to_jsonb(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
Unlike the other queries for this kind of result, array_agg
seems to be a little faster when using to_jsonb
. I suspect this is due to overhead parsing and validating the JSON result of json_agg
.
Or you can use an explicit cast:
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)::jsonb
FROM t
The to_jsonb
version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.
The json_build_object
function was new to 9.5, so you have to aggregate and convert to an object in previous versions:
SELECT to_json(r)
FROM (
SELECT
json_agg(t.a) AS a,
json_agg(t.b) AS b
FROM t
) r
or
SELECT to_jsonb(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
depending on whether you want json
or jsonb
.
(9.3 does not have jsonb
.)
In 9.2, not even to_json
exists. You must use row_to_json
:
SELECT row_to_json(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
Find the documentation for the JSON functions in JSON functions.
json_agg
is on the aggregate functions page.
If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.
Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.
Aggregate functions typically give back NULL
when they operate over zero rows. If this is a possibility, you might want to use COALESCE
to avoid them. A couple of examples:
SELECT COALESCE(json_agg(t), '[]'::json) FROM t
Or
SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t
Credit to Hannes Landeholm for pointing this out
So you have to exclude conflict dependencies. Try this:
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
This solved same problem with slf4j and Dozer.
I've solved it, it can be done executing:
netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33
To remove forwarding:
netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111
see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html
using loc = 0 will insert at the beginning
df.insert(loc, column, value)
df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})
df
Out:
B C
0 1 4
1 2 5
2 3 6
idx = 0
new_col = [7, 8, 9] # can be a list, a Series, an array or a scalar
df.insert(loc=idx, column='A', value=new_col)
df
Out:
A B C
0 7 1 4
1 8 2 5
2 9 3 6
Usually, when you create a Java project you want to use functionalities made in another Java projects. For example, if your project wants to send one email you dont need to create all the necessary code for doing that. You can bring a java library that does the most part of the work. Maven is a building tool that will help you in several tasks. One of those tasks is to bring these external dependencies or artifacts to your project in an automatic way ( only with some configuration in a XML file ). Of course Maven has more details but, for your question this is enough. And, of course too, Maven can build your project as an artifact (usually a jar file ) that can be used or imported in other projects.
This website has several articles talking about Maven :
Just call Math.abs. For example:
int x = Math.abs(-5);
Which will set x
to 5
.
Note that if you pass Integer.MIN_VALUE
, the same value (still negative) will be returned, as the range of int
does not allow the positive equivalent to be represented.
If you don't want to use external libraries there is .toSource()
native JavaScript method, but it's not perfectly cross-browser.
Based on your edit and comments.. would this be what you're after?
byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));
In addition to the above answers, I would say for columns having no single word name, you may use:-
df[df['Product ID'].str.contains("foo") == True]
Hope this helps.
In .NET, there are two categories of types, reference types and value types.
Structs are value types and classes are reference types.
The general difference is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.
A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.
A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.
This has one benefit, to begin with:
Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:
When you declare variables or fields, here's how the two types differ:
You can solve this by increasing the maximum request length in your web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime maxRequestLength="102400" />
</system.web>
</configuration>
The example above is for a 100Mb limit.
There are a variety of tools to aid blind people or partially sighted including speech feedback and braillie keyboards. http://www.rnib.org.uk/Pages/Home.aspx is a good site for help and advice over these issues.
save.patch
file to wherever (including binary files).git apply <file>
Note: it diff's the currently staged files too.
$ git diff --binary --staged HEAD > save.patch
$ git reset --hard
$ <transport it>
$ git apply save.patch
Make sure your article:author data is a Facebook author URL. Unfortunately, that conflicts with what Pinterest is expecting. It's the best thing about standards, there are so many ways to implement them!
<meta property="article:author" content="https://www.facebook.com/mpatnode76">
But Pinterest wants to see something like this:
<meta property="article:author" content="Mike Patnode">
We ended up swapping the formats depending upon the user agent. Hopefully, that doesn't screw up your page cache. That fixed it for us.
Full disclosure. Found this here: https://surniaulula.com/2014/03/01/pinterest-articleauthor-incompatible-with-open-graph/
I always find it easier to learn a language in a specific problem domain. You might try looking at Django and doing the tutorial. This will give you a very light-weight intro to both Python and to a web framework (a very well-documented one) that is 100% Python.
Then do something in your field(s) of expertise -- graph generation, or whatever -- and tie that into a working framework to see if you got it right. My universe tends to be computational linguistics and there are a number of Python-based toolkits to help get you started. E.g. Natural Language Toolkit.
Just a thought.
Angular will automatically update a component when it detects a variable change .
So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts
or via an @Input
variable...
an example...
main.html
<app-header [header-data]="headerData"></app-header>
main.component.ts
public headerData:int = 0;
ngOnInit(){
setInterval(()=>{this.headerData++;}, 250);
}
header.html
<p>{{data}}</p>
header.ts
@Input('header-data') data;
In the above example, the header will recieve the new data every 250ms and thus update the component.
For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks
Use my_map.count( key )
; it can only return 0 or 1, which is essentially the Boolean result you want.
Alternately my_map.find( key ) != my_map.end()
works too.
A mechanism that prevents the data of a particular objects safe from intentional or accidental misuse by external functions is called "data Encapsulation"
The act of representing essential features without including the background details or explanations is known as abstraction
As per the comments in the question... On Windows 10 Signtool.exe and other SDK tools have been moved into "%programfiles(x86)%\Windows Kits\".
Typical path to signtool on Windows 10.
Tools for SDK 8.0 and 8.1 also reside in the "Windows Kits" folder.
![alt-text](link)
example below:
![grab-landing-page](https://github.com/winnie1312/grab/blob/master/grab-landingpage-winnie.gif)
You can define an interface with an indexer:
interface EnumServiceGetOrderBy {
[index: number]: { id: number; label: string; key: any };
}
In your web.config, make sure these keys exist:
<configuration>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
If you want to do it from properties, you can do this by setting the Format
property of DateTimePicker
to DateTimePickerFormat.Time
and ShowUpDown
property to true
. Also, customFormat
can be set in properties.
I assume from db
that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);
Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).
For a trivial example of the type of thing you can do:
select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };
You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...
Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below
Step 2: JToken.Parse(...).ToObject<RootObject>()
.
public class Meta
{
public int code { get; set; }
public string status { get; set; }
public string method_name { get; set; }
}
public class Photos
{
public int total_count { get; set; }
}
public class Storage
{
public int used { get; set; }
}
public class Stats
{
public Photos photos { get; set; }
public Storage storage { get; set; }
}
public class From
{
public string id { get; set; }
public string first_name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public List<object> external_accounts { get; set; }
public string email { get; set; }
public string confirmed_at { get; set; }
public string username { get; set; }
public string admin { get; set; }
public Stats stats { get; set; }
}
public class ParticipateUser
{
public string id { get; set; }
public string first_name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public List<object> external_accounts { get; set; }
public string email { get; set; }
public string confirmed_at { get; set; }
public string username { get; set; }
public string admin { get; set; }
public Stats stats { get; set; }
}
public class ChatGroup
{
public string id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string message { get; set; }
public List<ParticipateUser> participate_users { get; set; }
}
public class Chat
{
public string id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string message { get; set; }
public From from { get; set; }
public ChatGroup chat_group { get; set; }
}
public class Response
{
public List<Chat> chats { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Response response { get; set; }
}
I faced the same problem,Eclipse splash screen for a second and it disappears.Then i noticed due to auto update of java there are two java version installed in my system. when i uninstalled one eclipse started working.
Thanks you..
from datetime import datetime,timedelta
today=datetime.today()
print("Todays Date:",today)
yesterday=today-datetime,timedelta(days=1)
print("Yesterday date:",yesterday)
tommorrow=today+datetime.timedelta(days=1)
print("Tommorrow Date:",tommorrow)
You can also use update ... from
syntax and use a mapping table. If you want to update more than one column, it's much more generalizable:
update test as t set
column_a = c.column_a
from (values
('123', 1),
('345', 2)
) as c(column_b, column_a)
where c.column_b = t.column_b;
You can add as many columns as you like:
update test as t set
column_a = c.column_a,
column_c = c.column_c
from (values
('123', 1, '---'),
('345', 2, '+++')
) as c(column_b, column_a, column_c)
where c.column_b = t.column_b;
I tried everything else and found helpless but this indeed worked for me "To update your credentials, go to Control Panel -> Credential Manager -> Generic Credentials. Find the credentials related to your git account and edit them to use the updated passwords".
Above Solution found in this link: https://cmatskas.com/how-to-update-your-git-credentials-on-windows/
I just encountered this problem and contrary to the accepted solution of "your make files are broken" and "host includes should never be included in a cross compile"
The android build includes many host executables used by the SDK to build an android app. In my case the make stopped while building zipalign, which is used to optimize an apk before installing on an android device.
Installing lib32z1-dev solved my problem, under Ubuntu you can install it with the following command:
sudo apt-get install lib32z1-dev
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
First check the Visual studio version of the developer PC which can publish the solution(project). as shown is for VS 2013
/p:VisualStudioVersion=12.0
add the above command line to specify what kind of a visual studio version should build the project. As previous answers, this might happen when we are trying to publish only one project, not the whole solution.
So the complete code would be something like this
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" "C:\Program Files (x86)\Jenkins\workspace\Jenkinssecondsample\MVCSampleJenkins\MVCSampleJenkins.csproj" /T:Build;Package /p:Configuration=DEBUG /p:OutputPath="obj\DEBUG" /p:DeployIisAppPath="Default Web Site/jenkinsdemoapp" /p:VisualStudioVersion=12.0
You can also try this to get the text.
foo.encode('ascii', 'ignore')
The @BeforeClass
and @AfterClass
annotated methods will be run exactly once during your test run - at the very beginning and end of the test as a whole, before anything else is run. In fact, they're run before the test class is even constructed, which is why they must be declared static
.
The @Before
and @After
methods will be run before and after every test case, so will probably be run multiple times during a test run.
So let's assume you had three tests in your class, the order of method calls would be:
setUpBeforeClass()
(Test class first instance constructed and the following methods called on it)
setUp()
test1()
tearDown()
(Test class second instance constructed and the following methods called on it)
setUp()
test2()
tearDown()
(Test class third instance constructed and the following methods called on it)
setUp()
test3()
tearDown()
tearDownAfterClass()
ACCESS_COARSE_LOCATION
, ACCESS_FINE_LOCATION
, and WRITE_EXTERNAL_STORAGE
are all part of the Android 6.0 runtime permission system. In addition to having them in the manifest as you do, you also have to request them from the user at runtime (using requestPermissions()
) and see if you have them (using checkSelfPermission()
).
One workaround in the short term is to drop your targetSdkVersion
below 23.
But, eventually, you will want to update your app to use the runtime permission system.
For example, this activity works with five permissions. Four are runtime permissions, though it is presently only handling three (I wrote it before WRITE_EXTERNAL_STORAGE
was added to the runtime permission roster).
/***
Copyright (c) 2015 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.permmonger;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String[] INITIAL_PERMS={
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_CONTACTS
};
private static final String[] CAMERA_PERMS={
Manifest.permission.CAMERA
};
private static final String[] CONTACTS_PERMS={
Manifest.permission.READ_CONTACTS
};
private static final String[] LOCATION_PERMS={
Manifest.permission.ACCESS_FINE_LOCATION
};
private static final int INITIAL_REQUEST=1337;
private static final int CAMERA_REQUEST=INITIAL_REQUEST+1;
private static final int CONTACTS_REQUEST=INITIAL_REQUEST+2;
private static final int LOCATION_REQUEST=INITIAL_REQUEST+3;
private TextView location;
private TextView camera;
private TextView internet;
private TextView contacts;
private TextView storage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
location=(TextView)findViewById(R.id.location_value);
camera=(TextView)findViewById(R.id.camera_value);
internet=(TextView)findViewById(R.id.internet_value);
contacts=(TextView)findViewById(R.id.contacts_value);
storage=(TextView)findViewById(R.id.storage_value);
if (!canAccessLocation() || !canAccessContacts()) {
requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
}
}
@Override
protected void onResume() {
super.onResume();
updateTable();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.camera:
if (canAccessCamera()) {
doCameraThing();
}
else {
requestPermissions(CAMERA_PERMS, CAMERA_REQUEST);
}
return(true);
case R.id.contacts:
if (canAccessContacts()) {
doContactsThing();
}
else {
requestPermissions(CONTACTS_PERMS, CONTACTS_REQUEST);
}
return(true);
case R.id.location:
if (canAccessLocation()) {
doLocationThing();
}
else {
requestPermissions(LOCATION_PERMS, LOCATION_REQUEST);
}
return(true);
}
return(super.onOptionsItemSelected(item));
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
updateTable();
switch(requestCode) {
case CAMERA_REQUEST:
if (canAccessCamera()) {
doCameraThing();
}
else {
bzzzt();
}
break;
case CONTACTS_REQUEST:
if (canAccessContacts()) {
doContactsThing();
}
else {
bzzzt();
}
break;
case LOCATION_REQUEST:
if (canAccessLocation()) {
doLocationThing();
}
else {
bzzzt();
}
break;
}
}
private void updateTable() {
location.setText(String.valueOf(canAccessLocation()));
camera.setText(String.valueOf(canAccessCamera()));
internet.setText(String.valueOf(hasPermission(Manifest.permission.INTERNET)));
contacts.setText(String.valueOf(canAccessContacts()));
storage.setText(String.valueOf(hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)));
}
private boolean canAccessLocation() {
return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}
private boolean canAccessCamera() {
return(hasPermission(Manifest.permission.CAMERA));
}
private boolean canAccessContacts() {
return(hasPermission(Manifest.permission.READ_CONTACTS));
}
private boolean hasPermission(String perm) {
return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
}
private void bzzzt() {
Toast.makeText(this, R.string.toast_bzzzt, Toast.LENGTH_LONG).show();
}
private void doCameraThing() {
Toast.makeText(this, R.string.toast_camera, Toast.LENGTH_SHORT).show();
}
private void doContactsThing() {
Toast.makeText(this, R.string.toast_contacts, Toast.LENGTH_SHORT).show();
}
private void doLocationThing() {
Toast.makeText(this, R.string.toast_location, Toast.LENGTH_SHORT).show();
}
}
(from this sample project)
For the requestPermissions() function, should the parameters just be "ACCESS_COARSE_LOCATION"? Or should I include the full name "android.permission.ACCESS_COARSE_LOCATION"?
I would use the constants defined on Manifest.permission
, as shown above.
Also, what is the request code?
That will be passed back to you as the first parameter to onRequestPermissionsResult()
, so you can tell one requestPermissions()
call from another.
The dplyr hybridized options are now around 30% faster than the Base R subset reassigns. On a 100M datapoint dataframe mutate_all(~replace(., is.na(.), 0))
runs a half a second faster than the base R d[is.na(d)] <- 0
option. What one wants to avoid specifically is using an ifelse()
or an if_else()
. (The complete 600 trial analysis ran to over 4.5 hours mostly due to including these approaches.) Please see benchmark analyses below for the complete results.
If you are struggling with massive dataframes, data.table
is the fastest option of all: 40% faster than the standard Base R approach. It also modifies the data in place, effectively allowing you to work with nearly twice as much of the data at once.
Locationally:
mutate_at(c(5:10), ~replace(., is.na(.), 0))
mutate_at(vars(var5:var10), ~replace(., is.na(.), 0))
mutate_at(vars(contains("1")), ~replace(., is.na(.), 0))
contains()
, try ends_with()
,starts_with()
mutate_at(vars(matches("\\d{2}")), ~replace(., is.na(.), 0))
Conditionally:
(change just single type and leave other types alone.)
mutate_if(is.integer, ~replace(., is.na(.), 0))
mutate_if(is.numeric, ~replace(., is.na(.), 0))
mutate_if(is.character, ~replace(., is.na(.), 0))
Updated for dplyr 0.8.0: functions use purrr format ~
symbols: replacing deprecated funs()
arguments.
# Base R:
baseR.sbst.rssgn <- function(x) { x[is.na(x)] <- 0; x }
baseR.replace <- function(x) { replace(x, is.na(x), 0) }
baseR.for <- function(x) { for(j in 1:ncol(x))
x[[j]][is.na(x[[j]])] = 0 }
# tidyverse
## dplyr
dplyr_if_else <- function(x) { mutate_all(x, ~if_else(is.na(.), 0, .)) }
dplyr_coalesce <- function(x) { mutate_all(x, ~coalesce(., 0)) }
## tidyr
tidyr_replace_na <- function(x) { replace_na(x, as.list(setNames(rep(0, 10), as.list(c(paste0("var", 1:10)))))) }
## hybrid
hybrd.ifelse <- function(x) { mutate_all(x, ~ifelse(is.na(.), 0, .)) }
hybrd.replace_na <- function(x) { mutate_all(x, ~replace_na(., 0)) }
hybrd.replace <- function(x) { mutate_all(x, ~replace(., is.na(.), 0)) }
hybrd.rplc_at.idx<- function(x) { mutate_at(x, c(1:10), ~replace(., is.na(.), 0)) }
hybrd.rplc_at.nse<- function(x) { mutate_at(x, vars(var1:var10), ~replace(., is.na(.), 0)) }
hybrd.rplc_at.stw<- function(x) { mutate_at(x, vars(starts_with("var")), ~replace(., is.na(.), 0)) }
hybrd.rplc_at.ctn<- function(x) { mutate_at(x, vars(contains("var")), ~replace(., is.na(.), 0)) }
hybrd.rplc_at.mtc<- function(x) { mutate_at(x, vars(matches("\\d+")), ~replace(., is.na(.), 0)) }
hybrd.rplc_if <- function(x) { mutate_if(x, is.numeric, ~replace(., is.na(.), 0)) }
# data.table
library(data.table)
DT.for.set.nms <- function(x) { for (j in names(x))
set(x,which(is.na(x[[j]])),j,0) }
DT.for.set.sqln <- function(x) { for (j in seq_len(ncol(x)))
set(x,which(is.na(x[[j]])),j,0) }
DT.nafill <- function(x) { nafill(df, fill=0)}
DT.setnafill <- function(x) { setnafill(df, fill=0)}
library(microbenchmark)
# 20% NA filled dataframe of 10 Million rows and 10 columns
set.seed(42) # to recreate the exact dataframe
dfN <- as.data.frame(matrix(sample(c(NA, as.numeric(1:4)), 1e7*10, replace = TRUE),
dimnames = list(NULL, paste0("var", 1:10)),
ncol = 10))
# Running 600 trials with each replacement method
# (the functions are excecuted locally - so that the original dataframe remains unmodified in all cases)
perf_results <- microbenchmark(
hybrid.ifelse = hybrid.ifelse(copy(dfN)),
dplyr_if_else = dplyr_if_else(copy(dfN)),
hybrd.replace_na = hybrd.replace_na(copy(dfN)),
baseR.sbst.rssgn = baseR.sbst.rssgn(copy(dfN)),
baseR.replace = baseR.replace(copy(dfN)),
dplyr_coalesce = dplyr_coalesce(copy(dfN)),
tidyr_replace_na = tidyr_replace_na(copy(dfN)),
hybrd.replace = hybrd.replace(copy(dfN)),
hybrd.rplc_at.ctn= hybrd.rplc_at.ctn(copy(dfN)),
hybrd.rplc_at.nse= hybrd.rplc_at.nse(copy(dfN)),
baseR.for = baseR.for(copy(dfN)),
hybrd.rplc_at.idx= hybrd.rplc_at.idx(copy(dfN)),
DT.for.set.nms = DT.for.set.nms(copy(dfN)),
DT.for.set.sqln = DT.for.set.sqln(copy(dfN)),
times = 600L
)
> print(perf_results) Unit: milliseconds expr min lq mean median uq max neval hybrd.ifelse 6171.0439 6339.7046 6425.221 6407.397 6496.992 7052.851 600 dplyr_if_else 3737.4954 3877.0983 3953.857 3946.024 4023.301 4539.428 600 hybrd.replace_na 1497.8653 1706.1119 1748.464 1745.282 1789.804 2127.166 600 baseR.sbst.rssgn 1480.5098 1686.1581 1730.006 1728.477 1772.951 2010.215 600 baseR.replace 1457.4016 1681.5583 1725.481 1722.069 1766.916 2089.627 600 dplyr_coalesce 1227.6150 1483.3520 1524.245 1519.454 1561.488 1996.859 600 tidyr_replace_na 1248.3292 1473.1707 1521.889 1520.108 1570.382 1995.768 600 hybrd.replace 913.1865 1197.3133 1233.336 1238.747 1276.141 1438.646 600 hybrd.rplc_at.ctn 916.9339 1192.9885 1224.733 1227.628 1268.644 1466.085 600 hybrd.rplc_at.nse 919.0270 1191.0541 1228.749 1228.635 1275.103 2882.040 600 baseR.for 869.3169 1180.8311 1216.958 1224.407 1264.737 1459.726 600 hybrd.rplc_at.idx 839.8915 1189.7465 1223.326 1228.329 1266.375 1565.794 600 DT.for.set.nms 761.6086 915.8166 1015.457 1001.772 1106.315 1363.044 600 DT.for.set.sqln 787.3535 918.8733 1017.812 1002.042 1122.474 1321.860 600
ggplot(perf_results, aes(x=expr, y=time/10^9)) +
geom_boxplot() +
xlab('Expression') +
ylab('Elapsed Time (Seconds)') +
scale_y_continuous(breaks = seq(0,7,1)) +
coord_flip()
qplot(y=time/10^9, data=perf_results, colour=expr) +
labs(y = "log10 Scaled Elapsed Time per Trial (secs)", x = "Trial Number") +
coord_cartesian(ylim = c(0.75, 7.5)) +
scale_y_log10(breaks=c(0.75, 0.875, 1, 1.25, 1.5, 1.75, seq(2, 7.5)))
When the datasets get larger, Tidyr''s replace_na
had historically pulled out in front. With the current collection of 100M data points to run through, it performs almost exactly as well as a Base R For Loop. I am curious to see what happens for different sized dataframes.
Additional examples for the mutate
and summarize
_at
and _all
function variants can be found here: https://rdrr.io/cran/dplyr/man/summarise_all.html
Additionally, I found helpful demonstrations and collections of examples here: https://blog.exploratory.io/dplyr-0-5-is-awesome-heres-why-be095fd4eb8a
With special thanks to:
local()
, and (with Frank's patient help, too) the role that silent coercion plays in speeding up many of these approaches. coalesce()
function in and update the analysis.data.table
functions well enough to finally include them in the lineup.is.numeric()
really tests.(Of course, please reach over and give them upvotes, too if you find those approaches useful.)
Note on my use of Numerics: If you do have a pure integer dataset, all of your functions will run faster. Please see alexiz_laz's work for more information. IRL, I can't recall encountering a data set containing more than 10-15% integers, so I am running these tests on fully numeric dataframes.
Hardware Used 3.9 GHz CPU with 24 GB RAM
Using balexandre's info:
SELECT usesysid, usename FROM pg_stat_activity;
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
Use map
if the function returns the object you need or flatMap
if the function returns an Optional
. For example:
public static void main(String[] args) {
Optional<String> s = Optional.of("input");
System.out.println(s.map(Test::getOutput));
System.out.println(s.flatMap(Test::getOutputOpt));
}
static String getOutput(String input) {
return input == null ? null : "output for " + input;
}
static Optional<String> getOutputOpt(String input) {
return input == null ? Optional.empty() : Optional.of("output for " + input);
}
Both print statements print the same thing.
With CSS 2 you can do this:
input[type='checkbox'] { ... }
This should be pretty widely supported by now. See support for browsers
Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id
?
UPDATE
SELECT t.*
FROM
(SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a
INNER JOIN temp_tickets t ON (t.id = a.id)
Just finished up a js library for formatting numbers Numeral.js. It handles decimals, dollars, percentages and even time formatting.
I got it working from qkzhu but instead of using MAX change it to MIN and window will close super fast.
@echo off
cd "C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin"
:: Title not needed:
start /MIN mysqld.exe
exit
I am guessing you're confused with the parameterization of the types:
// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>();
// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();
I was similarly underwhelmed by this situation and ended up making my own Ubuntu source packages for this. These source packages allow you to easily produce a binary package. They are based on the latest gtest & gmock source as of this post.
Google Test DEB Source Package
Google Mock DEB Source Package
To build the binary package do this:
tar -xzvf gtest-1.7.0.tar.gz
cd gtest-1.7.0
dpkg-source -x gtest_1.7.0-1.dsc
cd gtest-1.7.0
dpkg-buildpackage
It may tell you that you need some pre-requisite packages in which case you just need to apt-get install them. Apart from that, the built .deb binary packages should then be sitting in the parent directory.
For GMock, the process is the same.
As a side note, while not specific to my source packages, when linking gtest to your unit test, ensure that gtest is included first (https://bbs.archlinux.org/viewtopic.php?id=156639) This seems like a common gotcha.
FYI - I had this issue as well and it turned out that my html listed the .jpg file with a .JPG in caps, but the file itself was lowercase .jpg. That rendered fine locally and using Codekit, but when it was pushed to the web it wouldn't load. Simply changing the file names to have a lowercase .jpg extension to match the html did the trick.
You can create a dynamic table rows as below:
var tbl = document.createElement('table');
tbl.style.width = '100%';
for (var i = 0; i < files.length; i++) {
tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
::::: // As many <td> you want
td1.appendChild(document.createTextNode());
td2.appendChild(document.createTextNode());
td3.appendChild(document.createTextNode();
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tbl.appendChild(tr);
}
If you are looking for a real simple way to log, you can use this one liner. If the file doesn't exist, it's created.
System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");
Hey i always make methods for custom stuff that is usually not implemented in java. Here is a simple method i made for removing character from String Fast
public static String removeChar(String str, char c){
StringBuilder strNew=new StringBuilder(str.length());
char charRead;
for(int i=0;i<str.length();i++){
charRead=str.charAt(i);
if(charRead!=c)
strNew.append(charRead);
}
return strNew.toString();
}
For explaintion, yes there is no null character for replacing, but you can remove character like this. I know its a old question, but i am posting this answer because this code may be helpful for some persons.
Tested and working 100%
public class MainActivity extends ActionBarActivity {
Context context = this;
MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mp = MediaPlayer.create(context, R.raw.sound);
final Button b = (Button) findViewById(R.id.Button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
}
}
This was all we had to do
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
}
There are already some great answers but I would like to add a little visual explanation
Now, take a look at the image, there are
n/2^1
green nodes with height 0 (here 23/2 = 12)
n/2^2
red nodes with height 1 (here 23/4 = 6)
n/2^3
blue node with height 2 (here 23/8 = 3)
n/2^4
purple nodes with height 3 (here 23/16 = 2)
so there are n/2^(h+1)
nodes for height h
To find the time complexity lets count the amount of work done or max no of iterations performed by each node
now it can be noticed that each node can perform(atmost) iterations == height of the node
Green = n/2^1 * 0 (no iterations since no children)
red = n/2^2 * 1 (heapify will perform atmost one swap for each red node)
blue = n/2^3 * 2 (heapify will perform atmost two swaps for each blue node)
purple = n/2^4 * 3 (heapify will perform atmost three swaps for each purple node)
so for any nodes with height h maximum work done is n/2^(h+1) * h
Now total work done is
->(n/2^1 * 0) + (n/2^2 * 1)+ (n/2^3 * 2) + (n/2^4 * 3) +...+ (n/2^(h+1) * h)
-> n * ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) )
now for any value of h, the sequence
-> ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) )
will never exceed 1
Thus the time complexity will never exceed O(n) for building heap
add -e
key for passing environment variables to container.
example:
$ MYSQLHOSTIP=$(sudo docker inspect -format="{{ .NetworkSettings.IPAddress }}" $MYSQL_CONRAINER_ID)
$ sudo docker run -e DBIP=$MYSQLHOSTIP -i -t myimage /bin/bash
root@87f235949a13:/# echo $DBIP
172.17.0.2
If you want to safe time and lines of code you can make measuring the function execution time a one line macro:
a) Implement a time measuring class as already suggested above ( here is my implementation for android):
class MeasureExecutionTime{
private:
const std::chrono::steady_clock::time_point begin;
const std::string caller;
public:
MeasureExecutionTime(const std::string& caller):caller(caller),begin(std::chrono::steady_clock::now()){}
~MeasureExecutionTime(){
const auto duration=std::chrono::steady_clock::now()-begin;
LOGD("ExecutionTime")<<"For "<<caller<<" is "<<std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()<<"ms";
}
};
b) Add a convenient macro that uses the current function name as TAG (using a macro here is important, else __FUNCTION__
will evaluate to MeasureExecutionTime
instead of the function you wanto to measure
#ifndef MEASURE_FUNCTION_EXECUTION_TIME
#define MEASURE_FUNCTION_EXECUTION_TIME const MeasureExecutionTime measureExecutionTime(__FUNCTION__);
#endif
c) Write your macro at the begin of the function you want to measure. Example:
void DecodeMJPEGtoANativeWindowBuffer(uvc_frame_t* frame_mjpeg,const ANativeWindow_Buffer& nativeWindowBuffer){
MEASURE_FUNCTION_EXECUTION_TIME
// Do some time-critical stuff
}
Which will result int the following output:
ExecutionTime: For DecodeMJPEGtoANativeWindowBuffer is 54ms
Note that this (as all other suggested solutions) will measure the time between when your function was called and when it returned, not neccesarily the time your CPU was executing the function. However, if you don't give the scheduler any change to suspend your running code by calling sleep() or similar there is no difference between.
Another post on this topic with a nice jQuery/Ajax/PHP solution:
This is special restriction added by developers of create-react-app. It is implemented in ModuleScopePlugin
to ensure files reside in src/
. That plugin ensures that relative imports from app's source directory don't reach outside of it.
You can disable this feature (one of the ways) by eject
operation of create-react-app project.
Most features and its updates are hidden into the internals of create-react-app system. If you make eject
you will no more have some features and its update. So if you are not ready to manage and configure application included to configure webpack and so on - do not do eject
operation.
Play by the existing rules (move to src). But now you can know how to remove restriction: do eject
and remove ModuleScopePlugin
from webpack configuration file.
Instead of eject
there are intermediate solutions, like
rewire which allows you to programmatically modify the webpack config without eject
. But removing the ModuleScopePlugin
plugin is not good - this loses some protection and does not adds some features available in src
.
The better way is to add fully working additional directories similar to src
. This can be done using react-app-rewire-alias
Do not import from public
folder - that will be duplicated in the build
folder and will be available by two different url (or with different ways to load), which ultimately worsen the package download size.
Importing from the src
folder is preferable and has advantages. Everything will be packed by webpack to the bundle with chunks optimal size and for best loading efficiency.
Here are the changes I had to make to deliver PDFs for the django-publications app, using Django 1.10.6:
Used the same definitions for media directories as you, in settings.py
:
MEDIA_ROOT = '/home/user/mysite/media/'
MEDIA_URL = '/media/'
As provided by @thisisashwanipandey, in the project's main urls.py
:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and a modification of the answer provided by @r-allela, in settings.py
:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# ... the rest of your context_processors goes here ...
'django.template.context_processors.media',
],
},
},
]
I had the same problem and after some searching I was able to find my logs at the following location:
C:\Users\<yourid>\.AndroidStudioPreview\system\log
How about this? Just give it a thought-
import java.util.ArrayList;
class Solution
{
public static void main (String[] args){
ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");
int i[] = {1,3,5};
for (int j = 0; j < i.length; j++) {
List_Of_Array.remove(i[j]-j);
}
System.out.println(List_Of_Array);
}
}
And the output was-
[A, C, E, G, H]
I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.
Give "write" permission to the directory you need to put the file. In your case it is the current directory.
Use "chmod" in linux.
Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.
In templates, you can separate filter arguments by colons.
{{ yourExpression | yourFilter: arg1:arg2:... }}
From Javascript, you call it as
$filter('yourFilter')(yourExpression, arg1, arg2, ...)
There is actually an example hidden in the orderBy filter docs.
Example:
Let's say you make a filter that can replace things with regular expressions:
myApp.filter("regexReplace", function() { // register new filter
return function(input, searchRegex, replaceRegex) { // filter arguments
return input.replace(RegExp(searchRegex), replaceRegex); // implementation
};
});
Invocation in a template to censor out all digits:
<p>{{ myText | regexReplace: '[0-9]':'X' }}</p>
I like the example given by Active State using python. Here is the full link. I added the simple log in part from the link but you can get the gist of what you could do.
import telnetlib
prdLogBox='142.178.1.3'
uid = 'uid'
pwd = 'yourpassword'
tn = telnetlib.Telnet(prdLogBox)
tn.read_until("login: ")
tn.write(uid + "\n")
tn.read_until("Password:")
tn.write(pwd + "\n")
tn.write("exit\n")
tn.close()
http://jsfiddle.net/isherwood/gfgux
html, body {
height: 100%;
}
#table-row, #table-col, #table-wrapper {
height: 80%;
}
<div id="content" class="container">
<div id="table-row" class="row">
<div id="table-col" class="col-md-7 col-xs-10 pull-left">
<p>Hello</p>
<div id="table-wrapper" class="table-responsive">
<table class="table table-bordered ">
Removing only decimal part can be done as follows:
number.replace(/(\.\d+)+/,'');
This would convert 13.6667px into 13px (leaving units px untouched).
If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:
SQL> connect SYSTEM/fyicenter
Connected.
SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
2 FROM USER_TABLESPACES;
TABLESPACE_NAME STATUS CONTENTS
------------------------------ --------- ---------
SYSTEM ONLINE PERMANENT
UNDO ONLINE UNDO
SYSAUX ONLINE PERMANENT
TEMP ONLINE TEMPORARY
USERS ONLINE PERMANENT
http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html
All you need to do is a post request like below :-
POST https://www.googleapis.com/oauth2/v4/token
Content-Type: application/json
{
"client_id": <client_id>,
"client_secret": <client_secret>,
"refresh_token": <refresh_token>,
"grant_type": "refresh_token"
}
Simpiest way to get list of modified files and save it to some text file is:
git diff --name-only HEAD^ > modified_files.txt
Right click your project folder, look for Properties in Java build path and select the jar files that you see. It has worked for me.
Depth first, post order, non recursive, without stack
When you have parent:
node_t
{
left,
right
parent
}
traverse(node_t rootNode)
{
bool backthreading = false
node_t node = rootNode
while(node <> 0)
if (node->left <> 0) and backthreading = false then
node = node->left
continue
endif
>>> process node here <<<
if node->right <> 0 then
lNode = node->right
backthreading = false
else
node = node->parent
backthreading = true
endif
endwhile
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties
inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx
Add the event listeners etc..
Hope this helps
In Windows, if you have the shortcut in your taskbar, right-click the "Anaconda Prompt" icon, you'll see:
Right-click on "Anaconda Prompt" again.
Click "Properties"
Add the path you want your anaconda prompt to open up into in the "Start In:" section.
Note - you can also do this by searching for "Anaconda Prompt" in the Start Menu. The directions above are specifically for the shortcut.
If you want to get unique data based on the nested key:
app.filter('unique', function() {
return function(collection, primaryKey, secondaryKey) { //optional secondary key
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key;
secondaryKey === undefined ? key = item[primaryKey] : key = item[primaryKey][secondaryKey];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};
});
Call it like this :
<div ng-repeat="notify in notifications | unique: 'firstlevel':'secondlevel'">
And if you want to retain any of the aggregation info from the second level of the multiindex you can try this:
In [1]: new_cols = [''.join(t) for t in df.columns]
Out[1]:
['USAF',
'WBAN',
'day',
'month',
's_CDsum',
's_CLsum',
's_CNTsum',
's_PCsum',
'tempfamax',
'tempfamin',
'year']
In [2]: df.columns = new_cols
You could use the "Shown" event: MSDN - Form.Shown
"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."
substring(int startIndex, int endIndex)
If you don't specify endIndex, the method will return all the characters from startIndex.
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Example:
String str = "abcdefgh"
str.substring(0, 4)
=> abcd
str.substring(4, 6)
=> ef
str.substring(6)
=> gh
Sounds like you don't have the execute flag set on the file permissions, try:
chmod u+x program_name
You can use int()
function to convert float64
type data to an int
. Similarly you can use float64()
Example:
func check(n int) bool {
// count the number of digits
var l int = countDigit(n)
var dup int = n
var sum int = 0
// calculates the sum of digits
// raised to power
for dup > 0 {
**sum += int(math.Pow(float64(dup % 10), float64(l)))**
dup /= 10
}
return n == sum
}
You can get this in following way,
DateTimeFormatInfo mfi = new DateTimeFormatInfo();
string strMonthName = mfi.GetMonthName(8).ToString(); //August
Now, get first three characters
string shortMonthName = strMonthName.Substring(0, 3); //Aug
I know it's an old question Still thought it would help someone
1) Go to your jar file's folder.
2) change it's extension to .zip.
3) You are good to go and can easily extract it by just double clicking it.
Note: I tested this in MAC, it works. Hopefully it will work on windows too.
I see some of the above answers are now a bit out of date. From my perspective, and I work with both Solr(Cloud and non-Cloud) and ElasticSearch on a daily basis, here are some interesting differences:
For more thorough coverage of Solr vs. ElasticSearch topic have a look at https://sematext.com/blog/solr-vs-elasticsearch-part-1-overview/ . This is the first post in the series of posts from Sematext doing direct and neutral Solr vs. ElasticSearch comparison. Disclosure: I work at Sematext.
Spring Security is intended to work with other non-Spring frameworks, hence it is not tightly integrated with Spring MVC. Spring Security returns the Authentication
object from the HttpServletRequest.getUserPrincipal()
method by default so that's what you get as the principal. You can obtain your UserDetails
object directly from this by using
UserDetails ud = ((Authentication)principal).getPrincipal()
Note also that the object types may vary depending on the authentication mechanism used (you may not get a UsernamePasswordAuthenticationToken
, for example) and the Authentication
doesn't strictly have to contain a UserDetails
. It can be a string or any other type.
If you don't want to call SecurityContextHolder
directly, the most elegant approach (which I would follow) is to inject your own custom security context accessor interface which is customized to match your needs and user object types. Create an interface, with the relevant methods, for example:
interface MySecurityAccessor {
MyUserDetails getCurrentUser();
// Other methods
}
You can then implement this by accessing the SecurityContextHolder
in your standard implementation, thus decoupling your code from Spring Security entirely. Then inject this into the controllers which need access to security information or information on the current user.
The other main benefit is that it is easy to make simple implementations with fixed data for testing, without having to worry about populating thread-locals and so on.
First solution - simply change the extension of your .json file to .ts and add export default
at the beginning of the file, like so:
export default {
property: value;
}
Then you can just simply import the file without the need to add typings, like so:
import data from 'data';
Second solution get the json via HttpClient.
Inject HttpClient into your component, like so:
export class AppComponent {
constructor(public http: HttpClient) {}
}
and then use this code:
this.http.get('/your.json').subscribe(data => {
this.results = data;
});
This solution has one clear adventage over other solutions provided here - it doesn't require you to rebuild entire application if your json will change (it's loaded dynamically from a separate file, so you can modify only that file).
The != operator most certainly does exist! It is an alias for the standard <>
operator.
Perhaps your fields are not actually empty strings, but instead NULL
?
To compare to NULL
you can use IS NULL
or IS NOT NULL
or the null safe equals operator <=>
.
This is a pretty good source for info about Haskell and its uses:
In runtime you could simply execute
com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump = true
as dump is a public var defined in the class as follows
public static boolean dump;
prevArrow/nextArrow
Type:
string (html|jQuery selector) | object (DOM node|jQuery object)
Some example code
$(document).ready(function(){
$('.slick-carousel-1').slick({
// @type {string} html
nextArrow: '<button class="any-class-name-you-want-next">Next</button>',
prevArrow: '<button class="any-class-name-you-want-previous">Previous</button>'
});
$('.slick-carousel-2').slick({
// @type {string} jQuery Selector
nextArrow: '.next',
prevArrow: '.previous'
});
$('.slick-carousel-3').slick({
// @type {object} DOM node
nextArrow: document.getElementById('slick-next'),
prevArrow: document.getElementById('slick-previous')
});
$('.slick-carousel-4').slick({
// @type {object} jQuery Object
nextArrow: $('.example-4 .next'),
prevArrow: $('.example-4 .previous')
});
});
A little note on styling
Once Slick knows about your new buttons, you can style them to your heart's content; looking at the above example, you could target them based on class
name, id
name or even element
.
You can check this
[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{
string url = "https://localhost:44305/Templates/ReportPage.html";
System.Uri uri = new System.Uri(url);
return Redirect(uri);
}
For setting proxy server we need to set APNS
setting. To do this:
Go to Setting
Go to wireless and networks
Go to mobile networks
Go to access point names. Use menu to add new apns
Set Proxy = localhost
Set Port = port that you are using to make proxy server, in my case it is 8989
For setting Name and apn here is the link:
According to your sim
card you can see the table
If you know that the value of the XML element is a float number (latitude, longitude, distance), you can use (float)
$value = (float) $xml->code[0]->lat;
Also, (int)
for integer number:
$value = (int) $xml->code[0]->distance;
Or... You could place the image in an anchor tag. Cause I had the same problem and it fixed it without issue. A lot of people use local paths before they publish their site and photos. Just make sure you go back and fix that in the final editing phase.
So I'm not entirely sure why this works, but it saves an image with my plot:
dtf = pd.DataFrame.from_records(d,columns=h)
dtf2.plot()
fig = plt.gcf()
fig.savefig('output.png')
I'm guessing that the last snippet from my original post saved blank because the figure was never getting the axes generated by pandas. With the above code, the figure object is returned from some magic global state by the gcf() call (get current figure), which automagically bakes in axes plotted in the line above.
Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:
<select name='role'>
<option value="${selected}" selected>${selected}</option>
<c:forEach items="${roles}" var="role">
<c:if test="${role != selected}">
<option value="${role}">${role}</option>
</c:if>
</c:forEach>
</select>
UPDATE (next question)
You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.
Because of the limitations of the expression language, I think the best way to deal with this is to use a map:
Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
String productSubCategoryName=userProductData.get(i).getProductSubCategory();
System.out.println(productSubCategoryName);
map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);
And then in the JSP:
<select multiple="multiple" name="prodSKUs">
<c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
<option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
</c:forEach>
</select>
My solution is more simple than the other answers provided and doesn't have the downsides.
It preserves the Error prototype chain and all properties on Error without needing specific knowledge of them. It's been tested in Chrome, Firefox, Node, and IE11.
The only limitation is an extra entry at the top of the call stack. But that is easily ignored.
Here's an example with two custom parameters:
function CustomError(message, param1, param2) {
var err = new Error(message);
Object.setPrototypeOf(err, CustomError.prototype);
err.param1 = param1;
err.param2 = param2;
return err;
}
CustomError.prototype = Object.create(
Error.prototype,
{name: {value: 'CustomError', enumerable: false}}
);
Example Usage:
try {
throw new CustomError('Something Unexpected Happened!', 1234, 'neat');
} catch (ex) {
console.log(ex.name); //CustomError
console.log(ex.message); //Something Unexpected Happened!
console.log(ex.param1); //1234
console.log(ex.param2); //neat
console.log(ex.stack); //stacktrace
console.log(ex instanceof Error); //true
console.log(ex instanceof CustomError); //true
}
For environments that require a polyfil of setPrototypeOf:
Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
obj.__proto__ = proto;
return obj;
};
DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'
IF PATINDEX('%[0-9]%', @str) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'
The actual standard key-layout is found in /system/usr/keylayout/qwerty.kl
within the Android running on the handset. And it is a generic keylayout also.
key 115 VOLUME_UP WAKE
key 114 VOLUME_DOWN WAKE
From the AOSP source it can be found in sdk/emulator/keymaps/qwerty.kl
.
But bear in mind this, when the source gets compiled along with a device specific keylayout, that will override the standard layout instead so the mileage will vary depending on what the manufacturer has programmed into the keycode for the volume up/down buttons in your case!
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
You can use the viewport height, just set the height of your div to height:100vh;
, this will set the height of your div to the height of the viewport of the device, furthermore, if you want it to be exactly as your device screen, set the margin and padding to 0.
Plus, It will be a good idea to set the viewport meta tag:
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0" />
Please Note that this is relatively new and is not supported in IE8-, take a look at the support list before considering this approach (http://caniuse.com/#search=viewport).
Hope this helps.
You can use a window MAX() like this:
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
to get max dates per group
alongside other data:
group date cash checks max_date
----- -------- ---- ------ --------
1 1/1/2013 0 0 1/3/2013
2 1/1/2013 0 800 1/1/2013
1 1/3/2013 0 700 1/3/2013
3 1/1/2013 0 600 1/5/2013
1 1/2/2013 0 400 1/3/2013
3 1/5/2013 0 200 1/5/2013
Using the above output as a derived table, you can then get only rows where date
matches max_date
:
SELECT
group,
date,
checks
FROM (
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
) AS s
WHERE date = max_date
;
to get the desired result.
Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.
You can try the method at SQL Fiddle.
There could be a few things happening here. Start by first figuring out your library location:
Sys.getenv("R_LIBS_USER")
or
.libPaths()
We already know yours from the info you gave: C:\Program Files\R\R-3.0.1\library
I believe you have a file in there called: 00LOCK
. From ?install.packages
:
Note that it is possible for the package installation to fail so badly that the lock directory is not removed: this inhibits any further installs to the library directory (or for --pkglock, of the package) until the lock directory is removed manually.
You need to delete that file. If you had the pacman
package installed you could have simply used p_unlock()
and the 00LOCK
file is removed. You can't install pacman
now until the 00LOCK
file is removed.
To install pacman
use:
install.packages("pacman")
There may be a second issue. This is where you somehow corrupted MASS
. This can occur, in my experience, if you try to update a package while it is in use in another R session. I'm sure there's other ways to cause this as well. To solve this problem try:
Sys.getenv("R_LIBS_USER")
. In your case this is: C:\Program Files\R\R-3.0.1\libraryMASS
packageMASS
via install.packages("MASS")
If any of this works please let me know what worked.
I use JSONP.
Basically, you add
<script src="http://..../someData.js?callback=some_func"/>
on your page.
some_func() should get called so that you are notified that the data is in.
the core functions are getBytes(String charset)
and new String(byte[] data)
. you can use these functions to do UTF-8 decoding.
UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String()
is the byte array, which calling is equal to new String(bytes, "UTF-8")
Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.
The decoding sentence should be
String decoded = new String(encoded.getBytes("ISO-8859-1"));
First of all, if you want it displayed on a PHP form, the medium is HTML and so a new line will be rendered with the <br />
tag. Check the source HTML of the page - you may possibly have the new line rendered just as a line break, in which case your problem is simply one of translating the text for output to a web browser.
git config --list
to check current username & email in your local repo.git config [--global] user.name "Full Name"
git config [--global] user.email "[email protected]"
.git/config
manually instead.When performing step 2 if you see credential.helper=manager
you need to open the credential manager of your computer (Win or Mac) and update the credentials there
Here is how it look on windows
Troubleshooting? Learn more
Following examples work for me, please note "is_user_defined" NOT "is_table_type"
IF TYPE_ID(N'idType') IS NULL
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
IF not EXISTS (SELECT * FROM sys.types WHERE is_user_defined = 1 AND name = 'idType')
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
In your HTML you have set a "base" tag:
<base href="http://www.cyclistinsuranceaustralia.com.au/">
How can I display these open transactions and commit or cancel them?
There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).
You display threads using
SHOW FULL PROCESSLIST
See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html
It will not help you, because you cannot commit a transaction from a broken connection.
What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html
4.5.1.6.3. Disabling mysql Auto-Reconnect
If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.
This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:
Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
How to diagnose and fix this
To check for auto-reconnection:
If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call
mysql_thread_id()
to get the original connection identifier before callingmysql_ping()
, then callmysql_thread_id()
again to see whether the identifier has changed.
Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.
SAX
parser is working differently with a DOM
parser, it neither load any XML
document into memory nor create any object representation of the XML
document. Instead, the SAX
parser use callback function org.xml.sax.helpers.DefaultHandler
to informs clients of the XML
document structure.
SAX
Parser is faster and uses less memory than DOM
parser.
See following SAX
callback methods :
startDocument()
and endDocument()
– Method called at the start and end of an XML document.
startElement()
and endElement()
– Method called at the start and end of a document element.
characters()
– Method called with the text contents in between the start and end tags of an XML document element.
Create a simple XML file.
<?xml version="1.0"?>
<company>
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
Java file Use SAX parser to parse the XML file.
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("FIRSTNAME")) {
bfname = true;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}
if (qName.equalsIgnoreCase("NICKNAME")) {
bnname = true;
}
if (qName.equalsIgnoreCase("SALARY")) {
bsalary = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bfname) {
System.out.println("First Name : " + new String(ch, start, length));
bfname = false;
}
if (blname) {
System.out.println("Last Name : " + new String(ch, start, length));
blname = false;
}
if (bnname) {
System.out.println("Nick Name : " + new String(ch, start, length));
bnname = false;
}
if (bsalary) {
System.out.println("Salary : " + new String(ch, start, length));
bsalary = false;
}
}
};
saxParser.parse("c:\\file.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Result
Start Element :company
Start Element :staff
Start Element :firstname
First Name : yong
End Element :firstname
Start Element :lastname
Last Name : mook kim
End Element :lastname
Start Element :nickname
Nick Name : mkyong
End Element :nickname
and so on...
Source(MyKong) - http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
How about this solution:
str="Hello World" (as stated in problem) srr = str+ ""
Use korn shell, in bash you may have to compare the decimal part separately
#!/bin/ksh
X=0.2
Y=0.2
echo $X
echo $Y
if [[ $X -lt $Y ]]
then
echo "X is less than Y"
elif [[ $X -gt $Y ]]
then
echo "X is greater than Y"
elif [[ $X -eq $Y ]]
then
echo "X is equal to Y"
fi
for i in range(len(arr)):
if l[-1] > l[i]:
l[-1], l[i] = l[i], l[-1]
break
as a result of this if last element is greater than element at position i
then they both get swapped .
Look at these to build a solution more or less from scratch:
You always have the option of calling external tools from Java using the exec()
and similar methods. For instance, you could use wget
, or cURL
.
Then if you want to go into more fully-fledged stuff, thankfully the need for automated web-testing as given us very practical tools for this. Look at:
Some other libs are purposefully written with web-scraping in mind:
Java is a language, but also a platform, with many other languages running on it. Some of which integrate great syntactic sugar or libraries to easily build scrapers.
Check out:
If you know of a great library for Ruby (JRuby, with an article on scraping with JRuby and HtmlUnit) or Python (Jython) or you prefer these languages, then give their JVM ports a chance.
Some other similar questions:
In my case, it was caused by unhandled exception while creating eventLog source. Use try catch to pin point the cause.
I think your return string data is very long. so the JSON format has been corrupted. You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
I got the same problem with the string "PastelerÃa Mallorca" and I solved with:
unicode("PastelerÃa Mallorca", 'latin-1')
Template Syntax Error: is due to many reasons one of them is {{ post.date_posted|date: "F d, Y" }} is the space between colon(:) and quote (") if u remove the space then it work like this ..... {{ post.date_posted|date:"F d, Y" }}
You need to add a reference to System.Web.Extensions.dll
in project for System.Web.Script.Serialization error.
take a look at shutil
. shutil.copyfile(src, dst)
will copy a file to another file.
Note that shutil.copyfile
will not create directories that do not already exist. for that, use os.makedirs
With the atom editor, you just need to install the git-plus package.
I was facing the same issue, the funny thing was I had two projects opened on simultaneously, I have changed the wrong app.modules.ts files.
First, check that.
After that change add the following code to the app.module.ts file
import { HttpClientModule } from '@angular/common/http';
After that add the following to the imports array in the app.module.ts file
imports: [
HttpClientModule,....
],
Now you should be ok!
For me the problem was in that I wrote compileSdkVersion '23' instead of 23. The quotes were the problem.
The problem with asking this question is that you'll get so many subjective answers that simply state "I prefer this...". Instead of making such pointless statements, I'll try to answer this question with facts and references, rather than personal opinions.
Through experience, we can probably start by excluding the do-while alternatives (and the goto), as they are not commonly used. I can't recall ever seeing them in live production code, written by professionals.
The while(1)
, while(true)
and for(;;)
are the 3 different versions commonly existing in real code. They are of course completely equivalent and results in the same machine code.
for(;;)
This is the original, canonical example of an eternal loop. In the ancient C bible The C Programming Language by Kernighan and Ritchie, we can read that:
K&R 2nd ed 3.5:
for (;;) {
...
}
is an "infinite" loop, presumably to be broken by other means, such as a break or return. Whether to use while or for is largely a matter of personal preference.
For a long while (but not forever), this book was regarded as canon and the very definition of the C language. Since K&R decided to show an example of for(;;)
, this would have been regarded as the most correct form at least up until the C standardization in 1990.
However, K&R themselves already stated that it was a matter of preference.
And today, K&R is a very questionable source to use as a canonical C reference. Not only is it outdated several times over (not addressing C99 nor C11), it also preaches programming practices that are often regarded as bad or blatantly dangerous in modern C programming.
But despite K&R being a questionable source, this historical aspect seems to be the strongest argument in favour of the for(;;)
.
The argument against the for(;;)
loop is that it is somewhat obscure and unreadable. To understand what the code does, you must know the following rule from the standard:
ISO 9899:2011 6.8.5.3:
for ( clause-1 ; expression-2 ; expression-3 ) statement
/--/
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
Based on this text from the standard, I think most will agree that it is not only obscure, it is subtle as well, since the 1st and 3rd part of the for loop are treated differently than the 2nd, when omitted.
while(1)
This is supposedly a more readable form than for(;;)
. However, it relies on another obscure, although well-known rule, namely that C treats all non-zero expressions as boolean logical true. Every C programmer is aware of that, so it is not likely a big issue.
There is one big, practical problem with this form, namely that compilers tend to give a warning for it: "condition is always true" or similar. That is a good warning, of a kind which you really don't want to disable, because it is useful for finding various bugs. For example a bug such as while(i = 1)
, when the programmer intended to write while(i == 1)
.
Also, external static code analysers are likely to whine about "condition is always true".
while(true)
To make while(1)
even more readable, some use while(true)
instead. The consensus among programmers seem to be that this is the most readable form.
However, this form has the same problem as while(1)
, as described above: "condition is always true" warnings.
When it comes to C, this form has another disadvantage, namely that it uses the macro true
from stdbool.h. So in order to make this compile, we need to include a header file, which may or may not be inconvenient. In C++ this isn't an issue, since bool
exists as a primitive data type and true
is a language keyword.
Yet another disadvantage of this form is that it uses the C99 bool type, which is only available on modern compilers and not backwards compatible. Again, this is only an issue in C and not in C++.
So which form to use? Neither seems perfect. It is, as K&R already said back in the dark ages, a matter of personal preference.
Personally, I always use for(;;)
just to avoid the compiler/analyser warnings frequently generated by the other forms. But perhaps more importantly because of this:
If even a C beginner knows that for(;;)
means an eternal loop, then who are you trying to make the code more readable for?
I guess that's what it all really boils down to. If you find yourself trying to make your source code readable for non-programmers, who don't even know the fundamental parts of the programming language, then you are only wasting time. They should not be reading your code.
And since everyone who should be reading your code already knows what for(;;)
means, there is no point in making it further readable - it is already as readable as it gets.
There's our IDE / engine called Codea.
The runtime is iOS only, but it's open source. The development environment is iPad only at the moment.
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
Simply add your NextActivity
in the Manifest.XML
file
<activity
android:name="com.example.sms1.NextActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE
Let check the parameter value.
If in Case it is :
SQL> show parameter resource_limit
NAME TYPE VALUE
------------------------------------ ----------- ---------
resource_limit boolean FALSE
Its mean resource limit is off,we ist have to enable it.
Use the ALTER SYSTEM statement to turn on resource limits.
SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.
The problem was caused by not setting the CUDA_VISIBLE_DEVICES
variable within the shell correctly.
To specify CUDA device 1
for example, you would set the CUDA_VISIBLE_DEVICES
using
export CUDA_VISIBLE_DEVICES=1
or
CUDA_VISIBLE_DEVICES=1 ./cuda_executable
The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.
If you want to specify more than one device, use
export CUDA_VISIBLE_DEVICES=0,1
or
CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable
I have some code in my game that displays live score. It is in a function for quick access.
def texts(score):
font=pygame.font.Font(None,30)
scoretext=font.render("Score:"+str(score), 1,(255,255,255))
screen.blit(scoretext, (500, 457))
and I call it using this in my while loop:
texts(score)
I finally figured out, it's because the Hibernate is using slf4j log facade now, to bridge to log4j, you need to put log4j and slf4j-log4j12 jars to your lib and then the log4j properties will take control Hibernate logs.
My pom.xml setting looks as below:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<FilesMatch "\.(js|css)$">
ExpiresActive On
ExpiresDefault A1
Header append Cache-Control must-revalidate
</FilesMatch>
You can eventually extend the EL language by using the EL Functor, which will allow you to call any Java beans methods, even with parameters...
According to the Go specification:
For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.
A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.
In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.
If you were unsure if it was a string or not, you could test using the two return syntax.
str, ok := data.(string)
If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:
if str, ok := data.(string); ok {
/* act on str */
} else {
/* not string */
}
I have the same issue in Ubuntu 14.04.
I have installed "nodejs" and it's working, but only if I'm use command "nodejs". If I try to use "node" nothing happens.
I'm fixed this problem in next way:
Install nodejs-legacy
sudo apt-get install nodejs-legacy
After that, when I type "node" in command line I'm get an error message "/usr/sbin/node: No such file or directory"
Second, what I did, it's a symbolic link on "nodejs":
sudo ln -s /usr/bin/nodejs /usr/sbin/node
You can do it with using a FileOutputStream
and the writeTo
method.
ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
byteArrayOutputStream.writeTo(outputStream);
}
Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions
Below is the easy one -
cat countvariable.sh
echo "$@" |awk '{for(i=0;i<=NF;i++); print i-1 }'
Output :
#./countvariable.sh 1 2 3 4 5 6
6
#./countvariable.sh 1 2 3 4 5 6 apple orange
8
You would simply use jQuery like so...
<script>
jQuery(function(){
jQuery('#modal').click();
});
</script>
Use the click function to auto-click the #modal button
Or for fun:
>>> ast.literal_eval('[%s]'%','.join(map(repr,s.split())))
['QH', 'QD', 'JC', 'KD', 'JS']
>>>
ast.literal_eval
I think you want this:
Dim filename As String
filename = Application.GetOpenFilename
Dim cell As Range
cell = Application.Range("A1")
cell.Value = filename
easy as py:
class Downloder():
def download_manager(self, url, destination='Files/DownloderApp/', try_number="10", time_out="60"):
#threading.Thread(target=self._wget_dl, args=(url, destination, try_number, time_out, log_file)).start()
if self._wget_dl(url, destination, try_number, time_out, log_file) == 0:
return True
else:
return False
def _wget_dl(self,url, destination, try_number, time_out):
import subprocess
command=["wget", "-c", "-P", destination, "-t", try_number, "-T", time_out , url]
try:
download_state=subprocess.call(command)
except Exception as e:
print(e)
#if download_state==0 => successfull download
return download_state
Anders solution worked for me but I wasn't sure how to invert it to get the opposite (when you weren't an admin).
Here's my solution. It has two cases an IF and ELSE case, and some ascii art to ensure people actually read it. :)
Rushyo posted this solution here: How to detect if CMD is running as Administrator/has elevated privileges?
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator PRIVILEGES Detected!
) ELSE (
ECHO NOT AN ADMIN!
)
@rem ----[ This code block detects if the script is being running with admin PRIVILEGES If it isn't it pauses and then quits]-------
echo OFF
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator PRIVILEGES Detected!
) ELSE (
echo ######## ######## ######## ####### ########
echo ## ## ## ## ## ## ## ## ##
echo ## ## ## ## ## ## ## ## ##
echo ###### ######## ######## ## ## ########
echo ## ## ## ## ## ## ## ## ##
echo ## ## ## ## ## ## ## ## ##
echo ######## ## ## ## ## ####### ## ##
echo.
echo.
echo ####### ERROR: ADMINISTRATOR PRIVILEGES REQUIRED #########
echo This script must be run as administrator to work properly!
echo If you're seeing this after clicking on a start menu icon, then right click on the shortcut and select "Run As Administrator".
echo ##########################################################
echo.
PAUSE
EXIT /B 1
)
@echo ON
Works on WinXP --> Win8 (including 32/64 bit versions).
EDIT: 8/28/2012 Updated to support Windows 8. @BenHooper pointed this out in his answer below. Please upvote his answer.
With Xcode 7 you are no longer required to have a developer account in order to test your apps on your device:
Check it out here.
Please notice that this is the officially supported by Apple, so there's no need of jailbroken devices or testing on the simulator, but you'll have to use Xcode 7 (currently in beta by the time of this post) or later.
I successfully deployed an app to my iPhone without a developer account. You'll have to use your iCloud account to solve the provisioning profile issues. Just add your iCloud account and assign it in the Team dropdown (in the Identity menu) and the Fix Issue button should do the rest.
UPDATE:
Some people are having problems with iOS 8.4, here is how to fix it.
Anaconda is a very large installation ~ 2 GB and is most useful for those users who are not familiar with installing modules or packages with other package managers.
Anaconda seems to be promoting itself as the official package manager of Jupyter. It's not. Anaconda bundles Jupyter, R, python, and many packages with its installation.
Anaconda is not necessary for installing Jupyter Lab or the R kernel. There is plenty of information available elsewhere for installing Jupyter Lab or Notebooks. There is also plenty of information elsewhere for installing R studio. The following shows how to install the R kernel directly from R Studio:
To install the R kernel, without Anaconda, start R Studio. In the R terminal window enter these three commands:
install.packages("devtools")
devtools::install_github("IRkernel/IRkernel")
IRkernel::installspec()
Done. Next time Jupyter is opened, the R kernel will be available.
Most easiest way to do it as follow:
var elementPosition = $('#navigation').offset();
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('#navigation').css('position','fixed').css('top','0');
} else {
$('#navigation').css('position','static');
}
});
If highlighting is not working for large files, scalability mode has to be off. Properties / (c/c++) / Editor / Scalability
A quick search on the conda official docs will help you to find what each flag does.
So far:
-y
: Do not ask for confirmation.-f
: I think it should be --file
, so it read package versions from the given file.-q
: Do not display progress bar.-c
: Additional channel to search for packages. These are URLs searched in the orderroot folder changes for every directory os.walk finds. I solver that checking if root == directory
def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
if root == dir_name: #This only meet parent folder
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
Just try to without changing anything
npm install [email protected]
X.X.X is your current version
Use the Request.UrlReferrer
property.
Underneath the scenes it is just checking the ServerVariables("HTTP_REFERER")
property.
If I were confronted with extracting every 7th row I would “insert” a column before Column “A” . I would then (assuming that there is a header row in row 1) type in the numbers 1,2,3,4,5,6,7 in rows 2,3,4,5,6,7,8, I would highlight the 1,2,3,4,5,6,7 and paste that block to the end of the sheet (700 rows worth). The result will be 1,23,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7……. Now do a data sort ascending on column “A”. After the sort all of the 1’s will be the first in the series, all of the 7’s will be the seventh item.
small correction on @PetrosTsialiamanis post ,
new File( multipart.getOriginalFilename())
this will create file in server location where sometime you will face write permission issues for the user, its not always possible to give write permission to every user who perform action.
System.getProperty("java.io.tmpdir")
will create temp directory where your file will be created properly.
This way you are creating temp folder, where file gets created , later on you can delete file or temp folder.
public static File multipartToFile(MultipartFile multipart, String fileName) throws IllegalStateException, IOException {
File convFile = new File(System.getProperty("java.io.tmpdir")+"/"+fileName);
multipart.transferTo(convFile);
return convFile;
}
put this method in ur common utility and use it like for eg. Utility.multipartToFile(...)
Angular syntax is to use the : operator to perform the equivalent of an if modifier
<div ng-class="{ 'clearfix' : (row % 2) == 0 }">
Add clearfix class to even rows. Nonetheless, expression could be anything we can have in normal if condition and it should evaluate to either true or false.
This worked for me using GenyMotion 2.0.3 and VirtualBox 4.3.6. My problem was I have an existing host-only adaptor that is used by Vagrant. I can't simply delete it, it will trash my Vagrant VM.
Create a new host-only adaptor in the Virtual Box global settings.
Give it a separate address space from any existing host-only adaptors. For example, I set mine up as follows, where I also have a vboxnet0 (used by Vagrant) that uses 192.168.56.x
name: vboxnet1
IPV4 address: 192.168.57.1
mask: 255.255.255.0
DHCP:
address 192.168.57.100
mask: 255.255.255.0
low bounds: 192.168.57.101
high bound: 192.168.57.254
Then, edit your existing GenyMotion VM to use this host-only adaptor, and restart it from GenyMotion.
Good luck!
Swift 4 - GET request
var request = URLRequest(url: URL(string: "http://example.com/api/v1/example")!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
let jsonDecoder = JSONDecoder()
let responseModel = try jsonDecoder.decode(CustomDtoClass.self, from: data!)
print(responseModel)
} catch {
print("JSON Serialization error")
}
}).resume()
Don't forget to configure App Transport Security Settings to add your domain to the exceptions and allow insecure http requests if you're hitting endpoints without using HTTPS.
You can use a tool like http://www.json4swift.com/ to autogenerate your Codeable Mappings from your JSON responses.
You can do it in-place like so:
l = [1, 2, 3, 4, 5]
l[:] = [x * 5 for x in l]
This requires no additional imports and is very pythonic.
What worked for me was disabling the position: fixed;
CSS.
Your issue is in PHPMyAdmin itself. Some versions do not display the value of bit columns, even though you did set it correctly.
The order of execution of ng-click
and ng-model
is ambiguous since they do not define clear priorities. Instead you should use ng-change
or a $watch
on the $scope
to ensure that you obtain the correct values of the model variable.
In your case, this should work:
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
In my case the only solution was to add the reference to the System.Configuration
in my Test project as well.
Shape shape = new Shape();
Shape.ZShape zshape = shape.new ZShape();
I'm late but I need to say for those who need an object, using only html, there's a way. In some server side frameworks like PHP you can write the follow code:
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="name[first]" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="name[last]" id="lname"></p>
<input value="Submit" type="submit">
</form>
So, we need setup the name of the input as object[property]
for got an object. In the above example, we got a data with the follow JSON:
{
"name": {
"first": "some data",
"last": "some data"
}
}
Your elements need to have a position
attribute. (e.g. absolute
, relative
, fixed
) or z-index
won't work.
This looks like a missing SPN issue. The website you had pointed to has
principal="webserver/[email protected]"
This is the principal for which the ticket would be obtained. Did you change this to a value relative to your AD domain?
You could use the command line kerberos tools to test if you have the SPN defined:
[root@gen-cs218 bin]# kinit Administrator
[email protected]'s Password:
[root@gen-cs218 bin]# kgetcred host/[email protected]
[root@gen-cs218 bin]# klist
Credentials cache: FILE:/tmp/krb5cc_0
Principal: [email protected]
Issued Expires Principal <br>
Dec 15 11:42:34 2012 Dec 15 21:42:34 2012 krbtgt/[email protected]
Dec 15 11:42:48 2012 Dec 15 21:42:34 2012 host/[email protected]
Hostname based SPNs are pre-defined. If you want to use a SPN that is not pre-defined you will have to explicitly define it in AD using the setspn.exe tool and associate it with either a computer or an user account, for example:
c:\> setspn.exe -A "webserver/bully@MYDOMAIN" myuser
You can check which account a SPN is associated with by using the command below. This will not show pre-defined SPNs.
c:\> setspn.exe -L "webserver/bully@MYDOMAIN"
Here is the code to read the excel data by column.
public ArrayList<String> extractExcelContentByColumnIndex(int columnIndex){
ArrayList<String> columndata = null;
try {
File f = new File("sample.xlsx")
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){ //To filter column headings
if(cell.getColumnIndex() == columnIndex){// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(columndata);
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
the easiest way would be
which means you could just do:
new File(filename).text
Be careful when using the isa
function. This will be true if your object is of the specified type or one of its subclasses. You have to use strcmp
with the class
function to test if the object is specifically that type and not a subclass.
<img src="file://C:/wamp/www/site/img/mypicture.jpg"/>
Exclude specific pattern of file during creation of maven jar using maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3</version>
<configuration>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/*.exe</exclude>
<exclude>**/*.java</exclude>
<exclude>**/*.xls</exclude>
</excludes>
</configuration>
</plugin>
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
Something like:
SELECT id, email, IF(active = 1, 'enabled', 'disabled') AS account_status FROM users
This allows you to make operations and show it as columns.
EDIT:
you can also use joins and show operations as columns:
SELECT u.id, e.email, IF(c.id IS NULL, 'no selected', c.name) AS country
FROM users u LEFT JOIN countries c ON u.country_id = c.id
Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.
You should encode only the user name or other part of the URL that could be invalid. URL encoding a URL can lead to problems since something like this:
string url = HttpUtility.UrlEncode("http://www.google.com/search?q=Example");
Will yield
http%3a%2f%2fwww.google.com%2fsearch%3fq%3dExample
This is obviously not going to work well. Instead, you should encode ONLY the value of the key/value pair in the query string, like this:
string url = "http://www.google.com/search?q=" + HttpUtility.UrlEncode("Example");
Hopefully that helps. Also, as teedyay mentioned, you'll still need to make sure illegal file-name characters are removed or else the file system won't like the path.
You could use the XMLParser that I have been working on.
$xml = XMLParser::encode(array(
'bla' => 'blub',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
)
));
// @$xml instanceof SimpleXMLElement
echo $xml->asXML();
Would result in:
<?xml version="1.0"?>
<root>
<bla>blub</bla>
<foo>bar</foo>
<another_array>
<stack>overflow</stack>
</another_array>
</root>
The LogManager
class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:
log4j.defaultInitOverride
to false, it will not configure log4j at all.Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java
:
-Dlog4j.configuration=<path to properties file>
in your test runner configuration.
Allow log4j to scan the classpath for a log4j config file during your test. (the default)
See also the online documentation.
I find the fastest loop is a reverse while loop, e.g:
var i = myArray.length;
while(i--){
// Do something
}
Might help someone else : I encountered the same kind of issues while I had done some "copy-paste" from a side Microsoft Word document, where I took notes, to my shell script(s).
Re-writing, manually, the exact same code in the script just solved this.
It was quite un-understandable at first, I think Word's hidden characters and/or formatting were the issue. Obvious but not see-able ... I lost about one hour on this (I'm no shell expert, as you might guess ...)
If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.
Use decimal
. It doesn't have this "problem".
Give this a try
<style type="text/css">
form {width:400px;}
#text1 {float:right;}
#text2 {float:left;}
</style>
then
<form id="form1" name="form1" method="post" action="">
<label id="text1">Company Name<br />
<input type="text" name="textfield2" id="textfield2" />
</label>
<label id="text2">Contact Name<br />
<input type="text" name="textfield" id="textfield" />
</label>
</form>
Test Page: http://jsbin.com/ahelo4
Works for me in the latest versions of Firefox, Safari, Chrome, Opera. Not 100% sure about IE though as im on a Mac, but I cant see why it wouldn't :)
Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the question and it really isn't a good idea now. See this answer by hackbod for reasons:
Avoid reloading activity with asynctask on orientation change in android
Add android:configChanges="keyboardHidden|orientation"
to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.
<activity android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
See Developer reference configChanges for more details.
However, your application can be interrupted at any time, e.g. by a phone call, so you really should add code to save the state of your application when it is paused.
Update: As of Android 3.2, you also need to add "screenSize":
<activity
android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
From Developer guide Handling the Configuration Change Yourself
Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare
android:configChanges="orientation|screenSize"
. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
Assuming we're talking about internal integer types, there's no possible way one could be faster than the other. They're obviously semantically identical. They both ask the compiler to do precisely the same thing. Only a horribly broken compiler would generate inferior code for one of these.
If there was some platform where <
was faster than <=
for simple integer types, the compiler should always convert <=
to <
for constants. Any compiler that didn't would just be a bad compiler (for that platform).
Nvm. For anyone else having this problem you need to reboot your mac and press ?+R when booting up. Then go into Utilities > Terminal and type the following commands:
csrutil disable
reboot
This is a result of System Integrity Protection. More info here.
EDIT
If you know what you are doing and are used to running Linux, you should use the above solution as many of the SIP restrictions are a complete pain in the ass.
However, if you are a tinkerer/noob/"poweruser" and don't know what you are doing, this can be very dangerous and you are better off using the answer below.
Answering the additional question:
my following test code for typeid does not output the correct type name. what's wrong?
There isn't anything wrong. What you see is the string representation of the type name. The standard C++ doesn't force compilers to emit the exact name of the class, it is just up to the implementer(compiler vendor) to decide what is suitable. In short, the names are up to the compiler.
These are two different tools. typeof
returns the type of an expression, but it is not standard. In C++0x there is something called decltype
which does the same job AFAIK.
decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];
Whereas typeid
is used with polymorphic types. For example, lets say that cat
derives animal
:
animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
// the object is of type cat! but the pointer is base pointer.
}
Besides what Bert F said, many commands, including log
has the -r
(or --revision
) option. The following are some practical examples using this option to show ranges of revisions:
To list everything in ascending order:
svn log -r 1:HEAD
To list everything in descending order:
svn log -r HEAD:1
To list everything from the thirteenth to the base of the currently checked-out revision in ascending order:
svn log -r 13:BASE
To get everything between the given dates:
svn log -r {2011-02-02}:{2011-02-03}
You can combine all the above expressions with the --limit
option, so that can you have a quite granular control over what is printed. For more info about these -r
expressions refer to svn help log
or the relevant chapter in the book Version Control with Subversion