on CMD
type
ren *.* *.jpg
. will select all files, and rename to * (what ever name they have) plus extension to jpg
I think the basic problem is with "android:targetSdkVersion" which is defined in AndroidManifest.xml. In my case, the initial value which I have defined as:
android:targetSdkVersion=16
I changed it to:
android:targetSdkVersion=22
which resolved my all of the error. So, setting up the correct "targetSdkVersion" is also important before building an android app.
I had this issue with npm v1.1.4
(and node v0.6.12
), which are the Ubuntu 12.04
repository versions.
It looks like that version of npm
isn't supported any more, updating node (and npm with it) resolved the issue.
First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).
sudo apt-get purge nodejs npm
Then enable nodesource's repo and install:
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs
Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:
From: here
In my case, the issue was due to WAMP using a different php.ini for CLI than Apache, so your settings made through the WAMP menu don't apply to CLI. Just modify the CLI php.ini and it works.
For me cleaning the project (Command + Shift + K) and restarting xCode worked for me
This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.
change it to:
$(function () {
var specialElementHandlers = {
'#editor': function (element,renderer) {
return true;
}
};
$('#cmd').click(function () {
var doc = new jsPDF();
doc.fromHTML(
$('#target').html(), 15, 15,
{ 'width': 170, 'elementHandlers': specialElementHandlers },
function(){ doc.save('sample-file.pdf'); }
);
});
});
and it will work.
If you want to insert all the columns then
insert into def select * from abc;
here the number of columns in def should be equal to abc.
if you want to insert the subsets of columns then
insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc;
if you want to insert some hardcorded values then
insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;
I know this is an old question but...
import java.text.*;
public class FormatCurrency
{
public static void main(String[] args)
{
double price = 123.4567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(price));
}
}
I just thinking about the same problem, but I am using subquery in the FROM part. I need connect and query from large tables, the "slave" table have 28 million record but the result is only 128 so small result big data! I am using MAX() function on it.
First I am using LEFT JOIN because I think that is the correct way, the mysql can optimalize etc. Second time just for testing, I rewrite to sub-select against the JOIN.
LEFT JOIN runtime: 1.12s SUB-SELECT runtime: 0.06s
18 times faster the subselect than the join! Just in the chokito adv. The subselect looks terrible but the result ...
vertical-align
is only supposed to work on elements that are rendered as inline
. <span>
is rendered as inline by default, but not all elements are. The paragraph block element, <p>
, is rendered as a block by default. Table render types (e.g. table-cell
) will allow you to use vertical-align as well.
Some browsers may allow you to use the vertical-align
CSS property on items such as the paragraph block, but they are not supposed to. Text denoted as a paragraph should be filled with written-language content or the mark-up is incorrect and should be using one of a number of other options instead.
I hope this helps!
We can add the following to a particular tag in CSS:
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
In case of half rotation change 90
to 45
.
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
The --no-ff
option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff
.
If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.
For example, the author of this article thinks that --no-ff
option should be default and his reasoning is close to that I outlined above:
Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff
, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff
is not used], whereas it is easily done if the --no-ff
flag was used [because it's just one commit]."
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.
e.g.
var d = "";
var json = JSON.parse(d);
or if you are using AngularJS
var d = "";
var json = angular.fromJson(d);
In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.
Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.
for ANDROID , IPHONE, IPAD, BLACKBERRY, PALM, WINDOWS CE, PALM
<script language="javascript"> <!--
var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (mobile) {
alert("MOBILE DEVICE DETECTED");
document.write("<b>------------------------------------------<br>")
document.write("<b>" + navigator.userAgent + "<br>")
document.write("<b>------------------------------------------<br>")
var userAgent = navigator.userAgent.toLowerCase();
if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
document.write("<b> ANDROID MOBILE <br>")
else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
document.write("<b> ANDROID TABLET <br>")
else if ((userAgent.search("blackberry") > -1))
document.write("<b> BLACKBERRY DEVICE <br>")
else if ((userAgent.search("iphone") > -1))
document.write("<b> IPHONE DEVICE <br>")
else if ((userAgent.search("ipod") > -1))
document.write("<b> IPOD DEVICE <br>")
else if ((userAgent.search("ipad") > -1))
document.write("<b> IPAD DEVICE <br>")
else
document.write("<b> UNKNOWN DEVICE <br>")
}
else
alert("NO MOBILE DEVICE DETECTED"); //--> </script>
A solution is to create an Alias in your .gitconfig
and call it easily:
[alias]
tree = log --graph --decorate --pretty=oneline --abbrev-commit
And when you call it next time, you'll use:
git tree
To put it in your ~/.gitconfig without having to edit it, you can do:
git config --global alias.tree "log --graph --decorate --pretty=oneline --abbrev-commit"
(If you don't use the --global it will put it in the .git/config of your current repo.)
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
Unsigned variables can only be positive numbers, because they lack the ability to indicate that they are negative.
This ability is called the 'sign' or 'signing bit'.
A side effect is that without a signing bit, they have one more bit that can be used to represent the number, doubling the maximum number it can represent.
Use your jquery like this
$('.home').css({'background-image':'url(images/tabs3.png)'});
Note that this isn't perfect, since if you had something like, say, <a title=">">
it would break. However, it's about the closest you'd get in non-library Python without a really complex function:
import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
However, as lvc mentions xml.etree
is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml
version:
def remove_tags(text):
return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity
's fragments as you like using the FragmentTransaction
. Just make sure that your fragments can be identified either with an id or tag.
The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate()
. Instead, you should check if savedInstanceState
is not null and find the old references to the created fragments in this case.
Here is an example:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
myFragment = MyFragment.newInstance();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.my_container, myFragment, MY_FRAGMENT_TAG)
.commit();
} else {
myFragment = (MyFragment) getSupportFragmentManager()
.findFragmentByTag(MY_FRAGMENT_TAG);
}
...
}
Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.
A pointer-to-member allows you to write a single comparator, which can work with any data member of your class:
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
template <typename T, typename U>
struct CompareByMember {
// This is a pointer-to-member, it represents a member of class T
// The data member has type U
U T::*field;
CompareByMember(U T::*f) : field(f) {}
bool operator()(const T &lhs, const T &rhs) {
return lhs.*field < rhs.*field;
}
};
struct Test {
int a;
int b;
std::string c;
Test(int a, int b, std::string c) : a(a), b(b), c(c) {}
};
// for convenience, this just lets us print out a Test object
std::ostream &operator<<(std::ostream &o, const Test &t) {
return o << t.c;
}
int main() {
std::vector<Test> vec;
vec.push_back(Test(1, 10, "y"));
vec.push_back(Test(2, 9, "x"));
// sort on the string field
std::sort(vec.begin(), vec.end(),
CompareByMember<Test,std::string>(&Test::c));
std::cout << "sorted by string field, c: ";
std::cout << vec[0] << " " << vec[1] << "\n";
// sort on the first integer field
std::sort(vec.begin(), vec.end(),
CompareByMember<Test,int>(&Test::a));
std::cout << "sorted by integer field, a: ";
std::cout << vec[0] << " " << vec[1] << "\n";
// sort on the second integer field
std::sort(vec.begin(), vec.end(),
CompareByMember<Test,int>(&Test::b));
std::cout << "sorted by integer field, b: ";
std::cout << vec[0] << " " << vec[1] << "\n";
}
Output:
sorted by string field, c: x y
sorted by integer field, a: y x
sorted by integer field, b: x y
If someone is interested in the similar problem, but is not working with XAML, here's my solution:
var B1 = new Border();
B1.BorderBrush = Brushes.Black;
B1.BorderThickness = new Thickness(0, 1, 0, 0); // You can specify here which borders do you want
YourPanel.Children.Add(B1);
The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either "State Server Mode" or "SQL Server Mode"). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.
Using CSS you can do it if you add the following style to a tag, but you will need a wav
file:
<style type="text/css">
.beep {cue: url("beep.wav") }
</style>
var body=document.getElementByTagName("body");
body.className=body.className + " " + "beep";
James Gosling created the original JVM with support of goto
statements, but then he removed this feature as needless. The main reason goto
is unnecessary is that usually it can be replaced with more readable statements (like break/continue
) or by extracting a piece of code into a method.
Source: James Gosling, Q&A session
This is a very common question seen on Stackoverflow.
The important part here is not the command displayed in the error, but what the actual error tells you instead.
a Quick breakdown on why this error is received.
cmd.exe
Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.
How do I fix this:
When Actual Command/executable fails
First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.
If you have any executable which you are attempting to run from cmd.exe
then you need to tell cmd.exe
where this file is located. There are 2 ways of doing this.
specify the full path to the file.
"C:\My_Files\mycommand.exe"
Add the location of the file to your environment Variables.
Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables
In the System Variables
Window, locate path
and select edit
Now simply add your path to the end of the string, seperated by a semicolon ;
as:
;C:\My_Files\
Save the changes and exit. You need to make sure that ANY cmd.exe
windows you had open are then closed and re-opened to allow it to re-import the environment variables.
Now you should be able to run mycommand.exe from any path, within cmd.exe
as the environment is aware of the path to it.
When C:\Program
or Similar fails
This is a very simple error. Each string after a white space is seen as a different command in cmd.exe
terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe
to see it as a single string, and not separate commands.
So to execute C:\Program Files\My-App\Mobile.exe
simply run as:
"C:\Program Files\My-App\Mobile.exe"
I tried this in my Angular project and it worked fine without jQuery.
<input type='text' ng-paste='preventPaste($event)'>
And in script part:
$scope.preventPaste = function(e){
e.preventDefault();
return false;
};
In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instesd of '$event'.
This is rather verbose and don't like it but it's the only thing that worked for me:
if (inputFile && inputFile.current) {
((inputFile.current as never) as HTMLInputElement).click()
}
only
if (inputFile && inputFile.current) {
inputFile.current.click() // also with ! or ? didn't work
}
didn't work for me. Typesript version: 3.9.7 with eslint and recommended rules.
I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.
this is a generic example let me know if this explains the point i mentioned
CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
empName VARCHAR2(50);
empSalary NUMBER(7,2);
BEGIN
UPDATE emp
SET sal = sal + 1000
WHERE empno = 7499
RETURNING ename, sal
INTO empName, empSalary;
DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;
For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.
Removing the styles of next siblings on hover, so that it looks like only previous siblings have styles added on hover.
ul li {
color: red;
cursor: pointer;
}
ul:hover li {
color: blue;
}
ul:hover li:hover ~ li{
color: red;
}
_x000D_
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
_x000D_
Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)
Permanent:
UPDATE
MyTable
SET
MyColumn = UPPER(MyColumn)
Temporary:
SELECT
UPPER(MyColumn) AS MyColumn
FROM
MyTable
This is what I've done to automatically add my local project node_modules/.bin
path to PATH
. In ~/.profile
I added:
if [ -d "$PWD/node_modules/.bin" ]; then
PATH="$PWD/node_modules/.bin"
fi
Then reload your bash profile: source ~/.profile
I removed android platforms and installed again then worked. I wrote these lines in command window:
cordova platform remove android
then
cordova platform add android
just use a regex as a separator:
', *' - for leading spaces
' *,' - for trailing spaces
for both leading and trailing:
awk -F' *,? *' '{print $1","$2}' input.txt
You cannot use percentages to define the dimensions of a View inside a RelativeLayout. The best ways to do it is to use LinearLayout and weights, or a custom Layout.
You use it like this:
SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name
Use UNION ALL
to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION
.
I have a simpler and elegant solution that doesn't mess up with classes, styles, opacities and stuff.
For the draggable element - you add 'start' event which will execute every time you try to move the element somewhere. You will have a condition which move is not legal. For the moves that are illegal - prevent them with 'e.preventDefault();' like in the code below.
$(".disc").draggable({
revert: "invalid",
cursor: "move",
start: function(e, ui){
console.log("element is moving");
if(SOME_CONDITION_FOR_ILLEGAL_MOVE){
console.log("illegal move");
//This will prevent moving the element from it's position
e.preventDefault();
}
}
});
You are welcome :)
For a similar challenge, I really enjoyed this gist which exposes a polyfill for scrollIntoViewIfNeeded().
All the necessary Kung Fu needed to answer is within this block:
var parent = this.parentNode,
parentComputedStyle = window.getComputedStyle(parent, null),
parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width')),
parentBorderLeftWidth = parseInt(parentComputedStyle.getPropertyValue('border-left-width')),
overTop = this.offsetTop - parent.offsetTop < parent.scrollTop,
overBottom = (this.offsetTop - parent.offsetTop + this.clientHeight - parentBorderTopWidth) > (parent.scrollTop + parent.clientHeight),
overLeft = this.offsetLeft - parent.offsetLeft < parent.scrollLeft,
overRight = (this.offsetLeft - parent.offsetLeft + this.clientWidth - parentBorderLeftWidth) > (parent.scrollLeft + parent.clientWidth),
alignWithTop = overTop && !overBottom;
this
refers to the element that you want to know if it is, for example, overTop
or overBottom
- you just should get the drift...
You could also consider using preparedStatement.setObject(index,value,type);
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.
It is working. I just added square brackets to JSON data. The data is:
var data = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}
]
And the loop is:
for (var key in data) {
if (data.hasOwnProperty(key)) {
alert(data[key].id);
}
}
Not as a command, but this information is in the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion
REG_SZJava Runtime Environment
named with the CurrentVersion
valueJavaHome
REG_SZ to get the pathFor example on my workstation i have
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
JavaHome = "C:\Program Files\Java\jre6"
So my current JRE is in C:\Program Files\Java\jre6
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs. For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
public class MyObj {
private List<Interest> interests;
static final class Interest {
private String interestKey;
}
private static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue("{\"interests\": [{\"interestKey\": \"Dogs\"}, {\"interestKey\": \"Cats\" }]}", MyObj.class);
}
}
Let me know if you have any questions.
If you read error message, "icuuc36.dll" is missing. The problem is that you don't have the PHP dir in your PATH, or you can copy all "intl" files from php directory to apache\bin directory. They are : icudt36.dll icuin36.dll icuio36.dll icule36.dll iculx36.dll icutu36.dll icuuc36.dll
What helped in my case was dropping the audio track. It was silent before, but it had to be gone completely.
On ubuntu:
ffmpeg -i input.mp4 -vcodec copy -an output.mp4
And safari/desktop start to play the video
try this:
import time
import os
n = 0
for x in range(10): #enter your value here
print(n)
time.sleep(1) #to wait a second
os.system('cls') #to clear previous number
#use ('clear') if you are using linux or mac!
n = n + 1
So left div style depends on the presence of right div. I can't think of a CSS selector allowing that kind of behavior yet.
Thus it seems to me that you'll need to programmatically add a class server side (or in JS) on parent div or left div to do that.
<div id="parent twocols">
<div class="left"></div>
<div class="right"></div>
</div>
or
<div id="parent">
<div class="left"></div>
</div>
So right style is always :
.right {
float: right;
width: 200px; /* or whatever value you need */
/* margin and padding at your discretion */
}
and left style is :
.parent.twocols .left {
margin-right: 200px; /* according to right div width + margin + padding*/
}
for me following line is working for me , I put it in the css of my body ( where image is in same folder in which my css and .html files ) :
background: url('test.jpg');
Other thing that you must care about is , be careful about image extension , be sure that your image has .jpeg or .jpg extension. Thanks
<input type="text" value="3" class="field left" readonly>
No styling necessary.
See <input>
on MDN https://developer.mozilla.org/en/docs/Web/HTML/Element/input#Attributes
In Oracle you can do this:
SELECT * FROM table1 WHERE (col_a,col_b) IN (SELECT col_x,col_y FROM table2)
Quick solution to serialize a form without any libraries
function serializeIt(form) {_x000D_
return (_x000D_
Array.apply(0, form.elements).map(x => _x000D_
(_x000D_
(obj => _x000D_
(_x000D_
x.type == "radio" ||_x000D_
x.type == "checkbox"_x000D_
) ?_x000D_
x.checked ? _x000D_
obj_x000D_
: _x000D_
null_x000D_
:_x000D_
obj_x000D_
)(_x000D_
{_x000D_
[x.name]:x.value_x000D_
}_x000D_
)_x000D_
)_x000D_
).filter(x => x)_x000D_
);_x000D_
}_x000D_
_x000D_
function whenSubmitted(e) {_x000D_
e.preventDefault()_x000D_
console.log(_x000D_
JSON.stringify(_x000D_
serializeIt(document.forms[0]),_x000D_
4, 4, 4_x000D_
)_x000D_
)_x000D_
}
_x000D_
<form onsubmit="whenSubmitted(event)">_x000D_
<input type=text name=hiThere value=nothing>_x000D_
<input type=radio name=okRadioHere value=nothin>_x000D_
<input type=radio name=okRadioHere1 value=nothinElse>_x000D_
<input type=radio name=okRadioHere2 value=nothinStill>_x000D_
_x000D_
<input type=checkbox name=justAcheckBox value=checkin>_x000D_
<input type=checkbox name=justAcheckBox1 value=checkin1>_x000D_
<input type=checkbox name=justAcheckBox2 value=checkin2>_x000D_
_x000D_
<select name=selectingSomething>_x000D_
<option value="hiThere">Hi</option>_x000D_
<option value="hiThere1">Hi1</option>_x000D_
<option value="hiThere2">Hi2</option>_x000D_
<option value="hiThere3">Hi3</option>_x000D_
</select>_x000D_
<input type=submit value="click me!" name=subd>_x000D_
</form>
_x000D_
To summarize, for me following the two instructions above to change any instances where numberOfLines = 0 to 1 or greater, and manually adding preferredMaxLayoutWidth="0" to each instance of a label inside the storyboard source fixed all of my warnings.
I have one generic log4j.xml file for you:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">
<appender name="default.console" class="org.apache.log4j.ConsoleAppender">
<param name="target" value="System.out" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="default.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/mylogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="another.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/anotherlogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<logger name="com.yourcompany.SomeClass" additivity="false">
<level value="debug" />
<appender-ref ref="another.file" />
</logger>
<root>
<priority value="info" />
<appender-ref ref="default.console" />
<appender-ref ref="default.file" />
</root>
</log4j:configuration>
with one console, two file appender and one logger poiting to the second file appender instead of the first.
EDIT
In one of the older projects I have found a simple log4j.properties file:
# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.
# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file
# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n
log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n
For the description of all the layout arguments look here: log4j PatternLayout arguments
If the true intent of the question is the comparison between dicts (rather than printing differences), the answer is
dict1 == dict2
This has been mentioned before, but I felt it was slightly drowning in other bits of information. It might appear superficial, but the value comparison of dicts has actually powerful semantics. It covers
The last point again appears trivial, but is acutally interesting as it means that all of this applies recursively to nested dicts as well. E.g.
m1 = {'f':True}
m2 = {'f':True}
m3 = {'a':1, 2:2, 3:m1}
m4 = {'a':1, 2:2, 3:m2}
m3 == m4 # True
Similar semantics exist for the comparison of lists. All of this makes it a no-brainer to e.g. compare deep Json structures, alone with a simple "==".
// check whether date is valid
var t = new Date('2011-07-07T11:20:00.000+00:00x');
valid = !isNaN(t.valueOf());
I have query,
$("#login-button").click(function(e){ alert("hiii");
var username = $("#username-field").val();
var password = $("#username-field").val();
alert(username);
alert("password" + password);
var markers = { "userName" : "admin","password" : "admin123"};
$.ajax({
type: "POST",
url: url,
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify(markers),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert("got the data"+data);},
failure: function(errMsg) {
alert(errMsg);
}
});
});
I'm posting the the login details in json and getting a string as "Success"
,but I'm not getting the response.
You can do this:
a = np.array([])
for x in y:
a = np.append(a, x)
A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:
select * from FN('myFunc')
Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore
Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore
In this example, nothing really. The exact
param comes into play when you have multiple paths that have similar names:
For example, imagine we had a Users
component that displayed a list of users. We also have a CreateUser
component that is used to create users. The url for CreateUsers
should be nested under Users
. So our setup could look something like this:
<Switch>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
Now the problem here, when we go to http://app.com/users
the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users
route first and then return it. All good.
But, if we went to http://app.com/users/create
, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users
partially matches /users/create
, so it would incorrectly return the Users
route again!
The exact
param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.
So in this case, we should add exact
to our Users
route so that it will only match on /users
:
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
Try This:
int positionOfJPG=url.IndexOf(".jpg");
string newString = url.Substring(18, url.Length - positionOfJPG);
To answer your questions.
You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)
You are trying to run a Python 2 codebase with Python 3. xrange()
was renamed to range()
in Python 3.
Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond xrange()
vs. range()
.
For the record, what you are seeing is not a syntax error but a runtime exception instead.
If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range
. (Take into account that you may have to update any existing range()
use in the Python 2 codebase with list(range(...))
to ensure you still get a list object in Python 3):
try:
# Python 2
xrange
except NameError:
# Python 3, xrange is now named range
xrange = range
# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))
or replace all uses of xrange(...)
with range(...)
in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:
try:
# Python 2 forward compatibility
range = xrange
except NameError:
pass
# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).
The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.
Much simpler solution:
Get-PSDrive C | Select-Object Used,Free
and for remote computers (needs Powershell Remoting
)
Invoke-Command -ComputerName SRV2 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
Git- Git is a version control software that you install on your local system. For an individual working on a project alone, Git proves to be excellent software.
GitHub- As mentioned earlier, Git is a version control system that tracks code changes, while GitHub is a web-based Git version control repository hosting service. It provides all of the distributed version control and source code management (SCM) functionalities of Git while topping it with a few of its own features.
I also got same problem while generating signed APK. Just select APK signature scheme v1, not v2 (introduced in in Android 7.0). If you select v2 scheme it won't work on devices that use Android versions older than 7.0.
We are following the below steps in our project for debugging a website on mobile.
Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:
For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.
Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)
import os
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
self.var1 = os.environ["VAR1"]
self.var2 = os.environ["VAR2"]
def test_01(self):
print("var1: {}, var2: {}".format(self.var1, self.var2))
Then from the command line (tested on Linux)
$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
var isAlaCarte =
ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") &&
bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));
Give name and values to those submit buttons like:
<td>
<input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
</td>
<td>
<input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
</td>
and then in your php script you could check
if($_POST['mybutton'] == 'save')
{
///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
///do publish processing here
}
I know Gmail already fix all the problem above, the alt and stuff now.
And this is unrelated to the question but probably someone experiences the same as me.
So my web designer use "image" tag instead of "img", but the symptom was the same. It works on outlook but not Gmail.
It takes me an hour to realize. Sigh, such a waste of time.
So make sure the tag is "img" not "image" as well.
This is very late but i like to share my experience this same issue. i face the same issue in Android studio i tried to some other solution that i found in internet but nothing works for me unless i REBUILD THE PROJECT and it solve my issue.
Hope this will works for you too.
Happy coding.
This is a code snippet to retrieve the path of the current running web application project in java.
public String getPath() throws UnsupportedEncodingException {
String path = this.getClass().getClassLoader().getResource("").getPath();
String fullPath = URLDecoder.decode(path, "UTF-8");
String pathArr[] = fullPath.split("/WEB-INF/classes/");
System.out.println(fullPath);
System.out.println(pathArr[0]);
fullPath = pathArr[0];
return fullPath;
}
Source: https://dzone.com/articles/get-current-web-application
Generally, you would not include the comma after the final entry, but Python will correct that for you.
\xe2 is the '-' character, it appears in some copy and paste it uses a different equal looking '-' that causes encoding errors. Replace the '-'(from copy paste) with the correct '-' (from you keyboard button).
In Swift 2:
extension NSMutableURLRequest {
func setAuthorizationHeader(username username: String, password: String) -> Bool {
guard let data = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return false }
let base64 = data.base64EncodedStringWithOptions([])
setValue("Basic \(base64)", forHTTPHeaderField: "Authorization")
return true
}
}
If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon
Use a white space to match all descendants of an element:
div.dropdown * {
color: red;
}
x y
matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.
The asterisk *
matches any element.
Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
That's because although a Customer is an Object, a List of Customers is not a List of Objects. If it was, then you could put any object in a list of Customers.
A pure RESTful API should use the underlying protocol standard features:
For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.
RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.
Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.
I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.
I would recommend having a look at the plyr
package.
It might not be as fast as data.table or other packages, but it is quite instructive, especially when starting with R and having to do some data manipulation.
> DF <- data.frame(A = c("1", "1", "2", "3", "3"), B = c(2, 3, 3, 5, 6))
> library(plyr)
> DF.sum <- ddply(DF, c("A"), summarize, B = sum(B))
> DF.sum
A B
1 1 5
2 2 3
3 3 11
None of the other solution worked for me.
Even if I don't think its the best practice, I Had to add it into the code like this
configuration.addAnnotatedClass(com.myOrg.entities.Person.class);
here
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(com.myOrg.entities.Person.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:
import {Component, OnInit, NgZone} from 'angular2/core';
export class RecentDetectionComponent implements OnInit {
recentDetections: Array<RecentDetection>;
constructor(private zone:NgZone, // <== added
private recentDetectionService: RecentDetectionService) {
this.recentDetections = new Array<RecentDetection>();
}
getRecentDetections(): void {
this.recentDetectionService.getJsonFromApi()
.subscribe(recent => {
this.zone.run(() => { // <== added
this.recentDetections = recent;
console.log(this.recentDetections[0].macAddress)
});
});
}
ngOnInit() {
this.getRecentDetections();
let timer = Observable.timer(2000, 5000);
timer.subscribe(() => this.getRecentDetections());
}
}
For other ways to invoke change detection see Triggering change detection manually in Angular
Alternative ways to invoke change detection are
ChangeDetectorRef.detectChanges()
to immediately run change detection for the current component and its children
ChangeDetectorRef.markForCheck()
to include the current component the next time Angular runs change detection
ApplicationRef.tick()
to run change detection for the whole application
You can use * operator to unpack dict_values:
>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']
or list object
>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
For those that can accidentally add pdb into live commits, I can suggest this extension of #Koobz answer:
@register.filter
def pdb(element):
from django.conf import settings
if settings.DEBUG:
import pdb
pdb.set_trace()
return element
this work for me:-
String[] array = {"A", "B", "C"};
String abc = "";
Spinner spinner = new Spinner(getContext());
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
I am using a Fragment.
The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.
SO uses a hidden field for the upvote click.
<input value="16293741" name="postId" type="hidden">
Using this value, the server-side script can store the upvote.
I see some people prefer to generate sources into the target via jaxws-maven-plugin AND make this classes visible in source via build-helper-maven-plugin. As an argument for this structure
the version management system (svn/etc.) would always notice changed sources
With git it is not true. So you can just configure jaxws-maven-plugin
to put them into your sources, but not under the target folder. Next time you build your project, git will not mark these generated files as changed. Here is the simple solution with only one plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.6</version>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<packageName>som.path.generated</packageName>
<xjcArgs>
<xjcArg>-Xfluent-api</xjcArg>
</xjcArgs>
<verbose>true</verbose>
<keep>true</keep> <!--used by default-->
<sourceDestDir>${project.build.sourceDirectory}</sourceDestDir>
<wsdlDirectory>src/main/resources/META-INF/wsdl</wsdlDirectory>
<wsdlLocation>META-INF/wsdl/soap.wsdl</wsdlLocation>
</configuration>
</execution>
</executions>
</plugin>
Additionally (just to note) in this example SOAP classes are generated with Fluent API, so you can create them like:
A a = new A()
.withField1(value1)
.withField2(value2);
If you are using bootstrap 3, use tag, like this <small><span class="glyphicon glyphicon-send"></span></small>
It works perfect for Bootstrap 3.
You can even use multiple <small>
tags to set the size more smaller.
Code:
<small><small><span class="glyphicon glyphicon-send"></span></small></small>
Keep in mind that international users may be using a decimal separator other than .
in which case values can get mixed up or just become nil when using intValue
on a string.
For example, in the UK 1.23
is written 1,23
, so the number 1.777
would be input by user as 1,777
, which, as .intValue
, will be 1777
not 1
(truncated).
I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).
#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)
It could be that you have your own MSBUILD proj file and are using the <AspNetCompiler>
task. In which case you should add the ToolPath
for .NET4.
<AspNetCompiler
VirtualPath="/MyFacade"
PhysicalPath="$(MSBuildProjectDirectory)\MyFacade\"
TargetPath="$(MSBuildProjectDirectory)\Release\MyFacade"
Updateable="true"
Force="true"
Debug="false"
Clean="true"
ToolPath="C:\Windows\Microsoft.NET\Framework\v4.0.30319\">
</AspNetCompiler>
Depending on your definition of "special character", I think "[^a-zA-Z0-9]" would probably do the trick. That would find anything that is not a small letter, a capital letter, or a digit.
An update to @sourcesimian 's and @kunal-b's answer which dynamically sets the username and password if configured in the system properties.
The following sets the username and password if provided or just adds the host and port if no username and password is set.
task setHttpProxyFromEnv {
def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
for (e in System.getenv()) {
def key = e.key.toUpperCase()
if (key in map) {
def base = map[key]
//Get proxyHost,port, username, and password from http system properties
// in the format http://username:password@proxyhost:proxyport
def (val1,val2) = e.value.tokenize( '@' )
def (val3,val4) = val1.tokenize( '//' )
def(userName, password) = val4.tokenize(':')
def url = e.value.toURL()
//println " - systemProp.${base}.proxy=${url.host}:${url.port}"
System.setProperty("${base}.proxyHost", url.host.toString())
System.setProperty("${base}.proxyPort", url.port.toString())
System.setProperty("${base}.proxyUser", userName.toString())
System.setProperty("${base}.proxyPassword", password.toString())
}
}
}
There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as jq
:
curl -s 'https://api.github.com/users/lambda' | jq -r '.name'
You can also do this with tools that are likely already installed on your system, like Python using the json
module, and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:
Python 3:
curl -s 'https://api.github.com/users/lambda' | \
python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"
Python 2:
export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' | \
python2 -c "import sys, json; print json.load(sys.stdin)['name']"
The standard POSIX/Single Unix Specification shell is a very limited language which doesn't contain facilities for representing sequences (list or arrays) or associative arrays (also known as hash tables, maps, dicts, or objects in some other languages). This makes representing the result of parsing JSON somewhat tricky in portable shell scripts. There are somewhat hacky ways to do it, but many of them can break if keys or values contain certain special characters.
Bash 4 and later, zsh, and ksh have support for arrays and associative arrays, but these shells are not universally available (macOS stopped updating Bash at Bash 3, due to a change from GPLv2 to GPLv3, while many Linux systems don't have zsh installed out of the box). It's possible that you could write a script that would work in either Bash 4 or zsh, one of which is available on most macOS, Linux, and BSD systems these days, but it would be tough to write a shebang line that worked for such a polyglot script.
Finally, writing a full fledged JSON parser in shell would be a significant enough enough dependency that you might as well just use an existing dependency like jq or Python instead. It's not going to be a one-liner, or even small five-line snippet, to do a good implementation.
It is possible to use these tools to do some quick extraction from JSON with a known shape and formatted in a known way, such as one key per line. There are several examples of suggestions for this in other answers.
However, these tools are designed for line based or record based formats; they are not designed for recursive parsing of matched delimiters with possible escape characters.
So these quick and dirty solutions using awk/sed/grep are likely to be fragile, and break if some aspect of the input format changes, such as collapsing whitespace, or adding additional levels of nesting to the JSON objects, or an escaped quote within a string. A solution that is robust enough to handle all JSON input without breaking will also be fairly large and complex, and so not too much different than adding another dependency on jq
or Python.
I have had to deal with large amounts of customer data being deleted due to poor input parsing in a shell script before, so I never recommend quick and dirty methods that may be fragile in this way. If you're doing some one-off processing, see the other answers for suggestions, but I still highly recommend just using an existing tested JSON parser.
This answer originally recommended jsawk, which should still work, but is a little more cumbersome to use than jq
, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:
curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name'
This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys. The first answer for the original question would be:
curl 'http://twitter.com/users/username.json' | jq -r '.text'
i also had the same problem in one of my project. I resolved it by adding some following parameters in the theme provided to the splash screen.
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsTranslucent">true</item>
You can find the reason and resolution in this blog post written by me. Hope it helps.
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
def dbz():
try:
r = raw_input("Enter number:")
if r.isdigit():
i = int(raw_input("Enter divident:"))
d = int(r)/i
print "O/p is -:",d
else:
print "Not a number"
except Exception ,e:
print "Program halted incorrect data entered",type(e)
dbz()
Or
num = input("Enter Number:")#"input" will accept only numbers
"Unicode" is unfortunately used in various different ways, depending on the context. Its most correct use (IMO) is as a coded character set - i.e. a set of characters and a mapping between the characters and integer code points representing them.
UTF-8 is a character encoding - a way of converting from sequences of bytes to sequences of characters and vice versa. It covers the whole of the Unicode character set. ASCII is encoded as a single byte per character, and other characters take more bytes depending on their exact code point (up to 4 bytes for all currently defined code points, i.e. up to U-0010FFFF, and indeed 4 bytes could cope with up to U-001FFFFF).
When "Unicode" is used as the name of a character encoding (e.g. as the .NET Encoding.Unicode property) it usually means UTF-16, which encodes most common characters as two bytes. Some platforms (notably .NET and Java) use UTF-16 as their "native" character encoding. This leads to hairy problems if you need to worry about characters which can't be encoded in a single UTF-16 value (they're encoded as "surrogate pairs") - but most developers never worry about this, IME.
Some references on Unicode:
Not exactly the same as NUnit's Value
(or TestCase
) attributes, but MSTest has the DataSource
attribute, which allows you to do a similar thing.
You can hook it up to database or XML file - it is not as straightforward as NUnit's feature, but it does the job.
Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :
-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440
<?php
$link = mysqli_connect('localhost','root','');
if (!$link) {
die('Could not connect to MySQL: ' . mysqli_error());
}
echo 'Connection OK'; mysqli_close($link);
?>
This will solve your problem.
I ran into this using networkx
and bokeh
This works for me in Windows 7 (taken from here):
To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:
$ jupyter notebook --generate-config
Open the file and search for c.NotebookApp.iopub_data_rate_limit
Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000
and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000
This unforgiving default config is popping up in a lot of places. See git issues:
It looks like it might get resolved with the 5.1 release
Jupyter notebook is now on release 5.2.2
. This problem should have been resolved. Upgrade using conda or pip.
Marquee (<marquee>
) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!
One line is enough:
var x = '|f|oo||';
var y = x.replace(/^\|+|\|+$/g, '');
document.write(x + '<br />' + y);
_x000D_
^\|+ beginning of the string, pipe, one or more times
| or
\|+$ pipe, one or more times, end of the string
A general solution:
function trim (s, c) {
if (c === "]") c = "\\]";
if (c === "\\") c = "\\\\";
return s.replace(new RegExp(
"^[" + c + "]+|[" + c + "]+$", "g"
), "");
}
chars = ".|]\\";
for (c of chars) {
s = c + "foo" + c + c + "oo" + c + c + c;
console.log(s, "->", trim(s, c));
}
_x000D_
There is a big difference if you are using jQuery. jQuery is aware of more events on inputs than it does on buttons. On buttons, jQuery is only aware of 'click' events. On inputs, jQuery is aware of 'click', 'focus', and 'blur' events.
You could always bind events to your buttons as needed, but just be aware that the events that jQuery automatically is aware of are different. For example, if you created a function that was executed whenever there was a 'focusin' event on your page, an input would trigger the function but a button would not.
Try opening Port 3306, and using that in the connection string not 8080.
since async ajax is deprecated try using nested async functions with a Promise. There may be syntax errors.
async function fetch_my_data(_url, _dat) {
async function promised_fetch(_url, _dat) {
return new Promise((resolve, reject) => {
$.ajax({
url: _url,
data: _dat,
type: 'POST',
success: (response) => {
resolve(JSON.parse(response));
},
error: (response) => {
reject(response);
}
});
});
}
var _data = await promised_fetch(_url, _dat);
return _data;
}
var _my_data = fetch_my_data('server.php', 'get_my_data=1');
[this is a helpful link on multer github][1]
but for me i have to create a public folder in the server folder also its like -cb(null,'public/'). [1]: https://github.com/expressjs/multer/issues/513
If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):
String uri = request.getRequestURI();
String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());
if(redirectMap.containsKey(path)) {
response.sendRedirect(redirectMap.get(path) + rest);
} else {
chain.doFilter(request, response);
}
One time, after a power outage, I had to face the same slowness problem each time a breakpoint was hit or a Exception was thrown.
I had the vague remembering that the "suo" file (in the same directory as the "sln" solution file) can be corrupted and make everything slow down.
I deleted my "suo" files and everything was ok. The .suo files deletion is harmless and only implies to recreate my windows layout plus the starting project and a few other non critical customizations.
<asp:GridView ID="gv_Document" CssClass="gridstyle" runat="server" OnRowDataBound="gv_Document_RowDataBound" AutoGenerateColumns="false" DataKeyNames="SourceGUID,Source,FilePath" ShowHeaderWhenEmpty="false" OnRowDeleting="gv_Document_RowDeleting">
<Columns>
<asp:BoundField HeaderText="ItemID" DataField="ItemID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:BoundField HeaderText="SourceGUID" DataField="SourceGUID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:BoundField HeaderText="Source" DataField="Source" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:HyperLink ID="hyperLink" runat="server" Target="_blank" NavigateUrl='<%# Bind("FilePath")%>'
Text='<%# Bind("FileName")%>'> </asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Type" DataField="FileExtension" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:BoundField HeaderText="Content type" DataField="FileMimeType" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:BoundField HeaderText="File Path" DataField="FilePath" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:CommandField ShowDeleteButton="True" DeleteText="Delete" />
</Columns>
Use this code to disable delete button in gridview from code behind.
protected void gv_Document_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.Cells[7].Controls[0]).Visible = false;
}
}
angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs
In your case you need to find a div with ID or class name. for class name you can use
var elems =$element.find('div') //returns all the div's in the $elements
angular.forEach(elems,function(v,k)){
if(angular.element(v).hasClass('class-name')){
console.log(angular.element(v));
}}
or you can use much simpler way by query selector
angular.element(document.querySelector('#id'))
angular.element(elem.querySelector('.classname'))
it is not as flexible as jQuery but what
You can use display:inline-block
with white-space:nowrap
. Write like this:
.scrolls {
overflow-x: scroll;
overflow-y: hidden;
height: 80px;
white-space:nowrap
}
.imageDiv img {
box-shadow: 1px 1px 10px #999;
margin: 2px;
max-height: 50px;
cursor: pointer;
display:inline-block;
*display:inline;/* For IE7*/
*zoom:1;/* For IE7*/
vertical-align:top;
}
Check this http://jsfiddle.net/YbrX3/
Sleep causes thread to suspend itself for x milliseconds while yield suspends the thread and immediately moves it to the ready queue (the queue which the CPU uses to run threads).
I think DATETIME2
is the better way to store the date
, because it has more efficiency than
the DATETIME
. In SQL Server 2008
you can use DATETIME2
, it stores a date and time, takes 6-8 bytes
to store and has a precision of 100 nanoseconds
. So anyone who needs greater time precision will want DATETIME2
.
Any changes you commit, like deleting all your project files, will still be in place after a pull. All a pull does is merge the latest changes from somewhere else into your own branch, and if your branch has deleted everything, then at best you'll get merge conflicts when upstream changes affect files you've deleted. So, in short, yes everything is up to date.
If you describe what outcome you'd like to have instead of "all files deleted", maybe someone can suggest an appropriate course of action.
Update:
GET THE MOST RECENT OF THE CODE ON MY SYSTEM
What you don't seem to understand is that you already have the most recent code, which is yours. If what you really want is to see the most recent of someone else's work that's on the master branch, just do:
git fetch upstream
git checkout upstream/master
Note that this won't leave you in a position to immediately (re)start your own work. If you need to know how to undo something you've done or otherwise revert changes you or someone else have made, then please provide details. Also, consider reading up on what version control is for, since you seem to misunderstand its basic purpose.
Here is a solution using strings and converting it to decimal with ASCII tables:
#include <iostream>
#include <string>
#include "math.h"
using namespace std;
unsigned long hex2dec(string hex)
{
unsigned long result = 0;
for (int i=0; i<hex.length(); i++) {
if (hex[i]>=48 && hex[i]<=57)
{
result += (hex[i]-48)*pow(16,hex.length()-i-1);
} else if (hex[i]>=65 && hex[i]<=70) {
result += (hex[i]-55)*pow(16,hex.length( )-i-1);
} else if (hex[i]>=97 && hex[i]<=102) {
result += (hex[i]-87)*pow(16,hex.length()-i-1);
}
}
return result;
}
int main(int argc, const char * argv[]) {
string hex_str;
cin >> hex_str;
cout << hex2dec(hex_str) << endl;
return 0;
}
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
Assuming you are already in the directory, and that the "first 8 characters" from your comment hold true always. (Although "CHEESE_" is 7 characters... ? If so, change the 8 below to 7)
from glob import glob
from os import rename
for fname in glob('*.prj'):
rename(fname, fname[8:])
It is
android.R.drawable.expander_ic_minimized
look into built in android drawables:
You cannot have snapshot isolation and blocking reads at the same time. The purpose of snapshot isolation is to prevent blocking reads.
I had the same issue and resolved by adding "Connection Time" value in web.config file. locate the connectionStrings and add Connection Timeout=3600"
here is the sample
<connectionStrings>
<add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
</connectionStrings>
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
With Swift's property wrappers, this is what I'm using now:
@propertyWrapper public struct NCCSerialized<Wrapped> {
private let queue = DispatchQueue(label: "com.nuclearcyborg.NCCSerialized_\(UUID().uuidString)")
private var _wrappedValue: Wrapped
public var wrappedValue: Wrapped {
get { queue.sync { _wrappedValue } }
set { queue.sync { _wrappedValue = newValue } }
}
public init(wrappedValue: Wrapped) {
self._wrappedValue = wrappedValue
}
}
Then you can just do:
@NCCSerialized var foo: Int = 10
or
@NCCSerialized var myData: [SomeStruct] = []
Then access the variable as you normally would.
I was using a .Net Core 2.1 API with the [FromBody]
attribute and I had to use the following solution to successfully Post to it:
_apiClient = new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
FirstName = "Me",
LastName = "Myself"
};
var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));
I've had the same issue after using a web.config from another machine. The problem was related with an invalid MachineKey
. To solve the problem, I modified the web.config to use the correct MachineKey
of my server.
This MSDN blog post shows how to generate a MachineKey.
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
Assuming the existent url is
http://example.com/index.php/foo/bar
and we want to convert it into
http://example.com/foo/bar
You can use the following rule :
RewriteEngine on
#1) redirect the client from "/index.php/foo/bar" to "/foo/bar"
RewriteCond %{THE_REQUEST} /index\.php/(.+)\sHTTP [NC]
RewriteRule ^ /%1 [NE,L,R]
#2)internally map "/foo/bar" to "/index.php/foo/bar"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php/$1 [L]
In the spep #1 we first match against the request string and capture everything after the /index.php/ and the captured value is saved in %1 var. We then send the browser to a new url. The #2 processes the request internally. When the browser arrives at /foo/bar , #2rule rewrites the new url to the orignal location.
I was able to accomplish this with VBA in Excel 2013. No special editors needed. All you need is the Visual Basic code editor which can be accessed on the Developer tab. The Developer tab is not visible by default so it needs to be enabled in File>Options>Customize Ribbon. On the Developer tab, click the Visual Basic button. The code editor will launch. Right click in the Project Explorer pane on the left. Click the insert menu and choose module. Add both subs below to the new module.
Sub LoadCustRibbon()
Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String
hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"
ribbonXML = "<mso:customUI xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + " <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + " <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + " <mso:tab id='reportTab' label='Reports' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:group id='reportGroup' label='Reports' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:button id='runReport' label='PTO' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3' onAction='GenReport'/>" & vbNewLine
ribbonXML = ribbonXML + " </mso:group>" & vbNewLine
ribbonXML = ribbonXML + " </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + " </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + " </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"
ribbonXML = Replace(ribbonXML, """", "")
Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile
End Sub
Sub ClearCustRibbon()
Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String
hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"
ribbonXML = "<mso:customUI xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & _
"<mso:ribbon></mso:ribbon></mso:customUI>"
Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile
End Sub
Call LoadCustRibbon sub in the Wookbook open even and call the ClearCustRibbon sub in the Before_Close Event of the ThisWorkbook code file.
vi /usr/local/etc/redis.conf
Look for dir, logfile
# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /usr/local/var/db/redis/
# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile "redis_log"
So the log file is created at /usr/local/var/db/redis/redis_log
with the name redis_log
You can also try MONITOR
command from redis-cli
to review the number of commands executed.
For ASP.NET, the Load User Profile
setting needs to be set on the app pool but that's not enough. There is a hidden setting named setProfileEnvironment
in \Windows\System32\inetsrv\Config\applicationHost.config
, which for some reason is turned off by default, instead of on as described in the documentation. You can either change the default or set it on your app pool. All the methods on the Environment
class will then return proper values.
I had the same problem as the title of this question, so incase anyone else googles upon this question and wants to start MySql in 'skip-grant-tables' mode on Windows, here is what I did.
Stop the MySQL service through Administrator tools, Services.
Modify the my.ini configuration file (assuming default paths)
C:\Program Files\MySQL\MySQL Server 5.5\my.ini
or for MySQL version >= 5.6
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini
In the SERVER SECTION, under [mysqld], add the following line:
skip-grant-tables
so that you have
# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.
#
[mysqld]
skip-grant-tables
Start the service again and you should be able to log into your database without a password.
You could use PHP's dirname function.
<?php echo dirname(__DIR__); ?>
.
That will give you the name of the parent directory of __DIR__
, which stores the current directory.
It sounds like you are debugging an optimised / release build, despite having the optimised box un-checked. Things you can try are:
If you cant't see the Modules menu item in the Debug -> Windows menu then you may need to add it in the "Customise..." menu.
A bit improved code from GarciaWebDev and Henry Wang. If empty $start or $end is given, function returns values from the beginning or to the end of the $string. Also Inclusive option is available, whether we want to include search result or not:
function get_string_between ($string, $start, $end, $inclusive = false){
$string = " ".$string;
if ($start == "") { $ini = 0; }
else { $ini = strpos($string, $start); }
if ($end == "") { $len = strlen($string); }
else { $len = strpos($string, $end, $ini) - $ini;}
if (!$inclusive) { $ini += strlen($start); }
else { $len += strlen($end); }
return substr($string, $ini, $len);
}
if you just want the number of occurences then you can do this, $ grep -c "string_to_count" file_name
return "default" if x is None else x
try the above.
Make sure that you have compiled your *.cs file before browsing the ASPX page.
The code is
document.addEventListener('keydown', function(event){
alert(event.keyCode);
} );
This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)
\d+
\d
represents any digit, +
for one or more. If you want to catch negative numbers as well you can use -?\d+
.
Note that as a string, it should be represented in C# as "\\d+"
, or @"\d+"
Here's a simpler solution that worked for me:
In XCode5, double-click on your app's target. This brings up the Info pane for the target. In the "Build Settings" section, check the "code signing" section for any old profiles and replace with the correct one. update the value of "code signing identity" and "provisioning profile"
That's invalid Javascript syntax; a property name cannot have a -
.
Use either zIndex
or "z-index"
.
This is what I did to get formatted date from front end
@RequestMapping(value = "/{dateString}", method = RequestMethod.GET)
@ResponseBody
public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) {
return OK;
}
You can use it to get what you want.
include_once('../../../wp-config.php');
global $wpdb;
$password = wp_hash_password("your password");
*Updated
jQuery
version would be something like below:
function load(recieving_id){
$('#roommate_but').prop('disabled', true);
$.get('include.inc.php?i=' + recieving_id, function(data) {
$("#roommate_but").html(data);
});
}
This code works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
namespace Json
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DeserializeNames());
Console.ReadLine();
}
public static string DeserializeNames()
{
var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";
JavaScriptSerializer ser = new JavaScriptSerializer();
nameList myNames = ser.Deserialize<nameList>(jsonData);
return ser.Serialize(myNames);
}
//Class descriptions
public class name
{
public string last { get; set; }
}
public class nameList
{
public List<name> name { get; set; }
}
}
}
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
=VLOOKUP(LEFT(A1,3),LEFT(B$2:B$22,3), 1,FALSE)
LEFT() truncates the first n character of a string, and you need to do it in both columns. The third parameter of VLOOKUP is the number of the column to return with. So if your range is not only B$2:B$22 but B$2:C$22 you can choose to return with column B value (1) or column C value (2)
I'm not sure if you can alter the original element but how about switch from using the id attr to something else like data-id? Then just read the value of data-id for your hash value and it won't jump.
But for a better check:
if(str === null || str === '')
{
//enter code here
}
You can pass in the hostname as an environment variable. You could also mount /etc so you can cat /etc/hostname. But I agree with Vitaly, this isn't the intended use case for containers IMO.
You can just use String.ToCharArray() and then treat each char as a string in your code.
Here's an example:
foreach (char c in s.ToCharArray())
Debug.Log("one character ... " +c);
As suggested on the Chrome Mobile Emulation page, you can use Clumsy on Windows, Network Link Conditioner on Mac OS X and dummynet on Linux.
Whats the value for the SqlException.ErrorCode property? Can you work with that?
When having timeouts, it may be worth checking the code for -2146232060.
I would set this up as a static const in your data code.
I had to manage a scenario where the percentage of duplicates being provided in the new data records was very high, and so many thousands of database calls were being made to check for duplicates (so the CPU sent a lot of time at 100%). In the end I decided to keep the last 100,000 records cached in memory. This way I could check for duplicates against the cached records which was extremely fast when compared to a LINQ query against the SQL database, and then write any genuinely new records to the database (as well as add them to the data cache, which I also sorted and trimmed to keep its length manageable).
Note that the raw data was a CSV file that contained many individual records that had to be parsed. The records in each consecutive file (which came at a rate of about 1 every 5 minutes) overlapped considerably, hence the high percentage of duplicates.
In short, if you have timestamped raw data coming in, pretty much in order, then using a memory cache might help with the record duplication check.
Maybe (from git commit
man page):
git commit --no-verify
-n
--no-verify
This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).
As commented by Blaise, -n
can have a different role for certain commands.
For instance, git push -n
is actually a dry-run push.
Only git push --no-verify
would skip the hook.
Note: Git 2.14.x/2.15 improves the --no-verify behavior:
See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster
-- in commit c3e034f, 23 Aug 2017)
commit
: skip discarding the index if there is nopre-commit
hook"
git commit
" used to discard the index and re-read from the filesystem just in case thepre-commit
hook has updated it in the middle; this has been optimized out when we know we do not run thepre-commit
hook.
Davi Lima points out in the comments the git cherry-pick
does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue
, after a merge conflict resolution.
I had a similar kind of scenario, but in my case string is not a 1st level attribute. It is inside an object. In here I couldn't find a suitable answer for it. So I thought to share my solution with you all(Hope this will help anyone with a similar kind of problem).
Parent Collection
{
"Child":
{
"name":"Random Name",
"Age:"09"
}
}
Ex: If we need to get only collections that having child's name's length is higher than 10 characters.
db.getCollection('Parent').find({$where: function() {
for (var field in this.Child.name) {
if (this.Child.name.length > 10)
return true;
}
}})
The resources you put in src/main/resources will be copied during the build process to target/classes which can be accessed using:
...this.getClass().getResourceAsStream("/config.txt");
Here is an easy way with String output (I created a method to do this):
public static String (String input){
String output = "";
try {
/* From ISO-8859-1 to UTF-8 */
output = new String(input.getBytes("ISO-8859-1"), "UTF-8");
/* From UTF-8 to ISO-8859-1 */
output = new String(input.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return output;
}
// Example
input = "Música";
output = "Música";
I make it extension method and with string array, I think string[]
is more useful than char[]
because char can also be string:
public static class Helper
{
public static string RemoverStrs(this string str, string[] removeStrs)
{
foreach (var removeStr in removeStrs)
str = str.Replace(removeStr, "");
return str;
}
}
then you can use it anywhere:
string myname = "My name @is ,Wan.;'; Wan";
string result = myname.RemoveStrs(new[]{ "@", ",", ".", ";", "\\"});
You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)
That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:
int main()
{
for(;;)
{
printf ("%ld\n", time(NULL));
printf ("%f\n", time(NULL));
sleep(1);
}
return 0;
}
The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.
There is no standard Java class or method that will do what you want. Your options include:
Select and use some third-party expression evaluation library. For example JEL or any of the half dozen libraries listed here.
Wrap the expression in the Java source code for a class with an eval
method, send that to the Java compiler, and then load the resulting compiled class.
Use some scripting language that can be called from Java as an expression evaluator. Possibilities include Javascript, BeanShell, and so on.
Write your own expression evaluator from scratch.
The first approach is probably simplest. The second and third approaches are a potential security risk if you get the expression to be evaluated from an untrusted user. (Think code injection.)
First case:
A normal product lookup would look like this
http://our.api.com/product/1
So Im thinking that best practice would be for you to do this
http://our.api.com/Product/101404,7267261
Second Case
Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using []
.
PS This can be subjective, so do what you feel comfortable with.
The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.
EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.
For tesseract 3, the command is simpler tesseract imagename outputbase digits
according to the FAQ. But it doesn't work for me very well.
I turn to try different psm
options and find -psm 6
works best for my case.
man tesseract
for details.
You can use the Carbon
library, which is an API extension for DateTime.
You can:
function calculate_age($date) {
$date = new \Carbon\Carbon($date);
return (int) $date->diffInYears();
}
or:
$age = (new \Carbon\Carbon($date))->age;
The (currently) accepted answer by Jerub is correct for python2, but incorrect and may produce garbled results (as Apalala points out in a comment to that solution), for python3. That's because the unicode_escape codec requires its source to be coded in latin-1, not utf-8, as per the official python docs. Hence, in python3 use:
>>> myString="špåm\\nëðþ\\x73"
>>> print(myString)
špåm\nëðþ\x73
>>> decoded_string = myString.encode('latin-1','backslashreplace').decode('unicode_escape')
>>> print(decoded_string)
špåm
ëðþs
This method also avoids the extra unnecessary roundtrip between strings and bytes in metatoaster's comments to Jerub's solution (but hats off to metatoaster for recognizing the bug in that solution).
.htaccess:
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log
For 2 and more left joins (left joining creatorUser and initiatorUser )
IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
join candidateUser in authContext.AuthUsers
on r.CandidateId equals candidateUser.Id
join creatorUser in authContext.AuthUsers
on r.CreatorId equals creatorUser.Id into gj
from x in gj.DefaultIfEmpty()
join initiatorUser in authContext.AuthUsers
on r.InitiatorId equals initiatorUser.Id into init
from x1 in init.DefaultIfEmpty()
where candidateUser.UserName.Equals(candidateUsername)
select new CreateRequestModel
{
UserName = candidateUser.UserName,
CreatorId = (x == null ? String.Empty : x.UserName),
InitiatorId = (x1 == null ? String.Empty : x1.UserName),
CandidateId = candidateUser.UserName
};
The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:
http://api.jquery.com/category/selectors/
However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.
I tried to use more than two windows using the Rushy Panchal example above. The intent was to have the change to call more windows with different widgets in them. The butnew function creates different buttons to open different windows. You pass as argument the name of the class containing the window (the second argument is nt necessary, I put it there just to test a possible use. It could be interesting to inherit from another window the widgets in common.
import tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.master.geometry("400x400")
self.frame = tk.Frame(self.master)
self.butnew("Window 1", "ONE", Demo2)
self.butnew("Window 2", "TWO", Demo3)
self.frame.pack()
def butnew(self, text, number, _class):
tk.Button(self.frame, text = text, width = 25, command = lambda: self.new_window(number, _class)).pack()
def new_window(self, number, _class):
self.newWindow = tk.Toplevel(self.master)
_class(self.newWindow, number)
class Demo2:
def __init__(self, master, number):
self.master = master
self.master.geometry("400x400+400+400")
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.label = tk.Label(master, text=f"this is window number {number}")
self.label.pack()
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
class Demo3:
def __init__(self, master, number):
self.master = master
self.master.geometry("400x400+400+400")
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.label = tk.Label(master, text=f"this is window number {number}")
self.label.pack()
self.label2 = tk.Label(master, text="THIS IS HERE TO DIFFERENTIATE THIS WINDOW")
self.label2.pack()
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
To avoid having the chance to press multiple times the button having multiple windows... that are the same window, I made this script (take a look at this page too)
import tkinter as tk
def new_window1():
global win1
try:
if win1.state() == "normal": win1.focus()
except:
win1 = tk.Toplevel()
win1.geometry("300x300+500+200")
win1["bg"] = "navy"
lb = tk.Label(win1, text="Hello")
lb.pack()
win = tk.Tk()
win.geometry("200x200+200+100")
button = tk.Button(win, text="Open new Window")
button['command'] = new_window1
button.pack()
win.mainloop()
IE9 currently lacks CSS3 gradient support. However, here is a nice workaround solution using PHP to return an SVG (vertical linear) gradient instead, which allows us to keep our design in our stylesheets.
<?php
$from_stop = isset($_GET['from']) ? $_GET['from'] : '000000';
$to_stop = isset($_GET['to']) ? $_GET['to'] : '000000';
header('Content-type: image/svg+xml; charset=utf-8');
echo '<?xml version="1.0"?>
';
?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
<defs>
<linearGradient id="linear-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#<?php echo $from_stop; ?>" stop-opacity="1"/>
<stop offset="100%" stop-color="#<?php echo $to_stop; ?>" stop-opacity="1"/>
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="url(#linear-gradient)"/>
</svg>
Simply upload it to your server and call the URL like so:
gradient.php?from=f00&to=00f
This can be used in conjunction with your CSS3 gradients like this:
.my-color {
background-color: #f00;
background-image: url(gradient.php?from=f00&to=00f);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f00), to(#00f));
background-image: -webkit-linear-gradient(top, #f00, #00f);
background-image: -moz-linear-gradient(top, #f00, #00f);
background-image: linear-gradient(top, #f00, #00f);
}
If you need to target below IE9, you can still use the old proprietary 'filter' method:
.ie7 .my-color, .ie8 .my-color {
filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr="#ff0000", endColorStr="#0000ff");
}
Of course you can amend the PHP code to add more stops on the gradient, or make it more sophisticated (radial gradients, transparency etc.) but this is great for those simple (vertical) linear gradients.
You can use the default traceroute
command for this purpose, then there will be nothing to install.
traceroute -T -p 9100 <IP address/hostname>
The -T
argument is required so that the TCP protocol is used instead of UDP.
In the rare case when traceroute
isn't available, you can also use ncat
.
nc -Czvw 5 <IP address/hostname> 9100
You have the arguments in the wrong order:
git branch <branch-name> <commit>
and for that, it doesn't matter what branch is checked out; it'll do what you say. (If you omit the commit argument, it defaults to creating a branch at the same place as the current one.)
If you want to check out the new branch as you create it:
git checkout -b <branch> <commit>
with the same behavior if you omit the commit argument.
More simply in one line:
proxy=192.168.2.1:8080;curl -v example.com
eg. $proxy=192.168.2.1:8080;curl -v example.com
xxxxxxxxx-ASUS:~$ proxy=192.168.2.1:8080;curl -v https://google.com|head -c 15 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
string startTime = "7:00 AM";
string endTime = "2:00 PM";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
Will output: 07:00:00.
It also works if the user input military time:
string startTime = "7:00";
string endTime = "14:00";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
Outputs: 07:00:00.
To change the format: duration.ToString(@"hh\:mm")
More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Addendum:
Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".
Having is only used with aggregation but where with non aggregation statements If you have where word put it before aggregation (group by)
Check execution plan of this delete statement. Have a look if index seek is used. Also what is data type of col?
If you are using wrong data type, change update statement (like from '1' to 1 or N'1').
If index scan is used consider using some query hint..
Another solution (from a script, for example):
sed -i'' -e "s/password=.*\$/password=$pass/g" ~/.my.cnf
mysql -h $host -u $user $db_name -e "$sql_cmd"
The -i''
option is here for compatibility with Mac OS X. Standard UNIX OSes can use straight -i
**To avoid XSS security threat in spring application**
solution to the XSS issue is to filter all the textfields in the form at the time of submitting the form.
It needs XML entry in the web.xml file & two simple classes.
java code :-
The code for the first class named CrossScriptingFilter.java is :
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
public class CrossScriptingFilter implements Filter {
private static Logger logger = Logger.getLogger(CrossScriptingFilter.class);
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("Inlter CrossScriptingFilter ...............");
chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
logger.info("Outlter CrossScriptingFilter ...............");
}
}
The code second class named RequestWrapper.java is :
package com.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.log4j.Logger;
public final class RequestWrapper extends HttpServletRequestWrapper {
private static Logger logger = Logger.getLogger(RequestWrapper.class);
public RequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
public String[] getParameterValues(String parameter) {
logger.info("InarameterValues .. parameter .......");
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return encodedValues;
}
public String getParameter(String parameter) {
logger.info("Inarameter .. parameter .......");
String value = super.getParameter(parameter);
if (value == null) {
return null;
}
logger.info("Inarameter RequestWrapper ........ value .......");
return cleanXSS(value);
}
public String getHeader(String name) {
logger.info("Ineader .. parameter .......");
String value = super.getHeader(name);
if (value == null)
return null;
logger.info("Ineader RequestWrapper ........... value ....");
return cleanXSS(value);
}
private String cleanXSS(String value) {
// You'll need to remove the spaces from the html entities below
logger.info("InnXSS RequestWrapper ..............." + value);
//value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
//value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
//value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", "");
value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", "");
value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "");
value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");
//value = value.replaceAll("<script>", "");
//value = value.replaceAll("</script>", "");
logger.info("OutnXSS RequestWrapper ........ value ......." + value);
return value;
}
The only thing remained is the XML entry in the web.xml file:
<filter>
<filter-name>XSS</filter-name>
<display-name>XSS</display-name>
<description></description>
<filter-class>com.filter.CrossScriptingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>XSS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The /* indicates that for every request made from browser, it will call CrossScriptingFilter class. Which will parse all the components/elements came from the request & will replace all the javascript tags put by hacker with empty string i.e
Set the width and height to wrapper element of the sprite image. Use this css.
{
background-size: cover;
}
res.download()
It transfers the file at path as an “attachment”. For instance:
var express = require('express');
var router = express.Router();
// ...
router.get('/:id/download', function (req, res, next) {
var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
var fileName = "report.pdf"; // The default name the browser will use
res.download(filePath, fileName);
});
res.download()
Here is another method, where you don't have to duplicate the contents of the view:
IF (NOT EXISTS (SELECT 1 FROM sys.views WHERE name = 'data_VVV'))
BEGIN
EXECUTE('CREATE VIEW data_VVVV as SELECT 1 as t');
END;
GO
ALTER VIEW data_VVVV AS
SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A ;
The first checks for the existence of the view (there are other ways to do this). If it doesn't exist, then create it with something simple and dumb. If it does, then just move on to the alter view
statement.
Surround it with a div and give it a border and remove the border from the table
<div style="border: 1px solid black">
<table border="0">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>one</td>
<td>two</td>
</tr>
</table>
</div>
You can check the working fiddle here
As per your updated question .... where you want to add or remove borders. You should remove borders from the html table first and then do the following
<td style="border-top: 1px solid black">
Assuming like you only want the top border. Similarly you have to do for others. Better way create four css class...
.topBorderOnly {
border-top: 1px solid black;
}
.bottomBorderOnly {
border-bottom: 1px solid black;
}
Then add the css to your code depending on the requirements.
<td class="topBorderOnly bottomBorderOnly">
This will add both top and bottom border, similarly do for the rest.
In Get:
public IActionResult Create()
{
ViewData["Tags"] = new SelectList(_context.Tags, "Id", "Name");
return View();
}
In Post:
var selectedIds= Request.Form["Tags"];
In View :
<label>Tags</label>
<select asp-for="Tags" id="Tags" name="Tags" class="form-control" asp-items="ViewBag.Tags" multiple></select>
false == 0
and true = !false
i.e. anything that is not zero and can be converted to a boolean is not false
, thus it must be true
.
Some examples to clarify:
if(0) // false
if(1) // true
if(2) // true
if(0 == false) // true
if(0 == true) // false
if(1 == false) // false
if(1 == true) // true
if(2 == false) // false
if(2 == true) // false
cout << false // 0
cout << true // 1
true
evaluates to 1
, but any int
that is not false
(i.e. 0
) evaluates to true
but is not equal to true
since it isn't equal to 1
.
Use strtotime()
to make the date a UNIX timestamp.
For output, check out the various options of date().
$timestamp = strtotime("08/04/2010 22:15:00");
date("h.i A", $timestamp);
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
You are consuming a line at, which is discarded
while((str=input.readLine())!=null && str.length()!=0)
and reading a bigint at
BigInteger n = new BigInteger(input.readLine());
so try getting the bigint from string which is read as
BigInteger n = new BigInteger(str);
Constructor used: BigInteger(String val)
Aslo change while((str=input.readLine())!=null && str.length()!=0)
to
while((str=input.readLine())!=null)
see related post string to bigint
readLine()
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
see javadocs
This isn't straightforward, but
SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1
returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.
SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1
The easiest way I've found to place objects on the left is using FlowLayout.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
adding a component normally to this panel will place it on the left