Recently, I used this .NET Metadata API. I have also written a blog post about it, that shows reading, updating, and removing the EXIF data from images using C#.
using (Metadata metadata = new Metadata("image.jpg"))
{
IExif root = metadata.GetRootPackage() as IExif;
if (root != null && root.ExifPackage != null)
{
Console.WriteLine(root.ExifPackage.DateTime);
}
}
For log4j 2 API , you can use
Logger logger = LogManager.getRootLogger();
Configurator.setAllLevels(logger.getName(), Level.getLevel(level));
The official RFC which defines this specification could be found here:
http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)
2.1.2. Header Field: From
Description: Mailbox of message author [...] Related information: Specifies the author(s) of the message; that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. Defined as standard by RFC 822.
2.1.3. Header Field: Sender
Description: Mailbox of message sender [...] Related information: Specifies the mailbox of the agent responsible for the actual transmission of the message. Defined as standard by RFC 822.
2.1.22. Header Field: Return-Path
Description: Message return path [...] Related information: Return path for message response diagnostics. See also RFC 2821 [17]. Defined as standard by RFC 822.
Hej man, why are you using this ?
dir /s/b/o:gn > f.txt (wrong one)
Don't you know what is that 'g' in '/o' ??
Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help
You should be using this instead:
dir /s/b/o:n > f.txt (right one)
The slowest possible method is to compare two files byte by byte. The fastest I've been able to come up with is a similar comparison, but instead of one byte at a time, you would use an array of bytes sized to Int64, and then compare the resulting numbers.
Here's what I came up with:
const int BYTES_TO_READ = sizeof(Int64);
static bool FilesAreEqual(FileInfo first, FileInfo second)
{
if (first.Length != second.Length)
return false;
if (string.Equals(first.FullName, second.FullName, StringComparison.OrdinalIgnoreCase))
return true;
int iterations = (int)Math.Ceiling((double)first.Length / BYTES_TO_READ);
using (FileStream fs1 = first.OpenRead())
using (FileStream fs2 = second.OpenRead())
{
byte[] one = new byte[BYTES_TO_READ];
byte[] two = new byte[BYTES_TO_READ];
for (int i = 0; i < iterations; i++)
{
fs1.Read(one, 0, BYTES_TO_READ);
fs2.Read(two, 0, BYTES_TO_READ);
if (BitConverter.ToInt64(one,0) != BitConverter.ToInt64(two,0))
return false;
}
}
return true;
}
In my testing, I was able to see this outperform a straightforward ReadByte() scenario by almost 3:1. Averaged over 1000 runs, I got this method at 1063ms, and the method below (straightforward byte by byte comparison) at 3031ms. Hashing always came back sub-second at around an average of 865ms. This testing was with an ~100MB video file.
Here's the ReadByte and hashing methods I used, for comparison purposes:
static bool FilesAreEqual_OneByte(FileInfo first, FileInfo second)
{
if (first.Length != second.Length)
return false;
if (string.Equals(first.FullName, second.FullName, StringComparison.OrdinalIgnoreCase))
return true;
using (FileStream fs1 = first.OpenRead())
using (FileStream fs2 = second.OpenRead())
{
for (int i = 0; i < first.Length; i++)
{
if (fs1.ReadByte() != fs2.ReadByte())
return false;
}
}
return true;
}
static bool FilesAreEqual_Hash(FileInfo first, FileInfo second)
{
byte[] firstHash = MD5.Create().ComputeHash(first.OpenRead());
byte[] secondHash = MD5.Create().ComputeHash(second.OpenRead());
for (int i=0; i<firstHash.Length; i++)
{
if (firstHash[i] != secondHash[i])
return false;
}
return true;
}
No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below.
You also can create Firbase Dynamic links which will work as per your requirement. It supports multiple platforms. This link can be created, manually as well as via programming. You can then embed this link in QR code.
If the target app is installed, the link will redirect user to app. If its not installed it will redirect to Play Store/App store/Any other configured website.
For those who still do not understand.
>>> a = iter(list(range(10)))
>>> for i in a:
... print(i)
... next(a)
...
0 # print(i) printed this
1 # next(a) printed this
2 # print(i) printed this
3 # next(a) printed this
4 # print(i) printed this
5 # next(a) printed this
6 # print(i) printed this
7 # next(a) printed this
8 # print(i) printed this
9 # next(a) printed this
As others have already said, next
increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.
Make an equals
check on the keySet()
of both HashMap
s.
NOTE:
If your Map
contains String
keys then it is no problem, but if your Map contains objA
type keys then you need to make sure that your class objA
implements equals()
.
I have the same issue when processing a file generated from Linux. It turns out it was related with files containing question marks..
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
This will only work with modern browsers but I find it easier to just use a then
so please test first but:
Code
function rafAsync() {
return new Promise(resolve => {
requestAnimationFrame(resolve); //faster than set time out
});
}
function checkElement(selector) {
if (document.querySelector(selector) === null) {
return rafAsync().then(() => checkElement(selector));
} else {
return Promise.resolve(true);
}
}
Or using generator functions
async function checkElement(selector) {
const querySelector = null;
while (querySelector === null) {
await rafAsync();
querySelector = document.querySelector(selector);
}
return querySelector;
}
Usage
checkElement('body') //use whichever selector you want
.then((element) => {
console.info(element);
//Do whatever you want now the element is there
});
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
I have tried too many solutions but neither them was working,After wasting my half day finally i made a solution.
This code simply show you a DatePickerDialog with Minimum and Maximum date,month and year,whatever you want just modify it.
final Calendar calendar = Calendar.getInstance();
DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int year, int month, int day_of_month) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, (month+1));
calendar.set(Calendar.DAY_OF_MONTH, day_of_month);
String myFormat = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
your_edittext.setText(sdf.format(calendar.getTime()));
}
},calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());// TODO: used to hide previous date,month and year
calendar.add(Calendar.YEAR, 0);
dialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());// TODO: used to hide future date,month and year
dialog.show();
Output:- Disable previous and future calendar
Are you trying to reference a user variable in system variables? Try echo %path%
and the M2 should have been fully expanded to show the file path to your Maven directory. If it hasn't, then that's the problem.
To fix it, you should create a user variable called PATH
and add your %M2%
reference into there.
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
Or you can try to add in local name resolution (hosts
file found in the directory etc
in most operating systems, details differ) something like this:
192.168.1.1 Linksys
and next
var req = https.request({
host: 'Linksys',
port: 443,
path: '/',
method: 'GET'
...
will work.
You just need to override onCreateDialog
in an Activity.
//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";
private static final int DIALOG_LOAD_FILE = 1000;
private void loadFileList() {
try {
mPath.mkdirs();
}
catch(SecurityException e) {
Log.e(TAG, "unable to write on the sd card " + e.toString());
}
if(mPath.exists()) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
return filename.contains(FTYPE) || sel.isDirectory();
}
};
mFileList = mPath.list(filter);
}
else {
mFileList= new String[0];
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
switch(id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
if(mFileList == null) {
Log.e(TAG, "Showing file picker before loading the file list");
dialog = builder.create();
return dialog;
}
builder.setItems(mFileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChosenFile = mFileList[which];
//you can do stuff with the file here too
}
});
break;
}
dialog = builder.show();
return dialog;
}
You could write a function that converts a scientific notation to regular, something like
def sc2std(x):
s = str(x)
if 'e' in s:
num,ex = s.split('e')
if '-' in num:
negprefix = '-'
else:
negprefix = ''
num = num.replace('-','')
if '.' in num:
dotlocation = num.index('.')
else:
dotlocation = len(num)
newdotlocation = dotlocation + int(ex)
num = num.replace('.','')
if (newdotlocation < 1):
return negprefix+'0.'+'0'*(-newdotlocation)+num
if (newdotlocation > len(num)):
return negprefix+ num + '0'*(newdotlocation - len(num))+'.0'
return negprefix + num[:newdotlocation] + '.' + num[newdotlocation:]
else:
return s
Below Different tools for Editing Rdlc report:
The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:
Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).
Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:
For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to example.domain.com, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.
ALIAS or ANAME or @ example.domain.com.
If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.
I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer @subdomain.domain.org over @domain.org ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.
I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.
Basically, when you have something like:
<form onsubmit="return callSomeFunction();"></form>
or
<a href="#" onclick="return callSomeFunction();"></a>`
and callSomeFunction()
returns true, then the form
or a
will submit, otherwise it won't.
Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.
All above methods are not good because you might change event function name. The easiest is:
btnTest.PerfromClick();
I know it's a bit late to answer this question, and maybe you already found the solution, but I'm posting the solution I found (after I googled a lot) so it may help a little:
-Dlog4j.debug
@ the end of your java options of tomcatHope this will help.
rgds
You can use the pseudo-class a:hover
in external style sheets only. Therefore I recommend using an external style sheet. The code is:
a:hover {color:#FF00FF;} /* Mouse-over link */
You can right click the project file, select "Unload project" then you can open the file directly for editing by selecting "Edit project name.csproj".
You will have to load the project back after you have saved your changes in order for it to compile.
See How to: Unload and Reload Projects on MSDN.
Since project files are XML files, you can also simply edit them using any text editor that supports Unicode (notepad, notepad++ etc...)
However, I would be very reluctant to edit these files by hand - use the Solution explorer for this if at all possible. If you have errors and you know how to fix them manually, go ahead, but be aware that you can completely ruin the project file if you don't know exactly what you are doing.
The base dn is dc=example,dc=com
.
I don't know about openca, but I will try this answer since you got very little traffic so far.
A base dn is the point from where a server will search for users. So I would try to simply use admin
as a login name.
If openca behaves like most ldap aware applications, this is what is going to happen :
admin
will be done by the server starting at the base dn (dc=example,dc=com
).cn=admin,dc=example,dc=com
) will be used to bind with the supplied password.Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :
dn
your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com
.objectClass
for your admin
user. It will be either inetOrgPerson
or user
. There will be others like top
, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson)
. Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user))
. Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.
The reason for that error is that you are trying to copy a folder which requires -r option also to cp Thanks
The command palette
tells you the colours and their order when col = somefactor
. It can also be used to set the colours as well.
palette()
[1] "black" "red" "green3" "blue" "cyan" "magenta" "yellow" "gray"
In order to see that in your graph you could use a legend.
legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)
You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.
You could also be specific about the colours. Try ?rainbow
for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.
Given the following tables..
Domain Table
dom_id | dom_url
Review Table
rev_id | rev_dom_from | rev_dom_for
Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.
Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for
If you are still stuck, please be more specific with exactly it is that you don't understand.
If you don't want anything to display before the redirect, then you will need to use some server side scripting to accomplish the task before the page is served. The page has already begun loading by the time your Javascript is executed on the client side.
If Javascript is your only option, your best best is to make your script the first .js file included in the <head>
of your document.
Instead of Javascript, I recommend setting up your redirect logic in your Apache or nginx server configuration.
This is a small program that will keep asking an input until required input is given.
we should keep the required number as a string, otherwise it may not work. input is taken as string by default
required_number = '18'
while True:
number = input("Enter the number\n")
if number == required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
or you can use eval(input()) method
required_number = 18
while True:
number = eval(input("Enter the number\n"))
if number == required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
You have multiple ways to set :
as the separator:
awk -F: '{print $1}'
awk -v FS=: '{print $1}'
awk '{print $1}' FS=:
awk 'BEGIN{FS=":"} {print $1}'
All of them are equivalent and will return 1
given a sample input "1:2:3":
$ awk -F: '{print $1}' <<< "1:2:3"
1
$ awk -v FS=: '{print $1}' <<< "1:2:3"
1
$ awk '{print $1}' FS=: <<< "1:2:3"
1
$ awk 'BEGIN{FS=":"} {print $1}' <<< "1:2:3"
1
Using MacPorts you can install the client with:
sudo port install mysql57
You also need to select the installed version as your mysql
sudo port select mysql mysql57
The server is only installed if you append -server
to the package name (e.g. mysql57-server
)
This works for me: View view is your editText, spinner...etc. And int drawable is your drawable route example (R.drawable.yourDrawable)
public void verifyDrawable (View view, int drawable){
int sdk = Build.VERSION.SDK_INT;
if(sdk < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(
ContextCompat.getDrawable(getContext(),drawable));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(getResources().getDrawable(drawable));
}
}
.mat files contain binary data, so you will not be able to open them easily with a word processor. There are some options for opening them outside of MATLAB:
If all you need to do is look at the files, you could obtain Octave, which is a free, but somewhat slower implementation of MATLAB. You can refer to How do you open .mat files in Octave? for more information on the subject. You can get octave from http://www.gnu.org/software/octave/download.html. The interface is very similar to MATLAB's.
As NKN and Ergodicity mentioned, there are python libaries available for this as well.
The most hardcore solution would be to write your own processor from scratch. The MAT file specification is available from MathWorks at http://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf.
You just subindex it with [:5]
indicating that you want (up to) the first 5 elements.
>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]
Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!
>>> x[5:]
[11, 12]
System.AppDomain.CurrentDomain.BaseDirectory
This will give you the running directory of your application. This even works for web applications. Afterwards, you can reach your file.
Use money-rails gem. It nicely handles money and currencies in your model and also has a bunch of helpers to format your prices.
request.getSession()
will return a current session. if current session does not exist, then it will create a new one.
request.getSession(true)
will return current session. If current session does not exist, then it will create a new session.
So basically there is not difference between both method.
request.getSession(false)
will return current session if current session exists. If not, it will not create a new session.
Swift 4 example:
var filePath: String {
//manager lets you examine contents of a files and folders in your app.
let manager = FileManager.default
//returns an array of urls from our documentDirectory and we take the first
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
//print("this is the url path in the document directory \(String(describing: url))")
//creates a new path component and creates a new file called "Data" where we store our data array
return(url!.appendingPathComponent("Data").path)
}
I put the check in my loadData function which I called in viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
Then I defined loadData below.
func loadData() {
let manager = FileManager.default
if manager.fileExists(atPath: filePath) {
print("The file exists!")
//Do what you need with the file.
ourData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! Array<DataObject>
} else {
print("The file DOES NOT exist! Mournful trumpets sound...")
}
}
@Marc B Thanks for the comment. Helped me discover this:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
the_content();
endwhile; else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
You have to specify any one of the above phase to resolve the above error. In most of the situations, this would have occurred due to running the build from the eclipse environment.
instead of mvn clean package or mvn package you can try only package its work fine for me
These are the necersary imports:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
This is what finally worked for me:
<xsd:element name="bar">
<xsd:complexType>
<xsd:sequence>
<!-- Permit any of these tags in any order in any number -->
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element name="child1" type="xsd:string" />
<xsd:element name="child2" type="xsd:string" />
<xsd:element name="child3" type="xsd:string" />
</xsd:choice>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
I find that when I include a blank line in my source after the \\ then I also get a blank line in my output. Example:
It's time to recognize the income tax as another horrible policy mistake like banning beer, and to return to the tax policies that were correct in the Constitution in the first place. Our future depends on it.
\\
Wherefore the 16th Amendment must forthwith be repealed.
However you are correct that LaTeX only lets you do this once. For a more general solution allowing you to make as many blank lines as you want, use \null to make empty paragraphs. Example:
It's time to recognize the income tax as another horrible policy mistake like banning beer, and to return to the tax policies that were correct in the Constitution in the first place. Our future depends on it.
\null
\null
\null
Wherefore the 16th Amendment must forthwith be repealed.
double[,]
is a 2d array (matrix) while double[][]
is an array of arrays (jagged arrays) and the syntax is:
double[][] ServicePoint = new double[10][];
The best way use Java 8 time API:
LocalDateTime ldt = timeStamp.toLocalDateTime();
Timestamp ts = Timestamp.valueOf(ldt);
For use with JPA put in with your model (https://weblogs.java.net/blog/montanajava/archive/2014/06/17/using-java-8-datetime-classes-jpa):
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime ldt) {
return Timestamp.valueOf(ldt);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp ts) {
return ts.toLocalDateTime();
}
}
So now it is relative timezone independent time. Additionally it is easy do:
LocalDate ld = ldt.toLocalDate();
LocalTime lt = ldt.toLocalTime();
Formatting:
DateTimeFormatter DATE_TME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
String str = ldt.format(DATE_TME_FORMATTER);
ldt = LocalDateTime.parse(str, DATE_TME_FORMATTER);
UPDATE: postgres 9.4.1208, HSQLDB 2.4.0 etc understand Java 8 Time API without any conversations!
You can do the following (which I find trivial, but its actually correct). For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).
Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following
const myArray: any[][] = [];
And later, when you want to populate it, you can do the following:
myArray.push([<your value goes here>]);
A short example of the above can be the following:
const myArray: string[][] = [];
myArray.push(["value1", "value2"]);
For Windows : Uncomment this line in your php.ini file
;extension=php_gd2.dll
If the above step doesn't work uncomment the following line as well:
;extension=gd2
You need to check the return value against EOF
, not against 1
.
Note that in your example, you also used two different variable names, words
and word
, only declared words
, and didn't declare its length, which should be 16 to fit the 15 characters read in plus a NUL
character.
If you use Robert Harder's Base64 utility, then you can do:
InputStream is = new Base64.InputStream(cph);
Or with sun's JRE, you can do:
InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.
There are other Stack Overflow questions about Base64 decoding, such as this one.
I have created much more thorough benchmarks. First of all, as @ChaimG pointed out, early binding makes a big difference (I originally used @eksortso's code above verbatim which uses late binding). Secondly, my original benchmarks only included the time to create the unique object, however, it did not test the efficiency of using the object. My point in doing this is, it doesn't really matter if I can create an object really fast if the object I create is clunky and slows me down moving forward.
Old Remark: It turns out, that looping over a collection object is highly inefficient
It turns out that looping over a collection can be quite efficient if you know how to do it (I didn't). As @ChaimG (yet again), pointed out in the comments, using a For Each
construct is ridiculously superior to simply using a For
loop. To give you an idea, before changing the loop construct, the time for Collection2
for the Test Case Size = 10^6
was over 1400s (i.e. ~23 minutes). It is now a meager 0.195s (over 7000x faster).
For the Collection
method there are two times. The first (my original benchmark Collection1
) show the time to create the unique object. The second part (Collection2
) shows the time to loop over the object (which is very natural) to create a returnable array as the other functions do.
In the chart below, a yellow background indicates that it was the fastest for that test case, and red indicates the slowest ("Not Tested" algorithms are excluded). The total time for the Collection
method is the sum of Collection1
and Collection2
. Turquoise indicates that is was the fastest regardless of original order.
Below is the original algorithm I created (I have modified it slightly e.g. I no longer instantiate my own data type). It returns the unique values of an array with the original order in a very respectable time and it can be modified to take on any data type. Outside of the IndexMethod
, it is the fastest algorithm for very large arrays.
Here are the main ideas behind this algorithm:
Below is an example:
Let myArray = (86, 100, 33, 19, 33, 703, 19, 100, 703, 19)
1. (86, 100, 33, 19, 33, 703, 19, 100, 703, 19)
(1 , 2, 3, 4, 5, 6, 7, 8, 9, 10) <<-- Indexing
2. (19, 19, 19, 33, 33, 86, 100, 100, 703, 703) <<-- sort by values
(4, 7, 10, 3, 5, 1, 2, 8, 6, 9)
3. (19, 33, 86, 100, 703) <<-- remove duplicates
(4, 3, 1, 2, 6)
4. (86, 100, 33, 19, 703)
( 1, 2, 3, 4, 6) <<-- sort by index
Here is the code:
Function SortingUniqueTest(ByRef myArray() As Long, bOrigIndex As Boolean) As Variant
Dim MyUniqueArr() As Long, i As Long, intInd As Integer
Dim StrtTime As Double, Endtime As Double, HighB As Long, LowB As Long
LowB = LBound(myArray): HighB = UBound(myArray)
ReDim MyUniqueArr(1 To 2, LowB To HighB)
intInd = 1 - LowB 'Guarantees the indices span 1 to Lim
For i = LowB To HighB
MyUniqueArr(1, i) = myArray(i)
MyUniqueArr(2, i) = i + intInd
Next i
QSLong2D MyUniqueArr, 1, LBound(MyUniqueArr, 2), UBound(MyUniqueArr, 2), 2
Call UniqueArray2D(MyUniqueArr)
If bOrigIndex Then QSLong2D MyUniqueArr, 2, LBound(MyUniqueArr, 2), UBound(MyUniqueArr, 2), 2
SortingUniqueTest = MyUniqueArr()
End Function
Public Sub UniqueArray2D(ByRef myArray() As Long)
Dim i As Long, j As Long, Count As Long, Count1 As Long, DuplicateArr() As Long
Dim lngTemp As Long, HighB As Long, LowB As Long
LowB = LBound(myArray, 2): Count = LowB: i = LowB: HighB = UBound(myArray, 2)
Do While i < HighB
j = i + 1
If myArray(1, i) = myArray(1, j) Then
Do While myArray(1, i) = myArray(1, j)
ReDim Preserve DuplicateArr(1 To Count)
DuplicateArr(Count) = j
Count = Count + 1
j = j + 1
If j > HighB Then Exit Do
Loop
QSLong2D myArray, 2, i, j - 1, 2
End If
i = j
Loop
Count1 = HighB
If Count > 1 Then
For i = UBound(DuplicateArr) To LBound(DuplicateArr) Step -1
myArray(1, DuplicateArr(i)) = myArray(1, Count1)
myArray(2, DuplicateArr(i)) = myArray(2, Count1)
Count1 = Count1 - 1
ReDim Preserve myArray(1 To 2, LowB To Count1)
Next i
End If
End Sub
Here is the sorting algorithm I use (more about this algo here).
Sub QSLong2D(ByRef saArray() As Long, bytDim As Byte, lLow1 As Long, lHigh1 As Long, bytNum As Byte)
Dim lLow2 As Long, lHigh2 As Long
Dim sKey As Long, sSwap As Long, i As Byte
On Error GoTo ErrorExit
If IsMissing(lLow1) Then lLow1 = LBound(saArray, bytDim)
If IsMissing(lHigh1) Then lHigh1 = UBound(saArray, bytDim)
lLow2 = lLow1
lHigh2 = lHigh1
sKey = saArray(bytDim, (lLow1 + lHigh1) \ 2)
Do While lLow2 < lHigh2
Do While saArray(bytDim, lLow2) < sKey And lLow2 < lHigh1: lLow2 = lLow2 + 1: Loop
Do While saArray(bytDim, lHigh2) > sKey And lHigh2 > lLow1: lHigh2 = lHigh2 - 1: Loop
If lLow2 < lHigh2 Then
For i = 1 To bytNum
sSwap = saArray(i, lLow2)
saArray(i, lLow2) = saArray(i, lHigh2)
saArray(i, lHigh2) = sSwap
Next i
End If
If lLow2 <= lHigh2 Then
lLow2 = lLow2 + 1
lHigh2 = lHigh2 - 1
End If
Loop
If lHigh2 > lLow1 Then QSLong2D saArray(), bytDim, lLow1, lHigh2, bytNum
If lLow2 < lHigh1 Then QSLong2D saArray(), bytDim, lLow2, lHigh1, bytNum
ErrorExit:
End Sub
Below is a special algorithm that is blazing fast if your data contains integers. It makes use of indexing and the Boolean data type.
Function IndexSort(ByRef myArray() As Long, bOrigIndex As Boolean) As Variant
'' Modified to take both positive and negative integers
Dim arrVals() As Long, arrSort() As Long, arrBool() As Boolean
Dim i As Long, HighB As Long, myMax As Long, myMin As Long, OffSet As Long
Dim LowB As Long, myIndex As Long, count As Long, myRange As Long
HighB = UBound(myArray)
LowB = LBound(myArray)
For i = LowB To HighB
If myArray(i) > myMax Then myMax = myArray(i)
If myArray(i) < myMin Then myMin = myArray(i)
Next i
OffSet = Abs(myMin) '' Number that will be added to every element
'' to guarantee every index is non-negative
If myMax > 0 Then
myRange = myMax + OffSet '' E.g. if myMax = 10 & myMin = -2, then myRange = 12
Else
myRange = OffSet
End If
If bOrigIndex Then
ReDim arrSort(1 To 2, 1 To HighB)
ReDim arrVals(1 To 2, 0 To myRange)
ReDim arrBool(0 To myRange)
For i = LowB To HighB
myIndex = myArray(i) + OffSet
arrBool(myIndex) = True
arrVals(1, myIndex) = myArray(i)
If arrVals(2, myIndex) = 0 Then arrVals(2, myIndex) = i
Next i
For i = 0 To myRange
If arrBool(i) Then
count = count + 1
arrSort(1, count) = arrVals(1, i)
arrSort(2, count) = arrVals(2, i)
End If
Next i
QSLong2D arrSort, 2, 1, count, 2
ReDim Preserve arrSort(1 To 2, 1 To count)
Else
ReDim arrSort(1 To HighB)
ReDim arrVals(0 To myRange)
ReDim arrBool(0 To myRange)
For i = LowB To HighB
myIndex = myArray(i) + OffSet
arrBool(myIndex) = True
arrVals(myIndex) = myArray(i)
Next i
For i = 0 To myRange
If arrBool(i) Then
count = count + 1
arrSort(count) = arrVals(i)
End If
Next i
ReDim Preserve arrSort(1 To count)
End If
ReDim arrVals(0)
ReDim arrBool(0)
IndexSort = arrSort
End Function
Here are the Collection (by @DocBrown) and Dictionary (by @eksortso) Functions.
Function CollectionTest(ByRef arrIn() As Long, Lim As Long) As Variant
Dim arr As New Collection, a, i As Long, arrOut() As Variant, aFirstArray As Variant
Dim StrtTime As Double, EndTime1 As Double, EndTime2 As Double, count As Long
On Error Resume Next
ReDim arrOut(1 To UBound(arrIn))
ReDim aFirstArray(1 To UBound(arrIn))
StrtTime = Timer
For i = 1 To UBound(arrIn): aFirstArray(i) = CStr(arrIn(i)): Next i '' Convert to string
For Each a In aFirstArray ''' This part is actually creating the unique set
arr.Add a, a
Next
EndTime1 = Timer - StrtTime
StrtTime = Timer ''' This part is writing back to an array for return
For Each a In arr: count = count + 1: arrOut(count) = a: Next a
EndTime2 = Timer - StrtTime
CollectionTest = Array(arrOut, EndTime1, EndTime2)
End Function
Function DictionaryTest(ByRef myArray() As Long, Lim As Long) As Variant
Dim StrtTime As Double, Endtime As Double
Dim d As Scripting.Dictionary, i As Long '' Early Binding
Set d = New Scripting.Dictionary
For i = LBound(myArray) To UBound(myArray): d(myArray(i)) = 1: Next i
DictionaryTest = d.Keys()
End Function
Here is the Direct approach provided by @IsraelHoletz.
Function ArrayUnique(ByRef aArrayIn() As Long) As Variant
Dim aArrayOut() As Variant, bFlag As Boolean, vIn As Variant, vOut As Variant
Dim i As Long, j As Long, k As Long
ReDim aArrayOut(LBound(aArrayIn) To UBound(aArrayIn))
i = LBound(aArrayIn)
j = i
For Each vIn In aArrayIn
For k = j To i - 1
If vIn = aArrayOut(k) Then bFlag = True: Exit For
Next
If Not bFlag Then aArrayOut(i) = vIn: i = i + 1
bFlag = False
Next
If i <> UBound(aArrayIn) Then ReDim Preserve aArrayOut(LBound(aArrayIn) To i - 1)
ArrayUnique = aArrayOut
End Function
Function DirectTest(ByRef aArray() As Long, Lim As Long) As Variant
Dim aReturn() As Variant
Dim StrtTime As Long, Endtime As Long, i As Long
aReturn = ArrayUnique(aArray)
DirectTest = aReturn
End Function
Here is the benchmark function that compares all of the functions. You should note that the last two cases are handled a little bit different because of memory issues. Also note, that I didn't test the Collection
method for the Test Case Size = 10,000,000
. For some reason, it was returning incorrect results and behaving unusual (I'm guessing the collection object has a limit on how many things you can put in it. I searched and I couldn't find any literature on this).
Function UltimateTest(Lim As Long, bTestDirect As Boolean, bTestDictionary, bytCase As Byte) As Variant
Dim dictionTest, collectTest, sortingTest1, indexTest1, directT '' all variants
Dim arrTest() As Long, i As Long, bEquality As Boolean, SizeUnique As Long
Dim myArray() As Long, StrtTime As Double, EndTime1 As Variant
Dim EndTime2 As Double, EndTime3 As Variant, EndTime4 As Double
Dim EndTime5 As Double, EndTime6 As Double, sortingTest2, indexTest2
ReDim myArray(1 To Lim): Rnd (-2) '' If you want to test negative numbers,
'' insert this to the left of CLng(Int(Lim... : (-1) ^ (Int(2 * Rnd())) *
For i = LBound(myArray) To UBound(myArray): myArray(i) = CLng(Int(Lim * Rnd() + 1)): Next i
arrTest = myArray
If bytCase = 1 Then
If bTestDictionary Then
StrtTime = Timer: dictionTest = DictionaryTest(arrTest, Lim): EndTime1 = Timer - StrtTime
Else
EndTime1 = "Not Tested"
End If
arrTest = myArray
collectTest = CollectionTest(arrTest, Lim)
arrTest = myArray
StrtTime = Timer: sortingTest1 = SortingUniqueTest(arrTest, True): EndTime2 = Timer - StrtTime
SizeUnique = UBound(sortingTest1, 2)
If bTestDirect Then
arrTest = myArray: StrtTime = Timer: directT = DirectTest(arrTest, Lim): EndTime3 = Timer - StrtTime
Else
EndTime3 = "Not Tested"
End If
arrTest = myArray
StrtTime = Timer: indexTest1 = IndexSort(arrTest, True): EndTime4 = Timer - StrtTime
arrTest = myArray
StrtTime = Timer: sortingTest2 = SortingUniqueTest(arrTest, False): EndTime5 = Timer - StrtTime
arrTest = myArray
StrtTime = Timer: indexTest2 = IndexSort(arrTest, False): EndTime6 = Timer - StrtTime
bEquality = True
For i = LBound(sortingTest1, 2) To UBound(sortingTest1, 2)
If Not CLng(collectTest(0)(i)) = sortingTest1(1, i) Then
bEquality = False
Exit For
End If
Next i
For i = LBound(dictionTest) To UBound(dictionTest)
If Not dictionTest(i) = sortingTest1(1, i + 1) Then
bEquality = False
Exit For
End If
Next i
For i = LBound(dictionTest) To UBound(dictionTest)
If Not dictionTest(i) = indexTest1(1, i + 1) Then
bEquality = False
Exit For
End If
Next i
If bTestDirect Then
For i = LBound(dictionTest) To UBound(dictionTest)
If Not dictionTest(i) = directT(i + 1) Then
bEquality = False
Exit For
End If
Next i
End If
UltimateTest = Array(bEquality, EndTime1, EndTime2, EndTime3, EndTime4, _
EndTime5, EndTime6, collectTest(1), collectTest(2), SizeUnique)
ElseIf bytCase = 2 Then
arrTest = myArray
collectTest = CollectionTest(arrTest, Lim)
UltimateTest = Array(collectTest(1), collectTest(2))
ElseIf bytCase = 3 Then
arrTest = myArray
StrtTime = Timer: sortingTest1 = SortingUniqueTest(arrTest, True): EndTime2 = Timer - StrtTime
SizeUnique = UBound(sortingTest1, 2)
UltimateTest = Array(EndTime2, SizeUnique)
ElseIf bytCase = 4 Then
arrTest = myArray
StrtTime = Timer: indexTest1 = IndexSort(arrTest, True): EndTime4 = Timer - StrtTime
UltimateTest = EndTime4
ElseIf bytCase = 5 Then
arrTest = myArray
StrtTime = Timer: sortingTest2 = SortingUniqueTest(arrTest, False): EndTime5 = Timer - StrtTime
UltimateTest = EndTime5
ElseIf bytCase = 6 Then
arrTest = myArray
StrtTime = Timer: indexTest2 = IndexSort(arrTest, False): EndTime6 = Timer - StrtTime
UltimateTest = EndTime6
End If
End Function
And finally, here is the sub that produces the table above.
Sub GetBenchmarks()
Dim myVar, i As Long, TestCases As Variant, j As Long, temp
TestCases = Array(1000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000)
For j = 0 To 11
If j < 6 Then
myVar = UltimateTest(CLng(TestCases(j)), True, True, 1)
ElseIf j < 10 Then
myVar = UltimateTest(CLng(TestCases(j)), False, True, 1)
ElseIf j < 11 Then
myVar = Array("Not Tested", "Not Tested", 0.1, "Not Tested", 0.1, 0.1, 0.1, 0, 0, 0)
temp = UltimateTest(CLng(TestCases(j)), False, False, 2)
myVar(7) = temp(0): myVar(8) = temp(1)
temp = UltimateTest(CLng(TestCases(j)), False, False, 3)
myVar(2) = temp(0): myVar(9) = temp(1)
myVar(4) = UltimateTest(CLng(TestCases(j)), False, False, 4)
myVar(5) = UltimateTest(CLng(TestCases(j)), False, False, 5)
myVar(6) = UltimateTest(CLng(TestCases(j)), False, False, 6)
Else
myVar = Array("Not Tested", "Not Tested", 0.1, "Not Tested", 0.1, 0.1, 0.1, "Not Tested", "Not Tested", 0)
temp = UltimateTest(CLng(TestCases(j)), False, False, 3)
myVar(2) = temp(0): myVar(9) = temp(1)
myVar(4) = UltimateTest(CLng(TestCases(j)), False, False, 4)
myVar(5) = UltimateTest(CLng(TestCases(j)), False, False, 5)
myVar(6) = UltimateTest(CLng(TestCases(j)), False, False, 6)
End If
Cells(4 + j, 6) = TestCases(j)
For i = 1 To 9: Cells(4 + j, 6 + i) = myVar(i - 1): Next i
Cells(4 + j, 17) = myVar(9)
Next j
End Sub
Summary
From the table of results, we can see that the Dictionary
method works really well for cases less than about 500,000, however, after that, the IndexMethod
really starts to dominate. You will notice that when order doesn't matter and your data is made up of positive integers, there is no comparison to the IndexMethod
algorithm (it returns the unique values from an array containing 10 million elements in less than 1 sec!!! Incredible!). Below I have a breakdown of which algorithm is preferred in various cases.
Case 1
Your Data contains integers (i.e. whole numbers, both positive and negative): IndexMethod
Case 2
Your Data contains non-integers (i.e. variant, double, string, etc.) with less than 200000 elements: Dictionary Method
Case 3
Your Data contains non-integers (i.e. variant, double, string, etc.) with more than 200000 elements: Collection Method
If you had to choose one algorithm, in my opinion, the Collection
method is still the best as it only requires a few lines of code, it's super general, and it's fast enough.
Change branch, discarding all local modifications
git checkout -f 9-sign-in-out
Rename the current branch to master, discarding current master
git branch -M master
when selecting packages at installation or update search for 'make' in searchbox and select the boxes showing 'make' and also 'gcc' mostly found in devel package.
You could use IIF
statement like in the next example:
SELECT
IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
TABLE_NAME
In Twitter Bootstrap bootstrap 3.0.0, Twitter button is flat. You can customize it from http://getbootstrap.com/customize. Button color, border radious etc.
Also you can find the HTML code and others functionality http://twitterbootstrap.org/bootstrap-css-buttons.
Bootstrap 2.3.2 button is gradient but 3.0.0 ( new release ) flat and looks more cool.
and also you can find to customize the entire bootstrap looks and style form this resources: http://twitterbootstrap.org/top-5-customizing-bootstrap-resources/
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
According to supported databases, Oracle 11g is not officially supported. Although, I believe you shouldn't have any problems using org.hibernate.dialect.OracleDialect
.
We had the same issue, using Plesk Onyx 17. Instead of messing up with rights etc., solution was to add nginx user into psacln group, in which all the other domain owners (users) were:
usermod -aG psacln nginx
Now nginx has rights to access .htaccess or any other file necessary to properly show the content.
On the other hand, also make sure that Apache is in psaserv group, to serve static content:
usermod -aG psaserv apache
And don't forget to restart both Apache and Nginx in Plesk after! (and reload pages with Ctrl-F5)
It worked for me by executing "python37 -m pip install openpyxl"
It means that the query you wrote returns more than one element(result) while your code expects a single result.
With moment you can parse the date string you have:
var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")
That's for UTC, you'll have to convert the time zone from that point if you so desire.
Then you can get the day of the week:
dt.format('dddd');
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));
I've wrote a small extension to do so.
Since you are creating the page using C# you may want to implement this:
https://github.com/felix-d-git/DesktopAppLink
Basically u are creating some registry entries to parse the links you click in your html page.
The browser will then ask to open the specified app.
C#:
DesktopAppLink.CreateLink("applink.sample", "\"<path to exe>\"", "");
HTML:
<a href="applink.sample:">Run Desktop App</a>
Result:
try this
sudo chmod -R 0777 /opt/lampp/htdocs/testproject
According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:
{% if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') ) %}
<li>some text</li>
{% endif %}
Edit: Using line_statement_prefix = '#'
* the code would look like this:
# if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') )
<li>some text</li>
# endif
*Here's an example of how you'd specify the line_statement_prefix
in the Environment
:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml']),
line_statement_prefix='#'
)
Or using Flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
I display images in windows forms when I put it in Load event like this:
private void Form1_Load( object sender , EventArgs e )
{
pictureBox1.ImageLocation = "./image.png"; //path to image
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}
You could also use DateTime.FromFileTime(finishTime) where finishTme is a long containing the ticks of a time. Or FromFileTimeUtc.
In C++ (without error checking):
std::string blob = ...; // assume blob is in the string
std::string query = "INSERT INTO foo (blob_column) VALUES (?);";
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr);
sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(),
SQLITE_TRANSIENT);
That can be SQLITE_STATIC
if the query will be executed before blob
gets destructed.
Add items:
arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
Retrieve items:
productName = listView1.SelectedItems[0].SubItems[0].Text;
price = listView1.SelectedItems[0].SubItems[1].Text;
quantity = listView1.SelectedItems[0].SubItems[2].Text;
I was looking for a general way of adding a column of numpy.nan
s to a dataframe without getting the dumb SettingWithCopyWarning
.
From the following:
numpy
array of NaNs in-lineI came up with this:
col = 'column_name'
df = df.assign(**{col:numpy.full(len(df), numpy.nan)})
Or just try this after each text passage for a new line.
$pdf->Write(0, ' ', '*', 0, 'C', TRUE, 0, false, false, 0) ;
I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.
For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.
Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.
http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html
My case is when using two factor auth, outlook account and VS12.
I found out I have to
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
Example:
post('url', {name: 'Johnny Bravo'});
I'm always the one to bring up findall() =)
>>> strings = ['foofo21', 'bar432', 'foobar12345']
>>> [re.findall(r'(\w+?)(\d+)', s)[0] for s in strings]
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
Note that I'm using a simpler (less to type) regex than most of the previous answers.
It's not an NPP solution, but in a pinch, you can use this online JSON Formatter and then just paste the formatted text into NPP and then select Javascript as the language.
add a textbox and scrollbar
in VB
Private Sub Textbox1_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Textbox1.ValueChanged
If e.OldValue > e.NewValue Then
Textbox1.Text = (Textbox1.Text + 1)
Else
Textbox1.Text = (Textbox1.Text - 1)
End If
End Sub
The order of execution of ng-click
and ng-model
is ambiguous since they do not define clear priorities. Instead you should use ng-change
or a $watch
on the $scope
to ensure that you obtain the correct values of the model variable.
In your case, this should work:
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
To set precision with 9 digits, get:
print "%.9f" % numvar
Return precision with 2 digits:
print "%.2f" % numvar
Return precision with 2 digits and float converted value:
numvar = 4.2345
print float("%.2f" % numvar)
Screen
If process is running in a screen session you can use screen's log command to log the output of that window to a file:
Switch to the script's window, C-a H to log.
Now you can :
$ tail -f screenlog.2 | grep whatever
From screen's man page:
log [on|off]
Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.
I'm sure tmux has something similar as well.
import java.util.Scanner;
public class SumAll {
public static void sumAll(int arr[]) {//initialize method return sum
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum is : " + sum);
}
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);//create scanner object
System.out.print("How many # you want to add : ");
num = input.nextInt();//return num from keyboard
int[] arr2 = new int[num];
for (int i = 0; i < arr2.length; i++) {
System.out.print("Enter Num" + (i + 1) + ": ");
arr2[i] = input.nextInt();
}
sumAll(arr2);
}
}
The removeAttr()
function only removes HTML attributes. The display
is not a HTML attribute, it's a CSS property. You'd like to use css()
function instead to manage CSS properties.
But jQuery offers a show()
function which does exactly what you want in a concise call:
$("span").show();
This is pretty simple with numpy
, just subtract the arrays:
diffs = array1 - array2
I get:
diffs == array([ 0.1, 0.2, 0.3])
It is under View -> Render Whitespace.
?? Sometimes the menu item shows that it is currently active but you can's see white spaces. You should uncheck and check again to make it work. It is a known bug
In the mac environment, you can search for any menu option under the Help menu, then it will open the exact menu path you are looking for. For example, searching for whitespace result in this:
I like this method,use sind(x)
or cosd(x)
import math
def sind(x):
return math.sin(math.radians(x))
def cosd(x):
return math.cos(math.radians(x))
Simple as:
DateTime.Now.ToString("MM.dd.yyyy");
link to MSDN on ALL formatting options for DateTime.ToString() method
Check your migration file, maybe you are using Schema::table, like this:
Schema::table('table_name', function ($table) {
// ...
});
If you want to create a new table you must use Schema::create:
Schema::create('table_name', function ($table) {
// ...
});
If you are looking for a range of columns, you can try this:
df.iloc[7:] = df.iloc[7:].astype(float)
The examples above will convert type to be float, for all the columns begin with the 7th to the end. You of course can use different type or different range.
I think this is useful when you have a big range of columns to convert and a lot of rows. It doesn't make you go over each row by yourself - I believe numpy do it more efficiently.
This is useful only if you know that all the required columns contain numbers only - it will not change "bad values" (like string) to be NaN for you.
Connect to the Guest and find out the ip address:
ifconfig
example of result (ip address is 10.0.2.15):
eth0 Link encap:Ethernet HWaddr 08:00:27:AE:36:99
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
Go to Vbox instance window -> Menu -> Network adapters:
Go to host system and try it in browser:
http://127.0.0.1:8000
or your network ip address (find out on the host machine by running: ipconfig).
In this case port forwarding is not needed, the communication goes over the LAN back to the host.
On the host machine - find out your netw ip address:
ipconfig
example of result:
IP Address. . . . . . . . . . . . : 192.168.5.1
On the guest machine you can communicate directly with the host, e.g. check it with ping:
# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...
@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):
sudo ufw allow 8000
While you can access global variables without the global
keyword, if you want to modify them you have to use the global
keyword. For example:
foo = 1
def test():
foo = 2 # new local foo
def blub():
global foo
foo = 3 # changes the value of the global foo
In your case, you're just accessing the list sub
.
Change the button to :
<button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>
Or even better, use a proper event handler by identifying the button :
<button id="show_button">Check Availability</button>
and a script
<script type="text/javascript">
var button = document.getElementById('show_button')
button.addEventListener('click',hideshow,false);
function hideshow() {
document.getElementById('hidden-div').style.display = 'block';
this.style.display = 'none'
}
</script>
This will listen to the changed event. I have tried the answers from others but those did not work for me and finally, this one worked.
$('input:radio[name="postage"]').change(function(){
if($(this).is(":checked")){
alert("lksdahflk");
}
});
Try using the [StringLength]
attribute:
[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.
Just use
unicode_to_list = list(EmployeeList)
var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();
I have converted it to int because my Price field was int and Average method return double .I hope this will help
Every printer is different but 0.25" (6.35 mm) is a safe bet.
In my case, I was using Nginx in front of my application with the following configuration:
location / {
proxy_pass http://localhost:8080/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
add_header Content-Security-Policy 'upgrade-insecure-requests';
}
so in my application I get the real user ip like so:
String clientIP = request.getHeader("X-Real-IP");
Easiest way to check if they are authenticated is Request.User.IsAuthenticated
I think (from memory)
SELECT text
FROM all_source
where name = 'FGETALGOGROUPKEY'
order by line
alternatively:
select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY')
from dual;
#include<stdio.h>
void main()
{
char a;
scanf("%c",&a);
printf("%d",a);
}
Uninstall Java (via Control Panel / Programs and Features)
Install Java JRE 7 --> OFFLINE <--
Configure JAVA_HOME and Path = %JAVA_HOME%/bin;%PATH%
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
This may also happen if your JSON file is not just 1 JSON record. A JSON record looks like this:
[{"some data": value, "next key": "another value"}]
It opens and closes with a bracket [ ], within the brackets are the braces { }. There can be many pairs of braces, but it all ends with a close bracket ]. If your json file contains more than one of those:
[{"some data": value, "next key": "another value"}]
[{"2nd record data": value, "2nd record key": "another value"}]
then loads() will fail.
I verified this with my own file that was failing.
import json
guestFile = open("1_guests.json",'r')
guestData = guestFile.read()
guestFile.close()
gdfJson = json.loads(guestData)
This works because 1_guests.json has one record []. The original file I was using all_guests.json had 6 records separated by newline. I deleted 5 records, (which I already checked to be bookended by brackets) and saved the file under a new name. Then the loads statement worked.
Error was
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 10 column 1 (char 261900 - 6964758)
PS. I use the word record, but that's not the official name. Also, if your file has newline characters like mine, you can loop through it to loads() one record at a time into a json variable.
Thought someone might like explanation by (annotated) example:
Below, if my deepClone() function does its job right, the test (as described in the 'it()' call) will succeed:
describe('deepClone() array copy', ()=>{
let source:any = {}
let clone:any = source
beforeAll(()=>{
source.a = [1,'string literal',{x:10, obj:{y:4}}]
clone = Utils.deepClone(source) // THE CLONING ACT TO BE TESTED - lets see it it does it right.
})
it('should create a clone which has unique identity, but equal values as the source object',()=>{
expect(source !== clone).toBe(true) // If we have different object instances...
expect(source).not.toBe(clone) // <= synonymous to the above. Will fail if: you remove the '.not', and if: the two being compared are indeed different objects.
expect(source).toEqual(clone) // ...that hold same values, all tests will succeed.
})
})
Of course this is not a complete test suite for my deepClone(), as I haven't tested here if the object literal in the array (and the one nested therein) also have distinct identity but same values.
Add readonly
:
<input type="text" value="3" class="field left" readonly>
If you want the value to be not submitted in a form, instead add the disabled
attribute.
<input type="text" value="3" class="field left" disabled>
There is no way to use CSS that always works to do this.
Why? CSS can't "disable" anything. You can still turn off display or visibility and use pointer-events: none
but pointer-events
doesn't work on versions of IE that came out earlier than IE 11.
Just as a tidbit:
Even (
((A)null)
instanceof A)
will return false
.
(If typecasting null
seems surprising, sometimes you have to do it, for example in situations like this:
public class Test
{
public static void test(A a)
{
System.out.println("a instanceof A: " + (a instanceof A));
}
public static void test(B b) {
// Overloaded version. Would cause reference ambiguity (compile error)
// if Test.test(null) was called without casting.
// So you need to call Test.test((A)null) or Test.test((B)null).
}
}
So Test.test((A)null)
will print a instanceof A: false
.)
P.S.: If you are hiring, please don't use this as a job interview question. :D
A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:
arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)
You have a couple options, you could setTimeout()
or setInterval()
. Here's a great article that elaborates on how to use them.
The magic is that they're built in to JavaScript, you can use them with any library.
If you get your adb from Android Studio (which most will nowadays since Android is deprecated on Eclipse), your adb
program will most likely be located here:
%USERPROFILE%\AppData\Local\Android\sdk\platform-tools
Where %USERPROFILE%
represents something like C:\Users\yourName
.
If you go into your computer's environmental variables and add %USERPROFILE%\AppData\Local\Android\sdk\platform-tools
to the PATH (just copy-paste that line, even with the % --- it will work fine, at least on Windows, you don't need to hardcode your username) then it should work now. Open a new command prompt and type adb
to check.
All those results generate garbage in a zealous attempt to handle more than two arguments. I'd be curious to see how they perform compared to good 'ol:
def max (a,b)
a>b ? a : b
end
which is, by-the-way, my official answer to your question.
Simply add finish(); in your first class' (login activity) onPause(); method. that's all
/**
* ??????????????,????????
* English: Calculating the difference between the given time and the current time and then showing the results.
*/
function date2Text(date) {
var milliseconds = new Date() - date;
var timespan = new TimeSpan(milliseconds);
if (milliseconds < 0) {
return timespan.toString() + "??";
}else{
return timespan.toString() + "?";
}
}
/**
* ???????????
* English: Using a function to calculate the time interval
* @param milliseconds ???
*/
var TimeSpan = function (milliseconds) {
milliseconds = Math.abs(milliseconds);
var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
milliseconds -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(milliseconds / (1000 * 60 * 60));
milliseconds -= hours * (1000 * 60 * 60);
var mins = Math.floor(milliseconds / (1000 * 60));
milliseconds -= mins * (1000 * 60);
var seconds = Math.floor(milliseconds / (1000));
milliseconds -= seconds * (1000);
return {
getDays: function () {
return days;
},
getHours: function () {
return hours;
},
getMinuts: function () {
return mins;
},
getSeconds: function () {
return seconds;
},
toString: function () {
var str = "";
if (days > 0 || str.length > 0) {
str += days + "?";
}
if (hours > 0 || str.length > 0) {
str += hours + "??";
}
if (mins > 0 || str.length > 0) {
str += mins + "??";
}
if (days == 0 && (seconds > 0 || str.length > 0)) {
str += seconds + "?";
}
return str;
}
}
}
To add all file at a time, use git add -A
To check git whole status, use git log
The easiest way is probably with VLOOKUP()
. This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.
For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:
=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)
Then simply fill this formula down the rest of column D.
Explanation:
$D2
specifies the value to search for.Sheet2!$A$2:$B$65535
specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535
). Note I am assuming you have a header cell in row 1.2
specifies a 1-based index of the column to return from within the searched range. The value of 2
will return the second column in the range Sheet2!$A$2:$B$65535
, namely the value of the B
column.FALSE
says to only return exact matches.As documented in /usr/src/linux/Documentation/block/switching-sched.txt
, the I/O scheduler on any particular block device can be changed at runtime. There may be some latency as the previous scheduler's requests are all flushed before bringing the new scheduler into use, but it can be changed without problems even while the device is under heavy use.
# cat /sys/block/hda/queue/scheduler
noop deadline [cfq]
# echo anticipatory > /sys/block/hda/queue/scheduler
# cat /sys/block/hda/queue/scheduler
noop [deadline] cfq
Ideally, there would be a single scheduler to satisfy all needs. It doesn't seem to exist yet. The kernel often doesn't have enough knowledge to choose the best scheduler for your workload:
noop
is often the best choice for memory-backed block devices (e.g. ramdisks) and other non-rotational media (flash) where trying to reschedule I/O is a waste of resourcesdeadline
is a lightweight scheduler which tries to put a hard limit on latencycfq
tries to maintain system-wide fairness of I/O bandwidthThe default was anticipatory
for a long time, and it received a lot of tuning, but was removed in 2.6.33 (early 2010). cfq
became the default some while ago, as its performance is reasonable and fairness is a good goal for multi-user systems (and even single-user desktops). For some scenarios -- databases are often used as examples, as they tend to already have their own peculiar scheduling and access patterns, and are often the most important service (so who cares about fairness?) -- anticipatory
has a long history of being tunable for best performance on these workloads, and deadline
very quickly passes all requests through to the underlying device.
If you're getting error TS1005: 'finally' expected.
, it means you forgot to implement catch
after try
. Generally, it means the syntax you attempted to use was incorrect.
I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:
response.sendRedirect("simpleList.do")
In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.
To go back without refreshing the page, We can do in html like below javascript:history.back()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
Based on Don W's solution, with fewer variables.
void process_mem_usage(double& vm_usage, double& resident_set)
{
vm_usage = 0.0;
resident_set = 0.0;
// the two fields we want
unsigned long vsize;
long rss;
{
std::string ignore;
std::ifstream ifs("/proc/self/stat", std::ios_base::in);
ifs >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore
>> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore
>> ignore >> ignore >> vsize >> rss;
}
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
vm_usage = vsize / 1024.0;
resident_set = rss * page_size_kb;
}
I'm quite sure this can be very simple
2.0.0p247 :032 > list = Array.new(5)
=> [nil, nil, nil, nil, nil]
2.0.0p247 :033 > list.map!{ |x| x = [0] }
=> [[0], [0], [0], [0], [0]]
2.0.0p247 :034 > list[0][0]
=> 0
At the beginning of your main method, add this line of code :
final long startTime = System.nanoTime();
And then, at the last line of your main method, you can add :
final long duration = System.nanoTime() - startTime;
duration
now contains the time in nanoseconds that your program ran. You can for example print this value like this:
System.out.println(duration);
If you want to show duration time in seconds, you must divide the value by 1'000'000'000. Or if you want a Date
object: Date myTime = new Date(duration / 1000);
You can then access the various methods of Date
to print number of minutes, hours, etc.
If you want to do that yourself, without using any external library, a clean way would be to create a template.html
file with all the static content, like for example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>$title</title>
</head>
<body>$body
</body>
</html>
Put a tag like $tag
for any dynamic content and then do something like this:
File htmlTemplateFile = new File("path/template.html");
String htmlString = FileUtils.readFileToString(htmlTemplateFile);
String title = "New Page";
String body = "This is Body";
htmlString = htmlString.replace("$title", title);
htmlString = htmlString.replace("$body", body);
File newHtmlFile = new File("path/new.html");
FileUtils.writeStringToFile(newHtmlFile, htmlString);
Note: I used org.apache.commons.io.FileUtils for simplicity.
int main();
This is a simple declaration. It cannot take any command line arguments.
int main(int argc, char* argv[]);
This declaration is used when your program must take command-line arguments. When run like such:
myprogram arg1 arg2 arg3
argc
, or Argument Count, will be set to 4 (four arguments), and argv
, or Argument Vectors, will be populated with string pointers to "myprogram", "arg1", "arg2", and "arg3". The program invocation (myprogram
) is included in the arguments!
Alternatively, you could use:
int main(int argc, char** argv);
This is also valid.
There is another parameter you can add:
int main (int argc, char *argv[], char *envp[])
The envp
parameter also contains environment variables. Each entry follows this format:
VARIABLENAME=VariableValue
like this:
SHELL=/bin/bash
The environment variables list is null-terminated.
IMPORTANT: DO NOT use any argv
or envp
values directly in calls to system()
! This is a huge security hole as malicious users could set environment variables to command-line commands and (potentially) cause massive damage. In general, just don't use system()
. There is almost always a better solution implemented through C libraries.
The preferred way to get the length of any python object is to pass it as an argument to the len
function. Internally, python will then try to call the special __len__
method of the object that was passed.
// CMakeLists.txt : release
set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)
// CMakeLists.txt : debug
set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)
Here is another tidyverse approach using the modify_at()
function from the purrr
package.
library(purrr)
# Data frame with only integer columns
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
# Modify specified columns to a factor class
data_with_factors <- data %>%
purrr::modify_at(c("A", "C", "E"), factor)
# Check the results:
str(data_with_factors)
# 'data.frame': 4 obs. of 10 variables:
# $ A: Factor w/ 4 levels "8","12","33",..: 1 3 4 2
# $ B: int 25 32 2 19
# $ C: Factor w/ 4 levels "5","15","35",..: 1 3 4 2
# $ D: int 11 7 27 6
# $ E: Factor w/ 4 levels "1","4","16","20": 2 3 1 4
# $ F: int 21 23 39 18
# $ G: int 31 14 38 26
# $ H: int 17 24 34 10
# $ I: int 13 28 30 29
# $ J: int 3 22 37 9
Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)
Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.
$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
// and since all the following operations need a valid/ready statement object
// it doesn't make sense to go on
// you might want to use a more sophisticated mechanism than die()
// but's it's only an example
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
// again execute() is useless if you can't bind the parameters. Bail out somehow.
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
There is a certain amount of confusion in the answers to this this question.
The top answer is currently a server-side solution which sets a flag in the http header and some comments are indicating that a solution using a meta tag just doesn't work.
I think this blog entry gives a nice overview of how to use compatibility meta information and in my experience works as described: http://blogs.msdn.com/b/cjacks/archive/2012/02/29/using-x-ua-compatible-to-create-durable-enterprise-web-applications.aspx
The main points:
One important point (and I think lots of confusion comes from this point) is that IE has two "classes" of modes:
The document mode determines the rendering engine (how is the web page rendered).
The Browser Mode determines what User-Agent (UA) string IE sends to servers, what Document Mode IE defaults to, and how IE evaluates Conditional Comments.
More on the information on document mode vs. browser mode can be found in this article: http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx?Redirected=true
In my experience the compatibility meta data will only influence the document mode. So if you are relying on browser detection this won't help you. But if you are using feature detection this should be the way to go.
So I would recommend using the meta tag (in the html page) using this syntax:
<meta http-equiv="X-UA-Compatible" content="IE=9,10" ></meta>
Notice: give a list of browser modes you have tested for.
The blog post also advices against the use of EmulateIEX. Here a quote:
That being said, one thing I do find strange is when an application requests EmulateIE7, or EmulateIE8. These emulate modes are themselves decisions. So, instead of being specific about what you want, you’re asking for one of two things and then determining which of those two things by looking elsewhere in the code for a DOCTYPE (and then attempting to understand whether that DOCTYPE will give you standards or quirks depending on its contents – another sometimes confusing task). Rather than do that, I think it makes significantly more sense to directly specify what you want, rather than giving a response that is itself a question. If you want IE7 standards, then use IE=7, rather than IE=EmulateIE7. (Note that this doesn’t mean you shouldn’t use a DOCTYPE – you should.)
I needed to capture both stdout and stderr and have it timeout if the process didn't exit when expected. I came up with this:
Process process = new Process();
StringBuilder outputStringBuilder = new StringBuilder();
try
{
process.StartInfo.FileName = exeFileName;
process.StartInfo.WorkingDirectory = args.ExeDirectory;
process.StartInfo.Arguments = args;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.EnableRaisingEvents = false;
process.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.ErrorDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
var processExited = process.WaitForExit(PROCESS_TIMEOUT);
if (processExited == false) // we timed out...
{
process.Kill();
throw new Exception("ERROR: Process took too long to finish");
}
else if (process.ExitCode != 0)
{
var output = outputStringBuilder.ToString();
var prefixMessage = "";
throw new Exception("Process exited with non-zero exit code of: " + process.ExitCode + Environment.NewLine +
"Output from process: " + outputStringBuilder.ToString());
}
}
finally
{
process.Close();
}
I am piping the stdout and stderr into the same string, but you could keep it separate if needed. It uses events, so it should handle them as they come (I believe). I have run this successfully, and will be volume testing it soon.
I would just like to add another useful advantage of using %timeit to answer by mu ? that:
PS: I know this should be a comment to answer above but I currently don't have enough reputation for that, hope what I write will be helpful to someone and help me earn enough reputation to comment next time.
def exec = { encoding, execPath, execStr, execCommands ->
def outputCatcher = new ByteArrayOutputStream()
def errorCatcher = new ByteArrayOutputStream()
def proc = execStr.execute(null, new File(execPath))
def inputCatcher = proc.outputStream
execCommands.each { cm ->
inputCatcher.write(cm.getBytes(encoding))
inputCatcher.flush()
}
proc.consumeProcessOutput(outputCatcher, errorCatcher)
proc.waitFor()
return [new String(outputCatcher.toByteArray(), encoding), new String(errorCatcher.toByteArray(), encoding)]
}
def out = exec("cp866", "C:\\Test", "cmd", ["cd..\n", "dir\n", "exit\n"])
println "OUT:\n" + out[0]
println "ERR:\n" + out[1]
Read this:
http://www.quora.com/OAuth-2-0/How-does-OAuth-2-0-work
or an even simpler but quick explanation:
http://agileanswer.blogspot.se/2012/08/oauth-20-for-my-ninth-grader.html
The redirect URI is the callback entry point of the app. Think about how OAuth for Facebook works - after end user accepts permissions, "something" has to be called by Facebook to get back to the app, and that "something" is the redirect URI. Furthermore, the redirect URI should be different than the initial entry point of the app.
The other key point to this puzzle is that you could launch your app from a URL given to a webview. To do this, i simply followed the guide on here:
http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
and
http://inchoo.net/mobile-development/iphone-development/launching-application-via-url-scheme/
note: on those last 2 links, "http://" works in opening mobile safari but "tel://" doesn't work in simulator
in the first app, I call
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"secondApp://"]];
In my second app, I register "secondApp" (and NOT "secondApp://") as the name of URL Scheme, with my company as the URL identifier.
update:
I found the terms of use from Google Map:
Section 10.5
No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you may store limited amounts of Content solely for the purpose of improving the performance of your Maps API Implementation due to network latency (and not for the purpose of preventing Google from accurately tracking usage), and only if such storage: is temporary (and in no event more than 30 calendar days); is secure; does not manipulate or aggregate any part of the Content or Service; and does not modify attribution in any way.
It means we can cache for limited time actually
After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:
General -> Editors -> Text Editors -> Annotations
Look for Occurences
from the Annotation types list.
Then, be sure that Text as highlighted
is selected, then choose the desired color.
And, a picture is worth a thousand words...
(source: coobird.net)
(source: coobird.net)
You can define foreign key constraints on the tables with ON DELETE CASCADE
option.
Then deleting the record from parent table removes the records from child tables.
Check this link : http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
link=document.createElement('link');
link.href='href';
link.rel='rel';
document.getElementsByTagName('head')[0].appendChild(link);
There are many ways to convert an int to ASCII (depending on your needs) but here is a way to convert each integer byte to an ASCII character:
private static String toASCII(int value) {
int length = 4;
StringBuilder builder = new StringBuilder(length);
for (int i = length - 1; i >= 0; i--) {
builder.append((char) ((value >> (8 * i)) & 0xFF));
}
return builder.toString();
}
For example, the ASCII text for "TEST" can be represented as the byte array:
byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };
Then you could do the following:
int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"
...so this essentially converts the 4 bytes in a 32-bit integer to 4 separate ASCII characters (one character per byte).
If you do grouping by virtue of including GROUP BY
clause, any expression in SELECT
, which is not group function (or aggregate function or aggregated column) such as COUNT
, AVG
, MIN
, MAX
, SUM
and so on (List of Aggregate functions) should be present in GROUP BY
clause.
Example (correct way) (here employee_id
is not group function (non-aggregated column), so it must appear in GROUP BY
. By contrast, sum(salary) is a group function (aggregated column), so it is not required to appear in the GROUP BY
clause.
SELECT employee_id, sum(salary)
FROM employees
GROUP BY employee_id;
Example (wrong way) (here employee_id
is not group function and it does not appear in GROUP BY
clause, which will lead to the ORA-00979 Error .
SELECT employee_id, sum(salary)
FROM employees;
To correct you need to do one of the following :
SELECT
clause in the
GROUP BY
clauseSELECT
clause.A workspace is a collection of projects. It's useful to organize your projects when there's correlation between them (e.g.: Project A includes a library, that is provided as a project itself as project B. When you build the workspace project B is compiled and linked in project A).
It's common to use a workspace in the popular CocoaPods. When you install your pods, they are placed inside a workspace, that holds your project and the pod libraries.
@Theo
The LINQ translator is smart enough to execute:
.Where(r => r.UserName !="XXXX" && r.UsernName !="YYYY")
I've test this in LinqPad ==> YES, Linq translator is smart enough :))
This checks if the array is empty
if (!empty($result) {
// do stuf if array is not empty
} else {
// do stuf if array is empty
}
This checks if the array is null or not
if (is_null($result) {
// do stuf if array is null
} else {
// do stuf if array is not null
}
Note that the ansible
command doesn't collect facts, but the ansible-playbook
command does. When running ansible -m setup
, the setup module happens to run the fact collection so you get the facts, but running ansible -m command
does not. Therefore the facts aren't available. This is why the other answers include playbook YAML files and indicate the lookup works.
You want the --stat
option of git diff
, or if you're looking to parse this in a script, the --numstat
option.
git diff --stat <commit-ish> <commit-ish>
--stat
produces the human-readable output you're used to seeing after merges; --numstat
produces a nice table layout that scripts can easily interpret.
I somehow missed that you were looking to do this on multiple commits at the same time - that's a task for git log
. Ron DeVera touches on this, but you can actually do a lot more than what he mentions. Since git log
internally calls the diff machinery in order to print requested information, you can give it any of the diff stat options - not just --shortstat
. What you likely want to use is:
git log --author="Your name" --stat <commit1>..<commit2>
but you can use --numstat
or --shortstat
as well. git log
can also select commits in a variety other ways - have a look at the documentation. You might be interested in things like --since
(rather than specifying commit ranges, just select commits since last week) and --no-merges
(merge commits don't actually introduce changes), as well as the pretty output options (--pretty=oneline, short, medium, full...
).
Here's a one-liner to get total changes instead of per-commit changes from git log (change the commit selection options as desired - this is commits by you, from commit1 to commit2):
git log --numstat --pretty="%H" --author="Your Name" commit1..commit2 | awk 'NF==3 {plus+=$1; minus+=$2} END {printf("+%d, -%d\n", plus, minus)}'
(you have to let git log print some identifying information about the commit; I arbitrarily chose the hash, then used awk to only pick out the lines with three fields, which are the ones with the stat information)
You can use the str.split
method: string.split('__')
>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']
I always wanted to do this and found a nice and easy way of doing it. I wrote down the complete procedure just in case anyone else needs it.
First install a 16 kB program called xclip
:
sudo apt-get install xclip
You can then pipe the output into xclip
to be copied into the clipboard:
cat file | xclip
To paste the text you just copied, you shall use:
xclip -o
To simplify life, you can set up an alias in your .bashrc file as I did:
alias "c=xclip"
alias "v=xclip -o"
To see how useful this is, imagine I want to open my current path in a new terminal window (there may be other ways of doing it like Ctrl+T on some systems, but this is just for illustration purposes):
Terminal 1:
pwd | c
Terminal 2:
cd `v`
Notice the ` `
around v
. This executes v
as a command first and then substitutes it in-place for cd
to use.
Only copy the content to the X
clipboard
cat file | xclip
If you want to paste somewhere else other than a X
application, try this one:
cat file | xclip -selection clipboard
When you define any variable then you do not have to put in any extra spaces.
E.g.
name = "Stack Overflow"
// it is not valid, you will get an error saying- "Command not found"
So remove spaces:
name="Stack Overflow"
and it will work fine.
In the thread dump you can find the Line Number as below.
for the main thread which is currently running...
"main" #1 prio=5 os_prio=0 tid=0x0000000002120800 nid=0x13f4 runnable [0x0000000001d9f000]
java.lang.Thread.State: **RUNNABLE**
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:313)
at com.rana.samples.**HighCPUUtilization.main(HighCPUUtilization.java:17)**
IMO, implementation #1 is typical and being short and idiomatic for Perl trumps the others for that alone. A benchmark of the three choices might offer you insight into speed, at least.
Prior to C++11, you cannot initialise an array using type[]. However the latest c++11 provides(unifies) the initialisation, so you can do it in this way:
string* pStr = new string[3] { "hi", "there"};
See http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init
You ask two questions; your title says "Displaying a vector of strings", but you're not actually doing that, you actually build a single string composed of all the strings and output that.
Your question body asks "Why doesn't this work".
It doesn't work because your for loop is constrained by "userString.size()" which is 0, and you test your loop variable for being "userString.size() - 1". The condition of a for() loop is tested before permitting execution of the first iteration.
int n = 1;
for (int i = 1; i < n; ++i) {
std::cout << i << endl;
}
will print exactly nothing.
So your loop executes exactly no iterations, leaving userString and sentence empty.
Lastly, your code has absolutely zero reason to use a vector. The fact that you used "decltype(userString.size())" instead of "size_t" or "auto", while claiming to be a rookie, suggests you're either reading a book from back to front or you are setting yourself up to fail a class.
So to answer your question at the end of your post: It doesn't work because you didn't step through it with a debugger and inspect the values as it went. While I say it tongue-in-cheek, I'm going to leave it out there.
<style type="text/css">
#wrap {
width:600px;
margin:0 auto;
}
#left_col {
float:left;
width:300px;
}
#right_col {
float:right;
width:300px;
}
</style>
<div id="wrap">
<div id="left_col">
...
</div>
<div id="right_col">
...
</div>
</div>
Make sure that the sum of the colum-widths equals the wrap width. Alternatively you can use percentage values for the width as well.
For more info on basic layout techniques using CSS have a look at this tutorial
You could also create a new DevicePolicyManager and then use removeAdmin(adminReceiver) from an onClickListener of a button in your app
//set the onClickListener here
{
ComponentName devAdminReceiver = new ComponentName(context, deviceAdminReceiver.class);
DevicePolicyManager dpm = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
dpm.removeActiveAdmin(devAdminReceiver);
}
And then you can uninstall
Have you tried something like this?
sqlplus username/password@database < "EXECUTE some_proc /"
Seems like in UNIX you can do:
sqlplus username/password@database <<EOF
EXECUTE some_proc;
EXIT;
EOF
But I'm not sure what the windows equivalent of that would be.
Using Jad to decompile it is probably your best option. Unless the code has been obfuscated, it will produce an okay result.
That will be possible only if the HTML file is also loaded with the file
protocol from the local user's harddisk.
If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src
attribute with the file://
protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.
As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.
In your authentication service, set the currently authenticated user on the root scope.
// AuthService.js
// auth successful
$rootScope.user = user
// AdminController.js
.config(function ($routeProvider) {
$routeProvider.when('/admin', {
controller: 'AdminController',
auth: function (user) {
return user && user.isAdmin
}
})
})
// index.js
.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeStart', function (ev, next, curr) {
if (next.$$route) {
var user = $rootScope.user
var auth = next.$$route.auth
if (auth && !auth(user)) { $location.path('/') }
}
})
})
Alternatively you can set permissions on the user object and assign each route a permission, then check the permission in the event callback.
open the console as a administrator. Right Click on the command prompt or bash -> more and select "run as administrator"
If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.
val uri = myUriString.toUri()
To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
Hi thanx a lot it solved my issue ,
By default vs 2008 will add
<!--<add verb="*" path="*.asmx" validate="false" type="Microsoft.Web.Script.Services.ScriptHandlerFactory, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add verb="GET" path="ScriptResource.axd" type="Microsoft.Web.Handlers.ScriptResourceHandler" validate="false" />-->
Need to correct Default config(Above) to below code FIX
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler" validate="false"/>
Try one of these regular expressions:
// for numbers that need to start with a zero
[RegularExpression("([0-9]+)")]
// for numbers that begin from 1
[RegularExpression("([1-9][0-9]*)")]
hope it helps :D
Check out the range
documentation, you have to define a negative step:
>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Try:
var firstElement = lstComp.First();
You can also use FirstOrDefault()
just in case lstComp
does not contain any items.
http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx
Edit:
To get the Component Value
:
var firstElement = lstComp.First().ComponentValue("Dep");
This would assume there is an element in lstComp
. An alternative and safer way would be...
var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null)
{
var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}
document.getElementById('child')
should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.
edit : see this page - ids MUST be unique.
edit edit : alternate way to solve the problem :
<div onclick="test('child1')">
Test
<div id="child1">child</div>
</div>
then you just need the test() function to look up the element by id that you passed in.
While it was discussed in the comments, there isn't an answer containing it yet, so it can be easy to miss. DATE_FORMAT works really well and is flexible to handle many different patterns.
DATE_FORMAT(date,'%Y%m')
To put it in a query:
SELECT DATE_FORMAT(test_date,'%Y%m') AS date FROM test_table;
An element can have any number of classNames, however, it can only have one class attribute; only the first one will be read by jQuery.
Using the code you posted, $(".alert-box.warn")
will work but $(".alert-box.dead")
will not.
If you want to stage and commit all your files on Github do the following;
git add -A
git commit -m "commit message"
git push origin master
I would say "Yes". As "Matz" had said something like this in one of his talks, "Ruby objects have no types." Not all of it but the part that he is trying to get across to us. Why would anyone have said "Everything is an Object" then? To add he said "Data has Types not objects".
So we might enjoy this.
https://www.youtube.com/watch?v=1l3U1X3z0CE
But Ruby doesn't care to much about the type of object just the class. We use classes not types. All data then has a class.
12345.class
'my string'.class
They may also have ancestors
Object.ancestors
They also have meta classes but I'll save you the details on that.
Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed. If you really want to get into details the look up...
"The Ruby Object Model"
This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.
Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.
text blocks numbers
According to Property Accessors defined in ECMA-262(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, P67), there are two ways you can do to add properties to a exists object. All these two way, the Javascript engine will treat them the same.
The first way is to use dot notation:
obj.key3 = value3;
But this way, you should use a IdentifierName after dot notation.
The second way is to use bracket notation:
obj["key3"] = value3;
and another form:
var key3 = "key3";
obj[key3] = value3;
This way, you could use a Expression (include IdentifierName) in the bracket notation.
<?php
$radius = 20;
$thichness = 4;
$size = 200;
if($s == 'circle'){
echo '<svg width="' . $size . '" height="' . $size . '">';
echo '<circle cx="' . ($size/2) . '" cy="' . ($size/2) . '" r="' . (($size/2)-$thichness) . '" stroke="black" stroke-width="' . $thichness . '" fill="none" />';
echo '</svg>';
}elseif($s == 'square'){
echo '<svg width="' . $size . '" height="' . $size . '">';
echo '<path d="M' . ($radius+$thichness) . ',' . ($thichness) . ' h' . ($size-($radius*2)-($thichness*2)) . ' a' . $radius . ',' . $radius . ' 0 0 1 ' . $radius . ',' . $radius . ' v' . ($size-($radius*2)-($thichness*2)) . ' a' . $radius . ',' . $radius . ' 0 0 1 -' . $radius . ',' . $radius . ' h-' . ($size-($radius*2)-($thichness*2)) . ' a' . $radius . ',' . $radius . ' 0 0 1 -' . $radius . ',-' . $radius . ' v-' . ($size-($radius*2)-($thichness*2)) . ' a' . $radius . ',' . $radius . ' 0 0 1 ' . $radius . ',-' . $radius . ' z" fill="none" stroke="black" stroke-width="' . $thichness . '" />';
echo '</svg>';
}
?>
I installed Oracle Express Edition and I have the same error. One of the possible reason that is maybe your user does not have permission to open this shortcut. Here is how I solved the problem.
1. Right-click the shortcut and select the properties
.
2. Now click the Open File Location
.
Now you will see there is a Get_Started
shortcut.
3. Now right-click the Get_Started
and select the properties
. Then select your user and give permission to your user in the security
tab.
Instant.now()
.toString()
2016-05-06T23:24:25.694Z
ZonedDateTime
.now
(
ZoneId.of( "America/Montreal" )
)
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
2016-05-06 19:24:25.694
In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.
If you want to eliminate any microseconds or nanoseconds from your data, truncate.
Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;
The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z
at the end is short for Zulu
, and means UTC.
An Instant
represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer’s hardware clock’s abilities.
Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();
2016-05-06T23:24:25.694Z
Replace the T
in the middle with a space, and the Z
with nothing, to get your desired output.
String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.
2016-05-06 23:24:25.694
As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.
String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );
The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.
The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.
System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );
When run…
Now: 2013-11-26T20:25:12.014Z
Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:
int millisOfSecond = myDateTime.getMillisOfSecond ();
Vue.js considers this an anti-pattern. For example, declaring and setting some props like
this.propsVal = 'new Props Value'
So to solve this issue you have to take in a value from the props to the data or the computed property of a Vue instance, like this:
props: ['propsVal'],
data: function() {
return {
propVal: this.propsVal
};
},
methods: {
...
}
This will definitely work.
Below code snippet will show how how you can show UI elemnts depends on IE version and browser
$(document).ready(function () {
var msiVersion = GetMSIieversion();
if ((msiVersion <= 8) && (msiVersion != false)) {
//Show UI elements specific to IE version 8 or low
} else {
//Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
}
}
);
Below code will give how we can get IE version
function GetMSIieversion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser like Chrome,Mozila..etc
return false;
}
Here's one way in XSLT 2
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"','''')"/> </xsl:template> </xsl:stylesheet>
Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:variable name="apos">'</xsl:variable> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"',$apos)"/> </xsl:template> </xsl:stylesheet>
I think this is a simple example, how to check if a radio in a group of radios was checked.
if($('input[name=html_elements]:checked').length){
//a radio button was checked
}else{
//there was no radio button checked
}
I tried with CSS, and or you need to use display: table or you need to use new css that is not yet supported on most browsers (2016).
So, I wrote a jquery plugin to do it for us, I am happy to share it:
_x000D_
//Credit Efy Teicher_x000D_
$(document).ready(function () {_x000D_
$(".fillHight").fillHeight();_x000D_
$(".fillWidth").fillWidth();_x000D_
});_x000D_
_x000D_
window.onresize = function (event) {_x000D_
$(".fillHight").fillHeight();_x000D_
$(".fillWidth").fillWidth();_x000D_
}_x000D_
_x000D_
$.fn.fillHeight = function () {_x000D_
var siblingsHeight = 0;_x000D_
this.siblings("div").each(function () {_x000D_
siblingsHeight = siblingsHeight + $(this).height();_x000D_
});_x000D_
_x000D_
var height = this.parent().height() - siblingsHeight;_x000D_
this.height(height);_x000D_
};_x000D_
_x000D_
_x000D_
$.fn.fillWidth = function (){_x000D_
var siblingsWidth = 0;_x000D_
this.siblings("div").each(function () {_x000D_
siblingsWidth += $(this).width();_x000D_
});_x000D_
_x000D_
var width =this.parent().width() - siblingsWidth;_x000D_
this.width(width);_x000D_
}
_x000D_
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
html {_x000D_
}_x000D_
_x000D_
html, body, .fillParent {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div class="fillParent" style="background-color:antiquewhite">_x000D_
<div>_x000D_
no1_x000D_
</div>_x000D_
<div class="fillHight">_x000D_
no2 fill_x000D_
</div>_x000D_
<div class="deb">_x000D_
no3_x000D_
</div>_x000D_
</div>
_x000D_
workmad3 is apparently out of date, at least for current gpg, as the --allow-secret-key-import
is now obsolete and does nothing.
What happened to me was that I failed to export properly. Just doing gpg --export
is not adequate, as it only exports the public keys. When exporting keys, you have to do
gpg --export-secret-keys >keyfile
I know this question is a few years old, but jqgrid now supports virtual scrolling:
http://www.trirand.com/blog/phpjqgrid/examples/paging/scrollbar/default.php
but with pagination disabled
Definitely late to the party; anyway, for those interested, picking up on Lan's mention of HTML5 canvas, you can use gRaphaël Charting which has a MIT License (instead of HighCharts dual license). It's not Bootstrap-specific either, so it's more of a general suggestion.
I have to admit that HighCharts demos seem very pretty, and I have to warn that gRaphaël is quite hard to understand before becoming proficient with it. Anyway you can easily add nice features to your gRaphaël charts (say, tooltips or zooming effects), so it may be worth the effort.
go to...
C:\wamp\alias
Inside alias folder you will see some files like phpmyadmin,phpsysinfo,etc...
open each file, and you can see inside file some commented instruction are give to access from outside ,like to give access to phpmyadmin from outside replace the lines
Require local
by
Require all granted
Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!
If you are only saving a single object (your data frame), you could also use saveRDS
.
To save:
saveRDS(foo, file="data.Rda")
Then read it with:
bar <- readRDS(file="data.Rda")
The difference between saveRDS
and save
is that in the former only one object can be saved and the name of the object is not forced to be the same after you load it.
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
os.remove()
does not work on a directory, and os.rmdir()
will only work on an empty directory. And Python won't automatically expand "/home/me/test/*" like some shells do.
You can use shutil.rmtree()
on the directory to do this, however.
import shutil
shutil.rmtree('/home/me/test')
be careful as it removes the files and the sub-directories as well.
Instead of Promise.all
in conjunction with Array.prototype.map
(which does not guarantee the order in which the Promise
s are resolved), I use Array.prototype.reduce
, starting with a resolved Promise
:
async function printFiles () {
const files = await getFilePaths();
await files.reduce(async (promise, file) => {
// This line will wait for the last async function to finish.
// The first iteration uses an already resolved Promise
// so, it will immediately continue.
await promise;
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}, Promise.resolve());
}
When you need cookies from session to session, there is another way to do it. Use the Chrome options user-data-dir in order to use folders as profiles. I run:
# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")
Here you can do the logins that check for human interaction. I do this and then the cookies I need now every time I start the Webdriver with that folder everything is in there. You can also manually install the Extensions and have them in every session.
The second time I run, all the cookies are there:
# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") # Now you can see the cookies, the settings, extensions, etc., and the logins done in the previous session are present here.
The advantage is you can use multiple folders with different settings and cookies, Extensions without the need to load, unload cookies, install and uninstall Extensions, change settings, change logins via code, and thus no way to have the logic of the program break, etc.
Also, this is faster than having to do it all by code.
Also in the many IDEs now, ex: VSC, you can install an extension for AWS and simply click upload from there, no effort of typing all those commands + region.
Here's an example:
Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.
-5 / 2 = -2
5 / 2 = 2
For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).
SchemaCrawler for PostgreSQL can generate database diagrams from the command line, with the help of GraphViz. You can use regular expressions to include and exclude tables and columns. It can also infer relationships between tables using common naming conventions, if not foreign keys are defined.
I created a generic solution out of the existing answers which can be reused for any table:
CREATE OR REPLACE FUNCTION create_if_not_exists (table_name text, create_stmt text)
RETURNS text AS
$_$
BEGIN
IF EXISTS (
SELECT *
FROM pg_catalog.pg_tables
WHERE tablename = table_name
) THEN
RETURN 'TABLE ' || '''' || table_name || '''' || ' ALREADY EXISTS';
ELSE
EXECUTE create_stmt;
RETURN 'CREATED';
END IF;
END;
$_$ LANGUAGE plpgsql;
Usage:
select create_if_not_exists('my_table', 'CREATE TABLE my_table (id integer NOT NULL);');
It could be simplified further to take just one parameter if one would extract the table name out of the query parameter. Also I left out the schemas.