I'm not sure why you'd want to validate an optional email address, but I'd suggest you use
^$|^[^@\s]+@[^@\s]+$
meaning
^$ empty string
| or
^ beginning of string
[^@\s]+ any character but @ or whitespace
@
[^@\s]+
$ end of string
You won't stop fake emails anyway, and this way you won't stop valid addresses.
Use the .scroll()
event on window
, like this:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
}
});
You can test it here, this takes the top scroll of the window, so how much it's scrolled down, adds the height of the visible window and checks if that equals the height of the overall content (document
). If you wanted to instead check if the user is near the bottom, it'd look something like this:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
alert("near bottom!");
}
});
You can test that version here, just adjust that 100
to whatever pixel from the bottom you want to trigger on.
The solution for me was switching from IIS Express to Local IIS. Make sure though your virtual directory is bound to the same port.
This is supported for JPQL queries within the JPA specification.
Step 1: Declare a simple bean class
package com.path.to;
public class SurveyAnswerStatistics {
private String answer;
private Long cnt;
public SurveyAnswerStatistics(String answer, Long cnt) {
this.answer = answer;
this.count = cnt;
}
}
Step 2: Return bean instances from the repository method
public interface SurveyRepository extends CrudRepository<Survey, Long> {
@Query("SELECT " +
" new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) " +
"FROM " +
" Survey v " +
"GROUP BY " +
" v.answer")
List<SurveyAnswerStatistics> findSurveyCount();
}
MyBean
and it is in package com.path.to
, the fully-qualified path to the bean will be com.path.to.MyBean
. Simply providing MyBean
will not work (unless the bean class is in the default package).new
keyword. SELECT new com.path.to.MyBean(...)
will work, whereas SELECT com.path.to.MyBean(...)
will not.@Query("SELECT ...")
, or @Query(value = "SELECT ...")
, or @Query(value = "SELECT ...", nativeQuery = false)
will work, whereas @Query(value = "SELECT ...", nativeQuery = true)
will not work. This is because native queries are passed without modifications to the JPA provider, and are executed against the underlying RDBMS as such. Since new
and com.path.to.MyBean
are not valid SQL keywords, the RDBMS then throws an exception.As noted above, the new ...
syntax is a JPA-supported mechanism and works with all JPA providers. However, if the query itself is not a JPA query, that is, it is a native query, the new ...
syntax will not work as the query is passed on directly to the underlying RDBMS, which does not understand the new
keyword since it is not part of the SQL standard.
In situations like these, bean classes need to be replaced with Spring Data Projection interfaces.
Step 1: Declare a projection interface
package com.path.to;
public interface SurveyAnswerStatistics {
String getAnswer();
int getCnt();
}
Step 2: Return projected properties from the query
public interface SurveyRepository extends CrudRepository<Survey, Long> {
@Query(nativeQuery = true, value =
"SELECT " +
" v.answer AS answer, COUNT(v) AS cnt " +
"FROM " +
" Survey v " +
"GROUP BY " +
" v.answer")
List<SurveyAnswerStatistics> findSurveyCount();
}
Use the SQL AS
keyword to map result fields to projection properties for unambiguous mapping.
If you are sure about your sent JSON then you must trace your API carefully:
Microsoft.AspNet.WebApi.Tracing
packageconfig.EnableSystemDiagnosticsTracing();
in the WebApiConfig
class inside Register
method.Now look at the Debug output and you will probably find an invalid ModelState
log entry.
If ModelState
is invalid you may find the real cause in its Errors
:
No one can even guess such an exception:
Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
You can confirm this by printing out the string to see that it turns out identical to the first case.
Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string
, which would make it look perhaps like this:
$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
mysql_real_escape_string($prefix));
$query = mysql_query($sql);
Note that inside the first argument of sprintf
the percent sign needs to be doubled to end up appearing once in the result.
Use
[A-Z]?
to make the letter optional. {1}
is redundant. (Of course you could also write [A-Z]{0,1}
which would mean the same, but that's what the ?
is there for.)
You could improve your regex to
^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})
And, since in most regex dialects, \d
is the same as [0-9]
:
^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})
But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?
I have found another solution to prevent negative number.
<input type="number" name="test_name" min="0" oninput="validity.valid||(value='');">
I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.
If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.getElementById("chells").appendChild(input);
Restart Mac -> hold down "Command + R" after the startup chime -> Opens OS X Utilities -> Open Terminal and type "csrutil disable" -> Reboot OS X -> Open Terminal and check "csrutil status"
This should not be difficult. When creating a cell for your table, add a UITextField object to the cell's content view
UITextField *txtField = [[UITextField alloc] initWithFrame....]
...
[cell.contentView addSubview:txtField]
Set the delegate of the UITextField as self (ie your viewcontroller) Give a tag to the text field so you can identify which textfield was edited in your delegate methods. The keyboard should pop up when the user taps the text field. I got it working like this. Hope it helps.
Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:
<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin" />
<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />
The outcome would be
$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'],
'city' => [ 'Berlin' , 'New York'] ];
To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:
<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin" />
<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />
The outcome would be
$POST = [ 'address' => [
1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
2 => ['street' => 'Wallstreet', 'city' => 'New York'],
]
]
If you have python installed you could try:
python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
stores.dat
Looping D3 ways;
Sub SearchArray()
Dim arr(3, 2) As Variant
arr(0, 0) = "A"
arr(0, 1) = "1"
arr(0, 2) = "w"
arr(1, 0) = "B"
arr(1, 1) = "2"
arr(1, 2) = "x"
arr(2, 0) = "C"
arr(2, 1) = "3"
arr(2, 2) = "y"
arr(3, 0) = "D"
arr(3, 1) = "4"
arr(3, 2) = "z"
Debug.Print "Loop Dimension 1"
For i = 0 To UBound(arr, 1)
Debug.Print "arr(" & i & ", 0) is " & arr(i, 0)
Next i
Debug.Print ""
Debug.Print "Loop Dimension 2"
For j = 0 To UBound(arr, 2)
Debug.Print "arr(0, " & j & ") is " & arr(0, j)
Next j
Debug.Print ""
Debug.Print "Loop Dimension 1 and 2"
For i = 0 To UBound(arr, 1)
For j = 0 To UBound(arr, 2)
Debug.Print "arr(" & i & ", " & j & ") is " & arr(i, j)
Next j
Next i
Debug.Print ""
End Sub
For some purposes, HtmlUtils:
import org.springframework.web.util.HtmlUtils;
[...]
HtmlUtils.htmlEscapeDecimal("&"); //gives &
HtmlUtils.htmlEscape("&"); //gives &
The easiest way is to make the "button image" as a separate image. Then place it over the main image (using "style="position: absolute;". Assign the URL link to "button image". and smile :)
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
FAIL_ON_UNKNOWN_PROPERTIES option is true by default:
FAIL_ON_UNKNOWN_PROPERTIES (default: true)
Used to control whether encountering of unknown properties (one for which there is no setter; and there is no fallback "any setter" method defined using @JsonAnySetter annotation) should result in a JsonMappingException (when enabled), or just quietly ignored (when disabled)
If you want to search for the last instance of a string in a text, you can run rfind.
Example:
s="Hello"
print s.rfind('l')
output: 3
*no import needed
Complete syntax:
stringEx.rfind(substr, beg=0, end=len(stringEx))
You can use lodash's findIndex to get the index of the specific element and then splice using it.
myArray.splice(_.findIndex(myArray, function(item) {
return item.value === 'money';
}), 1);
Update
You can also use ES6's findIndex()
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
const itemToRemoveIndex = myArray.findIndex(function(item) {
return item.field === 'money';
});
// proceed to remove an item only if it exists.
if(itemToRemoveIndex !== -1){
myArray.splice(itemToRemoveIndex, 1);
}
Another way to do this
find . -name *.xml -exec sed -i "s/4.6.0-SNAPSHOT/5.0.0-SNAPSHOT/" {} \;
Some help regarding the above command
The find will do the find for you on the current directory indicated by .
-name
the name of the file in my case its pom.xml can give wild cards.
-exec
execute
sed
stream editor
-i
ignore case
s
is for substitute
/4.6.0.../
String to be searched
/5.0.0.../
String to be replaced
The main scenario where JAX-WS RPC and Document style are used as follows:
The Remote Procedure Call (RPC) pattern is used when the consumer views the web service as a single logical application or component with encapsulated data. The request and response messages map directly to the input and output parameters of the procedure call.
Examples of this type the RPC pattern might include a payment service or a stock quote service.
The document-based pattern is used in situations where the consumer views the web service as a longer running business process where the request document represents a complete unit of information. This type of web service may involve human interaction for example as with a credit application request document with a response document containing bids from lending institutions. Because longer running business processes may not be able to return the requested document immediately, the document-based pattern is more commonly found in asynchronous communication architectures. The Document/literal variation of SOAP is used to implement the document-based web service pattern.
The simple and straightforward answer -->
using System;
namespace DemoApp.App
{
public class TestClassDate
{
public static DateTime GetDate(string string_date)
{
DateTime dateValue;
if (DateTime.TryParse(string_date, out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", string_date, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", string_date);
return dateValue;
}
public static void Main()
{
string inString = "05/01/2009 06:32:00";
GetDate(inString);
}
}
}
/**
* Output:
* Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
* */
In Oracle we can use below.
SELECT * FROM TABLE_A WHERE ASCIISTR(COLUMN_A) <> COLUMN_A;
GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).
This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.
Only three lines of relevant code.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with
curl
or other clients) then a possible cause could be that the endpoint expects aUser-Agent
header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g.System.setProperty("http.agent", "Netscape 1.0");
.
select u from UserGroup ug inner join ug.user u
where ug.group_id = :groupId
order by u.lastname
As a named query:
@NamedQuery(
name = "User.findByGroupId",
query =
"SELECT u FROM UserGroup ug " +
"INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)
Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.
I tried both .empty()
as well as .remove()
for my dropdown and both were slow. Since I had almost 4,000 options there.
I used .html("")
which is much faster in my condition.
Which is below
$(dropdown).html("");
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *name = "hello";
int main(void) {
char *ext = ".txt";
int len = strlen(name) + strlen(ext) + 1;
char *n2 = malloc(len);
char *n2a = malloc(len);
if (n2 == NULL || n2a == NULL)
abort();
strlcpy(n2, name, len);
strlcat(n2, ext, len);
printf("%s\n", n2);
/* or for conforming C99 ... */
strncpy(n2a, name, len);
strncat(n2a, ext, len - strlen(n2a));
printf("%s\n", n2a);
return 0; // this exits, otherwise free n2 && n2a
}
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
I found a simple solution without using JQuery and using CSS only.
You have to put the fixed contents inside 'th' tags and add the CSS
table th {
position:sticky;
top:0;
z-index:1;
border-top:0;
background: #ededed;
}
The position, z-index and top properties are enough. But you can apply the rest to give for a better view.
You can use:
mpstat -P ALL 1
It shows how much each core is busy and it updates automatically each second. The output would be something like this (on a quad-core processor):
10:54:41 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle
10:54:42 PM all 8.20 0.12 0.75 0.00 0.00 0.00 0.00 0.00 90.93
10:54:42 PM 0 24.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 74.00
10:54:42 PM 1 22.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 76.00
10:54:42 PM 2 2.02 1.01 0.00 0.00 0.00 0.00 0.00 0.00 96.97
10:54:42 PM 3 2.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 98.00
10:54:42 PM 4 14.15 0.00 1.89 0.00 0.00 0.00 0.00 0.00 83.96
10:54:42 PM 5 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 99.00
10:54:42 PM 6 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
10:54:42 PM 7 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
This command doesn't answer original question though i.e. it does not show CPU core usage for a specific process.
Alternatively, if you want to solely obtain the current directory of the current NodeJS script, you could try something simple like this. Note that this will not work in the Node CLI itself:
var fs = require('fs'),
path = require('path');
var dirString = path.dirname(fs.realpathSync(__filename));
// output example: "/Users/jb/workspace/abtest"
console.log('directory to start walking...', dirString);
this should work
update table_name
set column_b = case
when column_a = 1 then 'Y'
else null
end,
set column_c = case
when column_a = 2 then 'Y'
else null
end,
set column_d = case
when column_a = 3 then 'Y'
else null
end
where
conditions
the question is why would you want to do that...you may want to rethink the data model. you can replace null
with whatever you want.
Actually, the question of throwing IllegalArgumentException or NullPointerException is in my humble view only a "holy war" for a minority with an incomlete understanding of exception handling in Java. In general, the rules are simple, and as follows:
There are at least three very good reasons against the case of mapping all kinds of argument constraint violations to IllegalArgumentException, with the third probably being so severe as to mark the practice bad style:
(1) A programmer cannot a safely assume that all cases of argument constraint violations result in IllegalArgumentException, because the large majority of standard classes use this exception rather as a wastebasket if there is no more specific kind of exception available. Trying to map all cases of argument constraint violations to IllegalArgumentException in your API only leads to programmer frustration using your classes, as the standard libraries mostly follow different rules that violate yours, and most of your API users will use them as well!
(2) Mapping the exceptions actually results in a different kind of anomaly, caused by single inheritance: All Java exceptions are classes, and therefore support single inheritance only. Therefore, there is no way to create an exception that is truly say both a NullPointerException and an IllegalArgumentException, as subclasses can only inherit from one or the other. Throwing an IllegalArgumentException in case of a null argument therefore makes it harder for API users to distinguish between problems whenever a program tries to programmatically correct the problem, for example by feeding default values into a call repeat!
(3) Mapping actually creates the danger of bug masking: In order to map argument constraint violations into IllegalArgumentException, you'll need to code an outer try-catch within every method that has any constrained arguments. However, simply catching RuntimeException in this catch block is out of the question, because that risks mapping documented RuntimeExceptions thrown by libery methods used within yours into IllegalArgumentException, even if they are no caused by argument constraint violations. So you need to be very specific, but even that effort doesn't protect you from the case that you accidentally map an undocumented runtime exception of another API (i.e. a bug) into an IllegalArgumentException of your API. Even the most careful mapping therefore risks masking programming errors of other library makers as argument constraint violations of your method's users, which is simply hillareous behavior!
With the standard practice on the other hand, the rules stay simple, and exception causes stay unmasked and specific. For the method caller, the rules are easy as well: - if you encounter a documented runtime exception of any kind because you passed an illegal value, either repeat the call with a default (for this specific exceptions are neccessary), or correct your code - if on the other hand you enccounter a runtime exception that is not documented to happen for a given set of arguments, file a bug report to the method's makers to ensure that either their code or their documentation is fixed.
Preflight is a web security feature implemented by the browser. For Chrome you can disable all web security by adding the --disable-web-security flag.
For example: "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\newChromeSettingsWithoutSecurity" . You can first create a new shortcut of chrome, go to its properties and change the target as above. This should help!
Your method must read byte by byte and fully understand and appreciate the byte wise construction of characters. The simplest method is to use an editor which will read anything but only output UTF-8 characters. Textpad is one choice.
Have a look at git bup which is a Git extension to smartly store large binaries in a Git repository.
You'd want to have it as a submodule, but you won't have to worry about the repository getting hard to handle. One of their sample use cases is storing VM images in Git.
I haven't actually seen better compression rates, but my repositories don't have really large binaries in them.
Your mileage may vary.
var customView = UIView()
@IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
If finding the minimum is a one time thing, just iterate through the list and find the minimum.
If finding the minimum is a very common thing and you only need to operate on the minimum, use a Heap data structure.
A heap will be faster than doing a sort on the list but the tradeoff is you can only find the minimum.
You can use Phantombuster. Instagram has set some rate limit, so you will have to use either multiple accounts or wait for 15 minutes for the next run.
You can write if, else if, else
statements in short form. For example:
Boolean isCapital = city.isCapital(); //Object Boolean (not boolean)
String isCapitalName = isCapital == null ? "" : isCapital ? "Capital" : "City";
This is short form of:
Boolean isCapital = city.isCapital();
String isCapitalName;
if(isCapital == null) {
isCapitalName = "";
} else if(isCapital) {
isCapitalName = "Capital";
} else {
isCapitalName = "City";
}
var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
Example: http://jsfiddle.net/e27r8/
This uses the closest()
[docs] method to get the first ancestor that has a nested h3 span b
, then does a .find()
.
Of course you could have multiple matches.
Otherwise, you're looking at doing a more direct traversal.
var link = $("#me").closest("h3 + div").prev().find('span b');
edit: This one works with your updated HTML.
Example: http://jsfiddle.net/e27r8/2/
EDIT: Updated to deal with updated question.
var link = $("#me").closest("h3 + *").prev().find('span b');
This makes the targeted element for .closest()
generic, so that even if there is no parent, it will still work.
Example: http://jsfiddle.net/e27r8/4/
For local access, large numbers of directories/files doesn't seem to be an issue. However, if you're accessing it across a network, there's a noticeable performance hit after a few hundred (especially when accessed from Vista machines (XP to Windows Server w/NTFS seemed to run much faster in that regard)).
i installed from source. there is a step-by-step tutorial here: http://golang.org/doc/install/source
sc.next().charat(0).........is the method of entering character by user based on the number entered at the run time
example: sc.next().charat(2)------------>>>>>>>>
you can also check by
ps -ef |grep -i ora
This has been changed since v32, thanks to @Daniel Alexiuc & @Thanatos for their comments.
Current (= v32)
At the top of the "Network" tab of DevTools, there's a checkbox to switch on the "Preserve log" functionality. If it is checked, the network log is preserved on page load.
The little red dot on the left now has the purpose to switch network logging on and off completely.
Older versions
In older versions of Chrome (v21 here), there's a little, clickable red dot in the footer of the "Network" tab.
If you hover over it, it will tell you, that it will "Preserve Log Upon Navigation" when it is activated. It holds the promise.
I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
CheckBox optSingleShot;
Button btnStart, btnCancel;
TextView textCounter;
Timer timer;
MyTimerTask myTimerTask;
int tobeShown = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
optSingleShot = (CheckBox)findViewById(R.id.singleshot);
btnStart = (Button)findViewById(R.id.start);
btnCancel = (Button)findViewById(R.id.cancel);
textCounter = (TextView)findViewById(R.id.counter);
tobeShown = 1;
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
btnStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
/*if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}*/
}});
btnCancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (timer!=null){
timer.cancel();
timer = null;
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
}
@Override
protected void onPause() {
super.onPause();
if (timer!=null){
timer.cancel();
timer = null;
}
}
@Override
protected void onStop() {
super.onStop();
if (timer!=null){
timer.cancel();
timer = null;
}
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
}
}
}
You can't modify the references in an enumerator whilst you enumerate over it; you must keep track of the ones to remove then remove them.
This is an example of the work around:
List<string> listbox = new List<string>();
List<object> toRemove = new List<object>();
foreach (string item in listbox)
{
string removelistitem = "OBJECT";
if (item.Contains(removelistitem))
{
toRemove.Add(item);
}
}
foreach (string item in toRemove)
{
listbox.Remove(item);
}
But if you're using c#3.5, you could say something like this.
listbox.Items = listbox.Items.Select(n => !n.Contains("OBJECT"));
you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java
For Windows 8 client computers, turn on "IIS-ASPNET45" in "Turn Windows Features On/Off" under "Internet Information Services-> World Wide Web Services -> Application Development Features -> ASP.NET 4.5".
This approach is without using
max()
function
a = [1,2,3,4,6,7,99,88,999]
max_num = 0
for i in a:
if i > max_num:
max_num = i
print(max_num)
Also if you want to find the index of the resulting max,
print(a.index(max_num))
Direct approach by using function max()
max() function returns the item with the highest value, or the item with the highest value in an iterable
Example: when you have to find max on integers/numbers
a = (1, 5, 3, 9)
print(max(a))
>> 9
Example: when you have string
x = max("Mike", "John", "Vicky")
print(x)
>> Vicky
It basically returns the name with the highest value, ordered alphabetically.
It's possible, but it depends on the power output of the beacon you're receiving, other rf sources nearby, obstacles and other environmental factors. Best thing to do is try it out in the environment you're interested in.
You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name
According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.
"Release 0.8.7 - May 13 2016
-Fix for issue when inserting read-only images on Windows. Issue #352.
-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.
-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."
Two solutions that spring to mind:
order by case id when 123 then 1 when 456 then 2 else null end asc
order by instr(','||id||',',',123,456,') asc
(instr()
is from Oracle; maybe you have locate()
or charindex()
or something like that)
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
we can use requestAnimationFrame to reset animation and reverse it when browser paints in next frame.
Also use onmouseenter and onmouseout event handlers to reverse animation direction
Any rAFs queued in your event handlers will be executed in the ?same frame?. Any rAFs queued in a rAF will be executed in the next frame?.
function fn(el, isEnter) {_x000D_
el.className = "";_x000D_
requestAnimationFrame(() => {_x000D_
requestAnimationFrame(() => {_x000D_
el.className = isEnter? "in": "out";_x000D_
});_x000D_
}); _x000D_
}
_x000D_
.in{_x000D_
animation: k 1s forwards;_x000D_
}_x000D_
_x000D_
.out{_x000D_
animation: k 1s forwards;_x000D_
animation-direction: reverse;_x000D_
}_x000D_
_x000D_
@keyframes k_x000D_
{_x000D_
from {transform: rotate(0deg);}_x000D_
to {transform: rotate(360deg);}_x000D_
}
_x000D_
<div style="width:100px; height:100px; background-color:red" _x000D_
onmouseenter="fn(this, true)"_x000D_
onmouseleave="fn(this, false)" _x000D_
></div>
_x000D_
There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.
Specifically, you are not validating the user input for creditPlan
- if the user enters a value of anything else than "0","1","2" or "3"
, then none of the branches indicated will be executed (and creditPlan
will not be defaulted to zero as per your user prompt).
As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else
statement).
I would however like to point out other potential improvements:
CreditPlan
appears to have a finite domain and is better suited to an enumeration
or Dictionary
than a string
. Financial data and percentages should always be modelled as decimal
, not double
to avoid rounding issues, and 'status' appears to be a boolean.monthlyCharge = balance * annualRate * (1/12))
is common to more than one branch. For maintenance reasons, do not duplicate this code.e.g. here is an alternative representation of your model:
// Keep all Credit Plan parameters together in a model
public class CreditPlan
{
public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
public decimal AnnualRate { get; set; }
public Func<bool, Decimal> LateFee { get; set; }
}
// DRY up repeated calculations
static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
{
return balance * annualRate / 12;
}
public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
{
{ 0, new CreditPlan
{
AnnualRate = .35M,
LateFee = _ => 0.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 1, new CreditPlan
{
AnnualRate = .30M,
LateFee = late => late ? 0 : 25.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 2, new CreditPlan
{
AnnualRate = .20M,
LateFee = late => late ? 0 : 35.0M,
MonthlyCharge = (balance, annualRate) => balance > 100
? balance * annualRate / 12
: 0
}
},
{ 3, new CreditPlan
{
AnnualRate = .15M,
LateFee = _ => 0.0M,
MonthlyCharge = (balance, annualRate) => balance > 500
? (balance - 500) * annualRate / 12
: 0
}
}
};
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push()
method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form
, however you don't have a form on the page. In order for this to work you would need to have <form>
tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick
attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert()
function uses the references to each input field to get their value. It then uses the push()
method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow()
function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value
property of each input to an empty string. It then clears out the .innerHTML
of our message box. Lastly, it calls the join()
method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
Yes. You know that you can put any Object
into the Object
parameter of most JOptionPane.showXXX methods
, and often that Object
happens to be a JPanel
.
In your situation, perhaps you could use a JPanel
that has several JTextFields
in it:
import javax.swing.*;
public class JOptionPaneMultiInput {
public static void main(String[] args) {
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("x:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("y:"));
myPanel.add(yField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("x value: " + xField.getText());
System.out.println("y value: " + yField.getText());
}
}
}
Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.
Type in console as root:
apt-get update && apt-get install php5-curl
or with sudo:
sudo apt-get update && sudo apt-get install php5-curl
Sorry I missread.
1st, check your DNS config and if you can ping any host at all,
ping google.com
ping zm.archive.ubuntu.com
If it does not work, check /etc/resolv.conf
or /etc/network/resolv.conf
, if not, change your apt-source to a different one.
/etc/apt/sources.list
Mirrors: http://www.debian.org/mirror/list
You should not use Ubuntu sources on Debian and vice versa.
I had content that was longer than the dialog. On open, the dialog would scoll to the first :tabbable which was at the bottom. Here was my fix.
$("#myDialog").dialog({
...
open: function(event, ui) { $(this).scrollTop(0); }
});
I have done it!
private void openWhatsApp() {
String smsNumber = "7****"; // E164 format without '+' sign
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
sendIntent.setPackage("com.whatsapp");
if (intent.resolveActivity(getActivity().getPackageManager()) == null) {
Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
return;
}
startActivity(sendIntent);
}
Here is the Hooks solution
import React, {useRef} from 'react';
const MyComponent = () =>{
const myRefname= useRef(null);
const handleClick = () => {
myRefname.current.focus();
}
return (
<div onClick={handleClick}>
<input ref={myRefname}/>
</div>
);
}
I'm going to push my pet peeve: the USING keyword.
If both tables on both sides of the JOIN have their foreign keys properly named (ie, same name, not just "id) then this can be used:
SELECT ...
FROM customers JOIN orders USING (customer_id)
I find this very practical, readable, and not used often enough.
I think of return
as a trick. As a general rule, the value of the last expression evaluated in a function becomes the function's value -- and this general pattern is found in many places. All of the following evaluate to 3:
local({
1
2
3
})
eval(expression({
1
2
3
}))
(function() {
1
2
3
})()
What return
does is not really returning a value (this is done with or without it) but "breaking out" of the function in an irregular way. In that sense, it is the closest equivalent of GOTO statement in R (there are also break and next). I use return
very rarely and never at the end of a function.
if(a) {
return(a)
} else {
return(b)
}
... this can be rewritten as if(a) a else b
which is much better readable and less curly-bracketish. No need for return
at all here. My prototypical case of use of "return" would be something like ...
ugly <- function(species, x, y){
if(length(species)>1) stop("First argument is too long.")
if(species=="Mickey Mouse") return("You're kidding!")
### do some calculations
if(grepl("mouse", species)) {
## do some more calculations
if(species=="Dormouse") return(paste0("You're sleeping until", x+y))
## do some more calculations
return(paste0("You're a mouse and will be eating for ", x^y, " more minutes."))
}
## some more ugly conditions
# ...
### finally
return("The end")
}
Generally, the need for many return's suggests that the problem is either ugly or badly structured.
[EDIT]
return
doesn't really need a function to work: you can use it to break out of a set of expressions to be evaluated.
getout <- TRUE
# if getout==TRUE then the value of EXP, LOC, and FUN will be "OUTTA HERE"
# .... if getout==FALSE then it will be `3` for all these variables
EXP <- eval(expression({
1
2
if(getout) return("OUTTA HERE")
3
}))
LOC <- local({
1
2
if(getout) return("OUTTA HERE")
3
})
FUN <- (function(){
1
2
if(getout) return("OUTTA HERE")
3
})()
identical(EXP,LOC)
identical(EXP,FUN)
Windows has a concept of current directory for each drive. Because of that, "c:sourcedir"
means "sourcedir" inside the current C: directory, and you'll need to specify an absolute directory.
Any of these should work and give the same result, but I don't have a Windows VM fired up at the moment to double check:
"c:/sourcedir"
os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")
If it is an update on a table all you have to do is run this update multiple times until it is affecting 0 rows.
update tableName
set colName = REPLACE(LTRIM(RTRIM(colName)), ' ', ' ')
where colName like '% %'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server_IP,22,username, password)
stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol-CXC_173_6456-R32A01/uecontrol.sh -host localhost ')
alldata = ""
while not stdout.channel.exit_status_ready():
solo_line = ""
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
solo_line = stdout.channel.recv(1024)
alldata += solo_line
if(cmp(solo_line,'uec> ') ==0 ): #Change Conditionals to your code here
if num_of_input == 0 :
data_buffer = ""
for cmd in commandList :
#print cmd
stdin.channel.send(cmd) # send input commmand 1
num_of_input += 1
if num_of_input == 1 :
stdin.channel.send('q \n') # send input commmand 2 , in my code is exit the interactive session, the connect will close.
num_of_input += 1
print alldata
ssh.close()
Why the stdout.read() will hang if use dierectly without checking stdout.channel.recv_ready(): in while stdout.channel.exit_status_ready():
For my case ,after run command on remote server , the session is waiting for user input , after input 'q' ,it will close the connection . But before inputting 'q' , the stdout.read() will waiting for EOF,seems this methord does not works if buffer is larger .
Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):
Improved code, using return value of Set#add
instead of comparing the size of list and set.
public static <T> boolean hasDuplicate(Iterable<T> all) {
Set<T> set = new HashSet<T>();
// Set#add returns false if the set does not change, which
// indicates that a duplicate element has been added.
for (T each: all) if (!set.add(each)) return true;
return false;
}
FWIW, here is my approach = a simple one that works for me:
<div id="outerDivWrapper">
<div id="outerDiv">
<div id="scrollableContent">
blah blah blah
</div>
</div>
</div>
html, body {
height: 100%;
margin: 0em;
}
#outerDivWrapper, #outerDiv {
height: 100%;
margin: 0em;
}
#scrollableContent {
height: 100%;
margin: 0em;
overflow-y: auto;
}
SQLAlchemy users can simply specify their field as convert_unicode=True
.
Example:
sqlalchemy.String(1000, convert_unicode=True)
SQLAlchemy will simply accept unicode objects and return them back, handling the encoding itself.
The CMake command target_compile_features()
is used to specify the required C++ feature cxx_range_for
. CMake will then induce the C++ standard to be used.
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(foobar CXX)
add_executable(foobar main.cc)
target_compile_features(foobar PRIVATE cxx_range_for)
There is no need to use add_definitions(-std=c++11)
or to modify the CMake variable CMAKE_CXX_FLAGS
, because CMake will make sure the C++ compiler is invoked with the appropriate command line flags.
Maybe your C++ program uses other C++ features than cxx_range_for
. The CMake global property CMAKE_CXX_KNOWN_FEATURES
lists the C++ features you can choose from.
Instead of using target_compile_features()
you can also specify the C++ standard explicitly by setting the CMake properties
CXX_STANDARD
and
CXX_STANDARD_REQUIRED
for your CMake target.
See also my more detailed answer.
If you dont have access to your webserver config, you can also just RENAME the font file so that it ends in svg (but retain the format). Works fine for me in Chrome and Firefox.
In my personal opinion trailing slashes are misused.
Basically the URL format came from the same UNIX format of files and folders, later on, on DOS systems, and finally, adapted for the web.
A typical URL for this book on a Unix-like operating system would be a file path such as file:///home/username/RomeoAndJuliet.pdf, identifying the electronic book saved in a file on a local hard disk.
Source: Wikipedia: Uniform Resource Identifier
Another good source to read: Wikipedia: URI Scheme
According to RFC 1738, which defined URLs in 1994, when resources contain references to other resources, they can use relative links to define the location of the second resource as if to say, "in the same place as this one except with the following relative path". It went on to say that such relative URLs are dependent on the original URL containing a hierarchical structure against which the relative link is based, and that the ftp, http, and file URL schemes are examples of some that can be considered hierarchical, with the components of the hierarchy being separated by "/".
Source: Wikipedia Uniform Resource Locator (URL)
Also:
That is the question we hear often. Onward to the answers! Historically, it’s common for URLs with a trailing slash to indicate a directory, and those without a trailing slash to denote a file:
http://example.com/foo/ (with trailing slash, conventionally a directory)
http://example.com/foo (without trailing slash, conventionally a file)
Source: Google WebMaster Central Blog - To slash or not to slash
Finally:
A slash at the end of the URL makes the address look "pretty".
A URL without a slash at the end and without an extension looks somewhat "weird".
You will never name your CSS file (for example) http://www.sample.com/stylesheet/ would you?
BUT I'm being a proponent of web best practices regardless of the environment. It can be wonky and unclear, just as you said about the URL with no ext.
The Heap is divided into young and old generations as follows :
Young Generation : It is place where lived for short period and divided into two spaces:
Old Generation : This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from Young Generation.
Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.
Java8 Update: PermGen is replaced with Metaspace which is very similar.
Main difference is that Metaspace re-sizes dynamically i.e., It can expand at runtime.
Java Metaspace space: unbounded (default)
Code Cache (Virtual or reserved) : If you are using HotSpot Java VM this includes code cache area that containing memory which will be used for compilation and storage of native code.
The default sort is stable, so we sort twice: First by the minor key, then by the major key
rum1 <- rum[order(rum$I2, decreasing = FALSE),]
rum2 <- rum1[order(rum1$I1, decreasing = TRUE),]
SELECT
object_name(parent_object_id),
object_name(referenced_object_id),
name
FROM sys.foreign_keys
WHERE parent_object_id = object_id('Table Name')
If it happens, then it means you have to upgrade your node.js. Simply uninstall your current node from your pc or mac and download the latest version from https://nodejs.org/en/
ES5 solution can be:
// for enumerable and non-enumerable properties
Object.getOwnPropertyNames(obj).forEach(function (prop) {
delete obj[prop];
});
And ES6 solution can be:
// for enumerable and non-enumerable properties
for (const prop of Object.getOwnPropertyNames(obj)) {
delete obj[prop];
}
Regardless of the specs, the quickest solutions will generally be:
// for enumerable and non-enumerable of an object with proto chain
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
delete obj[props[i]];
}
// for enumerable properties of shallow/plain object
for (var key in obj) {
// this check can be safely omitted in modern JS engines
// if (obj.hasOwnProperty(key))
delete obj[key];
}
The reason why for..in
should be performed only on shallow or plain object is that it traverses the properties that are prototypically inherited, not just own properties that can be deleted. In case it isn't known for sure that an object is plain and properties are enumerable, for
with Object.getOwnPropertyNames
is a better choice.
Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like
INSERT INTO HISTORICAL_CAR_STATS (
HISTORICAL_CAR_STATS_ID,
YEAR,
MONTH,
MAKE,
MODEL,
REGION,
AVG_MSRP,
CNT)
SELECT MY_SEQ.nextval,
year,
month,
make,
model,
region,
avg_msrp,
cnt
FROM (SELECT '2010' year,
'12' month,
'ALL' make,
'ALL' model,
REGION,
sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
sum(cnt) cnt
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010'
AND MONTH = '12'
AND MAKE != 'ALL'
GROUP BY REGION)
The fact that you're using a view model has no bearing. The standard way of using PagedList
is to store "one page of items" as a ViewBag
variable. All you have to determine is what collection constitutes what you'll be paging over. You can't logically page multiple collections at the same time, so assuming you chose Instructors
:
ViewBag.OnePageOfItems = myViewModelInstance.Instructors.ToPagedList(pageNumber, 10);
Then, the rest of the standard code works as it always has.
you can define attribute selected="selected" in Ex a
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
}
//removed the method call from the first sql server using statement
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//create parameters
}
}
You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).
Consider how your application should respond to various cases.
The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.
Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.
Syntax error, remove the ( )
from select
.
insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;
In some devices void onConfigurationChanged()
may crash. User will use this code to get current screen orientation.
public int getScreenOrientation()
{
Display getOrient = getActivity().getWindowManager().getDefaultDisplay();
int orientation = Configuration.ORIENTATION_UNDEFINED;
if(getOrient.getWidth()==getOrient.getHeight()){
orientation = Configuration.ORIENTATION_SQUARE;
} else{
if(getOrient.getWidth() < getOrient.getHeight()){
orientation = Configuration.ORIENTATION_PORTRAIT;
}else {
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
return orientation;
}
And use
if (orientation==1) // 1 for Configuration.ORIENTATION_PORTRAIT
{ // 2 for Configuration.ORIENTATION_LANDSCAPE
//your code // 0 for Configuration.ORIENTATION_SQUARE
}
I think this comes closest to what you wish:
(From IntelliJ IDEA Q&A for Eclipse Users):
The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.
Things to do:
Switch to 'Problems' view in the Project pane:
Enable the setting to compile the project automatically :
Finally, look at the Problems view:
Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler:
Relevant Links:
The maven project shown above : https://github.com/ajorpheus/CompileTimeErrors
FAQ For 'Eclipse Mode' / 'Automatically Compile' a project : http://devnet.jetbrains.com/docs/DOC-1122
here it is, obtaining a reference to the coresponding pointer of an iterator use :
example:
string my_str= "hello world";
string::iterator it(my_str.begin());
char* pointer_inside_buffer=&(*it); //<--
[notice operator * returns a reference so doing & on a reference will give you the address].
You could try:
.modal.modal-wide .modal-dialog {
width: 90%;
}
.modal-wide .modal-body {
overflow-y: auto;
}
Just add .modal-wide to your classes
In this case you can use a === undefined
comparison: if(val === undefined)
This works because val
always exists (it's a function argument).
If you wanted to test an arbitrary variable that is not an argument, i.e. might not be defined at all, you'd have to use if(typeof val === 'undefined')
to avoid an exception in case val
didn't exist.
This will take care of the empty td:
<td style="min-width: 20px;"></td>
Something like this should do the trick (However, read after the snippet for more info)
CREATE PROCEDURE GetFilteredData()
BEGIN
DECLARE bDone INT;
DECLARE var1 CHAR(16); -- or approriate type
DECLARE Var2 INT;
DECLARE Var3 VARCHAR(50);
DECLARE curs CURSOR FOR SELECT something FROM somewhere WHERE some stuff;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TEMPORARY TABLE IF EXISTS tblResults;
CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
--Fld1 type,
--Fld2 type,
--...
);
OPEN curs;
SET bDone = 0;
REPEAT
FETCH curs INTO var1,, b;
IF whatever_filtering_desired
-- here for whatever_transformation_may_be_desired
INSERT INTO tblResults VALUES (var1, var2, var3 ...);
END IF;
UNTIL bDone END REPEAT;
CLOSE curs;
SELECT * FROM tblResults;
END
A few things to consider...
Concerning the snippet above:
More generally: trying to avoid needing a cursor.
I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.
Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.
This is called the "shape" in NumPy, and can be requested via the .shape
attribute:
>>> a = zeros((2, 5))
>>> a.shape
(2, 5)
If you prefer a function, you could also use numpy.shape(a)
.
It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:
def addstudent():
print("Student Added.")
then called by writing addstudent()
.
I would recommend using a while
loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked)
, then put the if statements after the while. Or you can do a while
loop and continue
the loop if a valid option is not selected.
Additionally, a dictionary is defined in the following way:
my_dict = {key:definition,...}
The accepted answer is invalid with the double EXEC (only need the first EXEC):
DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue
And you still need to call PRINT (at least in Visual Studio).
Use window.open()
:
<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
Share Page
</a>
This will create a link titled Share Page
which opens the current url in a new window with a height of 570 and width of 520.
You can send Email by Jquery just follow these steps
include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :
$( document ).ready(function() {
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});
Figured this out with the help of a friend. The -m
PuTTY option will end your session immediately after it executes the shell file. What I've done instead is I've created a batch script called putty.bat
with these contents on my Windows machine:
@echo off
putty -load "host" -l username -pw password
This logs me in remotely to the Linux host. On the host side, I created a shell file called sql
with these contents:
#!/bin/tcsh
add oracle10g
sqlplus username password
My host's Linux build used tcsh
. Other Linux builds might use bash
, so simply replace tcsh with bash and you should be fine.
To summarize, automating these steps are now done in two easy steps:
putty.bat
. This opens PuTTY and logs me into the host.tcsh sql
. This adds the oracle tool to my host, and logs me into the sql database.In your case, $scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue);
does the trick - it makes both the form and the field dirty, and appends appropriate CSS classes.
Just to be honest, I found this solution in new post in the topic from the link from your question. It worked perfectly for me, so I am putting this here as a standalone answer to make it easier to be found.
EDIT:
Above solution works best for Angular version up to 1.3.3. Starting with 1.3.4 you should use newly exposed API method $setDirty()
from ngModel.NgModelController
.
This occurs typically when the stmt is reused butexpecting a different ResultSet, try creting a new stmt and executeQuery. It fixed it for me!
Your code is fine. There's no problem with returning Strings
in this manner.
In Java, a String
is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String
around without worrying that it would disapper on you, or that someone somewhere would modify it.
If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:
public String time_to_string(long t) // time in milliseconds
{
if (t < 0)
{
return "-";
}
else
{
int secs = (int)(t/1000);
int mins = secs/60;
secs = secs - (mins * 60);
return String.format("%d:%02d", mins, secs);
}
}
As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans
and have replaced the mix of string concatenation and String.format()
with a single call to String.format()
.
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});
You need to pass the values of the dict into the Bike
constructor before using like that. Or, see the namedtuple
-- seems more in line with what you're trying to do.
What I've done in this case is, in the primary jframe that I want to keep visible (for example, a menu frame), I deselect the option focusableWindowState
in the property window so It will be FALSE
. Once that is done, the jframes I call don´t lose focus until I close them.
If you just need the current date, without time, another option is:
DateTime.now().withTimeAtStartOfDay()
Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.
Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.
Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.
Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.
I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.
I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.
(I thought it might be helpful to lay out the ideas very simply here to summarize the good material posted by @doug, & linked by @duffymo; +1 to each,btw.)
?order tells you which element of the original vector needs to be put first, second, etc., so as to sort the original vector, whereas ?rank tell you which element has the lowest, second lowest, etc., value. For example:
> a <- c(45, 50, 10, 96)
> order(a)
[1] 3 1 2 4
> rank(a)
[1] 2 3 1 4
So order(a)
is saying, 'put the third element first when you sort... ', whereas rank(a)
is saying, 'the first element is the second lowest... '. (Note that they both agree on which element is lowest, etc.; they just present the information differently.) Thus we see that we can use order()
to sort, but we can't use rank()
that way:
> a[order(a)]
[1] 10 45 50 96
> sort(a)
[1] 10 45 50 96
> a[rank(a)]
[1] 50 10 45 96
In general, order()
will not equal rank()
unless the vector has been sorted already:
> b <- sort(a)
> order(b)==rank(b)
[1] TRUE TRUE TRUE TRUE
Also, since order()
is (essentially) operating over ranks of the data, you could compose them without affecting the information, but the other way around produces gibberish:
> order(rank(a))==order(a)
[1] TRUE TRUE TRUE TRUE
> rank(order(a))==rank(a)
[1] FALSE FALSE FALSE TRUE
getElementById
returns a single object for which you can specify the style.So, the above explanation is correct.
getElementsByTagName
returns multiple objects(array of objects and properties) for which we cannot apply the style directly.
You can use pydoc
.
Open your terminal and type python -m pydoc list.append
The advantage of pydoc
over help()
is that you do not have to import a module to look at its help text.
For instance python -m pydoc random.randint
.
Also you can start an HTTP server to interactively browse documentation by typing python -m pydoc -b
(python 3)
For more information python -m pydoc
I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.
But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.
import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
names = 0
values = 1
array = np.empty(shape=(2, len(result)), dtype=float)
array[names] = result.keys()
array[values] = result.values()
But my favorite is this (simpler):
import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
arrays = {'names': np.array(result.keys(), dtype=float),
'values': np.array(result.values(), dtype=float)}
Use x.fullNameMethod()
to call the method.
Now, in Django 1.9 you have first()
method for querysets.
YourModel.objects.all().first()
This is a better way than .get()
or [0]
because it does not throw an exception if queryset is empty, Therafore, you don't need to check using exists()
Very simple. Create a span for the text, get the width and reduce font-size until the span has the same width of the div container:
while($("#container").find("span").width() > $("#container").width()) {
var currentFontSize = parseInt($("#container").find("span").css("font-size"));
$("#container").find("span").css("font-size",currentFontSize-1);
}
You have to use Appcompat
library for that. Which is used like below:
dashboard.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:title="Search"/>
</menu>
Activity file (in Java):
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.dashboard, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
}
return super.onCreateOptionsMenu(menu);
}
Activity file (in Kotlin):
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search, menu)
val searchItem: MenuItem? = menu?.findItem(R.id.action_search)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView: SearchView? = searchItem?.actionView as SearchView
searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
return super.onCreateOptionsMenu(menu)
}
manifest file:
<meta-data
android:name="android.app.default_searchable"
android:value="com.apkgetter.SearchResultsActivity" />
<activity
android:name="com.apkgetter.SearchResultsActivity"
android:label="@string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
searchable xml file:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:label="@string/app_name" />
And at last, your SearchResultsActivity
class code. for showing result of your search.
The title of this thread asks how a subquery can be used in an update. Here's an example of that:
update [dbName].[dbo].[MyTable]
set MyColumn = 1
where
(
select count(*)
from [dbName].[dbo].[MyTable] mt2
where
mt2.ID > [dbName].[dbo].[MyTable].ID
and mt2.Category = [dbName].[dbo].[MyTable].Category
) > 0
Just Add Another Issue:
If you want to remove /public
from your project using .htaccess
,
then you can use this, [Add public
before /css
inside asset()
]
<link href="{{ asset('public/css/app.css') }}" rel="stylesheet">
[Sometimes, it is useful.]
Assuming you just want everything before \n
(or any other literal string/char), you should use indexOf()
with substring()
:
result = result.substring(0, result.indexOf('\n'));
If you want to extract the portion before a certain regular expression, you can use split()
:
result = result.split(regex, 2)[0];
String result = "34.1 -118.33\n<!--ABCDEFG-->";
System.out.println(result.substring(0, result.indexOf('\n')));
System.out.println(result.split("\n", 2)[0]);
34.1 -118.33 34.1 -118.33
(Obviously \n
isn't a meaningful regular expression, I just used it to demonstrate that the second approach also works.)
It appears I cannot use an if statement.
Arrow functions either allow to use an expression or a block as their body. Passing an expression
foo => bar
is equivalent to the following block
foo => { return bar; }
However,
if (person.age > 18) person
is not an expression, if
is a statement. Hence you would have to use a block, if you wanted to use if
in an arrow function:
foo => { if (person.age > 18) return person; }
While that technically solves the problem, this a confusing use of .filter
, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter
should return a Boolean, i.e. true
or false
, indicating whether the element should be included in the new array or not.
So all you need is
family.filter(person => person.age > 18);
In ES5:
family.filter(function (person) {
return person.age > 18;
});
For all smartphones and large screens use this format of media query
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
Just my 2 cents, had:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
at the end of body, wasn't working, had to add crossorigin="anonymous"
and now it's working, Bootstrap version 3.3.6. ...
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True
Out of curiosity, some comparative timing:
>>> T(lambda : 'one' in d.itervalues()).repeat()
[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]
>>> T(lambda : 'one' in d.values()).repeat()
[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]
>>> T(lambda : 'one' in d.viewvalues()).repeat()
[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]
EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:
>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>
EDIT2: As per request in comments...
>>> T(lambda : 'four' in d.itervalues()).repeat()
[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]
>>> T(lambda : 'four' in d.values()).repeat()
[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]
>>> T(lambda : 'four' in d.viewvalues()).repeat()
[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]
I agree with Als that you can not initialize at time of defining the structure in C. But you can initialize the structure at time of creating instance shown as below.
In C,
struct s {
int i;
int j;
};
struct s s_instance = { 10 ,20 };
in C++ its possible to give direct value in definition of structure shown as below
struct s {
int i;
s(): i(10)
{
}
};
If you do not have to sign the app, right click on your project
Project Properties -> Signing -> uncheck "Sign the ClickOnce Manifest"
Also as this MS article suggests,
If you are using Visual Studio 2008 and are targeting .NET 3.5 and using automatic updates, you can just change the certificate and deploy a new version,
You should probably check for errors in /var/log/nginx/error.log
.
In my case I did no add the port for ipv6. You should also do this (in case you are running nginx on a port other than 80):
listen [::]:8000 default_server ipv6only=on;
You need to specify the width
and height
in px
:
width: 10px; height: 10px;
In addition, you can use overflow: auto;
to prevent the horizontal scrollbar from showing.
Therefore, you may want to try the following:
<div style="width:100px; height:100px; overflow: auto;" >
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
</div>
You must have either disabled
, froze
or uninstalled
FaceProvider in settings>applications>all
This will only happen if it's frozen
, either uninstall
it, or enable
it.
If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before
//HTML
<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
<div class="morph-button morph-button-overlay morph-button-fixed">
<button id="user-interface" type="button">MORE INFO</button>
<!--a id="user-interface" href="javascript:void(0)">popup</a-->
<div class="morph-content">
<div>
<div class="content-style-overlay">
<span class="icon icon-close">Close the overlay</span>
<h2>About Parsley</h2>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
</div>
</div>
</div>
</div>
</div>
//CSS
/* Blur - doesn't work on IE */
.blur-on, .blur-element {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
-webkit-transition: all 5s linear;
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
.blur-off {
-webkit-filter: blur(0px) !important;
-moz-filter : blur(0px) !important;
-o-filter : blur(0px) !important;
-ms-filter : blur(0px) !important;
filter : blur(0px) !important;
}
.blur-bgimage:before {
content: "";
position: absolute;
height: 20%; width: 20%;
background-size: cover;
background: inherit;
z-index: -1;
transform: scale(5);
transform-origin: top left;
filter: blur(2px);
-moz-transform: scale(5);
-moz-transform-origin: top left;
-moz-filter: blur(2px);
-webkit-transform: scale(5);
-webkit-transform-origin: top left;
-webkit-filter: blur(2px);
-o-transform: scale(5);
-o-transform-origin: top left;
-o-filter: blur(2px);
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
//Javascript
function blurBehindPopup() {
if(blurredElements.length == 0) {
for(var i=0; i < document.body.children.length; i++) {
var element = document.body.children[i];
if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
classie.addClass( element, 'blur-element' );
blurredElements.push(element);
}
}
} else {
for(var i=0; i < blurredElements.length; i++) {
classie.addClass( blurredElements[i], 'blur-element' );
}
}
}
function unblurBehindPopup() {
for(var i=0; i < blurredElements.length; i++) {
classie.removeClass( blurredElements[i], 'blur-element' );
}
}
Actually, when you read docs the ListView should be inside Expanded Widget so it can work.
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Align(
child: PayableWidget(),
),
Expanded(
child: _myListView(context),
)
],
));
}
I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.
@GetMapping(value="/person/{id}/",
params="format=json",
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
Person person = personMapRepository.findPerson(id);
return ResponseEntity.ok(person);
}
@GetMapping(value="/person/{id}/",
params="format=xml",
produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
return GetPerson(id); // delegate
}
On Linux, the stat(1) command is useful when you don't need find(1):
(( $(stat -c %s "$filename") )) || rm "$filename"
The stat command here allows us just to get the file size, that's the -c %s
(see the man pages for other formats). I am running the stat program and capturing its output, that's the $( )
. This output is seen numerically, that's the outer (( ))
. If zero is given for the size, that is FALSE, so the second part of the OR is executed. Non-zero (non-empty file) will be TRUE, so the rm will not be executed.
Use media queries to separate each browser:
/* IE6/7 uses media, */
@media, {
.dude { color: green; }
.gal { color: red; }
}
/* IE8 uses \0 */
@media all\0 {
.dude { color: brown; }
.gal { color: orange; }
}
/* IE9 uses \9 */
@media all and (monochrome:0) {
.dude { color: yellow\9; }
.gal { color: blue\9; }
}
/* IE10 and IE11 both use -ms-high-contrast */
@media all and (-ms-high-contrast:none)
{
.foo { color: green } /* IE10 */
*::-ms-backdrop, .foo { color: red } /* IE11 */
}
References
You can use this two commands: tasklist
and netstat -oan
Tasklist.exe
is like taskmgr.exe
but in text mode.
With tasklist.exe
or taskmgr.exe
you can obtain a PID of sqlservr.exe
With netstat -oan
, it shows a connection PID, and you can filter it.
Example:
C:\>tasklist | find /i "sqlservr.exe"
sqlservr.exe 1184 Services 0 3.181.800 KB
C:\>netstat -oan | find /i "1184"
TCP 0.0.0.0:1280 0.0.0.0:0 LISTENING 1184
In this example, the SQLServer port is 1280
Extracted from: http://www.sysadmit.com/2016/03/mssql-ver-puerto-de-una-instancia.html
You can use axml2xml.pl tool developed a while ago within android-random project. It will generate the textual manifest file (AndroidManifest.xml) from the binary one.
I'm saying "textual" and not "original" because like many reverse-engineering tools this one isn't perfect and the result will not be complete. I presume either it was never feature complete or simply not forward-compatible (with newer binary encoding scheme). Whatever the reason, axml2xml.pl tool will not be able to extract all the attribute values correctly. Such attributes are minSdkVersion, targetSdkVersion and basically all attributes that are referencing resources (like strings, icons, etc.), i.e. only class names (of activities, services, etc.) are extracted correctly.
However, you can still find these missing information by running aapt tool on the original Android app file (.apk):
aapt l -a <someapp.apk>
you can use valign="top"
on the td tag it is working perfectly for me.
I think autocomplete=off
is supported in HTML 5.
Ask yourself why you want to do this though - it may make sense in some situations but don't do it just for the sake of doing it.
It's less convenient for users and not even a security issue in OS X (mentioned by Soren below). If you're worried about people having their passwords stolen remotely - a keystroke logger could still do it even though your app uses autcomplete=off
.
As a user who chooses to have a browser remember (most of) my information, I'd find it annoying if your site didn't remember mine.
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
self:: keyword used for the current class and basically it is used to access static members, methods, and constants. But in case of $this you cannot call the static member, method and functions.
You can use the self:: keyword in another class and access the static members, method and constants. When it will be extends from parent class and same in case of $this keyword. You can access the non static members, method and function in another class when it will be extends from parent class.
The code given below is a example of self:: and $this keyword. Just copy and paste the code in your code file and see the output.
class cars{
var $doors=4;
static $car_wheel=4;
public function car_features(){
echo $this->doors." Doors <br>";
echo self::$car_wheel." Wheels <br>";
}
}
class spec extends cars{
function car_spec(){
print(self::$car_wheel." Doors <br>");
print($this->doors." Wheels <br>");
}
}
/********Parent class output*********/
$car = new cars;
print_r($car->car_features());
echo "------------------------<br>";
/********Extend class from another class output**********/
$car_spec_show=new spec;
print($car_spec_show->car_spec());
looks to me yum install glibc.i686 should have worked. Unless Peter was not root. He has the 64 bit glib installed, he is installing a 32 bit package that requires the 32 bit glib which is glib.i686 for intel processors.
The String
class has a Replace
method that will do that.
Dim clean as String
clean = myString.Replace(",", "")
<div>
tags are always abused to create a web layout. Its symbolic purpose is to divide a section/portion in the page so that separate style can be added or applied to it. [w3schools Doc] [W3C]
some
and another
has.HTML5, has more logical meaning tags, instead of having plain layout tags. The section
, header
, nav
, aside
everything have their own semantic meaning to it. And are used against <div>
Use the command as
java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>
The above command will set the mentioned paths to classpath only once for executing the class named TestClass.
If you want to execute more then one classes, then you can follow this
set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"
After this you can execute as many classes as you want just by simply typing
java <your-class-name>
The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)
If you want to set the classpth only once so that it could work for everytime, then do as follows
1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
a. Variable Name- classpath
b. Variable Value- .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.
Remember this will work every time. You don't need to explicitly set the classpath again and again.
NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.
Hope this will help you.
HTML 5 allows summary tag, details element. That can be used to view or hide (collapse/expand) a section. Link
It's not really possible. You could, but if you're going to it would be useless without appropriate plugins. You'd be better using some other form. PDF's are used to have a consolidated output to printers and the screen, so animations won't work without other resources, and then it's not really a PDF.
You can also do:
start notepad "C:\Users\kemp\INSTALL\Text1.txt"
The C:\Users\kemp\Install\
is your PATH. The Text1.txt is the FILE.
Would √ (square root symbol, √) suffice?
Alternatively, ensure you're setting the Content-Type:
header before sending data to the browser. Merely specifying the <meta>
content-type tag may not be enough to encourage browsers to use the correct character set.
This is an embed example of video played in HD 1080.
<iframe width="560" height="315" src="http://youtube.com/v/IplDUxTQxsE&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>
Let's break apart the code:http://youtube.com/v/
video_id
&vq=hd1080
Video id for that video: IplDUxTQxsE you will see this type of random code in the link of every YouTube video.
So far so good, this trick works for playing full HD videos directly on webpages!
You can change the quality to 720 too. &vq=hd720
You can use the following flags --single-branch
&& --depth
to download the specific branch and to limit the amount of history which will be downloaded.
You will clone the repo from a certain point in time and only for the given branch
git clone -b <branch> --single-branch <url> --depth <number of commits>
--[no-]single-branch
Clone only the history leading to the tip of a single branch, either specified by the
--branch
option or the primary branch remote’sHEAD
points at.Further fetches into the resulting repository will only update the
remote-tracking
branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when--single-branch
clone was made, no remote-tracking branch is created.
--depth
Create a shallow clone with a history truncated to the specified number of commits
jsonVariable = {}
for(i=1; i<3; i++) {
var jsonKey = i+'name';
jsonVariable[jsonKey] = 'name1'
}
this will be similar to
jsonVariable = {
1name : 'name1'
2name : 'name1'
}
1) File >>> Project Structure OR press Ctrl+Alt+Shift+S
2) In SDK Location Tab you will find SDK Location:
3) Change your Project SDK location to the one you have installed
4) Sync your project
You could do something like this:
Point newLoc = new Point(5,5); // Set whatever you want for initial location
for(int i=0; i < 10; ++i)
{
Button b = new Button();
b.Size = new Size(10, 50);
b.Location = newLoc;
newLoc.Offset(0, b.Height + 5);
Controls.Add(b);
}
If you want them to layout in any sort of reasonable fashion it would be better to add them to one of the layout panels (i.e. FlowLayoutPanel) or to align them yourself.
Add it in database migrations, that way everyone gets it as they update. Handle all of your logic in the ruby/rails code, so you never have to mess with explicit ID settings.
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
There's also concat, but it doesn't get used much
select concat('a','b') from dual;
Please check if you have following error when you run react-native run-android
:
adb server version (XX) doesn't match this client (XX); killing...
In that case make sure /usr/local/opt/android-sdk/platform-tools/adb
and /usr/local/bin/adb
are pointed to the same adb
In my case one was pointed to /Users/sd/Library/Android/sdk/platform-tools/adb
(Android SDK), but another was pointed to /usr/local/Caskroom/android-platform-tools/26.0.2/platform-tools/adb
(Homebrew)
And issue have been fixed after both of them pointed to /Users/sd/Library/Android/sdk/platform-tools/adb
(Android SDK)
var=$(echo "asdf")
echo $var
# => asdf
Using this method, the command is immediately evaluated and it's return value is stored.
stored_date=$(date)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
Same with backtick
stored_date=`date`
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
Using eval in the $(...)
will not make it evaluated later
stored_date=$(eval "date")
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
Using eval, it is evaluated when eval
is used
stored_date="date" # < storing the command itself
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:05 EST 2015
# (wait a few seconds)
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:16 EST 2015
# ^^ Time changed
In the above example, if you need to run a command with arguments, put them in the string you are storing
stored_date="date -u"
# ...
For bash scripts this is rarely relevant, but one last note. Be careful with eval
. Eval only strings you control, never strings coming from an untrusted user or built from untrusted user input.
Note that another approach is to keep with the 4.0 validation behaviour, but to define your own class that derives from RequestValidator
and set:
<httpRuntime requestValidationType="YourNamespace.YourValidator" />
(where YourNamespace.YourValidator
is well, you should be able to guess...)
This way you keep the advantages of 4.0s behaviour (specifically, that the validation happens earlier in the processing), while also allowing the requests you need to let through, through.
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'https://www.xxxSite/get_quote/ajaxGetQuoteJSON.jsp?symbol=IRCTC&series=EQ');
//Set the GET method by giving 0 value and for POST set as 1
//curl_setopt($curl_handle, CURLOPT_POST, 0);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$query = curl_exec($curl_handle);
$data = json_decode($query, true);
curl_close($curl_handle);
//print complete object, just echo the variable not work so you need to use print_r to show the result
echo print_r( $data);
//at first layer
echo $data["tradedDate"];
//Inside the second layer
echo $data["data"][0]["companyName"];
Some time you might get 405, set the method type correctly.
As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose. you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.
No Worries! I have found the solution! I just installed https://msdn.microsoft.com/en-us/windows/desktop/bg162891.aspx and it all worked fine :)
That should work, you may need a space after the commas.
Also, the function you call afterwards must support an array of objects, and not just a singleton object.
On Selenium >= 3.41 (C#) the rigth syntax is:
webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));
If running
source ~/.bashrc
results in "No such file or directory"
On windows:
source <pasteCopiedPathHere>
-> for example: source "C:\Users\John\.bashhrc"
This is no longer up-to-date!
Push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.
Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.
Not sure if this helps but in my app I had to check if a dictionary has changed.
Doing this will not work since basically it's still the same object:
val={'A':1,'B':2}
old_val=val
val['A']=10
if old_val != val:
print('changed')
Using copy/deepcopy works:
import copy
val={'A':1,'B':2}
old_val=copy.deepcopy(val)
val['A']=10
if old_val != val:
print('changed')
I have edited the "Best answer" code, though I found a useful thing that was missing. This is will also track the ip of a user if they are using a Proxy or simply if the server has nginx installed as a proxy reverser.
I added this code to his script at the top of the function:
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$adresseip = getRealIpAddr();
Afther that I edited his code.
Find the line that says the following:
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
and replace it with this:
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;
This will work.
Here is the full code if anything happens:
<?php
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$adresseip = getRealIpAddr();
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
$filetxt = 'userson.txt'; // the file in which the online users /visitors are stored
$timeon = 120; // number of secconds to keep a user online
$sep = '^^'; // characters used to separate the user name and date-time
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the line with visitors
$nrvst = 0; // to store the number of visitors
// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)
$addrow[] = $uvon. $sep. time();
// check if the file from $filetxt exists and is writable
if(is_writable($filetxt)) {
// get into an array the lines added in $filetxt
$ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($ar_rows);
// number of rows
// if there is at least one line, parse the $ar_rows array
if($nrrows>0) {
for($i=0; $i<$nrrows; $i++) {
// get each line and separate the user /visitor and the timestamp
$ar_line = explode($sep, $ar_rows[$i]);
// add in $addrow array the records in last $timeon seconds
if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
$addrow[] = $ar_rows[$i];
}
}
}
}
$nruvon = count($addrow); // total online
$usron = ''; // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
if(preg_match($rgxvst, $addrow[$i])) $nrvst++; // increment the visitors
else {
// gets and stores the user's name
$ar_usron = explode($sep, $addrow[$i]);
$usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
}
}
$nrusr = $nruvon - $nrvst; // gets the users (total - visitors)
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
Haven't tested this on the Sql script yet.
return new String(Hex.encode(digest));
just install python-lib. (python27-lib). It will install libpython2.7.so1.0. We don't require to manually set anything.
Javascript should just put pointers into the mix coz it solves a lot of problems. It means code can refer to an unknown variable name or variables that were created dynamically. It also makes modular coding and injection easy.
This is what i see as the closest you can come to c pointers in practice
in js:
var a = 78; // creates a var with integer value of 78
var pointer = 'a' // note it is a string representation of the var name
eval (pointer + ' = 12'); // equivalent to: eval ('a = 12'); but changes value of a to 12
in c:
int a = 78; // creates a var with integer value of 78
int pointer = &a; // makes pointer to refer to the same address mem as a
*pointer = 12; // changes the value of a to 12
I think this is the solution you were looking for
<button type="submit" onclick="window.location.href='file.doc'">Download!</button>
I hade a case where my Javascript generated a CSV file. Since there is no remote URL to download it I use the following implementation.
downloadCSV: function(data){
var MIME_TYPE = "text/csv";
var blob = new Blob([data], {type: MIME_TYPE});
window.location.href = window.URL.createObjectURL(blob);
}
Greedy matching. The default behavior of regular expressions is to be greedy. That means it tries to extract as much as possible until it conforms to a pattern even when a smaller part would have been syntactically sufficient.
Example:
import re
text = "<body>Regex Greedy Matching Example </body>"
re.findall('<.*>', text)
#> ['<body>Regex Greedy Matching Example </body>']
Instead of matching till the first occurrence of ‘>’, it extracted the whole string. This is the default greedy or ‘take it all’ behavior of regex.
Lazy matching, on the other hand, ‘takes as little as possible’. This can be effected by adding a ?
at the end of the pattern.
Example:
re.findall('<.*?>', text)
#> ['<body>', '</body>']
If you want only the first match to be retrieved, use the search method instead.
re.search('<.*?>', text).group()
#> '<body>'
Source: Python Regex Examples
Because some images could have less than 500px of height, it's better to keep the auto-adjust, so i recommend the following:
<div class="carousel-inner" role="listbox" style="max-width:900px; max-height:600px !important;">`
I would go like this (regex explained in comments):
import re
# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")
# <\/{0,}\[\d+>
#
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»
subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.
and there are many other lines in the txt files
with<[3> such tags </[3>"""
result = pattern.sub("", subject)
print(result)
If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.
I used pyplot
's axes
object to manually adjust the sizes without using GridSpec
:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02
rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]
fig = plt.figure()
cones = plt.axes(rect_cones)
box = plt.axes(rect_box)
cones.plot(x, y)
box.plot(y, x)
plt.show()
An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.
http://docs.oracle.com/javase/8/docs/api/java/net/URI.html
So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?
URLEncoder.encode(uri)
You want to read raw lines to avoid problems with backslashes in the input (use -r
):
while read -r line; do
printf "<%s>\n" "$line"
done < file.txt
This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in
while IFS= read -r line; do
printf "%s\n" "$line"
done < file.txt
This now is an equivalent of cat < file.txt
as long as file.txt
ends with a newline.
Note that you must double quote "$line"
in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.
I use this:
private void MainForm_Load(object sender, EventArgs e)
{
if (Settings.Instance.HideAtStartup)
{
BeginInvoke(new MethodInvoker(delegate
{
Hide();
}));
}
}
Obviously you have to change the if condition with yours.
e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.
See http://unixpapa.com/js/key.html for more information.
I want to propose another way, how to solve limitation with IN operator.
For example we have following query
select *
from Users U
WHERE U.ID in (@ids)
We want to pass several IDs to filter users. Unfortunately it is not possible to do with C# in easy way. But I have fount workaround for this by using "string_split" function. We need to rewrite a bit our query to following.
declare @ids nvarchar(max) = '1,2,3'
SELECT *
FROM Users as U
CROSS APPLY string_split(@ids, ',') as UIDS
WHERE U.ID = UIDS.value
Now we can easily pass one parameter enumeration of values separated by comma.
If [John Smith]
is in cell A1, then use this formula to do what you want:
=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")
The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.
Follow these steps :
Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder. Refer the screenshot :
In your JSP at line <form>
tag,
try this code
<form name="registrationform" action="Register" method="post">
def dsearch(lod, **kw):
return filter(lambda i: all((i[k] == v for (k, v) in kw.items())), lod)
lod=[{'a':33, 'b':'test2', 'c':'a.ing333'},
{'a':22, 'b':'ihaha', 'c':'fbgval'},
{'a':33, 'b':'TEst1', 'c':'s.ing123'},
{'a':22, 'b':'ihaha', 'c':'dfdvbfjkv'}]
list(dsearch(lod, a=22))
[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'},
{'a': 22, 'b': 'ihaha', 'c': 'dfdvbfjkv'}]
list(dsearch(lod, a=22, b='ihaha'))
[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'},
{'a': 22, 'b': 'ihaha', 'c': 'dfdvbfjkv'}]
list(dsearch(lod, a=22, c='fbgval'))
[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'}]
This means that your selectedindex is out of the range of the array of items in the combobox. The array of items in your combo box is zero-based, so if you have 2 items, it's item 0 and item 1.
public static class ImageRename
{
public static void ApplyChanges(string fileUrl,
string temporaryImageName,
string permanentImageName)
{
var currentFileName = Path.Combine(fileUrl,
temporaryImageName);
if (!File.Exists(currentFileName))
throw new FileNotFoundException();
var extention = Path.GetExtension(temporaryImageName);
var newFileName = Path.Combine(fileUrl,
$"{permanentImageName}
{extention}");
if (File.Exists(newFileName))
File.Delete(newFileName);
File.Move(currentFileName, newFileName);
}
}
I'm not sure for JPA 1.0 but you can pass a Collection
in JPA 2.0:
String qlString = "select item from Item item where item.name IN :names";
Query q = em.createQuery(qlString, Item.class);
List<String> names = Arrays.asList("foo", "bar");
q.setParameter("names", names);
List<Item> actual = q.getResultList();
assertNotNull(actual);
assertEquals(2, actual.size());
Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:
String qlString = "select item from Item item where item.name IN (:names)";
But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.
If you want that image to be zoomed on mouse hover :
$(document).ready( function() {
$('#div img').hover(
function() {
$(this).animate({ 'zoom': 1.2 }, 400);
},
function() {
$(this).animate({ 'zoom': 1 }, 400);
});
});
?or you may do like this if zoom in and out buttons are used :
$("#ZoomIn").click(ZoomIn());
$("#ZoomOut").click(ZoomOut());
function ZoomIn (event) {
$("#div img").width(
$("#div img").width() * 1.2
);
$("#div img").height(
$("#div img").height() * 1.2
);
},
function ZoomOut (event) {
$("#div img").width(
$("#imgDtls").width() * 0.5
);
$("#div img").height(
$("#div img").height() * 0.5
);
}
Java's interface for reading filesystem folder contents is not very performant (as you've discovered). JDK 7 fixes this with a completely new interface for this sort of thing, which should bring native level performance to these sorts of operations.
The core issue is that Java makes a native system call for every single file. On a low latency interface, this is not that big of a deal - but on a network with even moderate latency, it really adds up. If you profile your algorithm above, you'll find that the bulk of the time is spent in the pesky isDirectory() call - that's because you are incurring a round trip for every single call to isDirectory(). Most modern OSes can provide this sort of information when the list of files/folders was originally requested (as opposed to querying each individual file path for it's properties).
If you can't wait for JDK7, one strategy for addressing this latency is to go multi-threaded and use an ExecutorService with a maximum # of threads to perform your recursion. It's not great (you have to deal with locking of your output data structures), but it'll be a heck of a lot faster than doing this single threaded.
In all of your discussions about this sort of thing, I highly recommend that you compare against the best you could do using native code (or even a command line script that does roughly the same thing). Saying that it takes an hour to traverse a network structure doesn't really mean that much. Telling us that you can do it native in 7 second, but it takes an hour in Java will get people's attention.
In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:
$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"
I'm surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.
>>> def func(a='a', b='b', c='c', **kwargs):
... print 'a:%s, b:%s, c:%s' % (a, b, c)
...
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>>
Use
sudo lsof -i:5000
This will give you a list of processes using the port if any. Once the list of processes is given, use the id on the PID column to terminate the process use
kill 379 #use the provided PID
In my case, there was a problem with MySQL reference. Somehow, I could list three versions of it under the list of all available references; for .net 2.0, .net 4.0 and .net 4.5. I followed process 1 through 6 above and it worked for me.
Something less verbose, std and takes anything separated by a comma.
stringstream ss( "1,1,1,1, or something else ,1,1,1,0" );
vector<string> result;
while( ss.good() )
{
string substr;
getline( ss, substr, ',' );
result.push_back( substr );
}
For float
have a look at sys.float_info
:
>>> import sys
>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2
250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsil
on=2.2204460492503131e-16, radix=2, rounds=1)
Specifically, sys.float_info.max
:
>>> sys.float_info.max
1.7976931348623157e+308
If that's not big enough, there's always positive infinity:
>>> infinity = float("inf")
>>> infinity
inf
>>> infinity / 10000
inf
The long
type has unlimited precision, so I think you're only limited by available memory.