It seems that this can't be done, not at least with current versions of IE (6 and 7).
IE supports form attribute accept-charset, but only if its value is 'utf-8'.
The solution is to modify server A to produce encoding 'ISO-8859-1' for page that contains the form.
Simple!
System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));
byte[] iso88591Data = theString.getBytes("ISO-8859-1");
Will do the trick. From your description it seems as if you're trying to "store an ISO-8859-1 String". String objects in Java are always implicitly encoded in UTF-16. There's no way to change that encoding.
What you can do, 'though is to get the bytes that constitute some other encoding of it (using the .getBytes()
method as shown above).
Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);
ISO-8859-1 is a legacy standards from back in 1980s. It can only represent 256 characters so only suitable for some languages in western world. Even for many supported languages, some characters are missing. If you create a text file in this encoding and try copy/paste some Chinese characters, you will see weird results. So in other words, don't use it. Unicode has taken over the world and UTF-8 is pretty much the standards these days unless you have some legacy reasons (like HTTP headers which needs to compatible with everything).
In my case this (a with caret) occurred in code I generated from visual studio using my own tool for generating code. It was easy to solve:
Select single spaces ( ) in the document. You should be able to see lots of single spaces that are looking different from the other single spaces, they are not selected. Select these other single spaces - they are the ones responsible for the unwanted characters in the browser. Go to Find and Replace with single space ( ). Done.
PS: It's easier to see all similar characters when you place the cursor on one or if you select it in VS2017+; I hope other IDEs may have similar features
The easiest way to convert an ISO-8859-1 string to UTF-8 string.
private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
return new String(example.getBytes("ISO-8859-1"), "utf-8");
}
If we want to convert an UTF-8 string to ISO-8859-1 string.
private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
return new String(example.getBytes("utf-8"), "ISO-8859-1");
}
Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.
public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
String res = "";
int i = 0;
for (i = 0; i < strISO_8859_1.length() - 1; i++) {
char ch = strISO_8859_1.charAt(i);
char chNext = strISO_8859_1.charAt(i + 1);
if (ch <= 127) {
res += ch;
} else if (ch == 194 && chNext >= 128 && chNext <= 191) {
res += chNext;
} else if(ch == 195 && chNext >= 128 && chNext <= 191){
int resNum = chNext + 64;
res += (char) resNum;
} else if(ch == 194){
res += (char) 173;
} else if(ch == 195){
res += (char) 224;
}
}
char ch = strISO_8859_1.charAt(i);
if (ch <= 127 ){
res += ch;
}
return res;
}
}
That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1
It is much better to use
$value = mb_convert_encode($value,'HTML-ENTITIES','UTF-8');
Specially when you are using AJAX call for submitting 'ISO-8859-1' characters. It works for Chinese, Japanese, Czech, German and many more languages.
You can use DataKeys for retrieving the value of such fields, because (as you said) when you set a normal BoundField
as visible false you cannot get their value.
In the .aspx
file set the GridView
property
DataKeyNames = "Outlook_ID"
Now, in an event handler you can access the value of this key like so:
grid.DataKeys[rowIndex]["Outlook_ID"]
This will give you the id at the specified rowindex of the grid.
I know it is not a good habit to answer an old question but I'm putting this answer for people who would see the question afterwards.
The best way to change the state in JQuery now is through
$("#input").prop('disabled', true);
$("#input").prop('disabled', false);
Please check this link for full illustration. Disable/enable an input with jQuery?
To bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming the attribute.
(For PHPMyAdmin users: To remove FK constrains in PHPMyAdmin, select the attribute then click "relation view" next to "print view" in the toolbar below the table structure)
The delete
operator deallocates memory and calls the destructor for a single object created with new
.
The delete []
operator deallocates memory and calls destructors for an array of objects created with new []
.
Using delete
on a pointer returned by new []
or delete []
on a pointer returned by new
results in undefined behavior.
tl;dr: use OSX's native process launcher and manager, launchd
.
To do so, make a launchctl
daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.
.plist
file according to the instructions in the Apple Dev docs here or more detail below.~/Library/LaunchAgents
launchctl load [filename.plist]
)For more on launchd
, the wikipedia article is quite good and describes the system and its advantages over other older systems.
Here's the specific plist file to run a script at login.
Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.user.loginscript</string>
<key>ProgramArguments</key>
<array><string>/path/to/executable/script.sh</string></array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Replace the <string>
after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh
to ensure it is for all users).
Save as ~/Library/LaunchAgents/com.user.loginscript.plist
Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist
and log out/in to test (or to test directly, run launchctl start com.user.loginscript
)
Tail /var/log/system.log
for error messages.
The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons
) are run on boot.
If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.
From Dashboard At a Glance
box
or at the bottom right corner of any admin page.
If that Glance box is hidden - click on screen options
at top-right corner and check At a Glance
option.
this is a follow up on the patricus [answer][1] above but for nested arrays:
$topLevelFields = ['id','status'];
$userFields = ['first_name','last_name','email','phone_number','op_city_id'];
return $onlineShoppers->map(function ($user) {
return collect($user)->only($topLevelFields)
->merge(collect($user['user'])->only($userFields))->all();
})->all();
Finally got a solution.
First .sql file converts into the UTF8.
Then use this command
mysql -p -u root --default_character_set utf8 test </var/201535.sql
---root is the username
---test is the database name
or
mysql -p -u root test < /var/201535.sql
---root is the username
---test is the database name
Just use this line
svn update -r yourOldRevesion
You can know your current revision by using:
svn info
To escape %
, you will need to double it up: %%
.
scrollTo
:function scroll() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
_x000D_
<button onclick="scroll">Scroll</button>
_x000D_
Specify POST method in form
<form name="registrationform" action="register.php" method="post">
your form code
</form>
If you are using React Router, use this:
<Link to="/files/myfile.pdf" target="_blank" download>Download</Link>
Where /files/myfile.pdf
is inside your public
folder.
Since the login page is a separate page, I am assuming that you want to redirect to the page that the user reached the login page from.
$_SERVER['REQUEST_URI']
will simply hold the current page. What you want to do is use $_SERVER['HTTP_REFERER']
So save the HTTP_REFERER in a hidden element on your form <input type="hidden" name="referer" value="<?= $_SERVER['HTTP_REFERER'] ?>" />
but keep in mind that in the PHP that processes the form you will need some logic that redirects back to the login page if login fails but also to check that the referer is actually your website, if it isn't, then redirect back to the homepage.
$_GET['start_date']
is not numeric is my bet, but an date format not supported by strtotime
. You will need to re-format the date to a workable format for strtotime or use combination of explode/mktime.
I could add you an example if you'd be kind enough to post the format you currently receive.
Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.
Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.
Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.
Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.
I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.
I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.
because of your a and b variable is not have been initialized. You must initialized this variables for excample if you declare this variable like this int a=0; int b=0; than your code run without error.
The make
uses the $
for its own variable expansions. E.g. single character variable $A
or variable with a long name - ${VAR}
and $(VAR)
.
To put the $
into a command, use the $$
, for example:
all:
@echo "Please execute next commands:"
@echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'
Also note that to make
the ""
and ''
(double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @
sign to see what make
sends to shell.) To prevent the shell from expanding $PATH
, second line uses the ''
.
You cant simply (directly) convert the datareader to list.
You have to loop through all the elements in datareader and insert into list
below the sample code
using (drOutput)
{
System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();
int customerId = drOutput.GetOrdinal("customerId ");
int CustomerName = drOutput.GetOrdinal("CustomerName ");
while (drOutput.Read())
{
CustomerEntity obj=new CustomerEntity ();
obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
arrObjects .Add(obj);
}
}
You can just use return
to end the method's execution
To specify both font size and rotation at the same time, try this:
plt.xticks(fontsize=14, rotation=90)
(Update: overlooked a fault in the matter, I have corrected)
(Update2: I wrote from memory the code screwed up, repaired it)
(Update3: check on SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150)
,Questions nvarchar(100)
,Answer nvarchar(100)
)
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
inner join deleted d on i.BusinessUnit = d.BusinessUnit
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
FROM
deleted d
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
delete Derived_Values;
and then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
Record Count: 0;
BUSINESSUNIT QUESTIONS ANSWER
Updated Record -- After Update Trigger.BU1 Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1 Q11 A11
Updated Record -- After Update Trigger.BU1 Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1 Q12 A12
Updated Record -- After Update Trigger.BU2 Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2 Q21 A21
Updated Record -- After Update Trigger.BU2 Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2 Q22 A22
(Update4: If you want to sync: SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
CREATE TRIGGER trgAfterInsert ON [Derived_Values]
FOR INSERT
AS
begin
insert
[Derived_Values_Test]
(BusinessUnit,Questions,Answer)
SELECT
i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
end
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
update
[Derived_Values_Test]
set
--BusinessUnit = i.BusinessUnit
--,Questions = i.Questions
Answer = i.Answer
from
[Derived_Values]
inner join inserted i
on
[Derived_Values].BusinessUnit = i.BusinessUnit
and
[Derived_Values].Questions = i.Questions
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR DELETE
AS
begin
delete
[Derived_Values_Test]
from
[Derived_Values_Test]
inner join deleted d
on
[Derived_Values_Test].BusinessUnit = d.BusinessUnit
and
[Derived_Values_Test].Questions = d.Questions
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
--delete Derived_Values;
And then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
var_dump(extension_loaded('curl'));
My npm install
worked fine, but I had this problem with npm update
. To fix it, I had to run npm cache clean
and then npm cache clear
.
I had the same thing happen to a PNG with transparency that was set as the background-image of an <A> element with opacity applied.
The fix was to set the background-color of the <A> element.
So, the following:
filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;
Turns into:
/* "Overwritten" by the background-image. However this fixes the IE7 and IE8 PNG-transparency-plus-opacity bug. */
background-color: #FFFFFF;
filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;
If I understand your issue correctly, I think I have found a solution to your problem:
I had the same issue where raw output was shown with no css styles, javascripts or jquery files found.
I just added mappings to the "default" servlet. The following was added to the web.xml file:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
This should filter out the javascript and css file requests from the DispatcherRequest object.
Again, not sure if this is what you are after, but it worked for me. I think "default" is the name of the default servlet within JBoss. Not too sure what it is for other servers.
Use the static methods in the Math
class for both - there are no operators for this in the language:
double root = Math.sqrt(value);
double absolute = Math.abs(value);
(Likewise there's no operator for raising a value to a particular power - use Math.pow
for that.)
If you use these a lot, you might want to use static imports to make your code more readable:
import static java.lang.Math.sqrt;
import static java.lang.Math.abs;
...
double x = sqrt(abs(x) + abs(y));
instead of
double x = Math.sqrt(Math.abs(x) + Math.abs(y));
To create POM.XML file in Eclipse:
Install M2E plugin (http://www.eclipse.org/m2e/)
Right click on project -> Configure -> Convert to Maven Project
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$('body').mousemove(function (e) {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
$('body').keypress(function (e) {
//alert("keypressed" + idleTime);
idleTime = 0;
});
$('body').click(function() {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 10) { // 10 minutes
window.location.assign("http://www.google.com");
}
}
</script>
I think this jquery code is perfect one , though copied and modified from above answers!! donot forgot to include jquery library in your file!
You could try passing a callback function to perform the replacement:
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return str.replace(/[&<>]/g, replaceTag);
}
Here is a performance test: http://jsperf.com/encode-html-entities to compare with calling the replace
function repeatedly, and using the DOM method proposed by Dmitrij.
Your way seems to be faster...
Why do you need it, though?
This will work:
<head>
<script type="text/javascript">
function Init () {
var counter = document.getElementById ("counter");
for (var i = 1; i < 1000; i++) {
var option = new Option (i, i);
counter.options.add (option);
}
counter.focus ();
}
function OnKeyPressCounter (event, counter) {
var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
if (chCode == 68 /* + */) {
if (counter.selectedIndex < counter.options.length - 1) {
counter.selectedIndex++;
}
}
if (chCode == 45 /* - */) {
if (counter.selectedIndex > 0) {
counter.selectedIndex--;
}
}
}
</script>
</head>
<body onload="Init ()">
Use the + and - keys to increase/decrease the counter.
<select id="counter" onkeypress="OnKeyPressCounter(event, this)" style="width:80px"></select>
</body>
You should add a line with:
*.pyc
to the .gitignore
file in the root folder of your git repository tree right after repository initialization.
As ralphtheninja said, if you forgot to to do it beforehand, if you just add the line to the .gitignore
file, all previously committed .pyc
files will still be tracked, so you'll need to remove them from the repository.
If you are on a Linux system (or "parents&sons" like a MacOSX), you can quickly do it with just this one line command that you need to execute from the root of the repository:
find . -name "*.pyc" -exec git rm -f "{}" \;
This just means:
starting from the directory i'm currently in, find all files whose name ends with extension
.pyc
, and pass file name to the commandgit rm -f
After *.pyc
files deletion from git as tracked files, commit this change to the repository, and then you can finally add the *.pyc
line to the .gitignore
file.
(adapted from http://yuji.wordpress.com/2010/10/29/git-remove-all-pyc/)
Edit the code to be as follows:
// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );
if( $moved ) {
echo "Successfully uploaded";
} else {
echo "Not uploaded because of error #".$_FILES["file"]["error"];
}
It will give you one of the following error code values 1 to 8:
UPLOAD_ERR_INI_SIZE = Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE = Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL = Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE = Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR = Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE = Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION = Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.
insert into OPT (email, campaign_id)
select 'mom@coxnet' as email, 100 as campaign_id from dual MINUS
select email, campaign_id from OPT;
If there is already a record with [email protected]
/100
in OPT, the MINUS
will subtract this record from the select 'mom@coxnet' as email, 100 as campaign_id from dual
record and nothing will be inserted. On the other hand, if there is no such record, the MINUS
does not subract anything and the values mom@coxnet
/100
will be inserted.
As p.marino has already pointed out, merge
is probably the better (and more correct) solution for your problem as it is specifically designed to solve your task.
You can use Convert.ToDateTime is it is shown at How to convert a Datetime string to a current culture datetime string
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
var result = Convert.ToDateTime("12/01/2011", usDtfi)
If BranchA has not been pushed to a remote then you can reorder the commits using rebase
and then simply merge
. It's preferable to use merge
over rebase
when possible because it doesn't create duplicate commits.
git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]
Use the SQLCMD utility.
http://technet.microsoft.com/en-us/library/ms162773.aspx
There is a connect statement that allows you to swing from database server A to server B in the same batch.
:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]] Connects to an instance of SQL Server. Also closes the current connection.
On the other hand, if you are familiar with PowerShell, you can programmatic do the same.
http://technet.microsoft.com/en-us/library/cc281954(v=sql.105).aspx
To complement these other answers, the //
operator also offers significant (3x) performance benefits over /
, presuming you want integer division.
$ python -m timeit '20.5 // 2'
100,000,000 loops, best of 3: 14.9 nsec per loop
$ python -m timeit '20.5 / 2'
10,000,000 loops, best of 3: 48.4 nsec per loop
$ python -m timeit '20 / 2'
10,000,000 loops, best of 3: 43.0 nsec per loop
$ python -m timeit '20 // 2'
100,000,000 loops, best of 3: 14.4 nsec per loop
Why would you want to do this? You shouldn't be executing controller code in the view, and most certainly shouldn't be trying to pull code inside of another servlet into the view either.
Do all of your processing and refactoring of the application first, then just pass off the results to a view. Make the view as dumb as possible and you won't even run into these problems.
If this kind of design is hard for you, try Freemarker or even something like Velocity (although I don't recommend it) to FORCE you to do this. You never have to do this sort of thing ever.
To put it more accurately, the problem you are trying to solve is just a symptom of a greater problem - your architecture/design of your servlets.
As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.
I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).
Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.
orderedtest - it works but I don't recommend it because:
Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.
You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.
The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.
This means the test method that is declared in the first place executes before the one that is declared in second place, etc.
To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.
I strongly suggest some old and tested rules:
VERY IMPORTANT
In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.
Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.
Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.
Just another solution, with the colors of ZetaSyanthis:
def config_log(log_level):
def set_color(level, code):
level_fmt = "\033[1;" + str(code) + "m%s\033[1;0m"
logging.addLevelName( level, level_fmt % logging.getLevelName(level) )
std_stream = sys.stdout
isatty = getattr(std_stream, 'isatty', None)
if isatty and isatty():
levels = [logging.DEBUG, logging.CRITICAL, logging.WARNING, logging.ERROR]
for idx, level in enumerate(levels):
set_color(level, 30 + idx )
set_color(logging.DEBUG, 0)
logging.basicConfig(stream=std_stream, level=log_level)
call it once from your __main__
function. I have something like this there:
options, arguments = p.parse_args()
log_level = logging.DEBUG if options.verbose else logging.WARNING
config_log(log_level)
it also verifies that the output is a console, otherwise no colors are used.
I prefer to use BIGINT
, and store the values in by multiply with 100, so that it will become integer.
For e.g., to represent a currency value of 93.49
, the value shall be stored as 9349
, while displaying the value we can divide by 100 and display. This will occupy less storage space.
Caution:
Mostly we don't performcurrency * currency
multiplication, in case if we are doing it then divide the result with 100 and store, so that it returns to proper precision.
About this, java declares that on Windows 10, Edge browser does not support plugins, so it will NOT run java. (see https://www.java.com/it/download/win10.jsp --> only visible with edge in win10) It also reports a notice: java is not officially supported yet in Windows 10. (see https://www.java.com/it/download/faq/win10_faq.xml)
Another way is to compare the character with an empty object, i don't really know's why it works, but it works :
for (let i = 1; i <= 26; i++) {
const letter = (i + 9).toString(36).toUpperCase();
console.log('letter', letter, 'is upper', letter<{}); // returns true
}
for (let i = 1; i <= 26; i++) {
const letter = (i + 9).toString(36);
console.log('letter', letter, 'is upper', letter<{}); // returns false
}
so in a function :
function charIsUpper(character) {
return character<{};
}
EDIT: it doesn't work with accents and diacritics, so it's possible to remove it
function charIsUpper(character) {
return character
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')<{};
}
Using this Function u can define your won position
setBounds(500, 200, 647, 418);
Thought i'd add my solution that i've been using.
If you're using the System.Web.Script.Serialization.JavaScriptSerializer()
then the time returned isn't going to be specific to your timezone. To fix this you'll also want to use dte.getTimezoneOffset()
to get it back to your correct time.
String.prototype.toDateFromAspNet = function() {
var dte = eval("new " + this.replace(/\//g, '') + ";");
dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
return dte;
}
now you'll just call
"/Date(1245398693390)/".toDateFromAspNet();
Fri Jun 19 2009 00:04:53 GMT-0400 (Eastern Daylight Time) {}
As you mentioned in a comment, you're using log4j. I discovered (inadvertently) a place where I had written
LOG.error(exc);
instead of the typical
LOG.error("Some informative message", e);
through laziness or perhaps just not thinking about it. The unfortunate part of this is that it doesn't behave as you expect. The logger API actually takes Object as the first argument, not a string - and then it calls toString() on the argument. So instead of getting the nice pretty stack trace, it just prints out the toString - which in the case of NPE is pretty useless.
Perhaps this is what you're experiencing?
Use the attribute selector
[id^=product]{property:value}
If you want the serialized data to be really compact, you can write serialization methods yourself. That way you will have a minimum of overhead.
Example:
public class MyClass {
public int Id { get; set; }
public string Name { get; set; }
public byte[] Serialize() {
using (MemoryStream m = new MemoryStream()) {
using (BinaryWriter writer = new BinaryWriter(m)) {
writer.Write(Id);
writer.Write(Name);
}
return m.ToArray();
}
}
public static MyClass Desserialize(byte[] data) {
MyClass result = new MyClass();
using (MemoryStream m = new MemoryStream(data)) {
using (BinaryReader reader = new BinaryReader(m)) {
result.Id = reader.ReadInt32();
result.Name = reader.ReadString();
}
}
return result;
}
}
below is one of my answers on another post - error: unable to load installed packages just now
(this is also relevant to this question)
For Linux(Ubuntu) users: If you have oracle-java (7/8) installed. It'll be at this location /usr/lib/jvm
and sudo
access is required.
Create the file /etc/ld.so.conf.d/java.conf
with the following entries:
/usr/lib/jvm/java-8-oracle/jre/lib/amd64
/usr/lib/jvm/java-8-oracle/jre/lib/amd64/server
(Replace java-8-oracle with java-7-oracle depending on your java version)
Then:
sudo ldconfig
Restart RStudio and then install the rJava package.
Use angular.bootstrap(element, [modules], [config])
to manually start up AngularJS application (for more information, see the Bootstrap guide).
See the following example:
// root-app_x000D_
const rootApp = angular.module('root-app', ['app1', 'app2']);_x000D_
_x000D_
// app1_x000D_
const app1 = angular.module('app1', []);_x000D_
app1.controller('main', function($scope) {_x000D_
$scope.msg = 'App 1';_x000D_
});_x000D_
_x000D_
// app2_x000D_
const app2 = angular.module('app2', []);_x000D_
app2.controller('main', function($scope) {_x000D_
$scope.msg = 'App 2';_x000D_
});_x000D_
_x000D_
// bootstrap_x000D_
angular.bootstrap(document.querySelector('#app1'), ['app1']);_x000D_
angular.bootstrap(document.querySelector('#app2'), ['app2']);
_x000D_
<!-- [email protected] -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>_x000D_
_x000D_
<!-- root-app -->_x000D_
<div ng-app="root-app">_x000D_
_x000D_
<!-- app1 -->_x000D_
<div id="app1">_x000D_
<div ng-controller="main">_x000D_
{{msg}}_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!-- app2 -->_x000D_
<div id="app2">_x000D_
<div ng-controller="main">_x000D_
{{msg}}_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
You can use df.columns.isin()
df.loc[:, ~df.columns.isin(['b'])]
When you want to drop multiple columns, as simple as:
df.loc[:, ~df.columns.isin(['col1', 'col2'])]
Please try CURRENT_TIME()
or now()
functions
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"
OR
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"
OR you could try with PHP date
function here:
$date = date("Y-m-d H:i:s");
You can do something like this to find out the cookies's value:
Request.Cookies[SESSION_COOKIE_NAME].Value
I referred a blog by Kim for doing this and its working fine for me. See the blog
The automated execution of macro can be accomplished with the help of a VB Script file which is being invoked by Windows Task Scheduler at specified times.
Remember to replace 'YourWorkbook' with the name of the workbook you want to open and replace 'YourMacro' with the name of the macro you want to run.
See the VB Script File (just named it RunExcel.VBS):
' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone
' Tell Excel what the current working directory is
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\YourWorkbook.xls"
Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)
' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "'" & strPath & "\YourWorkbook" & "!Sheet1.YourMacro"
on error resume next
' Run the calculation macro
myExcelWorker.Run strMacroName
if err.number <> 0 Then
' Error occurred - just close it down.
End If
err.clear
on error goto 0
oWorkBook.Save
myExcelWorker.DefaultFilePath = strSaveDefaultPath
' Clean up and shut down
Set oWorkBook = Nothing
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
if myExcelWorker.Workbooks.Count = 0 Then
myExcelWorker.Quit
End If
Set myExcelWorker = Nothing
Set WshShell = Nothing
You can test this VB Script from command prompt:
>> cscript.exe RunExcel.VBS
Once you have the VB Script file and workbook tested so that it does what you want, you can then use Microsoft Task Scheduler (Control Panel-> Administrative Tools--> Task Scheduler) to execute ‘cscript.exe RunExcel.vbs’ automatically for you.
Please note the path of the macro should be in correct format and inside single quotes like:
strMacroName = "'" & strPath & "\YourWorkBook.xlsm'" &
"!ModuleName.MacroName"
You need the correct argument for the nth-child
pseudo class.
The argument should be in the form of an + b
to match every ath child starting from b.
Both a
and b
are optional integers and both can be zero or negative.
a
is zero then there is no "every ath child" clause.a
is negative then matching is done backwards starting from b
.b
is zero or negative then it is possible to write equivalent expression using positive b
e.g. 4n+0
is same as 4n+4
. Likewise 4n-1
is same as 4n+3
.Examples:
li:nth-child(4n) {_x000D_
background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
</ol>
_x000D_
li:nth-child(4n+1) {_x000D_
background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
</ol>
_x000D_
/* two selectors are required */_x000D_
li:nth-child(4n+3),_x000D_
li:nth-child(4n+4) {_x000D_
background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
</ol>
_x000D_
/* when a is negative then matching is done backwards */_x000D_
li:nth-child(-n+4) {_x000D_
background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
<li>Item</li>_x000D_
</ol>
_x000D_
You need to load a package (like magrittr
or dplyr
) that defines the function first, then it should work.
install.packages("magrittr") # package installations are only needed the first time you use it
install.packages("dplyr") # alternative installation of the %>%
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr) # alternatively, this also loads %>%
The pipe operator %>%
was introduced to "decrease development time and to improve readability and maintainability of code."
But everybody has to decide for himself if it really fits his workflow and makes things easier.
For more information on magrittr
, click here.
Not using the pipe %>%
, this code would return the same as your code:
words <- colnames(as.matrix(dtm))
words <- words[nchar(words) < 20]
words
EDIT: (I am extending my answer due to a very useful comment that was made by @Molx)
Despite being from
magrittr
, the pipe operator is more commonly used with the packagedplyr
(which requires and loadsmagrittr
), so whenever you see someone using%>%
make sure you shouldn't loaddplyr
instead.
The answers here got me close, but in 2016, I was able to write the following LINQ:
List<ObjectType> objectList = similarTypeList.Select(o =>
new ObjectType
{
PropertyOne = o.PropertyOne,
PropertyTwo = o.PropertyTwo,
PropertyThree = o.PropertyThree
}).ToList();
again this is JS :) this still works ....
var linkToClick = document.getElementById('something');
linkToClick.click();
<Link id="something" to={/somewhaere}> the link </Link>
In programming, a "magic number" is a value that should be given a symbolic name, but was instead slipped into the code as a literal, usually in more than one place.
It's bad for the same reason SPOT (Single Point of Truth) is good: If you wanted to change this constant later, you would have to hunt through your code to find every instance. It is also bad because it might not be clear to other programmers what this number represents, hence the "magic".
People sometimes take magic number elimination further, by moving these constants into separate files to act as configuration. This is sometimes helpful, but can also create more complexity than it's worth.
While Parallels is technically a VM it is capable of running games in high resolution at a high frame rate. If you run Parallels in Coherence mode it completely integrates Windows 7 into OS X and .Net framework is fully supported. So yes you can install Visual Studio on your Mac however the Apps you created would only run of windows computers unless they were web based.
To change the text AB
into A \r B
in a table cell, put this into the cell position: \makecell{A \\ B}
.
Before doing that, you also need to include package makecell
.
path
is simply new in Django 2.0, which was only released a couple of weeks ago. Most tutorials won't have been updated for the new syntax.
It was certainly supposed to be a simpler way of doing things; I wouldn't say that URL is more powerful though, you should be able to express patterns in either format.
You can cut off the milliseconds using a Calendar
:
java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));
Output:
2014-04-04 10:10:17.78
2014-04-04 10:10:17.0
you should try using os.walk
yourpath = 'path'
import os
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
print(os.path.join(root, name))
stuff
for name in dirs:
print(os.path.join(root, name))
stuff
See file()
PHP Manual:
$url = 'http://mixednews.ru/wp-content/uploads/2011/10/0ed9320413f3ba172471860e77b15587.jpg';
$img = 'miki.png';
$file = file($url);
$result = file_put_contents($img, $file)
With ECMAScript 2015 you can export and import multiple classes like this
class Person
{
constructor()
{
this.type = "Person";
}
}
class Animal{
constructor()
{
this.type = "Animal";
}
}
module.exports = {
Person,
Animal
};
then where you use them:
const { Animal, Person } = require("classes");
const animal = new Animal();
const person = new Person();
In case of name collisions, or you prefer other names you can rename them like this:
const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");
const animal = new OtherAnimal();
const person = new OtherPerson();
Here's a rather simple solution:
In the controller we return our errors like this:
if (!ModelState.IsValid)
{
return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
}
Here's some of the client script:
function displayValidationErrors(errors)
{
var $ul = $('div.validation-summary-valid.text-danger > ul');
$ul.empty();
$.each(errors, function (idx, errorMessage) {
$ul.append('<li>' + errorMessage + '</li>');
});
}
That's how we handle it via ajax:
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
var isSuccessful = (data['success']);
if (isSuccessful) {
$('#partial-container-steps').html(data['view']);
initializePage();
}
else {
var errors = data['errors'];
displayValidationErrors(errors);
}
}
});
Also, I render partial views via ajax in the following way:
var view = this.RenderRazorViewToString(partialUrl, viewModel);
return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);
RenderRazorViewToString method:
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
To go to location WITH PIN on it, use:
String uri = "http://maps.google.com/maps?q=loc:" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
for without pin, use this in uri:
String uri = "geo:" + destinationLatitude + "," + destinationLongitude;
Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.
arr = arr.filter(v => v);
as returned v
is implicity converted to truthy
I use this feature often enough that I add a custom button to the command bar.
$('#grid').trigger( 'reloadGrid' );
I needed an array to became a String rappresentation of an array I mean I needed that
var a = ['a','b','c'];
//became a "real" array string-like to pass on query params so was easy to do:
JSON.stringify(a); //-->"['a','b','c']"
maybe someone need it :)
basicaly 2 blocks of code that do the same thing. maybe it's a bit weird example but it proves the point. SQL Server 2005:
SELECT * INTO #temp FROM master..spt_values
DECLARE @startTime DATETIME
BEGIN TRAN
SELECT @startTime = GETDATE()
UPDATE #temp
SET number = 0
select DATEDIFF(ms, @startTime, GETDATE())
ROLLBACK
BEGIN TRAN
DECLARE @name VARCHAR
DECLARE tempCursor CURSOR
FOR SELECT name FROM #temp
OPEN tempCursor
FETCH NEXT FROM tempCursor
INTO @name
SELECT @startTime = GETDATE()
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE #temp SET number = 0 WHERE NAME = @name
FETCH NEXT FROM tempCursor
INTO @name
END
select DATEDIFF(ms, @startTime, GETDATE())
CLOSE tempCursor
DEALLOCATE tempCursor
ROLLBACK
DROP TABLE #temp
the single update takes 156 ms while the cursor takes 2016 ms.
@IBInspectable is working for me on iOS 9 , Swift 2.0
extension UIView {
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set(newValue) {
layer.borderWidth = newValue
}
}
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set(newValue) {
layer.cornerRadius = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(CGColor: color)
}
return nil
}
set(newValue) {
layer.borderColor = newValue?.CGColor
}
}
Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW
, FIRST_COL
, and LAST_COL
, and that _xlSheet
is the name of the ExcelSheet
(using Microsoft.Interop.Excel
)
First, define the range:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
Then, set the background color of that range:
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
Finally, set the font color:
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
And here's the code combined:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
I've created go project for string formatting from template (it allow to format strings in C# or Python style, just first version for very simple cases), you could find it here https://github.com/Wissance/stringFormatter
it works in following manner:
func TestStrFormat(t *testing.T) {
strFormatResult, err := Format("Hello i am {0}, my age is {1} and i am waiting for {2}, because i am {0}!",
"Michael Ushakov (Evillord666)", "34", "\"Great Success\"")
assert.Nil(t, err)
assert.Equal(t, "Hello i am Michael Ushakov (Evillord666), my age is 34 and i am waiting for \"Great Success\", because i am Michael Ushakov (Evillord666)!", strFormatResult)
strFormatResult, err = Format("We are wondering if these values would be replaced : {5}, {4}, {0}", "one", "two", "three")
assert.Nil(t, err)
assert.Equal(t, "We are wondering if these values would be replaced : {5}, {4}, one", strFormatResult)
strFormatResult, err = Format("No args ... : {0}, {1}, {2}")
assert.Nil(t, err)
assert.Equal(t, "No args ... : {0}, {1}, {2}", strFormatResult)
}
func TestStrFormatComplex(t *testing.T) {
strFormatResult, err := FormatComplex("Hello {user} what are you doing here {app} ?", map[string]string{"user":"vpupkin", "app":"mn_console"})
assert.Nil(t, err)
assert.Equal(t, "Hello vpupkin what are you doing here mn_console ?", strFormatResult)
}
You could always use typeof
in the if statement. It is better than working with string values like the answer of Natarajan.
if (dt.Columns[0].DataType == typeof(DateTime))
{
}
You are looking for System.Environment.NewLine
.
On Windows, this is equivalent to \r\n
though it could be different under another .NET implementation, such as Mono on Linux, for example.
easy:
launching activity (onclick handler)
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
on the new activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
and add your new activity in the AndroidManifest.xml:
<activity android:label="@string/app_name" android:name="NextActivity"/>
As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):
<form id="form-id">
<input type="file" id="input-id" accept="image/jpeg"/>
</form>
<script type="text/javascript">
$(function(){
$("#input-id").on('change', function(event) {
var file = event.target.files[0];
if(file.size>=2*1024*1024) {
alert("JPG images of maximum 2MB");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
if(!file.type.match('image/jp.*')) {
alert("only JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
//verify the magic number
// for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
alert("ok!");
} else {
alert("only valid JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
};
fileReader.readAsArrayBuffer(file);
});
});
</script>
Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.
Both are correct.
You probably have some coding standard in your company - just see to follow it through. If you don't have - you should :)
No need of JQuery simply you can do
if(yourObject['email']){
// what if this property exists.
}
as with any value for email
will return you true
, if there is no such property or that property value is null
or undefined
will result to false
Your selector is retrieving the text box's surrounding <div class='textBoxEmployeeNumber'>
instead of the input inside it.
// Access the input inside the div with this selector:
$(function () {
$('.textBoxEmployeeNumber input').val("fgg");
});
If the ASP.NET code reliably outputs the HTML <input>
with an id attribute id='EmployeeId'
, you can more simply just use:
$(function () {
$('#EmployeeId').val("fgg");
});
Failing this, you will need to verify in your browser's error console that you don't have other script errors causing this to fail. The first example above works correctly in this demonstration.
We've seen in our projects that a post request with JSON and files is creating a lot of confusion between the frontend and backend developers, leading to unnecessary wastage of time.
Here's a better approach: convert file bytes array to Base64 string and send it in the JSON.
public Class UserDTO {
private String firstName;
private String lastName;
private FileDTO profilePic;
}
public class FileDTO {
private String base64;
// just base64 string is enough. If you want, send additional details
private String name;
private String type;
private String lastModified;
}
@PostMapping("/user")
public String saveUser(@RequestBody UserDTO user) {
byte[] fileBytes = Base64Utils.decodeFromString(user.getProfilePic().getBase64());
....
}
JS code to convert file to base64 string:
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
const userDTO = {
firstName: "John",
lastName: "Wick",
profilePic: {
base64: reader.result,
name: file.name,
lastModified: file.lastModified,
type: file.type
}
}
// post userDTO
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
Dump extensions:
code --list-extensions > extensions.txt
Install extensions with Bash (Linux, OS X and WSL):
cat extensions.txt | xargs code --list-extensions {}
Install extensions on Windows with PowerShell:
cat extensions.txt |% { code --install-extension $_}
I thought I would put a note here that explains a basic misconception for a lot of people who are using these Text Editors... Sublime Text in particular (or at least that's the one I use, so I don't know how it works for other editors):
There are "Themes" and there are "Color Schemes". They are similar but affect different things. "Themes" actively change the entire UI, and can include a Color Scheme if you set it up that way. This typically includes the sidebar, and can also include options for the file tabs, and some even include icons for the sidebar as well. And then we have "Color Schemes" which only change the coding windows and nothing else... not the Sidebar, nor the File tabs, etc.
The confusion happens because some people call Color Schemes "Themes" which makes folks think that their "Theme" is going to change everything.... when technically, it's just a color scheme.
And an additional note: Themes don't automatically install for all users. When I install a Theme, I have to open my User preferences (under "preferences > Settings - User"), and then you have to add the line which says something like:
"theme": "Theme-Name.sublime-theme"
(where "Theme-Name" is the name of your theme).
This is different than just activating a color scheme. If you've chosen a color scheme via the dropdown menus in Sublime Text, you will see a line in there like this:
"color_scheme": "Packages/Color-Scheme-Name.tmTheme"
(where "Color-Scheme-Name" is the name of your color scheme).
I have got the same error, but in my case I wrote class names for carousel item as .carousel-item the bootstrap.css is referring .item. SO ERROR solved. carosel-item is renamed to item
<div class="carousel-item active"></div>
RENAMED To the following:
<div class="item active"></div>
Runtime runtime = Runtime.getRuntime();
try {
Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
InputStream is = p1.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
} catch(IOException ioException) {
System.out.println(ioException.getMessage() );
}
Not Just HTML, Using atom-beautify
- Package for Atom, you can format code for HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more) in Atom within a matter of seconds.
To Install the atom-beautify
package :
Install Packages & Themes
. A Install Package window comes up.Beautify
package, you will see a lot of beautify packages. Install any. I will recommend for atom-beautify
.To Format text Using atom-beautify
:
when you return some thing, the code exits out of the loop with what ever you are returning.so, in your code, in the first iteration, name is "one"
. so, as soon as it reaches return new Text(name)
, code exits the loop with return new Text("one")
. so, try to print it or use asynchronous returns.
I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same "No module named site
" error. I've set PYTHONHOME to c:\Python27
and it's working. But the mystery remains why this is now needed when it wasn't with previous releases. And, if it is needed, why doesn't the installer set this var?
In Excel 2007, goto Insert/Shape and pick a shape. Colour it and enter whatever text you want. Then right click on the shape and insert a hyperlink
A few tips with shapes..
If you want to easily position the shape with cells, hold down Alt when you move the shape and it will lock to the cell. If you don't want the shape to move or resize with rows/columns, right click the shape, select size and properties and choose the setting which works best.
If you have an Array of strings, you can also initialize it like this:
array = %w{1 2 3}
just separate each element with any whitespace
I think you can try
<a href="JavaScript:void(0)">link</a>
The only catch I see over here is high level browser security may prompt on executing javascript.
Though this is one of the easier way than
<a href="#" onclick="return false;">Link</a>
this should be used sparingly
Read this article for some pointers https://web.archive.org/web/20090301044015/http://blog.reindel.com/2006/08/11/a-hrefjavascriptvoid0-avoid-the-void
Self Answer (pretty much summary of other's comments and answers):
In RStudio
, Esc
works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).
If the process is ran in say ubuntu shell (and this is not R
specific), for example using:
Rscript my_file.R
Ctrl + c
kills the process
Ctrl + z
suspends the process
Within R shell, Ctrl + C
kills helps you escape it
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
For html encoding, there's cgi.escape from the standard library:
>> help(cgi.escape)
cgi.escape = escape(s, quote=None)
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.
For html decoding, I use the following:
import re
from htmlentitydefs import name2codepoint
# for some reason, python 2.5.2 doesn't have this one (apostrophe)
name2codepoint['#39'] = 39
def unescape(s):
"unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
For anything more complicated, I use BeautifulSoup.
if you use this way :
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
you will get the /tmp path when you are running program using some IDE like GoLang because the executable will save and run from /tmp
i think the best way for getting the currentWorking Directory or '.' is :
import(
"os"
"fmt"
"log"
)
func main() {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
}
the os.Getwd() function will return the current working directory. and its all without using of any external library :D
I fell into this this with using the JQLayout plugin, especially when using nested layouts and modals with Bootstrap 4.
An overriding css needs to be added to correct the behaviour,
.pane-center{
z-index:inherit !important;
}
Had this problem too and found out that the easiest way is to point your domain to the public folder and leave everything else the way they are.
PLEASE ENSURE TO USE THE RIGHT VERSION OF PHP. Save yourself some stress :)
Try this jobber
String stringy =null;
byte[] buffer = new byte[100000];
for (int i = 0; i < buffer.length; i++) {
buffer[i] =0;
}
stringy =StringUtils.toAsciiString(buffer);
This is the simple answer I can give.
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
The above answers regarding @JsonProperty
and CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
are 100% accurate, although some people (like me) might be trying to do this inside a Spring MVC application with code-based configuration. Here's sample code (that I have inside Beans.java
) to achieve the desired effect:
@Bean
public ObjectMapper jacksonObjectMapper() {
return new ObjectMapper().setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
C# 7 adds support for local functions
Here is the previous example using a local function
void Method()
{
string localFunction(string source)
{
// add your functionality here
return source ;
};
// call the inline function
localFunction("prefix");
}
Here is a simple example:
package main
import "fmt"
func plusTwo() (func(v int) (int)) {
return func(v int) (int) {
return v+2
}
}
func plusX(x int) (func(v int) (int)) {
return func(v int) (int) {
return v+x
}
}
func main() {
p := plusTwo()
fmt.Printf("3+2: %d\n", p(3))
px := plusX(3)
fmt.Printf("3+3: %d\n", px(3))
}
I was having this issue too with SQL Server 2017.
I'm on the same network as the server via VPN and can ping it. After being frustrated that no authentication method would work - I set up an SSH server on the SQL server - and I was able to connect normally. This confirmed the correct port wasn't being hit for some reason. I even created a new user accounts, domain accounts, firewall checks on both ends, etc...
The solution for me was: 1. Set Connection to strictly use TCP/IP on SSMS 2. Use a custom string to point to the default port (ex: Data Source=192.168.168.166,1433;)
All the other comments above haven't worked so far. It looks like it was mandatory to include the port (even though its default).
Another simple way without using import OS is,
outFileName="F:\\folder\\folder\\filename.txt"
outFile=open(outFileName, "w")
outFile.write("""Hello my name is ABCD""")
outFile.close()
If you are ok with manually selecting the column, you could be very fast using pick:
svn st | pick | xargs rm
Just go to any cell of the 2nd column, press c
and then hit enter
To further generalize @Alexander's example, outer
is relevant in cases where a function must compute itself on each pair of vector values:
vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
var1*var2
}
outer(vars1,vars2,mult_one)
gives:
> outer(vars1, vars2, mult_one)
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 20 40 60
[3,] 30 60 90
Sass is a language that provides features to make it easier to deal with complex styling compared to editing raw .css
. An example of such a feature is allowing definition of variables that can be re-used in different styles.
The language has two alternative syntaxes:
.scss
.sass
Either of these must be compiled to .css
files which are recognized by browsers.
See https://sass-lang.com/ for further information.
This Perl code edits your original file:
perl -i -ne 's/^\s+//;print' file
The next one makes a backup copy before editing the original file:
perl -i.bak -ne 's/^\s+//;print' file
Notice that Perl borrows heavily from sed (and AWK).
If you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isProd
to activate certain features only in certain situations and only have a single webpack.config.js file.
const isProd = (process.env.NODE_ENV === 'production');
if (isProd) {
plugins.push(new AotPlugin({
"mainPath": "main.ts",
"hostReplacementPaths": {
"environments/index.ts": "environments/index.prod.ts"
},
"exclude": [],
"tsConfigPath": "src/tsconfig.app.json"
}));
plugins.push(new UglifyJsPlugin({
"mangle": {
"screw_ie8": true
},
"compress": {
"screw_ie8": true,
"warnings": false
},
"sourceMap": false
}));
}
By the way: The DedupePlugin plugin was removed from Webpack. You should remove it from your configuration.
UPDATE:
In addition to my previous answer:
If you want to hide your code for release, try enclosejs.com. It allows you to:
You can install it with npm install -g enclose
TextView tv = new TextView(this);
tv.setText(String.valueOf(number));
or
tv.setText(""+number);
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.
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
You can do it with plain JavaScript:
alert('123-4-'.substr(0, 4)); // outputs "123-"
This returns the first four characters of your string (adjust 4
to suit your needs).
The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:
os.path.dirname(sys.argv[0])
Py2exe does not provide an __file__
variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment
Rachel's solution is working fine, although you need to use the third party script from raw.githubusercontent.com
By now there is a feature they show on the landing page when advertisng the "modular" script. You can see a legend there with this structure:
<div class="labeled-chart-container">
<div class="canvas-holder">
<canvas id="modular-doughnut" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
</div>
<ul class="doughnut-legend">
<li><span style="background-color:#5B90BF"></span>Core</li>
<li><span style="background-color:#96b5b4"></span>Bar</li>
<li><span style="background-color:#a3be8c"></span>Doughnut</li>
<li><span style="background-color:#ab7967"></span>Radar</li>
<li><span style="background-color:#d08770"></span>Line</li>
<li><span style="background-color:#b48ead"></span>Polar Area</li>
</ul>
</div>
To achieve this they use the chart configuration option legendTemplate
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
You can find the doumentation here on chartjs.org This works for all the charts although it is not part of the global chart configuration.
Then they create the legend and add it to the DOM like this:
var legend = myPie.generateLegend();
$("#legend").html(legend);
Sample See also my JSFiddle sample
You could implement a JavaScript block which contains a function with your needs.
<div style="position: absolute; left: 10px; top: 40px;">
<img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>
In BASH, you can find a user's $HOME
directory by prefixing the user's login ID with a tilde character. For example:
$ echo ~bob
This will echo out user bob
's $HOME
directory.
However, you say you want to be able to execute a script as a particular user. To do that, you need to setup sudo. This command allows you to execute particular commands as either a particular user. For example, to execute foo
as user bob
:
$ sudo -i -ubob -sfoo
This will start up a new shell, and the -i
will simulate a login with the user's default environment and shell (which means the foo
command will execute from the bob's
$HOME` directory.)
Sudo is a bit complex to setup, and you need to be a superuser just to be able to see the shudders file (usually /etc/sudoers
). However, this file usually has several examples you can use.
In this file, you can specify the commands you specify who can run a command, as which user, and whether or not that user has to enter their password before executing that command. This is normally the default (because it proves that this is the user and not someone who came by while the user was getting a Coke.) However, when you run a shell script, you usually want to disable this feature.
Running the command prompt or Powershell ISE as an administrator fixed this for me.
Both the size
attribute in HTML and the width
property in CSS will set the width of an <input>
. If you want to set the width to something closer to the width of each character use the **ch**
unit as in:
input {
width: 10ch;
}
from selenium import webdriver
PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)
chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")
Typescript
async resizeImg(file: Blob): Promise<Blob> {
let img = document.createElement("img");
img.src = await new Promise<any>(resolve => {
let reader = new FileReader();
reader.onload = (e: any) => resolve(e.target.result);
reader.readAsDataURL(file);
});
await new Promise(resolve => img.onload = resolve)
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
let MAX_WIDTH = 1000;
let MAX_HEIGHT = 1000;
let width = img.naturalWidth;
let height = img.naturalHeight;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
let result = await new Promise<Blob>(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
return result;
}
The setInterval
method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:
function intervalTrigger() {
return window.setInterval( function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000 );
};
var id = intervalTrigger();
Then to clear the interval:
window.clearInterval(id);
This is a rehash of the previous answer but it's more likely to work on different mongodb versions.
db.collection.find().limit(1).sort({$natural:-1})
I found it easier to just take over the template from Bootstrap-ui. I have left the commented HTML still in-place to show what I changed.
Overwrite their default template:
<script type="text/ng-template" id="myDlgTemplateWrapper.html">
<div tabindex="-1" role="dialog" class="modal fade" ng-class="{in: animate}"
ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)">
<!-- <div class="modal-dialog"
ng-class="{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}"
>
<div class="modal-content" modal-transclude></div>
</div>-->
<div modal-transclude>
<!-- Your content goes here -->
</div>
</div>
</script>
Modify your dialog template (note the wrapper DIVs containing "modal-dialog" class and "modal-content" class):
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-dialog {{extraDlgClass}}"
style="width: {{width}}; max-width: {{maxWidth}}; min-width: {{minWidth}}; ">
<div class="modal-content">
<div class="modal-header bg-primary">
<h3>I am a more flexible modal!</h3>
</div>
<div class="modal-body"
style="min-height: {{minHeight}}; height: {{height}}; max-height {{maxHeight}}; ">
<p>Make me any size you want</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
</div>
</script>
And then call the modal with whatever CSS class or style parameters you wish to change (assuming you have already defined "app" somewhere else):
<script type="text/javascript">
app.controller("myTest", ["$scope", "$modal", function ($scope, $modal)
{
// Adjust these with your parameters as needed
$scope.extraDlgClass = undefined;
$scope.width = "70%";
$scope.height = "200px";
$scope.maxWidth = undefined;
$scope.maxHeight = undefined;
$scope.minWidth = undefined;
$scope.minHeight = undefined;
$scope.open = function ()
{
$scope.modalInstance = $modal.open(
{
backdrop: 'static',
keyboard: false,
modalFade: true,
templateUrl: "myModalContent.html",
windowTemplateUrl: "myDlgTemplateWrapper.html",
scope: $scope,
//size: size, - overwritten by the extraDlgClass below (use 'modal-lg' or 'modal-sm' if desired)
extraDlgClass: $scope.extraDlgClass,
width: $scope.width,
height: $scope.height,
maxWidth: $scope.maxWidth,
maxHeight: $scope.maxHeight,
minWidth: $scope.minWidth,
minHeight: $scope.minHeight
});
$scope.modalInstance.result.then(function ()
{
console.log('Modal closed at: ' + new Date());
},
function ()
{
console.log('Modal dismissed at: ' + new Date());
});
};
$scope.ok = function ($event)
{
if ($event)
$event.preventDefault();
$scope.modalInstance.close("OK");
};
$scope.cancel = function ($event)
{
if ($event)
$event.preventDefault();
$scope.modalInstance.dismiss('cancel');
};
$scope.openFlexModal = function ()
{
$scope.open();
}
}]);
</script>
Add an "open" button and fire away.
<button ng-controller="myTest" class="btn btn-default" type="button" ng-click="openFlexModal();">Open Flex Modal!</button>
Now you can add whatever extra class you want, or simply change width/height sizes as necessary.
I further enclosed it within a wrapper directive, which is should be trivial from this point forward.
Cheers.
Take a look at Datejs for all those petty date related issues.. You could solve this by parseDate function too
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
Based on Justin's answer above I came up with this:
/// <summary>
/// Converts Enum Value to different Enum Value (by Value Name) See https://stackoverflow.com/a/31993512/6500501.
/// </summary>
/// <typeparam name="TEnum">The type of the enum to convert to.</typeparam>
/// <param name="source">The source enum to convert from.</param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public static TEnum ConvertTo<TEnum>(this Enum source)
{
try
{
return (TEnum) Enum.Parse(typeof(TEnum), source.ToString(), ignoreCase: true);
}
catch (ArgumentException aex)
{
throw new InvalidOperationException
(
$"Could not convert {source.GetType().ToString()} [{source.ToString()}] to {typeof(TEnum).ToString()}", aex
);
}
}
If it's a direct child you can do as below if it could be nested deeper remove the >
$("#text-field").keydown(function(event) {
if($('#popup>p.filled-text').length !== 0) {
console.log("Found");
}
});
Depends on the extension. If it's .html, you can use <?
to start and ?>
to end a comment. That's really the only alternative that I can think of. http://jsfiddle.net/SuEAW/
Late to the party but I sometimes use this one-liner as an equivalent:
((Function<Value, Key>) Value::getKey).andThen(new HashSet<>()::add)::apply
The expression is a Predicate<Value>
but since the map is inline, it works as a filter. This is of course less readable but sometimes it can be helpful to avoid the method.
WCF = Windows Communication Foundation is used to build service-oriented applications. WPF = Windows Presentation Foundation is used to write platform-independent applications.
So I've been playing around with this and it seems you need both places and js maps api activated. Then use the following:
HTML:
<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">
JS:
<script>
function initMap() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
document.getElementById("address").value = JSON.stringify(place.address_components);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
componentDidMount() {
const head = document.querySelector("head");
const script = document.createElement("script");
script.setAttribute(
"src",
"https://assets.calendly.com/assets/external/widget.js"
);
head.appendChild(script);
}
On the contrary, you should always prefer stack allocations, to the extent that as a rule of thumb, you should never have new/delete in your user code.
As you say, when the variable is declared on the stack, its destructor is automatically called when it goes out of scope, which is your main tool for tracking resource lifetime and avoiding leaks.
So in general, every time you need to allocate a resource, whether it's memory (by calling new), file handles, sockets or anything else, wrap it in a class where the constructor acquires the resource, and the destructor releases it. Then you can create an object of that type on the stack, and you're guaranteed that your resource gets freed when it goes out of scope. That way you don't have to track your new/delete pairs everywhere to ensure you avoid memory leaks.
The most common name for this idiom is RAII
Also look into smart pointer classes which are used to wrap the resulting pointers on the rare cases when you do have to allocate something with new outside a dedicated RAII object. You instead pass the pointer to a smart pointer, which then tracks its lifetime, for example by reference counting, and calls the destructor when the last reference goes out of scope. The standard library has std::unique_ptr
for simple scope-based management, and std::shared_ptr
which does reference counting to implement shared ownership.
Many tutorials demonstrate object instantiation using a snippet such as ...
So what you've discovered is that most tutorials suck. ;) Most tutorials teach you lousy C++ practices, including calling new/delete to create variables when it's not necessary, and giving you a hard time tracking lifetime of your allocations.
#!/usr/bin/python
import sys
col = int(sys.argv[1]) - 1
for line in sys.stdin:
columns = line.split()
try:
print(columns[col])
except IndexError:
# ignore
pass
Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-
ls -lh | co 5
Though this is old, I think question is valid even today
My suspicion is that aud should refer to the resource server(s), and the client_id should refer to one of the client applications recognized by the authentication server
Yes, aud should refer to token consuming party. And client_id refers to token obtaining party.
In my current case, my resource server is also my web app client.
In the OP's scenario, web app and resource server both belongs to same party. So this means client and audience to be same. But there can be situations where this is not the case.
Think about a SPA which consume an OAuth protected resource. In this scenario SPA is the client. Protected resource is the audience of access token.
This second scenario is interesting. There is a working draft in place named "Resource Indicators for OAuth 2.0" which explain where you can define the intended audience in your authorisation request. So the resulting token will restricted to the specified audience. Also, Azure OIDC use a similar approach where it allows resource registration and allow auth request to contain resource parameter to define access token intended audience. Such mechanisms allow OAuth adpotations to have a separation between client and token consuming (audience) party.
If you are using Bootstrap 4, you can simple use a color utility class (e.g. text-success
, text-danger
, etc... ).
You can also create your own classes (e.g. text-my-own-color
)
Both options are shown in the example below, run the code snippet to see a live demo.
.text-my-own-color {
color: #663300 !important; // Define your own color in your CSS
}
.text-my-own-color:hover, .text-my-own-color:active {
color: #664D33 !important; // Define your own color's darkening/lightening in your CSS
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="navbar-collapse">
<ul class="nav pull-right">
<!-- Bootstrap's color utility class -->
<li class="active"><a class="text-success" href="#">? ???</a></li>
<!-- Bootstrap's color utility class -->
<li><a class="text-danger" href="#">??? ??? ????????</a></li>
<!-- Bootstrap's color utility class -->
<li><a class="text-warning" href="#">????</a></li>
<!-- Custom color utility class -->
<li><a class="text-my-own-color" href="#">????????</a></li>
</ul>
</div>
_x000D_
Incrementing dates can be accomplished using timedelta objects:
import datetime
datetime.datetime.now() + datetime.timedelta(days=1)
Look up timedelta objects in the Python docs: http://docs.python.org/library/datetime.html
If you are using Express as back-end you just have to install cors and import and use it in app.use(cors());. If it is not resolved then try switching ports. It will surely resolve after switching ports
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
If you're using dom4j, you can just do:
Document document = DocumentHelper.parseText(text);
(dom4j now found here: https://github.com/dom4j/dom4j)
I use a very old java. Jdk 1.4.08 and I had the same issue. The Node
class for me did not had the getTextContent()
method. I had to use Node.getFirstChild().getNodeValue()
instead of Node.getNodeValue()
to get the value of the node. This fixed for me.
Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http
it returns observable instead of promise, like you did
return this.http
.get(this.configEndPoint)
.map(res => res.json());
then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()
.map() is used to convert the observable (received from http request)to any form like .json(), .text()
as stated in Angular's official website,
.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view
this.myService.getConfig().subscribe(res => {
console.log(res);
this.data = res;
});
The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:
DECLARE @SQL NVARCHAR(100)
SET @SQL = N'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL
Simply put, an IDE offers additional time-saving features over a simple editor.
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
According to MSDN
result is the number of lines affected, and since your query is select
no lines are affected (i.e. inserted, deleted or updated) anyhow.
If you want to return a single row of the query, use ExecuteScalar()
instead of ExecuteNonQuery()
:
int result = (int) (command.ExecuteScalar());
However, if you expect many rows to be returned, ExecuteReader()
is the only option:
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
int result = reader.GetInt32(0);
...
}
}
I find it can be annoying and error prone to do a lot of these .stat.exists
type checks. For example they require extra care to get check mode (--check
) working.
Many answers here suggest
However, sometimes this is a code smell so always look for better ways to use Ansible, specifically there are many advantages to using the correct module. e.g.
- name: install ntpdate
package:
name: ntpdate
or
- file:
path: /etc/file.txt
owner: root
group: root
mode: 0644
But when it is not possible use one module, also investigate if you can register and check the result of a previous task. e.g.
# jmeter_version: 4.0
- name: Download Jmeter archive
get_url:
url: "http://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{{ jmeter_version }}.tgz"
dest: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
checksum: sha512:eee7d68bd1f7e7b269fabaf8f09821697165518b112a979a25c5f128c4de8ca6ad12d3b20cd9380a2b53ca52762b4c4979e564a8c2ff37196692fbd217f1e343
register: download_result
- name: Extract apache-jmeter
unarchive:
src: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
dest: "/opt/jmeter/"
remote_src: yes
creates: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}"
when: download_result.state == 'file'
Note the when:
but also the creates:
so --check
doesn't error out
I mention this because often these less-than-ideal practices come in pairs i.e. no apt/yum package so we have to 1) download and 2) unzip
Hope this helps
Best implementation depends of what you are attempting to do exactly. Nadeem_MK gives you a valid one. Know you can also:
raise the Button2_Click
event using PerformClick()
method:
Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
'do stuff
Me.Button2.PerformClick()
End Sub
attach the same handler to many buttons:
Private Sub Button1_Click(sender As Object, e As System.EventArgs) _
Handles Button1.Click, Button2.Click
'do stuff
End Sub
call the Button2_Click
method using the same arguments than Button1_Click(...)
method (IF you need to know which is the sender, for example) :
Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
'do stuff
Button2_Click(sender, e)
End Sub
You MUST add below part to enable NameVirtualHost
functionality with given IP.
NameVirtualHost IP_Address:443
its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".
and install the package. it will resolve the issue for me.
Making more general the @showdev answer.
var getObjectByValue = function (array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
};
Example:
getObjectByValue(data, "code", "DZ" );
Given this route
app.get('/hi/:param1', function(req,res){} );
and given this URL
http://www.google.com/hi/there?qs1=you&qs2=tube
You will have:
req.query
{
qs1: 'you',
qs2: 'tube'
}
req.params
{
param1: 'there'
}
Why not just performing the calculation in your SQL?
SELECT
t.TenantName
, t.CarPlateNumber
, t.CarColor
, t.Sex
, t.SSNO
, t.Phone
, t.Memo
, u.UnitNumber
, p.PropertyName
, trans.TenantBalance
FROM tblTenant t
LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
LEFT JOIN tblProperty p ON u.PropertyID = p.ID
INNER JOIN (
SELECT tenant.ID AS TenantID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance
FROM tblTenant tenant
LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
GROUP BY tenant.ID
) trans ON trans.ID = t.ID
ORDER BY
p.PropertyName
, t.CarPlateNumber
If you don't mind using 3rd Party Libraries cyclops-react has an extended Stream type that will allow you to do just that via the append / prepend operators.
Individual values, arrays, iterables, Streams or reactive-streams Publishers can be appended and prepended as instance methods.
Stream stream = ReactiveSeq.of(1,2)
.filter(x -> x!=0)
.append(ReactiveSeq.of(3,4))
.filter(x -> x!=1)
.append(5)
.filter(x -> x!=2);
[Disclosure I am the lead developer of cyclops-react]
It depends a bit on your needs. Some toolkits are better at drawing, others are better for writing text. Cairo has a pretty good for drawing (it support a wide range of screen and file types, including pdf), but it may not be ideal for good typography.
This code removes the inner html of an element from the dom when the debugger is open (tested in Chrome and IE)
var currentInnerHtml;
var element = new Image();
var elementWithHiddenContent = document.querySelector("#element-to-hide");
var innerHtml = elementWithHiddenContent.innerHTML;
element.__defineGetter__("id", function() {
currentInnerHtml = "";
});
setInterval(function() {
currentInnerHtml = innerHtml;
console.log(element);
console.clear();
elementWithHiddenContent.innerHTML = currentInnerHtml;
}, 1000);
Here #element-to-hide
is the id of element you want to hide.
It is a hack, but I hope it helps you.
Don't be so verbose. It's Javascript. Use a Naming Convention.
After years of working in es6 classes, I recently started work on an es5 project (using requireJS which is already very verbose-looking). I've been over and over all the strategies mentioned here and it all basically boils down to use a naming convention:
private
. Other developers entering Javascript will know this upfront. Therefore, a simple naming convention is more than sufficient. A simple naming convention of prefixing with an underscore solves the problem of both private properties and private methods. my-tooltip.js
define([
'tooltip'
],
function(
tooltip
){
function MyTooltip() {
// Later, if needed, we can remove the underscore on some
// of these (make public) and allow clients of our class
// to set them.
this._selector = "#my-tooltip"
this._template = 'Hello from inside my tooltip!';
this._initTooltip();
}
MyTooltip.prototype = {
constructor: MyTooltip,
_initTooltip: function () {
new tooltip.tooltip(this._selector, {
content: this._template,
closeOnClick: true,
closeButton: true
});
}
}
return {
init: function init() {
new MyTooltip(); // <-- Our constructor adds our tooltip to the DOM so not much we need to do after instantiation.
}
// You could instead return a new instantiation,
// if later you do more with this class.
/*
create: function create() {
return new MyTooltip();
}
*/
}
});
For me the Anonymous User access was fine at the server level, but varied at just one of my "virtual" folders.
Took me quite a bit of foundering about and then some help from a colleague to learn that IIS has "authentication" settings at the virtual folder level too - hopefully this helps someone else with my predicament.
Try this:
Import RouterModule
into your app.module.ts
import { RouterModule } from '@angular/router';
Add RouterModule
into your imports []
like this:
imports: [ RouterModule, ]
For the ones facing issue with IntelliJ IDEA 13, uninstall Build Tools 19.
I got solution after working whole day on it. It is little hacky solution Added span inside td tag
<td><span><%= item.StartICDate %></span></td>.
Date format which Im using is dd/MM/YYYY. Tested in Datatables1.9.0
This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding
ABS(CHARINDEX(' ', PostCode ) -1))
which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1)
is a -ve value. Correct me if I'm wrong!
You have multiple options. Two options are the following.
numpy.sum(boolarr)
numpy.count_nonzero(boolarr)
Here's an example:
>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False, True],
[ True, False, True],
[ True, False, True]], dtype=bool)
>>> np.sum(boolarr)
5
Of course, that is a bool
-specific answer. More generally, you can use numpy.count_nonzero
.
>>> np.count_nonzero(boolarr)
5
TypeA[] array = (TypeA[]) a.toArray();
If you are using jQuery then by using plugin formInteract, you just need to do this:
// Just keep the HTML as it is.
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
At bottom of the page just include this plugin file and write this code:
// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();
search.getAjax("http://www.myurl.com/search/", function(rsp){
// Now do whatever you want to with your response
});
Or if using a parameterized URL then use this:
$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
// Now do work with your response;
})
Here is the link to project https://bitbucket.org/ranjeet1985/forminteract
You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more. You can see some example of code in the index.html file of the project.
Of course I am the author of this project and all are welcome to make it better.
i was surprised to find that when i had a class that was closed it produced this vague error. changing it to a open class resolved the issue.
before:
class DefaultSubscriber<T> : Observer<T> {//...
}
after:
open class DefaultSubscriber<T> : Observer<T> {//...
}
$ date
Wed 24 Apr 2019 09:54:53 AM PDT
$ rsync --version
rsync version 3.1.3 protocol version 31
...
Syntax: rsync <file_/_folder_list> <source> <target>
Folder names (here, WITH a trailing /
; e.g. Cancer - Evolution/
) are in a folder list file (e.g.: cm_folder_list_test):
# /mnt/Vancouver/projects/ie/claws/data/cm_folder_list_test
# test file: 2019-04-24
Cancer/
Cancer - Evolution/
Cancer - Genomic Variants/
Cancer - Metastasis (EMT Transition ...)/
Cancer Pathways, Networks/
Catabolism - Autophagy; Phagosomes; Mitophagy/
Catabolism - Lysosomes/
If you don't include those trailing /
, the rsync'd target folders are created, but are empty.
Those folder names are appended to the rest of their path (/home/victoria/Mail/2_RESEARCH - NEWS
), thus providing the complete folder path to rsync; e.g.: /home/victoria/Mail/2_RESEARCH - NEWS/Cancer - Evolution/
.
Note that you also need to use --files-from=
..., NOT --include-from=
...
rsync -aqP --delete --files-from=/mnt/Vancouver/projects/ie/claws/data/cm_folder_list_test "/home/victoria/Mail/2_RESEARCH - NEWS" $IN/
(In my BASH script, I defined variable $IN
as follows.)
BASEDIR="/mnt/Vancouver/projects/ie/claws"
IN=$BASEDIR/data/test/input
rsync options used:
-a : archive: equals -rlptgoD (no -H,-A,-X)
-r : recursive
-l : copy symlinks as symlinks
-p : preserve permissions
-t : preserve modification times
-g : preserve group
-o : preserve owner (super-user only)
-D : same as --devices --specials
-q : quiet (https://serverfault.com/questions/547106/run-totally-silent-rsync)
--delete
This tells rsync to delete extraneous files from the RECEIVING SIDE (ones
that AREN’T ON THE SENDING SIDE), but only for the directories that are
being synchronized. You must have asked rsync to send the whole directory
(e.g. "dir" or "dir/") without using a wildcard for the directory’s contents
(e.g. "dir/*") since the wildcard is expanded by the shell and rsync thus
gets a request to transfer individual files, not the files’ parent directory.
Files that are excluded from the transfer are also excluded from being
deleted unless you use the --delete-excluded option or mark the rules as
only matching on the sending side (see the include/exclude modifiers in the
FILTER RULES section). ...
Adds vertical column guides to the Visual Studio text editor. This version is for Visual Studio 2012, Visual Studio 2013 or Visual Studio 2015.
See the plugin.
Use the join
method from the Array type.
a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();
The join
method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.
This error can also show up if there are parts in your string that json.loads()
does not recognize. An in this example string, an error will be raised at character 27 (char 27)
.
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
My solution to this would be to use the string.replace()
to convert these items to a string:
import json
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
string = string.replace("False", '"False"')
dict_list = json.loads(string)
The summary is that I found ECMerge to be a great, though commercial product. http://www.elliecomputing.com/products/merge_overview.asp
I also agree with MrTelly that Ultracompare is very good. One nice feature is that it will compare RTF and Word docs, which is handy when you end up programming in word with the sales guys and they don't manage their docs correctly.
I find solution that instead of using ListBox I used ListView.It allows to change list items BackColor.
private void listView1_Refresh()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
listView1.Items[i].BackColor = Color.Red;
for (int j = 0; j < existingStudents.Count; j++)
{
if (listView1.Items[i].ToString().Contains(existingStudents[j]))
{
listView1.Items[i].BackColor = Color.Green;
}
}
}
}
Use Load function
load(filename)
You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.
Example : mongo localhost:27017/mydb myfile.js
This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.
For loading external js you can write
load("/data/db/scripts/myloadjs.js")
Suppose we have two js file myFileOne.js and myFileTwo.js
myFileOne.js
print('From file 1');
load('myFileTwo.js'); // Load other js file .
myFileTwo.js
print('From file 2');
MongoShell
>mongo myFileOne.js
Output
From file 1
From file 2
You can use this to delete ALL Files Inside a Folder and Subfolders:
DEL "C:\Folder\*.*" /S /Q
Or use this to Delete Certain File Types Only:
DEL "C:\Folder\*.mp4" /S /Q
DEL "C:\Folder\*.dat" /S /Q
tl;dr Remove all unused modules which have a dependency on the support library from your settings.gradle
.
Long version:
In our case we had declared the support library as a dependency for all of our modules (one app module and multiple library modules) in a common.gradle
file which is imported by every module. However there was one library module which wasn't declared as a dependency for any other module and therefore wasn't build. In every few syncs Android Studio would pick that exact module as the one where to look for the support library (that's why it appeared to happen randomly for us). As this module was never used it never got build which in turn caused the jar file not being in the intermediates folder of the module.
Removing this library module from settings.gradle
and syncing again fixed the problem for us.
The most recent versions of hibernate JPA provider applies the bean validation constraints (JSR 303) like @NotNull
to DDL by default (thanks to hibernate.validator.apply_to_ddl property
defaults to true
). But there is no guarantee that other JPA providers do or even have the ability to do that.
You should use bean validation annotations like @NotNull
to ensure, that bean properties are set to a none-null value, when validating java beans in the JVM (this has nothing to do with database constraints, but in most situations should correspond to them).
You should additionally use the JPA annotation like @Column(nullable = false)
to give the jpa provider hints to generate the right DDL for creating table columns with the database constraints you want. If you can or want to rely on a JPA provider like Hibernate, which applies the bean validation constraints to DDL by default, then you can omit them.
parseInt()
:
NaN
will be returned.parseInt()
function encounters a non numerical value, it will cut off the rest of input string and only parse the part until the non numerical value.undefined
or 0, JS will assume the following:
ES5
specifies that 10 should be used then. However, this is not supported by all browsers, therefore always specify radix if your numbers can begin with a 0.Number()
:
Number()
constructor can convert any argument input into a number. If the Number()
constructor cannot convert the input into a number, NaN
will be returned.Number()
constructor can also handle hexadecimal number, they have to start with 0x
.console.log(parseInt('0xF', 16)); // 15_x000D_
_x000D_
// z is no number, it will only evaluate 0xF, therefore 15 is logged_x000D_
console.log(parseInt('0xFz123', 16));_x000D_
_x000D_
// because the radix is 10, A is considered a letter not a number (like in Hexadecimal)_x000D_
// Therefore, A will be cut off the string and 10 is logged_x000D_
console.log(parseInt('10A', 10)); // 10_x000D_
_x000D_
// first character isnot a number, therefore parseInt will return NaN_x000D_
console.log(parseInt('a1213', 10));_x000D_
_x000D_
_x000D_
console.log('\n');_x000D_
_x000D_
_x000D_
// start with 0X, therefore Number will interpret it as a hexadecimal value_x000D_
console.log(Number('0x11'));_x000D_
_x000D_
// Cannot be converted to a number, NaN will be returned, notice that_x000D_
// the number constructor will not cut off a non number part like parseInt does_x000D_
console.log(Number('123A'));_x000D_
_x000D_
// scientific notation is allowed_x000D_
console.log(Number('152e-1')); // 15.21
_x000D_
If you are designing your Javafx application using SceneBuilder
then use -fx-text-fill
(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield
.
I came here for the same problem and solved it in this way.
Spaces are used for separating Arguments. In your case C:\Program becomes argument. If your file path contains spaces then add Double quotation marks. Then cmd will recognize it as single argument.
Here is a full-fledged css solution inspired by Bulma. Just add
.button {
display: inline-flex;
align-items: center;
justify-content: center;
position: relative;
min-width: 200px;
max-width: 100%;
min-height: 40px;
text-align: center;
cursor: pointer;
}
@-webkit-keyframes spinAround {
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes spinAround {
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.button.is-loading {
text-indent: -9999px;
box-shadow: none;
font-size: 1rem;
height: 2.25em;
line-height: 1.5;
vertical-align: top;
padding-bottom: calc(0.375em - 1px);
padding-left: 0.75em;
padding-right: 0.75em;
padding-top: calc(0.375em - 1px);
white-space: nowrap;
}
.button.is-loading::after {
-webkit-animation: spinAround 500ms infinite linear;
animation: spinAround 500ms infinite linear;
border: 2px solid #dbdbdb;
border-radius: 290486px;
border-right-color: transparent;
border-top-color: transparent;
content: "";
display: block;
height: 1em;
position: relative;
width: 1em;
}
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
For me, some of the answers mentioned earlier were helpful from understanding point of view, but those didn't solve my problem.
So this is what I did to solve issue.
Bundler -v
command). I had version 1.12.5 installedgem install bundler -v '1.11.2'
) The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...