have you tried SQL> alter database open; ? after first login?
you need to replace path with the help of replace function.
update table_name set column_name = replace(column_name, 'oldstring', 'newstring')
here column_name
refers to that column which you want to change.
Hope it will work.
You can use this sql statement to get the history for any date:
SELECT * FROM V$SQL V where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss') > sysdate - 60
I would suggest Jetbrain's IDE: DataGrip https://www.jetbrains.com/datagrip/
set ORACLE_SID=<YOUR_SID>
sqlplus "/as sysdba"
alter system disable restricted session;
or maybe
shutdown abort;
or maybe
lsnrctl stop
lsnrctl start
To answer the question asked, here is the most accurate SQL to accomplish the job, you can combine it with PL/SQL loop to actually run kill statements:
select ses.USERNAME,
substr(MACHINE,1,10) as MACHINE,
substr(module,1,25) as module,
status,
'alter system kill session '''||SID||','||ses.SERIAL#||''';' as kill
from v$session ses LEFT OUTER JOIN v$process p ON (ses.paddr=p.addr)
where schemaname <> 'SYS'
and not exists
(select 1
from DBA_ROLE_PRIVS
where GRANTED_ROLE='DBA'
and schemaname=grantee)
and machine!='yourlocalhostname'
order by LAST_CALL_ET desc;
In Oracle 11g, To get the complete date from the Timestamp, use this-
Select TRUNC(timestamp) FROM TABLE_NAME;
To get the Year from the Timestamp, use this-
Select EXTRACT(YEAR FROM TRUNC(timestamp)) from TABLE_NAME;
To get the Month from the Timestamp, use this-
Select EXTRACT(MONTH FROM TRUNC(timestamp)) from TABLE_NAME;
To get the Day from the Timestamp, use this-
Select EXTRACT(DAY FROM TRUNC(timestamp)) from TABLE_NAME;
There is something wrong with your code.
position : absolute
makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll
This can be solved with position : fixed
This property will make the element position fixed and still relative to the scroll.
Or
You can check it out Here
Random character:
String.fromCharCode(i); //where is an int
Random int:
Math.floor(Math.random()*100);
Put it all together:
function randomNum(hi){
return Math.floor(Math.random()*hi);
}
function randomChar(){
return String.fromCharCode(randomNum(100));
}
function randomString(length){
var str = "";
for(var i = 0; i < length; ++i){
str += randomChar();
}
return str;
}
var RandomString = randomString(32); //32 length string
At least the way I've done this is as follows:
If you have a nested src tree (say com.test.myclass.MyClass) and you are compiling from a root directory you need to do the following:
1) when you create the jar (usually put this in a script): jar -cvfm my.jar com/test/myclass/manifest.txt com/test/myclass/MyClass.class
2) The manifest should look like:
Mainfest-version: 1.0 Main-Class: com.test.myclass.MyClass Class-Path: . my.jar
3) Now you can run the jar from anywhere like this:
java -jar my.jar
Hope this helps someone
You can add all pages with this code:
JS code:
/* Top btn */
$(window).scroll(function() {
if ($(this).scrollTop()) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
var top_btn_html="<topbtn id='toTop' onclick='gotoTop()'>↑</topbtn>";
$('document').ready(function(){
$("body").append(top_btn_html);
});
function gotoTop(){
$("html, body").animate({scrollTop: 0}, 500);
}
/* Top btn */
CSS CODE
/*Scrool top btn*/
#toTop{
position: fixed;
z-index: 10000;
opacity: 0.5;
right: 5px;
bottom: 10px;
background-color: #ccc;
border: 1px solid black;
width: 40px;
height: 40px;
border-radius: 20px;
color: black;
font-size: 22px;
font-weight: bolder;
text-align: center;
vertical-align: middle;
}
how do I programmatically add an event to the user's calendar?
Which calendar?
Is there a common API they all share?
No, no more than there is a "common API they all share" for Windows calendar apps. There are some common data formats (e.g., iCalendar) and Internet protocols (e.g., CalDAV), but no common API. Some calendar apps don't even offer an API.
If there are specific calendar applications you wish to integrate with, contact their developers and determine if they offer an API. So, for example, the Calendar application from the Android open source project, that Mayra cites, offers no documented and supported APIs. Google has even explicitly told developers to not use the techniques outlined in the tutorial Mayra cites.
Another option is for you to add events to the Internet calendar in question. For example, the best way to add events to the Calendar application from the Android open source project is to add the event to the user's Google Calendar via the appropriate GData APIs.
UPDATE
Android 4.0 (API Level 14) added a CalendarContract
ContentProvider
.
What you can do too is usingtype()
Example:
if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"
I've fixed this issue by doing, step by step:
node_modules
package-lock.json
, npm --depth 9999 update
npm install
I've tried so many solutions, some of them works on Windows XP and all of them did NOT work on Windows 7. After all I write a simple method to do so.
private void GoFullscreen(bool fullscreen)
{
if (fullscreen)
{
this.WindowState = FormWindowState.Normal;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Bounds = Screen.PrimaryScreen.Bounds;
}
else
{
this.WindowState = FormWindowState.Maximized;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
}
}
the order of code is important and will not work if you change the place of WindwosState and FormBorderStyle.
One of the advantages of this method is leaving the TOPMOST on false that allow other forms to come over the main form.
It absolutely solved my problem.
To add global include path use custom command for qmake in Projects/Build/Build Steps section in "Additional arguments" like this:
"QT+=your_qt_modules" "DEFINES+=your_defines"
I think that you can use any command from *.pro files in that way.
If you are using Jenkins pipelines and want to checkout a specific tag (eg: a TAG
parameter of your build), here is what you can do:
stage('Checkout') {
steps {
checkout scm: [$class: 'GitSCM', userRemoteConfigs: [[url: 'YOUR_GIT_REPO_URL.git', credentialsId: 'YOUR_GIT_CREDENTIALS_ID' ]], branches: [[name: 'refs/tags/${TAG}']]], poll: false
}
}
For SSIS you could go with:
RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())
Expression builder screen:
default.aspx code
<asp:FileUpload runat="server" id="fileUpload1" Multiple="Multiple">
</asp:FileUpload>
<asp:Button runat="server" Text="Upload Files" id="uploadBtn"/>
default.aspx.vb
Protected Sub uploadBtn_Click(sender As Object, e As System.EventArgs) Handles uploadBtn.Click
Dim ImageFiles As HttpFileCollection = Request.Files
For i As Integer = 0 To ImageFiles.Count - 1
Dim file As HttpPostedFile = ImageFiles(i)
file.SaveAs(Server.MapPath("Uploads/") & file.FileName)
Next
End Sub
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
Thanks to Andrey-Egorov and this answer, I've managed to do it in C#
IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
You can use the start command to spawn background processes without launching new windows:
start /b foo.exe
The new process will not be interruptable with CTRL-C; you can kill it only with CTRL-BREAK (or by closing the window, or via Task Manager.)
I think these could be helpful for you .
Using a SELECT
statement with a simple CASE
expression
Within a SELECT
statement, a simple CASE
expression allows for only an equality check; no other comparisons are made. The following example uses the CASE
expression to change the display of product line categories to make them more understandable.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
Using a SELECT
statement with a searched CASE
expression
Within a SELECT
statement, the searched CASE
expression allows for values to be replaced in the result set based on comparison values. The following example displays the list price as a text comment based on the price range for a product.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Using CASE
in an ORDER BY
clause
The following examples uses the CASE
expression in an ORDER BY
clause to determine the sort order of the rows based on a given column value. In the first example, the value in the SalariedFlag column of the HumanResources.Employee table is evaluated. Employees that have the SalariedFlag set to 1 are returned in order by the BusinessEntityID in descending order. Employees that have the SalariedFlag set to 0 are returned in order by the BusinessEntityID in ascending order. In the second example, the result set is ordered by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows.
SELECT BusinessEntityID, SalariedFlag
FROM HumanResources.Employee
ORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC
,CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END;
GO
SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionName
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL
ORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName
ELSE CountryRegionName END;
Using CASE
in an UPDATE
statement
The following example uses the CASE
expression in an UPDATE
statement to determine the value that is set for the column VacationHours for employees with SalariedFlag set to 0. When subtracting 10 hours from VacationHours results in a negative value, VacationHours is increased by 40 hours; otherwise, VacationHours is increased by 20 hours. The OUTPUT
clause is used to display the before and after vacation values.
USE AdventureWorks2012;
GO
UPDATE HumanResources.Employee
SET VacationHours =
( CASE
WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40
ELSE (VacationHours + 20.00)
END
)
OUTPUT Deleted.BusinessEntityID, Deleted.VacationHours AS BeforeValue,
Inserted.VacationHours AS AfterValue
WHERE SalariedFlag = 0;
Using CASE
in a HAVING
clause
The following example uses the CASE
expression in a HAVING
clause to restrict the rows returned by the SELECT
statement. The statement returns the the maximum hourly rate for each job title in the HumanResources.Employee table. The HAVING
clause restricts the titles to those that are held by men with a maximum pay rate greater than 40 dollars or women with a maximum pay rate greater than 42 dollars.
USE AdventureWorks2012;
GO
SELECT JobTitle, MAX(ph1.Rate)AS MaximumRate
FROM HumanResources.Employee AS e
JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityID
GROUP BY JobTitle
HAVING (MAX(CASE WHEN Gender = 'M'
THEN ph1.Rate
ELSE NULL END) > 40.00
OR MAX(CASE WHEN Gender = 'F'
THEN ph1.Rate
ELSE NULL END) > 42.00)
ORDER BY MaximumRate DESC;
For more details description of these example visit the source.
Also visit here and here for some examples with great details.
Both Redirect::to()
and Redirect::away()
should work.
Difference
Redirect::to() does additional URL checks and generations. Those additional steps are done in Illuminate\Routing\UrlGenerator and do the following, if the passed URL is not a fully valid URL (even with protocol):
Determines if URL is secure rawurlencode() the URL trim() URL
src : https://medium.com/@zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f
You can do this
.footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: 1rem;
text-align: center;
}
It's not a good idea to uninstall 1.8.6 if it's in /usr/bin
. That is owned by the OS and is expected to be there.
If you put /usr/local/bin
in your PATH before /usr/bin
then things you have installed in /usr/local/bin
will be found before any with the same name in /usr/bin
, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin
in your #! interpreter invocation line at the top of your code.
@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.
If you just want to run a function for testing purposes, you can use the Immediate Window in Access.
Press Ctrl + G
in the VBA editor to open it.
Then you can run your functions like this:
?YourFunction("parameter")
YourSub "parameter"
?variable
private void BindDataBInfo()
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
Literal1.Text = "<table border=\"1\" cellspacing=\"3\" cellpadding=\"2\">";
foreach (string key in browser.Capabilities.Keys)
{
Literal1.Text += "<tr><td>" + key + "</td><td>" + browser[key] + "</tr>";
}
Literal1.Text += "</table>";
browser = null;
}
A different approach is to clean the value of the password field on page load instead of trying to prevent it from auto-filling.
With jQuery simply add something like:
$(function() { $('input[type="password"]').val(''); });
Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.
<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->
Otherwise, you can put !important
at the end of your CSS like this: color:#ffffff!important;
but I would advise against using !important
at all costs.
use <meta http-equiv="X-Frame-Options" content="allow">
in the one to show in the iframe to allow it.
The map
function can be very useful here.
Using map
we can apply any function to each element of an iterable.
Python 3.x
>>> def my_mul(x,y):
... return x*y
...
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>>
>>> list(map(my_mul,a,b))
[2, 6, 12, 20]
>>>
Of course:
map(f, iterable)
is equivalent to
[f(x) for x in iterable]
So we can get our solution via:
>>> [my_mul(x,y) for x, y in zip(a,b)]
[2, 6, 12, 20]
>>>
In Python 2.x map()
means: apply a function to each element of an iterable and construct a new list.
In Python 3.x, map
construct iterators instead of lists.
Instead of my_mul
we could use mul
operator
Python 2.7
>>>from operator import mul # import mul operator
>>>a = [1,2,3,4]
>>>b = [2,3,4,5]
>>>map(mul,a,b)
[2, 6, 12, 20]
>>>
Python 3.5+
>>> from operator import mul
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>> [*map(mul,a,b)]
[2, 6, 12, 20]
>>>
Please note that since map()
constructs an iterator we use *
iterable unpacking operator to get a list.
The unpacking approach is a bit faster then the list
constructor:
>>> list(map(mul,a,b))
[2, 6, 12, 20]
>>>
I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:
select min(Id), distinct MailId, EmailAddress, Name
from yourTableName
group by MailId, EmailAddress, Name
I see that I am using a GROUP BY clause
but you still won't have two rows against any particular MailId
.
If you want to install Python 2.7 on Oracle Linux, you can proceed as follows:
Enable the Software Collection in /etc/yum.repos.d/public-yum-ol6.repo.
vim /etc/yum.repos.d/public-yum-ol6.repo
[public_ol6_software_collections]
name=Software Collection Library release 1.2 packages for Oracle Linux 6
(x86_64)
baseurl=[http://yum.oracle.com/repo/OracleLinux/OL6/SoftwareCollections12/x86_64/][1]
gpgkey=file:[///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle][2]
gpgcheck=1
enabled=1 <==============change from 0 to 1
After making this change to the yum repository you can simply run the yum command to install the Python:
yum install gcc libffi libffi-devel python27 python27-python-devel openssl-devel python27-MySQL-python
edit bash_profile with follow variables:
vim ~/.bash_profile
PATH=$PATH:$HOME/bin:/opt/rh/python27/root/usr/bin export PATH
LD_LIBRARY_PATH=/opt/rh/python27/root/usr/lib64 export LD_LIBRARY_PATH
PKG_CONFIG_PATH=/opt/rh/python27/root/usr/lib64/pkgconfig export PKG_CONFIG_PATH
Now you can use python2.7 and pip for install Python modules:
/opt/rh/python27/root/usr/bin/pip install pynacl
/opt/rh/python27/root/usr/bin/python2.7 --version
I didn't like that the map would load only after the hidden div had become visible. In a carousel, for example, that doesn't really work.
This my solution is to add class to the hidden element to unhide it and hide it with position absolute instead, then render the map, and remove the class after map load.
Tested in Bootstrap Carousel.
HTML
<div class="item loading"><div id="map-canvas"></div></div>
CSS
.loading { display: block; position: absolute; }
JS
$(document).ready(function(){
// render map //
google.maps.event.addListenerOnce(map, 'idle', function(){
$('.loading').removeClass('loading');
});
}
I prefer
l.at(4)= -1;
while [4] is your index
I'm using Ubuntu and I tried as @Arie said above but with this line only in terminal:
sudo apt-get install tcl-dev tk-dev python-tk python3-tk
And it worked!
I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().
If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.
If you provide proper date format it should work please recheck once if you have given correct date format in insert values
200
Ugh... (309, 400, 403, 409, 415, 422)... a lot of answers trying to guess, argue and standardize what is the best return code for a successful HTTP request but a failed REST call.
It is wrong to mix HTTP status codes and REST status codes.
However, I saw many implementations mixing them, and many developers may not agree with me.
HTTP return codes are related to the HTTP Request
itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.
For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:
"403 Forbidden/Access Denied" may mean:
And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...
From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.
If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the HTTP server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as HTTP result, right?
Instead of this you may return 200 HTTP code with some options:
Also, some internet providers may intercept your requests and return you a 404 HTTP code. This does not means that your data are not found, but it's something wrong at transport level.
From Wiki:
In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".
Why not simply answer with something like this?
{
"result": false,
"error": {"code": 102, "message": "Validation failed: Wrong NAME."}
}
Google always returns 200 as status code in their Geocoding API, even if the request logically fails: https://developers.google.com/maps/documentation/geocoding/intro#StatusCodes
Facebook always return 200 for successful HTTP requests, even if REST request fails: https://developers.facebook.com/docs/graph-api/using-graph-api/error-handling
It's simple, HTTP status codes are for HTTP requests. REST API is Your, define Your status codes.
Putting this code at the end of your body
tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.
<script>
(function(){
var forms = document.forms || [];
for(var i = 0; i < forms.length; i++){
for(var j = 0; j < forms[i].length; j++){
if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
forms[i][j].focus();
return;
}
}
}
})();
</script>
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
Job done :)
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.
Here is the one I most liked.
Worked hours on this. My problem was with Java 10 installation. I uninstalled it and installed Java 8, and now Pyspark works.
You can use:
mse = ((A - B)**2).mean(axis=ax)
Or
mse = (np.square(A - B)).mean(axis=ax)
ax=0
the average is performed along the row, for each column, returning an arrayax=1
the average is performed along the column, for each row, returning an arrayax=None
the average is performed element-wise along the array, returning a scalar valueJust discovered a handy way to get an index while parsing. My mind was blown.
$handle = fopen("test.csv", "r");
for ($i = 0; $row = fgetcsv($handle ); ++$i) {
// Do something will $row array
}
fclose($handle);
Source: link
This solution seems easy to follow:
public static bool isValidURL(string url) {
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse;
try
{
webResponse = webRequest.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
return false ;
}
return true ;
}
The only code that worked for me is:
scanf(" %c",&c);
I was having the same problem, and only with single characters. After an hour of random testing I can not report an issue yet. One would think that C would have by now a bullet-proof function to retrieve single characters from the keyboard, and not an array of possible hackarounds... Just saying...
You can use the code below:
int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
Just a tip for this, you don't need the BEGIN and END if it only contains a single statement.
ie:
IF(@Trans_type = 'subscr_signup')
set @tmpType = 'premium'
ELSE iF(@Trans_type = 'subscr_cancel')
set @tmpType = 'basic'
To stop your loop you can use break with label. It will stop your loop for sure. Code is written in Java but aproach is the same for the all languages.
public void exitFromTheLoop() {
boolean value = true;
loop_label:for (int i = 0; i < 10; i++) {
if(!value) {
System.out.println("iteration: " + i);
break loop_label;
}
}
}
}
It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".
maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi
Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.
In addition to @ericgol's answer: In the French version of Visual Studio Community 2017, type "Concepteur de classes" in the search bar.
I believe this will work:
TextArea.Text = "Line 1" & vbCrLf & "Line 2"
System.Environment.NewLine could be used in place of vbCrLf if you wanted to be a little less VB6 about it.
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
It doesn't. There's a vague equivalent:
mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))
JPEG will have poor quality around sharp edges etc. and for this reason it is unsuitable for most web graphics. It excels at photographs.
Compared to GIF, PNG offers better compression, larger pallette and more features, including transparency. And it is lossless.
List<String> lista =new ArrayList<String>();
List<String> listb =new ArrayList<String>();
lista.add("Isabella");
lista.add("Angelina");
lista.add("Pille");
lista.add("Hazem");
listb.add("Isabella");
listb.add("Angelina");
listb.add("Bianca");
// Create an aplusb list which will contain both list (list1 and list2) in which common element will occur twice
List<String> listapluslistb =new ArrayList<String>(lista);
listapluslistb.addAll(listb);
// Create an aunionb set which will contain both list (list1 and list2) in which common element will occur once
Set<String> listaunionlistb =new HashSet<String>(lista);
listaunionlistb.addAll(listb);
for(String s:listaunionlistb)
{
listapluslistb.remove(s);
}
System.out.println(listapluslistb);
This is what helped me [src]:
it is easy to detect whether the cookies is enabled:
if you can get the cookie you set, the cookie
is enabled, otherwise not.
BTW: it is a bad idea to Embedding the session id in the links and forms
, it is bad for SEO.
In my opinion, it is not very common that people dont want to enable cookies.
This is another option:
export default function Counter() {
}
Syntax change in swift 3.0
alert.addAction(UIAlertAction(title: "Okay",
style: .default,
handler: { _ in print("Foo") } ))
And to complement Rich's recursive answer, a non-recursive method.
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1)
with Set oFolder = queue(queue.Count)
and replace queue.Remove(1)
with queue.Remove(queue.Count)
, and probably rename the variable...)
Removing double-quotes
solve my problem, now its:
DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug
Using jquery
<html>
<head>
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js" ></script>
</head>
<body>
<script>
$.get("www.google.com", function(response) { alert(response) });
</script>
</body>
How is the rectangle represented? Three points? Four points? Point, sides and angle? Two points and a side? Something else? Without knowing that, any attempts to answer your question will have only purely academic value.
In any case, for any convex polygon (including rectangle) the test is very simple: check each edge of the polygon, assuming each edge is oriented in counterclockwise direction, and test whether the point lies to the left of the edge (in the left-hand half-plane). If all edges pass the test - the point is inside. If at least one fails - the point is outside.
In order to test whether the point (xp, yp)
lies on the left-hand side of the edge (x1, y1) - (x2, y2)
, you just need to calculate
D = (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)
If D > 0
, the point is on the left-hand side. If D < 0
, the point is on the right-hand side. If D = 0
, the point is on the line.
The previous version of this answer described a seemingly different version of left-hand side test (see below). But it can be easily shown that it calculates the same value.
... In order to test whether the point (xp, yp)
lies on the left-hand side of the edge (x1, y1) - (x2, y2)
, you need to build the line equation for the line containing the edge. The equation is as follows
A * x + B * y + C = 0
where
A = -(y2 - y1)
B = x2 - x1
C = -(A * x1 + B * y1)
Now all you need to do is to calculate
D = A * xp + B * yp + C
If D > 0
, the point is on the left-hand side. If D < 0
, the point is on the right-hand side. If D = 0
, the point is on the line.
However, this test, again, works for any convex polygon, meaning that it might be too generic for a rectangle. A rectangle might allow a simpler test... For example, in a rectangle (or in any other parallelogram) the values of A
and B
have the same magnitude but different signs for opposing (i.e. parallel) edges, which can be exploited to simplify the test.
Try in yourbatch
set "batchisin=%~dp0"
which should set the variable to your batch's location.
The following is of course all not quite precise. Take it with a grain of salt when you read it :)
Well, the three things you refer to are automatic, static and dynamic storage duration, which has something to do with how long objects live and when they begin life.
You use automatic storage duration for short lived and small data, that is needed only locally within some block:
if(some condition) {
int a[3]; // array a has automatic storage duration
fill_it(a);
print_it(a);
}
The lifetime ends as soon as we exit the block, and it starts as soon as the object is defined. They are the most simple kind of storage duration, and are way faster than in particular dynamic storage duration.
You use static storage duration for free variables, which might be accessed by any code all times, if their scope allows such usage (namespace scope), and for local variables that need extend their lifetime across exit of their scope (local scope), and for member variables that need to be shared by all objects of their class (classs scope). Their lifetime depends on the scope they are in. They can have namespace scope and local scope and class scope. What is true about both of them is, once their life begins, lifetime ends at the end of the program. Here are two examples:
// static storage duration. in global namespace scope
string globalA;
int main() {
foo();
foo();
}
void foo() {
// static storage duration. in local scope
static string localA;
localA += "ab"
cout << localA;
}
The program prints ababab
, because localA
is not destroyed upon exit of its block. You can say that objects that have local scope begin lifetime when control reaches their definition. For localA
, it happens when the function's body is entered. For objects in namespace scope, lifetime begins at program startup. The same is true for static objects of class scope:
class A {
static string classScopeA;
};
string A::classScopeA;
A a, b; &a.classScopeA == &b.classScopeA == &A::classScopeA;
As you see, classScopeA
is not bound to particular objects of its class, but to the class itself. The address of all three names above is the same, and all denote the same object. There are special rule about when and how static objects are initialized, but let's not concern about that now. That's meant by the term static initialization order fiasco.
The last storage duration is dynamic. You use it if you want to have objects live on another isle, and you want to put pointers around that reference them. You also use them if your objects are big, and if you want to create arrays of size only known at runtime. Because of this flexibility, objects having dynamic storage duration are complicated and slow to manage. Objects having that dynamic duration begin lifetime when an appropriate new operator invocation happens:
int main() {
// the object that s points to has dynamic storage
// duration
string *s = new string;
// pass a pointer pointing to the object around.
// the object itself isn't touched
foo(s);
delete s;
}
void foo(string *s) {
cout << s->size();
}
Its lifetime ends only when you call delete for them. If you forget that, those objects never end lifetime. And class objects that define a user declared constructor won't have their destructors called. Objects having dynamic storage duration requires manual handling of their lifetime and associated memory resource. Libraries exist to ease use of them. Explicit garbage collection for particular objects can be established by using a smart pointer:
int main() {
shared_ptr<string> s(new string);
foo(s);
}
void foo(shared_ptr<string> s) {
cout << s->size();
}
You don't have to care about calling delete: The shared ptr does it for you, if the last pointer that references the object goes out of scope. The shared ptr itself has automatic storage duration. So its lifetime is automatically managed, allowing it to check whether it should delete the pointed to dynamic object in its destructor. For shared_ptr reference, see boost documents: http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm
If you are in this specific situation:
a) want to just press the key, but you not have a specific webElement to click on
b) you are using Selenium 2 (WebDriver)
Then the solution is:
Actions builder = new Actions(webDriverInstance);
builder.sendKeys(Keys.RETURN).perform();
One of alternatives is MSYS2 , in another words "MinGW-w64"/Git Bash. You can simply ssh to Unix machines and run most of linux commands from it. Also install tmux!
To install tmux in MSYS2:
run command pacman -S tmux
To run tmux on Git Bash:
install MSYS2 and copy tmux.exe
and msys-event-2-1-6.dll
from MSYS2 folder C:\msys64\usr\bin
to your Git Bash directory C:\Program Files\Git\usr\bin
.
You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.
var data = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500" }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250" }, { h_id: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];_x000D_
_x000D_
data.sort(function (a, b) {_x000D_
return a.city.localeCompare(b.city) || b.price - a.price;_x000D_
});_x000D_
_x000D_
console.log(data);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
Or, using es6, simply:
data.sort((a, b) => a.city.localeCompare(b.city) || b.price - a.price);
Alternatively, you can give the "full location" to the database in your queries a la:
SELECT photo_id FROM [my database name].photogallery;
If using one more often than others, use USE
. Even if you do, you can still use the database.table
syntax.
If you want to remove or unset all $_SESSION 's then try this
session_destroy();
If you want to remove specific $_SESSION['name'] then try this
session_unset('name');
You can simply use This one line code to get date in year
var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
The <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
getTitle
is a function, so you need to put ()
after it.
string t = obj.getTitle();
What you're basically trying to do is this:-
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
The reason being, the String
which you're printing is just a String
representation of the Date
in your required format. If you try to convert it to date, you'll eventually end up doing what I've mentioned above.
Formatting Date
(cal.getTime()) to a String
and trying to get back a Date
from it - makes no sense. Date
has no format as such. You can only get a String
representation of that using the SDF.
Both awk
and sed
are plenty fast, but if you think it matters feel free to use one of the following:
If the characters that you want to delete are always at the end of the string
echo '1234567890 *' | tr -d ' *'
If they can appear anywhere within the string and you only want to delete those at the end
echo '1234567890 *' | rev | cut -c 4- | rev
The man pages of all the commands will explain what's going on.
I think you should use sed
, though.
I should this On Windows, environment variable expansion is %BUILD_NUMBER%
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}
You can just use top
It will display everything running on your OSX
It looks like ng-attr
is a new directive in AngularJS 1.1.4 that you can possibly use in this case.
<!-- example -->
<a ng-attr-title="{{product.shortDesc}}"></a>
However, if you stay with 1.0.7, you can probably write a custom directive to mirror the effect.
you can also add comment by pressing Ctrl+shift+/ and shift+ / for one line.
None of these solutions worked for me, however I was able to fix it by taking the width and subtracting the width of the scroll bar. I'm not sure how cross-browser compatible this is.
All of them need to be vertically aligned within the div
Aligned how? Tops of the images aligned with the top of the text?
One of the images needs to be absolute positioned within the div.
Absolutely positioned relative to the DIV? Perhaps you could sketch out what you're looking for...?
fd has described the steps for absolute positioning, as well as adjusting the display of the H1
element such that images will appear inline with it. To that, i'll add that you can align the images by use of the vertical-align
style:
#header h1 { display: inline; }
#header img { vertical-align: middle; }
...this would put the header and images together, with top edges aligned. Other alignment options exist; see the documentation. You might also find it beneficial to drop the DIV and move the images inside the H1
element - this provides semantic value to the container, and removes the need to adjust the display of the H1
:
<h1 id=header">
<img src=".." ></img>
testing...
<img src="..."></img>
</h1>
Following @Tobu answer and @mipadi comment, in a more pythonic way, if not interested in the created flag, I would use:
customer.source, _ = Source.objects.get_or_create(name="Website")
Others already posted very good answers, but some people might still be looking for a classic way to find Mean(avg), so here I post this (code tested in Python 3.6):
def meanmanual(listt):
mean = 0
lsum = 0
lenoflist = len(listt)
for i in listt:
lsum += i
mean = lsum / lenoflist
return float(mean)
a = [1, 2, 3, 4, 5, 6]
meanmanual(a)
Answer: 3.5
SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).
The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).
You can use customValidity
$(function(){ var elements = document.getElementsByTagName("input"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity("This can't be left blank!"); }; } });
I think that will work on at least Chrome and FF, I'm not sure about other browsers
Just follow the steps:
In the head section of your html place your custom.css below bootstrap.css.
<link href="bootstrap.min.css" rel="stylesheet">
<link href="custom.css" rel="stylesheet">
Then in custom.css you have to use the exact same selector for the element you want to override. In the case of legend
it just stays legend
in your custom.css because bootstrap hasn't got any selectors more specific.
legend {
display: inline;
width: auto;
padding: 0;
margin: 0;
font-size: medium;
line-height: normal;
color: #000000;
border: 0;
border-bottom: none;
}
But in case of h1
for example you have to take care of the more specific selectors like .jumbotron h1
because
h1 {
line-height: 2;
color: #f00;
}
will not override
.jumbotron h1,
.jumbotron .h1 {
line-height: 1;
color: inherit;
}
Here is a helpfull explantion of specificity of css selectors which you need to understand to know exactly which style rules will apply to an element. http://css-tricks.com/specifics-on-css-specificity/
Everything else is just a matter of copy/paste and edit styles.
Try with:
ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
Or with:
ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
If you want to reset every RowId via content provider try this
rowCounter=1;
do {
rowId = cursor.getInt(0);
ContentValues values;
values = new ContentValues();
values.put(Table_Health.COLUMN_ID,
rowCounter);
updateData2DB(context, values, rowId);
rowCounter++;
while (cursor.moveToNext());
public static void updateData2DB(Context context, ContentValues values, int rowId) {
Uri uri;
uri = Uri.parseContentProvider.CONTENT_URI_HEALTH + "/" + rowId);
context.getContentResolver().update(uri, values, null, null);
}
Using the command line is an option, and would remove the need for an Eclipse Plugin. First, create a directory to hold the project.
mkdir myGitRepo
cd myGitRepo
Clone the desired repository in the directory you just created.
git clone https://github.com/JonasHelming/gitTutorial.git
Then open Eclipse and select the directory you created (myGitRepo) as the Eclipse Workspace.
Don't worry that the Project Explorer is empty, Eclipse can't recognize the source files yet.
Lastly, create a new Java project with the exact same name as the project you pulled. In this case, it was 'gitTutorial'.
File -> New -> Java Project
At this point, the project's sub directories should contain the files pulled from Github. Take a look at the following post in my blog for a more detailed explanation.
http://brianredd.com/application/pull-java-project-from-github
$files = glob('uploads/*');
$count = 0;
$totalCount = 0;
$subFileCount = 0;
foreach ($files as $file)
{
global $count, $totalCount;
if(is_dir($file))
{
$totalCount += getFileCount($file);
}
if(is_file($file))
{
$count++;
}
}
function getFileCount($dir)
{
global $subFileCount;
if(is_dir($dir))
{
$subfiles = glob($dir.'/*');
if(count($subfiles))
{
foreach ($subfiles as $file)
{
getFileCount($file);
}
}
}
if(is_file($dir))
{
$subFileCount++;
}
return $subFileCount;
}
$totalFilesCount = $count + $totalCount;
echo 'Total Files Count ' . $totalFilesCount;
There is no 100% solution to delete browser cookies.
The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".
Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie
. It's not available through the HTTP Cookie header either!
However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:
function clearCookie(name, domain, path){
var domain = domain || document.domain;
var path = path || "/";
document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
I try to contribute my code collaboration with my friend . modification from this forum.
$('#upload').on('click', function() {
var fd = new FormData();
var c=0;
var file_data,arr;
$('input[type="file"]').each(function(){
file_data = $('input[type="file"]')[c].files; // get multiple files from input file
console.log(file_data);
for(var i = 0;i<file_data.length;i++){
fd.append('arr[]', file_data[i]); // we can put more than 1 image file
}
c++;
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
});
this my html file
<form name="form" id="form" method="post" enctype="multipart/form-data">
<input type="file" name="file[]"multiple>
<input type="button" name="submit" value="upload" id="upload">
this php code file
<?php
$count = count($_FILES['arr']['name']); // arr from fd.append('arr[]')
var_dump($count);
echo $count;
var_dump($_FILES['arr']);
if ( $count == 0 ) {
echo 'Error: ' . $_FILES['arr']['error'][0] . '<br>';
}
else {
$i = 0;
for ($i = 0; $i < $count; $i++) {
move_uploaded_file($_FILES['arr']['tmp_name'][$i], 'uploads/' . $_FILES['arr']['name'][$i]);
}
}
?>
I hope people with same problem , can fast solve this problem. i got headache because multiple upload image.
After setting the path of your jdk use JPS
.Then You can eaisly kill it by Task ManagerJPS
will give you all java processes
Implementing interfaces with abstract base classes is much simpler in modern Python 3 and they serve a purpose as an interface contract for plug-in extensions.
Create the interface/abstract base class:
from abc import ABC, abstractmethod
class AccountingSystem(ABC):
@abstractmethod
def create_purchase_invoice(self, purchase):
pass
@abstractmethod
def create_sale_invoice(self, sale):
log.debug('Creating sale invoice', sale)
Create a normal subclass and override all abstract methods:
class GizmoAccountingSystem(AccountingSystem):
def create_purchase_invoice(self, purchase):
submit_to_gizmo_purchase_service(purchase)
def create_sale_invoice(self, sale):
super().create_sale_invoice(sale)
submit_to_gizmo_sale_service(sale)
You can optionally have common implementation in the abstract methods as in create_sale_invoice()
, calling it with super()
explicitly in the subclass as above.
Instantiation of a subclass that does not implement all the abstract methods fails:
class IncompleteAccountingSystem(AccountingSystem):
pass
>>> accounting = IncompleteAccountingSystem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class IncompleteAccountingSystem with abstract methods
create_purchase_invoice, create_sale_invoice
You can also have abstract properties, static and class methods by combining corresponding annotations with @abstractmethod
.
Abstract base classes are great for implementing plugin-based systems. All imported subclasses of a class are accessible via __subclasses__()
, so if you load all classes from a plugin directory with importlib.import_module()
and if they subclass the base class, you have direct access to them via __subclasses__()
and you can be sure that the interface contract is enforced for all of them during instantiation.
Here's the plugin loading implementation for the AccountingSystem
example above:
...
from importlib import import_module
class AccountingSystem(ABC):
...
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
module_name = settings.ACCOUNTING_SYSTEM_MODULE_NAME
import_module(module_name)
subclasses = cls.__subclasses__()
if len(subclasses) > 1:
raise InvalidAccountingSystemError('More than one '
f'accounting module: {subclasses}')
if not subclasses or module_name not in str(subclasses[0]):
raise InvalidAccountingSystemError('Accounting module '
f'{module_name} does not exist or does not '
'subclass AccountingSystem')
cls._instance = subclasses[0]()
return cls._instance
Then you can access the accounting system plugin object through the AccountingSystem
class:
>>> accountingsystem = AccountingSystem.instance()
(Inspired by this PyMOTW-3 post.)
A Comma Separated File is really just a text file where the lines consist of values separated by commas.
There is no standard which defines the contents of a CSV file, so there is no defined way of indicating a comment. It depends on the program which will be importing the CSV file.
Of course, this is usually Excel. You should ask yourself how does Excel define a comment? In other words, what would make Excel ignore a line (or part of a line) in the CSV file? I'm not aware of anything which would do this.
You can add it from the notepad++ toolbar Plugins > Plugin Manager > Show Plugin Manager. Then select the Explorer plugin and click the Install button.
To had to distinct by two fields (derivative_id & vehicle_type) and to sort by cheapest car. Had to nest aggs.
GET /cars/_search
{
"size": 0,
"aggs": {
"distinct_by_derivative_id": {
"terms": {
"field": "derivative_id"
},
"aggs": {
"vehicle_type": {
"terms": {
"field": "vehicle_type"
},
"aggs": {
"cheapest_vehicle": {
"top_hits": {
"sort": [
{ "rental": { "order": "asc" } }
],
"_source": { "includes": [ "manufacturer_name",
"rental",
"vehicle_type"
]
},
"size": 1
}
}
}
}
}
}
}
}
Result:
{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 8,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"distinct_by_derivative_id" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "04",
"doc_count" : 3,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 2,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "8",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Renault",
"rental" : 89.99
},
"sort" : [
89.99
]
}
]
}
}
},
{
"key" : "LCV",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "7",
"_score" : null,
"_source" : {
"vehicle_type" : "LCV",
"manufacturer_name" : "Ford",
"rental" : 99.99
},
"sort" : [
99.99
]
}
]
}
}
}
]
}
},
{
"key" : "01",
"doc_count" : 2,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "1",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Ford",
"rental" : 599.99
},
"sort" : [
599.99
]
}
]
}
}
},
{
"key" : "LCV",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "2",
"_score" : null,
"_source" : {
"vehicle_type" : "LCV",
"manufacturer_name" : "Ford",
"rental" : 599.99
},
"sort" : [
599.99
]
}
]
}
}
}
]
}
},
{
"key" : "02",
"doc_count" : 2,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 2,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "4",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Audi",
"rental" : 499.99
},
"sort" : [
499.99
]
}
]
}
}
}
]
}
},
{
"key" : "03",
"doc_count" : 1,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "5",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Audi",
"rental" : 399.99
},
"sort" : [
399.99
]
}
]
}
}
}
]
}
}
]
}
}
}
This is a good solution to many problems:
function datetotime ($date, $format = 'YYYY-MM-DD') {
if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $date);
if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $date);
if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $date);
if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $date);
if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $date);
if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $date);
if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $date);
if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $date);
if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $date);
return mktime(0, 0, 0, $month, $day, $year);
}
Static tStart As Single, tEnd As Single, myInterval As Integer
myInterval = 5 ' seconds
tStart = VB.Timer()
tEnd = myInterval + VB.Timer()
Do While tEnd > tStart
Application.DoEvents()
tStart = VB.Timer()
Loop
place your "a href" tag without any styling before div / span of text. then make your styling in the div/span tag.
for the most restricted styling email client.
<div><a href=""><span style="text-decoration:none">title</span><a/></div>
Using alias for referencing the tables to get the columns from different tables after joining them.
Select tb1.*, tb2.col1, tb2.col2 from table1 tb1 JOIN table2 tb2 on tb1.Id = tb2.Id
Solved my own problem. This line:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
needs to be:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
or since Java 7:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
You can use my code here
//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += PrintPage;
//here to select the printer attached to user PC
PrintDialog printDialog1 = new PrintDialog();
printDialog1.Document = pd;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
pd.Print();//this will trigger the Print Event handeler PrintPage
}
}
//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
try
{
if (File.Exists(this.ImagePath))
{
//Load the image from the file
System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");
//Adjust the size of the image to the page to print the full image without loosing any part of it
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
}
catch (Exception)
{
}
}
You can use the comm
command to compare two sorted files
comm -13 <(sort file1) <(sort file2)
Here is a Multi-line String Literal example in Node.js.
> let name = 'Fred'
> tm = `Dear ${name},
... This is to inform you, ${name}, that you are
... IN VIOLATION of Penal Code 64.302-4.
... Surrender yourself IMMEDIATELY!
... THIS MEANS YOU, ${name}!!!
...
... `
'Dear Fred,\nThis is to inform you, Fred, that you are\nIN VIOLATION of Penal Code 64.302-4.\nSurrender yourself IMMEDIATELY!\nTHIS MEANS YOU, Fred!!!\n\n'
console.log(tm)
Dear Fred,
This is to inform you, Fred, that you are
IN VIOLATION of Penal Code 64.302-4.
Surrender yourself IMMEDIATELY!
THIS MEANS YOU, Fred!!!
undefined
>
Try this to remove the labels (but not the ticks):
import matplotlib.pyplot as plt
plt.setp( ax.get_xticklabels(), visible=False)
You can do this with a list comprehension and index()
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x[0] for x in tuple_list].index("kumquat")
2
[x[1] for x in tuple_list].index(7)
1
As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */
in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.
Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME
which has a unique constraint on a column called IDX_COL_NAME
.
INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */
INTO TABLE_NAME(
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n)
SELECT
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n);
This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.
There are two ways of getting query params:
In second case one has to be careful as body parameters will take precedence over query parameters. A full description about getting query params can be found here
https://golangbyexample.com/net-http-package-get-query-params-golang
Using JQuery you can do:
$('input:submit').click( function() { this.disabled = true } );
&
$('input:submit').keypress( function(e) {
if (e.which == 13) {
this.disabled = true
}
}
);
$blog is an object, not an array, so you should access it like so:
$blog->id;
$blog->title;
$blog->content;
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
I think, this is you exactly needed.
Here drawable(xml) file that creates rounded rectangle. round_rect_shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#ffffff" />
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
</shape>
Here layout file: my_layout.xml
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/round_rect_shape"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Something text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ff0000" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>
-> In the above code, LinearLayout having the background(That is the key role to place to create rounded rectangle). So you can place any view like TextView, EditText... in that LinearLayout to see background as round rectangle for all.
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
If you want type safety and a bunch of constants that match that type, one way to go is to have an abstract class for your enum and then extend that class with a locked constructor, like so:
abstract class DaysOfWeekEnum{
public function __construct(string $value){
$this->value = $value;
}
public function __toString(){
return $this->value;
}
}
class Monday extends DaysOfWeekEnum{
public function __construct(){
parent::__construct("Monday");
}
}
class Tuesday extends DaysOfWeekEnum{
public function __construct(){
parent::__construct("Tuesday");
}
}
Then you can have your methods take an instance of DaysOfWeek and pass it an instance of Monday, Tuesday, etc... The only downside is having to 'new-up' an instance every time you want to use your enum, but I find it worth it.
function printWeekDay(DaysOfWeek $day){
echo "Today is $day.";
}
printWeekDay(new Monday());
As explained in Spring documentation, there are several ways to do that:
Either you set the port in the command line (for example 8888)
-Dserver.port=8888
or --server.port=8888
Example : java -jar -Dserver.port=8888 test.jar
Or you set the port in the application.properties
server.port=${port:4588}
or (in application.yml with yaml syntax)
server:
port: ${port:4588}
If the port passed by -Dport (or -Dserver.port) is set in command line then this port will be taken into account. If not, then the port will be 4588 by default.
If you want to enforce the port in properties file whatever the environment variable, you just have to write:
server.port=8888
Here are several options for getting the "tail" items of an iterable:
Given
n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Desired Output
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Code
We get the latter output using any of the following options:
from collections import deque
import itertools
import more_itertools
# A: Slicing
iterable[-n:]
# B: Implement an itertools recipe
def tail(n, iterable):
"""Return an iterator over the last *n* items of *iterable*.
>>> t = tail(3, 'ABCDEFG')
>>> list(t)
['E', 'F', 'G']
"""
return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))
# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))
# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))
# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))
Details
iter(iterable)
. itertools
recipe. It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools
module.more_itertools
(install via > pip install more-itertools
); see more_itertools.tail
.itertools
library. Note, itertools.islice
does not support negative slicing. more_itertools
that generalizes itertools.islice
to support negative slicing; see more_itertools.islice_extended
.Which one do I use?
It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.
You might be able to resize the image with canvas
and export it using dataURI. Not sure about compression, though.
Take a look at this: Resizing an image in an HTML5 canvas
This code worked for me:
$(function(){
$('input:radio').change(function(){
alert('changed');
});
});
Though an old question, I would like to add that currently mock
library (backport of unittest.mock) supports assert_not_called
method.
Just upgrade yours;
pip install mock --upgrade
A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:
select * from FN('myFunc')
You need to make sure that you add forward slash before your link to socket.io:
<script src="/socket.io/socket.io.js"></script>
Then in the view/controller just do:
var socket = io.connect()
That should solve your problem.
have you tried:
.image_block{
text-align: center;
vertical-align: bottom;
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
Use where
with a !=
operator in combination with whereNull
Code::where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id')->get()
You can do it like this
[btnTwo setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
Solution based on @Elnoor answer, but working with multiple file upload form input and without the "fakepath hack":
HTML:
<div class="custom-file">
<input id="logo" type="file" class="custom-file-input" multiple>
<label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>
JS:
$('input[type="file"]').on('change', function () {
let filenames = [];
let files = document.getElementById('health_claim_file_form_files').files;
for (let i in files) {
if (files.hasOwnProperty(i)) {
filenames.push(files[i].name);
}
}
$(this).next('.custom-file-label').addClass("selected").html(filenames.join(', '));
});
Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated) {
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Account",
action = "Unauthorised"
})
);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
I encountered the same error than adding
Task.Delay(2000);
in each request solved the problem
The fix is really simple: just replace YOUR_API_KEY on the last line of your code with your actual API key!
If you don't have one, you can get it for free on the Google Developers Website.
You need to explicitly include a BoundField of the primary key. If you don't want the user to see the primary key, you have to hide it via css:
<asp:BoundField DataField="Id_primary_key" ItemStyle-CssClass="hidden"
HeaderStyle-CssClass="hidden" />
Where 'hidden' is a class in css that has it's display set to 'none'.
setState()
has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:
// Form Input
this.setState(
{
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search
},
this.findRoutes // here is where you put the callback
);
Notice the call to findRoutes
is now inside the setState()
call,
as the second parameter.
Without ()
because you are passing the function.
Ctrl + I (indentation). See at http://www.rossenstoyanchev.org/write/prog/eclipse/eclipse3.html Search for Indentation.
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "Status = " + message.getBody() , Toast.LENGTH_LONG).show();
}
});
this works for me
EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...
If your goroutine exists solely to process the items coming out of the chan, you can make use of the "close" builtin and the special receive form for channels.
That is, once you're done sending items on the chan, you close it. Then inside your goroutine you get an extra parameter to the receive operator that shows whether the channel has been closed.
Here is a complete example (the waitgroup is used to make sure that the process continues until the goroutine completes):
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
ch := make(chan int)
go func() {
for {
foo, ok := <- ch
if !ok {
println("done")
wg.Done()
return
}
println(foo)
}
}()
ch <- 1
ch <- 2
ch <- 3
close(ch)
wg.Wait()
}
Give this a try...
server {
listen 80;
server_name dev.int.com;
access_log off;
location / {
proxy_pass http://IP:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:8080/jira /;
proxy_connect_timeout 300;
}
location ~ ^/stash {
proxy_pass http://IP:7990;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:7990/ /stash;
proxy_connect_timeout 300;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
If we declare a variable as static, there will be only one copy of the variable. So, whenever different threads access that variable, there will be only one final value for the variable(since there is only one memory location allocated for the variable).
If a variable is declared as volatile, all threads will have their own copy of the variable but the value is taken from the main memory.So, the value of the variable in all the threads will be the same.
So, in both cases, the main point is that the value of the variable is same across all threads.
I added this to Espuz and JCC's answer. It uses the y position of the subviews and doesn't include the scroll bars. Edit Uses the bottom of the lowest sub view that is visible.
+ (CGFloat) bottomOfLowestContent:(UIView*) view
{
CGFloat lowestPoint = 0.0;
BOOL restoreHorizontal = NO;
BOOL restoreVertical = NO;
if ([view respondsToSelector:@selector(setShowsHorizontalScrollIndicator:)] && [view respondsToSelector:@selector(setShowsVerticalScrollIndicator:)])
{
if ([(UIScrollView*)view showsHorizontalScrollIndicator])
{
restoreHorizontal = YES;
[(UIScrollView*)view setShowsHorizontalScrollIndicator:NO];
}
if ([(UIScrollView*)view showsVerticalScrollIndicator])
{
restoreVertical = YES;
[(UIScrollView*)view setShowsVerticalScrollIndicator:NO];
}
}
for (UIView *subView in view.subviews)
{
if (!subView.hidden)
{
CGFloat maxY = CGRectGetMaxY(subView.frame);
if (maxY > lowestPoint)
{
lowestPoint = maxY;
}
}
}
if ([view respondsToSelector:@selector(setShowsHorizontalScrollIndicator:)] && [view respondsToSelector:@selector(setShowsVerticalScrollIndicator:)])
{
if (restoreHorizontal)
{
[(UIScrollView*)view setShowsHorizontalScrollIndicator:YES];
}
if (restoreVertical)
{
[(UIScrollView*)view setShowsVerticalScrollIndicator:YES];
}
}
return lowestPoint;
}
You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.
http://developer.android.com/reference/android/os/Parcelable.html
Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.
Here I launch the kmlreader class of my app when I recieve an onclick in the listview.
Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview
List<KmlSummary> summary = null;
...
public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";
...
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
lastshownitem = position;
Intent intent = new Intent(context, KmlReader.class);
intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
summary.get(position));
startActivity(intent);
}
later in the new activity I pull out the parseable class with
kmlSummary = intent.getExtras().getParcelable(
ImageTextListViewActivity.EXTRA_KMLSUMMARY);
//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.
public KmlSummary(Parcel in) {
this._id = in.readInt();
this._description = in.readString();
this._name = in.readString();
this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
in.readDouble());
this._resrawid = in.readInt();
this._resdrawableid = in.readInt();
this._pathstring = in.readString();
String s = in.readString();
this.set_isThumbCreated(Boolean.parseBoolean(s));
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeInt(this._id);
arg0.writeString(this._description);
arg0.writeString(this._name);
arg0.writeDouble(this.get_bounds().southwest.latitude);
arg0.writeDouble(this.get_bounds().southwest.longitude);
arg0.writeDouble(this.get_bounds().northeast.latitude);
arg0.writeDouble(this.get_bounds().northeast.longitude);
arg0.writeInt(this._resrawid);
arg0.writeInt(this._resdrawableid);
arg0.writeString(this.get_pathstring());
String s = Boolean.toString(this.isThumbCreated());
arg0.writeString(s);
}
Good Luck Danny117
Your implementation (the one in the question) is faster than e.g. wrapping with toList()
and using a comparator-based method. Auto-boxing and running through comparator methods or wrapped Collections objects is far slower than just reversing.
Of course you could write your own sort. That might not be the answer you're looking for, but note that if your comment about "if the array is already sorted quite well" happens frequently, you might do well to choose a sorting algorithm that handles that case well (e.g. insertion) rather than use Arrays.sort()
(which is mergesort, or insertion if the number of elements is small).
Try like this way,
Step 1: First check who you are? it will return current user name e.g ubuntu
$ whoami
Step 2: Then set permission to your current user, in that case, ubuntu by
sudo chown -R ubuntu .git/
One liner for callstack:
begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace; end
One liner for callstack without all the gems's:
begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//); end
One liner for callstack without all the gems's and relative to current directory
begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//).map { |l| l.gsub(`pwd`.strip + '/', '') }; end
Couldn't you just write all the commands into a .cmd file in the temp folder and then execute that file?
<!--[if !IE]><!--><script src="zepto.min.js"></script><!--<![endif]-->
<!--[if IE]><script src="jquery-1.7.2.min.js"></script><![endif]-->
Note: These conditional comments are no longer supported from IE 10 onwards.
Solution:
If you created the virtualenv as root, run the following command:
sudo chown -R your_username:your_username path/to/virtuaelenv/
This will probably fix your problem.
Cheers
Simple Way
if ($('#text-field > p.filled-text').length != 0)
Always have a check before reading row.
if (SqlCommand.ExecuteScalar() == null)
{
}
@Thad you need to add a blur event handler as well
$(document).ready(function(){
$("#dropdown").mousedown(function(){
if($.browser.msie) {
$(this).css("width","auto");
}
});
$("#dropdown").change(function(){
if ($.browser.msie) {
$(this).css("width","175px");
}
});
$("#dropdown").blur(function(){
if ($.browser.msie) {
$(this).css("width","175px");
}
});
});
However, this will still expand the selectbox on click, instead of just the elements. (and it seems to fail in IE6, but works perfectly in Chrome and IE7)
There are some really good answers and attempts to answer your question here. I am not an encoding master, but I understand your desire to have a pure UTF-8 stack all the way through to your database. I have been using MySQL's utf8mb4
encoding for tables, fields, and connections.
My situation boiled down to "I just want my sanitizers, validators, business logic, and prepared statements to deal with UTF-8 when data comes from HTML forms, or e-mail registration links." So, in my simple way, I started off with this idea:
$encodings = ['UTF-8', 'ISO-8859-1', 'ASCII'];
throw new RuntimeException
UTF-8
, carry on.Else, if it is ISO-8859-1
or ASCII
a. Attempt conversion to UTF-8 (wait, not finished)
b. Detect the encoding of the converted value
c. If the reported encoding and converted value are both UTF-8
, carry on.
d. Else, throw new RuntimeException
From my abstract class Sanitizer
private function isUTF8($encoding, $value)
{
return (($encoding === 'UTF-8') && (utf8_encode(utf8_decode($value)) === $value));
}
private function utf8tify(&$value)
{
$encodings = ['UTF-8', 'ISO-8859-1', 'ASCII'];
mb_internal_encoding('UTF-8');
mb_substitute_character(0xfffd); //REPLACEMENT CHARACTER
mb_detect_order($encodings);
$stringEncoding = mb_detect_encoding($value, $encodings, true);
if (!$stringEncoding) {
$value = null;
throw new \RuntimeException("Unable to identify character encoding in sanitizer.");
}
if ($this->isUTF8($stringEncoding, $value)) {
return;
} else {
$value = mb_convert_encoding($value, 'UTF-8', $stringEncoding);
$stringEncoding = mb_detect_encoding($value, $encodings, true);
if ($this->isUTF8($stringEncoding, $value)) {
return;
} else {
$value = null;
throw new \RuntimeException("Unable to convert character encoding from ISO-8859-1, or ASCII, to UTF-8 in Sanitizer.");
}
}
return;
}
One could make an argument that I should separate encoding concerns from my abstract Sanitizer
class and simply inject an Encoder
object into a concrete child instance of Sanitizer
. However, the main problem with my approach is that, without more knowledge, I simply reject encoding types that I do not want (and I am relying on PHP mb_* functions). Without further study, I cannot know if that hurts some populations or not (or, if I am losing out on important information). So, I need to learn more. I found this article.
Moreover, what happens when encrypted data is added to my email registration links (using OpenSSL
or mcrypt
)? Could this interfere with decoding? What about Windows-1252? What about security implications? The use of utf8_decode()
and utf8_encode()
in Sanitizer::isUTF8
are dubious.
People have pointed out short-comings in the PHP mb_* functions. I never took time to investigate iconv
, but if it works better than mb_*functions, let me know.
Update @Paul Grimshaw answer, use includes
insteed of indexOf
for more readable
let found = arr1.some(r=> arr2.indexOf(r) >= 0)
let found = arr1.some(r=> arr2.includes(r))
Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.
So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:
Using scp, copy file to a directory in the remote user's account, for example the Documents directory:
scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents
Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:
ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www
Answer 1 - "response" gave a nice answer/link for it. To put it in short, "auto" is the default, so it is like removing any changes in the width of an element
Answer 2 - use width: 100%
instead. It will fill the 100% of the parent container, in this case, the "form".
try the below code
execute immediate 'truncate table tablename' ;
declare @dt datetime
set @dt = '09-22-2007 15:07:38.850'
select dateadd(mi, datediff(mi, 0, @dt), 0)
select dateadd(hour, datediff(hour, 0, @dt), 0)
will return
2007-09-22 15:07:00.000
2007-09-22 15:00:00.000
The above just truncates the seconds and minutes, producing the results asked for in the question. As @OMG Ponies pointed out, if you want to round up/down, then you can add half a minute or half an hour respectively, then truncate:
select dateadd(mi, datediff(mi, 0, dateadd(s, 30, @dt)), 0)
select dateadd(hour, datediff(hour, 0, dateadd(mi, 30, @dt)), 0)
and you'll get:
2007-09-22 15:08:00.000
2007-09-22 15:00:00.000
Before the date data type was added in SQL Server 2008, I would use the above method to truncate the time portion from a datetime to get only the date. The idea is to determine the number of days between the datetime in question and a fixed point in time (0
, which implicitly casts to 1900-01-01 00:00:00.000
):
declare @days int
set @days = datediff(day, 0, @dt)
and then add that number of days to the fixed point in time, which gives you the original date with the time set to 00:00:00.000
:
select dateadd(day, @days, 0)
or more succinctly:
select dateadd(day, datediff(day, 0, @dt), 0)
Using a different datepart (e.g. hour
, mi
) will work accordingly.
If you end up with none of the above working, you might be able to retrieve data using the suggestion from here: http://www.spinics.net/lists/git/msg62499.html
git prune -n
git cat-file -p <blob #>
Try this
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btn.setBackgroundResource(R.drawable.icon);
}
});
There are a few alternate ways to figure out the currently used python in Linux is:
which python
command.command -v python
commandtype python
commandSimilarly On Windows with Cygwin will also result the same.
kuvivek@HOSTNAME ~
$ which python
/usr/bin/python
kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4 /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz
kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3
kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python
kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)
If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.
>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>
If you are not sure of the actual path of the python command and is available in your system, Use the following command.
pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $
It is, but requires a CSS2 capable browser (all major browsers, IE8+).
.OwnerJoe:before {
content: "Joe's Task:";
}
But I would rather recommend using Javascript for this. With jQuery:
$('.OwnerJoe').each(function() {
$(this).before($('<span>').text("Joe's Task: "));
});
I used this solution to convert single letter color codes into their descriptions:
=CHOOSE(FIND(H5,"GYR"),"Good","OK","Bad")
You basically look up the element you're trying to decode in the array, then use CHOOSE()
to pick the associated item. It's a little more compact than building a table for VLOOKUP()
.
use of list comprehension, pd.DataFrame
and pd.concat
pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3] for _ in range(df.shape[0])],
df.index, ['column_new_1', 'column_new_2','column_new_3']
)
], axis=1)
I had fixed this problem by removing the .gradle folder
in windows: C:\Users{Logged in User}.gradle
The iPython shell makes this easy: function?
will give you the documentation. function??
shows also the code. BUT this only works for pure python functions.
Then you can always download the source code for the (c)Python.
If you're interested in pythonic implementations of core functionality have a look at PyPy source.
no, 100 small objects needs more information (memory) than one big.
Your vector<string> userString
has size 0
, so the loop is never entered. You could start with a vector of a given size:
vector<string> userString(10);
string word;
string sentence;
for (decltype(userString.size()) i = 0; i < userString.size(); ++i)
{
cin >> word;
userString[i] = word;
sentence += userString[i] + " ";
}
although it is not clear why you need the vector at all:
string word;
string sentence;
for (int i = 0; i < 10; ++i)
{
cin >> word;
sentence += word + " ";
}
If you don't want to have a fixed limit on the number of input words, you can use std::getline
in a while
loop, checking against a certain input, e.g. "q"
:
while (std::getline(std::cin, word) && word != "q")
{
sentence += word + " ";
}
This will add words to sentence
until you type "q".
How about creating a custom function and using that in your formula? VBA has a built-in function, InStrRev
, that does exactly what you're looking for.
Put this in a new module:
Function RSearch(str As String, find As String)
RSearch = InStrRev(str, find)
End Function
And your function will look like this (assuming the original string is in B1):
=LEFT(B1,RSearch(B1,"\"))
There are a couple of things to be aware of:
src/main/resources/public
will be served from the root of your application.
For example src/main/resources/public/hello.jpg
would be served from http://localhost:8080/hello.jpg
This is why your current matcher configuration hasn't permitted access to the static resources. For /resources/**
to work, you would have to place the resources in src/main/resources/public/resources
and access them at http://localhost:8080/resources/your-resource
.
As you're using Spring Boot, you may want to consider using its defaults rather than adding extra configuration. Spring Boot will, by default, permit access to /css/**
, /js/**
, /images/**
, and /**/favicon.ico
. You could, for example, have a file named src/main/resources/public/images/hello.jpg
and, without adding any extra configuration, it would be accessible at http://localhost:8080/images/hello.jpg
without having to log in. You can see this in action in the web method security smoke test where access is permitted to the Bootstrap CSS file without any special configuration.
The android studio and Gradle version looks like very bad managed. And there's tons of version in-capability issues. And the error message is mostly clueless. For this particular issue. The closest answer is from "Jitendra Singh". Change the version to:
classpath 'com.android.tools.build:gradle:2.0.0'
But in my case: Android studio 2.2 RC, I still get another error:
Could not find matching constructor for: com.android.build.gradle.internal.LibraryTaskManager(org.gradle.api.internal.project.DefaultProject_Decorated, com.android.builder.core.AndroidBuilder, android.databinding.tool.DataBindingBuilder, com.android.build.gradle.LibraryExtension_Decorated, com.android.build.gradle.internal.SdkHandler, com.android.build.gradle.internal.DependencyManager, org.gradle.tooling.provider.model.internal.DefaultToolingModelBuilderRegistry)
So I went to the maven central to find the latest com.android.tools.build:gradle version which is 2.1.3 for now. So after change to
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
}
}
Solved my problem eventually.
steps to change cookie expiration
step 1:Go to settings of Phpmyadmin
step 2:General
step 3:Login cookie validity
step 4:Update 1440 seconds default cookie expiration time with your new value
Increasing the memory size in the environment variable 'MAVEN_OPTS' will help resolve this issue. For me, increasing from -Xmx756M to -Xmx1024M worked.
properties-maven-plugin plugin may help:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<goals>
<goal>set-system-properties</goal>
</goals>
<configuration>
<properties>
<property>
<name>my.property.name</name>
<value>my.property.value</value>
</property>
</properties>
</configuration>
</execution>
</executions>
</plugin>
while u write R
. you are referring to the R.java
class created by eclipse, use getResources().getString()
and pass the id
of the resource from which you are trying to read inside the getString()
method.
Example : String[] yourStringArray = getResources().getStringArray(R.array.Your_array);
You need to try on an emulator with the Google API's version. Each platform has two versions, Android and Android+Google APIs. Ensure that when you create the AVD, you select the Google APIs version on target field.
And the page Ensure Devices Have the Google Play services APK can be also helpful.
You've got a stray byte floating around. You can find it by running
with open("x.py") as fp:
for i, line in enumerate(fp):
if "\xe2" in line:
print i, repr(line)
where you should replace "x.py"
by the name of your program. You'll see the line number and the offending line(s). For example, after inserting that byte arbitrarily, I got:
4 "\xe2 lb = conn.create_load_balancer('my_lb', ['us-east-1a', 'us-east-1b'],[(80, 8080, 'http'), (443, 8443, 'tcp')])\n"
You have to wrap the word in a span to accomplish this.
You can use -
$isTouch = isset($variable);
It will return true
if the $variable
is defined. if the variable is not defined it will return false
.
Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
If you want to check for false
, 0
etc You can then use empty()
-
$isTouch = empty($variable);
empty()
works for -
This works for me for more or less standard forms:
<button type="submit" value="Submit" name="ButtonType" id="whateveristheId" class="button-class">Submit<img src="/img/selectedImage.png" alt=""></button>
I've also seen
x <- {}
Now you can concatenate or bind a vector of any dimension to x
rbind(x, 1:10)
cbind(x, 1:10)
c(x, 10)
Using Now() is not a good idea. It only save the current time and date. It will not update the the current date and time, when you update your data. If you want to add the time once, The default value =Now() is best option. If you want to use timestamp. and want to update the this value, each time that row is updated. Then, trigger is best option to use.
These two toturial will help to implement the trigger.
Not sure why no one mentioned to just use the built-in sticky header style for elements. Worked great for me.
.tableContainerDiv {
overflow: auto;
max-height: 80em;
}
th {
position: sticky;
top: 0;
background: white;
}
Put a min-width on the in @media if you need to make responsive (or similar).
see Table headers position:sticky or Position Sticky and Table Headers
boolean isWithinRange(Date testDate) {
return !(testDate.before(startDate) || testDate.after(endDate));
}
Doesn't seem that awkward to me. Note that I wrote it that way instead of
return testDate.after(startDate) && testDate.before(endDate);
so it would work even if testDate was exactly equal to one of the end cases.
A huge issue for me is that tables, especially nested tables, take much longer to render than a properly layed out css implementation. (You can make css just as slow).
All browsers render the css faster because each div is a seperate element, so a screen can be loading as the user is reading. (For huge data sets, etc). I've used css instead of tables in that instance not even dealing with layout.
A nested table (tables inside of cells, etc) will not render to the browser window until the last "/table" is found. Even worse - a poorly defined table will somtimes not even render! Or when it does, things misbehave. (not colspanning properly with "TD"'s etc.)
I use tables for most things, but when it comes to large data and the desire to have a screen render quickly for an end-user - I try my best to utilize what CSS has to offer.
I had the same issue.For me the problem was how to configure a cache limit to images.And i came across this site which gave some insights to the procedure on how the issue can be handled.Hope it will be helpful for you too Link:[https://varvy.com/pagespeed/cache-control.html]
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {_x000D_
$("#result").html($(this).val());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h2>Form "your_form_name"</h2>_x000D_
<form name="your_form_name">_x000D_
<input type="text" name="one_a" id="one_a" value="AAAAAAAA" />_x000D_
<input type="text" name="one_b" id="one_b" value="BBBBBBBB" />_x000D_
<input type="text" name="one_c" id="one_c" value="CCCCCCCC" />_x000D_
<select name="one_d">_x000D_
<option value="111111">111111</option>_x000D_
<option value="222222">222222</option>_x000D_
<option value="333333">333333</option>_x000D_
</select>_x000D_
</form>_x000D_
<hr/>_x000D_
<h2>Form "your_other_form_name"</h2>_x000D_
<form name="your_other_form_name">_x000D_
<input type="text" name="two_a" id="two_a" value="DDDDDDDD" />_x000D_
<input type="text" name="two_b" id="two_b" value="EEEEEEEE" />_x000D_
<input type="text" name="two_c" id="two_c" value="FFFFFFFF" />_x000D_
<input type="text" name="two_d" id="two_d" value="GGGGGGGG" />_x000D_
<input type="text" name="two_e" id="two_f" value="HHHHHHHH" />_x000D_
<input type="text" name="two_f" id="two_e" value="IIIIIIII" />_x000D_
<select name="two_g">_x000D_
<option value="444444">444444</option>_x000D_
<option value="555555">555555</option>_x000D_
<option value="666666">666666</option>_x000D_
</select>_x000D_
</form>_x000D_
<h2>Result</h2>_x000D_
<div id="result">_x000D_
<h2>Click on a field..</h2>_x000D_
</div>
_x000D_
In addition to above @JoeD's answer.
If you want to target fields in a particular form (assuming there are more than one forms) than just fields, you can use the following code:
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
// A form element was clicked
});
Like so?
static void Main()
{
byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
#if defined(__OBJC__)
#define __bool BOOL
#include <stdbool.h>
#define __bool bool
#endif
static inline __bool xor(__bool a, __bool b)
{
return (!a && b) || (a && !b);
}
It works as defined. The conditionals are to detect if you are using Objective-C, which is asking for BOOL instead of bool (the length is different!)
The most elegant way to fix this: use pipe. Here is example (my blog). So you can then simply use url | safe
pipe to bypass the security.
<iframe [src]="url | safe"></iframe>
Refer to the documentation on npm for details: https://www.npmjs.com/package/safe-pipe
I faced same issue but after a lot of RND. I found that whts the problem so run this command on your terminal.
sudo service mongod start
then run mongo on terminal
If you want to delete a commit you can do it as part of an interactive rebase. But do it with caution, so you don't end up messing up your repo.
In Sourcetree:
Check out this Atlassian blog post for more on interactive rebasing in Sourcetree.
c map (_.getP) zip c
Works well and is very intuitiv
I'm not sure if you can do this in every browser but you can set the css property of the specified img.
Try to work with jQuery which allows you to make css changes much faster and efficiently.
in jQuery you will have the options of using .animate(),.fadeTo(),.fadeIn(),.hide("slow"),.show("slow")
for example.
I mean this CSS snippet should do the work for you:
img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
Also check out this website where everything further is explained:
http://www.w3schools.com/css/css_image_transparency.asp
It can be done using:-
SELECT COUNT(COLUMN_NAME) 'NO OF COLUMN' FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Address'
I have done this way
function uniqeId() {
var ranDom = Math.floor(new Date().valueOf() * Math.random())
return _.uniqueId(ranDom);
}
If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>
Updated fiddle http://jsfiddle.net/gFCzV/34/
use OutputStream instead of FileWriter to set encoding type
// file is your File object where you want to write you data
OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(json); // json is your data
outputStreamWriter.flush();
outputStreamWriter.close();
The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.
You could use String.prototype.indexOf
to accomplish that. Try something like this:
$('.type').keyup(function() {_x000D_
var v = $(this).val();_x000D_
if (v.indexOf('> <') !== -1) {_x000D_
console.log('contains > <');_x000D_
}_x000D_
console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
Update
Modern browsers also have a String.prototype.includes
method.
var topViewController: UIViewController? {
guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
while let presentedViewController = topViewController.presentedViewController {
topViewController = presentedViewController
}
return topViewController
}