In javascript:
document.getElementById("myDIV").style.display = "none";
and in jquery:
$("#myDIV").css({display: "none"});
$("#myDIV").css({display: "block"});
and you can use:
$('#myDIV').hide();
$('#myDIV').show();
document.addEventListener('scroll', function (event) {
if ((<HTMLInputElement>event.target).id === 'latest-div') { // or any other filtering condition
}
}, true /*Capture event*/);
You can use this to capture an event and and here "latest-div" is the id name so u can capture all scroller action here based on the id you can do the action as well inside here.
In most cases (including this one), return
will exit immediately. However, if the return is in a try
block with an accompanying finally
block, the finally
always executes and can "override" the return
in the try
.
function foo() {
try {
for (var i = 0; i < 10; i++) {
if (i % 3 == 0) {
return i; // This executes once
}
}
} finally {
return 42; // But this still executes
}
}
console.log(foo()); // Prints 42
If data already exists in the column you should do:
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;
As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.
You can request a path in this format:
/package/path/to/the/resource.ext
Even the bytes for creating the classes in memory are found this way:
my.Class -> /my/Class.class
and getResource
will give you a URL which can be used to retrieve an InputStream
.
But... I'd recommend using directly getClass().getResourceAsStream(...)
with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.
In short: try using getResourceAsStream
and some constructor of ImageIcon
that uses an InputStream
as an argument.
Classloaders
Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon
was capable of finding it.
Edit: classpath
getResource
is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.
Type "Sysout
" and then Ctrl+Space
. It expands to
System.out.println();
By process (in the JSF specification it's called execute) you tell JSF to limit the processing to component that are specified every thing else is just ignored.
update indicates which element will be updated when the server respond back to you request.
@all : Every component is processed/rendered.
@this: The requesting component with the execute attribute is processed/rendered.
@form : The form that contains the requesting component is processed/rendered.
@parent: The parent that contains the requesting component is processed/rendered.
With Primefaces you can even use JQuery selectors, check out this blog: http://blog.primefaces.org/?p=1867
First, some similarities that have not been mentioned yet. Ruby supports open classes, but modules as open too. After all, Class inherits from Module in the Class inheritance chain and so Class and Module do have some similar behavior.
But you need to ask yourself what is the purpose of having both a Class and a Module in a programming language? A class is intended to be a blueprint for creating instances, and each instance is a realized variation of the blueprint. An instance is just a realized variation of a blueprint (the Class). Naturally then, Classes function as object creation. Furthermore, since we sometimes want one blueprint to derive from another blueprint, Classes are designed to support inheritance.
Modules cannot be instantiated, do not create objects, and do not support inheritance. So remember one module does NOT inherit from another!
So then what is the point of having Modules in a language? One obvious usage of Modules is to create a namespace, and you will notice this with other languages too. Again, what's cool about Ruby is that Modules can be reopened (just as Classes). And this is a big usage when you want to reuse a namespace in different Ruby files:
module Apple
def a
puts 'a'
end
end
module Apple
def b
puts 'b'
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c527c98>
> f.a
=> a
> f.b
=> b
But there is no inheritance between modules:
module Apple
module Green
def green
puts 'green'
end
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c462420>
> f.green
NoMethodError: undefined method `green' for #<Fruit:0x007fe90c462420>
The Apple module did not inherit any methods from the Green module and when we included Apple in the Fruit class, the methods of the Apple module are added to the ancestor chain of Apple instances, but not methods of the Green module, even though the Green module was defined in the Apple module.
So how do we gain access to the green method? You have to explicitly include it in your class:
class Fruit
include Apple::Green
end
=> Fruit
> f.green
=> green
But Ruby has another important usage for Modules. This is the Mixin facility, which I describe in another answer on SO. But to summarize, mixins allow you to define methods into the inheritance chain of objects. Through mixins, you can add methods to the inheritance chain of object instances (include) or the singleton_class of self (extend).
I use this to get the Parent, similarly for child
$( this ).children( 'li.target' ).css("border", "3px double red");
Good Luck
Since I just lost two days of my life trying to solve for tryCatch for an irr function, I thought I should share my wisdom (and what is missing). FYI - irr is an actual function from FinCal in this case where got errors in a few cases on a large data set.
Set up tryCatch as part of a function. For example:
irr2 <- function (x) {
out <- tryCatch(irr(x), error = function(e) NULL)
return(out)
}
For the error (or warning) to work, you actually need to create a function. I originally for error part just wrote error = return(NULL)
and ALL values came back null.
Remember to create a sub-output (like my "out") and to return(out)
.
The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)
This can be invoked using Guid.Empty
or new Guid()
If you want a new GUID, you use Guid.NewGuid()
This is the simple only you have to set background color as transparent
ImageButton btn=(ImageButton)findViewById(R.id.ImageButton01);
btn.setBackgroundColor(Color.TRANSPARENT);
It can be done with a compare validator as below. Unlike the other answers, this also allows negative numbers to be entered, which is valid for integer values.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator ControlToValidate="TextBox1" runat="server" ErrorMessage="Integers only please" Operator="DataTypeCheck" Type="Integer" ></asp:CompareValidator>
You can easily fix the problem by changing bundle identifier on the Apple web page from com.my.app
to com.my.app.iOS
. I found this solution at https://forums.developer.apple.com/thread/15712.
I don't know if this question is still open for a new solution with all the answer already given, but I happened to have faced exactly the same question myself. I tried to "reason" with myself for a solution, and I found one. It might be the same thing as some have already suggested here, but anyway here it is:
in order for two elements of the circle's surface to be equal, assuming equal dr's, we must have dtheta1/dtheta2 = r2/r1. Writing expression of the probability for that element as P(r, theta) = P{ r1< r< r1 + dr, theta1< theta< theta + dtheta1} = f(r,theta)*dr*dtheta1, and setting the two probabilities (for r1 and r2) equal, we arrive to (assuming r and theta are independent) f(r1)/r1 = f(r2)/r2 = constant, which gives f(r) = c*r. And the rest, determining the constant c follows from the condition on f(r) being a PDF.
The SQLiteDatabase.deleteDatabase(File file) static method was added in API 16. If you want to write apps that support older devices, how do you do this?
I tried: file.delete();
but it messes up SQLiteOpenHelper.
Thanks.
NEVER MIND! I later realized you are using Context.deleteDatabase(). The Context one works great and deletes the journal too. Works for me.
Also, I found I needed to call SQLiteOpenHelp.close() before doing the delete, so that I could then use LoaderManager to recreate it.
A clean way to download a file is:
import urllib
testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")
This downloads a file from a website and names it file.gz
. This is one of my favorite solutions, from Downloading a picture via urllib and python.
This example uses the urllib
library, and it will directly retrieve the file form a source.
//split string into an array and grab the first item
var streetaddress = addy.split(',')[0];
Also, I'd recommend naming your variables with camel-case(streetAddress) for better readability.
I disagree with the previous answers suggesting ArrayList
, because ArrayList
is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:
ArrayList list = new ArrayList(4);
list.put(3,"Test");
It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance
I had same problem about SaveChanges() in EF but in my case I forget to update my sql table then after I used migration my problem solved so maybe updating your tables will solve problem.
Maybe you can try on pyconcrete
encrypt .pyc
to .pye
and decrypt when import it
encrypt & decrypt by library OpenAES
convert all of your .py
to *.pye
$ pyconcrete-admin.py compile --source={your py script} --pye
$ pyconcrete-admin.py compile --source={your py module dir} --pye
remove *.py
*.pyc
or copy *.pye
to other folder
main.py encrypted as main.pye, it can't be executed by normal python
.
You must use pyconcrete
to process the main.pye script.
pyconcrete
(exe) will be installed in your system path (ex: /usr/local/bin)
pyconcrete main.pye
src/*.pye # your libs
download pyconcrete source and install by setup.py
$ python setup.py install \
--install-lib={your project path} \
--install-scripts={where you want to execute pyconcrete-admin.py and pyconcrete(exe)}
import pyconcrete in your main script
recommendation project layout
main.py # import pyconcrete and your lib
pyconcrete/* # put pyconcrete lib in project root, keep it as original files
src/*.pye # your libs
Maven is not designed to work that way, but a workaround exists to achieve this goal (maybe with side effects, you will have to give a try). The trick is to tell the child project to find its parent via its relative path rather than its pure maven coordinates, and in addition to externalize the version number in a property :
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<packaging>pom</packaging>
<properties>
<!-- Unique entry point for version number management -->
<global.version>0.1-SNAPSHOT</global.version>
</properties>
<parent>
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<relativePath>..</relativePath>
</parent>
<groupId>com.dummy.bla.sub</groupId>
<artifactId>kid</artifactId>
I used that trick for a while for one of my project, with no specific problem, except the fact that maven logs a lot of warnings at the beginning of the build, which is not very elegant.
Seems maven 3.0.4 does not allow such a configuration anymore.
CREATE FUNCTION getDateDiffHours(@fdate AS datetime,@tdate as datetime) RETURNS varchar (50) AS BEGIN DECLARE @cnt int DECLARE @cntDate datetime DECLARE @dayDiff int DECLARE @dayDiffWk int DECLARE @hrsDiff decimal(18)
DECLARE @markerFDate datetime
DECLARE @markerTDate datetime
DECLARE @fTime int
DECLARE @tTime int
DECLARE @nfTime varchar(8)
DECLARE @ntTime varchar(8)
DECLARE @nfdate datetime
DECLARE @ntdate datetime
-------------------------------------
--DECLARE @fdate datetime
--DECLARE @tdate datetime
--SET @fdate = '2005-04-18 00:00:00.000'
--SET @tdate = '2005-08-26 15:06:07.030'
-------------------------------------
DECLARE @tempdate datetime
--setting weekends
SET @fdate = dbo.getVDate(@fdate)
SET @tdate = dbo.getVDate(@tdate)
--RETURN @fdate
SET @fTime = datepart(hh,@fdate)
SET @tTime = datepart(hh,@tdate)
--RETURN @fTime
if datediff(hour,@fdate, @tdate) <= 9
RETURN(convert(varchar(50),0) + ' Days ' + convert(varchar(50),datediff(hour,@fdate, @tdate))) + ' Hours'
else
--setting working hours
SET @nfTime = dbo.getV00(convert(varchar(2),datepart(hh,@fdate))) + ':' +dbo.getV00(convert(varchar(2),datepart(mi,@fdate))) + ':'+ dbo.getV00(convert(varchar(2),datepart(ss,@fdate)))
SET @ntTime = dbo.getV00(convert(varchar(2),datepart(hh,@tdate))) + ':' +dbo.getV00(convert(varchar(2),datepart(mi,@tdate))) + ':'+ dbo.getV00(convert(varchar(2),datepart(ss,@tdate)))
IF @fTime > 17
begin
set @nfTime = '17:00:00'
end
else
begin
IF @fTime < 8
set @nfTime = '08:00:00'
end
IF @tTime > 17
begin
set @ntTime = '17:00:00'
end
else
begin
IF @tTime < 8
set @ntTime = '08:00:00'
end
-- used for working out whole days
SET @nfdate = dateadd(day,1,@fdate)
SET @ntdate = @tdate
SET @nfdate = convert(varchar,datepart(yyyy,@nfdate)) + '-' + convert(varchar,datepart(mm,@nfdate)) + '-' + convert(varchar,datepart(dd,@nfdate))
SET @ntdate = convert(varchar,datepart(yyyy,@ntdate)) + '-' + convert(varchar,datepart(mm,@ntdate)) + '-' + convert(varchar,datepart(dd,@ntdate))
SET @cnt = 0
SET @dayDiff = 0
SET @cntDate = @nfdate
SET @dayDiffWk = convert(decimal(18,2),@ntdate-@nfdate)
--select @nfdate,@ntdate
WHILE @cnt < @dayDiffWk
BEGIN
IF (NOT DATENAME(dw, @cntDate) = 'Saturday') AND (NOT DATENAME(dw, @cntDate) = 'Sunday')
BEGIN
SET @dayDiff = @dayDiff + 1
END
SET @cntDate = dateadd(day,1,@cntDate)
SET @cnt = @cnt + 1
END
--SET @dayDiff = convert(decimal(18,2),@ntdate-@nfdate) --datediff(day,@nfdate,@ntdate)
--SELECT @dayDiff
set @fdate = convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) + ' ' + @nfTime
set @tdate = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate)) + ' ' + @ntTime
set @markerFDate = convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) + ' ' + '17:00:00'
set @markerTDate = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate)) + ' ' + '08:00:00'
--select @fdate,@tdate
--select @markerFDate,@markerTDate
set @hrsDiff = convert(decimal(18,2),datediff(hh,@fdate,@markerFDate))
--select @hrsDiff
set @hrsDiff = @hrsDiff + convert(int,datediff(hh,@markerTDate,@tdate))
--select @fdate,@tdate
IF convert(varchar,datepart(yyyy,@fdate)) + '-' + convert(varchar,datepart(mm,@fdate)) + '-' + convert(varchar,datepart(dd,@fdate)) = convert(varchar,datepart(yyyy,@tdate)) + '-' + convert(varchar,datepart(mm,@tdate)) + '-' + convert(varchar,datepart(dd,@tdate))
BEGIN
--SET @hrsDiff = @hrsDiff - 9
Set @hrsdiff = datediff(hour,@fdate,@tdate)
END
--select FLOOR((@hrsDiff / 9))
IF (@hrsDiff / 9) > 0
BEGIN
SET @dayDiff = @dayDiff + FLOOR(@hrsDiff / 9)
SET @hrsDiff = @hrsDiff - FLOOR(@hrsDiff / 9)*9
END
--select convert(varchar(50),@dayDiff) + ' Days ' + convert(varchar(50),@hrsDiff) + ' Hours'
RETURN(convert(varchar(50),@dayDiff) + ' Days ' + convert(varchar(50),@hrsDiff)) + ' Hours'
END
You must sort your data according your needs (es. in reverse order) and use select top query
You can use Runtime.getRuntime().addShutdownHook(...)
, but you cannot be guaranteed that it will be called in any case.
In Excel 2007 you have the option to show empty cells as gaps, zero or connect data points with a line (I assume it's similar for Excel 2010):
If none of these are optimal and you have a "chunk" of data points (or even single ones) missing, you can group-and-hide them, which will remove them from the chart.
Before hiding:
After hiding:
Issue #1: Multiple Oracle clients are installed.
A very common issue I see in my environment is that I see both workstations and (app) servers with multiple Oracle clients, sometimes as many as four, and possibly with different versions and architectures. If you are relying on the PATH
and running a utility like SQLPLUS
or TNSPING
you'll have one of two unacceptable results:
PATH
successfully resolves the executable and you get ONE version resultPATH
didn't resolve the executable, and you get no results.Either way, you are blind to possibly multiple client installations.
Issue #2: Instant Client doesn't have TNSPING, and sometimes doesn't include SQL*Plus.
If a computer has the Oracle Instant Client (not the full client), then TNSPING
is not included, and SQLPLUS
is an optional-addon. So can't rely on those tools being there. Furthermore, the Instant Client is sometimes installed as an unzip-and-go solution, so there's no Oracle Inventory and nothing in HKLM.
Issue #3: Client was installed using "Custom", and ODBC, OLEDB, ODP.Net, and JDBC were not installed.
Obvious case, there will be no ODBC or JDBC readme's to scrape version info from.
Solution:
One thing that the Instant client and the full client have in common is a DLL file called oraclient10.dll
, oraclient11.dll
, generally: oraclient*.dll
. So let's traverse the hard disk to find them and extract their version info. PowerShell is amazing at this and can do it in one line, reminds me of home sweet Unix. So you could do this programatically or even remotely.
Here's the one-liner (sorry about the right scroll, but that's the nature of one-liners, eh?). Supposing you're already in a PowerShell:
gci C:\,D:\ -recurse -filter 'oraclient*.dll' -ErrorAction SilentlyContinue | %{ $_.VersionInfo } | ft -Property FileVersion, FileName -AutoSize
And if you're not in PowerShell, i.e. you're simply in a CMD shell, then no problem, just call powershell " ... "
, as follows:
powershell "gci C:\,D:\ -recurse -filter 'oraclient*.dll' -ErrorAction SilentlyContinue | %{ $_.VersionInfo } | ft -Property FileVersion, FileName -AutoSize"
Example Outputs
Here's some outputs from some of my systems. This bad citizen has 3 Oracle 11.2.0.3 clients. You can see that some of them are 32-bit and others are 64-bit:
FileVersion FileName
----------- --------
11.2.0.3.0 Production C:\NoSync\app\oracle\product\11.2\client_1\bin\oraclient...
11.2.0.3.0 Production C:\oracle\product\11.2.0\client_1\bin\oraclient11.dll
11.2.0.3.0 Production C:\oracle64\product\11.2.0\client_1\bin\oraclient11.dll
Another system, this one has 10g client on the D:\
FileVersion FileName
----------- --------
10.2.0.4.0 Production D:\oracle\product\10.2\BIN\oraclient10.dll
Caveats/Issues
This obviously requires PowerShell, which is standard in Windows 7+ and Server 2008 R2+. If you have XP (which you shouldn't any more) you can easily install PowerShell.
I haven't tried this on 8i/9i or 12c. If you are running 8i/9i, then there's a good chance you are on an old OS as well and don't have PowerShell and Heaven help you. It should work with 12c, since I see there is such a file oraclient12.dll
that gets installed. I just don't have a Windows 12c client to play with yet.
Just use the following code. It is really useful to send email via Java, and it works:
import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;
public class Main {
public static void main(String[] args) {
final String username="[email protected]";
final String password="password";
Properties prop=new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String body="Dear Renish Khunt Welcome";
String htmlBody = "<strong>This is an HTML Message</strong>";
String textBody = "This is a Text Message.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
message.setText(htmlBody);
message.setContent(textBody, "text/html");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.
const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });
Let's take the example of an NSError
, if there isn't an error being returned you'd want to make it optional to return Nil. There's no point in assigning a value to it if there isn't an error..
var error: NSError? = nil
This also allows you to have a default value. So you can set a method a default value if the function isn't passed anything
func doesntEnterNumber(x: Int? = 5) -> Bool {
if (x == 5){
return true
} else {
return false
}
}
We have two array a and b. the code what did here is array a value is pushed into array b.
let a = [2, 4, 6, 8, 9, 15]
function transform(a) {
let b = ['4', '16', '64']
a.forEach(function(e) {
b.push(e.toString());
});
return b;
}
transform(a)
[ '4', '16', '64', '2', '4', '6', '8', '9', '15' ]
I know it's an old post but I came across the exact same issue and I managed to use this by turning off MALWAREBYTES
program which was causing the issue.
If you have the directory name in myDirectoryPath
,
import java.io.File;
...
File dir = new File(myDirectoryPath);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
}
} else {
// Handle the case where dir is not really a directory.
// Checking dir.isDirectory() above would not be sufficient
// to avoid race conditions with another process that deletes
// directories.
}
to resize image in javascript:
$(window).load(function() {
mitad();doble();
});
function mitad(){
imag0.width=imag0.width/2;
imag0.height=imag0.height/2;
}
function doble(){
imag0.width=imag0.width*2;
imag0.height=imag0.height*2;}
imag0 is the name of the image:
<img src="xxx.jpg" name="imag0">
You can also use
Remove-Migration -Force
This will revert and remove the last applied migration
Nowadays there is a much simpler way:
var fileInput = document.getElementById('upload');
var filename = fileInput.files[0].name;
You may use this..
<body>
<form method="" action="">
<input type="text" name="email" class="input" />
<input type="submit" value="Sign Up" class="button" />
</form>
</body>
<script>
$(document).ready(function() {
$(".input").val("Email Address");
$(".input").on("focus", function() {
$(".input").val("");
});
$(".button").on("click", function(event) {
$(".input").val("");
});
});
</script>
Talking of your own code, the problem is that the attr api of jquery is set by
$('.input').attr('value','Email Adress');
and not as you have done:
$('.input').attr('value') = 'Email address';
http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
Remember that using uninitialized variables in C# is not allowed.
With
bool foo = new bool();
foo will have the default value.
Boolean default is false
consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1. To do this open visual studio and do the following:
Right click on t1, then Script table as, then DROP and Create To, then New Query Editor
you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one.
Thanks
Exception
is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception
must handle or declare it.
Because the join()
method is in the string class, instead of the list class?
I agree it looks funny.
See http://www.faqs.org/docs/diveintopython/odbchelper_join.html:
Historical note. When I first learned Python, I expected join to be a method of a list, which would take the delimiter as an argument. Lots of people feel the same way, and there’s a story behind the join method. Prior to Python 1.6, strings didn’t have all these useful methods. There was a separate string module which contained all the string functions; each function took a string as its first argument. The functions were deemed important enough to put onto the strings themselves, which made sense for functions like lower, upper, and split. But many hard-core Python programmers objected to the new join method, arguing that it should be a method of the list instead, or that it shouldn’t move at all but simply stay a part of the old string module (which still has lots of useful stuff in it). I use the new join method exclusively, but you will see code written either way, and if it really bothers you, you can use the old string.join function instead.
--- Mark Pilgrim, Dive into Python
If you wanted to learn some GUI, may be tic tac toe is good. Even for console, I still find that is a fun problem. Not challenging but a little bit fun. Later you can advance some other games or port that game to GUI, client server or java applet for the web. I think if you want to learn something and get fun as well, game is a good choice:)
Why not use the Actions menu option to set this?
Do the following: If you have Acrobat Pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose 'Execute a menu item'. Click the Add button then select 'File > Print' then OK. Click OK again and save the PDF.
Wrap the label and input in another div with a defined height. This may not work in IE versions lower than 8.
position:absolute;
top:0; bottom:0; left:0; right:0;
margin:auto;
If you want a destructive backspace, you'll need something like
"\b \b"
i.e. a backspace, a space, and another backspace.
For python >= 3.6
, you can use dload:
import dload
t = dload.text(url)
For json
:
j = dload.json(url)
Install:
pip install dload
Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.
Try find / -iname '*numpy*'
I found this post very helpful as I needed to investigate dependencies from a 3rd party supplied library (32 vs 64 bit execution path(s)).
I put together a Q&D recursing bash script based on the 'readelf -d' suggestion on a RHEL 6 distro.
It is very basic and will test every dependency every time even if it might have been tested before (i.e very verbose). Output is very basic too.
#! /bin/bash
recurse ()
# Param 1 is the nuumber of spaces that the output will be prepended with
# Param 2 full path to library
{
#Use 'readelf -d' to find dependencies
dependencies=$(readelf -d ${2} | grep NEEDED | awk '{ print $5 }' | tr -d '[]')
for d in $dependencies; do
echo "${1}${d}"
nm=${d##*/}
#libstdc++ hack for the '+'-s
nm1=${nm//"+"/"\+"}
# /lib /lib64 /usr/lib and /usr/lib are searched
children=$(locate ${d} | grep -E "(^/(lib|lib64|usr/lib|usr/lib64)/${nm1})")
rc=$?
#at least locate... didn't fail
if [ ${rc} == "0" ] ; then
#we have at least one dependency
if [ ${#children[@]} -gt 0 ]; then
#check the dependeny's dependencies
for c in $children; do
recurse " ${1}" ${c}
done
else
echo "${1}no children found"
fi
else
echo "${1}locate failed for ${d}"
fi
done
}
# Q&D -- recurse needs 2 params could/should be supplied from cmdline
recurse "" !!full path to library you want to investigate!!
redirect the output to a file and grep for 'found' or 'failed'
Use and modify, at your own risk of course, as you wish.
Adding a bit more to above-mentioned answers.
id
of a variable changes upon reassignment.
>>> a = 'initial_string'
>>> id(a)
139982120425648
>>> a = 'new_string'
>>> id(a)
139982120425776
Which means that we have mutated the variable a
to point to a new string. Now there exist two string
(str) objects:
'initial_string'
with id
= 139982120425648
and
'new_string'
with id
= 139982120425776
Consider the below code:
>>> b = 'intitial_string'
>>> id(b)
139982120425648
Now, b
points to the 'initial_string'
and has the same id
as a
had before reassignment.
Thus, the 'intial_string'
has not been mutated.
The question was to see if ping responded which this script does.
However this will not work if you get the Host Unreachable message as this returns ERRORLEVEL 0 and passes the check for Received = 1 used in this script, returning Link is UP from the script. Host Unreachable occurs when ping was delivered to target notwork but remote host cannot be found.
If I recall the correct way to check if ping was successful is to look for the string 'TTL' using Find.
@echo off
cls
set ip=%1
ping -n 1 %ip% | find "TTL"
if not errorlevel 1 set error=win
if errorlevel 1 set error=fail
cls
echo Result: %error%
This wont work with IPv6 networks because ping will not list TTL when receiving reply from IPv6 address.
This moment.utc(stringDate, format).toDate()
worked for me.
This not.moment.utc(date).toDate()
None of the above solution work for me. I tried and very frustrated until I watched the following video: https://www.youtube.com/watch?v=tGinfzlp0fE
pip uninstall mysql-connector
work on some computer and it might not work for other computer.
I did the followings:
pip uninstall mysql-connector
pip uninstall mysql-connector-python
pip install mysql-connector-python
Actually, you can process the find
command output in a copy command in two ways:
If the find
command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:
Syntax:
find <Path> <Conditions> | xargs cp -t <copy file path>
Example:
find -mtime -1 -type f | xargs cp -t inner/
But our production data files might contain spaces, so most of time this command is effective:
Syntax:
find <path> <condition> -exec cp '{}' <copy path> \;
Example
find -mtime -1 -type f -exec cp '{}' inner/ \;
In the second example, the last part, the semi-colon is also considered as part of the find
command, and should be escaped before pressing Enter. Otherwise you will get an error something like:
find: missing argument to `-exec'
I am using org.springframework.core.ResolvableType for a ListResultEntity :
ResolvableType resolvableType = ResolvableType.forClassWithGenerics(ListResultEntity.class, itemClass);
ParameterizedTypeReference<ListResultEntity<T>> typeRef = ParameterizedTypeReference.forType(resolvableType.getType());
So in your case:
public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
ResponseEntity<ResponseWrapper<T>> response = template.exchange(
uri,
HttpMethod.POST,
null,
ParameterizedTypeReference.forType(ResolvableType.forClassWithGenerics(ResponseWrapper.class, clazz)));
return response;
}
This only makes use of spring and of course requires some knowledge about the returned types (but should even work for things like Wrapper>> as long as you provide the classes as varargs )
This will add an image to another.
using (Graphics grfx = Graphics.FromImage(image))
{
grfx.DrawImage(newImage, x, y)
}
Graphics is in the namespace System.Drawing
If you
you can do that starting with git 2.10. 2.10 or later is required, because 2.10 fixed the behavior of text=auto together with eol=lf. Source.
Put a .gitattributes
file in the root of your git repository having following contents:
* text=auto eol=lf
Commit it.
You can also add an .editorconfig
in the root of your repository to ensure that modern tooling creates new files with the desired line endings.
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
Try to make use of linq to Dataset
(from b in table1.AsEnumerable()
select new { id = b.Field<int>("id")}).Except(
from a in table2.AsEnumerable()
select new {id = a.Field<int>("id")})
Check this article : Comparing DataSets using LINQ
One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'
This will install google test and mock library in Ubuntu/Debian based system:
sudo apt-get install google-mock
Tested in google cloud in debian based image.
Please be aware that the accepted answer is a bit incomplete. Yes, at the most basic level Collation handles sorting. BUT, the comparison rules defined by the chosen Collation are used in many places outside of user queries against user data.
COLLATE SQL_Latin1_General_CP1_CI_AS
do?" means "What does the COLLATE
clause of CREATE DATABASE
do?", then:The COLLATE {collation_name}
clause of the CREATE DATABASE
statement specifies the default Collation of the Database, and not the Server; Database-level and Server-level default Collations control different things.
Server (i.e. Instance)-level controls:
master
, model
, msdb
, and tempdb
.tempdb
, it is then the default Collation for string columns in temporary tables (global and local), but not table variables.master
, it is then the Collation used for Server-level data, such as Database names (i.e. name
column in sys.databases
), Login names, etc.GOTO
labelsCOLLATE
clause is missingDatabase-level controls:
CHAR
, VARCHAR
, NCHAR
, NVARCHAR
, TEXT
, and NTEXT
-- but don't use TEXT
or NTEXT
) when the COLLATE
clause is missing from the column definition. This goes for both CREATE TABLE
and ALTER TABLE ... ADD
statements.'some text'
) and string variables (i.e. @StringVariable
). This Collation is only ever used when comparing strings and variables to other strings and variables. When comparing strings / variables to columns, then the Collation of the column will be used.sys.objects
), column names (i.e. sys.columns
), index names (i.e. sys.indexes
), etc.Also:
Latin1
does not mean "ASCII" since standard ASCII only covers values 0 - 127, and all code pages (that can be represented in SQL Server, and even NVARCHAR
) map those same 128 values to the same characters.COLLATE SQL_Latin1_General_CP1_CI_AS
do?" means "What does this particular collation do?", then:Because the name start with SQL_
, this is a SQL Server collation, not a Windows collation. These are definitely obsolete, even if not officially deprecated, and are mainly for pre-SQL Server 2000 compatibility. Although, quite unfortunately SQL_Latin1_General_CP1_CI_AS
is very common due to it being the default when installing on an OS using US English as its language. These collations should be avoided if at all possible.
Windows collations (those with names not starting with SQL_
) are newer, more functional, have consistent sorting between VARCHAR
and NVARCHAR
for the same values, and are being updated with additional / corrected sort weights and uppercase/lowercase mappings. These collations also don't have the potential performance problem that the SQL Server collations have: Impact on Indexes When Mixing VARCHAR and NVARCHAR Types.
Latin1_General
is the culture / locale.
NCHAR
, NVARCHAR
, and NTEXT
data this determines the linguistic rules used for sorting and comparison.CHAR
, VARCHAR
, and TEXT
data (columns, literals, and variables) this determines the:
Latin1_General
collations use code page 1252, Hebrew
collations use code page 1255, and so on.CP{code_page}
or {version}
CP{code_page}
, is the 8-bit code page that determines what characters map to values 128 - 255. While there are four code pages for Double-Byte Character Sets (DBCS) that can use 2-byte combinations to create more than 256 characters, these are not available for the SQL Server collations.For Windows collations: {version}
, while not present in all collation names, refers to the SQL Server version in which the collation was introduced (for the most part). Windows collations with no version number in the name are version 80
(meaning SQL Server 2000 as that is version 8.0). Not all versions of SQL Server come with new collations, so there are gaps in the version numbers. There are some that are 90
(for SQL Server 2005, which is version 9.0), most are 100
(for SQL Server 2008, version 10.0), and a small set has 140
(for SQL Server 2017, version 14.0).
I said "for the most part" because the collations ending in _SC
were introduced in SQL Server 2012 (version 11.0), but the underlying data wasn't new, they merely added support for supplementary characters for the built-in functions. So, those endings exist for version 90
and 100
collations, but only starting in SQL Server 2012.
CS
= case-sensitive or CI
= case-insensitiveAS
= accent-sensitive or AI
= accent-insensitiveKS
= Kana type-sensitive or missing = Kana type-insensitiveWS
= width-sensitive or missing = width insensitiveVSS
= variation selector sensitive (only available in the version 140 collations) or missing = variation selector insensitiveOptional last piece:
_SC
at the end means "Supplementary Character support". The "support" only affects how the built-in functions interpret surrogate pairs (which are how supplementary characters are encoded in UTF-16). Without _SC
at the end (or _140_
in the middle), built-in functions don't see a single supplementary character, but instead see two meaningless code points that make up the surrogate pair. This ending can be added to any non-binary, version 90 or 100 collation._BIN
or _BIN2
at the end means "binary" sorting and comparison. Data is still stored the same, but there are no linguistic rules. This ending is never combined with any of the 5 sensitivities or _SC
. _BIN
is the older style, and _BIN2
is the newer, more accurate style. If using SQL Server 2005 or newer, use _BIN2
. For details on the differences between _BIN
and _BIN2
, please see: Differences Between the Various Binary Collations (Cultures, Versions, and BIN vs BIN2)._UTF8
is a new option as of SQL Server 2019. It's an 8-bit encoding that allows for Unicode data to be stored in VARCHAR
and CHAR
datatypes (but not the deprecated TEXT
datatype). This option can only be used on collations that support supplementary characters (i.e. version 90 or 100 collations with _SC
in their name, and version 140 collations). There is also a single binary _UTF8
collation (_BIN2
, not _BIN
).
PLEASE NOTE: UTF-8 was designed / created for compatibility with environments / code that are set up for 8-bit encodings yet want to support Unicode. Even though there are a few scenarios where UTF-8 can provide up to 50% space savings as compared to NVARCHAR
, that is a side-effect and has a cost of a slight hit to performance in many / most operations. If you need this for compatibility, then the cost is acceptable. If you want this for space-savings, you had better test, and TEST AGAIN. Testing includes all functionality, and more than just a few rows of data. Be warned that UTF-8 collations work best when ALL columns, and the database itself, are using VARCHAR
data (columns, variables, string literals) with a _UTF8
collation. This is the natural state for anyone using this for compatibility, but not for those hoping to use it for space-savings. Be careful when mixing VARCHAR data using a _UTF8
collation with either VARCHAR
data using non-_UTF8
collations or NVARCHAR
data, as you might experience odd behavior / data loss. For more details on the new UTF-8 collations, please see: Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?
In Kotlin you just need to set your string value like this:
<string name="song_number_and_title">"%1$d ~ %2$s"</string>
Create a text view on your layout:
<TextView android:text="@string/song_number_and_title"/>
Then do this in your code if you using Anko:
val song = database.use { // get your song from the database }
song_number_and_title.setText(resources.getString(R.string.song_number_and_title, song.number, song.title))
You might need to get your resources from the application context.
ctrl + w, w as mentioned can be used for navigating from pane to pane.
Now you can select a particular change alone and paste it to the other pane as follows.Here I am giving an eg as if I wanted to change my piece of code from pane 1 to pane 2 and currently my cursor is in pane1
Use Shift-v to highlight a line and use up or down keys to select the piece of code you require and continue from step 3 written below to paste your changes in the other pane.
Use visual mode and then change it
1 click 'v' this will take you to visual mode 2 use up or down key to select your required code 3 click on ,Esc' escape key 4 Now use 'yy' to copy or 'dd' to cut the change 5 do 'ctrl + w, w' to navigate to pane2 6 click 'p' to paste your change where you require
Without favouring any particular naming choice, remember that a git repo can be cloned into any root directory of your choice:
git clone https://github.com/user/repo.git myDir
Here repo.git
would be cloned into the myDir
directory.
So even if your naming convention for a public repo ended up to be slightly incorrect, it would still be possible to fix it on the client side.
That is why, in a distributed environment where any client can do whatever he/she wants, there isn't really a naming convention for Git repo.
(except to reserve "xxx.git
" for bare form of the repo 'xxx
')
There might be naming convention for REST service (similar to "Are there any naming convention guidelines for REST APIs?"), but that is a separate issue.
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
As a Windows 10 user, I followed Dheerendra's answer, and it worked for me one day. The next day, I experienced the issue again, and his fix didn't work. For me, the fix was to update bundler
with:
gem update bundler
I believe my version of bundler
was more than a few months old.
How about the PATINDEX function?
The pattern matching in TSQL is not a complete regex library, but it gives you the basics.
(From Books Online)
Wildcard Meaning
% Any string of zero or more characters.
_ Any single character.
[ ] Any single character within the specified range
(for example, [a-f]) or set (for example, [abcdef]).
[^] Any single character not within the specified range
(for example, [^a - f]) or set (for example, [^abcdef]).
Here is a working solution:
Instead of setting the spinner's OnClickListener, we are setting OnTouchListener and OnKeyListener.
spinner.setOnTouchListener(Spinner_OnTouch);
spinner.setOnKeyListener(Spinner_OnKey);
and the listeners:
private View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
doWhatYouWantHere();
}
return true;
}
};
private static View.OnKeyListener Spinner_OnKey = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
doWhatYouWantHere();
return true;
} else {
return false;
}
}
};
You should follow the guidelines on Add a secondary horizontal axis:
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
Click Secondary Horizontal Axis, and then click the display option that you want.
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
I don't have an Ubuntu box, but on Red Hat Linux you can see all running services by running the following command:
service --status-all
On the list the +
indicates the service is running, -
indicates service is not running, ?
indicates the service state cannot be determined.
iter->first
and iter->second
are variables, you are attempting to call them as methods.
For single line comment you can use Ctrl+/ and for multiple line comment you can use Ctrl + Shift + / after selecting the lines you want to comment in java editor.
On Mac/OS X you can use ? + / to comment out single lines or selected blocks.
First of all, install the prerequisite libraries:
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
Then install rbenv, which is used to install Ruby:
cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL
rbenv install 2.3.1
rbenv global 2.3.1
ruby -v
Then (optional) tell Rubygems to not install local documentation:
echo "gem: --no-ri --no-rdoc" > ~/.gemrc
Credits: https://gorails.com/setup/ubuntu/14.10
Warning!!!
There are issues with Gnome-Shell
. See comment below.
Don't forget to specify mapping information in .config file
e.g.
where MyApp.Data is assembly that contains your mappings
The public java.util.List
subclasses of the JDK don't provide a fixed size feature that doesn't make part of the List
specification.
You could find it only in Queue
subclasses (for example ArrayBlockingQueue
, a bounded blocking queue backed by an array for example) that handle very specific requirements.
In Java, with a List
type, you could implement it according to two scenarios :
1) The fixed list size is always both the actual and the maximum size.
It sounds as an array definition. So Arrays.asList()
that returns a fixed-size list backed by the specified array is what you are looking for. And as with an array you can neither increase nor decrease its size but only changing its content. So adding and removing operation are not supported.
For example :
Foo[] foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput);
foos.add(new Foo()); // throws an Exception
foos.remove(new Foo()); // throws an Exception
It works also with a collection as input while first we convert it into an array :
Collection<Foo> foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput.toArray(Foo[]::new)); // Java 11 way
// Or
List<Foo> foos = Arrays.asList(foosInput.stream().toArray(Foo[]::new)); // Java 8 way
2) The list content is not known as soon as its creation. So you mean by fixed size list its maximum size.
You could use inheritance (extends ArrayList
) but you should favor composition over that since it allows you to not couple your class with the implementation details of this implementation and provides also flexibility about the implementation of the decorated/composed.
With Guava Forwarding classes you could do :
import com.google.common.collect.ForwardingList;
public class FixedSizeList<T> extends ForwardingList<T> {
private final List<T> delegate;
private final int maxSize;
public FixedSizeList(List<T> delegate, int maxSize) {
this.delegate = delegate;
this.maxSize = maxSize;
}
@Override protected List<T> delegate() {
return delegate;
}
@Override public boolean add(T element) {
assertMaxSizeNotReached(1);
return super.add(element);
}
@Override public void add(int index, T element) {
assertMaxSizeNotReached(1);
super.add(index, element);
}
@Override public boolean addAll(Collection<? extends T> collection) {
assertMaxSizeNotReached(collection.size());
return super.addAll(collection);
}
@Override public boolean addAll(int index, Collection<? extends T> elements) {
assertMaxSizeNotReached(elements.size());
return super.addAll(index, elements);
}
private void assertMaxSizeNotReached(int size) {
if (delegate.size() + size >= maxSize) {
throw new RuntimeException("size max reached");
}
}
}
And use it :
List<String> fixedSizeList = new FixedSizeList<>(new ArrayList<>(), 3);
fixedSizeList.addAll(Arrays.asList("1", "2", "3"));
fixedSizeList.add("4"); // throws an Exception
Note that with composition, you could use it with any List
implementation :
List<String> fixedSizeList = new FixedSizeList<>(new LinkedList<>(), 3);
//...
Which is not possible with inheritance.
Best answer is to use the from dateutil import parser
.
usage:
from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())
Using C# it's very easy to start a batch command without having a window open. Have a look at the following code example:
Process process = new Process();
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "doSomeBatch.bat";
process.Start();
Is your logic not round the wrong way in that example, you have it hiding when the screen is bigger than 1024. Reverse the cases, make the none
in to a block
and vice versa.
Update January 2016
In addition to other answers, there is sometimes the scenario where you wish to have private modules available in a team context.
Both Github and Bitbucket support the concept of generating a team API Key. This API key can be used as the password to perform API requests as this team.
In your private npm modules add
"private": true
to your package.json
Then to reference the private module in another module, use this in your package.json
{
"name": "myapp",
"dependencies": {
"private-repo":
"git+https://myteamname:[email protected]/myprivate.git",
}
}
where team name = myteamname, and API Key = aQqtcplwFzlumj0mIDdRGCbsAq5d6Xg4
Here I reference a bitbucket repo, but it is almost identical using github too.
Finally, as an alternative, if you really don't mind paying $7 per month (as of writing) then you can now have private NPM modules out of the box.
As per your description, things don't add up. If aSourceDictionary
is a dictionary, then your for loop has to work properly.
>>> source = {'a': [1, 2], 'b': [2, 3]}
>>> target = {}
>>> for key in source:
... target[key] = []
... target[key].extend(source[key])
...
>>> target
{'a': [1, 2], 'b': [2, 3]}
>>>
This code helps to change the background of the title bar programmatically in Android. Change the color to any color you want.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));
}
I'm new to R as well and faced the exact same problem. But then I looked at my data and noticed that it is being caused due to the fact that my csv file was using a comma separator (,) in all numeric columns (Ex: 1,233,444.56 instead of 1233444.56).
I removed the comma separator in my csv file and then reloaded into R. My data frame now recognises all columns as numbers.
I'm sure there's a way to handle this within the read.csv function itself.
Extending the contains function you linked to:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
if(a[i].search(regex) > -1){
return i;
}
}
return -1;
}
Then you call the function with an array of strings and a regex, in your case to look for height:
containsRegex([ '<param name=\"bgcolor\" value=\"#FFFFFF\" />', 'sdafkdf' ], /height/)
You could additionally also return the index where height was found:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
int pos = a[i].search(regex);
if(pos > -1){
return [i, pos];
}
}
return null;
}
Can't you just set left
to 50%
and then have margin-left
set to -25px
to account for it's width: http://jsfiddle.net/9AbYc/
.hero:after {
content:'';
position: absolute;
top: 100%;
left: 50%;
margin-left: -50px;
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/
.hero:after {
content:'';
position: absolute;
top: 100%;
left: 0;
right: 0;
margin: 0 auto;
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
In Short,
git remote rm origin
git remote add origin [email protected]:username/myapp.git
Worked !
Cheers!
Here is a good way to do it.
from django.utils.datastructures import MultiValueDictKeyError
try:
message = 'You submitted: %r' % request.GET['q']
except MultiValueDictKeyError:
message = 'You submitted nothing!'
You don't need to check again if q is in GET request. The call in the QueryDict.get already does that to you.
Another way to see information is stat
command that will show more information. Command stat ~/.ssh
on my machine display
File: ‘/home/sumon/.ssh’ -> ‘/home/sumon/ssh-keys/.ssh.personal’
Size: 34 Blocks: 0 IO Block: 4096 symbolic link
Device: 801h/2049d Inode: 25297409 Links: 1
Access: (0777/lrwxrwxrwx) Uid: ( 1000/ sumon) Gid: ( 1000/ sumon)
Access: 2017-09-26 16:41:18.985423932 +0600
Modify: 2017-09-25 15:48:07.880104043 +0600
Change: 2017-09-25 15:48:07.880104043 +0600
Birth: -
Hope this may help someone.
Sometimes you want to have your GridView as simple as:
<asp:GridView ID="grid" runat="server" />
You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.
protected void Page_Load(object sender, EventArgs e)
{
grid.RowDataBound += grid_RowDataBound;
// Your DB access code here...
// grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// grid.DataBind();
}
void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}
The results shown here.
The simple way to make the browser downloads a file is to make the request like that:
function downloadFile(urlToSend) {
var req = new XMLHttpRequest();
req.open("GET", urlToSend, true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=fileName;
link.click();
};
req.send();
}
This opens the browser download pop up.
Starting with a context, the root view of the associated activity can be had by
View rootView = ((Activity)_context).Window.DecorView.FindViewById(Android.Resource.Id.Content);
In Raw Android it'd look something like:
View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content)
Then simply call the findViewById on this
View v = rootView.findViewById(R.id.your_view_id);
You can simply set to null the file path every time user clicks on the control. Now, even if the user selects the same file, the onchange event will be triggered.
<input id="file" onchange="file_changed(this)" onclick="this.value=null;" type="file" accept="*/*" />
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
final EditText edit = (EditText)findViewById(R.id.editText);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);
if(rb1.isChecked()){
edit.setVisibility(View.VISIBLE);
}
else if(rb2.isChecked()){
edit.setVisibility(View.INVISIBLE);
}
}
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
You can do it if you wrap your text into a span like:
a {_x000D_
color: red;_x000D_
text-decoration: underline;_x000D_
}_x000D_
span {_x000D_
color: blue;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<a href="#">_x000D_
<span>Text</span>_x000D_
</a>
_x000D_
I was able to screen using the device's name anyway so that wasn't the issue. I was actually just trying to find the port number, i.e. 5331, 5332 etc. I managed to find this by a trial and error process using an app called TCP2Serial from the app store on Mac OS X. It isn't free but that's fine as long as I know it works!
Worth the 99c :) http://itunes.apple.com/us/app/tcp2serial/id506186902?mt=12
var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());
The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:
print ("\n" * 100)
Though you could put this in a function:
def cls(): print ("\n" * 100)
And then call it when needed as cls()
You can use .ToArray()
on Lists
and IEnumerables
, and then use String.Join()
as you wanted.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyJRadioButton extends JFrame implements ActionListener
{
JRadioButton rb1,rb2; //components
ButtonGroup bg;
MyJRadioButton()
{
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rb1=new JRadioButton("male");
rb2=new JRadioButton("female");
//add radio button to button group
bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
//add radio buttons to frame,not button group
add(rb1);
add(rb2);
//add action listener to JRadioButton, not ButtonGroup
rb1.addActionListener(this);
rb2.addActionListener(this);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new MyJRadioButton(); //calling constructor
}
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println(((JRadioButton) e.getSource()).getActionCommand());
}
}
:set tabstop=4
:set shiftwidth=4
:set expandtab
This will insert four spaces instead of a tab character. Spaces are a bit more “stable”, meaning that text indented with spaces will show up the same in the browser and any other application.
If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.
based on @fabien-snauwaert's answer but simplified if you do not need the original key
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_values( $array ) as $index=>$value ) {
// display the current index + value
echo $index . ':' . $value;
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}
As firefox does not stringify some object as screen object ; if you want to have the same result such as : JSON.stringify(obj)
:
function objToString (obj) {
var tabjson=[];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
tabjson.push('"'+p +'"'+ ':' + obj[p]);
}
} tabjson.push()
return '{'+tabjson.join(',')+'}';
}
If you control both the HTML and CSS, I'd suggest switching to using ID's on all the divs needed for the rounded corner.
CSS
#d1 {
background: #CFFEB6 url('tr.gif') no-repeat top right;
}
#d2 {
background: url('br.gif') no-repeat bottom right;
}
#d3 {
background: url('bl.gif') no-repeat bottom left;
}
#d4 {
padding: 10px;
}
HTML
<div id="d1"><div id="d2"><div id="d3"><div id="d4">
<div class='button'><a href='#'>Test</a></div>
</div></div></div></div>
If you use Jquery you can add this to your javascript:
$('.smooth-goto').on('click', function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
return false;
});
Also, don't forget to add this class to your a tag too like this:
<a href="#id-of-element" class="smooth-goto">Text</a>
As previously answered (and retracted). To get the base directory, as in the location of the running assembly, don't use Directory.GetCurrentDirectory(), rather get it from IHostingEnvironment.ContentRootPath.
private IHostingEnvironment _hostingEnvironment;
private string projectRootFolder;
public Program(IHostingEnvironment env)
{
_hostingEnvironment = env;
projectRootFolder = env.ContentRootPath.Substring(0,
env.ContentRootPath.LastIndexOf(@"\ProjectRoot\", StringComparison.Ordinal) + @"\ProjectRoot\".Length);
}
However I made an additional error: I had set the ContentRoot Directory to Directory.GetCurrentDirectory() at startup undermining the default value which I had so desired! Here I commented out the offending line:
public static void Main(string[] args)
{
var host = new WebHostBuilder().UseKestrel()
// .UseContentRoot(Directory.GetCurrentDirectory()) //<== The mistake
.UseIISIntegration()
.UseStartup<Program>()
.Build();
host.Run();
}
Now it runs correctly - I can now navigate to sub folders of my projects root with:
var pathToData = Path.GetFullPath(Path.Combine(projectRootFolder, "data"));
I realised my mistake by reading BaseDirectory vs. Current Directory and @CodeNotFound founds answer (which was retracted because it didn't work because of the above mistake) which basically can be found here: Getting WebRoot Path and Content Root Path in Asp.net Core
You can do $this->getRequest()->query->all();
to get all GET params and $this->getRequest()->request->all();
to get all POST params.
So in your case:
$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];
For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html
In order to find chart data using the financial data API of Google, one must simply go to Google as if looking for a search term, type finance into the search engine, and a link to Google finance will appear. Once at the Google finance search engine, type the ticker name into the financial data API engine and the result will be displayed. However, it should be noted that all Google finance charts are delayed by 15 minutes, and at most can be used for a better understanding of the ticker's past history, rather than current price.
A solution to the delayed chart information is to obtain a real-time financial data API. An example of one would be the barchartondemand interface that has real-time quote information, along with other detailed features that make it simpler to find the exact chart you're looking for. With fully customizable features, and specific programming tools for the precise trading information you need, barchartondemand's tools outdo Google finance by a wide margin.
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
For the newbies like me among us: after a little research I figured out what the code jalf posted did.
A functor is a class or struct object which can be "called" like a function. This is made possible by overloading the () operator
. The () operator
(not sure what its called) can take any number of arguments. Other operators only take two i.e. the + operator
can only take two values (one on each side of the operator) and return whatever value you have overloaded it for. You can fit any number of arguments inside a () operator
which is what gives it its flexibility.
To create a functor first you create your class. Then you create a constructor to the class with a parameter of your choice of type and name. This is followed in the same statement by an initializer list (which uses a single colon operator, something I was also new to) which constructs the class member objects with the previously declared parameter to the constructor. Then the () operator
is overloaded. Finally you declare the private objects of the class or struct you have created.
My code (I found jalf's variable names confusing)
class myFunctor
{
public:
/* myFunctor is the constructor. parameterVar is the parameter passed to
the constructor. : is the initializer list operator. myObject is the
private member object of the myFunctor class. parameterVar is passed
to the () operator which takes it and adds it to myObject in the
overloaded () operator function. */
myFunctor (int parameterVar) : myObject( parameterVar ) {}
/* the "operator" word is a keyword which indicates this function is an
overloaded operator function. The () following this just tells the
compiler that () is the operator being overloaded. Following that is
the parameter for the overloaded operator. This parameter is actually
the argument "parameterVar" passed by the constructor we just wrote.
The last part of this statement is the overloaded operators body
which adds the parameter passed to the member object. */
int operator() (int myArgument) { return myObject + myArgument; }
private:
int myObject; //Our private member object.
};
If any of this is inaccurate or just plain wrong feel free to correct me!
You could use a captured variable.
Item result = items.FirstOrDefault();
items.ForEach(x =>
{
if(result.ID < x.ID)
result = x;
});
According to the CI docs (CodeIgniter Email Library)...
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called the email.php, add the $config array in that file. Then save the file at config/email.php and it will be used automatically. You will NOT need to use the $this->email->initialize() function if you save your preferences in a config file.
I was able to get this to work by putting all the settings into application/config/email.php.
$config['useragent'] = 'CodeIgniter';
$config['protocol'] = 'smtp';
//$config['mailpath'] = '/usr/sbin/sendmail';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_user'] = '[email protected]';
$config['smtp_pass'] = 'YOURPASSWORDHERE';
$config['smtp_port'] = 465;
$config['smtp_timeout'] = 5;
$config['wordwrap'] = TRUE;
$config['wrapchars'] = 76;
$config['mailtype'] = 'html';
$config['charset'] = 'utf-8';
$config['validate'] = FALSE;
$config['priority'] = 3;
$config['crlf'] = "\r\n";
$config['newline'] = "\r\n";
$config['bcc_batch_mode'] = FALSE;
$config['bcc_batch_size'] = 200;
Then, in one of the controller methods I have something like:
$this->load->library('email'); // Note: no $config param needed
$this->email->from('[email protected]', '[email protected]');
$this->email->to('[email protected]');
$this->email->subject('Test email from CI and Gmail');
$this->email->message('This is a test.');
$this->email->send();
Also, as Cerebro wrote, I had to uncomment out this line in my php.ini file and restart PHP:
extension=php_openssl.dll
[open git settings (TortoiseGit ? Settings ? Git)][1]
[In GIt: click to edit global .gitconfig][2]
I don't have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1)
in a script tag after the script tags that define function1, etc., you should be good to go.
<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'>
$(document).ready(function1);
</script>
Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.
EDIT: Just realized that I didn't actually answer your question: I don't think there's a cross-browser event that's fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:
<script type='text/javascript'>
function fireWhenReady() {
if (typeof function1 != 'undefined') {
function1();
}
else {
setTimeout(fireWhenReady, 100);
}
}
$(document).ready(fireWhenReady);
</script>
...but you shouldn't have to do that if you get your script tag order correct.
Update: You can get load notifications for script
elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:
function loadScript(path, callback) {
var done = false;
var scr = document.createElement('script');
scr.onload = handleLoad;
scr.onreadystatechange = handleReadyStateChange;
scr.onerror = handleError;
scr.src = path;
document.body.appendChild(scr);
function handleLoad() {
if (!done) {
done = true;
callback(path, "ok");
}
}
function handleReadyStateChange() {
var state;
if (!done) {
state = scr.readyState;
if (state === "complete") {
handleLoad();
}
}
}
function handleError() {
if (!done) {
done = true;
callback(path, "error");
}
}
}
In my experience, error notification (onerror
) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done
variable to avoid duplicate notifications.
Ok so the answer I got helped me in the right direction and I am very thankful. It helped me figure out how to actually record on the iPhone, but I thought I would also include some helpful code I got from the iPhone Reference Library:
I used this code and added it to the avTouch example fairly easily. With the above code sample and the sample from the reference library, I was able to get this to work pretty good.
here is the code for showing no of rows in the table with PHP
$sql="select count(*) as total from student_table";
$result=mysqli_query($con,$sql);
$data=mysqli_fetch_assoc($result);
echo $data['total'];
Python 3
from urllib.error import HTTPError
Python 2
from urllib2 import HTTPError
Just catch HTTPError
, handle it, and if it's not Error 404, simply use raise
to re-raise the exception.
See the Python tutorial.
e.g. complete example for Pyhton 2
import urllib2
from urllib2 import HTTPError
try:
urllib2.urlopen("some url")
except HTTPError as err:
if err.code == 404:
<whatever>
else:
raise
These are the main factors involved:
Note 1: you must initialize final member variables on every implemented constructor!
Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is not valid:
private final int memberVar;
public Foo() {
// Invalid initialization of a final member
init();
}
private void init() {
memberVar = 10;
}
Note 3: arrays are Objects in Java, even if they store primitives.
Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.
I am attaching a code example, presenting the aforementioned cases:
public class Foo {
// Static and member variables are initialized to default values
// Primitives
private int a; // Default 0
private static int b; // Default 0
// Objects
private Object c; // Default NULL
private static Object d; // Default NULL
// Arrays (note: they are objects too, even if they store primitives)
private int[] e; // Default NULL
private static int[] f; // Default NULL
// What if declared as final?
// Primitives
private final int g; // Not initialized. MUST set in the constructor
private final static int h; // Not initialized. MUST set in a static {}
// Objects
private final Object i; // Not initialized. MUST set in constructor
private final static Object j; // Not initialized. MUST set in a static {}
// Arrays
private final int[] k; // Not initialized. MUST set in constructor
private final static int[] l; // Not initialized. MUST set in a static {}
// Initialize final statics
static {
h = 5;
j = new Object();
l = new int[5]; // Elements of l are initialized to 0
}
// Initialize final member variables
public Foo() {
g = 10;
i = new Object();
k = new int[10]; // Elements of k are initialized to 0
}
// A second example constructor
// You have to initialize final member variables to every constructor!
public Foo(boolean aBoolean) {
g = 15;
i = new Object();
k = new int[15]; // Elements of k are initialized to 0
}
public static void main(String[] args) {
// Local variables are not initialized
int m; // Not initialized
Object n; // Not initialized
int[] o; // Not initialized
// We must initialize them before use
m = 20;
n = new Object();
o = new int[20]; // Elements of o are initialized to 0
}
}
EXISTS
will be faster because once the engine has found a hit, it will quit looking as the condition has proved true.
With IN
, it will collect all the results from the sub-query before further processing.
make sure your app is live on developer.facebook.com
This green circle is indicating the app is live
If it is not then follow this two steps for make your app live
Step 1 Go to your application -> setting => and add Contact Email and apply save Changes
Setp 2 Then goto App Review option and make sure this toggle is Yes i added a screen shot
Do it in two steps.
rm -r bar/
cp -r foo/ bar/
Use django-widget-tweaks, it is easy to use and works pretty well.
Otherwise this can be done using a custom template filter.
Considering you render your form this way :
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject }}
</div>
</form>
form.subject is an instance of BoundField which has the as_widget method.
you can create a custom filter "addcss" in "my_app/templatetags/myfilters.py"
from django import template
register = template.Library()
@register.filter(name='addcss')
def addcss(value, arg):
css_classes = value.field.widget.attrs.get('class', '').split(' ')
if css_classes and arg not in css_classes:
css_classes = '%s %s' % (css_classes, arg)
return value.as_widget(attrs={'class': css_classes})
And then apply your filter:
{% load myfilters %}
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject|addcss:'MyClass' }}
</div>
</form>
form.subjects will then be rendered with the "MyClass" css class.
Hope this help.
EDIT 1
Update filter according to dimyG's answer
Add django-widget-tweak link
EDIT 2
You can use relative URLs from the root of your repo with <a href="">
. Assuming your repo is named testRel
, put the following in testRel/README.md
:
# My Project
is really really cool. My Project has a subdir named myLib, see below.
## myLib docs
see documentation:
* <a href="testRel/myLib">myLib/</a>
* <a href="testRel/myLib/README.md">myLib/README.md</a>
This error:
python: can't open file 'test.py': [Errno 2] No such file or directory
Means that the file "test.py" doesn't exist. (Or, it does, but it isn't in the current working directory.)
I must save the file in any specific folder to make it run on terminal?
No, it can be where ever you want. However, if you just say, "test.py", you'll need to be in the directory containing test.py.
Your terminal (actually, the shell in the terminal) has a concept of "Current working directory", which is what directory (folder) it is currently "in".
Thus, if you type something like:
python test.py
test.py
needs to be in the current working directory. In Linux, you can change the current working directory with cd
. You might want a tutorial if you're new. (Note that the first hit on that search for me is this YouTube video. The author in the video is using a Mac, but both Mac and Linux use bash
for a shell, so it should apply to you.)
Update
Ruby 2.1.0 is released today. And I comes with Array#to_h
(release notes and ruby-doc), which solves the issue of converting an Array
to a Hash
.
Ruby docs example:
[[:foo, :bar], [1, 2]].to_h # => {:foo => :bar, 1 => 2}
Well, PHP can do this easily.
It can be done with the PHP mail()
function. Here's what a simple function would look like:
<?php
$to_email = '[email protected]';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: [email protected]';
mail($to_email,$subject,$message,$headers);
?>
This will send a background e-mail to the recipient specified in the $to_email
.
The above example uses hard coded values in the source code for the email address and other details for simplicity.
Let’s assume you have to create a contact us form for users fill in the details and then submit.
Let’s create a custom function that validates and sanitizes the email address using the filter_var()
built in function.
Here's an example code:
<?php
function sanitize_my_email($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
$to_email = '[email protected]';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: [email protected]';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
echo "Invalid input";
} else { //send email
mail($to_email, $subject, $message, $headers);
echo "This email is sent using PHP Mail";
}
?>
We will now let this be a separate PHP file, for example sendmail.php
.
Then, will use this file on form submission, using the action
attribute of the form, like:
<form action="sendmail.php" method="post">
<input type="text" value="Your Name: ">
<input type="password" value="Set Up A Passworrd">
<input type="submit" value="Signup">
<input type="reset" value="Reset Form">
</form>
Hope I could help
Attributes is same term used alternativly for properties or fields or data members or class members.
For me, the problem was that my target profile by accident got set to ".Net Framework 4 Client profile". When I rebuilt the service in question using the ".Net Framework 4", the problem went away!
128M == 134217728
, the number you are seeing.
The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.
Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.
This functionality has been added to the IDE now (working Pycharm 2018.3)
Just click the EnvFile
tab in the run configuration, click Enable EnvFile
and click the + icon to add an env file
Update: Essentially the same as the answer by @imguelvargasf but the the plugin was enabled by default for me.
I'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>
, then the proper syntax is
int myInt;
scanf("%d", &myInt);
You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where
stdin
file is closed or broken, so you get nothing at all.To check for this, you can capture the return code from scanf
like this:
int result = scanf("%d", &myInt);
If stdin
encounters an error while reading, result
will be EOF
, and you can check for errors like this:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin
until you consume all the offending input. You can do this as follows, using the fact that scanf
returns 0 if nothing was read:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
if (result == 0) {
while (fgetc(stdin) != '\n') // Read until a newline is found
;
}
Hope this helps!
EDIT: In response to the more detailed question, here's a more appropriate answer. :-)
The problem with this code is that when you write
printf("got the number: %d", scanf("%d", &x));
This is printing the return code from scanf
, which is EOF
on a stream error, 0
if nothing was read, and 1
otherwise. This means that, in particular, if you enter an integer, this will always print 1
because you're printing the status code from scanf
, not the number you read.
To fix this, change this to
int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);
Hope this helps!
Revised (works if you have multiple children): You can use jQuery (Look at the JSFiddle link)
var d= $('div');
var w;
d.children().each(function(){
w = w + $(this).outerWidth();
d.css('width', w + 'px')
});
Do not forget to include the jQuery...
This answer should be enough to get you set up to follow this tutorial on Building a functional search component with MongoDB, Elasticsearch, and AngularJS.
If you're looking to use faceted search with data from an API then Matthiasn's BirdWatch Repo is something you might want to look at.
So here's how you can setup a single node Elasticsearch "cluster" to index MongoDB for use in a NodeJS, Express app on a fresh EC2 Ubuntu 14.04 instance.
Make sure everything is up to date.
sudo apt-get update
Install NodeJS.
sudo apt-get install nodejs
sudo apt-get install npm
Install MongoDB - These steps are straight from MongoDB docs. Choose whatever version you're comfortable with. I'm sticking with v2.4.9 because it seems to be the most recent version MongoDB-River supports without issues.
Import the MongoDB public GPG Key.
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
Update your sources list.
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Get the 10gen package.
sudo apt-get install mongodb-10gen
Then pick your version if you don't want the most recent. If you are setting your environment up on a windows 7 or 8 machine stay away from v2.6 until they work some bugs out with running it as a service.
apt-get install mongodb-10gen=2.4.9
Prevent the version of your MongoDB installation being bumped up when you update.
echo "mongodb-10gen hold" | sudo dpkg --set-selections
Start the MongoDB service.
sudo service mongodb start
Your database files default to /var/lib/mongo and your log files to /var/log/mongo.
Create a database through the mongo shell and push some dummy data into it.
mongo YOUR_DATABASE_NAME
db.createCollection(YOUR_COLLECTION_NAME)
for (var i = 1; i <= 25; i++) db.YOUR_COLLECTION_NAME.insert( { x : i } )
Now to Convert the standalone MongoDB into a Replica Set.
First Shutdown the process.
mongo YOUR_DATABASE_NAME
use admin
db.shutdownServer()
Now we're running MongoDB as a service, so we don't pass in the "--replSet rs0" option in the command line argument when we restart the mongod process. Instead, we put it in the mongod.conf file.
vi /etc/mongod.conf
Add these lines, subbing for your db and log paths.
replSet=rs0
dbpath=YOUR_PATH_TO_DATA/DB
logpath=YOUR_PATH_TO_LOG/MONGO.LOG
Now open up the mongo shell again to initialize the replica set.
mongo DATABASE_NAME
config = { "_id" : "rs0", "members" : [ { "_id" : 0, "host" : "127.0.0.1:27017" } ] }
rs.initiate(config)
rs.slaveOk() // allows read operations to run on secondary members.
Now install Elasticsearch. I'm just following this helpful Gist.
Make sure Java is installed.
sudo apt-get install openjdk-7-jre-headless -y
Stick with v1.1.x for now until the Mongo-River plugin bug gets fixed in v1.2.1.
wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.1.deb
sudo dpkg -i elasticsearch-1.1.1.deb
curl -L http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz
sudo mv *servicewrapper*/service /usr/local/share/elasticsearch/bin/
sudo rm -Rf *servicewrapper*
sudo /usr/local/share/elasticsearch/bin/service/elasticsearch install
sudo ln -s `readlink -f /usr/local/share/elasticsearch/bin/service/elasticsearch` /usr/local/bin/rcelasticsearch
Make sure /etc/elasticsearch/elasticsearch.yml has the following config options enabled if you're only developing on a single node for now:
cluster.name: "MY_CLUSTER_NAME"
node.local: true
Start the Elasticsearch service.
sudo service elasticsearch start
Verify it's working.
curl http://localhost:9200
If you see something like this then you're good.
{
"status" : 200,
"name" : "Chi Demon",
"version" : {
"number" : "1.1.2",
"build_hash" : "e511f7b28b77c4d99175905fac65bffbf4c80cf7",
"build_timestamp" : "2014-05-22T12:27:39Z",
"build_snapshot" : false,
"lucene_version" : "4.7"
},
"tagline" : "You Know, for Search"
}
Now install the Elasticsearch plugins so it can play with MongoDB.
bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb/1.6.0
bin/plugin --install elasticsearch/elasticsearch-mapper-attachments/1.6.0
These two plugins aren't necessary but they're good for testing queries and visualizing changes to your indexes.
bin/plugin --install mobz/elasticsearch-head
bin/plugin --install lukas-vlcek/bigdesk
Restart Elasticsearch.
sudo service elasticsearch restart
Finally index a collection from MongoDB.
curl -XPUT localhost:9200/_river/DATABASE_NAME/_meta -d '{
"type": "mongodb",
"mongodb": {
"servers": [
{ "host": "127.0.0.1", "port": 27017 }
],
"db": "DATABASE_NAME",
"collection": "ACTUAL_COLLECTION_NAME",
"options": { "secondary_read_preference": true },
"gridfs": false
},
"index": {
"name": "ARBITRARY INDEX NAME",
"type": "ARBITRARY TYPE NAME"
}
}'
Check that your index is in Elasticsearch
curl -XGET http://localhost:9200/_aliases
Check your cluster health.
curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'
It's probably yellow with some unassigned shards. We have to tell Elasticsearch what we want to work with.
curl -XPUT 'localhost:9200/_settings' -d '{ "index" : { "number_of_replicas" : 0 } }'
Check cluster health again. It should be green now.
curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'
Go play.
Simple Steps:
-Open Eclipse.
You can use result emitted from previous Observable thanks to mergeMap (or his alias flatMap) operator like this:
const one = Observable.of('https://api.github.com/users');
const two = (c) => ajax(c);//ajax from Rxjs/dom library
one.mergeMap(two).subscribe(c => console.log(c))
If use update()
or findOneAndUpdate()
with {upsert: true}
option
you can use $setOnInsert
var update = {
updatedAt: new Date(),
$setOnInsert: {
createdAt: new Date()
}
};
Well, I'm a bit late but still would like to share my way of schema creation.
I have schemas for everything that can be described by a word, like you would do it in the classical OOP.
E.G.
Every schema can be saved as a Document or Subdocument, so I declare this for each schema.
Document:
Subdocument:
Using current
on explode
would ease the process.
$str = current(explode("/", $str, 2));
You can use this to refresh an Activity from within itself.
finish();
startActivity(getIntent());
If you want to easily view the contents of objects while debugging, install a tool like Firebug and use console.log
:
console.log(product);
If you want to view the properties of the object itself, don't alert
the object, but its properties:
alert(product.ProductName);
alert(product.UnitPrice);
// etc... (or combine them)
As said, if you really want to boost your JavaScript debugging, use Firefox with the Firebug addon. You will wonder how you ever debugged your code before.
For Debian distro we can override the setting via defaults
/etc/default/tomcat6
Set the JAVA_HOME
pointing to the java version you want.
JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
--DROP TABLE #Employee
CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)
INSERT INTO #Employee VALUES('M11M','Manager',NULL)
INSERT INTO #Employee VALUES('P11P','Manager',NULL)
INSERT INTO #Employee VALUES('AA','Clerk',1)
INSERT INTO #Employee VALUES('AB','Assistant',1)
INSERT INTO #Employee VALUES('ZC','Supervisor',2)
INSERT INTO #Employee VALUES('ZD','Security',2)
SELECT * FROM #Employee (NOLOCK)
;
WITH Emp_CTE
AS
(
SELECT EmpId,EmpName,Designation, ManagerID
,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
FROM #Employee
)
select EmpId,EmpName,Designation, ManagerID
FROM Emp_CTE
order BY ManagerID_N, EmpId
var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');
To loop with each()
$("a.directions-link").each(function() {
var $this = $(this);
var _href = $this.attr("href");
$this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});
The terminology is a bit confusing indeed, but both javax.net.ssl.keyStore
and javax.net.ssl.trustStore
are used to specify which keystores to use, for two different purposes. Keystores come in various formats and are not even necessarily files (see this question), and keytool
is just a tool to perform various operations on them (import/export/list/...).
The javax.net.ssl.keyStore
and javax.net.ssl.trustStore
parameters are the default parameters used to build KeyManager
s and TrustManager
s (respectively), then used to build an SSLContext
which essentially contains the SSL/TLS settings to use when making an SSL/TLS connection via an SSLSocketFactory
or an SSLEngine
. These system properties are just where the default values come from, which is then used by SSLContext.getDefault()
, itself used by SSLSocketFactory.getDefault()
for example. (All of this can be customized via the API in a number of places, if you don't want to use the default values and that specific SSLContext
s for a given purpose.)
The difference between the KeyManager
and TrustManager
(and thus between javax.net.ssl.keyStore
and javax.net.ssl.trustStore
) is as follows (quoted from the JSSE ref guide):
TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted.
KeyManager: Determines which authentication credentials to send to the remote host.
(Other parameters are available and their default values are described in the JSSE ref guide. Note that while there is a default value for the trust store, there isn't one for the key store.)
Essentially, the keystore in javax.net.ssl.keyStore
is meant to contain your private keys and certificates, whereas the javax.net.ssl.trustStore
is meant to contain the CA certificates you're willing to trust when a remote party presents its certificate. In some cases, they can be one and the same store, although it's often better practice to use distinct stores (especially when they're file-based).
Look into nginx config file to be sure. This command greps for whatever is configured on your Machine:
cat /etc/nginx/sites-enabled/default |grep "root"
on my machine it was :root /usr/share/nginx/www;
$("body").on('change', '#location', function(e) {
var option = $('option:selected', this).attr('myTag');
});
Look at the help page for load
. What load returns is the names of the objects created, so you can look at the contents of isfar to see what objects were created. The fact that nothing else is showing up with ls()
would indicate that maybe there was nothing stored in your file.
Also note that load will overwrite anything in your global environment that has the same name as something in the file being loaded when used with default behavior. If you mainly want to examine what is in the file, and possibly use something from that file along with other objects in your global environment then it may be better to use the attach
function or create a new environment (new.env
) and load the file into that environment using the envir
argument to load
.
You can get value
of key
like this...
var obj = {
a: "A",
b: "B",
c: "C"
};
console.log(obj.a);
console.log(obj['a']);
name = "a";
console.log(obj[name])
_x000D_
For a nice step-by-step x86 Mac-specific introduction see http://peter.michaux.ca/articles/assembly-hello-world-for-os-x. The other links I’ve tried have some non-Mac pitfalls.
@Jon's :parse
/:endparse
scheme is a great start, and he has my gratitude for the initial pass, but if you think that the Windows torturous batch system would let you off that easy… well, my friend, you are in for a shock. I have spent the whole day with this devilry, and after much painful research and experimentation I finally managed something viable for a real-life utility.
Let us say that we want to implement a utility foobar
. It requires an initial command. It has an optional parameter --foo
which takes an optional value (which cannot be another parameter, of course); if the value is missing it defaults to default
. It also has an optional parameter --bar
which takes a required value. Lastly it can take a flag --baz
with no value allowed. Oh, and these parameters can come in any order.
In other words, it looks like this:
foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]
Complicated? No, that seems pretty typical of real life utilities. (git
anyone?)
Without further ado, here is a solution:
@ECHO OFF
SETLOCAL
REM FooBar parameter demo
REM By Garret Wilson
SET CMD=%~1
IF "%CMD%" == "" (
GOTO usage
)
SET FOO=
SET DEFAULT_FOO=default
SET BAR=
SET BAZ=
SHIFT
:args
SET PARAM=%~1
SET ARG=%~2
IF "%PARAM%" == "--foo" (
SHIFT
IF NOT "%ARG%" == "" (
IF NOT "%ARG:~0,2%" == "--" (
SET FOO=%ARG%
SHIFT
) ELSE (
SET FOO=%DEFAULT_FOO%
)
) ELSE (
SET FOO=%DEFAULT_FOO%
)
) ELSE IF "%PARAM%" == "--bar" (
SHIFT
IF NOT "%ARG%" == "" (
SET BAR=%ARG%
SHIFT
) ELSE (
ECHO Missing bar value. 1>&2
ECHO:
GOTO usage
)
) ELSE IF "%PARAM%" == "--baz" (
SHIFT
SET BAZ=true
) ELSE IF "%PARAM%" == "" (
GOTO endargs
) ELSE (
ECHO Unrecognized option %1. 1>&2
ECHO:
GOTO usage
)
GOTO args
:endargs
ECHO Command: %CMD%
IF NOT "%FOO%" == "" (
ECHO Foo: %FOO%
)
IF NOT "%BAR%" == "" (
ECHO Bar: %BAR%
)
IF "%BAZ%" == "true" (
ECHO Baz
)
REM TODO do something with FOO, BAR, and/or BAZ
GOTO :eof
:usage
ECHO FooBar
ECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]
EXIT /B 1
Yes, it really is that bad. See my similar post at https://stackoverflow.com/a/50653047/421049, where I provide more analysis of what is going on in the logic, and why I used certain constructs.
Hideous. Most of that I had to learn today. And it hurt.
In XSLT the same <xsl:variable>
can be declared only once and can be given a value only at its declaration. If more than one variables are declared at the same time, they are in fact different variables and have different scope.
Therefore, the way to achieve the wanted conditional setting of the variable and producing its value is the following:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="class">
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
subexists: <xsl:text/>
<xsl:value-of select="$subexists" />
</xsl:template>
</xsl:stylesheet>
When the above transformation is applied on the following XML document:
<class>
<joined-subclass/>
</class>
the wanted result is produced:
subexists: true
How you test depends on the Property's DataType:
| Type | Test | Test2 | Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then | | Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then | Object | If obj.Property Is Nothing Then | | String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then | Variant | If obj.Property = Empty Then |
You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)
Since there is no brute-force approach which (done with it manualy). To know what exactly happened.
Given a hexadecimal number
K?K??1K??2....K2K1K0
The equivalent decimal value is:
K? * 16? + K??1 * 16??1 + K??2 * 16??2 + .... + K2 * 162 + K1 * 161 + K0 * 160
For example, the hex number AB8C
is:
10 * 163 + 11 * 162 + 8 * 161 + 12 * 160 = 43916
Implementation:
//convert hex to decimal number
private static int hexToDecimal(String hex) {
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}
return decimalValue;
}
private static int hexCharToDecimal(char character) {
if (character >= 'A' && character <= 'F')
return 10 + character - 'A';
else //character is '0', '1',....,'9'
return character - '0';
}
In response to @MiniQuark's answer:
I was trying to read in a csv file that was half-French (containing accents) and also some strings which would eventually become integers and floats.
As a test, I created a test.txt
file that looked like this:
Montréal, über, 12.89, Mère, Françoise, noël, 889
I had to include lines 2
and 3
to get it to work (which I found in a python ticket), as well as incorporate @Jabba's comment:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import csv
import unicodedata
def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', unicode(input_str))
return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])
with open('test.txt') as f:
read = csv.reader(f)
for row in read:
for element in row:
print remove_accents(element)
The result:
Montreal
uber
12.89
Mere
Francoise
noel
889
(Note: I am on Mac OS X 10.8.4 and using Python 2.7.3)
You are missing the height
CSS property.
Adding it you will notice that scroll bar will appear.
.wrapper{
// width: 1000px;
width:600px;
overflow-y:scroll;
position:relative;
height: 300px;
}
From documentation:
overflow-y
The overflow-y CSS property specifies whether to clip content, render a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.
instanceof is a keyword that can be used to test if an object is of a specified type.
Example :
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}
Here is my source.
i would suggest the following way:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
private String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.
This whole setup seems a little unstable to me.
Talk to the ffmpegx folks about having a GUI front-end over a command-line backend. It doesn't seem to bother them.
Indeed, I submit that a GUI (or web) front-end over a command-line backend is actually more stable, since you have a very, very clean interface between GUI and command. The command can evolve at a different pace from the web, as long as the command-line options are compatible, you have no possibility of breakage.
In C#, a nice String SubString counter is this unexpectedly tricky fellow:
public static int CCount(String haystack, String needle)
{
return haystack.Split(new[] { needle }, StringSplitOptions.None).Length - 1;
}
You can use the -notmatch operator to get the lines that don't have the characters you are interested in.
Get-Content $FileName | foreach-object {
if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }
a = "A long string with a . in the middle ending with ."
# if you want to find the index of the last occurrence of any string, In our case we #will find the index of the last occurrence of with
index = a.rfind("with")
# the result will be 44, as index starts from 0.
The compile()
method is always called at some point; it's the only way to create a Pattern object. So the question is really, why should you call it explicitly? One reason is that you need a reference to the Matcher object so you can use its methods, like group(int)
to retrieve the contents of capturing groups. The only way to get ahold of the Matcher object is through the Pattern object's matcher()
method, and the only way to get ahold of the Pattern object is through the compile()
method. Then there's the find()
method which, unlike matches()
, is not duplicated in the String or Pattern classes.
The other reason is to avoid creating the same Pattern object over and over. Every time you use one of the regex-powered methods in String (or the static matches()
method in Pattern), it creates a new Pattern and a new Matcher. So this code snippet:
for (String s : myStringList) {
if ( s.matches("\\d+") ) {
doSomething();
}
}
...is exactly equivalent to this:
for (String s : myStringList) {
if ( Pattern.compile("\\d+").matcher(s).matches() ) {
doSomething();
}
}
Obviously, that's doing a lot of unnecessary work. In fact, it can easily take longer to compile the regex and instantiate the Pattern object, than it does to perform an actual match. So it usually makes sense to pull that step out of the loop. You can create the Matcher ahead of time as well, though they're not nearly so expensive:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("");
for (String s : myStringList) {
if ( m.reset(s).matches() ) {
doSomething();
}
}
If you're familiar with .NET regexes, you may be wondering if Java's compile()
method is related to .NET's RegexOptions.Compiled
modifier; the answer is no. Java's Pattern.compile()
method is merely equivalent to .NET's Regex constructor. When you specify the Compiled
option:
Regex r = new Regex(@"\d+", RegexOptions.Compiled);
...it compiles the regex directly to CIL byte code, allowing it to perform much faster, but at a significant cost in up-front processing and memory use--think of it as steroids for regexes. Java has no equivalent; there's no difference between a Pattern that's created behind the scenes by String#matches(String)
and one you create explicitly with Pattern#compile(String)
.
(EDIT: I originally said that all .NET Regex objects are cached, which is incorrect. Since .NET 2.0, automatic caching occurs only with static methods like Regex.Matches()
, not when you call a Regex constructor directly. ref)
x = 10;
if(x > 100 ) console.log('over 100')
else if (x > 90 ) console.log('over 90')
else if (x > 50 ) console.log('over 50')
else if (x > 9 ) console.log('over 9')
else console.log('lower 9')
I found another way to convert an object to a byte[], here is my solution:
IEnumerable en = (IEnumerable) myObject;
byte[] myBytes = en.OfType<byte>().ToArray();
Regards
In older versions of jquery you'll have to do it the "javascript way" using settimeout
setTimeout( function(){$('div').hide();} , 4000);
or
setTimeout( "$('div').hide();", 4000);
Recently with jquery 1.4 this solution has been added:
$("div").delay(4000).hide();
Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.
You can use a third-party library like base64-img or base64-to-image.
const base64Img = require('base64-img');
const data = 'data:image/png;base64,...';
const destpath = 'dir/to/save/image';
const filename = 'some-filename';
base64Img.img(data, destpath, filename, (err, filepath) => {}); // Asynchronous using
const filepath = base64Img.imgSync(data, destpath, filename); // Synchronous using
const base64ToImage = require('base64-to-image');
const base64Str = 'data:image/png;base64,...';
const path = 'dir/to/save/image/'; // Add trailing slash
const optionalObj = { fileName: 'some-filename', type: 'png' };
const { imageType, fileName } = base64ToImage(base64Str, path, optionalObj); // Only synchronous using
std::string
is the C++ equivalent: It's mutable.
UPDATE just use the new way from @cminatti
old answer for historic purposes
IMO it's better to use select() and on() since that way you can have multiple resize event handlers... just don't get too crazy
d3.select(window).on('resize', resize);
function resize() {
// update width
width = parseInt(d3.select('#chart').style('width'), 10);
width = width - margin.left - margin.right;
// resize the chart
x.range([0, width]);
d3.select(chart.node().parentNode)
.style('height', (y.rangeExtent()[1] + margin.top + margin.bottom) + 'px')
.style('width', (width + margin.left + margin.right) + 'px');
chart.selectAll('rect.background')
.attr('width', width);
chart.selectAll('rect.percent')
.attr('width', function(d) { return x(d.percent); });
// update median ticks
var median = d3.median(chart.selectAll('.bar').data(),
function(d) { return d.percent; });
chart.selectAll('line.median')
.attr('x1', x(median))
.attr('x2', x(median));
// update axes
chart.select('.x.axis.top').call(xAxis.orient('top'));
chart.select('.x.axis.bottom').call(xAxis.orient('bottom'));
}
http://eyeseast.github.io/visible-data/2013/08/28/responsive-charts-with-d3/
Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.
In order to match PyQt5's behavior, you have to create the started signal yourself.
Here is an easy solution:
# Use this class instead of QThread
class QThread2(QThread):
# Use this signal instead of "started"
started2 = Signal()
def __init__(self):
QThread.__init__(self)
self.started.connect(self.onStarted)
def onStarted(self):
self.started2.emit()
This will work:
// Connect to Mongo
mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);
mongoose
.connect(db) // Connection String here
.then(() => console.log("MongoDB Connected..."))
.catch(() => console.log(err));
bundle exec rake db:rollback
rails destroy model <model_name>
When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run
bundle exec rake db:rollback
Facebook sharing from a share dialog fails even with @Matthieu answer (which is 100% correct for the rest of social URLs). I had to add a set of URL i reversed from Facebook SDK.
<array>
<string>fbapi</string>
<string>fbauth2</string>
<string>fbshareextension</string>
<string>fb-messenger-api</string>
<string>twitter</string>
<string>whatsapp</string>
<string>wechat</string>
<string>line</string>
<string>instagram</string>
<string>kakaotalk</string>
<string>mqq</string>
<string>vk</string>
<string>comgooglemaps</string>
<string>fbapi20130214</string>
<string>fbapi20130410</string>
<string>fbapi20130702</string>
<string>fbapi20131010</string>
<string>fbapi20131219</string>
<string>fbapi20140410</string>
<string>fbapi20140116</string>
<string>fbapi20150313</string>
<string>fbapi20150629</string>
</array>
To check if any module in a project is 'old':
npm outdated
'outdated' will check every module defined in package.json
and see if there is a newer version in the NPM registry.
For example, say xml2js 0.2.6
(located in node_modules
in the current project) is outdated because a newer version exists (0.2.7). You would see:
[email protected] node_modules/xml2js current=0.2.6
To update all dependencies, if you are confident this is desirable:
npm update
Or, to update a single dependency such as xml2js
:
npm update xml2js
I would suggest (as a first pass) that PUT
should only be used for updating existing entities. POST
should be used for creating new ones. i.e.
/api/users when called with PUT, creates user record
doesn't feel right to me. The rest of your first section (re. verb usage) looks logical, however.
You need to add some arguments. Also, instancing and opening can be put in one line:
fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);
It's ugly, but you can use the setfacl command to achieve exactly what you want.
On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise):
user::rwx
user:user_a:rwx
user:user_b:rwx
...
group::rwx
mask:rwx
other:r-x
default:user:user_a:rwx
default:user:user_b:rwx
....
default:group::rwx
default:user::rwx
default:mask:rwx
default:other:r-x
Name the file acl.lst and fill in your real user names instead of user_X.
You can now set those acls on your directory by issuing the following command:
setfacl -f acl.lst /your/dir/here
Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.
Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.
You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.
To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.
A typical C++ code will be:
hVaultLib = LoadLibrary(L"vaultcli.dll");
if (hVaultLib != NULL)
{
pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");
bStatus = (pVaultEnumerateVaults != NULL)
&& (pVaultFree != NULL)
&& (pVaultGetItemW7 != NULL)
&& (pVaultGetItemW8 != NULL)
&& (pVaultOpenVault != NULL)
&& (pVaultCloseVault != NULL)
&& (pVaultEnumerateItems != NULL);
}
Then you enumerate all stored credentials by calling
VaultEnumerateVaults
Then you go over the results.
Rather than encoding the URL beforehand you can do the following
String link = "http://example.com";
URL url = null;
URI uri = null;
try {
url = new URL(link);
} catch(MalformedURLException e) {
e.printStackTrace();
}
try{
uri = new URI(url.toString())
} catch(URISyntaxException e {
try {
uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),
url.getPort(), url.getPath(), url.getQuery(),
url.getRef());
} catch(URISyntaxException e1 {
e1.printStackTrace();
}
}
try {
url = uri.toURL()
} catch(MalfomedURLException e) {
e.printStackTrace();
}
String encodedLink = url.toString();
Assuming you know the position and the length of the substring:
char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);
You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.
This is a good example of avoiding unnecessary copying by using pointers.
In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.
For example:
INSERT INTO MyTable
( Column1, Column2, Column3 )
VALUES
('John', 123, 'Lloyds Office'),
('Jane', 124, 'Lloyds Office'),
('Billy', 125, 'London Office'),
('Miranda', 126, 'Bristol Office');
Sometimes you may enter instead of in your image location/src: try
./assets/images/picture.jpg
instead of
../assets/images/picture.jpg
All I had to do was set the Minimum SDK Version to 21 in File > Project Structure > App > Flavors
If you use the track by
option, the value
attribute is correctly written, e.g.:
<div ng-init="a = [{label: 'one', value: 15}, {label: 'two', value: 20}]">
<select ng-model="foo" ng-options="x for x in a track by x.value"/>
</div>
produces:
<select>
<option value="" selected="selected"></option>
<option value="15">one</option>
<option value="20">two</option>
</select>
example how i made it , After i fill a Maximum length it will blur from my Field (and the Keyboard will disappear ) , if you have more than one field , you can just add the line that i add '//'
var MaxLength = 8;
$(document).ready(function () {
$('#MyTB').keyup(function () {
if ($(this).val().length >= MaxLength) {
$('#MyTB').blur();
// $('#MyTB2').focus();
}
}); });
The globals()
function returns a dictionary, where keys are names of objects you can name (and values, by the way, are id
s of these objects)
The exec()
function takes a string and executes it as if you just type it in a python console. So, the code is
for i in list(globals().keys()):
if(i[0] != '_'):
exec('del {}'.format(i))
try something like
background: url(bgimage.jpg) no-repeat;
background-size: 100%;
The parameters that you are passing into the DrawImage method should be the size you want the image on the paper rather than the size of the image itself, the DrawImage command will then take care of the scaling for you. Probably the easiest way is to use the following override of the DrawImage command.
args.Graphics.DrawImage(i, args.MarginBounds);
Note: This will skew the image if the proportions of the image are not the same as the rectangle. Some simple math on the size of the image and paper size will allow you to create a new rectangle that fits in the bounds of the paper without skewing the image.
For one liner lovers Array.from()
// creates 8x8 array filed with "0"
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"))
Another one (from comment by dmitry_romanov) use Array().fill()
// creates 8x8 array filed with "0"
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"))
Using ES6+ spread operator ("inspired" by InspiredJW answer :) )
// same as above just a little shorter
const arr2d = [...Array(8)].map(() => Array(8).fill("0"))
With NodeJS is simple like that! And if you want to run this script at each boot of your server, you can have a look on the forever-service application!
var exec = require('child_process').exec;
exec('php main.php', function (error, stdOut, stdErr) {
// do what you want!
});
do wget -r -l0 www.oldsite.com
Then just find www.oldsite.com
would reveal all urls, I believe.
Alternatively, just serve that custom not-found page on every 404 request! I.e. if someone used the wrong link, he would get the page telling that page wasn't found, and making some hints about site's content.
input[type=text]
{
height: 15px;
line-height: 15px;
}
this is correct way to set vertical-middle position.
You're looking for the Skip
and Take
extension methods. Skip
moves past the first N elements in the result, returning the remainder; Take
returns the first N elements in the result, dropping any remaining elements.
See MSDN for more information on how to use these methods: http://msdn.microsoft.com/en-us/library/bb386988.aspx
Assuming you are already taking into account that the pageNumber should start at 0 (decrease per 1 as suggested in the comments) You could do it like this:
int numberOfObjectsPerPage = 10;
var queryResultPage = queryResult
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(numberOfObjectsPerPage);
Otherwise as suggested by @Alvin
int numberOfObjectsPerPage = 10;
var queryResultPage = queryResult
.Skip(numberOfObjectsPerPage * (pageNumber - 1))
.Take(numberOfObjectsPerPage);
The answer from Kukkuz did not work for me until I added in this dependency into the pom file:
<!-- Spring boot Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
From the guide here.
As well as updating the registry resources as outlined here.
It then started working just fine. If anyone in the future runs into the same issue and following the first answer does not solve your problem, follow these 2 other steps after utilizing the code in @Kukkuz's answer and see if that makes a difference.
<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
if(parameter.toLowerCase().startsWith("question")) {
String[] values = parameters.get(parameter);
//your code here
}
}
You have to also add the "navbar-brand" class to your image a
container, also you have to include it inside the .navbar-inner
container, like so:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="navbar-brand" href="index.html"> <img src="images/57x57x300.jpg"></a>
</div>
</div>
</div>
I am not sure if this fits your oracle version. On my 10g I can use pipelined table functions:
set serveroutput on
create type number_list as table of number;
-- since you want this solution
create or replace function split_csv (i_csv varchar2) return number_list pipelined
is
mystring varchar2(2000):= i_csv;
begin
for r in
( select regexp_substr(mystring,'[^,]+',1,level) element
from dual
connect by level <= length(regexp_replace(mystring,'[^,]+')) + 1
)
loop
--dbms_output.put_line(r.element);
pipe row(to_number(r.element, '999999.99'));
end loop;
end;
/
insert into foo
select column_a,column_b from
(select column_value column_a, rownum rn from table(split_csv('0.75, 0.64, 0.56, 0.45'))) a
,(select column_value column_b, rownum rn from table(split_csv('0.25, 0.5, 0.65, 0.8'))) b
where a.rn = b.rn
;