Looks like the image is too big and the window simply doesn't fit the screen.
Create window with the cv2.WINDOW_NORMAL
flag, it will make it scalable. Then you can resize it to fit your screen like this:
from __future__ import division
import cv2
img = cv2.imread('1.jpg')
screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)
cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)
cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
According to the OpenCV documentation CV_WINDOW_KEEPRATIO
flag should do the same, yet it doesn't and it's value not even presented in the python module.
For the line
line.split()
What are you splitting on? Looks like a CSV, so try
line.split(',')
Example:
"one,two,three".split() # returns one element ["one,two,three"]
"one,two,three".split(',') # returns three elements ["one", "two", "three"]
As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.
You can use the next code:
JS
function showname () {
var name = document.getElementById('fileInput');
alert('Selected file: ' + name.files.item(0).name);
alert('Selected file: ' + name.files.item(0).size);
alert('Selected file: ' + name.files.item(0).type);
};
HTML
<body>
<p>
<input type="file" id="fileInput" multiple onchange="showname()"/>
</p>
</body>
type this command
select CURRENT_USER();
You will get the username and server
Forking creates an entirely new repository from existing repository (simply doing git clone on gitHub/bitbucket)
Forks are best used: when the intent of the ‘split’ is to create a logically independent project, which may never reunite with its parent.
Branch strategy creates a new branch over the existing/working repository
Branches are best used: when they are created as temporary places to work through a feature, with the intent to merge the branch with the origin.
More Specific :- In open source projects it is the owner of the repository who decides who can push to the repository. However, the idea of open source is that everybody can contribute to the project.
This problem is solved by forks: any time a developer wants to change something in an open source project, they don’t clone the official repository directly. Instead, they fork it to create a copy. When the work is finished, they make a pull request so that the owner of the repository can review the changes and decide whether to merge them to his project.
At its core forking is similar to feature branching, but instead of creating branches a fork of the repository is made, and instead of doing a merge request you create a pull request.
The below links provide the difference in a well-explained manner :
https://blog.gitprime.com/the-definitive-guide-to-forks-and-branches-in-git/
You're correct, in that example the throws
is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.
Emm... Why not to use something like this?
function displayArrayObjects(arrayObjects) {_x000D_
var len = arrayObjects.length, text = "";_x000D_
_x000D_
for (var i = 0; i < len; i++) {_x000D_
var myObject = arrayObjects[i];_x000D_
_x000D_
for (var x in myObject) {_x000D_
text += ( x + ": " + myObject[x] + " ");_x000D_
}_x000D_
text += "<br/>";_x000D_
}_x000D_
_x000D_
document.getElementById("message").innerHTML = text;_x000D_
}_x000D_
_x000D_
_x000D_
var lineChartData = [{_x000D_
date: new Date(2009, 10, 2),_x000D_
value: 5_x000D_
}, {_x000D_
date: new Date(2009, 10, 25),_x000D_
value: 30_x000D_
}, {_x000D_
date: new Date(2009, 10, 26),_x000D_
value: 72,_x000D_
customBullet: "images/redstar.png"_x000D_
}];_x000D_
_x000D_
displayArrayObjects(lineChartData);
_x000D_
<h4 id="message"></h4>
_x000D_
result:
date: Mon Nov 02 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 5
date: Wed Nov 25 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 30
date: Thu Nov 26 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 72 customBullet: images/redstar.png
If you are on windows and using mingw, gcc uses the win32 runtime, where printf needs %I64d
for a 64 bit integer. (and %I64u
for an unsinged 64 bit integer)
For most other platforms you'd use %lld
for printing a long long. (and %llu
if it's unsigned). This is standarized in C99.
gcc doesn't come with a full C runtime, it defers to the platform it's running on - so the general case is that you need to consult the documentation for your particular platform - independent of gcc.
Try this:
CONCATENATE(""""; B2 ;"""")
@widor provided a nice solution alternative too - integrated with mine:
CONCATENATE(char(34); B2 ;char(34))
You can at least stop the the non-tech savvy people from using the right-click context menu to download your video. You can disable the context menu for any element using the oncontextmenu attribute.
oncontextmenu="return false;"
This works for the body element (whole page) or just a single video using it inside the video tag.
<video oncontextmenu="return false;" controls>...</video>
data = {a: {b: [1, 2]}}.to_json
uri = URI 'https://myapp.com/api/v1/resource'
https = Net::HTTP.new uri.host, uri.port
https.use_ssl = true
https.post2 uri.path, data, 'Content-Type' => 'application/json'
This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:
The client have two network cards,a wireless one and a normal one.
The ping to server can be succeed.However telnet serverAddress 3306
would fail.
And would complain
Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)
when try to connect to server.So I forbidden the normal network adapters.
And tried telnet serverAddress 3306
it works.And then it work when connect to MySQL server.
This answer is easy to understand
Replace original file
FILENAME='app/Providers/AuthServiceProvider.php'
sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp
cat << 'EOL' >> ${FILENAME}_temp
HERE YOU COPY AND
PASTE MULTIPLE
LINES, ALSO YOU CAN
//WRITE COMMENTS
AND NEW LINES
AND SPECIAL CHARS LIKE $THISONE
EOL
grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp
mv ${FILENAME}_temp $FILENAME
cat << EOL >> ${FILENAME}_temp
this variable will expand: $variable1
EOL
Both are same, there is no difference its just a different term for the same thing in C#.
In object-oriented programming, a method is a subroutine (or procedure or function) associated with a class.
With respect to Object Oriented programming the term "Method" is used, not functions.
strip
removes the whitespace from the beginning and end of the string. If you want the whitespace, don't call strip.
You can solve without nesting tables.
<table border="1">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>ABC</th>_x000D_
<th>ABC</th>_x000D_
<th colspan="2">ABC</th>_x000D_
<th>ABC</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td rowspan="4">Item1</td>_x000D_
<td rowspan="4">Item1</td>_x000D_
<td colspan="2">Item1</td>_x000D_
<td rowspan="4">Item1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Name1</td>_x000D_
<td>Price1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Name2</td>_x000D_
<td>Price2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Name3</td>_x000D_
<td>Price3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Item2</td>_x000D_
<td>Item2</td>_x000D_
<td colspan="2">Item2</td>_x000D_
<td>Item2</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This will remove it - short and clean:
.btn {
outline: none !important;
}
Like this:
InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));
Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.
For versions of Java less than 7, replace StandardCharsets.UTF_8
with "UTF-8"
.
I wanted to find a string between / and #, but # is sometimes optional. Here is the regex I use:
(?<=\/)([^#]+)(?=#*)
For the code to work smoothy in different enviroments, path.resolve can be used in places where path is manipulated. Here is code which works better.
Reading part:
var fs = require('fs');
function readFiles(dirname, onFileContent, onError) {
fs.readdir(dirname, function(err, filenames) {
if (err) {
onError(err);
return;
}
filenames.forEach(function(filename) {
fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
if (err) {
onError(err);
return;
}
onFileContent(filename, content);
});
});
});
}
Storing part:
var data = {};
readFiles(path.resolve(__dirname, 'dirname/'), function(filename, content) {
data[filename] = content;
}, function(error) {
throw err;
});
As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)
| YOUR_DT | SQL2008 |
|-----------------------------|---------------------|
| 2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
| 2013-08-29 13:55:48 blah | (null) |
| 2013-08-29 13:55:48 rubbish | (null) |
SELECT
[Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
THEN convert(datetime,[Your_Dt])
ELSE NULL
END
) AS ca1 (dt_converted)
;
Notes:
You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'
For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison
declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'
select
FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008
| SQL2012 | SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 |
Now you can get time for the current location but for this you have to set the system's persistent default time zone.setTimeZone(String timeZone)
which can be get from
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
TimeZone current = calendar.getTimeZone();
setAutoTimeEnabled(boolean enabled)
Sets whether or not wall clock time should sync with automatic time updates from NTP.
TimeManager timeManager = TimeManager.getInstance();
// Use 24-hour time
timeManager.setTimeFormat(TimeManager.FORMAT_24);
// Set clock time to noon
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 12);
long timeStamp = calendar.getTimeInMillis();
timeManager.setTime(timeStamp);
I was looking for that type of answer I read your answer but didn't satisfied and it was bit old. I found the new solution and share it. :)
For more information visit: https://developer.android.com/things/reference/com/google/android/things/device/TimeManager.html
is what they are saying about this:
OK, guys, sorry about all this trouble, and we apologize for the messed up releases. Here's the summary:
You can do one of two options:
Install Eclipse from eclipse.org and install ADT by pointing to the update site: https://dl-ssl.google.com/android/eclipse
Download bundles from here:
Starting with ADT bundle 23.0.2, you should be able to update to future versions of ADT.
Source: https://code.google.com/p/android/issues/detail?id=72912
This is a lack of a feature which is weird: Python has no switch
statement (although workarounds exist).
Mostly 301 vs 302 is important for indexing in search engines, as their crawlers take this into account and transfer PageRank when using 301.
See Peter Lee's answer for more details.
You could also try setting style
inline without using a variable, like so:
style={{"height" : "100%"}}
or,
for multiple attributes: style={{"height" : "100%", "width" : "50%"}}
You need to do type assertion for converting your interface{} to int value.
iAreaId := val.(int)
iAreaId, ok := val.(int)
More information is available.
You could try a for loop
for func,args,kwargs in zip([a,b,c,d],
[args_a,args_b,args_c,args_d],
[kw_a,kw_b,kw_c,kw_d]):
try:
func(*args, **kwargs)
break
except:
pass
This way you can loop as many functions as you want without making the code look ugly
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
In order to have Click Listener
, DoubleClick Listener
, OnLongPress Listener
, Swipe Left
, Swipe Right
, Swipe Up
, Swipe Down
on Single View
you need to setOnTouchListener
. i.e,
view.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
@Override
public void onClick() {
super.onClick();
// your on click here
}
@Override
public void onDoubleClick() {
super.onDoubleClick();
// your on onDoubleClick here
}
@Override
public void onLongClick() {
super.onLongClick();
// your on onLongClick here
}
@Override
public void onSwipeUp() {
super.onSwipeUp();
// your swipe up here
}
@Override
public void onSwipeDown() {
super.onSwipeDown();
// your swipe down here.
}
@Override
public void onSwipeLeft() {
super.onSwipeLeft();
// your swipe left here.
}
@Override
public void onSwipeRight() {
super.onSwipeRight();
// your swipe right here.
}
});
}
For this you need OnSwipeTouchListener
class that implements OnTouchListener
.
public class OnSwipeTouchListener implements View.OnTouchListener {
private GestureDetector gestureDetector;
public OnSwipeTouchListener(Context c) {
gestureDetector = new GestureDetector(c, new GestureListener());
}
public boolean onTouch(final View view, final MotionEvent motionEvent) {
return gestureDetector.onTouchEvent(motionEvent);
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
onClick();
return super.onSingleTapUp(e);
}
@Override
public boolean onDoubleTap(MotionEvent e) {
onDoubleClick();
return super.onDoubleTap(e);
}
@Override
public void onLongPress(MotionEvent e) {
onLongClick();
super.onLongPress(e);
}
// Determines the fling velocity and then fires the appropriate swipe event accordingly
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
} else {
if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeDown();
} else {
onSwipeUp();
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeUp() {
}
public void onSwipeDown() {
}
public void onClick() {
}
public void onDoubleClick() {
}
public void onLongClick() {
}
}
In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods to Parse GUID. Here is example for this.
//Generate New GUID
Guid objGuid = Guid.NewGuid();
//Take invalid guid format
string strGUID = "aaa-a-a-a-a";
Guid newGuid;
if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
{
Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
}
else
{
Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
}
Guid newTmpGuid;
if (Guid.TryParse(strGUID, out newTmpGuid) == true)
{
Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
}
else
{
Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
}
In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.
There are many methods to convert an array to comma separated list
From MDN
The join() method joins all elements of an array (or an array-like object) into a string.
The code
var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.join(",");_x000D_
console.log(arr);
_x000D_
From MDN
The toString() method returns a string representing the specified array and its elements.
The code
var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.toString();_x000D_
console.log(arr);
_x000D_
The []+ or +[] will convert it into a string
([]+[] === [].toString())
will output true
console.log([]+[] === [].toString());
_x000D_
var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = []+arr;_x000D_
console.log(arr);
_x000D_
var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr + [];_x000D_
console.log(arr);
_x000D_
You could do many of the given answers, but if you just want to do it to be able to use it with strcpy
, then you could do the following:
...
strcpy( ... , (char[2]) { (char) c, '\0' } );
...
The (char[2]) { (char) c, '\0' }
part will temporarily generate null-terminated string out of a character c
.
This way you could avoid creating new variables for something that you already have in your hands, provided that you'll only need that single-character string just once.
It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr()
method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]
IE has some problems with the DOM setAttribute
method but in this case it should be fine:
this.setAttribute("checked", "checked");
In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked
attribute, you need to set the checked
property as well:
this.setAttribute("checked", "checked");
this.checked = true;
To uncheck the checkbox and remove the attribute, do the following:
this.setAttribute("checked", ""); // For IE
this.removeAttribute("checked"); // For other browsers
this.checked = false;
Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt:
Declare @d datetime
select @d = getdate()
select @d as OriginalDate,
convert(varchar,@d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select @d,convert(varchar,@d,101),101,'mm/dd/yy'
union all
select @d,convert(varchar,@d,102),102,'yy.mm.dd'
union all
select @d,convert(varchar,@d,103),103,'dd/mm/yy'
union all
select @d,convert(varchar,@d,104),104,'dd.mm.yy'
union all
select @d,convert(varchar,@d,105),105,'dd-mm-yy'
union all
select @d,convert(varchar,@d,106),106,'dd mon yy'
union all
select @d,convert(varchar,@d,107),107,'Mon dd, yy'
union all
select @d,convert(varchar,@d,108),108,'hh:mm:ss'
union all
select @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select @d,convert(varchar,@d,110),110,'mm-dd-yy'
union all
select @d,convert(varchar,@d,111),111,'yy/mm/dd'
union all
select @d,convert(varchar,@d,12),12,'yymmdd'
union all
select @d,convert(varchar,@d,112),112,'yyyymmdd'
union all
select @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'
You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :--> (inside main)
Orderbook o1;
o1.m.check(side)
but that would be unnecessary. Keeping things short :-
You can't call functions inside a Class
The most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.
What about this?
std::sort(numbers.begin(), numbers.end());
std::reverse(numbers.begin(), numbers.end());
The easiest way to achieve is by applying width to view.
width: '80%'
To simply answer your question when you do a mvn:install, maven will create a packaged artifact based on (packaging attribute in pom.xml), After you run your maven install you can find the file with .package extension
You need to add $ANDROID_SDK/platform-tools
to your PATH
, where $ANDROID_SDK
is wherever you installed the Android SDK.
Solved:
Just add
org.gradle.jvmargs=-Xmx1024m
in
gradle.properties
and if it does not exist, create it.
Here is a method I used and worked for me
public static String toSql(Session session, Criteria criteria){
String sql="";
Object[] parameters = null;
try{
CriteriaImpl c = (CriteriaImpl) criteria;
SessionImpl s = (SessionImpl)c.getSession();
SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
String[] implementors = factory.getImplementors( c.getEntityOrClassName() );
CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]), factory, c, implementors[0], s.getEnabledFilters());
Field f = OuterJoinLoader.class.getDeclaredField("sql");
f.setAccessible(true);
sql = (String)f.get(loader);
Field fp = CriteriaLoader.class.getDeclaredField("traslator");
fp.setAccessible(true);
CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
parameters = translator.getQueryParameters().getPositionalParameterValues();
}
catch(Exception e){
throw new RuntimeException(e);
}
if (sql !=null){
int fromPosition = sql.indexOf(" from ");
sql = "SELECT * "+ sql.substring(fromPosition);
if (parameters!=null && parameters.length>0){
for (Object val : parameters) {
String value="%";
if(val instanceof Boolean){
value = ((Boolean)val)?"1":"0";
}else if (val instanceof String){
value = "'"+val+"'";
}
sql = sql.replaceFirst("\\?", value);
}
}
}
return sql.replaceAll("left outer join", "\nleft outer join").replace(" and ", "\nand ").replace(" on ", "\non ");
}
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
I had a similar issue that led me to this question. In my browser debugger I was getting this error message:
Access to fetch at 'http://localhost:8081/index.delta?platform=android&dev=true&minify=false' from origin 'http://127.0.0.1:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
It took me awhile to realize I was using 127.0.0.1:8081
instead of localhost:8081
for my debugger.
To fix it, I simply had to change Chrome from:
http://127.0.0.1:8081/debugger-ui/
to
http://localhost:8081/debugger-ui/
When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:
http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake
If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:
http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx
In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:
This should work :
str = str.replace(/[^a-z0-9-]/g, '');
Everything between the indicates what your are looking for
/
is here to delimit your pattern so you have one to start and one to end[]
indicates the pattern your are looking for on one specific character^
indicates that you want every character NOT corresponding to what followsa-z
matches any character between 'a' and 'z' included0-9
matches any digit between '0' and '9' included (meaning any digit)-
the '-' characterg
at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole stringThen your expression is delimited by /
before and after.
So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
This is the method I use in my applications, it's fairly simple and self explanatory but I'm happy to give more details in answer to your comments.
public Form1()
{
InitializeComponent();
// When window state changed, trigger state update.
this.Resize += SetMinimizeState;
// When tray icon clicked, trigger window state change.
systemTrayIcon.Click += ToggleMinimizeState;
}
// Toggle state between Normal and Minimized.
private void ToggleMinimizeState(object sender, EventArgs e)
{
bool isMinimized = this.WindowState == FormWindowState.Minimized;
this.WindowState = (isMinimized) ? FormWindowState.Normal : FormWindowState.Minimized;
}
// Show/Hide window and tray icon to match window state.
private void SetMinimizeState(object sender, EventArgs e)
{
bool isMinimized = this.WindowState == FormWindowState.Minimized;
this.ShowInTaskbar = !isMinimized;
systemTrayIcon.Visible = isMinimized;
if (isMinimized) systemTrayIcon.ShowBalloonTip(500, "Application", "Application minimized to tray.", ToolTipIcon.Info);
}
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
<input type="radio" name="myRadios" value="3" /> 3
<input type="radio" name="myRadios" value="4" /> 4
<input type="radio" name="myRadios" value="5" /> 5
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
//using radio elements previousCheckedRadio and currentCheckedRadio
//storing radio element for using in future 'change' event handler
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
function logInfo(info) {
if (!console || !console.log) return;
console.log(info);
}
function logPrevious(element) {
if (!element) return;
var message = element.value + ' was unchecked';
logInfo(message);
}
function logCurrent(element) {
if (!element) return;
var message = element.value + ' is checked';
logInfo(message);
}
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
logPrevious(previousCheckedRadio);
logCurrent(currentCheckedRadio);
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
Like the other answers said, sp_reset_connection
indicates that connection pool is being reused. Be aware of one particular consequence!
Jimmy Mays' MSDN Blog said:
sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.
UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.
ref: SQL Server: Isolation level leaks across pooled connections
Here is some additional information:
What does sp_reset_connection do?
Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.
sp_reset_connection resets the following aspects of a connection:
All error states and numbers (like @@error)
Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query
Waits for any outstanding I/O operations that is outstanding
Frees any held buffers on the server by the connection
Unlocks any buffer resources that are used by the connection
Releases all allocated memory owned by the connection
Clears any work or temporary tables that are created by the connection
Kills all global cursors owned by the connection
Closes any open SQL-XML handles that are open
Deletes any open SQL-XML related work tables
Closes all system tables
Closes all user tables
Drops all temporary objects
Aborts open transactions
Defects from a distributed transaction when enlisted
Decrements the reference count for users in current database which releases shared database locks
Frees acquired locks
Releases any acquired handles
Resets all SET options to the default values
Resets the @@rowcount value
Resets the @@identity value
Resets any session level trace options using dbcc traceon()
Resets CONTEXT_INFO to
NULL
in SQL Server 2005 and newer [ not part of the original article ]sp_reset_connection will NOT reset:
Security context, which is why connection pooling matches connections based on the exact connection string
Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when
sp_setapprole
is executed.
Note: I am including the list here as I do not want it to be lost in the ever transient web.
99% of the time I would use XMLHttpRequest or fetch for something like this. However, there's an alternative solution which doesn't require javascript...
You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.
<style>
.hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>
<iframe name="hiddenFrame" class="hide"></iframe>
<form action="receiver.pl" method="post" target="hiddenFrame">
<input name="signed" type="checkbox">
<input value="Save" type="submit">
</form>
There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...
You can use the following command:
git checkout HEAD -- my-file.txt
... which will update both the working copy of my-file.txt
and its state in the index with that from HEAD.
--
basically means: treat every argument after this point as a file name. More details in this answer. Thanks to VonC for pointing this out.
if your button is inside your form class:
buttonOk.Click += new EventHandler(your_click_method);
(might not be exactly EventHandler
)
and in your click method:
this.Close();
If you need to show a message box:
MessageBox.Show("test");
You're comparing the message with the empty string using ==
.
First, your comparison is wrong because the message will be null (and not the empty string).
Second, it's wrong because Objects must be compared with equals()
and not with ==
.
Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:
<c:id test="${!empty message}">
<c:out value="${message}"/>
</c:if>
Quoting the Forms Page in the HTML manual:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.
I'm not really sure if I got your question right. Maybe something like
public class CommentsController : Controller
{
[HttpPost]
public ActionResult WriteComment(CommentModel comment)
{
// Do the basic model validation and other stuff
try
{
if (ModelState.IsValid )
{
// Insert the model to database like:
db.Comments.Add(comment);
db.SaveChanges();
// Pass the comment's article id to the read action
return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
}
}
catch ( Exception e )
{
throw e;
}
// Something went wrong
return View(comment);
}
}
public class ArticlesController : Controller
{
// id is the id of the article
public ActionResult Read(int id)
{
// Get the article from database by id
var model = db.Articles.Find(id);
// Return the view
return View(model);
}
}
add typing.d.ts in main folder of the application and over there declare the varible which you want to use every time
declare var System: any;
declare var require: any;
after declaring this in typing.d.ts, error for require will not come in the application..
You need to search the World from the top right search bar and delete the expired certificate. Make sure you selected Login and All items.
To answer your second question, yes, you can cast the List<?>
as a List<Object>
or a List<T>
of any type, since the ?
(Wildcard) parameter indicates that the list contains a homogenous collection of an any Object
. However, there's no way to know at compile what the type
is since it's part of the exported API only - meaning you can't see what's being inserted into the List<?>
.
Here's how you would make the cast:
List<?> wildcardList = methodThatReturnsWildcardList();
// generates Unchecked cast compiler warning
List<Object> objectReference = (List<Object>)wildcardList;
In this case you can ignore the warning because in order for an object to be used in a generic class it must be a subtype of Object
. Let's pretend that we're trying to cast this as a List<Integer>
when it actually contains a collection of String
s.
// this code will compile safely
List<?> wildcardList = methodThatReturnsWildcardList();
List<Integer> integerReference = (List<Integer>)wildcardList;
// this line will throw an invalid cast exception for any type other than Integer
Integer myInteger = integerRefence.get(0);
Remember: generic types are erased at runtime. You won't know what the collection contains, but you can get an element and call .getClass()
on it to determine its type.
Class objectClass = wildcardList.get(0).getClass();
The problem is related with your file - you are trying to create a DB using a copy - at the top of your file you will find something like this:
CREATE DATABASE IF NOT EXISTS *THE_NAME_OF_YOUR_DB*
DEFAULT CHARACTER SET latin1 COLLATE latin1_general_ci;
USE *THE_NAME_OF_YOUR_DB*
;
and I'm sure that you already have a DB with this name - IN THE SAME SERVER - please check. Just change the name OR ERASE THIS LINE!
If the remote branch already exists then you can (probably) get away with..
git checkout branch_name
and git will automatically set up to track the remote branch with the same name on origin.
I implemeneted this algorithm in typescript and ES6
export type Coordinate = {
lat: number;
lon: number;
};
get the distance between two points:
function getDistanceBetweenTwoPoints(cord1: Coordinate, cord2: Coordinate) {
if (cord1.lat == cord2.lat && cord1.lon == cord2.lon) {
return 0;
}
const radlat1 = (Math.PI * cord1.lat) / 180;
const radlat2 = (Math.PI * cord2.lat) / 180;
const theta = cord1.lon - cord2.lon;
const radtheta = (Math.PI * theta) / 180;
let dist =
Math.sin(radlat1) * Math.sin(radlat2) +
Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = (dist * 180) / Math.PI;
dist = dist * 60 * 1.1515;
dist = dist * 1.609344; //convert miles to km
return dist;
}
get the distance between an array of coordinates
export function getTotalDistance(coordinates: Coordinate[]) {
coordinates = coordinates.filter((cord) => {
if (cord.lat && cord.lon) {
return true;
}
});
let totalDistance = 0;
if (!coordinates) {
return 0;
}
if (coordinates.length < 2) {
return 0;
}
for (let i = 0; i < coordinates.length - 2; i++) {
if (
!coordinates[i].lon ||
!coordinates[i].lat ||
!coordinates[i + 1].lon ||
!coordinates[i + 1].lat
) {
totalDistance = totalDistance;
}
totalDistance =
totalDistance +
getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1]);
}
return totalDistance.toFixed(2);
}
Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.
If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.
Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.
<StackPanel x:Name="myStackPanel">
<CheckBox x:Name="myCheckBox"
Content="My CheckBox" />
<Button Content="Click to Uncheck"
x:Name="myUncheckButton" />
<Button Content="Click to check the box in code."
Click="OnClick" />
<StackPanel.Triggers>
<EventTrigger RoutedEvent="Button.Click"
SourceName="myUncheckButton">
<EventTrigger.Actions>
<BeginStoryboard x:Name="myBeginStoryboard">
<Storyboard x:Name="myStoryboard">
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
Storyboard.TargetProperty="IsChecked">
<DiscreteBooleanKeyFrame KeyTime="00:00:00"
Value="False" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="CheckBox.Click"
SourceName="myCheckBox">
<EventTrigger.Actions>
<StopStoryboard BeginStoryboardName="myBeginStoryboard" />
</EventTrigger.Actions>
</EventTrigger>
</StackPanel.Triggers>
</StackPanel>
To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.
We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.
private void OnClick(object sender, RoutedEventArgs e)
{
myStoryboard.Remove(myStackPanel);
myCheckBox.IsChecked = true;
}
Create a new file startCmdLine.bat in your directory and put this line in it
call cmd
That is it. Now double click on the .bat file. It works for me.
You can replace call with start, it will also work.
@Skelly 's answer is correct. It won't let me add a comment (<50 rep)... but to answer your question on his answer: In the example he linked, if you add
col-xs-3
class to each of the thumbnails, like this:
class="col-md-3 col-xs-3"
then it should stay the way you want it when sized down to phone width.
Now there's the s (single line) modifier, that lets the dot matches new lines as well :) \s will also match new lines :D
Just add the s behind the slash
/<pre.*?<\/pre>/gms
If you don't know (or care) how many arguments you will be passing to the function, you could also use a very simple approach like;
Code:
function FunctionName()
{
Write-Host $args
}
That would print out all arguments. For example:
FunctionName a b c 1 2 3
Output
a b c 1 2 3
I find this particularly useful when creating functions that use external commands that could have many different (and optional) parameters, but relies on said command to provide feedback on syntax errors, etc.
Here is a another real-world example (creating a function to the tracert command, which I hate having to remember the truncated name);
Code:
Function traceroute
{
Start-Process -FilePath "$env:systemroot\system32\tracert.exe" -ArgumentList $args -NoNewWindow
}
*You can use layout_weight
properties. If you want to take 70% of parent width you must set child layout_width
property value 0dp, like android:layout_width="0dp"
*
As of Python 3.6+, the best way of doing this is by the new timespec
argument for isoformat
.
isoformat(timespec='seconds', sep=' ')
Usage:
>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'
You may try like this:
new Date($.now());
Also using Javascript you can do like this:
var dt = new Date();_x000D_
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();_x000D_
document.write(time);
_x000D_
str_replace is considerably faster.
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
Here is the reusable function to generate the random IDs :
function revisedRandId() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}
// It will not start with the any number digit so it will be supported by CSS3
temp$quartile <- ceiling(sapply(temp$value,function(x) sum(x-temp$value>=0))/(length(temp$value)/4))
I generated a node/gulp app using the generator-gulp-webapp Yeoman generator. It handled the "clean conundrum" this way (translating to the original tasks mentioned in the question):
gulp.task('develop', ['clean'], function () {
gulp.start('coffee');
});
Gradle wrapper needs to be built. Try running gradle wrapper --gradle-version 2.13
Remember to change 2.13 to your gradle version number. After running this command, you should see new scripts added to your project folder. You should be able to run the wrapper with ./gradlew build
to build your code. Please refer to this guid for more information https://spring.io/guides/gs/gradle/.
System.XML handles the encoding for you, so you don't need a method like this.
Scanning object for first intance of a determinated prop:
var obj = {a:'Saludos',
b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
d:'Hasta luego'
}
function scan (element,list){
var res;
if (typeof(list) != 'undefined'){
if (typeof(list) == 'object'){
for(key in list){
if (typeof(res) == 'undefined'){
res = (key == element)?list[key]:scan(element,list[key]);
}
});
}
}
return res;
}
console.log(scan('a',obj));
I've got one for you guys that might be a little ugly, but it does get'er done across platforms
function myFunc () {
var _myAttribute = "default";
this.myAttribute = function() {
if (arguments.length > 0) _myAttribute = arguments[0];
return _myAttribute;
}
}
this way, when you call
var test = new myFunc();
test.myAttribute(); //-> "default"
test.myAttribute("ok"); //-> "ok"
test.myAttribute(); //-> "ok"
If you really want to spice things up.. you can insert a typeof check:
if (arguments.length > 0 && typeof arguments[0] == "boolean") _myAttribute = arguments[0];
if (arguments.length > 0 && typeof arguments[0] == "number") _myAttribute = arguments[0];
if (arguments.length > 0 && typeof arguments[0] == "string") _myAttribute = arguments[0];
or go even crazier with the advanced typeof check: type.of() code at codingforums.com
You can use css filters, below and example for web-kit. please look at this example: http://jsfiddle.net/m9sjdbx6/4/
img { -webkit-filter: brightness(0.2);}
Have you tried
adb kill-server
adb shell
Sometimes adb gets stuck and first killing adb server and then starting some command forces authorization window to pop-up.
Also please check adb client version on your phone. THis feature is supported from adb 1.0.31 as far as I remember.
A tip that may be obvious to some but not others..
If you're using the HTML Helper based on DropDownListFor
then your ID will be duplicated in the HiddenFor
input. Therefore, you'll have duplicate IDs which is invalid in HTML and if you're using javascript to populate the HiddenFor
and DropDownList
then you'll have a problem.
The solution is to manually set the ID property in the htmlattributes array...
@Html.HiddenFor(model => model.Entity)
@Html.EnumDropDownListFor(
model => model.Entity,
new {
@class = "form-control sharp",
onchange = "",
id =` "EntityDD",
disabled = "disabled"
}
)
A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.
For example, If I do this:
Integer myInteger = null;
int n = myInteger.intValue();
The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.
What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!
As of go1.2+, cgo automatically incorporates and compiles C++ code:
nchar requires more space than nvarchar.
eg,
A nchar(100) will always store 100 characters even if you only enter 5, the remaining 95 chars will be padded with spaces. Storing 5 characters in a nvarchar(100) will save 5 characters.
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
Case sensitive: document.getElementById
(notice the capital B
).
With a few exceptions, Python is used pretty much wherever a programmer who knows Python wants to focus on solving a problem instead of struggling with implementation details. You'll find it in games, web applications, network servers, scientific computing, media tools, application scripting, etc. (There's a somewhat old list of some organizations that use it here.) People who know it well tend to love it because it strikes a very rare balance of conciseness and clarity, and (perhaps to a lesser extent) because it has a rich set of useful libraries.
Some places where Python isn't used as much:
Code:
/**
* sort keys like in key list
* filter: remove keys are not listed in keyList
* ['c'=>'red', 'd'=>'2016-12-29'] = sortAndFilterKeys(['d'=>'2016-12-29', 'c'=>'red', 'a'=>3 ]], ['c', 'd', 'z']){
*
* @param array $inputArray
* @param string[]|int[] $keyList
* @param bool $removeUnknownKeys
* @return array
*/
static public function sortAndFilterKeys($inputArray, $keyList, $removeUnknownKeys=true){
$keysAsKeys = array_flip($keyList);
$result = array_replace($keysAsKeys, $inputArray); // result = sorted keys + values from input +
$result = array_intersect_key($result, $inputArray); // remove keys are not existing in inputArray
if( $removeUnknownKeys ){
$result = array_intersect_key($result, $keysAsKeys); // remove keys are not existing in keyList
}
return $result;
}
I had some problems with andy's code, but it gave me some great ideas. First problem was that we should pop off any jqXHR objects that successfully complete. I also had to modify the abortAll function. Here is my final working code:
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
}
});
$(document).ajaxComplete(function() {
$.xhrPool.pop();
});
I didn't like the ajaxComplete() way of doing things. No matter how I tried to configure .ajaxSetup it did not work.
If you're still getting that page, it's likely that it's blowing up before getting past the Web.Config
Make sure that ASP.Net has permissions it needs to things like the .Net Framework folders, the IIS Metabase, etc. Do you have any way of checking that ASP.Net is installed correctly and associated in IIS correctly?
Edit: After Greg's comment it occured to me I assumed that what you posted was your entire very minimal web.config, is there more to it? If so can you post the entire web.config?
//Representation of table
<div class="search-table-outter">
<table class="table table-responsive search-table inner">
</table>
</div>
//Css to make Horizontal Dropdown
<style>
.search-table{table-layout: auto; margin:40px auto 0px auto; }
.search-table, td, th {
border-collapse: collapse;
}
th{padding:20px 7px; font-size:15px; color:#444;}
td{padding:5px 10px; height:35px;}
.search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }
</style>
Firstly create a new class that extends the WorldView
class. I called my new class Background
. So in this new class import all the Java packages you will need in order to override the paintBackground
method. This should be:
import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;
Next after the class name make sure that it says extends WorldView
. Something like this:
public class Background extends WorldView
Then declare the variables game of type Game
and an image variable of type Image
something like this:
private Game game;
private Image image;
Then in the constructor of this class make sure the game of type Game
is in the signature of the constructor and that in the call to super
you will have to initialise the WorldView
, initialise the game and initialise the image variables, something like this:
super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();
Then you just override the paintBackground
method in exactly the same way as you did when overriding the paint
method in the Player
class. Just like this:
public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}
Now finally you have to declare a class level reference to the new class you just made in the Game
class and initialise this in the Game
constructor, something like this:
private Background image;
And in the Game constructor:
image = new Background(this);
Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable frame
has been declared:
frame.add(image);
Make sure you add this code just before frame.pack();
.
Also make sure you use a background image that isn't too big!
Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.
I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".
You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.
This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.
Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.
Your fiddle is updated, see here: jsfiddle
The code:
$('form').on('submit', function (e) {
var focusSet = false;
if (!$('#email').val()) {
if ($("#email").parent().next(".validation").length == 0) // only add if not added
{
$("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
}
e.preventDefault(); // prevent form from POST to server
$('#email').focus();
focusSet = true;
} else {
$("#email").parent().next(".validation").remove(); // remove it
}
if (!$('#password').val()) {
if ($("#password").parent().next(".validation").length == 0) // only add if not added
{
$("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
}
e.preventDefault(); // prevent form from POST to server
if (!focusSet) {
$("#password").focus();
}
} else {
$("#password").parent().next(".validation").remove(); // remove it
}
});
The CSS:
.validation
{
color: red;
margin-bottom: 20px;
}
Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.
For all browsers
I perform 2 tests cases:
Below snippet presents solutions Aa Ab Ba Bb Ca Cb Da Db E F
// https://stackoverflow.com/questions/10398931/how-to-strToRemove-text-from-a-string
// https://stackoverflow.com/a/10398941/860099
function Aa(str,strToRemove) {
return str.replace(strToRemove,'');
}
// https://stackoverflow.com/a/63362111/860099
function Ab(str,strToRemove) {
return str.replaceAll(strToRemove,'');
}
// https://stackoverflow.com/a/23539019/860099
function Ba(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replace(new RegExp(re),'');
}
// https://stackoverflow.com/a/63362111/860099
function Bb(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replaceAll(new RegExp(re,'g'),'');
}
// https://stackoverflow.com/a/27098801/860099
function Ca(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/27098801/860099
function Cb(str,strToRemove) {
let start = str.search(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/23181792/860099
function Da(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/23181792/860099
function Db(str,strToRemove) {
let start = str.search(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/49857431/860099
function E(str,strToRemove) {
return str.split(strToRemove).join('');
}
// https://stackoverflow.com/a/45406624/860099
function F(str,strToRemove) {
var n = str.search(strToRemove);
while (str.search(strToRemove) > -1) {
n = str.search(strToRemove);
str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length);
}
return str;
}
let str = "data-123";
let strToRemove = "data-";
[Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`${f.name.padEnd(2,' ')} ${f(str,strToRemove)}`));
_x000D_
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
And here are example results for chrome
Getting name and subsetting based on Start, Contains, and Ends:
# from: https://stackoverflow.com/questions/21285380/find-column-whose-name-contains-a-specific-string
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html
# from: https://cmdlinetips.com/2019/04/how-to-select-columns-using-prefix-suffix-of-column-names-in-pandas/
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html
import pandas as pd
data = {'spike_starts': [1,2,3], 'ends_spike_starts': [4,5,6], 'ends_spike': [7,8,9], 'not': [10,11,12]}
df = pd.DataFrame(data)
print("\n")
print("----------------------------------------")
colNames_contains = df.columns[df.columns.str.contains(pat = 'spike')].tolist()
print("Contains")
print(colNames_contains)
print("\n")
print("----------------------------------------")
colNames_starts = df.columns[df.columns.str.contains(pat = '^spike')].tolist()
print("Starts")
print(colNames_starts)
print("\n")
print("----------------------------------------")
colNames_ends = df.columns[df.columns.str.contains(pat = 'spike$')].tolist()
print("Ends")
print(colNames_ends)
print("\n")
print("----------------------------------------")
df_subset_start = df.filter(regex='^spike',axis=1)
print("Starts")
print(df_subset_start)
print("\n")
print("----------------------------------------")
df_subset_contains = df.filter(regex='spike',axis=1)
print("Contains")
print(df_subset_contains)
print("\n")
print("----------------------------------------")
df_subset_ends = df.filter(regex='spike$',axis=1)
print("Ends")
print(df_subset_ends)
From Activity Class:
Send the data using bundle arguments to the fragment and load the fragment
Fragment fragment = new myFragment();
Bundle bundle = new Bundle();
bundle.putString("pName", personName);
bundle.putString("pEmail", personEmail);
bundle.putString("pId", personId);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
fragment).commit();
From myFragment Class:
Get the arguments from the bundle and set them to xml
Bundle arguments = getArguments();
String personName = arguments.getString("pName");
String personEmail = arguments.getString("pEmail");
String personId = arguments.getString("pId");
nameTV = v.findViewById(R.id.name);
emailTV = v.findViewById(R.id.email);
idTV = v.findViewById(R.id.id);
nameTV.setText("Name: "+ personName);
emailTV.setText("Email: "+ personEmail);
idTV.setText("ID: "+ personId);
Another easy way is to use the WC_Product_Factory class and then call function get_product(ID)
http://docs.woothemes.com/wc-apidocs/source-class-WC_Product_Factory.html#16-63
sample:
// assuming the list of product IDs is are stored in an array called IDs;
$_pf = new WC_Product_Factory();
foreach ($IDs as $id) {
$_product = $_pf->get_product($id);
// from here $_product will be a fully functional WC Product object,
// you can use all functions as listed in their api
}
You can then use all the function calls as listed in their api: http://docs.woothemes.com/wc-apidocs/class-WC_Product.html
For me, it just was that service console restart didn't work after tomcat ran into an error. Only stop/start brought it back.
You can change the value of a static readonly string
only in the static
constructor of the class or a variable initializer, whereas you cannot change the value of a const
string anywhere.
In my case, I wanted to move a submodule from one directory into a subdirectory, e.g. "AFNetworking" -> "ext/AFNetworking". These are the steps I followed:
[core] worktree
line. Mine changed from ../../../AFNetworking
to ../../../../ext/AFNetworking
gitdir
. Mine changed from ../.git/modules/AFNetworking
to ../../git/modules/ext/AFNetworking
git add .gitmodules
git rm --cached AFNetworking
git submodule add -f <url> ext/AFNetworking
Finally, I saw in the git status:
matt$ git status
# On branch ios-master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: .gitmodules
# renamed: AFNetworking -> ext/AFNetworking
Et voila. The above example doesn't change the directory depth, which makes a big difference to the complexity of the task, and doesn't change the name of the submodule (which may not really be necessary, but I did it to be consistent with what would happen if I added a new module at that path.)
Not entirely sure what you want here, but if you want to discount blank cells in the range and pass over zeros then this would do it; if a little contrived:
=MIN(IF(A1:E1=0,MAX(A1:E1),A1:E1))
With Ctrl+Shift+Enter as an array.
What I'm doing here is replacing zeros with the maximum value in the list.
You are on the right track.
On your header set
Content-Type: application/x-www-form-urlencoded
The body of the POST request should be =test
and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.
See also POST string to ASP.NET Web Api application - returns null
As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap
is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:
private _entityId: number;
constructor(private _route: ActivatedRoute) {
// ...
}
ngOnInit() {
// For a static snapshot of the route...
this._entityId = this._route.snapshot.paramMap.get('id');
// For subscribing to the observable paramMap...
this._route.paramMap.pipe(
switchMap((params: ParamMap) => this._entityId = params.get('id'))
);
// Or as an alternative, with slightly different execution...
this._route.paramMap.subscribe((params: ParamMap) => {
this._entityId = params.get('id');
});
}
I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.
If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.
val uri = myUriString.toUri()
To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Replace '_' || '/' to your own need
This java code checks if the key (file) exists in s3 bucket.
public static boolean isExistS3(String accessKey, String secretKey, String bucketName, String file) {
// Amazon-s3 credentials
AWSCredentials myCredentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3Client s3Client = new AmazonS3Client(myCredentials);
ObjectListing objects = s3Client.listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix(file));
for (S3ObjectSummary objectSummary: objects.getObjectSummaries()) {
if (objectSummary.getKey().equals(file)) {
return true;
}
}
return false;
}
Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.
Therefore, you can not use this variation
> sitemap: /sitemap.xml
Recommended syntax is
Sitemap: https://www.yourdomain.com/sitemap.xml
Note:
I am using this with Beautifulsoup 4.8.1 to get the value of all class attributes of certain elements:
from bs4 import BeautifulSoup
html = "<td class='val1'/><td col='1'/><td class='val2' />"
bsoup = BeautifulSoup(html, 'html.parser')
for td in bsoup.find_all('td'):
if td.has_attr('class'):
print(td['class'][0])
Its important to note that the attribute key retrieves a list even when the attribute has only a single value.
I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:
select min(Id), distinct MailId, EmailAddress, Name
from yourTableName
group by MailId, EmailAddress, Name
I see that I am using a GROUP BY clause
but you still won't have two rows against any particular MailId
.
I am currently using tmux.
Installation: sudo apt-get install tmux Run it: tmux
Ctrl + b followed by Ctr + % : it splits your terminal window in two vertical halves.
Ctrl + "arrow left | arrow right" : moves between terminals.
With 500k documents, there is no reason to scale whatsoever. A typical laptop with an SSD and 8GB of ram can easily do 10s of millions of records, so if you are trying to pick because of scaling your choice doesn't really matter. I would suggest you pick what you like the most, and perhaps where you can find the most online support with.
Simply type conda update pandas
in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory).
See this document for a detailed instruction.
It's just more versatile if you give it a class name as the style you specify will only apply to that class name. But if you exactly know every .column img
and want to style that in the same way, there's no reason why you can't use that selector.
The performance difference, if any, is negligible these days.
The simplest way I found was to override default_msec_format:
formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'
Working example of link posted by pranav:
http://jsbin.com/nolanole/1/edit?html,js,output
FYI: Tested in IE 6, 7, & 8 (compatibility mode on or off), FF 3 & 3.5, Chrome 2. Not screen-reader-friendly (headers aren't part of content table).
EDIT 5/5/14: moved example to jsBin. This is old, but amazingly still works in current Chrome, IE, and Firefox (though IE and Firefox might require some adjustments to row heights).
Use cURL
,
Check if you have it via phpinfo();
And for the code:
function getHtml($url, $post = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
if(!empty($post)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
It's the difference between strings and integers. See:
>>> "1" * 9
'111111111'
>>> 1 * 9
9
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
You'll get that error once your numbers are greater than sys.maxsize
:
>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long
You can confirm this by checking:
>>> import sys
>>> sys.maxsize
2147483647
To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:
>>> preds = np.zeros((1, 3))
I had exactly the same issue last week - WCF program behaves strangely on one server - why?
For me the solution was rather simple. Sharepoint has its own set of permissions. My client tried to log on as a user that wasn't explicitly given access to the webservice through Sharepoint's administration panel.
I added the user to Sharepoint's whitelist and bang - it just worked.
Even if that isn't the issue, please note that
The HTTP request is unauthorized with client authentication scheme ‘Ntlm’. The authentication header received from the server was ‘NTLM’.
Means (in English) that you simply don't have permission. Your protocol is probably right - your user just doesn't have permissions.
The above solution will modify the inf
s that are not in the target columns. To remedy that,
lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)
The question is already answered, but you can resolve it like this:
const doSomething = (x) => x
export default doSomething;
import doSomething from "./dependency";
export default (x) => doSomething(x * 2);
jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";
describe('myModule', () => {
it('calls the dependency with double the input', () => {
doSomething.mockImplementation((x) => x * 10)
myModule(2);
expect(doSomething).toHaveBeenCalledWith(4);
console.log(myModule(2)) // 40
});
});
Here is how I do it in spring data rest
by using
org.springframework.web.util.ContentCachingRequestWrapper
and
org.springframework.web.util.ContentCachingResponseWrapper
/**
* Doogies very cool HTTP request logging
*
* There is also {@link org.springframework.web.filter.CommonsRequestLoggingFilter} but it cannot log request method
* And it cannot easily be extended.
*
* https://mdeinum.wordpress.com/2015/07/01/spring-framework-hidden-gems/
* http://stackoverflow.com/questions/8933054/how-to-read-and-copy-the-http-servlet-response-output-stream-content-for-logging
*/
public class DoogiesRequestLogger extends OncePerRequestFilter {
private boolean includeResponsePayload = true;
private int maxPayloadLength = 1000;
private String getContentAsString(byte[] buf, int maxLength, String charsetName) {
if (buf == null || buf.length == 0) return "";
int length = Math.min(buf.length, this.maxPayloadLength);
try {
return new String(buf, 0, length, charsetName);
} catch (UnsupportedEncodingException ex) {
return "Unsupported Encoding";
}
}
/**
* Log each request and respponse with full Request URI, content payload and duration of the request in ms.
* @param request the request
* @param response the response
* @param filterChain chain of filters
* @throws ServletException
* @throws IOException
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
long startTime = System.currentTimeMillis();
StringBuffer reqInfo = new StringBuffer()
.append("[")
.append(startTime % 10000) // request ID
.append("] ")
.append(request.getMethod())
.append(" ")
.append(request.getRequestURL());
String queryString = request.getQueryString();
if (queryString != null) {
reqInfo.append("?").append(queryString);
}
if (request.getAuthType() != null) {
reqInfo.append(", authType=")
.append(request.getAuthType());
}
if (request.getUserPrincipal() != null) {
reqInfo.append(", principalName=")
.append(request.getUserPrincipal().getName());
}
this.logger.debug("=> " + reqInfo);
// ========= Log request and response payload ("body") ========
// We CANNOT simply read the request payload here, because then the InputStream would be consumed and cannot be read again by the actual processing/server.
// String reqBody = DoogiesUtil._stream2String(request.getInputStream()); // THIS WOULD NOT WORK!
// So we need to apply some stronger magic here :-)
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);
filterChain.doFilter(wrappedRequest, wrappedResponse); // ======== This performs the actual request!
long duration = System.currentTimeMillis() - startTime;
// I can only log the request's body AFTER the request has been made and ContentCachingRequestWrapper did its work.
String requestBody = this.getContentAsString(wrappedRequest.getContentAsByteArray(), this.maxPayloadLength, request.getCharacterEncoding());
if (requestBody.length() > 0) {
this.logger.debug(" Request body:\n" +requestBody);
}
this.logger.debug("<= " + reqInfo + ": returned status=" + response.getStatus() + " in "+duration + "ms");
if (includeResponsePayload) {
byte[] buf = wrappedResponse.getContentAsByteArray();
this.logger.debug(" Response body:\n"+getContentAsString(buf, this.maxPayloadLength, response.getCharacterEncoding()));
}
wrappedResponse.copyBodyToResponse(); // IMPORTANT: copy content of response back into original response
}
}
Basically
Start debugging your project
Most probably , your errors will be fixed by then
Hope it works for you
#nav ul {
display: inline-block;
list-style-type: none;
}
It should work, I tested it in your site.
You're looking for the zip builtin function. From the docs:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
As of Groovy 2.2 it is possible to declare a base script class with the new @BaseScript
AST transform annotation.
Example:
file MainScript.groovy:
abstract class MainScript extends Script {
def meaningOfLife = 42
}
file test.groovy:
import groovy.transform.BaseScript
@BaseScript MainScript mainScript
println "$meaningOfLife" //works as expected
I think this is an even simpler example
List<String> emptyList = new ArrayList<>();
Optional<String> opt2 = emptyList.stream().findFirst();
assertThrows(NoSuchElementException.class, () -> opt2.get());
Calling get()
on an optional containing an empty ArrayList
will throw a NoSuchElementException
. assertThrows
declares the expected exception and provides a lambda supplier (takes no arguments and returns a value).
Thanks to @prime for his answer which I hopefully elaborated on.
Add this at the start of main
ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");
//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());
Try this:
SELECT Locations.Name, Schools.Name
FROM Locations
INNER JOIN School_Locations ON School_Locations.Locations_Id = Locations.Id
INNER JOIN Schools ON School.Id = Schools_Locations.School_Id
WHERE Locations.Type = "coun"
You can join Locations to School_Locations and then School_Locations to School. This forms a set of all related Locations and Schools, which you can then widdle down using the WHERE clause to those whose Location is of type "coun."
I merged a few of the answers here into a script that uses CustomEvent to fire swiped events in the DOM. Add the 0.7k swiped-events.min.js script to your page and listen for swiped events:
document.addEventListener('swiped', function(e) {
console.log(e.target); // the element that was swiped
console.log(e.detail.dir); // swiped direction
});
document.addEventListener('swiped-left', function(e) {
console.log(e.target); // the element that was swiped
});
document.addEventListener('swiped-right', function(e) {
console.log(e.target); // the element that was swiped
});
document.addEventListener('swiped-up', function(e) {
console.log(e.target); // the element that was swiped
});
document.addEventListener('swiped-down', function(e) {
console.log(e.target); // the element that was swiped
});
You can also attach directly to an element:
document.getElementById('myBox').addEventListener('swiped-down', function(e) {
console.log(e.target); // the element that was swiped
});
You can specify the following attributes to tweak how swipe interaction functions in your page (these are optional).
<div data-swipe-threshold="10"
data-swipe-timeout="1000"
data-swipe-ignore="false">
Swiper, get swiping!
</div>
To set defaults application wide, set config attributes on topmost element:
<body data-swipe-threshold="100" data-swipe-timeout="250">
<div>Swipe me</div>
<div>or me</div>
</body>
Source code is available on Github
the $ sign in the string is for definition of interpolation string that is a feature in C# to interpolate the string is a "true string" that might contain interpolated expressions
for further information this is the source of the answer and example: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
If you need to hide and then remove the element use the remove method inside the callback function of hide method.
This should work
$target.hide("slow", function(){ $(this).remove(); })
A couple of things to enhance the other answers. First, you should never return a HashMap
, which is a specific implementation. Return instead a plain old java.util.Map
. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>
. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).
ieshims.dll
is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess
) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll
is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.
I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.
With angular 6 and rxjs 6 Observable.throw()
, Observable.off()
has been deprecated instead you need to use throwError
ex :
return this.http.get('yoururl')
.pipe(
map(response => response.json()),
catchError((e: any) =>{
//do your processing here
return throwError(e);
}),
);
In case someone is still searching for a query to display the difference in hr min and sec format: (This will display the difference in this format: 2 hr 20 min 22 secs)
SELECT
CAST(DATEDIFF(minute, StartDateTime, EndDateTime)/ 60 as nvarchar(20)) + ' hrs ' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)/60 as nvarchar(20)) + ' mins' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)% 60 as nvarchar(20)) + ' secs'
OR can be in the format as in the question:
CAST(DATEDIFF(minute, StartDateTime, EndDateTime)/ 60 as nvarchar(20)) + ':' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)/60 as nvarchar(20))
hi how to delete from datagridview
1.make query delete by id
2.type
tabletableadaptor.delete
query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);
>>> {i:i for i in range(1, 11)}
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
Use LESS with Bootstrap...
Here are the Bootstrap docs for how to use LESS
(they have moved since previous answers)
Check out this discussion [How to automatically generate junits?]
If you are starting new and its a java application then Spring ROO looks very interesting too!
Hope that helps.
When rejecting you should pass an rejection error, then wrap step error handlers in a function that checks whether the rejection should be processed or "rethrown" until the end of the chain :
// function mocking steps
function step(i) {
i++;
console.log('step', i);
return q.resolve(i);
}
// function mocking a failing step
function failingStep(i) {
i++;
console.log('step '+ i + ' (will fail)');
var e = new Error('Failed on step ' + i);
e.step = i;
return q.reject(e);
}
// error handler
function handleError(e){
if (error.breakChain) {
// handleError has already been called on this error
// (see code bellow)
log('errorHandler: skip handling');
return q.reject(error);
}
// firs time this error is past to the handler
console.error('errorHandler: caught error ' + error.message);
// process the error
// ...
//
error.breakChain = true;
return q.reject(error);
}
// run the steps, will fail on step 4
// and not run step 5 and 6
// note that handleError of step 5 will be called
// but since we use that error.breakChain boolean
// no processing will happen and the error will
// continue through the rejection path until done(,)
step(0) // 1
.catch(handleError)
.then(step) // 2
.catch(handleError)
.then(step) // 3
.catch(handleError)
.then(failingStep) // 4 fail
.catch(handleError)
.then(step) // 5
.catch(handleError)
.then(step) // 6
.catch(handleError)
.done(function(){
log('success arguments', arguments);
}, function (error) {
log('Done, chain broke at step ' + error.step);
});
What you'd see on the console :
step 1
step 2
step 3
step 4 (will fail)
errorHandler: caught error 'Failed on step 4'
errorHandler: skip handling
errorHandler: skip handling
Done, chain broke at step 4
Here is some working code https://jsfiddle.net/8hzg5s7m/3/
If you have specific handling for each step, your wrapper could be something like:
/*
* simple wrapper to check if rejection
* has already been handled
* @param function real error handler
*/
function createHandler(realHandler) {
return function(error) {
if (error.breakChain) {
return q.reject(error);
}
realHandler(error);
error.breakChain = true;
return q.reject(error);
}
}
then your chain
step1()
.catch(createHandler(handleError1Fn))
.then(step2)
.catch(createHandler(handleError2Fn))
.then(step3)
.catch(createHandler(handleError3Fn))
.done(function(){
log('success');
}, function (error) {
log('Done, chain broke at step ' + error.step);
});
If this is a submit button, use <input type="image" src="..." ... />
.
http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_IMAGE.html
If you want to specify the image with CSS, you'll have to use type="submit"
.
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
You need to select that column:
In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1
df
Out[41]:
Team First Season Total Games
0 Dallas Cowboys 1960 894
1 Chicago Bears 1920 1357
2 Green Bay Packers 1921 1339
3 Miami Dolphins 1966 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 1950 1003
So the syntax here is:
df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]
You can check the docs and also the 10 minutes to pandas which shows the semantics
EDIT
If you want to generate a boolean indicator then you can just use the boolean condition to generate a boolean Series and cast the dtype to int
this will convert True
and False
to 1
and 0
respectively:
In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)
df
Out[43]:
Team First Season Total Games
0 Dallas Cowboys 0 894
1 Chicago Bears 0 1357
2 Green Bay Packers 0 1339
3 Miami Dolphins 0 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 0 1003
If you're looking for the RPM.
rpm -qa | grep MySQL
Most of it's data is stored in /var/lib/mysql so that's another good place to look.
If it is installed
which mysql
will give you the location of the binary.
You could also do an
updatedb
and a
locate mysql
to find any mysql files.
Invoke mysql with the -N
(the alias for -N
is --skip-column-names
) option:
mysql -N ...
use testdb;
select * from names;
+------+-------+
| 1 | pete |
| 2 | john |
| 3 | mike |
+------+-------+
3 rows in set (0.00 sec)
Credit to ErichBSchulz for pointing out the -N alias.
To remove the grid (the vertical and horizontal lines) around the results use -s
(--silent
). Columns are separated with a TAB
character.
mysql -s ...
use testdb;
select * from names;
id name
1 pete
2 john
3 mike
To output the data with no headers and no grid just use both -s
and -N
.
mysql -sN ...
As said by Faiyaz, to get default backup location for the instance, you cannot get it into msdb, but you have to look into Registry. You can get it in T-SQL in using xp_instance_regread stored procedure like this:
EXEC master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQLServer',N'BackupDirectory'
The double backslash (\\) is because the spaces into that key name part (Microsoft SQL Server). The "MSSQL12.MSSQLSERVER" part is for default instance name for SQL 2014. You have to adapt to put your own instance name (look into Registry).
Using java 8 Stream API could simplify your job.
public static boolean inArray(int[] array, int check) {
return Stream.of(array).anyMatch(i -> i == check);
}
It's just you have the overhead of creating a new Stream
from Array
, but this gives exposure to use other Stream
API. In your case you may not want to create new method for one-line operation, unless you wish to use this as utility.
Hope this helps!
This debate boils down to the age-old question of whether the developers know best or whether the user knows best. Professional designers in all areas of human factors struggle with this every day.
Ted has made a point in that one of the most downloaded apps on the Market is the 'App Killer'. People get a bit of extra serotonin when they quit applications. They're used to it with a desktop/laptop. It keeps things moving fast. It keeps the processor cool and the fan from turning on. It uses less power.
When you consider that a mobile device is a much smaller ship, then you can especially appreciate their incentive to 'throw overboard what you no longer need'. Now the developers of Android have reasoned that the OS knows best and that quitting an app is antique. I wholeheartedly support this.
However, I also believe that you should not frustrate the user, even if that frustration is borne out of their own ignorance. Because of that, I conclude that having a 'Quit' option is good design, even if it is mostly a placebo button that does nothing more than close a View.
Imagine the string could be reversed. Then it is really easy. Instead of working on the string:
"My little cat" (1)
you work with
"tac elttil yM" (2)
With =LEFT(A1;FIND(" ";A1)-1)
in A2 you get "My"
with (1) and "tac"
with (2), which is reversed "cat"
, the last word in (1).
There are a few VBAs around to reverse a string. I prefer the public VBA function ReverseString
.
Install the above as described. Then with your string in A1, e.g., "My little cat"
and this function in A2:
=ReverseString(LEFT(ReverseString(A1);IF(ISERROR(FIND(" ";A1));
LEN(A1);(FIND(" ";ReverseString(A1))-1))))
you'll see "cat"
in A2.
The method above assumes that words are separated by blanks. The IF
clause is for cells containing single words = no blanks in cell. Note: TRIM
and CLEAN
the original string are useful as well. In principle it reverses the whole string from A1 and simply finds the first blank in the reversed string which is next to the last (reversed) word (i.e., "tac "
). LEFT
picks this word and another string reversal reconstitutes the original order of the word (" cat"
). The -1
at the end of the FIND
statement removes the blank.
The idea is that it is easy to extract the first(!) word in a string with LEFT
and FIND
ing the first blank. However, for the last(!) word the RIGHT
function is the wrong choice when you try to do that because unfortunately FIND does not have a flag for the direction you want to analyse your string.
Therefore the whole string is simply reversed. LEFT
and FIND
work as normal but the extracted string is reversed. But his is no big deal once you know how to reverse a string. The first ReverseString
statement in the formula does this job.
Notice that you're using Observable#map to convert the raw Response
object your base Observable emits to a parsed representation of the JSON response.
If I understood you correctly, you want to map
again. But this time, converting that raw JSON to instances of your Model
. So you would do something like:
http.get('api/people.json')
.map(res => res.json())
.map(peopleData => peopleData.map(personData => new Person(personData)))
So, you started with an Observable that emits a Response
object, turned that into an observable that emits an object of the parsed JSON of that response, and then turned that into yet another observable that turned that raw JSON into an array of your models.
Put the line in a stringstream and extract word by word back:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string t;
getline(cin,t);
istringstream iss(t);
string word;
while(iss >> word) {
/* do stuff with word */
}
}
Of course, you can just skip the getline part and read word by word from cin
directly.
And here you can read why is using namespace std
considered bad practice.
start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.
start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh
hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.
Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,
bin/hadoop-daemon.sh start datanode
Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.
Hope this answers your query.
If you want to join all PDF files in a directory with Ghostscript, you can use find to do just that. Here's an example
find . -name '*.pdf' -exec gs -o -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=../out.pdf {} +
Will find all pdf in current directory, and create out.pdf in parent directory. Might be useful if they're looking for a quick way for do an entire directory with ghostscript.
Browsers make their best guess with the data they receive. This works for markup (which Websites often get wrong) and other media content. A program that receives a file can often figure out what its received regardless of the MIME content type it's been told.
This isn't something you should rely on however. It's recommended you always use the correct MIME content.
function ping($ip){
$output = shell_exec("ping $ip");
var_dump($output);
}
ping('127.0.0.1');
UPDATE: If you pass an hardcoded IP (like in this example and most of the real-case scenarios), this function can be enough.
But since some users seem to be very concerned about safety, please remind to never pass user generated inputs to the shell_exec
function:
If the IP comes from an untrusted source, at least check it with a filter before using it.
I had the same question before visiting this thread. For me the sys.stdout.write worked only if I properly flush the buffer i.e.
for x in range(10):
sys.stdout.write('\r'+str(x))
sys.stdout.flush()
Without flushing, the result is printed only at the end out the script
You aren't going to be able to do this from the HashMap class alone.
I would take the Map<String, String> codes
, construct a reverse map of TreeMap<String, String> reversedMap
where you map the values of the codes
Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.
Map<String, String> reversedMap = new TreeMap<String, String>(codes);
//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.
You can use the Google Docs PDF-viewing widget, if you don't mind having them host the "application" itself.
I had more suggestions, but stack overflow only lets me post one hyperlink as a new user, sorry.
Of course, this is not a CSS-solution, but you can use the CDN Proton with filter
:
body {
background: url('https://i0.wp.com/IMAGEURL?w=600&filter=blurgaussian&smooth=1');
}
It is from https://developer.wordpress.com/docs/photon/api/#filter
One approach: if you can guarantee unrelated applications won't use the files in a conflicting manner, just create a pool of files of varying sizes in a specific directory, then create links to them when needed.
For example, have a pool of files called:
Then, if you have an application that needs a 1G file called /home/oracle/logfile, execute a "ln /home/bigfiles/1024M-A /home/oracle/logfile
".
If it's on a separate filesystem, you will have to use a symbolic link.
The A/B/etc files can be used to ensure there's no conflicting use between unrelated applications.
The link operation is about as fast as you can get.
Use the document.createElement function and then add it as a child of your select.
var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);
Only such dialog is FileDialog. Its part of WinForms, but its actually only wrapper around WinAPI standard OS file dialog. And I don't think it is ugly, its actually part of OS, so it looks like OS it is run on.
Other way, there is nothing to help you with. You either need to look for 3rd party implementation, either free (and I don't think there are any good) or paid.
http://jsfiddle.net/Bq6eK/215/
I did not modify your code for this solution, I wrote my own instead. My solution isn't quite what you asked for, but maybe you could build on it with existing knowledge. I commented the code as well so you know what exactly I'm doing with the changes.
As a solution to "avoid setting the height in JavaScript", I just made 'maxHeight' a parameter in the JS function called toggleHeight. Now it can be set in the HTML for each div of class expandable.
I'll say this up front, I'm not super experienced with front-end languages, and there's an issue where I need to click the 'Show/hide' button twice initially before the animation starts. I suspect it's an issue with focus.
The other issue with my solution is that you can actually figure out what the hidden text is without pressing the show/hide button just by clicking in the div and dragging down, you can highlight the text that's not visible and paste it to a visible space.
My suggestion for a next step on top of what I've done is to make it so that the show/hide button changes dynamically. I think you can figure out how to do that with what you already seem to know about showing and hiding text with JS.
Chrome on Android makes it possible to use the Chrome developer tools on the desktop to inspect the HTML that was loaded from the Chrome application on the Android device.
See: https://developers.google.com/chrome-developer-tools/docs/remote-debugging
Note: if you have vs2010 and vs2008 and you want to reset the 2008, you will need to specify in command line the whole path. like this:
"C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" /resetsettings
If you don't specify the path (like devenv.exe /resetsettings
), it will reset the latest version of Visual studio installed on your computer.
Why not using just css?
<div id="wrapper">
<input onkeyup="keyup(event)">
<div id="ghost"></div>
</div>
function keyup(e) {_x000D_
document.getElementById('ghost').innerText = e.target.value;_x000D_
}
_x000D_
#wrapper {_x000D_
position: relative;_x000D_
min-width: 30px;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
input {_x000D_
position: absolute;_x000D_
left:0;_x000D_
right:0;_x000D_
border:1px solid blue;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#ghost {_x000D_
color: transparent;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<input onkeyup="keyup(event)">_x000D_
<div id="ghost"></div>_x000D_
</div>
_x000D_
wrapper {
position: relative;
min-width: 30px;
border: 1px solid red;
display: inline-block;
}
input {
position: absolute;
left:0;
right:0;
width: 100%;
}
#ghost {
color: transparent;
}
this code was introduced by @Iain Todd to and I thought I should share it
As of May 1st 2019, use BottomSheetTheme.
MaterialApp(
theme: ThemeData(
// Draw all modals with a white background and top rounded corners
bottomSheetTheme: BottomSheetThemeData(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(10))
)
)
),
Introduced recently, using a theme to control the sheets style should be the most best to this problem.
If you want to theme different bottom sheets differently, include a new Theme object in the appropriate subtree to override the bottom sheet theme just for that area.
If for some reason you'd still like to override the theme manually when launching a bottom sheet, showBottomSheet and showModalBottomSheet now have a backgroundColor parameter. Use it like this:
showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context,
builder: (c) {return NavSheet();},
);
Using the theme allows bottom sheets to be re-used regardless of the app / app's current theme, and has none of the negative side effects of setting canvas color as mentioned.
import sys
sys.stdout.write('h')
sys.stdout.flush()
sys.stdout.write('m')
sys.stdout.flush()
You need to call sys.stdout.flush()
because otherwise it will hold the text in a buffer and you won't see it.
It is hard to make a good timing, because the performance.dominteractive is miscalulated (anyway an interesting link for timing developers).
When dom is parsed it still may load and execute deferred scripts. And inline scripts waiting for css (css blocking dom) has to be loaded also until DOMContentloaded. So it is not yet parsed?
And we have readystatechange event where we can look at readyState that unfortunately is missing "dom is parsed" that happens somewhere between "loaded" and "interactive".
Everything becomes problematic when even not the Timing API gives us a time when dom stoped parsing HTML and starting The End process. This standard say the first point has to be that "interactive" fires precisely after dom parsed! Both Chrome and FF has implemented it when document has finished loading sometime after it has parsed. They seem to (mis)interpret the standars as parsing continues beyond deferred scripts executed while people misinterpret DOMContentLoaded as something hapen before defered executing and not after. Anyway...
My recommendation for you is to read about? Navigation Timing API. Or go the easy way and choose a oneliner of these, or run all three and look in your browsers console ...
document.addEventListener('readystatechange', function() { console.log("Fiered '" + document.readyState + "' after " + performance.now() + " ms"); });
document.addEventListener('DOMContentLoaded', function() { console.log("Fiered DOMContentLoaded after " + performance.now() + " ms"); }, false);
window.addEventListener('load', function() { console.log("Fiered load after " + performance.now() + " ms"); }, false);
The time is in milliseconds after document started. I have verified with Navigation? Timing API.
To get seconds for exampe from the time you did var ti = performance.now()
you can do parseInt(performance.now() - ti) / 1000
Instead of that kind of performance.now() subtractions the code get little shorter by User Timing API where you set marks in your code and measure between marks.
I don't know if my solution is best practice, but I achieved loading a bitmap with my desired scaling by using the inDensity
and inTargetDensity
options. inDensity
is 0
initially when not loading a drawable resource, so this approach is for loading non resource images.
The variables imageUri
, maxImageSideLength
and context
are parameters of my method. I posted only the method implementation without the wrapping AsyncTask for clarity.
ContentResolver resolver = context.getContentResolver();
InputStream is;
try {
is = resolver.openInputStream(imageUri);
} catch (FileNotFoundException e) {
Log.e(TAG, "Image not found.", e);
return null;
}
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, opts);
// scale the image
float maxSideLength = maxImageSideLength;
float scaleFactor = Math.min(maxSideLength / opts.outWidth, maxSideLength / opts.outHeight);
// do not upscale!
if (scaleFactor < 1) {
opts.inDensity = 10000;
opts.inTargetDensity = (int) ((float) opts.inDensity * scaleFactor);
}
opts.inJustDecodeBounds = false;
try {
is.close();
} catch (IOException e) {
// ignore
}
try {
is = resolver.openInputStream(imageUri);
} catch (FileNotFoundException e) {
Log.e(TAG, "Image not found.", e);
return null;
}
Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);
try {
is.close();
} catch (IOException e) {
// ignore
}
return bitmap;
I believe it means 'anything but a whitespace character'.
The code below worked. Corrected the issue on I.E 9.0 atleast. Hope this helps
var oTable = $('#tblList').dataTable({
"sScrollY": "320px",
"bScrollCollapse": true,
});
setTimeout(function(){
oTable.fnAdjustColumnSizing();
},10);
Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:
//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ1
{
static void Main( )
{
//Load xml
XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new
{
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
StringBuilder result = new StringBuilder(); //had to add this to make the result work
//Loop through results
foreach (var lv1 in lv1s)
{
result.AppendLine(" " + lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result.ToString()); //added this so you could see the output on the console
}
}
And next:
//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ
{
static void Main( )
{
XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
Console.WriteLine(GetOutline(0, rootElement));
}
static private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
}
These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.
EDIT: added @eglasius' example as well since it became useful to me:
//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ2
{
static void Main( )
{
StringBuilder result = new StringBuilder(); //needed for result below
XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Console.WriteLine(result);//added this so you could see the result
}
}
Play cross browser compatible notifications
As adviced by @Tim Tisdall from this post , Check Howler.js Plugin.
Browsers like chrome disables javascript
execution when minimized or inactive for performance improvements. But This plays notification sounds even if browser is inactive or minimized by the user.
var sound =new Howl({
src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
'../sounds/rings.aiff'],
autoplay: true,
loop: true
});
sound.play();
Hope helps someone.
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
You need to use a delegated event handler, as the #add
elements dynamically appended won't have the click event bound to them. Try this:
$("#buildyourform").on('click', "#add", function() {
// your code...
});
Also, you can make your HTML strings easier to read by mixing line quotes:
var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');
Or even supplying the attributes as an object:
var fieldWrapper = $('<div></div>', {
'class': 'fieldwrapper',
'name': 'field' + intId,
'id': 'field' + intId
});
In Python you may use the in
operator. You can do stuff like this:
>>> "c" in "abc"
True
Taking this further, you can check for complex structures, like tuples:
>>> (2, 4, 8) in ((1, 2, 3), (2, 4, 8))
True
Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html
One way to handle this is to create a dynamic javascript file with the URLs embedded in it. Here are the steps (if you are using Spring MVC)
@RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public String dynamicJS(HttpServletRequest request) {
return "Your javascript code....";
}
If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received.
int func(int arr[], ...){
.
.
.
}
int func(int arr[SIZE], ...){
.
.
.
}
int func(int* arr, ...){
.
.
.
}
So, you are modifying the original values.
Thanks !!!
Support for peer to peer WiFi networking is available since API level 14.
it is working perfectly by only using html
<p><a href="#"onclick="window.open('http://google.com');window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
On Linux-based systems you can view/edit a configuration file by
vi/vim/nano .git/config
Make sure you are inside the Git init folder.
If you want to work with --global config
, it's
vi/vim/nano .gitconfig
on /home/userName
This should help with editing: https://help.github.com/categories/setup/
Notice you can use WHEN exception THEN NULL
the same way as you would use WHEN exception THEN continue
. Example:
DECLARE
extension_already_exists EXCEPTION;
PRAGMA EXCEPTION_INIT(extension_already_exists, -20007);
l_hidden_col_name varchar2(32);
BEGIN
FOR t IN ( SELECT table_name, cast(extension as varchar2(200)) ext
FROM all_stat_extensions
WHERE owner='{{ prev_schema }}'
and droppable='YES'
ORDER BY 1
)
LOOP
BEGIN
l_hidden_col_name := dbms_stats.create_extended_stats('{{ schema }}', t.table_name, t.ext);
EXCEPTION
WHEN extension_already_exists THEN NULL; -- ignore exception and go to next loop iteration
END;
END LOOP;
END;
Just use the plain ol' class selector.
$('#my_id .my_class')
It doesn't matter if the element also has other classes. It has the .my_class class, and it's somewhere inside #my_id, so it will match that selector.
According to the jQuery selector performance documentation, it's faster to use the two selectors separately, like this:
$('#my_id').find('.my_class')
Here's the relevant part of the documentation:
ID-Based Selectors
// Fast: $( "#container div.robotarm" ); // Super-fast: $( "#container" ).find( "div.robotarm" );
The
.find()
approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled usingdocument.getElementById()
, which is extremely fast because it is native to the browser.
Selecting by ID or by class alone (among other things) invokes browser-supplied functions like document.getElementById()
which are quite rapid, whereas using a descendent selector invokes the Sizzle engine as mentioned which, although fast, is slower than the suggested alternative.
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
I found that switching to use full html instead of filtered html (below the editor in the Text Format dropdown box) is what fixed this problem for me. Otherwise the style would disappear.
The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.
Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.
I know this is old, but I have to add this in here..
And while this is not a full answer, it is an 'IN ADDITION TO'
The address bar will not disappear if you're NOT using https.
ALSO
If you are using https and the address bar still won't hide, you might have some https errors in your webpage (such as certain images being served from a non-https location.)
Hope this helps..
I've got similar error using camel-mail component to send e-mails by gmail smtp.
The solution was changing from TLS port (587) to SSL port (465) as below:
<route id="sendMail">
<from uri="jason:toEmail"/>
<convertBodyTo type="java.lang.String"/>
<setHeader headerName="Subject"><constant>Something</constant></setHeader>
<to uri="smtps://smtp.gmail.com:[email protected]&password=mypw&[email protected]&debugMode=true&mail.smtp.starttls.enable=true"/>
</route>
mysql GROUP_CONCAT
function could help https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat
SELECT ProductID, GROUP_CONCAT(DISTINCT ProductName) as Names, SUM(OrderQuantity)
FROM OrderDetails GROUP BY ProductID
This would return:
ProductID Names OrderQuantity
1001 red 5
1002 red,black 6
1003 orange 8
1004 black,orange 15
Similar idea as the one @Urs Marian here posted https://stackoverflow.com/a/38779277/906265
In Access, you will probably find a Join is quicker unless your tables are very small:
SELECT DISTINCT Table1.Column1
FROM Table1
LEFT JOIN Table2
ON Table1.Column1 = Table2.Column1
WHERE Table2.Column1 Is Null
This will exclude from the list all records with a match in Table2.
This is the simplest wat to get the File object to which a certain URL object is pointing at:
File file=new File(url.toURI());
Now, for your concrete questions:
- finding all resources in the META-INF "directory":
You can indeed get the File object pointing to this URL
Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
URL metaInf=en.nextElement();
File fileMetaInf=new File(metaInf.toURI());
File[] files=fileMetaInf.listFiles();
//or
String[] filenames=fileMetaInf.list();
}
- all resources named bla.xml (recursivly)
In this case, you'll have to do some custom code. Here is a dummy example:
final List<File> foundFiles=new ArrayList<File>();
FileFilter customFilter=new FileFilter() {
@Override
public boolean accept(File pathname) {
if(pathname.isDirectory()) {
pathname.listFiles(this);
}
if(pathname.getName().endsWith("bla.xml")) {
foundFiles.add(pathname);
return true;
}
return false;
}
};
//rootFolder here represents a File Object pointing the root forlder of your search
rootFolder.listFiles(customFilter);
When the code is run, you'll get all the found ocurrences at the foundFiles
List.
First off; best practice would be to get the users Desktop folder with
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Then you can find all the files with something like
string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.
Then you could copy or move the files by enumerating the above collection like
// For copying...
foreach (string s in files)
{
File.Copy(s, "C:\newFolder\newFilename.txt");
}
// ... Or for moving
foreach (string s in files)
{
File.Move(s, "C:\newFolder\newFilename.txt");
}
Please note that you will have to include the filename in your Copy()
(or Move()
) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.
With that in mind you could also check out the DirectoryInfo
and FileInfo
classes.
These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily
Check out these for more info:
http://msdn.microsoft.com/en-us/library/system.io.directory.aspx