It is also a good idea to instruct the client browser to clear session id cookie value.
Session.Clear();
Session.Abandon();
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-10);
For namespace and Library
@using NameSpace_Name
For Model
@model Application_Name.Models.Model_Name
For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)
@model List<Application_Name.Models.Model_Name>
@foreach (var item in Model)
{
<tr>
<td>@item.srno</td>
<td>@item.name</td>
</tr>
}
As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf()
.
Placeholders:
%s
String.%d
,%i
Integer number.%f
Floating point number.%o
Object hyperlink.e.g.
console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);
BTW, to see the output:
Ctrl + Shift + J
or F12
to open developer tool.Ctrl + Shift + K
or F12
to open developer tool.@Update - nodejs support
Seems nodejs don't support %f
, instead, could use %d
in nodejs.
With %d
number will be printed as floating number, not just integer.
This is Web GUI of a GitHub repository:
Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:
Yowza, that’s a lot of files. Try again with fewer than 100 files.
and add commit message
And press button Commit changes is the last step.
Public Class Form1
Private boxes(5) As TextBox
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim newbox As TextBox
For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
newbox.Name = "TextBox" & i
newbox.Text = newbox.Name 'Connect it to a handler, save a reference to the array & add it to the form control.
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
boxes(i) = newbox
Me.Controls.Add(newbox)
Next
End Sub
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
'When you modify the contents of any textbox, the name of that textbox
'and its current contents will be displayed in the title bar
Dim box As TextBox = DirectCast(sender, TextBox)
Me.Text = box.Name & ": " & box.Text
End Sub
End Class
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
Just a small detail that I think is missing in above answers.
If your child activity can be opened from multiple parent activities then you can check if you need to do setResult
or not, based on if your activity was opened by startActivity
or startActivityForResult
. You can achieve this by using getCallingActivity()
. More info here.
It depends on where you are looking for the information from.
If you are looking for the information from the console you can use the jps command. The command gives output similar to the Unix ps command and comes with the JDK since I believe 1.5
If you are looking from the process the RuntimeMXBean (as said by Wouter Coekaerts) is probably your best choice. The output from getName() on Windows using Sun JDK 1.6 u7 is in the form [PROCESS_ID]@[MACHINE_NAME]. You could however try to execute jps and parse the result from that:
String jps = [JDK HOME] + "\\bin\\jps.exe";
Process p = Runtime.getRuntime().exec(jps);
If run with no options the output should be the process id followed by the name.
If non of the above works try editing /etc/apache2/sites-enabled/000-default
almost at the top you will find
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Change the AllowOverride None
to AllowOverride All
this worked for me
Instead of saving it to a file, save it to php://output
Docs:
$objWriter->save('php://output');
This will send it AS-IS to the browser.
You want to add some headersDocs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');
// Write file to the browser
$objWriter->save('php://output');
First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.
You could use THROW
(available in SQL Server 2012+):
THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>
The following formula determines if the text "CHECK" appears in cell C10. If it does not, the result is blank. If it does, the result is the work "CHECK".
=IF(ISERROR(FIND("CHECK",C10,1)),"","CHECK")
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
Try this code:
Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A3:D" & lastrow).Sort key1:=Range("B3:B" & lastrow), _
order1:=xlAscending, Header:=xlNo
The Bootstrap datepicker is able to set date-range. But it is not available in the initial release/Master Branch. Check the branch as 'range' there (or just see at https://github.com/eternicode/bootstrap-datepicker), you can do it simply with startDate and endDate.
Example:
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
If you are reading this and you are using Spring Boot, you have 1 more option for this feature
Usually comma separated list are very clumsy for real world use case (And sometime not even feasible, if you want to use commas in your config):
[email protected],[email protected],[email protected],.....
With Spring Boot, you can write it like these (Index start at 0):
email.sendTo[0][email protected]
email.sendTo[1][email protected]
email.sendTo[2][email protected]
And use it like these:
@Component
@ConfigurationProperties("email")
public class EmailProperties {
private List<String> sendTo;
public List<String> getSendTo() {
return sendTo;
}
public void setSendTo(List<String> sendTo) {
this.sendTo = sendTo;
}
}
@Component
public class EmailModel {
@Autowired
private EmailProperties emailProperties;
//Use the sendTo List by
//emailProperties.getSendTo()
}
@Configuration
public class YourConfiguration {
@Bean
public EmailProperties emailProperties(){
return new EmailProperties();
}
}
#Put this in src/main/resource/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=example.compackage.YourConfiguration
LIMIT 1
is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order
clause in an outer query).
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
There is a way to do it using reflection. It works with .NET 4.0. It accesses a private field and may not work in other versions of .NET without modifications.
I have no idea why Microsoft did not expose this field with a property.
private static int GetStatusCode(WebClient client, out string statusDescription)
{
FieldInfo responseField = client.GetType().GetField("m_WebResponse", BindingFlags.Instance | BindingFlags.NonPublic);
if (responseField != null)
{
HttpWebResponse response = responseField.GetValue(client) as HttpWebResponse;
if (response != null)
{
statusDescription = response.StatusDescription;
return (int)response.StatusCode;
}
}
statusDescription = null;
return 0;
}
var group = new L.featureGroup([marker1, marker2, marker3]);
map.fitBounds(group.getBounds());
See the documentation for more info.
Above answers are correct and they give great and short answer.
I was also looking for getting the current page's url in Django template as my intention was to activate HOME page
, MEMBERS page
, CONTACT page
, ALL POSTS page
when they are requested.
I am pasting the part of the HTML code snippet that you can see below to understand the use of request.path
. You can see it in my live website
at http://pmtboyshostelraipur.pythonanywhere.com/
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<!--HOME-->
{% if "/" == request.path %}
<li class="active text-center">
<a href="/" data-toggle="tooltip" title="Home" data-placement="bottom">
<i class="fa fa-home" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true">
</i>
</a>
</li>
{% else %}
<li class="text-center">
<a href="/" data-toggle="tooltip" title="Home" data-placement="bottom">
<i class="fa fa-home" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true">
</i>
</a>
</li>
{% endif %}
<!--MEMBERS-->
{% if "/members/" == request.path %}
<li class="active text-center">
<a href="/members/" data-toggle="tooltip" title="Members" data-placement="bottom">
<i class="fa fa-users" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
</a>
</li>
{% else %}
<li class="text-center">
<a href="/members/" data-toggle="tooltip" title="Members" data-placement="bottom">
<i class="fa fa-users" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
</a>
</li>
{% endif %}
<!--CONTACT-->
{% if "/contact/" == request.path %}
<li class="active text-center">
<a class="nav-link" href="/contact/" data-toggle="tooltip" title="Contact" data-placement="bottom">
<i class="fa fa-volume-control-phone" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
</a>
</li>
{% else %}
<li class="text-center">
<a class="nav-link" href="/contact/" data-toggle="tooltip" title="Contact" data-placement="bottom">
<i class="fa fa-volume-control-phone" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
</a>
</li>
{% endif %}
<!--ALL POSTS-->
{% if "/posts/" == request.path %}
<li class="text-center">
<a class="nav-link" href="/posts/" data-toggle="tooltip" title="All posts" data-placement="bottom">
<i class="fa fa-folder-open" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
</a>
</li>
{% else %}
<li class="text-center">
<a class="nav-link" href="/posts/" data-toggle="tooltip" title="All posts" data-placement="bottom">
<i class="fa fa-folder-open" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
</a>
</li>
{% endif %}
</ul>
The ab (apache bench) tool allows you to send many requests to a single page and you specify how many clients you want to be used and how many concurrent connection you want.
This may be the first step when developing a site. Just test some pages with a specific load. This way of benchmarking may have some problem, like caching being over used.
Later you may want a tool that simulate some concrete traffic and not for a single page. I don't have a refence handy on such tool yet.
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
If anybody falls here from google, this is how to check if string contains at least one digit in C#:
With Regex
if (Regex.IsMatch(myString, @"\d"))
{
// do something
}
Info: necessary to add using System.Text.RegularExpressions
With linq:
if (myString.Any(c => Char.IsDigit(c)))
{
// do something
}
Info: necessary to add using System.Linq
Use:
git diff 15dc8^!
as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):
Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.
This means that you can use 15dc8^!
as a shorthand for 15dc8^..15dc8
anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8
is understood as git diff 15dc8^ 15dc8
, which means the difference between parent of commit (15dc8^
) and commit (15dc8
).
Note: the description in git-rev-parse(1)
manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^!
is "r1 --not r1^@
" i.e. "r1 ^r1^1 ^r1^2 ...
"
Also, you can use git show COMMIT
to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT
This one is useful as well when you want to implement a functional interface
Runnable r = ()-> System.out.print("Run method");
is equivalent to
Runnable r = new Runnable() {
@Override
public void run() {
System.out.print("Run method");
}
};
Do this in your .profile -
export JAVA_HOME=`/usr/libexec/java_home`
(backticks make sure to execute the command and place its value in JAVA_HOME)
I found this one more helpful and simple
DECLARE @StartTime datetime,@EndTime datetime
SELECT @StartTime=GETDATE()
--Your Query to be run goes here--
SELECT @EndTime=GETDATE()
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]
Not beautiful, but a solution nonetheless:
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();
String stackTrace = writer.toString();
I am not sure if this will work for you (I still use OS 10.8
), but these work for my terminal:
home = move cursor to the start of the line
shift+end = move cursor to the end of the line
alt+leftArrow = move one "word" to the left
alt+rightArrow = move one "word" to the right
Hope this helps!
WITH CTE_DocTotal (DocTotal, InvoiceNumber)
AS
(
SELECT InvoiceNumber,
SUM(Sale + VAT) AS DocTotal
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
)
UPDATE PEDI_InvoiceDetail
SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal
FROM CTE_DocTotal
INNER JOIN PEDI_InvoiceDetail ON ...
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
This works like charm!
So I edited the code as per my requirement. And here are the changes: It will save the id number from the response into the environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++)
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}
I got this completely worthless and uninformative error when I tried to:
ALTER TABLE `comments` ADD CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
My problem was in my comments table, user_id was defined as:
`user_id` int(10) unsigned NOT NULL
So... in my case, the problem was with the conflict between NOT NULL, and ON DELETE SET NULL.
I started using mocks through JMock, but eventually transitioned to use EasyMock. EasyMock was just that, --easier-- and provided a syntax that felt more natural. I haven't switched since.
I know it is very late but following approach can also be used:
<select id="type" name="type" >
<option value="Permanent" id="permanent">I am here to stay.</option>
<option value="toremove" id="toremove">Remove me!</option>
<option value="Other" id="other">Other</option>
</select>
and if I have to remove second option (id=toremove), the script would look like
$('#toremove').hide();
myInt.ToString("D4");
Your disabled attribute requires a boolean value:
<input :disabled="validated" />
Notice how i've only checked if validated
- This should work as 0 is falsey
...e.g
0 is considered to be false in JS (like undefined or null)
1 is in fact considered to be true
To be extra careful try:
<input :disabled="!!validated" />
This double negation turns the falsey
or truthy
value of 0
or 1
to false
or true
don't believe me? go into your console and type !!0
or !!1
:-)
Also, to make sure your number 1
or 0
are definitely coming through as a Number and not the String '1'
or '0'
pre-pend the value you are checking with a +
e.g <input :disabled="!!+validated"/>
this turns a string of a number into a Number e.g
+1 = 1
+'1' = 1
Like David Morrow said above you could put your conditional logic into a method - this gives you more readable code - just return out of the method the condition you wish to check.
The already existing answers seem to only concern oneself with the *.java files themselves and not how to easily do it with library files that might be needed for the build.
A nice one-line situation which recursively gets all *.java files as well as includes *.jar files necessary for building is:
javac -cp ".:lib/*" -d bin $(find ./src/* | grep .java)
Here the bin file is the destination of class files, lib (and potentially the current working directory) contain the library files and all the java files in the src directory and beneath are compiled.
The development of Unicode was aimed at creating a new standard for mapping the characters in a great majority of languages that are being used today, along with other characters that are not that essential but might be necessary for creating the text. UTF-8 is only one of the many ways that you can encode the files because there are many ways you can encode the characters inside a file into Unicode.
Source:
http://www.differencebetween.net/technology/difference-between-unicode-and-utf-8/
Set your working directory one level/folder higher. For example, if it is already set as:
setwd("C:/Users/Z/Desktop/Files/RStudio/Coursera/specdata")
go up one level back and set it as:
setwd("C:/Users/Z/Desktop/Files/RStudio/Coursera")
In other words, do not make "specdata" folder as your working directory.
CNAME'ing a root record is technically not against RFC, but does have limitations meaning it is a practice that is not recommended.
Normally your root record will have multiple entries. Say, 3 for your name servers and then one for an IP address.
Per RFC:
If a CNAME RR is present at a node, no other data should be present;
And Per IETF 'Common DNS Operational and Configuration Errors' Document:
This is often attempted by inexperienced administrators as an obvious way to allow your domain name to also be a host. However, DNS servers like BIND will see the CNAME and refuse to add any other resources for that name. Since no other records are allowed to coexist with a CNAME, the NS entries are ignored. Therefore all the hosts in the podunk.xx domain are ignored as well!
References:
I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.
Working JSFiddle below.
When using position absolute, margin: 0 auto
will not work, but you can do like this (will also scale):
left: 50%;
transform: translateX(-50%);
Update: Working JSFiddle
getClass().getProtectionDomain().getCodeSource().getLocation();
You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.
Try using something like
Creates or overwrites a file in the specified path.
Had the same error with PHP 7 on XAMPP and OSX.
The above mentioned answer in https://stackoverflow.com/ is good, but it did not completely solve the problem for me. I had to provide the complete certificate chain to make file_get_contents() work again. That's how I did it:
Get root / intermediate certificate
First of all I had to figure out what's the root and the intermediate certificate.
The most convenient way is maybe an online cert-tool like the ssl-shopper
There I found three certificates, one server-certificate and two chain-certificates (one is the root, the other one apparantly the intermediate).
All I need to do is just search the internet for both of them. In my case, this is the root:
thawte DV SSL SHA256 CA
And it leads to his url thawte.com. So I just put this cert into a textfile and did the same for the intermediate. Done.
Get the host certificate
Next thing I had to to is to download my server cert. On Linux or OS X it can be done with openssl:
openssl s_client -showcerts -connect whatsyoururl.de:443 </dev/null 2>/dev/null|openssl x509 -outform PEM > /tmp/whatsyoururl.de.cert
Now bring them all together
Now just merge all of them into one file. (Maybe it's good to just put them into one folder, I just merged them into one file). You can do it like this:
cat /tmp/thawteRoot.crt > /tmp/chain.crt
cat /tmp/thawteIntermediate.crt >> /tmp/chain.crt
cat /tmp/tmp/whatsyoururl.de.cert >> /tmp/chain.crt
tell PHP where to find the chain
There is this handy function openssl_get_cert_locations() that'll tell you, where PHP is looking for cert files. And there is this parameter, that will tell file_get_contents() where to look for cert files. Maybe both ways will work. I preferred the parameter way. (Compared to the solution mentioned above).
So this is now my PHP-Code
$arrContextOptions=array(
"ssl"=>array(
"cafile" => "/Applications/XAMPP/xamppfiles/share/openssl/certs/chain.pem",
"verify_peer"=> true,
"verify_peer_name"=> true,
),
);
$response = file_get_contents($myHttpsURL, 0, stream_context_create($arrContextOptions));
That's all. file_get_contents() is working again. Without CURL and hopefully without security flaws.
From my limited experience, this happens for two main reasons:
The simple solution here is to use an error handler ending with Resume Next
If your lookup_value
is a variable you can enclose it with TRIM()
cellNum = wsFunc.VLookup(TRIM(currName), rngLook, 13, False)
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Use Calender Api
For windows user, type netstat -an
in command prompt to see ports that are listening, this may come handy.
Here you are. An answer that shows yet another way to solve the problem:
// For the sake of simplicity, here is a complete function:
function truncate(numToBeTruncated, numOfDecimals) {
var theNumber = numToBeTruncated.toString();
var pointIndex = theNumber.indexOf('.');
return +(theNumber.slice(0, pointIndex > -1 ? ++numOfDecimals + pointIndex : undefined));
}
Note the use of + before the final expression. That is to convert our truncated, sliced string back to number type.
Hope it helps!
Click on email which you want to forward
Edit - > Copy As -> Document Link
create new mail and paste.
it will work
The best practice and Best OneLiner:
df.to_csv(newformat,header=1)
Notice the header value:
Header refer to the Row number(s) to use as the column names. Make no mistake, the row number is not the df but from the excel file(0 is the first row, 1 is the second and so on).
This way, you will get the column name you want and won't have to write additional codes or create new df.
Good thing is, it drops the replaced row.
And in clean javascript:
var texts = [], lis = document.getElementsByTagName("li");
for(var i=0, im=lis.length; im>i; i++)
texts.push(lis[i].firstChild.nodeValue);
alert(texts);
class Program
{
static void Main(string[] args)
{
string s, revs = "";
Console.WriteLine(" Enter string");
s = Console.ReadLine();
for (int i = s.Length - 1; i >= 0; i--) //String Reverse
{
Console.WriteLine(i);
revs += s[i].ToString();
}
if (revs == s) // Checking whether string is palindrome or not
{
Console.WriteLine("String is Palindrome");
}
else
{
Console.WriteLine("String is not Palindrome");
}
Console.ReadKey();
}
}
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="@+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/Weight"
/>
In your java file, getActivity
is used in fragment; if you write that code in activity, then remove getActivity
.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
There are some options to do that.
One would be:
document.write(produceMessage())
Other would be appending some element in your document this way:
var span = document.createElement("span");
span.appendChild(document.createTextNode(produceMessage()));
document.body.appendChild(span);
Or just:
document.body.appendChild(document.createTextNode(produceMessage()));
If you're using jQuery, you can do this:
$(document.body).append(produceMessage());
I used this tutorial to install R on my mac, and it had me install xquartz
and a fortran complier (gfortran
) as well.
My suggestion would be to brew untap homebrew/science
and then brew tap homebrew/science
and try again, also, make sure you don't have any errors when you run brew doctor
Hope this helps
I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.
Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.
Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.
Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.
In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO TableName ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
Another way
INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
Here's what I'm currently using. Some of the other techniques I've tried have been non-optimal because they changed the bit depth of the pixels (24-bit vs. 32-bit) or ignored the image's resolution (dpi).
// ImageConverter object used to convert byte arrays containing JPEG or PNG file images into
// Bitmap objects. This is static and only gets instantiated once.
private static readonly ImageConverter _imageConverter = new ImageConverter();
Image to byte array:
/// <summary>
/// Method to "convert" an Image object into a byte array, formatted in PNG file format, which
/// provides lossless compression. This can be used together with the GetImageFromByteArray()
/// method to provide a kind of serialization / deserialization.
/// </summary>
/// <param name="theImage">Image object, must be convertable to PNG format</param>
/// <returns>byte array image of a PNG file containing the image</returns>
public static byte[] CopyImageToByteArray(Image theImage)
{
using (MemoryStream memoryStream = new MemoryStream())
{
theImage.Save(memoryStream, ImageFormat.Png);
return memoryStream.ToArray();
}
}
Byte array to Image:
/// <summary>
/// Method that uses the ImageConverter object in .Net Framework to convert a byte array,
/// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be
/// used as an Image object.
/// </summary>
/// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
/// <returns>Bitmap object if it works, else exception is thrown</returns>
public static Bitmap GetImageFromByteArray(byte[] byteArray)
{
Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);
if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
bm.VerticalResolution != (int)bm.VerticalResolution))
{
// Correct a strange glitch that has been observed in the test program when converting
// from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts"
// slightly away from the nominal integer value
bm.SetResolution((int)(bm.HorizontalResolution + 0.5f),
(int)(bm.VerticalResolution + 0.5f));
}
return bm;
}
Edit: To get the Image from a jpg or png file you should read the file into a byte array using File.ReadAllBytes():
Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
This avoids problems related to Bitmap wanting its source stream to be kept open, and some suggested workarounds to that problem that result in the source file being kept locked.
Modify your filter like this:
filter isNumeric {
[Helpers]::IsNumeric($_)
}
function
uses the $input
variable to contain pipeline information whereas the filter
uses the special variable $_
that contains the current pipeline object.
Edit:
For a powershell syntax way you can use just a filter (w/o add-type):
filter isNumeric() {
return $_ -is [byte] -or $_ -is [int16] -or $_ -is [int32] -or $_ -is [int64] `
-or $_ -is [sbyte] -or $_ -is [uint16] -or $_ -is [uint32] -or $_ -is [uint64] `
-or $_ -is [float] -or $_ -is [double] -or $_ -is [decimal]
}
Float elements will be rendered at the line they are normally in the layout. To fix this, you have two choices:
Move the header and the p after the login box:
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
Or enclose the left block in a pull-left div, and add a clearfix at the bottom
<div class='container'>
<div class='hero-unit'>
<div class="pull-left">
<h2>Welcome</h2>
<p>Please log in</p>
</div>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<div class="clearfix"></div>
</div>
</div>
Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
and Java 8 you could do
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);
Update: For pre 26 use Joda time
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);
In app/build.gradle file, add like this-
dependencies {
compile 'joda-time:joda-time:2.9.4'
}
If you just want to remove untracked files, do this:
git clean -df
add x
to that if you want to also include specifically ignored files. I use git clean -dfx
a lot throughout the day.
You can create custom git by just writing a script called git-whatever
and having it in your path.
I couldn't get mvn eclipse:clean etc to work with Kepler.
However I changed creating and extending variables to just using external jars in my eclipse classpath. This was reflected in no var's in my .classpath.
This corrected the problem. I was able to do a Maven update.
In case of not having the yaml file:
kubectl get pod PODNAME -n NAMESPACE -o yaml | kubectl replace --force -f -
Since version 4.2, they introduced a much more convenience method that simplifies connection release: HttpRequestBase.releaseConnection()
There's another explanation for why .env
doesn't exist, and it happens when you move all the Laravel files.
Take this workflow: in your project directory you do laravel new whatever
, Laravel is installed in whatever
, you do mv * ..
to move all the files to your project folder, and you remove whatever
. The problem is, mv
doesn't move hidden files by default, so the .env
files are left behind, and are removed!
I have expanded the method with font as a parameter:
public static void AppendText(this RichTextBox box, string text, Color color, Font font)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.SelectionFont = font;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
Here is a practical example of Anchor tag with different
I prefer to use git-bash.exe instead of sh.exe.
start "" "%ProgramFiles%\Git\git-bash.exe" -c "tail -f /c/Windows/win.ini"
You can stop closing the window when call /usr/bin/bash --login -i
in the end;
start "" "%ProgramFiles%\Git\git-bash.exe" -c "echo 1 && echo 2 && /usr/bin/bash --login -i"
Note: I'm not sure this is a good way :)
If it's a submodule you need to cd into it then use git add . && git commit -m 'Your message'
From there you can cd out and push to whichever branch you want.
Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables
After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory
should be set to your M2_HOME variable.
Took the following code from php manual for get_browser.
$browser = get_browser(null, true);
print_r($browser);
The $browser
array has platform
information included which gives you the specific Operating System in use.
Please make sure to see the "Notes" section in that page. This might be something (thismachine.info) is using if not something already pointed in other answers.
So, the issue was that I was trying to inappropriately use @lazy, which caused my Business variable to essentially be a constant, and thusly uneditable. Also, instead of loading the local json, I'm now loading only the data returned from the API.
import UIKit
class BusinessTableViewController: UITableViewController {
var data: NSMutableData = NSMutableData()
var Business: NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = UIImageView(image: UIImage(named: "growler"))
tableView.registerClass(BeerTableViewCell.self, forCellReuseIdentifier: "cell")
tableView.separatorStyle = .None
fetchKimono()
}
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return Business.count
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
if (Business.count > 0) {
let biz = Business[section] as NSDictionary
let beers = biz["results"] as NSArray
return beers.count
} else {
return 0;
}
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell = tableView!.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath!) as BeerTableViewCell
if let path = indexPath {
let biz = Business[path.section] as NSDictionary
let beers = biz["results"] as NSArray
let beer = beers[path.row] as NSDictionary
cell.titleLabel.text = beer["BeerName"] as String
} else {
cell.titleLabel.text = "Loading"
}
return cell
}
override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
let view = LocationHeaderView()
let biz = Business[section] as NSDictionary
if (Business.count > 0) {
let count = "\(Business.count)"
view.titleLabel.text = (biz["name"] as String).uppercaseString
}
return view
}
override func tableView(tableView: UITableView!, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
func fetchKimono() {
var urlPath = "names have been removed to protect the innocent"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
connection.start()
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
// Recieved a new request, clear out the data object
self.data = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
// Append the recieved chunk of data to our data object
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
// Request complete, self.data should now hold the resulting info
// Convert the retrieved data in to an object through JSON deserialization
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var results: NSDictionary = jsonResult["results"] as NSDictionary
var collection: NSArray = results["collection1"] as NSArray
if jsonResult.count>0 && collection.count>0 {
Business = jsonResult
tableView.reloadData()
}
}
}
You must always declare a lazy property as a variable (with the var keyword), because its initial value may not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.
It seems the original author has found their solution, but for anyone else who gets here looking to add actual custom headers, if you have access to mod the generated Protocol code you can override GetWebRequest
:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("myheader", "myheader_value");
return request;
}
Make sure you remove the DebuggerStepThroughAttribute
attribute if you want to step into it.
See here http://dev.mysql.com/doc/refman/5.0/en/connecting.html
mysql -u USERNAME -pPASSWORD -h HOSTNAMEORIP DATABASENAME
The options above means:
-u: username
-p: password (**no space between -p and the password text**)
-h: host
last one is name of the database that you wanted to connect.
Look into the link, it's detailed there!
As already mentioned by Rick, you can avoid passing the password as the part of the command by not passing the password like this:
mysql -u USERNAME -h HOSTNAMEORIP DATABASENAME -p
People editing this answer: PLEASE DONOT ADD A SPACE between -p
and PASSWORD
Type in the terminal as follows:
mysql.server start
$("#" + $(this).attr("name")).hide();
Also, There is org.springframework.util.StringUtils
in Spring Framework:
StringUtils.capitalize(str);
This will work for any resolution,
button{
position:absolute;
bottom: 5%;
right:20%;
}
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
Empty strings are falsey, so you can just write:
if ($a) {
echo 'text';
}
Although if you're asking if a particular substring exists in that string, you can use strpos()
to do that:
if (strpos($a, 'some text') !== false) {
echo 'text';
}
You're initialising your SSLContext
with a null
KeyManager
array.
The key manager is what handles the server certificate (on the server side), and this is what you're probably aiming to set when using javax.net.ssl.keyStore
.
However, as described in the JSSE Reference Guide, using null
for the first parameter doesn't do what you seem to think it does:
If the KeyManager[] parameter is null, then an empty KeyManager will be defined for this context. If the TrustManager[] parameter is null, the installed security providers will be searched for the highest-priority implementation of the TrustManagerFactory, from which an appropriate TrustManager will be obtained. Likewise, the SecureRandom parameter may be null, in which case a default implementation will be used.
An empty KeyManager
doesn't contain any RSA or DSA certificates. Therefore, all the default cipher suites that would rely on such a certificate are disabled. This is why you get all these "Ignoring unavailable cipher suite" messages, which ultimately result in a "no cipher suites in common" message.
If you want your keystore to be used as a keystore, you'll need to load it and initialise a KeyManagerFactory with it:
KeyStore ks = KeyStore.getInstance("JKS");
InputStream ksIs = new FileInputStream("...");
try {
ks.load(ksIs, "password".toCharArray());
} finally {
if (ksIs != null) {
ksIs.close();
}
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(ks, "keypassword".toCharArray());
The use kmf.getKeyManagers()
as the first parameter to SSLContext.init()
.
For the other two parameters, since you're visibly not requesting client-certificate authentication, you should leave the trust manager to its default value (null
) instead of copying/pasting a trust manager that's a potential cause of vulnerability, and you can also use the default null
SecureRandom
.
devnull is right;
sudo update-alternatives --config x-terminal-emulator
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
git pull
is really just a shorthand for git pull <remote> <branchname>
, in most cases it's equivalent to git pull origin master
. You will need to add another remote and pull explicitly from it. This page describes it in detail:
I use varargs frequently for outputting to the logs for purposes of debugging.
Pretty much every class in my app has a method debugPrint():
private void debugPrint(Object... msg) {
for (Object item : msg) System.out.print(item);
System.out.println();
}
Then, within methods of the class, I have calls like the following:
debugPrint("for assignment ", hwId, ", student ", studentId, ", question ",
serialNo, ", the grade is ", grade);
When I'm satisfied that my code is working, I comment out the code in the debugPrint() method so that the logs will not contain too much extraneous and unwanted information, but I can leave the individual calls to debugPrint() uncommented. Later, if I find a bug, I just uncomment the debugPrint() code, and all my calls to debugPrint() are reactivated.
Of course, I could just as easily eschew varargs and do the following instead:
private void debugPrint(String msg) {
System.out.println(msg);
}
debugPrint("for assignment " + hwId + ", student " + studentId + ", question "
+ serialNo + ", the grade is " + grade);
However, in this case, when I comment out the debugPrint() code, the server still has to go through the trouble of concatenating all the variables in every call to debugPrint(), even though nothing is done with the resulting string. If I use varargs, however, the server only has to put them in an array before it realizes that it doesn't need them. Lots of time is saved.
We cannot add relations, unless related tables gets created. Laravel run migrations order by date of migration files. So if you want to create a relation with a table that exists in 2nd migration file it fails.
I faced the same problem, so I created one more migration file at last to specify all relations.
Schema::table('properties', function(Blueprint $table) {
$table->foreign('user')->references('id')->on('users')->onDelete('cascade');
$table->foreign('area')->references('id')->on('areas')->onDelete('cascade');
$table->foreign('city')->references('id')->on('cities')->onDelete('cascade');
$table->foreign('type')->references('id')->on('property_types')->onDelete('cascade');
});
Schema::table('areas', function(Blueprint $table) {
$table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
});
In Java8 you can use streams:
public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsIn) {
return listCarnet.stream().filter(carnet -> codeIsIn.equals(carnet.getCodeIsin())).findFirst().orElse(null);
}
Additionally, in case you have many different objects (not only Carnet
) or you want to find it by different properties (not only by cideIsin
), you could build an utility class, to ecapsulate this logic in it:
public final class FindUtils {
public static <T> T findByProperty(Collection<T> col, Predicate<T> filter) {
return col.stream().filter(filter).findFirst().orElse(null);
}
}
public final class CarnetUtils {
public static Carnet findByCodeTitre(Collection<Carnet> listCarnet, String codeTitre) {
return FindUtils.findByProperty(listCarnet, carnet -> codeTitre.equals(carnet.getCodeTitre()));
}
public static Carnet findByNomTitre(Collection<Carnet> listCarnet, String nomTitre) {
return FindUtils.findByProperty(listCarnet, carnet -> nomTitre.equals(carnet.getNomTitre()));
}
public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsin) {
return FindUtils.findByProperty(listCarnet, carnet -> codeIsin.equals(carnet.getCodeIsin()));
}
}
Another possibility for this warning (and, most likely, problems with app behavior) is that the original author of the app relied on session.auto_start
being on (defaults to off)
If you don't want to mess with the code and just need it to work, you can always change php configuration and restart php-fpm (if this is a web app):
/etc/php.d/my-new-file.ini :
session.auto_start = 1
(This is correct for CentOS 8, adjust for your OS/packaging)
type T1 = Omit<XYZ, "z"> // { x: number; y: number; }
type T2 = Omit<XYZ, "y" | "z"> // { x: number; }
type Keys_StringExcluded<T> =
{ [K in keyof T]: T[K] extends string ? never : K }[keyof T]
type XYZ = { x: number; y: string; z: number; }
type T3a = Pick<XYZ, Keys_StringExcluded<XYZ>> // { x: number; z: number; }
Shorter version with TS 4.1 key remapping / as
clause in mapped types (PR):
type T3b = { [K in keyof XYZ as XYZ[K] extends string ? never : K]: XYZ[K] }
// { x: number; z: number; }
string
patterntype OmitGet<T> = {[K in keyof T as K extends `get${infer _}` ? never : K]: T[K]}
type XYZ2 = { getA: number; b: string; getC: boolean; }
type T4 = OmitGet<XYZ2> // { b: string; }
Note: Above template literal types are supported with TS 4.1.
Note 2: You can also write get${string}
instead of get${infer _}
here.
Pick
, Omit
and other utility types
How to Pick and rename certain keys using Typescript? (rename instead of exclude)
multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.
The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).
The payload passed looks something like this:
Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”file”; filename=”captcha”
Content-Type:
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”action”
submit
-----WebKitFormBoundary7MA4YWxkTrZu0gW--
On the webservice side, it's consumed in @Consumes("multipart/form-data") form.
Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.
Javascript is base of jQuery.
jQuery is a wrapper of JavaScript, with much pre-written functionality and DOM traversing.
This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.
typedef double (*pf)(double x); /*this defines a type pf */
double f1(double x) { return(x+x);}
double f2(double x) { return(x*x);}
pf pa[] = {f1, f2};
main()
{
pf p;
p = pa[0];
printf("%f\n", p(3.0));
p = pa[1];
printf("%f\n", p(3.0));
}
Yes, you can assign the value of variable inside if.
I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single =
instead of ==
or ===
.
It will be better if you do something like this:
int v;
if((v = someMethod()) != 0)
return true;
It's a unicode character. In this case \u003C
and \u003E
mean :
U+003C < Less-than sign
U+003E > Greater-than sign
See a list here
How about putting the checkbox
into the label
, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange
event?
<label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....>
function toggleCheckbox(element)
{
element.checked = !element.checked;
}
This will additionally catch users using a keyboard to toggle the check box, something onclick
would not.
Add this code to your page:
<script type="text/javascript">
$(document).ready(function() {
$("input[type='submit']").click(function(){
$(this).css('background-color','red');
});
});
</script>
I like to use the ternary operator for this, since it's a bit more succinct for something that feels like it shouldn't be more than 1 line.
True if myString=="True" else False
just to offer up some variety. ds.oop is a nice way to declare classes with constructors in javascript. It supports every possible type of inheritance (Including 1 type that even c# does not support) as well as Interfaces which is nice.
var Color = ds.make.class({
type: 'Color',
constructor: function (r,g,b) {
this.r = r; /* now r,g, and b are available to */
this.g = g; /* other methods in the Color class */
this.b = b;
}
});
var red = new Color(255,0,0); // using the new keyword to instantiate the class
In addition to DCookie's answer above, you can also use chr(39) for a single quote.
I find this particularly useful when I have to create a number of insert/update statements based on a large amount of existing data.
Here's a very quick example:
Lets say we have a very simple table, Customers, that has 2 columns, FirstName and LastName. We need to move the data into Customers2, so we need to generate a bunch of INSERT statements.
Select 'INSERT INTO Customers2 (FirstName, LastName) ' ||
'VALUES (' || chr(39) || FirstName || chr(39) ',' ||
chr(39) || LastName || chr(39) || ');' From Customers;
I've found this to be very useful when moving data from one environment to another, or when rebuilding an environment quickly.
A one-liner command in Windows PowerShell to delete or rename certain characters will be as below. (here the whitespace is being replaced with underscore)
Dir | Rename-Item –NewName { $_.name –replace " ","_" }
The line height of the <br>
can be different from the line height of the rest of the text inside a <p>
. You can control the line height of your <br>
tags independently of the rest of the text by enclosing two of them in a <span>
that is styled. Use the line-height
css property, as others have suggested.
<p class="normalLineHeight">
Lots of text here which will display on several lines with normal line height if you put it in a narrow container...
<span class="customLineHeight"><br><br></span>
After a custom break, this text will again display on several lines with normal line height...
</p>
I had the same problem. Try this.
<nav>
<ul>
<li><a href="#">AnaSayfa</a></li>
<li><a href="#">Hakkimizda</a></li>
<li><a href="#">Iletisim</a></li>
</ul>
</nav>
@charset "utf-8";
nav {
background-color: #9900CC;
height: 80px;
width: 400px;
}
ul {
list-style: none;
float: right;
margin: 0;
}
li {
float: left;
width: 100px;
line-height: 80px;
vertical-align: middle;
text-align: center;
margin: 0;
}
nav li a {
width: 100px;
text-decoration: none;
color: #FFFFFF;
}
It needs to be clarified that not only data should be cache-friendly, it is just as important for the code. This is in addition to branch predicition, instruction reordering, avoiding actual divisions and other techniques.
Typically the denser the code, the fewer cache lines will be required to store it. This results in more cache lines being available for data.
The code should not call functions all over the place as they typically will require one or more cache lines of their own, resulting in fewer cache lines for data.
A function should begin at a cache line-alignment-friendly address. Though there are (gcc) compiler switches for this be aware that if the the functions are very short it might be wasteful for each one to occupy an entire cache line. For example, if three of the most often used functions fit inside one 64 byte cache line, this is less wasteful than if each one has its own line and results in two cache lines less available for other usage. A typical alignment value could be 32 or 16.
So spend some extra time to make the code dense. Test different constructs, compile and review the generated code size and profile.
Ansible has a version_compare
filter since 1.6.
You can do something like below in when
conditional:
when: ansible_distribution_version | version_compare('12.04', '>=')
This will give you support for major & minor versions comparisons and you can compare versions using operators like:
<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
You can find more information about this here: Ansible - Version comparison filters
Otherwise if you have really simple case you can use what @ProfHase85 suggested
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
with LoDash you could simply do this:
_.transform(this.attributes, function (result, item) {
item.specified && (result[item.name] = item.value);
}, {});
justify-content
only has an effect if there's space left over after your flex items have flexed to absorb the free space. In most/many cases, there won't be any free space left, and indeed justify-content
will do nothing.
Some examples where it would have an effect:
if your flex items are all inflexible (flex: none
or flex: 0 0 auto
), and smaller than the container.
if your flex items are flexible, BUT can't grow to absorb all the free space, due to a max-width
on each of the flexible items.
In both of those cases, justify-content
would be in charge of distributing the excess space.
In your example, though, you have flex items that have flex: 1
or flex: 6
with no max-width
limitation. Your flexible items will grow to absorb all of the free space, and there will be no space left for justify-content
to do anything with.
You need a semicolon after font-family: Arial, Helvetica, sans-serif
. This will make your updated code the following:
<!DOCTYPE>
<html>
<head>
<title>DIV Font</title>
<style>
.my_text
{
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="my_text">some text</div>
</body>
</html>
This works for WordPress Bootstrap:
.navbar .nav > li > .dropdown-menu:after,
.navbar .nav > li > .dropdown-menu:before {
content: none;
}
First, your HTML markup looks like this:
<video id="awesome_video" src="first_video.mp4" autoplay />
Second, your JavaScript code will look like this:
<script type="text/javascript">
var index = 1,
playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
video = document.getElementById('awesome_video');
video.addEventListener('ended', rotate_video, false);
function rotate_video() {
video.setAttribute('src', playlist[index]);
video.load();
index++;
if (index >= playlist.length) { index = 0; }
}
</script>
And last but not least, your CSS:
#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.
There is Q
objects that allow to complex lookups. Example:
from django.db.models import Q
Item.objects.filter(Q(creator=owner) | Q(moderated=False))
These are different Form content types defined by W3C. If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work. This is the default.
But if you have to send non-ASCII text or large binary data, the form-data is for that.
You can use Raw if you want to send plain text or JSON or any other kind of string. Like the name suggests, Postman sends your raw string data as it is without modifications. The type of data that you are sending can be set by using the content-type header from the drop down.
Binary can be used when you want to attach non-textual data to the request, e.g. a video/audio file, images, or any other binary data file.
Refer to this link for further reading: Forms in HTML documents
const isPromise = (value) => {
return !!(
value &&
value.then &&
typeof value.then === 'function' &&
value?.constructor?.name === 'Promise'
)
}
As for me - this check is better, try it out
You can use Container to contain your widget:
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color(0xff000000),
width: 1,
)),
child: Text()
),
<context:component-scan base-package="" />
tells Spring to scan those packages for Annotations.
<mvc:annotation-driven>
registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.
This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.
You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.
Check out the 3.1 documentation to learn more.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config
>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
[3, 0, 1, 2],
[2, 0, 1, 1],
[4, 0, 2, 3],
[0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False, True, True, True],
[False, True, True, True],
[ True, True, True, True],
[False, True, True, False],
[ True, True, True, True]], dtype=bool)
>>>
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 0],
[1, 1, 1, 1]])
You can shorten this with:
>>> c = (a < 3).astype(int)
Assuming this is what the HTML looks like
<div class="form-group required">
<label class="col-md-2 control-label">E-mail</label>
<div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>
To display an asterisk on the right of the label:
.form-group.required .control-label:after {
color: #d00;
content: "*";
position: absolute;
margin-left: 8px;
top:7px;
}
Or to the left of the label:
.form-group.required .control-label:before{
color: red;
content: "*";
position: absolute;
margin-left: -15px;
}
To make a nice big red asterisks you can add these lines:
font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;
Or if you are using Font Awesome add these lines (and change the content line):
font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";
Actually, none of the given answers are fully cover the request.
As the OP didn't provided a specific use case or types of numbers, I will try to cover all possible cases and permutations.
This number is usually called unsigned integer, but you can also call it a positive non-fractional number, include zero. This includes numbers like 0
, 1
and 99999
.
The Regular Expression that covers this validation is:
/^(0|[1-9]\d*)$/
This number is usually called signed integer, but you can also call it a non-fractional number. This includes numbers like 0
, 1
, 99999
, -99999
, -1
and -0
.
The Regular Expression that covers this validation is:
/^-?(0|[1-9]\d*)$/
As you probably noticed, I have also included -0
as a valid number. But, some may argue with this usage, and tell that this is not a real number (you can read more about Signed Zero here). So, if you want to exclude this number from this regex, here's what you should use instead:
/^-?(0|[1-9]\d*)(?<!-0)$/
All I have added is (?<!-0)
, which means not to include -0
before this assertion. This (?<!...)
assertion called negative lookbehind, which means that any phrase replaces the ...
should not appear before this assertion. Lookbehind has limitations, like the phrase cannot include quantifiers. That's why for some cases I'll be using Lookahead instead, which is the same, but in the opposite way.
Many regex flavors, including those used by Perl and Python, only allow fixed-length strings. You can use literal text, character escapes, Unicode escapes other than
\X
, and character classes. You cannot use quantifiers or backreferences. You can use alternation, but only if all alternatives have the same length. These flavors evaluate lookbehind by first stepping back through the subject string for as many characters as the lookbehind needs, and then attempting the regex inside the lookbehind from left to right.
You can read more bout Lookaround assertions here.
This number is usually called unsigned float or unsigned double, but you can also call it a positive fractional number, include zero. This includes numbers like 0
, 1
, 0.0
, 0.1
, 1.0
, 99999.000001
, 5.10
.
The Regular Expression that covers this validation is:
/^(0|[1-9]\d*)(\.\d+)?$/
Some may say, that numbers like .1
, .0
and .00651
(same as 0.1
, 0.0
and 0.00651
respectively) are also valid fractional numbers, and I cannot disagree with them. So here is a regex that is additionally supports this format:
/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
This number is usually called signed float or signed double, but you can also call it a fractional number. This includes numbers like 0
, 1
, 0.0
, 0.1
, 1.0
, 99999.000001
, 5.10
, -0
, -1
, -0.0
, -0.1
, -99999.000001
, 5.10
.
The Regular Expression that covers this validation is:
/^-?(0|[1-9]\d*)(\.\d+)?$/
For non -0
believers:
/^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d+)?$/
For those who want to support also the invisible zero representations, like .1
, -.1
, use the following regex:
/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
The combination of non -0
believers and invisible zero believers, use this regex:
/^(?!-0?(\.0+)?$)-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
Some may want to support in their validations, numbers with a scientific character e
, which is by the way, an absolutely valid number, it is created for shortly represent a very long numbers. You can read more about Scientific Notation here. These numbers are usually looks like 1e3
(which is 1000
), 1e-3
(which is 0.001) and are fully supported by many major programming languages (e.g. JavaScript). You can test it by checking if the expression '1e3'==1000
returns true
.
I will divide the support for all the above sections, including numbers with scientific notation.
Whole positive number regex validation, supports numbers like 6e4
, 16e-10
, 0e0
but also regular numbers like 0
, 11
:
/^(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Whole positive and negative number regex validation, supports numbers like -6e4
, -16e-10
, -0e0
but also regular numbers like -0
, -11
and all the whole positive numbers above:
/^-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Whole positive and negative number regex validation for non -0
believers, same as the above, except now it forbids numbers like -0
, -0e0
, -0e5
and -0e-6
:
/^(?!-0)-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Positive number regex validation, supports also the whole numbers above, plus numbers like 0.1e3
, 56.0e-3
, 0.0e10
and 1.010e0
:
/^(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Positive number with invisible zero support regex validation, supports also the above positive numbers, in addition numbers like .1e3
, .0e0
, .0e-5
and .1e-7
:
/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Negative and positive number regex validation, supports the positive numbers above, but also numbers like -0e3
, -0.1e0
, -56.0e-3
and -0.0e10
:
/^-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Negative and positive number regex validation fro non -0
believers, same as the above, except now it forbids numbers like -0
, -0.00000
, -0.0e0
, -0.00000e5
and -0e-6
:
/^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Negative and positive number with invisible zero support regex validation, supports also the above positive and negative numbers, in addition numbers like -.1e3
, -.0e0
, -.0e-5
and -.1e-7
:
/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Negative and positive number with the combination of non -0
believers and invisible zero believers, same as the above, but forbids numbers like -.0e0
, -.0000e15
and -.0e-19
:
/^(?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
In many programming languages, string representation of hexadecimal number like 0x4F7A
may be easily cast to decimal number 20346
.
Thus, one may want to support it in his validation script.
The following Regular Expression supports only hexadecimal numbers representations:
/^0x[0-9a-f]+$/i
These final Regular Expressions, support the invisible zero numbers.
/^(-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i
/^((?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i
Hope I covered all number permutations that are supported in many programming languages.
Good luck!
Oh, forgot to mention, that those who want to validate a number includes a thousand separator, you should clean all the commas (,
) first, as there may be any type of separator out there, you can't actually cover them all.
But you can remove them first, before the number validation:
//JavaScript
function clearSeparators(number)
{
return number.replace(/,/g,'');
}
The solution is quite simple.
In your php.ini, just uncomment the line extension=php_gd2.dll
(or .so extension for unix systems.)
Hope it helps.
SET JAVA_HOME=C:\Program Files\Java\jdk1.8.0
worked fine for me.
Note - Don't put double quotes over the path as mentioned above. Otherwise when you run
mvn -version
it will give following error
Files\java\jdk1.8.0_201\jre""==""
was unexpected at this time.
try this:
String DATE_FORMAT_NOW = "yyyy-MM-dd";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String stringDate = sdf.format(date );
try {
Date date2 = sdf.parse(stringDate);
} catch(ParseException e){
//Exception handling
} catch(Exception e){
//handle exception
}
Your CSV file might have variable number of columns and read_csv
inferred the number of columns from the first few rows. Two ways to solve it in this case:
1) Change the CSV file to have a dummy first line with max number of columns (and specify header=[0]
)
2) Or use names = list(range(0,N))
where N is the max number of columns.
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
It depends on what you want to do and what type of data/information you are displaying. In general, tables are reserved for displaying tabular data.
An alternate for your situation would be to use css. A simple option would be to float your image and give it a margin:
<p>
<img style="float: left; margin: 5px;" ... />
Text goes here...
</p>
This would cause the text to wrap around the image. If you don't want the text to wrap around the image, put the text in a separate container:
<div>
<img style="float: left; margin: ...;" ... />
<p style="float: right;">Text goes here...</p>
</div>
Note that it may be necessary to assign a width to the paragraph tag to display the way you'd like. Also note, for elements that appear below floated elements, you may need to add the style "clear: left;" (or clear: right, or clear: both).
You need to change Java compiler version in in build config.
Here's how I got it working:
Include your URL in IE Trusted Sites
run gpedit.msc
(as Admin) and enable the following setting:
gpedit->Local->Computer->Windows Comp->ActiveX Installer->ActiveX installation policy for sites in Trusted Zones
Enabled + Silently,Silently,Prompt
Run gpupdate
Relaunch your Browser
NOTES: Windows 10 EDGE don't have trusted sites, so you have to use IE 11. Lots of folk moaning about that!
Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:
External
option in Unity ? Preferences ? Packages ? Repository
Hidden Meta Files
in Editor ? Project Settings ? Editor ? Version Control Mode
Force Text
in Editor ? Project Settings ? Editor ? Asset Serialization Mode
File
menuNote that the only folders you need to keep under source control are Assets
and ProjectSettigns
.
More information about keeping Unity Project under source control you can find in this post.
Try running fuser command
[root@guest2 ~]# fuser -mv /home
USER PID ACCESS COMMAND
/home: root 2919 f.... automount
[root@guest2 ~]# kill -9 2919
autofs
service is known to cause this issue.
You can use command
#service autofs stop
And try again.
Well, your syntax isn't really Python to begin with.
Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container
. In this case, the container is the cars
list, but you want to skip the first and last elements, so that means cars[1:-1]
(python lists are zero-based, negative numbers count from the end, and :
is slicing syntax.
So you want
for c in cars[1:-1]:
do something with c
Using DISTINCT will work
SELECT GROUP_CONCAT(DISTINCT(categories) SEPARATOR ' ') FROM table
REf:- this
Posting my answer to help someone, the top rated answer didn't solve my qualm.
When I implemented the following [from the top answer], my vertical scroll animation just jittered back and forth:
$(function () {
$("#first").animate({
width: '200px'
}, { duration: 200, queue: false });
$("#second").animate({
width: '600px'
}, { duration: 200, queue: false });
});
I referred to: W3 Schools Set Interval and it solved my issue, namely the 'Syntax' section:
setInterval(function, milliseconds, param1, param2, ...)
Having my parameters of the form { duration: 200, queue: false }
forced a duration of zero and it only looked at the parameters for guidance.
The long and short, here's my code, if you want to understand why it works, read the link or analyse the interval expected parameters:
var $scrollDiv = '#mytestdiv';
var $scrollSpeed = 1000;
var $interval = 800;
function configureRepeats() {
window.setInterval(function () {
autoScroll($scrollDiv, $scrollSpeed);
}, $interval, { queue: false });
};
Where 'autoScroll' is:
$($scrollDiv).animate({
scrollTop: $($scrollDiv).get(0).scrollHeight
}, { duration: $scrollSpeed });
//Scroll to top immediately
$($scrollDiv).animate({
scrollTop: 0
}, 0);
Happy coding!
in your tsconfig you have to add: "esModuleInterop": true - it should help.
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
here is the general rule: DTO==evil and indicator of over-engineered software. POCO==good. 'enterprise' patterns have destroyed the brains of a lot of people in the Java EE world. please don't repeat the mistake in .NET land.
You can specify multiple patterns in an array.
select-string VendorEnquiry,Failed C:\Logs
This works with -notmatch as well:
select-string -notmatch VendorEnquiry,Failed C:\Logs
This is known as a fork bomb. It keeps splitting itself until there is no option but to restart the system. http://en.wikipedia.org/wiki/Fork_bomb
Only ASCII or are other characters allowed too?
^\w*$
restricts (in Java) to ASCII letters/digits und underscore,
^[\pL\pN\p{Pc}]*$
also allows international characters/digits and "connecting punctuation".
worked for me too:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parsed = null;
try {
parsed = sdf.parse("02/01/2014");
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Date data = new java.sql.Date(parsed.getTime());
contato.setDataNascimento( data);
// Contato DataNascimento era Calendar
//contato.setDataNascimento(Calendar.getInstance());
// grave nessa conexão!!!
ContatoDao dao = new ContatoDao("mysql");
// método elegante
dao.adiciona(contato);
System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());
From your code, it looks like your Comparator
is already parameterized with Campaign
. This will only work with List<Campaign>
. Also, the method you're looking for is compareTo
.
if (list.size() > 0) {
Collections.sort(list, new Comparator<Campaign>() {
@Override
public int compare(final Campaign object1, final Campaign object2) {
return object1.getName().compareTo(object2.getName());
}
});
}
Or if you are using Java 1.8
list
.stream()
.sorted((object1, object2) -> object1.getName().compareTo(object2.getName()));
One final comment -- there's no point in checking the list size. Sort will work on an empty list.
a = 0.000006;
b = 6;
c = a/b;
textbox.Text = c.ToString("0.000000");
As you requested:
textbox.Text = c.ToString("0.######");
This will only display out to the 6th decimal place if there are 6 decimals to display.
A first stab at it seems to work for your particular case.
awk '{ f = $1; i = $NF; while (i <= 0); gsub(/^[A-Z][A-Z][ ][ ]/,""); print $i, f; }'
This works for type of data: Data1, Data2, Data3 ......,Data21. Means "Data" String is common in all rows.
For ORDER BY ASC it will sort perfectly, For ORDER BY DESC not suitable.
SELECT * FROM table_name ORDER BY LENGTH(column_name), column_name ASC;
Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)
They are designed to work with WCF.
If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP
The code you provided would print the number of tabs, not the number of spaces. The below function should count the number of whitespace characters in a given string.
int countSpaces(String string) {
int spaces = 0;
for(int i = 0; i < string.length(); i++) {
spaces += (Character.isWhitespace(string.charAt(i))) ? 1 : 0;
}
return spaces;
}
I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:
<html>
<head>
<style>
div.both:hover .image { border: 1px solid blue }
div.both:hover .layer { border: 1px solid blue }
</style>
</head>
<body>
<div class="section">
<div class="both">
<div class="image"><img src="myImage.jpg" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
</div>
</body>
</html>
So, There is something I would like to bring up which I think is important and I think that you should consider. runtime and memory. Say you have a list and want to sort it, well you can, there is a built in sort or you could develop your own. Then you say, want to reverse the list. That is the answer which is listed above.
If you are creating that list though, it might be good to use a different datastructure to store it and then just dump it into an array.
Heaps do just this. You filter in data, and it will handle everything, then you can pop everything off of the object and it would be sorted.
Another option would be to understand how maps work. A lot of times, a Map or HashMap as something things are called, have an underlying concept behind it.
For example.... you feed in a bunch of key-value pairs where the key is the long, and when you add all the elements, you can do: .keys
and it would return to you a sorted list automatically.
It depends on how you process the data prior as to how i think you should continue with your sorting and subsequent reverses
function get_content(){
var returnInnerHTML = document.getElementById('A').innerHTML + document.getElementById('B').innerHTML + document.getElementById('A').innerHTML;
document.getElementById('txt').innerHTML = returnInnerHTML;
}
That should do it.
at -l
to list jobs, which gives return like this:
age2%> at -l
11 2014-10-21 10:11 a hoppent
10 2014-10-19 13:28 a hoppent
atrm 10
kills job 10
Or so my sysadmin told me, and it
Question might be a little dated, but you could simply use AbstractMap.SimpleEntry<> as follows:
private Map<String, AttributeType> mapConfig(
Map<String, String> input, String prefix) {
int subLength = prefix.length();
return input.entrySet()
.stream()
.map(e -> new AbstractMap.SimpleEntry<>(
e.getKey().substring(subLength),
AttributeType.GetByName(e.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
any other Pair-like value object would work too (ie. ApacheCommons Pair tuple).
There are various web APIs that will do this for you. Here's an example using my service, http://ipinfo.io:
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
echo $details->country; // -> "US"
Web APIs are a nice quick and easy solution, but if you need to do a lot of lookups then having an IP -> country database on your own machine is a better solution. MaxMind offer a free database that you can use with various PHP libraries, including GeoIP.
class MyApp2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: AppBarTheme(
elevation: 0,
color: Colors.blueAccent,
)
),
title: 'Welcome to flutter ',
home: HomePage()
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int number = 0;
void _increment(){
setState(() {
number ++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueAccent,
appBar: AppBar(
title: Text('MyApp2'),
leading: Icon(Icons.menu),
// backgroundColor: Colors.blueAccent,
),
body: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(200.0),
topRight: Radius.circular(200)
),
color: Colors.white,
),
)
);
}
}
The accepted answer works only if you want exactly 31 days later. That means if you are using the date "2013-05-31" that you expect to not be in June which is not what I wanted.
If you want to have the next month, I suggest you to use the current year and month but keep using the 1st.
$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
This way, you will be able to get the month and year of the next month without having a month skipped.
If you're using #
as an operator, consider defining a new operator for it:
\newcommand{\pound}{\operatornamewithlimits{\#}}
You can then write things like \pound_{n = 1}^N
and get:
See §6.7.9 Initialization:
21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
So, yes both of them work. Note that in C99 a new way of initialization, called designated initialization can be used too:
myStruct _m1 = {.c2 = 0, .c1 = 1};
No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.
If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.
A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.
You mentioned that PHP solutions were acceptable, and PHP does offer a way to accomplish this even though it only supports XPath v1.0. You can extend the XPath support to allow PHP function calls.
$xpathObj = new DOMXPath($docObj);
$xpathObj->registerNamespace('php','http://php.net/xpath'); // (required)
$xpathObj->registerPhpFunctions("strtolower"); // (leave empty to allow *any* PHP function)
$xpathObj->query('//CD[php:functionString("strtolower",@title) = "empire burlesque"]');
See the PHP registerPhpFunctions documentation for more examples. It basically demonstrates that "php:function" is for boolean evaluation and "php:functionString" is for string evaluation.
The bitwise method depends on the inner representation of the integer. Modulo will work anywhere there is a modulo operator. For example, some systems actually use the low level bits for tagging (like dynamic languages), so the raw x & 1 won't actually work in that case.
A portable solution could use getc
.
#include <stdio.h>
char buffer[MAX_FILE_SIZE];
size_t i;
for (i = 0; i < MAX_FILE_SIZE; ++i)
{
int c = getc(fp);
if (c == EOF)
{
buffer[i] = 0x00;
break;
}
buffer[i] = c;
}
If you don't want to have a MAX_FILE_SIZE
macro or if it is a big number (such that buffer
would be to big to fit on the stack), use dynamic allocation.
If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:
Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:
In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.
Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx
If you're running Windows 10 Creators Update (1703) and are comfortable navigating around a Unix terminal, you could potentially achieve this using the native Feature Bash on Ubuntu on Windows (aka Bash/WSL)
This was originally introduced on the launch of Build 2016 but many additions and bug fixes were addressed at the Creators update but please be warned this is still in Beta.
To enable simply navigate to Control Panel\All Control Panel Items\Programs and Features\Turn Windows features on or off
Then select the Windows Subsystem for Linux (Beta) as below Bash on Windows Feature
__FILE__
is the filename with extension of the file containing the code being executed.
In foo.rb
, __FILE__
would be "foo.rb".
If foo.rb
were in the dir /home/josh
then File.dirname(__FILE__)
would return /home/josh
.
This may help a small percentage of people still scratching their heads. Text copied from clipboard into VSCode may have an invisible hard space character preventing wrapping. Check it with HTML inspector
In MySQL TRUE
and FALSE
are synonyms for TINYINT(1)
.
So therefore its basically the same thing, but MySQL is converting to 0/1 - so just use a TINYINT
if that's easier for you
P.S.
The performance is likely to be so minuscule (if at all), that if you need to ask on StackOverflow, then it won't affect your database :)
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
swift 4 answer
static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
let date = dateFormatter.date(from: strDate)
return date!
}
public static func dateToString(inputdate : Date) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
return formatter.string(from: inputdate)
}
On my PC I had to open the Tomcat6 entry again after the 7th step mentioned above and then change the default option under Server locations
to Use tomcat installation
.
For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:
// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;
// jQuery:
$('#scrollable-section').scrollTop(1).scrollTop(0);
This triggers the visual cue fading in and out.
Updated June 2020
It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.
Before December 2019:
It is now "possible":
https://developers.facebook.com/docs/instagram-api/content-publishing
The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.
Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from https://stackoverflow.com/a/49677468/445887
Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.
$scope.storage = $localStorage; //connects an object to $localstorage
$scope.storage.hasSeenPopup = "false"; // they haven't seen it
$scope.showPopup = function() { // popup to tell people to turn sound on
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<p class="popuptext">Turn Sound On!</p>',
cssClass: 'popup'
});
$timeout(function() {
myPopup.close(); //close the popup after 3 seconds for some reason
}, 2000);
$scope.storage.hasSeenPopup = "true"; // they've now seen it
};
$scope.playStream = function(show) {
PlayerService.play(show);
$scope.audioObject = audioObject; // this allow for styling the play/pause icons
if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
$scope.showPopup();
}
}
insertion sort:
1.In the insertion sort swapping is not required.
2.the time complexity of insertion sort is O(n)for best case and O(n^2) worst case.
3.less complex as compared to bubble sort.
4.example: insert books in library, arrange cards.
bubble sort: 1.Swapping required in bubble sort.
2.the time complexity of bubble sort is O(n)for best case and O(n^2) worst case.
3.more complex as compared to insertion sort.
"cedivad" solved the issue for me with persistent result of Swedish chars ÅÄÖ.
$text = preg_replace( '/[^\p{L}\s]/u', '', $text );
Thanks!
Facing the blank screen in Laravel 5.8. Every thing seems fine with both storage and bootstrap folder given 777 rights. On
php artisan cache:clear
It shows the problem it was the White spaces in App Name of .env file
You can use the following code to check if the file can be opened with exclusive access (that is, it is not opened by another application). If the file isn't closed, you could wait a few moments and check again until the file is closed and you can safely copy it.
You should still check if File.Copy fails, because another application may open the file between the moment you check the file and the moment you copy it.
public static bool IsFileClosed(string filename)
{
try
{
using (var inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}
In my case this turned out to be a bad USB hub.
The 'lsusb' command can be used to display all recognized devices. If the unit is not plugged in the option to set the speed will be disabled.
The lsusb command should output something like the string 'Future Technology Devices International, Ltd Bridge(I2C/SPI/UART/FIFO)' if your device is recognized. Mine was an RFDuino
In python:
>>> from dateutil.rrule import rrule, DAILY
>>> import datetime, random
>>> random.choice(
list(
rrule(DAILY,
dtstart=datetime.date(2009,8,21),
until=datetime.date(2010,10,12))
)
)
datetime.datetime(2010, 2, 1, 0, 0)
(need python dateutil
library – pip install python-dateutil
)
SELECT id,
IF(type = 'P', amount, amount * -1) as amount
FROM report
See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html.
Additionally, you could handle when the condition is null. In the case of a null amount:
SELECT id,
IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM report
The part IFNULL(amount,0)
means when amount is not null return amount else return 0.
You can also use uic
in PyQt5 with the following code.
from PyQt5 import uic, QtWidgets
import sys
class Ui(QtWidgets.QDialog):
def __init__(self):
super(Ui, self).__init__()
uic.loadUi('SomeUi.ui', self)
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui()
sys.exit(app.exec_())
from functools import reduce
def f(x):
return x % 2 != 0 and x % 3 != 0
print(*filter(f, range(2, 25)))
#[5, 7, 11, 13, 17, 19, 23]
def cube(x):
return x**3
print(*map(cube, range(1, 11)))
#[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
def add(x,y):
return x+y
reduce(add, range(1, 11))
#55
It works as is. To get the output of map use * or list
In Android Studio 2.3.3 I was able to get my AVD to start and run by changing Graphics
in the Emulated Performance
section from Automatic
to Software-GLES 2.0
:
I was able to infer this after following the advice at https://stackoverflow.com/a/44931679/1843329 and doing:
$ ./emulator -avd Nexus_4_API_21 -use-system-libs
which resulted in:
emulator: ERROR: Could not initialize OpenglES emulation, use '-gpu off' to disable it.
And when I did:
./emulator -avd Nexus_4_API_21 -use-system-libs -gpu off
the emulator then launched.
The accepted answer here is problematic, because there is no guarantee that an image will have any sort of interactive shell. For example, the drone/drone image contains on a single command /drone
, and it has an ENTRYPOINT
as well, so this will fail:
$ docker run -it drone/drone sh
FATA[0000] DRONE_HOST is not properly configured
And this will fail:
$ docker run --rm -it --entrypoint sh drone/drone
docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"sh\": executable file not found in $PATH".
This is not an uncommon configuration; many minimal images contain only the binaries necessary to support the target service. Fortunately, there are mechanisms for exploring an image filesystem that do not depend on the contents of the image. The easiest is probably the docker export
command, which will export a container filesystem as a tar archive. So, start a container (it does not matter if it fails or not):
$ docker run -it drone/drone sh
FATA[0000] DRONE_HOST is not properly configured
Then use docker export
to export the filesystem to tar
:
$ docker export $(docker ps -lq) | tar tf -
The docker ps -lq
there means "give me the id of the most recent docker container". You could replace that with an explicit container name or id.
For those of you (like me) that wasted too much time from this error:
I had received the same error: "Could not find implementation of query Pattern for source type 'DbSet'" but the solution for me was fixing a mistake at the DbContext level.
When I created my context I had this:
public class ContactContext : DbContext
{
public ContactContext() : base() { }
public DbSet Contacts { get; set; }
}
And my Repository (I was following a Repository pattern in ASP.NET guide) looked like this:
public Contact FindById(int id)
{
var contact = from c in _db.Contacts where c.Id == id select c;
return contact;
}
My issue came from the initial setup of my DbContext, when I used DbSet as a generic instead of the type.
I changed public DbSet Contacts { get; set; }
to public DbSet<Contact> Contacts { get; set; }
and suddenly the query was recognized.
This is probably what k.m says in his answer, but since he mentioned IEnumerable<t>
and not DbSet<<YourDomainObject>>
I had to dig around in the code for a couple hours to find the line that caused this headache.
I'd rather not turn an integer into a string, so here's the function I use for this:
def digitize(n, base=10):
if n == 0:
yield 0
while n:
n, d = divmod(n, base)
yield d
Examples:
tuple(digitize(123456789)) == (9, 8, 7, 6, 5, 4, 3, 2, 1)
tuple(digitize(0b1101110, 2)) == (0, 1, 1, 1, 0, 1, 1)
tuple(digitize(0x123456789ABCDEF, 16)) == (15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
As you can see, this will yield digits from right to left. If you'd like the digits from left to right, you'll need to create a sequence out of it, then reverse it:
reversed(tuple(digitize(x)))
You can also use this function for base conversion as you split the integer. The following example splits a hexadecimal number into binary nibbles as tuples:
import itertools as it
tuple(it.zip_longest(*[digitize(0x123456789ABCDEF, 2)]*4, fillvalue=0)) == ((1, 1, 1, 1), (0, 1, 1, 1), (1, 0, 1, 1), (0, 0, 1, 1), (1, 1, 0, 1), (0, 1, 0, 1), (1, 0, 0, 1), (0, 0, 0, 1), (1, 1, 1, 0), (0, 1, 1, 0), (1, 0, 1, 0), (0, 0, 1, 0), (1, 1, 0, 0), (0, 1, 0, 0), (1, 0, 0, 0))
Note that this method doesn't handle decimals, but could be adapted to.
In short, size_t
is never negative, and it maximizes performance because it's typedef'd to be the unsigned integer type that's big enough -- but not too big -- to represent the size of the largest possible object on the target platform.
Sizes should never be negative, and indeed size_t
is an unsigned type. Also, because size_t
is unsigned, you can store numbers that are roughly twice as big as in the corresponding signed type, because we can use the sign bit to represent magnitude, like all the other bits in the unsigned integer. When we gain one more bit, we are multiplying the range of numbers we can represents by a factor of about two.
So, you ask, why not just use an unsigned int
? It may not be able to hold big enough numbers. In an implementation where unsigned int
is 32 bits, the biggest number it can represent is 4294967295
. Some processors, such as the IP16L32, can copy objects larger than 4294967295
bytes.
So, you ask, why not use an unsigned long int
? It exacts a performance toll on some platforms. Standard C requires that a long
occupy at least 32 bits. An IP16L32 platform implements each 32-bit long as a pair of 16-bit words. Almost all 32-bit operators on these platforms require two instructions, if not more, because they work with the 32 bits in two 16-bit chunks. For example, moving a 32-bit long usually requires two machine instructions -- one to move each 16-bit chunk.
Using size_t
avoids this performance toll. According to this fantastic article, "Type size_t
is a typedef that's an alias for some unsigned integer type, typically unsigned int
or unsigned long
, but possibly even unsigned long long
. Each Standard C implementation is supposed to choose the unsigned integer that's big enough--but no bigger than needed--to represent the size of the largest possible object on the target platform."
Use -A and -B switches (mean lines-after and lines-before):
grep -A 1 -B 1 FAILED file.txt
I create the tag like this and then I push it to GitHub:
git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags
Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
* [new tag] v1.1 -> v1.1
This should be performant, thread-safe and flexible enough for many uses:
#include <random>
#include <iostream>
template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
thread_local static Generator gen(std::random_device{}());
using dist_type = typename std::conditional
<
std::is_integral<Numeric>::value
, std::uniform_int_distribution<Numeric>
, std::uniform_real_distribution<Numeric>
>::type;
thread_local static dist_type dist;
return dist(gen, typename dist_type::param_type{from, to});
}
int main(int, char*[])
{
for(auto i = 0U; i < 20; ++i)
std::cout << random<double>(0.0, 0.3) << '\n';
}
look at
http://jtds.sourceforge.net/faq.html#driverImplementation
What is the URL format used by jTDS?
The URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
... domain Specifies the Windows domain to authenticate in. If present and the user name and password are provided, jTDS uses Windows (NTLM) authentication instead of the usual SQL Server authentication (i.e. the user and password provided are the domain user and password). This allows non-Windows clients to log in to servers which are only configured to accept Windows authentication.
If the domain parameter is present but no user name and password are provided, jTDS uses its native Single-Sign-On library and logs in with the logged Windows user's credentials (for this to work one would obviously need to be on Windows, logged into a domain, and also have the SSO library installed -- consult README.SSO in the distribution on how to do this).
In this case you use -1.
Declare native count queries for pagination at the query method by using @Query
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
nativeQuery = true)
Page<User> findByLastname(String lastname, Pageable pageable);
}
Hope this helps
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
Here's a solution for more extreme cases:
if [ `command | head -c1 | wc -c` -gt 0 ]; then ...; fi
This will work
however,
git reset c14809fafb08b9e96ff2879999ba8c807d10fb07
is what you're after...
You can try below:
find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'
Just write this query in your db phpmyadmin.
ALTER TABLE TableName ADD UNIQUE (FieldName)
Eg: ALTER TABLE user ADD UNIQUE (email)