[Performance Test] just in case anyone is wondering, in a stopwatch test comparing
if(nopass.Trim().Length > 0)
if (!string.IsNullOrWhiteSpace(nopass))
these were the results:
Trim-Length with empty value = 15
Trim-Length with not empty value = 52
IsNullOrWhiteSpace with empty value = 11
IsNullOrWhiteSpace with not empty value = 12
What about using the Count
property.
if(listOfObjects.Count != 0)
{
ShowGrid();
HideError();
}
else
{
HideGrid();
ShowError();
}
You could use the ternary operator:
return string.IsNullOrEmpty(strTestString) ? "0" : strTestString
FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
You can do this with the following:
int counter = 0;
String sql = "SELECT projectName,Owner " + "FROM Project WHERE Owner= ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, "");
ResultSet rs = prep.executeQuery();
while (rs.next()) {
counter++;
}
System.out.println(counter);
This will give you the no of rows where the column value is null or blank.
this is how to print whitespaces in python.
import string
string.whitespace
'\t\n\x0b\x0c\r '
i.e .
print "hello world"
print "Hello%sworld"%' '
print "hello", "world"
print "Hello "+"world
.gitignore
.======== Easy peasy! No command line required! ========
All answers are correct, but you need to convert a long big fat number into a timer first:
public String toTimer(long milliseconds){
String finalTimerString = "";
String secondsString;
// Convert total duration into time
int hours = (int)( milliseconds / (1000*60*60));
int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
// Add hours if there
if(hours > 0){
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if(seconds < 10){
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
And this is how you use it:
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));
}
SELECT DATEADD(day,1-DATEpart(day, GETDATE()),GETDATE())
You could use gitk --all
and search for commits "touching paths" and the pathname you are interested in.
If you have a folder and sub-folder full of wav's you want to convert, put below command in a file, save it in a .bat file in the root of the folder where you wan to convert, and then run the bat file
for /R %%g in (*.wav) do start /b /wait "" "C:\ffmpeg-4.0.1-win64-static\bin\ffmpeg" -threads 16 -i "%%g" -acodec libmp3lame "%%~dpng.mp3" && del "%%g"
Adding some content to a div, whether through jQuery or via de DOM-API directly, defaults to the .appendChild()
function. What you can do is to override the .appendChild()
function of the current object and implement an observer in it. Now having overridden our .appendChild()
function, we need to borrow that function from an other object to be able to append the content. Therefor we call the .appendChild()
of an other div to finally append the content. Ofcourse, this counts also for the .removeChild()
.
var obj = document.getElementById("mydiv");
obj.appendChild = function(node) {
alert("changed!");
// call the .appendChild() function of some other div
// and pass the current (this) to let the function affect it.
document.createElement("div").appendChild.call(this, node);
}
};
Here you can find a naïf example. You can extend it by yourself I guess. http://jsfiddle.net/RKLmA/31/
By the way: this shows JavaScript complies the OpenClosed priciple. :)
List running containers:-
$ docker ps
List all containers:-
$ docker ps -a
List only stopped containers:-
$ docker ps --filter "status=exited"
or
$ docker ps -f "status=exited"
Try sudo dpkg-reconfigure phpmyadmin
To Replace config file /etc/phpmyadmin/config-db.php with new version
I've mixed and matched from different schemes I've seen and based on the tooling I'm using.
So my completed branch name would be:
name/feature/issue-tracker-number/short-description
which would translate to:
mike/blogs/RSSI-12/logo-fix
The parts are separated by forward slashes because those get interpreted as folders in SourceTree for easy organization. We use Jira for our issue tracking so including the number makes it easier to look up in the system. Including that number also makes it searchable when trying to find that issue inside Github when trying to submit a pull request.
Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. For example, if you need to add extra validation, or to change a stored field into a calculated you can do so easily if you initially exposed the field as a property. If you just exposed a field directly, then you would have to change the public interface of your class to add the new functionality. That change would break existing clients, requiring them to be recompiled before they could use the new version of your code.
If you write a class library designed for wide consumption (like the .NET Framework, which is used by millions of people), that can be a problem. However, if you are writing a class used internally inside a small code base (say <= 50 K lines), it's really not a big deal, because no one would be adversely affected by your changes. In that case it really just comes down to personal preference.
I did something like that:
HTML:
<p class='parent'>text text text</p>
<img class='child' src='idk.png'>
CSS:
.child {
visibility: hidden;
}
.parent:hover .child {
visibility: visible;
}
Other alternatives to an installer and gacutil are GUI tools like Gac Manager or GACAdmin. Or if you like PowerShell you could use PowerShell GAC from which I am the author.
Code snippet for both recursive and non-recursive approaches:
//helper method to get the list of files from the HDFS path
public static List<String>
listFilesFromHDFSPath(Configuration hadoopConfiguration,
String hdfsPath,
boolean recursive) throws IOException,
IllegalArgumentException
{
//resulting list of files
List<String> filePaths = new ArrayList<String>();
//get path from string and then the filesystem
Path path = new Path(hdfsPath); //throws IllegalArgumentException
FileSystem fs = path.getFileSystem(hadoopConfiguration);
//if recursive approach is requested
if(recursive)
{
//(heap issues with recursive approach) => using a queue
Queue<Path> fileQueue = new LinkedList<Path>();
//add the obtained path to the queue
fileQueue.add(path);
//while the fileQueue is not empty
while (!fileQueue.isEmpty())
{
//get the file path from queue
Path filePath = fileQueue.remove();
//filePath refers to a file
if (fs.isFile(filePath))
{
filePaths.add(filePath.toString());
}
else //else filePath refers to a directory
{
//list paths in the directory and add to the queue
FileStatus[] fileStatuses = fs.listStatus(filePath);
for (FileStatus fileStatus : fileStatuses)
{
fileQueue.add(fileStatus.getPath());
} // for
} // else
} // while
} // if
else //non-recursive approach => no heap overhead
{
//if the given hdfsPath is actually directory
if(fs.isDirectory(path))
{
FileStatus[] fileStatuses = fs.listStatus(path);
//loop all file statuses
for(FileStatus fileStatus : fileStatuses)
{
//if the given status is a file, then update the resulting list
if(fileStatus.isFile())
filePaths.add(fileStatus.getPath().toString());
} // for
} // if
else //it is a file then
{
//return the one and only file path to the resulting list
filePaths.add(path.toString());
} // else
} // else
//close filesystem; no more operations
fs.close();
//return the resulting list
return filePaths;
} // listFilesFromHDFSPath
For scientific python users, here is a simple solution using Pandas:
import pandas as pd
stats = {'a': 1000, 'b': 3000, 'c': 100}
series = pd.Series(stats)
series.idxmax()
>>> b
Yes, I can give you the outline but my Python is a bit rusty and I'm too busy to explain in detail.
Basically, you need to put a proxy in the method that will call the original, eg:
class fred(object):
def blog(self):
print "We Blog"
class methCallLogger(object):
def __init__(self, meth):
self.meth = meth
def __call__(self, code=None):
self.meth()
# would also log the fact that it invoked the method
#example
f = fred()
f.blog = methCallLogger(f.blog)
This StackOverflow answer about callable may help you understand the above.
In more detail:
Although the answer was accepted, due to the interesting discussion with Glenn and having a few minutes free, I wanted to enlarge on my answer:
# helper class defined elsewhere
class methCallLogger(object):
def __init__(self, meth):
self.meth = meth
self.was_called = False
def __call__(self, code=None):
self.meth()
self.was_called = True
#example
class fred(object):
def blog(self):
print "We Blog"
f = fred()
g = fred()
f.blog = methCallLogger(f.blog)
g.blog = methCallLogger(g.blog)
f.blog()
assert(f.blog.was_called)
assert(not g.blog.was_called)
For each works with JQuery as in
$(<selector>).each(function() {
//this points to item
alert('<msg>');
});
JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/
Check it out, works really well.
HTH.
The
break
statement terminates the execution of the nearest enclosingdo
,for
,switch
, orwhile
statement in which it appears. Control passes to the statement that follows the terminated statement.
from msdn.
Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
E.g.
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
I've read a few things about this and unfortunately the ANDROID_ID should not be relied on for uniquely identifying an individual device.
It doesn't seem to be enforced in Android compliance requirements and so manufacturers seem to implement it the way they choose including some using it more as a 'model' ID etc.
Also, be aware that even if a manufacturer has written a generator to make it a UUID (for example), it's not guaranteed to survive a factory reset.
You can use
app:cardBackgroundColor="@color/red"
or
android:backgroundTint="@color/red"
Add bellow line in build.gradle:
compile 'com.commit451:PhotoView:1.2.4'
or
compile 'com.github.chrisbanes:PhotoView:1.3.0'
In Java file:
PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(Your_Image_View);
photoAttacher.update();
When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,
ErrorDocument 404 /yourfoldernames/errors/404.html
Create a User-Defined TableType
in your database:
CREATE TYPE [dbo].[MyTableType] AS TABLE(
[Id] int NOT NULL,
[Name] [nvarchar](128) NULL
)
and define a parameter in your Stored Procedure
:
CREATE PROCEDURE [dbo].[InsertTable]
@myTableType MyTableType readonly
AS
BEGIN
insert into [dbo].Records select * from @myTableType
END
and send your DataTable
directly to sql server:
using (var command = new SqlCommand("InsertTable") {CommandType = CommandType.StoredProcedure})
{
var dt = new DataTable(); //create your own data table
command.Parameters.Add(new SqlParameter("@myTableType", dt));
SqlHelper.Exec(command);
}
To edit the values inside stored-procedure, you can declare a local variable with the same type and insert input table into it:
DECLARE @modifiableTableType MyTableType
INSERT INTO @modifiableTableType SELECT * FROM @myTableType
Then, you can edit @modifiableTableType
:
UPDATE @modifiableTableType SET [Name] = 'new value'
Reading from JsonFile
public static ArrayList<Employee> readFromJsonFile(String fileName){
ArrayList<Employee> result = new ArrayList<Employee>();
try{
String text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(text);
JSONArray arr = obj.getJSONArray("employees");
for(int i = 0; i < arr.length(); i++){
String name = arr.getJSONObject(i).getString("name");
short salary = Short.parseShort(arr.getJSONObject(i).getString("salary"));
String position = arr.getJSONObject(i).getString("position");
byte years_in_company = Byte.parseByte(arr.getJSONObject(i).getString("years_in_company"));
if (position.compareToIgnoreCase("manager") == 0){
result.add(new Manager(name, salary, position, years_in_company));
}
else{
result.add(new OrdinaryEmployee(name, salary, position, years_in_company));
}
}
}
catch(Exception ex){
System.out.println(ex.toString());
}
return result;
}
To get the precise stack trace, as a string, that would have been raised if no try/except were there to step over it, simply place this in the except block that catches the offending exception.
desired_trace = traceback.format_exc(sys.exc_info())
Here's how to use it (assuming flaky_func
is defined, and log
calls your favorite logging system):
import traceback
import sys
try:
flaky_func()
except KeyboardInterrupt:
raise
except Exception:
desired_trace = traceback.format_exc(sys.exc_info())
log(desired_trace)
It's a good idea to catch and re-raise KeyboardInterrupt
s, so that you can still kill the program using Ctrl-C. Logging is outside the scope of the question, but a good option is logging. Documentation for the sys and traceback modules.
Swift 4 & 5:
extension String {
subscript(_ i: Int) -> String {
let idx1 = index(startIndex, offsetBy: i)
let idx2 = index(idx1, offsetBy: 1)
return String(self[idx1..<idx2])
}
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return String(self[start ..< end])
}
subscript (r: CountableClosedRange<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(startIndex, offsetBy: r.upperBound - r.lowerBound)
return String(self[startIndex...endIndex])
}
}
How to use it:
"abcde"[0] --> "a"
"abcde"[0...2] --> "abc"
"abcde"[2..<4] --> "cd"
* How to Download and install CodeBlocks.* ( I have already downloaded )
***How to solve the CodeBlocks environment error.
Go to "Settings"----"Compiler"----"Selected compiler"( GNU GCC Compiler ).
Then, Selected "Toolchain executables".
Now, "( C:\Program Files (x86)\CodeBlocks\MinGW )"
See Video : https://youtu.be/Tb1VnXs60Lg
By default, Log4j
logs to standard output and that means you should be able to see log messages on your Eclipse's console view. To log to a file you need to use a FileAppender
explicitly by defining it in a log4j.properties
file in your classpath.
Create the following log4j.properties
file in your classpath. This allows you to log your message to both a file as well as your console.
log4j.rootLogger=debug, stdout, file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=example.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%p %t %c - %m%n
Note: The above creates an example.log in your current working directory (i.e. Eclipse's project directory) so that the same log4j.properties could work with different projects without overwriting each other's logs.
References:
Apache log4j 1.2 - Short introduction to log4j
Just a quick note. It is DbContext, not DBContext. i.e. with a lowercase 'B'. I discovered this because I had the same problem while intelesense was not working until I tried typing the full name space System.Data.Entity... and name and finally it suggested the lowercase 'b' option:-
System.Data.Entity.DbContext
On Ubuntu 16.04
Here's how I fixed this issue: Refer Docker Compose documentation
sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
After you do the curl command , it'll put docker-compose into the
/usr/local/bin
which is not on the PATH
.
To fix it, create a symbolic link:
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
And now if you do:
docker-compose --version
You'll see that docker-compose is now on the PATH
String
s are immutable. Therefore String.replace()
does not modify id
, it returns a new String
with the appropriate value. Therefore you want to use id = id.replace(".xml", "");
.
You can use something like this
[HttpPost]
public async Task<HttpResponseMessage> AddFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key == "companyName")
{
var companyName = val;
}
}
}
// On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
// so this is how you can get the original file name
var originalFileName = GetDeserializedFileName(result.FileData.First());
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
string path = result.FileData.First().LocalFileName;
//Do whatever you want to do with your file here
return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName );
}
private string GetDeserializedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
public string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
Oxi's answer is just wrong.¹
What you want is:
var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;
Working example:
(function (){
var i = 20, l = 20, html = '';
while (i--){
html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
html += '[ Scroll to #DIV' +i+ ' ]</a>';
html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
}
document.write( html );
})();
¹ I haven't got enough reputation to comment on his answer
You will have to create an auto-increment field with the sequence object (this object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".
It looks like the issue is now solved using an external command called brew rmdeps
or brew rmtree
.
To install and use, issue the following commands:
$ brew tap beeftornado/rmtree
$ brew rmtree <package>
See the above link for more information and discussion.
It appears that currently, there's no easy way to accomplish this.
However, I filed an issue on Homebrew's GitHub page, and somebody suggested a temporary solution until they add an exclusive command to solve this.
There's an external command called brew leaves
which prints all packages that are not dependencies of other packages.
If you do a logical and on the output of brew leaves
and brew deps <package>
, you might just get a list of the orphaned dependency packages, which you can uninstall manually afterwards. Combine this with xargs
and you'll get what you need, I guess (untested, don't count on this).
EDIT: Somebody just suggested a very similar solution, using join
instead of xargs
:
brew rm FORMULA
brew rm $(join <(brew leaves) <(brew deps FORMULA))
See the comment on the issue mentioned above for more info.
Make sure that you have enable windows authentication. If you have anonymous authentication enabled you may be getting a null string.
You could specify the dtype directly when constructing the DataFrame:
>>> df = pd.DataFrame(index=range(0,4),columns=['A'], dtype='float')
>>> df.dtypes
A float64
dtype: object
Specifying the dtype forces Pandas to try creating the DataFrame with that type, rather than trying to infer it.
Simple way on macOS e.g. installed via homebrew
$ ls -l $(which kafka-topics)
/usr/local/bin/kafka-topics -> ../Cellar/kafka/0.11.0.1/bin/kafka-topics
Select File>New>Folder>Assets Folder
Click finish
Right click on assets and create a folder called fonts
Put your font file in assets > fonts
Use code below to change your textView's font
TextView textView = (TextView) findViewById(R.id.textView);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/yourfont.ttf");
textView.setTypeface(typeface);
in addition to original
SELECT DATENAME(m, str(2) + '/1/2011')
you can do this
SELECT DATENAME(m, str([column_name]) + '/1/2011')
this way you get names for all rows in a table. where [column_name] represents a integer column containing numeric value 1 through 12
2 represents any integer, by contact string i created a date where i can extract the month. '/1/2011' can be any date
if you want to do this with variable
DECLARE @integer int;
SET @integer = 6;
SELECT DATENAME(m, str(@integer) + '/1/2011')
Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below
=====================
Yes, you need to import the operator:
import 'rxjs/add/operator/catch';
Or import Observable
this way:
import {Observable} from 'rxjs/Rx';
But in this case, you import all operators.
See this question for more details:
You've changed your scheme destination to a simulator instead of Generic iOS Device.
That's why it is greyed out.
Just use python-benedict
(I did it), it has a merge
(deepupdate) utility method and many others. It works with python 2 / python 3 and it is well tested.
from benedict import benedict
dictionary1=benedict({'level1':{'level2':{'levelA':0,'levelB':1}}})
update={'level1':{'level2':{'levelB':10}}}
dictionary1.merge(update)
print(dictionary1)
# >> {'level1':{'level2':{'levelA':0,'levelB':10}}}
Installation: pip install python-benedict
Documentation: https://github.com/fabiocaccamo/python-benedict
Note: I am the author of this project
Yes that will work, though note that .
will not match newlines unless you pass the DOTALL flag when compiling the expression:
Pattern pattern = Pattern.compile(".*123", Pattern.DOTALL);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
Replace this:
StreamWriter file2 = new StreamWriter("c:/file.txt");
with this:
StreamWriter file2 = new StreamWriter("c:/file.txt", true);
true
indicates that it appends text.
To obtain multiple outputs from a function and keep them in the desired format you can save the outputs to your hard disk (in the working directory) from within the function and then load them from outside the function:
myfun <- function(x) {
df1 <- ...
df2 <- ...
save(df1, file = "myfile1")
save(df2, file = "myfile2")
}
load("myfile1")
load("myfile2")
Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards
In case one wants to create FK constraints from UAT environment table to Live, fire below dynamic query.....
SELECT 'ALTER TABLE '||OBJ.NAME||' ADD CONSTRAINT '||CONST.NAME||' FOREIGN KEY ('||COALESCE(ACOL.NAME, COL.NAME)||') REFERENCES '
||ROBJ.NAME ||' ('||COALESCE(RACOL.NAME, RCOL.NAME) ||');'
FROM SYS.CON$ CONST
INNER JOIN SYS.CDEF$ CDEF ON CDEF.CON# = CONST.CON#
INNER JOIN SYS.CCOL$ CCOL ON CCOL.CON# = CONST.CON#
INNER JOIN SYS.COL$ COL ON (CCOL.OBJ# = COL.OBJ#) AND (CCOL.INTCOL# = COL.INTCOL#)
INNER JOIN SYS.OBJ$ OBJ ON CCOL.OBJ# = OBJ.OBJ#
LEFT JOIN SYS.ATTRCOL$ ACOL ON (CCOL.OBJ# = ACOL.OBJ#) AND (CCOL.INTCOL# = ACOL.INTCOL#)
INNER JOIN SYS.CON$ RCONST ON RCONST.CON# = CDEF.RCON#
INNER JOIN SYS.CCOL$ RCCOL ON RCCOL.CON# = RCONST.CON#
INNER JOIN SYS.COL$ RCOL ON (RCCOL.OBJ# = RCOL.OBJ#) AND (RCCOL.INTCOL# = RCOL.INTCOL#)
INNER JOIN SYS.OBJ$ ROBJ ON RCCOL.OBJ# = ROBJ.OBJ#
LEFT JOIN SYS.ATTRCOL$ RACOL ON (RCCOL.OBJ# = RACOL.OBJ#) AND (RCCOL.INTCOL# = RACOL.INTCOL#)
WHERE CONST.OWNER# = userenv('SCHEMAID')
AND RCONST.OWNER# = userenv('SCHEMAID')
AND CDEF.TYPE# = 4
AND OBJ.NAME = <table_name>;
find /usr/lib/jvm/java-1.x.x-openjdk
vim /etc/profile
Prepend sudo if logged in as not-privileged user, ie. sudo vim
add:
export JAVA_HOME="path that you found"
export PATH=$JAVA_HOME/bin:$PATH
source /etc/profile
to apply changes immediately in your current shellThis is one way to do it:
Fiddle here: http://jsfiddle.net/4Mvan/1/
HTML:
<div class='container'>
<a href='#'>
<img class='resize_fit_center'
src='http://i.imgur.com/H9lpVkZ.jpg' />
</a>
</div>
CSS:
.container {
margin: 10px;
width: 115px;
height: 115px;
line-height: 115px;
text-align: center;
border: 1px solid red;
}
.resize_fit_center {
max-width:100%;
max-height:100%;
vertical-align: middle;
}
Not only is the boolean datatype missing in Oracle's SQL (not PL/SQL), but they also have no clear recommendation about what to use instead. See this thread on asktom. From recommending CHAR(1) 'Y'/'N'
they switch to NUMBER(1) 0/1
when someone points out that 'Y'/'N'
depends on the English language, while e.g. German programmers might use 'J'/'N'
instead.
The worst thing is that they defend this stupid decision just like they defend the ''=NULL
stupidity.
These answers all collect shallow size information. I suspect that visitors to this question will end up here looking to answer the question, "How big is this complex object in memory?"
There's a great answer here: https://goshippo.com/blog/measure-real-size-any-python-object/
The punchline:
import sys
def get_size(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size
Used like so:
In [1]: get_size(1)
Out[1]: 24
In [2]: get_size([1])
Out[2]: 104
In [3]: get_size([[1]])
Out[3]: 184
If you want to know Python's memory model more deeply, there's a great article here that has a similar "total size" snippet of code as part of a longer explanation: https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609
the easiest way would be
which means you could just do:
new File(filename).text
Switch to the branch from which you created the pull request:
$ git checkout pull-request-branch
Overwrite the modified file(s) with the file in another branch, let's consider it's master:
git checkout origin/master -- src/main/java/HelloWorld.java
Commit and push it to the remote:
git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch
The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash
:
git stash
git checkout other-branch
git stash pop
The first stash
hides away your changes (basically making a temporary commit), and the subsequent stash pop
re-applies them. This lets Git use its merge capabilities.
If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.
On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:
# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset
# Add the things you *do* want to commit here
git add -p # or maybe git add -i
git commit
# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop
# Add the changes meant for this branch
git add -p
git commit
# And throw away the rest
git reset --hard
Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:
git add -p
git commit
git stash
git checkout other-branch
git stash pop
And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1)
to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)
From a web page this cannot work since IE restricts the use of that object.
(It's not action="get"
or action="post"
it's method="get"
or method="post"
Try to do it using post method:
<form action="third.php" method="POST">
Red<input type="checkbox" name="color[]" id="color" value="red">
Green<input type="checkbox" name="color[]" id="color" value="green">
Blue<input type="checkbox" name="color[]" id="color" value="blue">
Cyan<input type="checkbox" name="color[]" id="color" value="cyan">
Magenta<input type="checkbox" name="color[]" id="color" value="Magenta">
Yellow<input type="checkbox" name="color[]" id="color" value="yellow">
Black<input type="checkbox" name="color[]" id="color" value="black">
<input type="submit" value="submit">
</form>
and in third.php
or for a pericular field you colud get value in:
$_POST['color'][0] //for RED
$_POST['color'][1] // for GREEN
In Android, How to use a Cursor with a raw query in sqlite:
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
"where Age > 10 LIMIT 5", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
c.close();
In my case I had an empty line prior a drawable definition in xml. This was braking aapt essentially not allowing to generate R.java .
There are two branches lets say
Being in branch A you can type
git diff --color B
then this will give you a output of
The important point about this is
Text in green is inside present in Branch A
Text in red is present in Branch B
The options object can be added to the chart when the new Chart object is created.
var chart1 = new Chart(canvas, {
type: "pie",
data: data,
options: {
legend: {
display: false
},
tooltips: {
enabled: false
}
}
});
and.. we must call "waitTimer.purge()" for the GC. If you don't use Timer anymore, "purge()" !! "purge()" removes all canceled tasks from the task queue.
if(waitTimer != null) {
waitTimer.cancel();
waitTimer.purge();
waitTimer = null;
}
In my case it was looking after .babelrc
file, and it should contain something like this:
{
"presets": ["es2015-node5", "stage-3"],
"plugins": []
}
I was getting this exception and the "solution" I found was through Netbeans IDE, simply:
I don't know WHY this worked, but it did!
What often gets overlooked is the expected behavior of your algorithms. It doesn't change the Big-O of your algorithm, but it does relate to the statement "premature optimization. . .."
Expected behavior of your algorithm is -- very dumbed down -- how fast you can expect your algorithm to work on data you're most likely to see.
For instance, if you're searching for a value in a list, it's O(n), but if you know that most lists you see have your value up front, typical behavior of your algorithm is faster.
To really nail it down, you need to be able to describe the probability distribution of your "input space" (if you need to sort a list, how often is that list already going to be sorted? how often is it totally reversed? how often is it mostly sorted?) It's not always feasible that you know that, but sometimes you do.
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
$(document).ready(function() {_x000D_
_x000D_
// Executes when the HTML document is loaded and the DOM is ready_x000D_
alert("Document is ready");_x000D_
});_x000D_
_x000D_
// .load() method deprecated from jQuery 1.8 onward_x000D_
$(window).on("load", function() {_x000D_
_x000D_
// Executes when complete page is fully loaded, including_x000D_
// all frames, objects and images_x000D_
alert("Window is loaded");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
_x000D_
The JOIN
statements are also part of the FROM
clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM
. See http://www.postgresql.org/docs/9.1/static/sql-select.html .
So the direct solution to your problem is:
SELECT something
FROM
master as parent LEFT JOIN second as parentdata
ON parent.secondary_id = parentdata.id,
master as child LEFT JOIN second as childdata
ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'
A better option would be to only use JOIN
's, as it has already been suggested.
CSS Gallery has variety of Time Pickers. Have a look.
Perifer Design's time picker is similar to google one
<html>
<div style="width:100%; height:100%; position:fixed; left:0;top:0;overflow:hidden;">
</div>
</html>
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
Worked for me in python3 on linux
import sys
sys.path.append(pathToFolderContainingScripts)
from scriptName import functionName #scriptName without .py extension
The name
is present inside the data
. You need to parse a JSON hierarchically to be able to fetch the data properly.
JSONObject jObject = new JSONObject(output); // json
JSONObject data = jObject.getJSONObject("data"); // get data object
String projectname = data.getString("name"); // get the name from data.
Note: This example uses the org.json.JSONObject
class and not org.json.simple.JSONObject
.
As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject
, I'm adding my comment details in the answer.
Try to use the
org.json.JSONObject
instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.
Sample from the link provided:
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
Extending the solution (suggested by Shubham Khatri) for use with React hooks (16.8 onwards):
package.json (always worth updating to latest packages)
{
...
"react": "^16.12.0",
"react-router-dom": "^5.1.2",
...
}
Passing parameters with history push:
import { useHistory } from "react-router-dom";
const FirstPage = props => {
let history = useHistory();
const someEventHandler = event => {
history.push({
pathname: '/secondpage',
search: '?query=abc',
state: { detail: 'some_value' }
});
};
};
export default FirstPage;
Accessing the passed parameter using useLocation from 'react-router-dom':
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
const SecondPage = props => {
const location = useLocation();
useEffect(() => {
console.log(location.pathname); // result: '/secondpage'
console.log(location.search); // result: '?query=abc'
console.log(location.state.detail); // result: 'some_value'
}, [location]);
};
const params = new URLSearchParams(location.search)
params.delete('key_to_delete')
console.log(params.toString())
You can use
sessionStorage.SessionName = "SessionData"
,
sessionStorage.getItem("SessionName")
and
sessionStorage.setItem("SessionName","SessionData");
See the supported browsers on http://caniuse.com/namevalue-storage
Got it working. Here was my procedure:
Sources
tab in chrome inspectorElements
tab in inspectorYou want either auto-fit
or auto-fill
inside the repeat()
function:
grid-template-columns: repeat(auto-fit, 186px);
The difference between the two becomes apparent if you also use a minmax()
to allow for flexible column sizes:
grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill
will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:
Using auto-fit
instead will prevent empty columns, stretching yours further if necessary:
iPad Media Queries (All generations - including iPad mini)
Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.
iPad in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) { /* STYLES GO HERE */}
iPad in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) { /* STYLES GO HERE */}
iPad in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) { /* STYLES GO HERE */ }
iPad 3 & 4 Media Queries
If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.
Retina iPad in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}
Retina iPad in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}
Retina iPad in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }
iPad 1 & 2 Media Queries
If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!
iPad 1 & 2 in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}
iPad 1 & 2 in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */}
iPad 1 & 2 in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }
Source: http://stephen.io/mediaqueries/
viewDidLoad()
—Called when the view controller’s content view (the top of its view hierarchy) is created and loaded from a storyboard. … Use this method to perform any additional setup required by your view controller.
viewWillAppear()
—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen
viewDidAppear()
—Called just after the view controller’s content view has been added to the app’s view hierarchy. Use this method to trigger any operations that need to occur as soon as the view is presented onscreen, such as fetching data or showing an animation.
viewWillDisappear()
—Called just before the view controller’s content view is removed from the app’s view hierarchy. Use this method to perform cleanup tasks like committing changes or resigning the first responder status.
viewDidDisappear()
—Called just after the view controller’s content view has been removed from the app’s view hierarchy. Use this method to perform additional teardown activities.
Just wanted to add that if you want to add several parameters with the same key name for example: www.test.com/home?id=1&id=2
let params = new HttpParams();
params = params.append(key, value);
Use append, if you use set, it will overwrite the previous value with the same key name.
This solution will change the git file permissions from 100755 to 100644 and push changes back to the bitbucket remote repo.
Take a look at your repo's file permissions: git ls-files --stage
If 100755 and you want 100644
Then run this command: git ls-files --stage | sed 's/\t/ /g' | cut -d' ' -f4 | xargs git update-index --chmod=-x
Now check your repo's file permissions again: git ls-files --stage
Now commit your changes:
git status
git commit -m "restored proper file permissions"
git push
Its actually formulated more like:
https://<bucket-name>.s3.amazonaws.com/<key>
See here
Please see This article
Then goto the "overrides" tab
You can not delete the directory if it has subdirectories or files in Java. Try this two-line simple solution. This will delete the directory and contests inside the directory.
File dirName = new File("directory path");
FileUtils.deleteDirectory(dirName);
Add this line in gradle file and sync the project
compile 'org.apache.commons:commons-io:1.3.2'
I wrote more flexible function which can give you random number but not only integer.
function rand(min,max,interval)
{
if (typeof(interval)==='undefined') interval = 1;
var r = Math.floor(Math.random()*(max-min+interval)/interval);
return r*interval+min;
}
var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0
Fixed version.
Here is my reason:
before:
var path = "D:\xxx\util.s"
which \u
is a escape, I figured it out by using Codepen's analyze JS.
after:
var path = "D:\\xxx\\util.s"
and the error fixed
TortoiseSVN always prompts for username. (unless you tell it not to)
I found this PostgreSQL documentation helpful: http://www.postgresql.org/docs/8.0/interactive/functions-conditional.html.
In my case, I sought plain SQL to concatenate a field with brackets around it, if the field is not empty.
select itemid,
CASE
itemdescription WHEN '' THEN itemname
ELSE itemname || ' (' || itemdescription || ')'
END
from items;
I also faced this issue on a PR that has been merged to the master branch of a GitHub repo.
Since I just wanted to modify some modified files but not the whole changes the PR brought, I had to amend
the merge commit
with git commit --am
.
Steps:
git add *
or git add <file>
git commit --am
and validategit push -f
Why it's interesting:
The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:
$data = [
"rs" => null
]
this above will work absolutely fine when used like:
$data["rs"] = 5;
But the below will throw a warning ::
$data = [
"rs" => [
"rs1" => null;
]
]
..
$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
I had this problem with Firefox and my server. I contacted GoDaddy customer support, and they had me install the intermediate server certificate:
http://support.godaddy.com/help/article/868/what-is-an-intermediate-certificate
After a re-start of the World Wide Web Publishing Service, everything worked perfectly.
If you do not have full access to your server, your ISP will have to do this for you.
Use break
.
Unrelated to your question, I see in your code the line:
Violated = !(name.firstname == null) ? false : true;
In this line, you take a boolean value (name.firstname == null)
. Then, you apply the !
operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null)
. Why not use that, as in:
Violated = (name.firstname == null);
As stated by user2246674, using success
and error
as parameter of the ajax function is valid.
To be consistent with precedent answer, reading the doc :
Deprecation Notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
If you are using the callback-manipulation function (using method-chaining for example), use .done()
, .fail()
and .always()
instead of success()
, error()
and complete()
.
For Mac Users if command + fn + f12
or command + f12
is not working, then your key map is not selected as "Mac Os X". To select key map follow the below steps.
Android Studio -> Preferences -> Keymap -> From the drop down Select "Mac OS X" -> Click Apply -> OK.
This is what I'm using to get the running jobs (principally so I can kill the ones which have probably hung):
SELECT
job.Name, job.job_ID
,job.Originating_Server
,activity.run_requested_Date
,datediff(minute, activity.run_requested_Date, getdate()) AS Elapsed
FROM
msdb.dbo.sysjobs_view job
INNER JOIN msdb.dbo.sysjobactivity activity
ON (job.job_id = activity.job_id)
WHERE
run_Requested_date is not null
AND stop_execution_date is null
AND job.name like 'Your Job Prefix%'
As Tim said, the MSDN / BOL documentation is reasonably good on the contents of the sysjobsX tables. Just remember they are tables in MSDB.
I concur with Franci, all Sysinternals utilities are worth taking a look (Autoruns is a must too), and Process Monitor, which replaces the good old Filemon and Regmon is precious.
Beside the usage you want, it is very useful to see why a process fails (like trying to access a file or a registry key that doesn't exist), etc.
if you are trying to write a pandas dataframe into a file using a json format i'd recommend this
destination='filepath'
saveFile = open(destination, 'w')
saveFile.write(df.to_json())
saveFile.close()
To unlock a blocked document: 1. Right click -> Lock 2. Check the "Steal the locks" check box 2. Release the lock
After doing it both ways for a few projects my stance is that composer.lock
should not be committed as part of the project.
composer.lock
is build metadata which is not part of the project. The state of dependencies should be controlled through how you're versioning them (either manually or as part of your automated build process) and not arbitrarily by the last developer to update them and commit the lock file.
If you are concerned about your dependencies changing between composer updates then you have a lack of confidence in your versioning scheme. Versions (1.0, 1.1, 1.2, etc) should be immutable and you should avoid "dev-" and "X.*" wildcards outside of initial feature development.
Committing the lock file is a regression for your dependency management system as the dependency version has now gone back to being implicitly defined.
Also, your project should never have to be rebuilt or have its dependencies reacquired in each environment, especially prod. Your deliverable (tar, zip, phar, a directory, etc) should be immutable and promoted through environments without changing.
I am trying to Understand your Question and it seems that you want the values in the first JSP to be available in the Second JSP.
It is very bad Habit to Place Java Code snippets Inside JSP file, so that code snippet should go to a servlet.
Pick the values in a servlet ie.
String username = request.getParameter("username");
String password = request.getParameter("password");
Then Store the Values inside the Session:
HttpSession sess = request.getSession();
sess.setAttribute("username", username);
sess.setAttribute("password", password);
These values Will be available anywhere in the Application as long as the session is valid.
HttpSession sess = request.getSession(false); //use false to use the existing session
sess.getAttribute("username");//this will return username anytime in the session
sess.getAttribute("password");//this will return password Any time in the session
I hope this is what you wanted to know, but please do not use code snippets in the JSP. You can always get the values into the JSP using jstl
in the JSPs:
${username}//this will give you the username in the JSP
${password}// this will give you the password in the JSP
Since you don't state if the form can resize or not there is an easy way if you don't care about resizing (if you do care, go with Mitch Wheats solution):
Select the control -> Format (menu option) -> Center in Window -> Horizontally or Vertically
If you are using MySQL
public static boolean isDbConnected() {
final String CHECK_SQL_QUERY = "SELECT 1";
boolean isConnected = false;
try {
final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
isConnected = true;
} catch (SQLException | NullPointerException e) {
// handle SQL error here!
}
return isConnected;
}
I have not tested with other databases. Hope this is helpful.
I was thinking about this problem for my own code and even though I probably will end up using something simpler/faster, here's another Linq solution that's similar to one that @Francisco added.
I just like it because it reads the most like what you actually want to do: "Take chars while the resulting substring has fewer than 2 spaces."
string input = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
var substring = input.TakeWhile((c0, index) =>
input.Substring(0, index + 1).Count(c => c == ' ') < 2);
string result = new String(substring.ToArray());
You can also use pytiff of which I'm the author.
import pytiff
with pytiff.Tiff("filename.tif") as handle:
part = handle[100:200, 200:400]
# multipage tif
with pytiff.Tiff("multipage.tif") as handle:
for page in handle:
part = page[100:200, 200:400]
It's a fairly small module and may not have as many features as other modules, but it supports tiled tiffs and bigtiff, so you can read parts of large images.
As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
@Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
**PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null &&
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}
}
}
}
So it's better to use plain setters given the cost reflection
I have found the solution even though it might be a little difficult for some to carry out.
1st step (for python3 and linux):
pip3 install pip-autoremove
2nd step:
cd /home/usernamegoeshere/.local/bin/
3rd step:
gedit /home/usernamegoeshere/.local/lib/python3.8/site-packages/pip_autoremove.py
and change all pip(s) to pip3
4th step:
./pip-autoremove packagenamegoeshere
At least, this was what worked for me ...
I thought I'd just add that in python 3, filter() is actually an iterator object, so you'd have to pass your filter method call to list() in order to build the filtered list. So in python 2:
lst_a = range(25) #arbitrary list
lst_b = [num for num in lst_a if num % 2 == 0]
lst_c = filter(lambda num: num % 2 == 0, lst_a)
lists b and c have the same values, and were completed in about the same time as filter() was equivalent [x for x in y if z]. However, in 3, this same code would leave list c containing a filter object, not a filtered list. To produce the same values in 3:
lst_a = range(25) #arbitrary list
lst_b = [num for num in lst_a if num % 2 == 0]
lst_c = list(filter(lambda num: num %2 == 0, lst_a))
The problem is that list() takes an iterable as it's argument, and creates a new list from that argument. The result is that using filter in this way in python 3 takes up to twice as long as the [x for x in y if z] method because you have to iterate over the output from filter() as well as the original list.
In C++, the size of int
isn't specified explicitly. It just tells you that it must be at least the size of short int
, which must be at least as large as signed char
. The size of char
in bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long long
to be at least 64 bits.
Probably due to the fact that I could not explain well you do not really understand my question. In general, I found the solution.
Sorry for my english
You can echo files manually using the fs object, but I'd recommend using the ExpressJS framework to make your life much easier.
...But if you insist on doing it the hard way:
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res){
fs.readFile('test.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
}).listen(8000);
The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).
Another late answer, but I was playing with this and came up with a general purpose Sass solution that I found useful and many others might as well. To give an overview, this introduces new classes that can modify the column count of a .card-columns
element in very similar ways to columns with .col-4
or .col-lg-3
:
@import "bootstrap";
$card-column-counts: 1, 2, 3, 4, 5;
.card-columns {
@each $column-count in $card-column-counts {
&.card-columns-#{$column-count} {
column-count: $column-count;
}
}
@each $breakpoint in map-keys($grid-breakpoints) {
@include media-breakpoint-up($breakpoint) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
@each $column-count in $card-column-counts {
&.card-columns#{$infix}-#{$column-count} {
column-count: $column-count;
}
}
}
}
}
The end result of this is if you have the following:
<div class="card-columns card-columns-2 card-columns-md-3 card-columns-xl-4">
...
</div>
Then you would have 2 columns by default, 3 for medium devices and up and 4 for xl devices and up. Additionally if you change your grid breakpoints this will automatically support those, and the $card-column-counts
can be overridden to change the allowed numbers of columns.
Ignore this answer. Not that it doesn't work. But there are better methods available. Moreover, Android emphatically discourage direct communication between fragments. See official doc. Thanks user @Wahib Ul Haq for the tip.
Well, you can create a private variable and setter in Fragment B, and set the value from Fragment A itself,
FragmentB.java
private String inputString;
....
....
public void setInputString(String string){
inputString = string;
}
FragmentA.java
//go to fragment B
FragmentB frag = new FragmentB();
frag.setInputString(YOUR_STRING);
//create your fragment transaction object, set animation etc
fragTrans.replace(ITS_ARGUMENTS)
Or you can use Activity as you suggested in question..
My simple fix it turned out to be calling the form's Activate()
method, so there's no need to use TopMost
(which is what I was aiming at).
The difference is obvious in console:
You could use numpy.arange
.
EDIT: The docs prefer numpy.linspace
. Thanks @Droogans for noticing =)
This topic is well covered but I still would like to propose another approach in a slightly different philosophy.
It is a bit more complex to set-up but it allow (in my opinion) a bit more flexibility. For example, one can play with the respective ratios of each subplots / colorbar:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
# Define number of rows and columns you want in your figure
nrow = 2
ncol = 3
# Make a new figure
fig = plt.figure(constrained_layout=True)
# Design your figure properties
widths = [3,4,5,1]
gs = GridSpec(nrow, ncol + 1, figure=fig, width_ratios=widths)
# Fill your figure with desired plots
axes = []
for i in range(nrow):
for j in range(ncol):
axes.append(fig.add_subplot(gs[i, j]))
im = axes[-1].pcolormesh(np.random.random((10,10)))
# Shared colorbar
axes.append(fig.add_subplot(gs[:, ncol]))
fig.colorbar(im, cax=axes[-1])
plt.show()
See the UIScreen Reference: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScreen_Class/Reference/UIScreen.html
if([[UIScreen mainScreen] respondsToSelector:NSSelectorFromString(@"scale")])
{
if ([[UIScreen mainScreen] scale] < 1.1)
NSLog(@"Standard Resolution Device");
if ([[UIScreen mainScreen] scale] > 1.9)
NSLog(@"High Resolution Device");
}
I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:
create table destination_old as select * from destination;
drop table destination;
create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;
It's safe because you have a copy of destination
before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.
Using the pattern above you end up with two country
fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old
and perhaps using coalesce
to retrieve the values from destination_old
if the country
field in source
is null. So for example:
create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;
If you want something that works well on windows there is a package called WinFoldersJava which wraps the native call to get the 'special' directories on Windows. We use it frequently and it works well.
You can do this without jquery...
<select onchange="event.target.selectedIndex = 0">
...
</select>
or you can do a function to check your condition
<select onchange="check(event)">
...
</select>
<script>
function check(e){
if (my_condition){
event.target.selectedIndex = 0;
}
}
</script>
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('modx', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
Is a regular expression an easier/better way to enforce a simple constraint than the more obvious way?
static bool ValidatePassword( string password )
{
const int MIN_LENGTH = 8 ;
const int MAX_LENGTH = 15 ;
if ( password == null ) throw new ArgumentNullException() ;
bool meetsLengthRequirements = password.Length >= MIN_LENGTH && password.Length <= MAX_LENGTH ;
bool hasUpperCaseLetter = false ;
bool hasLowerCaseLetter = false ;
bool hasDecimalDigit = false ;
if ( meetsLengthRequirements )
{
foreach (char c in password )
{
if ( char.IsUpper(c) ) hasUpperCaseLetter = true ;
else if ( char.IsLower(c) ) hasLowerCaseLetter = true ;
else if ( char.IsDigit(c) ) hasDecimalDigit = true ;
}
}
bool isValid = meetsLengthRequirements
&& hasUpperCaseLetter
&& hasLowerCaseLetter
&& hasDecimalDigit
;
return isValid ;
}
Which do you think that maintenance programmer 3 years from now who needs to modify the constraint will have an easier time understanding?
I use this command:
mount -o rw,remount /system
First you create a MySQL table to store images, like for example:
create table testblob (
image_id tinyint(3) not null default '0',
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_ctgy varchar(25) not null default '',
image_name varchar(50) not null default ''
);
Then you can write an image to the database like:
/***
* All of the below MySQL_ commands can be easily
* translated to MySQLi_ with the additions as commented
***/
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli
// $link = mysqli_connect("localhost", $username, $password,$dbname);
$sql = sprintf("INSERT INTO testblob
(image_type, image, image_size, image_name)
VALUES
('%s', '%s', '%d', '%s')",
/***
* For all mysqli_ functions below, the syntax is:
* mysqli_whartever($link, $functionContents);
***/
mysql_real_escape_string($size['mime']),
mysql_real_escape_string($imgData),
$size[3],
mysql_real_escape_string($_FILES['userfile']['name'])
);
mysql_query($sql);
You can display an image from the database in a web page with:
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);
Here is another thought n for appending multiple items in one line without changing the name of series. However, this may be not as efficient as the other answer.
>>> df = pd.Series(np.random.random(5), name='random')
>>> df
0 0.363885
1 0.402623
2 0.450449
3 0.172917
4 0.983481
Name: random, dtype: float64
>>> df.to_frame().T.assign(a=3, b=2, c=5).squeeze()
0 0.363885
1 0.402623
2 0.450449
3 0.172917
4 0.983481
a 3.000000
b 2.000000
c 5.000000
Name: random, dtype: float64
The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.
As an example, let's say you have a person class:
class Person {
String name;
List<String> emailAddresses
}
How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses
in the new object. But if you modified the contents of the emailAddresses
list, you would be modifying the list in both copies (since that's how object references work).
A deep copy would mean that you recursively copy every member, so you would need to create a new List
for the new Person
, and then copy the contents from the old to the new object.
Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.
To see both the normal distribution and your actual data you should plot your data as a histogram, then draw the probability density function over this. See the example on https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html for exactly how to do this.
Full example demonstrating a listener of the internet connectivity and its source.
Credit to : connectivity and Günter Zöchbauer
import 'dart:async';
import 'dart:io';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Map _source = {ConnectivityResult.none: false};
MyConnectivity _connectivity = MyConnectivity.instance;
@override
void initState() {
super.initState();
_connectivity.initialise();
_connectivity.myStream.listen((source) {
setState(() => _source = source);
});
}
@override
Widget build(BuildContext context) {
String string;
switch (_source.keys.toList()[0]) {
case ConnectivityResult.none:
string = "Offline";
break;
case ConnectivityResult.mobile:
string = "Mobile: Online";
break;
case ConnectivityResult.wifi:
string = "WiFi: Online";
}
return Scaffold(
appBar: AppBar(title: Text("Internet")),
body: Center(child: Text("$string", style: TextStyle(fontSize: 36))),
);
}
@override
void dispose() {
_connectivity.disposeStream();
super.dispose();
}
}
class MyConnectivity {
MyConnectivity._internal();
static final MyConnectivity _instance = MyConnectivity._internal();
static MyConnectivity get instance => _instance;
Connectivity connectivity = Connectivity();
StreamController controller = StreamController.broadcast();
Stream get myStream => controller.stream;
void initialise() async {
ConnectivityResult result = await connectivity.checkConnectivity();
_checkStatus(result);
connectivity.onConnectivityChanged.listen((result) {
_checkStatus(result);
});
}
void _checkStatus(ConnectivityResult result) async {
bool isOnline = false;
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
isOnline = true;
} else
isOnline = false;
} on SocketException catch (_) {
isOnline = false;
}
controller.sink.add({result: isOnline});
}
void disposeStream() => controller.close();
}
For the record, the spring.jpa.hibernate.ddl-auto
property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto
.
The values create
, create-drop
, validate
, and update
basically influence how the schema tool management will manipulate the database schema at startup.
For example, the update
operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.
The update
operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.
Typically in test case scenarios, you'll likely use create-drop
so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.
In development, it's often common to see developers use update
to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.
In production, it's often highly recommended you use none
or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.
To remove all files from staging area use -
git reset
To remove specific file use -
git reset "File path"
Finally solved issue of reinitialization of select2 after ajax call.
You can call this in success function of ajax.
Note : Don't forget to replace ".selector" to your class of <select class="selector">
element.
jQuery('.select2-container').remove();
jQuery('.selector').select2({
placeholder: "Placeholder text",
allowClear: true
});
jQuery('.select2-container').css('width','100%');
To answer your other question. The size of a pointer and the size of what it points to are not related. A good analogy is to consider them like postal addresses. The size of the address of a house has no relationship to the size of the house.
First, the network name is likely "Ethernet", not "Local Area Connection". To find out the name you can do this:
netsh interface show interface
Which will show the name under the "Interface Name" column (shown here in bold):
Admin State State Type Interface Name ------------------------------------------------------------------------- Enabled Connected Dedicated Ethernet
Now you can change the primary dns (index=1), assuming that your interface is static (not using dhcp):
netsh interface ipv4 add dnsserver "Ethernet" address=192.168.x.x index=1
2018 Update - The command will work with either dnsserver
(singular) or dnsservers
(plural). The following example uses the latter and is valid as well:
netsh interface ipv4 add dnsservers "Ethernet" address=192.168.x.x index=1
Vanilla JDBC only supports named parameters in a CallableStatement
(e.g. setString("name", name)
), and even then, I suspect the underlying stored procedure implementation has to support it.
An example of how to use named parameters:
//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
+ "if @id is not null "
+ "select * from sysobjects where id = @id "
+ "else if @name is not null "
+ "select * from sysobjects where name = @name "
+ " end");
stmt.execute();
//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
HTML Form Element Validation
Run Function
<script>
$("#validationForm").validation({
button: "#btnGonder",
onSubmit: function () {
alert("Submit Process");
},
onCompleted: function () {
alert("onCompleted");
},
onError: function () {
alert("Error Process");
}
});
</script>
Go to example and download https://github.com/naimserin/Validation.
There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.
app.get('/category', function(req, res) {
var string = encodeURIComponent('something that would break');
res.redirect('/?valid=' + string);
});
You can snag that in your other route by getting the parameters sent by using req.query
.
app.get('/', function(req, res) {
var passedVariable = req.query.valid;
// Do something with variable
});
For more dynamic way you can use the url
core module to generate the query string for you:
const url = require('url');
app.get('/category', function(req, res) {
res.redirect(url.format({
pathname:"/",
query: {
"a": 1,
"b": 2,
"valid":"your string here"
}
}));
});
So if you want to redirect all req query string variables you can simply do
res.redirect(url.format({
pathname:"/",
query:req.query,
});
});
And if you are using Node >= 7.x you can also use the querystring
core module
const querystring = require('querystring');
app.get('/category', function(req, res) {
const query = querystring.stringify({
"a": 1,
"b": 2,
"valid":"your string here"
});
res.redirect('/?' + query);
});
Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:
app.get('/category', function(req, res) {
req.session.valid = true;
res.redirect('/');
});
And later on after the redirect...
app.get('/', function(req, res) {
var passedVariable = req.session.valid;
req.session.valid = null; // resets session variable
// Do something
});
There is also the option of using an old feature of Express, req.flash
. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.
Hopefully that will give you a general idea how to pass information around in an Express application.
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.
There are demo on the author's site and let our company site serve as a real-world example too.
Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML via supporting specs like HTML-AAM. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.
http://www.w3.org/TR/wai-aria/
There are a few primary reasons to use roles in addition to your native semantic element.
Reason #1. Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.
In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.
<a href="#" role="button" aria-label="Delete item 1">Delete</a>
<!-- Note: href="#" is just a shorthand here, not a recommended technique. Use progressive enhancement when possible. -->
Screen readers users will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.
[role="button"] {
/* style these as buttons w/o relying on a .button class */
}
[Update 7 years later: removed the * selector to make some commenters happy, since the old browser quirk that required universal selector on attribute selectors is unnecessary in 2020.]
Reason #2. Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.
For example, the "main" role has been supported in browsers for many years, but it's a relatively recent addition to HTML5, so many browsers don't yet support the semantic for <main>
.
<main role="main">…</main>
This is technically redundant, but helps some users and doesn't harm any. In a few years, this technique will likely become unnecessary for main.
Reason #3. Update 7 years later (2020): As at least one commenter pointed out, this is now very useful for custom elements, and some spec work is underway to define the default accessibility role of a web component. Even if/once that API is standardized, there may be need to override the default role of a component.
Note/Reply
You also wrote:
I see some people make up their own. Is that allowed or a correct use of the role attribute?
That's an allowed use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.
<span role="foo link note bar">...</a>
Out of the list, only link
and note
are valid roles, and so the link role will be applied in the platform accessibility API because it comes first. If you use custom roles, make sure they don't conflict with any defined role in ARIA or the host language you're using (HTML, SVG, MathML, etc.)
From Docker documentation:
docker export
does not export the contents of volumes associated with the container. If a volume is mounted on top of an existing directory in the container,docker export
will export the contents of the underlying directory, not the contents of the volume. Refer to Backup, restore, or migrate data volumes in the user guide for examples on exporting data in a volume.
If you want to accomplish the same in Gecko (NS6+, Mozilla, etc) and IE4+ simultaneously, I believe this should do the trick:V
body {
overflow: -moz-scrollbars-vertical;
overflow-x: hidden;
overflow-y: auto;
}
This will be applied to entire body tag, please update it to your relevant css and apply this properties.
This is my solution
var error=0;
var test = [" ", " "];
if(test[0].match(/^\s*$/g)) {
$("#output").html("MATCH!");
error+=1;
} else {
$("#output").html("no_match");
}
The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Example usage:
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
Which I got from https://stackoverflow.com/a/8412989/1232175.
Changing the 'w' (write) in this line:
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)
To 'wb' (write binary) fixed this problem for me:
output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)
Credit to @dandrejvv for the solution in the comment on the original post above.
I realize this is a very old question, but I don't see one crucial aspect mentioned in any of the answers: inlining into query plan.
Functions can be...
Scalar:
CREATE FUNCTION ... RETURNS scalar_type AS BEGIN ... END
Multi-statement table-valued:
CREATE FUNCTION ... RETURNS @r TABLE(...) AS BEGIN ... END
Inline table-valued:
CREATE FUNCTION ... RETURNS TABLE AS RETURN SELECT ...
The third kind (inline table-valued) are treated by the query optimizer essentially as (parametrized) views, which means that referencing the function from your query is similar to copy-pasting the function's SQL body (without actually copy-pasting), leading to the following benefits:
The above can lead to potentially significant performance savings, especially when combining multiple levels of functions.
NOTE: Looks like SQL Server 2019 will introduce some form of scalar function inlining as well.
I just did this for fun
>>> s = 'a,b,c,d'
>>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
['a,b,c', 'd']
Caution: Refer to the first comment in below where this answer can go wrong.
$Name= "'".$row['Name']."'";
$Val1= "'".$row['Val1']."'";
$Year= "'".$row['Year']."'";
$Month="'".$row['Month']."'";
echo '<button type="button" onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');" >submit</button>';
From the documentation:
requests
can also ignore verifying the SSL certificate if you setverify
to False.>>> requests.get('https://kennethreitz.com', verify=False) <Response [200]>
If you're using a third-party module and want to disable the checks, here's a context manager that monkey patches requests
and changes it so that verify=False
is the default and suppresses the warning.
import warnings
import contextlib
import requests
from urllib3.exceptions import InsecureRequestWarning
old_merge_environment_settings = requests.Session.merge_environment_settings
@contextlib.contextmanager
def no_ssl_verification():
opened_adapters = set()
def merge_environment_settings(self, url, proxies, stream, verify, cert):
# Verification happens only once per connection so we need to close
# all the opened adapters once we're done. Otherwise, the effects of
# verify=False persist beyond the end of this context manager.
opened_adapters.add(self.get_adapter(url))
settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)
settings['verify'] = False
return settings
requests.Session.merge_environment_settings = merge_environment_settings
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore', InsecureRequestWarning)
yield
finally:
requests.Session.merge_environment_settings = old_merge_environment_settings
for adapter in opened_adapters:
try:
adapter.close()
except:
pass
Here's how you use it:
with no_ssl_verification():
requests.get('https://wrong.host.badssl.com/')
print('It works')
requests.get('https://wrong.host.badssl.com/', verify=True)
print('Even if you try to force it to')
requests.get('https://wrong.host.badssl.com/', verify=False)
print('It resets back')
session = requests.Session()
session.verify = True
with no_ssl_verification():
session.get('https://wrong.host.badssl.com/', verify=True)
print('Works even here')
try:
requests.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
print('It breaks')
try:
session.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
print('It breaks here again')
Note that this code closes all open adapters that handled a patched request once you leave the context manager. This is because requests maintains a per-session connection pool and certificate validation happens only once per connection so unexpected things like this will happen:
>>> import requests
>>> session = requests.Session()
>>> session.get('https://wrong.host.badssl.com/', verify=False)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
<Response [200]>
>>> session.get('https://wrong.host.badssl.com/', verify=True)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
<Response [200]>
In simple terms you need to build your payload into a key array
payload = {'key1': 'value1', 'key2': 'value2'}
Then send the payload directly to the action
this.$store.dispatch('yourAction', payload)
No change in your action
yourAction: ({commit}, payload) => {
commit('YOUR_MUTATION', payload )
},
In your mutation call the values with the key
'YOUR_MUTATION' (state, payload ){
state.state1 = payload.key1
state.state2 = payload.key2
},
If you have button'ed your button this seems to work:
<button id="button">First caption</button>
$('#button').button();//make it nice
var text="new caption";
$('#button').children().first().html(text);
you can use
$('#elementID').css('background-color', '#C0C0C0');
gacutil comes with Visual Studio, not with VSTS. It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en . This installation will have gacutil.exe
included. But first check it here
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
you might have it installed.
As @devi mentioned
If you decide to grab gacutil files from existing installation, note that from .NET 4.0 is three files: gacutil.exe gacutil.exe.config and 1033/gacutlrc.dll
There are several reasons this can happen. Some of these I found here, others I discovered on my own.
Id
, you need to add the [Key]
attribute to it.public
uint
, ulong
etc. are not allowed.As long as you don't want any special formatting: yes.
foreach ($_POST as $key => $value)
$body .= $key . ' -> ' . $value . '<br>';
Obviously, more formatting would be necessary, however that's the "easy" way. Unless I misunderstood the question.
You could also do something like this (and if you like the format, it's certainly easier):
$body = print_r($_POST, true);
var text = File.ReadAllText(file, Encoding.GetEncoding(codePage));
List of codepages : http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
In Short,
Logins will have the access of the server.
and
Users will have the access of the database.
You can do that by using this simple code:
Object.keys(myObject).length
var result = list.GroupBy(x => x.Category).Select(x => x.First())
$html = <<<HTML
...
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$tags_to_remove = array('script','style','iframe','link');
foreach($tags_to_remove as $tag){
$element = $dom->getElementsByTagName($tag);
foreach($element as $item){
$item->parentNode->removeChild($item);
}
}
$html = $dom->saveHTML();
'<>'
is from the SQL-92 standard and '!='
is a proprietary T-SQL operator. It's available in other databases as well, but since it isn't standard you have to take it on a case-by-case basis.
In most cases, you'll know what database you're connecting to so this isn't really an issue. At worst you might have to do a search and replace in your SQL.
Added to TruelyObservableCollection event "ItemPropertyChanged":
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel; // ObservableCollection
using System.ComponentModel; // INotifyPropertyChanged
using System.Collections.Specialized; // NotifyCollectionChangedEventHandler
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObservableCollectionTest
{
class Program
{
static void Main(string[] args)
{
// ATTN: Please note it's a "TrulyObservableCollection" that's instantiated. Otherwise, "Trades[0].Qty = 999" will NOT trigger event handler "Trades_CollectionChanged" in main.
// REF: http://stackoverflow.com/questions/8490533/notify-observablecollection-when-item-changes
TrulyObservableCollection<Trade> Trades = new TrulyObservableCollection<Trade>();
Trades.Add(new Trade { Symbol = "APPL", Qty = 123 });
Trades.Add(new Trade { Symbol = "IBM", Qty = 456});
Trades.Add(new Trade { Symbol = "CSCO", Qty = 789 });
Trades.CollectionChanged += Trades_CollectionChanged;
Trades.ItemPropertyChanged += PropertyChangedHandler;
Trades.RemoveAt(2);
Trades[0].Qty = 999;
Console.WriteLine("Hit any key to exit");
Console.ReadLine();
return;
}
static void PropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(DateTime.Now.ToString() + ", Property changed: " + e.PropertyName + ", Symbol: " + ((Trade) sender).Symbol + ", Qty: " + ((Trade) sender).Qty);
return;
}
static void Trades_CollectionChanged(object sender, EventArgs e)
{
Console.WriteLine(DateTime.Now.ToString() + ", Collection changed");
return;
}
}
#region TrulyObservableCollection
public class TrulyObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public event PropertyChangedEventHandler ItemPropertyChanged;
public TrulyObservableCollection()
: base()
{
CollectionChanged += new NotifyCollectionChangedEventHandler(TrulyObservableCollection_CollectionChanged);
}
void TrulyObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (Object item in e.NewItems)
{
(item as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
}
}
if (e.OldItems != null)
{
foreach (Object item in e.OldItems)
{
(item as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged);
}
}
}
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs a = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(a);
if (ItemPropertyChanged != null)
{
ItemPropertyChanged(sender, e);
}
}
}
#endregion
#region Sample entity
class Trade : INotifyPropertyChanged
{
protected string _Symbol;
protected int _Qty = 0;
protected DateTime _OrderPlaced = DateTime.Now;
public DateTime OrderPlaced
{
get { return _OrderPlaced; }
}
public string Symbol
{
get
{
return _Symbol;
}
set
{
_Symbol = value;
NotifyPropertyChanged("Symbol");
}
}
public int Qty
{
get
{
return _Qty;
}
set
{
_Qty = value;
NotifyPropertyChanged("Qty");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
#endregion
}
preg_replace
offers one way:
$newText = preg_replace('/\bBy.*$/', '', $text);
@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver
program on all your old classes. put these serialVersionUID
values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID
on all Serializable
classes)
if the new versions are not serial compatible, then you need to do some magic with a custom readObject
implementation (you would only need a custom writeObject
if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.
Of course, even if the new class is serial compatible, you may still want a custom readObject
implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).
In my case the Data provider entry for MySQL was "simply" missing in the machine.config file described above (though I had installed the MySQL connector properly)
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
Don't forget to put the right Version of your MySQL on the Entry
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
If you can use Java NIO (JDK 1.4 or greater), then I think you're looking for java.nio.channels.FileChannel.lock()
Another option is to use the TimeUtils
utility method:
TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)
There is no difference in C++, but I believe in C it would allow you to declare instances of the struct Foo without explicitly doing:
struct Foo bar;
Opacity changes the context of your z-index, as does the static positioning. Either add opacity to the element that doesn't have it or remove it from the element that does. You'll also have to either make both elements static positioned or specify relative or absolute position. Here's some background on contexts: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/
This code is to solve our problem to set unique key for existing table
alter ignore table ioni_groups add unique (group_name);
Possible Duplicate:
Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:
For radio button:
var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();
For textbox:
var txt=$('input:text[name=DrugDurationLength]').val();
I was able to get rid of my scroll bar on the body of text by removing my max-height attribute of my class.
use text-align: center
css property
April 11, 2019
None of the answers above solved my problem so I wanted to include a current solution (as of April 2019) for people using Ubuntu 18.04. This is how I solved the question above...
/usr/lib/Android/
Search for where the SDK is installed and the version. In my case it was here:
/usr/lib/Android/Sdk/build-tools/28.0.3
Note: that I am using version 28.0.3, your version may differ.
Add ANDROID_HOME
to the environment path. To do this, open /etc/environment with a text editor:
sudo nano /etc/environment
Add a line for ANDROID_HOME
for your specific version and path. In my case it was:
ANDROID_HOME="/usr/lib/Android/Sdk/build-tools/28.0.3"
Finally, source the updated environment with: source /etc/environment
Confirm this by trying: echo $ANDROID_HOME
in the terminal. You should get the path of your newly created variable.
One additionally note about sourcing, I did have to restart my computer for the VScode terminal to recognize my changes. After the restart, the environment was set and I haven't had any issues since.
First, make sure you understand, if you need to use Secure FTP (=FTPS, as per your text) or SFTP (as per tag you have used).
Neither is supported by Windows command-line ftp.exe
. As you have suggested, you can use WinSCP. It supports both FTPS and SFTP.
Using WinSCP, your batch file would look like (for SFTP):
echo open sftp://ftp_user:[email protected] -hostkey="server's hostkey" >> ftpcmd.dat
echo put c:\directory\%1-export-%date%.csv >> ftpcmd.dat
echo exit >> ftpcmd.dat
winscp.com /script=ftpcmd.dat
del ftpcmd.dat
And the batch file:
winscp.com /log=ftpcmd.log /script=ftpcmd.dat /parameter %1 %date%
Though using all capabilities of WinSCP (particularly providing commands directly on command-line and the %TIMESTAMP%
syntax), the batch file simplifies to:
winscp.com /log=ftpcmd.log /command ^
"open sftp://ftp_user:[email protected] -hostkey=""server's hostkey""" ^
"put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
"exit"
For the purpose of -hostkey
switch, see verifying the host key in script.
Easier than assembling the script/batch file manually is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you:
All you need to tweak is the source file name (use the %TIMESTAMP%
syntax as shown previously) and the path to the log file.
For FTPS, replace the sftp://
in the open
command with ftpes://
(explicit TLS/SSL) or ftps://
(implicit TLS/SSL). Remove the -hostkey
switch.
winscp.com /log=ftpcmd.log /command ^
"open ftps://ftp_user:[email protected] -explicit" ^
"put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
"exit"
You may need to add the -certificate
switch, if your server's certificate is not issued by a trusted authority.
Again, as with the SFTP, easier is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you.
See a complete conversion guide from ftp.exe
to WinSCP.
You should also read the Guide to automating file transfers to FTP server or SFTP server.
Note to using %TIMESTAMP#yyyymmdd%
instead of %date%
: A format of %date%
variable value is locale-specific. So make sure you test the script on the same locale you are actually going to use the script on. For example on my Czech locale the %date%
resolves to ct 06. 11. 2014
, what might be problematic when used as a part of a file name.
For this reason WinSCP supports (locale-neutral) timestamp formatting natively. For example %TIMESTAMP#yyyymmdd%
resolves to 20170515
on any locale.
(I'm the author of WinSCP)
A one-line version of this excellent answer to plot the line of best fit is:
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
Using np.unique(x)
instead of x
handles the case where x
isn't sorted or has duplicate values.
The call to poly1d
is an alternative to writing out m*x + b
like in this other excellent answer.
This means that the maximum number of simultaneously open files.
Solved:
At the end of the file /etc/security/limits.conf
you need to add the following lines:
* soft nofile 16384
* hard nofile 16384
In the current console from root (sudo does not work) to do:
ulimit -n 16384
Although this is optional, if it is possible to restart the server.
In /etc/nginx/nginx.conf
file to register the new value worker_connections
equal to 16384
divide by value worker_processes
.
If not did ulimit -n 16384
, need to reboot, then the problem will recede.
PS:
If after the repair is visible in the logs error accept() failed (24: Too many open files)
:
In the nginx configuration, propevia (for example):
worker_processes 2;
worker_rlimit_nofile 16384;
events {
worker_connections 8192;
}
I gave it a try, with regular expressions. I implemented it for ints and const strings as an example, but you can add whatever other types (POD types but with pointers you can print anything).
#include <assert.h>
#include <cstdarg>
#include <string>
#include <sstream>
#include <regex>
static std::string
formatArg(std::string argDescr, va_list args) {
std::stringstream ss;
if (argDescr == "i") {
int val = va_arg(args, int);
ss << val;
return ss.str();
}
if (argDescr == "s") {
const char *val = va_arg(args, const char*);
ss << val;
return ss.str();
}
assert(0); //Not implemented
}
std::string format(std::string fmt, ...) {
std::string result(fmt);
va_list args;
va_start(args, fmt);
std::regex e("\\{([^\\{\\}]+)\\}");
std::smatch m;
while (std::regex_search(fmt, m, e)) {
std::string formattedArg = formatArg(m[1].str(), args);
fmt.replace(m.position(), m.length(), formattedArg);
}
va_end(args);
return fmt;
}
Here is an example of use of it:
std::string formatted = format("I am {s} and I have {i} cats", "bob", 3);
std::cout << formatted << std::endl;
Output:
I am bob and I have 3 cats
This worked for me:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="39dip"
android:scaleType="centerCrop"
android:adjustViewBounds ="true"
There's lots of FTP sites you can get into with the 'anonymous' account and download, but a 'public' site that allows anonymous uploads would be utterly swamped with pr0n and warez in short order.
It's easy enough to set up your own FTP server for testing uploads. There's plenty of them for most any desktop OS. There's one built into IIS, for instance.
The simplest way of doing this is:
SELECT id,name,FROM_UNIXTIME(registration_date) FROM `tbl_registration`;
This gives the date column atleast in a readable format. Further if you want to change te format click here.
This worked for me in Luna elementary OS
sudo apt-get install libxtst6:i386
It's more clear when the query return a string (an array of char):
For example if the list 'Fruits' contains 'apple'
'Select' returns the string:
Fruits.Select(s=>s)
[0]: "apple"
'SelectMany' flattens the string:
Fruits.SelectMany(s=>s)
[0]: 97 'a'
[1]: 112 'p'
[2]: 112 'p'
[3]: 108 'l'
[4]: 101 'e'
and
has lower precedence than &&
.
But for an unassuming user, problems might occur if it is used along with other operators whose precedence are in between, for example, the assignment operator:
def happy?() true; end
def know_it?() true; end
todo = happy? && know_it? ? "Clap your hands" : "Do Nothing"
todo
# => "Clap your hands"
todo = happy? and know_it? ? "Clap your hands" : "Do Nothing"
todo
# => true
Take a look at the log_errors
configuration option in php.ini. It seems to do just what you want to. I think you can use the error_log
option to set your own logging file too.
When the log_errors
directive is set to On
, any errors reported by PHP would be logged to the server log or the file specified with error_log
. You can set these options with ini_set
too, if you need to.
(Please note that display_errors
should be disabled in php.ini if this option is enabled)
If the problem happens intermittently in production, it could be due to an action method getting interrupted. For example, during a POST operation involving a large file upload, the user closes the browser window before the upload completes. In this case, the action method may throw a null reference exception resulting from a null model or view object. A solution would be to wrap the method body in a try/catch and return null. Like this:
[HttpPost]
public ActionResult Post(...)
{
try
{
...
}
catch (NullReferenceException ex) // could happen if POST is interrupted
{
// perhaps log a warning here
return null;
}
return View(model);
}
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
$(document).ready(function() {
var num = $('div.number').text()
num = addPeriod(num);
$('div.number').text('Rp. '+num)
});
function addPeriod(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
If you want using it with parameter (ie. delete all subdirs under the given directory), then put this two lines into a *.bat or *.cmd file:
@echo off
for /f "delims=" %%d in ('dir %1 /s /b /ad ^| sort /r') do rd "%%d" 2>nul && echo rmdir %%d
and add script-path to your PATH environment variable. In this case you can call your batch file from any location (I suppose UNC path should work, too).
Eg.:
YourBatchFileName c:\temp
(you may use quotation marks if needed)
will remove all empty subdirs under c:\temp folder
YourBatchFileName
will remove all empty subdirs under the current directory.
I would like to expand the answer of Jason Bunting
like this
ActionResult action = new SampelController().Index(2, "text");
return action;
And Eli will be here for something idea on how to make it generic variable
Can get all types of controller
The native PHP function mail()
does not work for me. It issues the message:
503 This mail server requires authentication when attempting to send to a non-local e-mail address
So, I usually use PHPMailer
package
I've downloaded the version 5.2.23 from: GitHub.
I've just picked 2 files and put them in my source PHP root
class.phpmailer.php
class.smtp.php
In PHP, the file needs to be added
require_once('class.smtp.php');
require_once('class.phpmailer.php');
After this, it's just code:
require_once('class.smtp.php');
require_once('class.phpmailer.php');
...
//----------------------------------------------
// Send an e-mail. Returns true if successful
//
// $to - destination
// $nameto - destination name
// $subject - e-mail subject
// $message - HTML e-mail body
// altmess - text alternative for HTML.
//----------------------------------------------
function sendmail($to,$nameto,$subject,$message,$altmess) {
$from = "[email protected]";
$namefrom = "yourname";
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // by SMTP
$mail->SMTPAuth = true; // user and password
$mail->Host = "localhost";
$mail->Port = 25;
$mail->Username = $from;
$mail->Password = "yourpassword";
$mail->SMTPSecure = ""; // options: 'ssl', 'tls' , ''
$mail->setFrom($from,$namefrom); // From (origin)
$mail->addCC($from,$namefrom); // There is also addBCC
$mail->Subject = $subject;
$mail->AltBody = $altmess;
$mail->Body = $message;
$mail->isHTML(); // Set HTML type
//$mail->addAttachment("attachment");
$mail->addAddress($to, $nameto);
return $mail->send();
}
It works like a charm