This problem will solve when we change the version of apache-maven
I faced it and it was solved when i used apache-maven-2.2.1
In my case, I had started untar before the uploading of the tar file was complete.
Surprised no one has posted the type-safe C++ version yet:
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Benefits:
copysign
is slow, especially if you need to promote and then narrow again. This is branchless and optimizes excellentlyCaveats:
The < 0
part of the check triggers GCC's -Wtype-limits
warning when instantiated for an unsigned type. You can avoid this by using some overloads:
template <typename T> inline constexpr
int signum(T x, std::false_type is_signed) {
return T(0) < x;
}
template <typename T> inline constexpr
int signum(T x, std::true_type is_signed) {
return (T(0) < x) - (x < T(0));
}
template <typename T> inline constexpr
int signum(T x) {
return signum(x, std::is_signed<T>());
}
(Which is a good example of the first caveat.)
logging
Instead of using the basic print()
function, the more flexible logging
module can be used to log the exception. The logging
module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)
Logging an exception can be done with the module-level function logging.exception()
like so:
import logging
try:
1/0
except BaseException:
logging.exception("An exception was thrown!")
Output:
ERROR:root:An exception was thrown!
Traceback (most recent call last):
File ".../Desktop/test.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
Notes:
the function logging.exception()
should only be called from an exception handler
the logging
module should not be used inside a logging handler to avoid a RecursionError
(thanks @PrakharPandey)
It's also possible to log the exception with another log-level by using the keyword argument exc_info=True
like so:
logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)
Setting the img
tag color
works
img {color:#fff}
body {background:#000022}_x000D_
img {color:#fff}
_x000D_
<img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" />
_x000D_
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.
While gcc 3.2.3 was more forgiving of the issue, gcc 4.1.2 is highlighting a potentially serious issue for the linking of your program later. Rather then trying to suppress the error you should make the forward declaration match the function declaration.
If you intended for the function to be globally available (as per the forward declaration) then don't subsequently declare it as static. Likewise if it's indented to be locally scoped then make the forward declaration static to match.
Strings, though they are not set
types, have a valuable in
property during validation in scripts:
yn = input("Are you sure you want to do this? ")
if yn in "yes":
#accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes'
return True
return False
I hope this helps you better understand the use of in
with this example.
in A you have used a definition of B which is not given until then , that's why the compiler is giving error .
use this code
window.onhashchange = function() {
//code
}
with jQuery
$(window).bind('hashchange', function() {
//code
});
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
Thank to Brian for the code. I was trying to connect to the sql server with {call spname(?,?)}
and I got errors, but when I change my code to exec sp...
it works very well.
I post my code in hope this helps others with problems like mine:
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?,?,?,?,?,?");
cs.setEscapeProcessing(true);
cs.setQueryTimeout(90);
cs.setString(1, "valueA");
cs.setString(2, "valueB");
cs.setString(3, "0418");
//commented, because no need to register parameters out!, I got results from the resultset.
//cs.registerOutParameter(1, Types.VARCHAR);
//cs.registerOutParameter(2, Types.VARCHAR);
rs = cs.executeQuery();
ArrayList<ObjectX> listaObjectX = new ArrayList<ObjectX>();
while (rs.next()) {
ObjectX to = new ObjectX();
to.setFecha(rs.getString(1));
to.setRefId(rs.getString(2));
to.setRefNombre(rs.getString(3));
to.setUrl(rs.getString(4));
listaObjectX.add(to);
}
return listaObjectX;
} catch (SQLException se) {
System.out.println("Error al ejecutar SQL"+ se.getMessage());
se.printStackTrace();
throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.
Try this one:
find . -type f -printf "%T@ %p\n" | sort -nr | cut -d\ -f2-
Yes IFNULL function will be working to achieve your desired result.
SELECT uo.order_id, uo.order_total, uo.order_status,
(SELECT IFNULL(SUM(uop.price * uop.qty),0)
FROM uc_order_products uop
WHERE uo.order_id = uop.order_id
) AS products_subtotal,
(SELECT IFNULL(SUM(upr.amount),0)
FROM uc_payment_receipts upr
WHERE uo.order_id = upr.order_id
) AS payment_received,
(SELECT IFNULL(SUM(uoli.amount),0)
FROM uc_order_line_items uoli
WHERE uo.order_id = uoli.order_id
) AS line_item_subtotal
FROM uc_orders uo
WHERE uo.order_status NOT IN ("future", "canceled")
AND uo.uid = 4172;
A catch-all jQuery custom event based on an extension of it's core methods like it was proposed by different people in this thread:
(function() {
var ev = new $.Event('event.css.jquery'),
css = $.fn.css,
show = $.fn.show,
hide = $.fn.hide;
// extends css()
$.fn.css = function() {
css.apply(this, arguments);
$(this).trigger(ev);
};
// extends show()
$.fn.show = function() {
show.apply(this, arguments);
$(this).trigger(ev);
};
// extends hide()
$.fn.hide = function() {
hide.apply(this, arguments);
$(this).trigger(ev);
};
})();
An external library then, uses sth like $('selector').css('property', value)
.
As we don't want to alter the library's code but we DO want to extend it's behavior we do sth like:
$('#element').on('event.css.jquery', function(e) {
// ...more code here...
});
Example: user clicks on a panel that is built by a library. The library shows/hides elements based on user interaction. We want to add a sensor that shows that sth has been hidden/shown because of that interaction and should be called after the library's function.
Another example: jsfiddle.
FYI this turned out to be an issue for me where I had two tables in a statement like the following:
SELECT * FROM table1
UNION ALL
SELECT * FROM table2
It worked, but then somewhere along the line the order of columns in one of the table definitions got changed. Changing the *
to SELECT column1, column2
fixed the issue. No idea how that happened, but lesson learned!
generate .class file separate and paste it into relevant package into the workspace. Refresh Project.
What's Context
exactly?
Per the Android reference documentation, it's an entity that represents various environment data. It provides access to local files, databases, class loaders associated to the environment, services (including system-level services), and more. Throughout this book, and in your day-to-day coding with Android, you'll see the Context passed around frequently.
From the "Android in Practice" book, p. 60.
Several Android APIs require a Context
as parameter
If you look through the various Android APIs, you’ll
notice that many of them take an android.content.Context
object as a
parameter. You’ll also see that an Activity or a Service is usually used as a
Context
. This works because both of these classes extend from Context
.
The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:
DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';
I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database
line=`sed -n 2p myfile`
echo $line
Assuming you mean "list" where you say "array", you can do
if item in my_list:
# whatever
This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.
isset
will return true even if the variable is "". isset
returns false only if a variable is null. What you should be doing:
if (!empty($web)) {
// foo
}
This will check that he variable is not empty.
Hope this helps
I've been using this module ng2 truncate, its pretty easy, import module and u are ready to go... in {{ data.title | truncate : 20 }}
var cur_value = $(this).find('option:selected').text();
Since option
is likely to be immediate child of select
you can also use:
var cur_value = $(this).children('option:selected').text();
That is why the new __dir__()
method has been added in python 2.6
see:
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
Round tripping dates through strings has always been a pain...but the docs to indicate that the 'o' specifier is the one to use for round tripping which captures the UTC state. When parsed the result will usually have Kind == Utc if the original was UTC. I've found that the best thing to do is always normalize dates to either UTC or local prior to serializing then instruct the parser on which normalization you've chosen.
DateTime now = DateTime.Now;
DateTime utcNow = now.ToUniversalTime();
string nowStr = now.ToString( "o" );
string utcNowStr = utcNow.ToString( "o" );
now = DateTime.Parse( nowStr );
utcNow = DateTime.Parse( nowStr, null, DateTimeStyles.AdjustToUniversal );
Debug.Assert( now == utcNow );
I don't think you can do this in XML (at least not in Android), but I've found a good solution posted here that looks like it'd be a great help!
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, width, height,
new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);
return lg;
}
};
PaintDrawable p=new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
Basically, the int array allows you to select multiple color stops, and the following float array defines where those stops are positioned (from 0 to 1). You can then, as stated, just use this as a standard Drawable.
Edit: Here's how you could use this in your scenario. Let's say you have a Button defined in XML like so:
<Button
android:id="@+id/thebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press Me!"
/>
You'd then put something like this in your onCreate() method:
Button theButton = (Button)findViewById(R.id.thebutton);
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, 0, theButton.getHeight(),
new int[] {
Color.LIGHT_GREEN,
Color.WHITE,
Color.MID_GREEN,
Color.DARK_GREEN }, //substitute the correct colors for these
new float[] {
0, 0.45f, 0.55f, 1 },
Shader.TileMode.REPEAT);
return lg;
}
};
PaintDrawable p = new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
theButton.setBackground((Drawable)p);
I cannot test this at the moment, this is code from my head, but basically just replace, or add stops for the colors that you need. Basically, in my example, you would start with a light green, fade to white slightly before the center (to give a fade, rather than a harsh transition), fade from white to mid green between 45% and 55%, then fade from mid green to dark green from 55% to the end. This may not look exactly like your shape (Right now, I have no way of testing these colors), but you can modify this to replicate your example.
Edit: Also, the 0, 0, 0, theButton.getHeight()
refers to the x0, y0, x1, y1 coordinates of the gradient. So basically, it starts at x = 0 (left side), y = 0 (top), and stretches to x = 0 (we're wanting a vertical gradient, so no left to right angle is necessary), y = the height of the button. So the gradient goes at a 90 degree angle from the top of the button to the bottom of the button.
Edit: Okay, so I have one more idea that works, haha. Right now it works in XML, but should be doable for shapes in Java as well. It's kind of complex, and I imagine there's a way to simplify it into a single shape, but this is what I've got for now:
green_horizontal_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners
android:radius="3dp"
/>
<gradient
android:angle="0"
android:startColor="#FF63a34a"
android:endColor="#FF477b36"
android:type="linear"
/>
</shape>
half_overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid
android:color="#40000000"
/>
</shape>
layer_list.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:drawable="@drawable/green_horizontal_gradient"
android:id="@+id/green_gradient"
/>
<item
android:drawable="@drawable/half_overlay"
android:id="@+id/half_overlay"
android:top="50dp"
/>
</layer-list>
test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<TextView
android:id="@+id/image_test"
android:background="@drawable/layer_list"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:gravity="center"
android:text="Layer List Drawable!"
android:textColor="@android:color/white"
android:textStyle="bold"
android:textSize="26sp"
/>
</RelativeLayout>
Okay, so basically I've created a shape gradient in XML for the horizontal green gradient, set at a 0 degree angle, going from the top area's left green color, to the right green color. Next, I made a shape rectangle with a half transparent gray. I'm pretty sure that could be inlined into the layer-list XML, obviating this extra file, but I'm not sure how. But okay, then the kind of hacky part comes in on the layer_list XML file. I put the green gradient as the bottom layer, then put the half overlay as the second layer, offset from the top by 50dp. Obviously you'd want this number to always be half of whatever your view size is, though, and not a fixed 50dp. I don't think you can use percentages, though. From there, I just inserted a TextView into my test.xml layout, using the layer_list.xml file as my background. I set the height to 100dp (twice the size of the offset of the overlay), resulting in the following:
Tada!
One more edit: I've realized you can just embed the shapes into the layer list drawable as items, meaning you don't need 3 separate XML files any more! You can achieve the same result combining them like so:
layer_list.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners
android:radius="3dp"
/>
<gradient
android:angle="0"
android:startColor="#FF63a34a"
android:endColor="#FF477b36"
android:type="linear"
/>
</shape>
</item>
<item
android:top="50dp"
>
<shape
android:shape="rectangle"
>
<solid
android:color="#40000000"
/>
</shape>
</item>
</layer-list>
You can layer as many items as you like this way! I may try to play around and see if I can get a more versatile result through Java.
I think this is the last edit...: Okay, so you can definitely fix the positioning through Java, like the following:
TextView tv = (TextView)findViewById(R.id.image_test);
LayerDrawable ld = (LayerDrawable)tv.getBackground();
int topInset = tv.getHeight() / 2 ; //does not work!
ld.setLayerInset(1, 0, topInset, 0, 0);
tv.setBackgroundDrawable(ld);
However! This leads to yet another annoying problem in that you cannot measure the TextView until after it has been drawn. I'm not quite sure yet how you can accomplish this...but manually inserting a number for topInset does work.
I lied, one more edit
Okay, found out how to manually update this layer drawable to match the height of the container, full description can be found here. This code should go in your onCreate() method:
final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable)tv.getBackground();
ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
}
});
And I'm done! Whew! :)
A checkbox has a linked cell, which contains the True/False representing the state of the checkbox. It is much easier to reference this cell's value than the value of the embedded object which is the checkbox.
Manually: Right click on the checkbox, choose Format, click in the Linked Cell box, and select the cell to contain the checkbox value.
In code:
Set cbTime = ActiveSheet.CheckBoxes.Add(100, 100, 50, 15)
With cbTime
.Value = xlOff ' = unchecked xlOn = checked
.LinkedCell = "$A$1"
End With
Run:
mysqldump -u root -p your_target_DB --compatible=mssql > MSSQL_Compatible_Data.sql
Do you want to see a process bar?
pv mysqldump -u root -p your_target_DB --compatible=mssql > MSSQL_Compatible_Data.sql
The problem is caused by the fact that the Model
's toArray()
method ignores any accessors which do not directly relate to a column in the underlying table.
As Taylor Otwell mentioned here, "This is intentional and for performance reasons." However there is an easy way to achieve this:
class EventSession extends Eloquent {
protected $table = 'sessions';
protected $appends = array('availability');
public function getAvailabilityAttribute()
{
return $this->calculateAvailability();
}
}
Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.
Old answer (for Laravel versions < 4.08):
The best solution that I've found is to override the toArray()
method and either explicity set the attribute:
class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
$array['upper'] = $this->upper;
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
or, if you have lots of custom accessors, loop through them all and apply them:
class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
foreach ($this->getMutatedAttributes() as $key)
{
if ( ! array_key_exists($key, $array)) {
$array[$key] = $this->{$key};
}
}
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
I had to change the js file, so to include "function()" at the beginning of it, and also "()" at the end line. That solved the problem
This is not specifically for eclipse, but the way I got around this was by creating a symbolic link to my maven repository and pointing it to something like "C:\R". Then I added the following to my settings.xml file:
<localRepository>C:\R</localRepository>
The maven repository path was contributing to the length problems in my windows machine.
Try this:
public interface MyService {
//Code
}
@Component("One")
public class MyServiceOne implements MyService {
//Code
}
@Component("Two")
public class MyServiceTwo implements MyService {
//Code
}
Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.
Make certain to specify
stringsAsFactors=FALSE
when creating the dataframe:
> rm(list=ls())
> trigonometry <- data.frame(character(0), numeric(0), stringsAsFactors=FALSE)
> colnames(trigonometry) <- c("theta", "sin.theta")
> trigonometry
[1] theta sin.theta
<0 rows> (or 0-length row.names)
> trigonometry[nrow(trigonometry) + 1, ] <- c("0", sin(0))
> trigonometry[nrow(trigonometry) + 1, ] <- c("pi/2", sin(pi/2))
> trigonometry
theta sin.theta
1 0 0
2 pi/2 1
> typeof(trigonometry)
[1] "list"
> class(trigonometry)
[1] "data.frame"
Failing to use stringsAsFactors=FALSE
when creating the dataframe will
result in the following error when attempting to add the new row:
> trigonometry[nrow(trigonometry) + 1, ] <- c("0", sin(0))
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = "0") :
invalid factor level, NA generated
LatLngBounds
must be defined with points in (south-west, north-east) order. Your points are not in that order.
The general fix, especially if you don't know the points will definitely be in that order, is to extend an empty bounds:
var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);
The API will sort out the bounds.
In neither case can you modify a string literal, regardless of whether the pointer to that string literal is declared as char *
or const char *
.
However, the difference is that if the pointer is const char *
then the compiler must give a diagnostic if you attempt to modify the pointed-to value, but if the pointer is char *
then it does not.
Or you could just perform a trim()
on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)
As described here: Angular NgModelController, you should provide the <input
with the required controller ngModel
<input submit-required="true" ng-model="user.Name"></input>
A stream is a continuous flow of liquid, air, or gas.
Java stream is a flow of data from a source into a destination. The source or destination can be a disk, memory, socket, or other programs. The data can be bytes, characters, or objects. The same applies for C# or C++ streams. A good metaphor for Java streams is water flowing from a tap into a bathtub and later into a drainage.
The data represents the static part of the stream; the read and write methods the dynamic part of the stream.
InputStream
represents a flow of data from the source, the OutputStream
represents a flow of data into the destination.
Finally, InputStream
and OutputStream
are abstractions over low-level access to data, such as C file pointers.
Create a new Android Application Project
and uncheck Create activity
in step two (Configure project).
If your file and its metadata creating one resource, its perfectly fine to upload them both in one request. Sample request would be :
POST https://target.com/myresources/resourcename HTTP/1.1
Accept: application/json
Content-Type: multipart/form-data;
boundary=-----------------------------28947758029299
Host: target.com
-------------------------------28947758029299
Content-Disposition: form-data; name="application/json"
{"markers": [
{
"point":new GLatLng(40.266044,-74.718479),
"homeTeam":"Lawrence Library",
"awayTeam":"LUGip",
"markerImage":"images/red.png",
"information": "Linux users group meets second Wednesday of each month.",
"fixture":"Wednesday 7pm",
"capacity":"",
"previousScore":""
},
{
"point":new GLatLng(40.211600,-74.695702),
"homeTeam":"Hamilton Library",
"awayTeam":"LUGip HW SIG",
"markerImage":"images/white.png",
"information": "Linux users can meet the first Tuesday of the month to work out harward and configuration issues.",
"fixture":"Tuesday 7pm",
"capacity":"",
"tv":""
},
{
"point":new GLatLng(40.294535,-74.682012),
"homeTeam":"Applebees",
"awayTeam":"After LUPip Mtg Spot",
"markerImage":"images/newcastle.png",
"information": "Some of us go there after the main LUGip meeting, drink brews, and talk.",
"fixture":"Wednesday whenever",
"capacity":"2 to 4 pints",
"tv":""
},
] }
-------------------------------28947758029299
Content-Disposition: form-data; name="name"; filename="myfilename.pdf"
Content-Type: application/octet-stream
%PDF-1.4
%
2 0 obj
<</Length 57/Filter/FlateDecode>>stream
x+r
26S00SI2P0Qn
F
!i\
)%[email protected]
[
endstream
endobj
4 0 obj
<</Type/Page/MediaBox[0 0 595 842]/Resources<</Font<</F1 1 0 R>>>>/Contents 2 0 R/Parent 3 0 R>>
endobj
1 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
3 0 obj
<</Type/Pages/Count 1/Kids[4 0 R]>>
endobj
5 0 obj
<</Type/Catalog/Pages 3 0 R>>
endobj
6 0 obj
<</Producer(iTextSharp 5.5.11 2000-2017 iText Group NV \(AGPL-version\))/CreationDate(D:20170630120636+02'00')/ModDate(D:20170630120636+02'00')>>
endobj
xref
0 7
0000000000 65535 f
0000000250 00000 n
0000000015 00000 n
0000000338 00000 n
0000000138 00000 n
0000000389 00000 n
0000000434 00000 n
trailer
<</Size 7/Root 5 0 R/Info 6 0 R/ID [<c7c34272c2e618698de73f4e1a65a1b5><c7c34272c2e618698de73f4e1a65a1b5>]>>
%iText-5.5.11
startxref
597
%%EOF
-------------------------------28947758029299--
This will literally list (that is, print) all subdirectories. It basically is a loop kind of where you don’t need to store the items in between to a list. This is what one most likely needs, so I leave it here.
Path directory = Paths.get("D:\\directory\\to\\list");
Files.walk(directory, 1).filter(entry -> !entry.equals(directory))
.filter(Files::isDirectory).forEach(subdirectory ->
{
// do whatever you want with the subdirectories
System.out.println(subdirectory.getFileName());
});
I wanted to downgrade from API 23 to 22 and got this error. I had to change all build.gradle
files in a project in order to compile.
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.yourapp.app"
minSdkVersion 14
targetSdkVersion 22
}
...
dependencies {
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.1'
compile 'com.google.android.gms:play-services-gcm:10.0.1'
}
Depending on the actual value and what exception fits best:
ArgumentException
(something is wrong with the value)
ArgumentNullException
(the argument is null while this is not allowed)
ArgumentOutOfRangeException
(the argument has a value outside of the valid range)
If this is not precise enough, just derive your own exception class from ArgumentException
.
Yoooder's answer enlightened me. An input is invalid if it is not valid at any time, while an input is unexpected if it is not valid for the current state of the system. So in the later case an InvalidOperationException
is a reasonable choice.
Here is how you do in Eloquent
$users = User::whereIn('id', array(1, 2, 3))->get();
And if you are using Query builder then :
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
For strings containing   I've had to double-decode the string. First decode would turn it into the second pass would correctly decode it to the expected character.
Oh I figured this out, please ignore unless you have the same problem i did in which case:
$prevmonth = date("M Y",mktime(0,0,0,date("m")-1,1,date("Y")));
If you know the exact size of the view, just use setLayoutParams()
:
graphView.setLayoutParams(new LayoutParams(width, height));
Or in Kotlin:
graphView.layoutParams = LayoutParams(width, height)
However, if you need a more flexible approach you can override onMeasure()
to measure the view more precisely depending on the space available and layout constraints (wrap_content
, match_parent
, or a fixed size). You can find more details about onMeasure()
in the android docs.
This question is enormously old but is still the top result on google when you search for ways to try to disable this popup message as an extension developer who hasn't added their extension to the chrome store, doesn't have access to group policies due to their OS, and is not using the chrome dev build. There is currently no official solution in this circumstance so I'll post a somewhat 'hacky' one here.
This method has us immediately create a new window and close the old one. The popup window is associated with the original window so in normal use cases the popup never appears since that window gets closed.
The simplest solution here is we create a new window, and we close all windows that are not the window we just created in the callback:
chrome.windows.create({
type: 'normal',
focused: true,
state: 'maximized'
}, function(window) {
chrome.windows.getAll(function(windows) {
for (var i = 0; i < windows.length; i++) {
if (windows[i].id != window.id) {
chrome.windows.remove(windows[i].id);
}
}
});
});
Additionally we can detect how this extension is installed and only run this code if it is a development install (although probably best to completely remove altogether from release code). First we create the callback function for a chrome.management.getSelf call which allows us to check the extension's install type, which is basically just wrapping the code above in an if statement:
function suppress_dev_warning(info) {
if (info.installType == "development") {
chrome.windows.create({
type: 'normal',
focused: true,
state: 'maximized'
}, function(window) {
chrome.windows.getAll(function(windows) {
for (var i = 0; i < windows.length; i++) {
if (windows[i].id != window.id) {
chrome.windows.remove(windows[i].id);
}
}
});
});
}
}
next we call chrome.management.getSelf with the callback we made:
chrome.management.getSelf(suppress_dev_warning);
This method has some caveats, namely we are assuming a persistent background page which means the code runs only once when chrome is first opened. A second issue is that if we reload/refresh the extension from the chrome://extensions page, it will close all windows that are currently open and in my experience sometimes display the warning anyways. This special case can be avoided by checking if any tabs are open to "chrome://extensions" and not executing if they are.
It depends on placement of your array in memory and the hit ratio of memory pages while you are accessing that array.
In some cases accessing array members in column order is faster than row order because of the increase in hit ratio.
The way I do it is to do a Topological Sort, counting the number of vertices visited. If that number is less than the total number of vertices in the DAG, you have a cycle.
here's another way
import numpy as np
set(np.concatenate(df.values))
Navigate to /tomcat-root/conf folder. Within you will find the server.xml file.
Open the server.xml in your preferred editor. Search the below similar statement (not exactly same as below will differ)
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Going to give the port number to 9090
<Connector port="9090" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Save the file and restart the server. Now the tomcat will listen at port 9090
This question has mentioned for the OSX, but it happened to me in my linux OS.
I tried using nvm alias default <version>
but for each new terminal session the used node version was forgotten.
so, here is the solution that i figured out.
make sure to set a default alias for node version,put the following code in .bashrc, and source .bashrc
.
export NVM_DIR="/home/bonnie/.nvm"
## If the file exists and is not empty
if [ -s "$NVM_DIR/nvm.sh" ]; then
## Source it
source "$NVM_DIR/nvm.sh"
fi
NODE_DEFAULT_VERSION=$(<"$NVM_DIR/alias/default")
export PATH="$NVM_DIR/versions/node/$NODE_DEFAULT_VERSION/bin":$PATH
First of All Theory
Big O = Upper Limit O(n)
Theta = Order Function - theta(n)
Omega = Q-Notation(Lower Limit) Q(n)
In many Blogs & Books How this Statement is emphasised is Like
"This is Big O(n^3)" etc.
and people often Confuse like weather
O(n) == theta(n) == Q(n)
But What Worth keeping in mind is They Are Just Mathematical Function With Names O, Theta & Omega
so they have same General Formula of Polynomial,
Let,
f(n) = 2n4 + 100n2 + 10n + 50 then,
g(n) = n4, So g(n) is Function which Take function as Input and returns Variable with Biggerst Power,
Same f(n) & g(n) for Below all explainations
Big O(n4) = 3n4, Because 3n4 > 2n4
3n4 is value of Big O(n4) Just like f(x) = 3x
n4 is playing a role of x here so,
Replacing n4 with x'so, Big O(x') = 2x', Now we both are happy General Concept is
So 0 = f(n) = O(x')
O(x') = cg(n) = 3n4
Putting Value,
0 = 2n4 + 100n2 + 10n + 50 = 3n4
3n4 is our Upper Bound
Theta(n4) = cg(n) = 2n4 Because 2n4 = Our Example f(n)
2n4 is Value of Theta(n4)
so, 0 = cg(n) = f(n)
0 = 2n4 = 2n4 + 100n2 + 10n + 50
2n4 is our Lower Bound
This is Calculated to find out that weather lower Bound is similar to Upper bound,
Case 1). Upper Bound is Similar to Lower Bound
if Upper Bound is Similar to Lower Bound, The Average Case is Similar
Example, 2n4 = f(x) = 2n4,
Then Omega(n) = 2n4
Case 2). if Upper Bound is not Similar to Lower Bound
in this case, Omega(n) is Not fixed but Omega(n) is the set of functions with the same order of growth as g(n).
Example 2n4 = f(x) = 3n4, This is Our Default Case,
Then, Omega(n) = c'n4, is a set of functions with 2 = c' = 3
Hope This Explained!!
Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).
apt-get install -d -o=dir::cache=/tmp whateveryouwant
One of the data columns in the excel (Column Id 6) has one or more cell data that exceed the datacolumn datatype length in the database.
Verify the data in excel. Also verify the data in the excel for its format to be in compliance with the database table schema.
To avoid this, try exceeding the data-length of the string datatype in the database table.
Hope this helps.
At terminal run this command with root permission:
sudo /etc/init.d/apache2 start
You must be root for starting a webserver otherwise you would get similar error.
Here is another option.
function getOrdinalSuffix(day) {_x000D_
_x000D_
if(/^[2-3]?1$/.test(day)){_x000D_
return 'st';_x000D_
} else if(/^[2-3]?2$/.test(day)){_x000D_
return 'nd';_x000D_
} else if(/^[2-3]?3$/.test(day)){_x000D_
return 'rd';_x000D_
} else {_x000D_
return 'th';_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
console.log(getOrdinalSuffix('1'));_x000D_
console.log(getOrdinalSuffix('13'));_x000D_
console.log(getOrdinalSuffix('22'));_x000D_
console.log(getOrdinalSuffix('33'));
_x000D_
Notice the exception for the teens? Teens are so akward!
Edit: Forgot about 11th and 12th
I believe you are all wrong. you need to do:
array = array[]
in order to define it, and then:
array.append ["hello"]
to add to it.
(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)
Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.
For subdomains (like www.example.com
) you can use CNAME records pointing to your-app-name.herokuapp.com
. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com
so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)
Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com
is an HTTP redirect to www.example.com
.
Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.
Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):
@ IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.
Remember @
here is a shorthand for the root domain (example.com
). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.
Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.
Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.
Another way to remove VBA project password is;
UPDATE: For Excel 2010 (Works for MS Office Pro Plus 2010 [14.0.6023.1000 64bit]),
If workbook is protected:
xl
workbook.xml
and select Edit<workbookProtection workbookPassword="XXXX" lockStructure="1"/>
(XXXX
is your encrypted password)XXXX
part. (ie. <workbookProtection workbookPassword="" lockStructure="1"/>
)If worksheets are protected:
xl/worksheets/
folder.Sheet1.xml
, sheet2.xml
, etc and select Edit.<sheetProtection password="XXXX" sheet="1" objects="1" scenarios="1" />
<sheetProtection password="" sheet="1" objects="1" scenarios="1" />
)import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
public class API{
public static void main(String args[]) throws IOException
{
URL url = new URL("http://www.google.com");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();
System.out.println(statusCode);
}
}
The issue was with the dmp file itself. I had to re-export the file and the command works fine. Thank you @Justin Cave
Not PIL, but scipy.misc.imread
might still be interesting:
import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So you can iterate over it by
for y in range(im.shape[0]):
for x in range(im.shape[1]):
color = tuple(im[y][x])
r, g, b = color
Another option:
$(el).trigger({type: 'keypress', which: 13, keyCode: 13});
I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)
There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12
There's a few things with your code as it stands:
The first thing we are going to do is to declare your variable as let
, as we are not going to modify it later.
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")! // We can force unwrap because we are 100% certain the constructor will not return nil in this case.
Then we need to download the contents of that URL. We can do this with the URLSession
object. When the completion handler is called, we will have a UIImage
downloaded from the web.
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
Finally you need to call resume
on the download task, otherwise your task will never start:
downloadPicTask.resume()
.
All this code may look a bit intimidating at first, but the URLSession
APIs are block based so they can work asynchronously - If you block your UI thread for a few seconds, the OS will kill your app.
Your full code should look like this:
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
You need to first cast the instance to any
because Function
's type definition does not have a name
property.
class MyClass {
getName() {
return (<any>this).constructor.name;
// OR return (this as any).constructor.name;
}
}
// From outside the class:
var className = (<any>new MyClass()).constructor.name;
// OR var className = (new MyClass() as any).constructor.name;
console.log(className); // Should output "MyClass"
// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"
With TypeScript 2.4 (and potentially earlier) the code can be even cleaner:
class MyClass {
getName() {
return this.constructor.name;
}
}
// From outside the class:
var className = (new MyClass).constructor.name;
console.log(className); // Should output "MyClass"
// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"
find . -type f -print0 | xargs -0 <sed/perl/ruby cmd>
will process multiple space contained file names at once loading one interpreter per batch. Much faster.
You can use the this customization to change the default mapping to java.util.Date
<xsd:annotation>
<xsd:appinfo>
<jaxb:globalBindings>
<jaxb:javaType name="java.util.Date" xmlType="xsd:dateTime"
parseMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.parseDateTime"
printMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.printDateTime"/>
</jaxb:globalBindings>
</xsd:appinfo>
I'm using something like this:
String scheme = uri.getScheme();
if (scheme.equals("file")) {
fileName = uri.getLastPathSegment();
}
else if (scheme.equals("content")) {
String[] proj = { MediaStore.Images.Media.TITLE };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE);
cursor.moveToFirst();
fileName = cursor.getString(columnIndex);
}
if (cursor != null) {
cursor.close();
}
}
Be careful if you have to deal with large numbers.
int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
long sum = Arrays.stream(arr).sum(); // Wrong: sum == 0
The sum above is not 2 * Integer.MIN_VALUE
.
You need to do this in this case.
long sum = Arrays.stream(arr).mapToLong(Long::valueOf).sum(); // Correct
One very small nit to pick:
The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:
"john@work"@myemployer.com
This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:
SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1
More information:
If you are sure there are no commas in your input, other than to separate the category, you can read the file line by line and split on ,
, then push the result to List
That said, it looks like you are looking at a CSV file, so you might consider using the modules for it
You forgot the .class
:
if (value.getClass() == Integer.class) {
System.out.println("This is an Integer");
}
else if (value.getClass() == String.class) {
System.out.println("This is a String");
}
else if (value.getClass() == Float.class) {
System.out.println("This is a Float");
}
Note that this kind of code is usually the sign of a poor OO design.
Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:
"foo".getClass() == Object.class
is false, whereas
"foo" instanceof Object
is true.
Whether one or the other must be used depends on your requirements.
$fp = fopen("$address",'w+');
if(!$fp)
echo 'not Open';
//-----------------------------------
while(!feof($fp))
{
fputs($fp,' ',999);
}
fclose($fp);
You must remove the constraints
from the column before removing the column. The name you are referencing is a default constraint
.
e.g.
alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
alter table CompanyTransactions drop column [Created];
No, they both have their uses:
Use xrange()
when iterating, as it saves memory. Say:
for x in xrange(1, one_zillion):
rather than:
for x in range(1, one_zillion):
On the other hand, use range()
if you actually want a list of numbers.
multiples_of_seven = range(7,100,7)
print "Multiples of seven < 100: ", multiples_of_seven
Going back to the original question (4 years later), rather than rebuilding your own section header, iOS can simply call you (with willDisplayHeaderView:forSection:) right after it's built the default one. For example, I wanted to add a graph button on right edge of section header:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView * header = (UITableViewHeaderFooterView *) view;
if (header.contentView.subviews.count > 0) return; //in case of reuse
CGFloat rightEdge = CGRectGetMaxX(header.contentView.bounds);
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(rightEdge - 44, 0, 44, CGRectGetMaxY(header.contentView.bounds))];
[button setBackgroundImage:[UIImage imageNamed:@"graphIcon"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(graphButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
}
private static boolean isValidFolderPath(String path) {
File file = new File(path);
if (!file.exists()) {
return file.mkdirs();
}
return true;
}
In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:
var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');
(note: this answer has been updated on 2014-08-01 to make it more detailed, more accurate, and to add a live demo)
According to W3C CSS2.1 specification (“Omitted values are set to their initial values”), the following properties are equivalent:
border: hidden; border-style: hidden;
border-width: medium;
border-color: <the same as 'color' property>
border: none; border-style: none;
border-width: medium;
border-color: <the same as 'color' property>
border: 0; border-style: none;
border-width: 0;
border-color: <the same as 'color' property>
If these rules are the most specific ones applied to the borders of an element, then the borders won't be shown, either because of zero-width, or because of hidden
/none
style. So, at the first look, these three rules look equivalent. However, they behave in different ways when combined with other rules.
When a table is rendered using border-collapse: collapse
, then each rendered border is shared between multiple elements (inner borders are shared among as neighbor cells; outer borders are shared between cells and the table itself; but also rows, row groups, columns and column groups share borders). The specification defines some rules for border conflict resolution:
Borders with the
border-style
ofhidden
take precedence over all other conflicting borders. […]Borders with a style of
none
have the lowest priority. […]If none of the styles are
hidden
and at least one of them is notnone
, then narrow borders are discarded in favor of wider ones. […]If border styles differ only in color, […]
So, in a table context, border: hidden
(or border-style: hidden
) will have the highest priority and will make the shared border hidden, no matter what.
On the other end of the priorities, border: none
(or border-style: none
) have the lowest priority, followed by the zero-width border (because it is the narrowest border). This means that a computed value of border-style: none
and a computed value of border-width: 0
are essentially the same.
Since none
and 0
affect different properties (border-style
and border-width
), they will behave differently when a more specific rule defines just the style or just the width. See Chris answer for an example.
Want to see all these cases in one single page? Open the live demo!
You need to set the NTAuthenticationProviders to NTLM
MSDN Article: https://msdn.microsoft.com/en-us/library/ee248703(VS.90).aspx
IIS Command-line (http://msdn.microsoft.com/en-us/library/ms525006(v=vs.90).aspx):
cscript adsutil.vbs set w3svc/WebSiteValueData/root/NTAuthenticationProviders "NTLM"
There is a 3rd party debugger in the works, it's currently in preview, but you can install the debugger Android extension in VSCode right now and get more information on it here:
Félix's answer is correct and upvoted, backed-up by Dan Abramov himself.
But for those who would like to change the structure of the output itself (within the build
folder), one can run post-build commands with the help of postbuild
, which automatically runs after the build
script defined in the package.json
file.
The example below changes it from static/
to user/static/
, moving files and updating file references on relevant files (full gist here):
package.json
{
"name": "your-project",
"version": "0.0.1",
[...]
"scripts": {
"build": "react-scripts build",
"postbuild": "./postbuild.sh",
[...]
},
}
postbuild.sh
#!/bin/bash
# The purpose of this script is to do things with files generated by
# 'create-react-app' after 'build' is run.
# 1. Move files to a new directory called 'user'
# The resulting structure is 'build/user/static/<etc>'
# 2. Update reference on generated files from
# static/<etc>
# to
# user/static/<etc>
#
# More details on: https://github.com/facebook/create-react-app/issues/3824
# Browse into './build/' directory
cd build
# Create './user/' directory
echo '1/4 Create "user" directory'
mkdir user
# Find all files, excluding (through 'grep'):
# - '.',
# - the newly created directory './user/'
# - all content for the directory'./static/'
# Move all matches to the directory './user/'
echo '2/4 Move relevant files'
find . | grep -Ev '^.$|^.\/user$|^.\/static\/.+' | xargs -I{} mv -v {} user
# Browse into './user/' directory
cd user
# Find all files within the folder (not subfolders)
# Replace string 'static/' with 'user/static/' on all files that match the 'find'
# ('sed' requires one to create backup files on OSX, so we do that)
echo '3/4 Replace file references'
find . -type f -maxdepth 1 | LC_ALL=C xargs -I{} sed -i.backup -e 's,static/,user/static/,g' {}
# Delete '*.backup' files created in the last process
echo '4/4 Clean up'
find . -name '*.backup' -type f -delete
# Done
These instructions are for windows machine with a single user profile for AWS. Make sure your ~/.aws/credentials
file looks like this
[profile_name]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey
I had to set the AWS_DEFAULT_PROFILE
environment variable to profile_name
found in your credentials.
Then my python was able to connect. eg from here
import boto3
# Let's use Amazon S3
s3 = boto3.resource('s3')
# Print out bucket names
for bucket in s3.buckets.all():
print(bucket.name)
It is possible to use the convert function here, but 36 characters are enough to hold the unique identifier value:
convert(nvarchar(36), requestID) as requestID
Evaluating String
variables with a switch statement have been implemented in Java SE 7, and hence it only works in java 7. You can also have a look at how this new feature is implemented in JDK 7.
def insenStringCompare(s1, s2):
""" Method that takes two strings and returns True or False, based
on if they are equal, regardless of case."""
try:
return s1.lower() == s2.lower()
except AttributeError:
print "Please only pass strings into this method."
print "You passed a %s and %s" % (s1.__class__, s2.__class__)
The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:
For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next
If you do not want the symbols like colon to be inserted put an if condition in the loop.
In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.
However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)
While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.
You didn't create your project as "Dynamic Web Project", so Eclipse doesn't recognize it like a web project. Create a new "Dynamic Web Project" or go to Properties ? Projects Facets and check Dynamic Web Module.
try this :
string getValue = Convert.ToString(cmd.ExecuteScalar());
You can compile your C programs with an ARM cross-compiler:
arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test
Then you can push your compiled binary file to somewhere (don't push it in to the SD card):
adb push test /data/local/tmp/test
i found this way useful also.
import tkinter.filedialog
from_filename = tkinter.filedialog.askopenfilename()
here a window will appear so you can browse till you find the file , you click on it then you can continue using open , and read .
from_file = open(from_filename, 'r')
contents = from_file.read()
contents
The error you get if because you need to escape the quotes (like other answers said).
To avoid that, you can use an alternative syntax for you strings declarations, called "Heredoc"
With this syntax, you can declare a long string, even containing single-quotes and/or double-quotes, whithout having to escape thoses ; it will make your Javascript code easier to write, modify, and understand -- which is always a good thing.
As an example, your code could become :
$str = <<<MY_MARKER
<script type="text/javascript">
document.write("Hello World!");
</script>
MY_MARKER;
echo $str;
Note that with Heredoc syntax (as with string delimited by double-quotes), variables are interpolated.
For those who use docker-compose
, it’s really easy to set a password without any config file like redis.conf
. Here’s how you would normally use the official Redis image:
redis:
image: 'redis:4-alpine'
ports:
- '6379:6379'
And here’s all you need to change to set a custom password:
redis:
image: 'redis:4-alpine'
command: redis-server --requirepass yourpassword
ports:
- '6379:6379'
Everything will start up as normal and your Redis server will be protected by a password.
For details, this blog post seems to support the idea.
If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.
The most effective way to center text in IE is to use something like this with "dy":
<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>
The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.
Create initMap method between "" tag or load javascript file before call google api.
<script src="Scripts/main.js"></script>_x000D_
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=abcde&libraries=places&callback=initMap" async defer></script>
_x000D_
you can add this code :
[class*="col-"] {
padding-top: 1rem;
padding-bottom: 1rem;
}
Something throws an exception of type std::bad_alloc
, indicating that you ran out of memory. This exception is propagated through until main
, where it "falls off" your program and causes the error message you see.
Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h
looks like a syntax error.
Make sure to use full paths, e.g. not only "video.avi" but the full path to that file.
A simple trick for debugging would be to start a command window using cmd /k <command>
instead:
string ffmpegPath = Path.Combine(path, "ffmpeg.exe");
string ffmpegParams = @"-f image2 -i frame%d.jpg -vcodec"
+ @" mpeg4 -b 800k C:\myFolder\video.avi"
Process ffmpeg = new Process();
ffmpeg.StartInfo.FileName = "cmd.exe";
ffmpeg.StartInfo.Arguments = "/k " + ffmpegPath + " " + ffmpegParams
ffmpeg.Start();
This will leave the command window open so that you can easily check the output.
If you aren't allowing the column to be Null you need to provide a default to populate existing rows. e.g.
ALTER TABLE dbo.YourTbl ADD
newcol int NOT NULL CONSTRAINT DF_YourTbl_newcol DEFAULT 0
On Enterprise Edition this is a metadata only change since 2012
Illustrating what StaxMan has stated, this works for me
private String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.
There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.
PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.
There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.
You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.
Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!
At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.
In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!
Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?>
on your site and look for the Server API
entry. This could say something like CGI/FastCGI
or Apache 2.0 Handler
.
If you also look at the command-line version of PHP -- thread safety does not matter.
Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!
I'm using this simple code for this task:
CSS Code
.demo {
background: tomato;
color: white;
}
Javascript code
function myFunction() {
/* Assign element to x variable by id */
var x = document.getElementById('para);
if (x.hasAttribute('class') {
x.removeAttribute('class');
} else {
x.setAttribute('class', 'demo');
}
}
Whats the value for the SqlException.ErrorCode property? Can you work with that?
When having timeouts, it may be worth checking the code for -2146232060.
I would set this up as a static const in your data code.
Yes you can do so and I have created a library for the same.
This allows you to connect up-to four devices to the main server device creating different channels for each client and running interactions on different threads.
To use this library simple add compile com.mdg.androble:library:0.1.2
in dependency section of your build.gradl
e .
if you're just looking to make sure the individual parts of the date stay the same for display purposes, *this appears to work, even when I change my timezone:
var doo = new Date("2011-09-24 00:00:00")
just add the zeros in there.
In my code I do this:
let dateForDisplayToUser =
new Date( `${YYYYMMDDdateStringSeparatedByHyphensFromAPI} 00:00:00` )
.toLocaleDateString(
'en-GB',
{ day: 'numeric', month: 'short', year: 'numeric' }
)
And I switch around my timezone on my computer and the date stays the same as the yyyy-mm-dd date string I get from the API.
But am I missing something/is this a bad idea ?
*at least in chrome. This Doesn't work in Safari ! as of this writing
0x7ffffff's answer is ok and definitely exhaustive.
As a plus, I suggest you to make an UIView extension, in this way:
public extension UIView {
/**
Fade in a view with a duration
- parameter duration: custom animation duration
*/
func fadeIn(duration duration: NSTimeInterval = 1.0) {
UIView.animateWithDuration(duration, animations: {
self.alpha = 1.0
})
}
/**
Fade out a view with a duration
- parameter duration: custom animation duration
*/
func fadeOut(duration duration: NSTimeInterval = 1.0) {
UIView.animateWithDuration(duration, animations: {
self.alpha = 0.0
})
}
}
Swift-3
/// Fade in a view with a duration
///
/// Parameter duration: custom animation duration
func fadeIn(withDuration duration: TimeInterval = 1.0) {
UIView.animate(withDuration: duration, animations: {
self.alpha = 1.0
})
}
/// Fade out a view with a duration
///
/// - Parameter duration: custom animation duration
func fadeOut(withDuration duration: TimeInterval = 1.0) {
UIView.animate(withDuration: duration, animations: {
self.alpha = 0.0
})
}
In this way you can do this wherever in your code:
let newImage = UIImage(named: "")
newImage.alpha = 0 // or newImage.fadeOut(duration: 0.0)
self.view.addSubview(newImage)
...
newImage.fadeIn()
Code reuse is important!
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
You can not "attach" a SASS/SCSS file to an HTML document.
SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.
There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.
It's as simple as adding 2 lines of code to your HTML file.
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
To run docker daemon on Linux (from CLI), run:
$ sudo service docker start # Ubuntu/Debian
Note: Skip the $
character when copy and pasting.
On RedHat/CentOS, run: sudo systemctl start docker
.
To initialize the "base" filesystem, run:
$ sudo service docker stop
$ sudo rm -rf /var/lib/docker
$ sudo service docker start
or manually like:
$ sudo docker -d --storage-opt dm.basesize=20G
docker-machine
on LinuxTo install machine binaries on Linux:
locally:
install -vm755 <(curl -L https://github.com/docker/machine/releases/download/v0.5.3/docker-machine_linux-amd64) $HOME/bin/docker-machine
global:
sudo bash -c 'install -vm755 <(curl -L https://github.com/docker/machine/releases/download/v0.5.3/docker-machine_linux-amd64) /usr/local/bin/docker-machine'
On macOS the docker
binary is only a client and you cannot use it to run the docker daemon, because Docker daemon uses Linux-specific kernel features, therefore you can’t run Docker natively in OS X. So you have to install docker-machine
in order to create VM and attach to it.
docker-machine
on macOSIf you don't have docker-machine
command yet, install it by using one of the following methods:
brew install docker-machine docker
.manually from GitHub:
install -v <(curl https://github.com/docker/machine/releases/download/v0.5.3/docker-machine_linux-amd64) /usr/local/bin/docker-machine
See: Get started with Docker for Mac.
docker-machine
on macOSTo start Docker Machine via Homebrew, run:
brew services start docker-machine
To create a default
machine (if you don't have one, see: docker-machine ls
):
docker-machine create --driver virtualbox default
Then set-up the environment for the Docker client:
eval "$(docker-machine env default)"
Then double-check by listing containers:
docker ps
See: Get started with Docker Machine and a local VM.
Alternatively to above solution, you can install a Docker app by:
brew cask install docker
Check this post for more details. See also: Cannot connect to the Docker daemon on macOS
Regex can be rather slow even with simple tasks. This creates an extension method that can be used off of any string
.
public static class StringExtension
{
public static String ReduceWhitespace(this String value)
{
var newString = new StringBuilder();
bool previousIsWhitespace = false;
for (int i = 0; i < value.Length; i++)
{
if (Char.IsWhiteSpace(value[i]))
{
if (previousIsWhitespace)
{
continue;
}
previousIsWhitespace = true;
}
else
{
previousIsWhitespace = false;
}
newString.Append(value[i]);
}
return newString.ToString();
}
}
It would be used as such:
string testValue = "This contains too much whitespace."
testValue = testValue.ReduceWhitespace();
// testValue = "This contains too much whitespace."
Tomcat can work in 2 modes:
Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol
parameter in the server.xml
file.
HTTP/1.1
or org.apache.coyote.http11.Http11Protocol
org.apache.coyote.http11.Http11NioProtocol
If you're using BIO then I believe they should be more or less the same.
If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.
HashSet
don't maintain the order of insertion item
LinkedHashSet
maintain the order of insertion item
Example
Set<String> set = ...;// using new HashSet<>() OR new LinkedHashSet<>()
set.add("2");
set.add("1");
set.add("ab");
for(String value : set){
System.out.println(value);
}
HashSet
output
1
ab
2
LinkedHashSet
output
2
1
ab
Here is a portable shell function that should work in ANY Bourne comparable shell. It will resolve the relative path punctuation ".. or ." and dereference symbolic links.
If for some reason you do not have a realpath(1) command, or readlink(1) this can be aliased.
which realpath || alias realpath='real_path'
Enjoy:
real_path () {
OIFS=$IFS
IFS='/'
for I in $1
do
# Resolve relative path punctuation.
if [ "$I" = "." ] || [ -z "$I" ]
then continue
elif [ "$I" = ".." ]
then FOO="${FOO%%/${FOO##*/}}"
continue
else FOO="${FOO}/${I}"
fi
## Resolve symbolic links
if [ -h "$FOO" ]
then
IFS=$OIFS
set `ls -l "$FOO"`
while shift ;
do
if [ "$1" = "->" ]
then FOO=$2
shift $#
break
fi
done
IFS='/'
fi
done
IFS=$OIFS
echo "$FOO"
}
also, just in case anybody is interested here is how to implement basename and dirname in 100% pure shell code:
## http://www.opengroup.org/onlinepubs/000095399/functions/dirname.html
# the dir name excludes the least portion behind the last slash.
dir_name () {
echo "${1%/*}"
}
## http://www.opengroup.org/onlinepubs/000095399/functions/basename.html
# the base name excludes the greatest portion in front of the last slash.
base_name () {
echo "${1##*/}"
}
You can find updated version of this shell code at my google site: http://sites.google.com/site/jdisnard/realpath
EDIT: This code is licensed under the terms of the 2-clause (freeBSD style) license. A copy of the license may be found by following the above hyperlink to my site.
Just a remind: I tried to work with idea and imported maven, and encountered the same problem, I have tried all the solutions and they didnt work. Finally, I found out it was because of the root access... I opened idea with administrator access and all things work just fine, hope you not as silly as i am...
Use rowspan
if you want to extend cells down and colspan
to extend across.
select p.pid, p.cid, c1.name,c2.name
from product p
left outer join customer1 c1 on c1.cid=p.cid
left outer join customer2 c2 on c2.cid=p.cid
Since you've got both the shell that you're typing into and the shell that sudo -s
runs, you need to quote or escape twice. (EDITED fixed quoting)
sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'
or
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)
Out of curiosity, why do you need -s? Can't you just do this:
sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
In higher versions of Firefox, like Nightly, there is an options named "disable cache", you can find it by clicking the gear. And that options works only in current session, which means when you close inspector and restart it, you have to check it again if you want catch disabled.
In my case I forgot to add @RequestBody
annotation to the method argument:
public TestController(@RequestBody KeeperClient testClient) {
TestController.testClient = testClient;
}
I think You are trying to use the normal URL of video Like this :
Copying Direct URL from YouTube
That doesn't let you display the content on other domains.To Tackle this up , You should use the Copy Embed Code feature provided by the YouTube itself .Like this :
That would free you up from any issues .
For the above Scenario :
Go to Youtube Video
Copy Embed Code
With jquery you could do to sth. like this, which will simply switch classes.
$('.showhide').click(function() {
$(this).removeClass('myclass');
$(this).addClass('showhidenew');
});
If you want to switch classes back and forth on each click, you can use toggleClass, like so:
$('.showhide').click(function() {
$(this).toggleClass('myclass');
$(this).toggleClass('showhidenew');
});
basename($_SERVER['REQUEST_URI'])
returns everything after and including the '?',
In my code sometimes I need only sections, so separate it out so I can get the value of what I need on the fly. Not sure on the performance speed compared to other methods, but it's really useful for me.
$urlprotocol = 'http'; if ($_SERVER["HTTPS"] == "on") {$urlprotocol .= "s";} $urlprotocol .= "://";
$urldomain = $_SERVER["SERVER_NAME"];
$urluri = $_SERVER['REQUEST_URI'];
$urlvars = basename($urluri);
$urlpath = str_replace($urlvars,"",$urluri);
$urlfull = $urlprotocol . $urldomain . $urlpath . $urlvars;
With coalesce
:
coalesce(column_name,0)
Although, where summing when condition then 1
, you could just as easily change sum
to count
- eg:
count(case when c.runstatus = 'Succeeded' then 1 end) as Succeeded,
(Count(null)
returns 0, while sum(null)
returns null.)
Any positive integer, excluding 0: ^\+?[1-9]\d*$
Any positive integer, including 0: ^(0|\+?[1-9]\d*)$
Better solution for different currency formats:
def text_currency_to_float(text):
t = text
dot_pos = t.rfind('.')
comma_pos = t.rfind(',')
if comma_pos > dot_pos:
t = t.replace(".", "")
t = t.replace(",", ".")
else:
t = t.replace(",", "")
return(float(t))
Here is a bit shorter version, based on @connor 's answer
guard let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist"),
let myDict = NSDictionary(contentsOfFile: path) else {
return nil
}
let value = dict.value(forKey: "CLIENT_ID") as! String?
Another Solution in Case You Don't Have Control Over Dynamic Content
This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).
Wrap up Your Content
Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.
<div class="selector">
<grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>
Use Angular Injector
You can use the following code to get a reference to $compile if you don't have one.
$(".selector").each(function () {
var content = $(this);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
});
});
Summary
The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.
One Caveat of the previous code
If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.
Here is the way to remedy it:
Replace the prevous code snippet with the following overload.
...
angular.element(document).injector().invoke(
[
"$compile", function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
}
]);
...
This caused a lot of grief for me before I pieced it together.
Assuming the type is CV_8UC3 you would do this:
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
Vec3b bgrPixel = foo.at<Vec3b>(i, j);
// do something with BGR values...
}
}
Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.
EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:
Here is how you might go about this:
uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R
// do something with BGR values...
}
}
Or alternatively:
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
uint8_t* rowPtr = foo.row(i);
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
bgrPixel.val[2] = rowPtr[j*cn + 2]; // R
// do something with BGR values...
}
}
You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use
if (count % 5 == 4)
You need to install all necessary packages with Android SDK Manager:
Android SDK Tools
Android SDK Platform-tools
Android SDK Build-tools
SDK Platform
ARM\Intel System Image
Android Support Repository
Android Support Library
I have been having this issue for a couple of weeks and finally decided to sit down and try and fix it. I have no interest in config file editing as I'm primarily a Windows user.
In a fit of "clickyness" I noticed that the ubuntu server location was set "for United kingdom". I switched this over to "Main Server" and hey presto... it all stared updating.
So, it seems like the regionalised server (for the UK at least) has a very limited support window so if you are an infrequent user it is likely it will not have a valid upgrade path from your current version to the latest.
Edit: I only just noticted the previous reply, after posting. 100% agree.
Fortes is right, thank you.
When you have a shared hosting it is usual to obtain an 500 server error
.
I have a website with Joomla and I added to the index.php
:
ini_set('display_errors','off');
The error line showed in my website disappeared.
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
assuming certain column names...
INSERT one
newToner = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
dbsession.add(newToner)
dbsession.commit()
INSERT multiple
newToner1 = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
newToner2 = Toner(toner_id = 2,
toner_color = 'red',
toner_hex = '#F01731')
dbsession.add_all([newToner1, newToner2])
dbsession.commit()
UPDATE
q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'
dbsession.commit()
or using a fancy one-liner using MERGE
record = dbsession.merge(Toner( **kwargs))
You should install node.js with nvm, because that way you do not have to provide superuser privileges when installing global packages (you can simply execute "npm install -g packagename" without prepending 'sudo').
Brew is fantastic for other things, however. I tend to be biased towards Bower whenever I have the option to install something with Bower.
Another elegant one is
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;
maybe i'm misunderstanding but what if you press Escape until you got the Display All X possibilities ?
You should be able to use \n
inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n
for proper formatting like so:
var example: String = "Hello World \nThis is a new line"
Which, if printed to the console, should become:
Hello World
This is a new line
However, there are some other considerations to make depending on how you will be using this string, such as:
\r\n
instead, which is the Windows newline.Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.
The most generic and the easiest way to reverse a list will be :
public static <T> void reverseHelper(List<T> li){
li.stream()
.sorted((x,y)-> -1)
.collect(Collectors.toList())
.forEach(System.out::println);
}
In addition to the other answers.
If you control the structure of the DataTable there is a shortcut for adding rows:
// Assume you have a data table defined as in your example named dt dt.Rows.Add("Name", "Marks");
The DataRowCollection.Add() method has an overload that takes a param array of objects. This method lets you pass as many values as needed, but they must be in the same order as the columns are defined in the table.
So while this is a convenient way to add row data, it can be risky to use. If the table structure changes your code will fail.
See this question. LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo().
A purportedly faster extension method is described here.
since openssl v1.1.0
C:\openssl>openssl version
OpenSSL 1.1.0g 2 Nov 2017
C:\openssl>openssl s_client -proxy 192.168.103.115:3128 -connect www.google.com -CAfile C:\TEMP\internalCA.crt
CONNECTED(00000088)
depth=2 DC = com, DC = xxxx, CN = xxxx CA interne
verify return:1
depth=1 C = FR, L = CROIX, CN = svproxysg1, emailAddress = [email protected]
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN = www.google.com
verify return:1
---
Certificate chain
0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com
i:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
1 s:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
i:/DC=com/DC=xxxxx/CN=xxxxx CA interne
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDkTCCAnmgAwIBAgIJAIv4/hQAAAAAMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV
BAYTAkZSMQ4wDAYDVQQHEwVDUk9JWDETMBEGA1UEAxMKc3Zwcm94eXNnMTEeMBwG
echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
echo "<tr>";
foreach($v as $vv){
echo "<td>{$vv}</td>";
}
echo "<tr>";
}
echo "</table>";
sys.dm_tran_locks contains the locking information of the sessions
If you want to know a specific table is locked or not, you can use the following query
SELECT
*
from
sys.dm_tran_locks
where
resource_associated_entity_id = object_id('schemaname.tablename')
if you are interested in finding both login name of the user and the query being run
SELECT
DB_NAME(resource_database_id)
, s.original_login_name
, s.status
, s.program_name
, s.host_name
, (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
,*
from
sys.dm_tran_locks dbl
JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
INNER JOIN sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
where
DB_NAME(dbl.resource_database_id) = 'dbname'
For more infomraton locking query
More infor about sys.dm_tran_locks
I have been getting this same problem. I have even tried above enable migrations even though I have already done. But it keeps giving same error. Then I had to use the force switch to get overcome this problem. I am sure this will help in someone else's case as well as its a possible work around.
After enabling migration with force, you should update your database (Make sure default project is set correctly). Otherwise you will get another problem like explicit migrations are pending.
Then just execute your add-migrations or any other commands, it should work.
Enable-Migrations -ProjectName <PROJECT_NAME> -ContextTypeName <FULL_CONTEXT_NAMESPACE.YOUR_CONTEXT_NAME> -force
A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.
The most commonly used type parameter names are:
In Java 7 it is permitted to instantiate like this:
Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6
Ugly, but:
<div *ngFor="let a of [aVariable]">
<span>{{a}}</span>
</div>
When used with async pipe:
<div *ngFor="let a of [aVariable | async]">
<span>{{a.prop1}}</span>
<span>{{a.prop2}}</span>
</div>
I am on mingw bash, so I have created ~.profile file with following: alias atom='~/AppData/Local/atom/bin/atom'
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
You can create a global method to show message(alert) in your web form application.
public static class PageUtility
{
public static void MessageBox(System.Web.UI.Page page,string strMsg)
{
//+ character added after strMsg "')"
ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "alertMessage", "alert('" + strMsg + "')", true);
}
}
webform.aspx
protected void btnSave_Click(object sender, EventArgs e)
{
PageUtility.MessageBox(this, "Success !");
}
Hopefully this can help others: The above examples use ax.lines
.
With more recent mpl (3.3.1), there is ax.get_lines()
.
This bypasses the need for calling ax.lines=[]
for line in ax.get_lines(): # ax.lines:
line.remove()
# ax.lines=[] # needed to complete removal when using ax.lines
They always say it depends but when it comes to mirroring a website The best exists httrack. It is super fast and easy to work. The only downside is it's so called support forum but you can find your way using official documentation. It has both GUI and CLI interface and it Supports cookies just read the docs This is the best.(Be cureful with this tool you can download the whole web on your harddrive)
httrack -c8 [url]
By default maximum number of simultaneous connections limited to 8 to avoid server overload
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
what you are doing here is reading one character at a time from the input stream and assume that all the characters between " " represent a word. BUT it's unlikely to be a " " after the last word, so that's probably why it does not work:
"word1 word2 word2EOF"
Just make a comparison function/functor:
bool my_cmp(const data& a, const data& b)
{
// smallest comes first
return a.word.size() < b.word.size();
}
std::sort(info.begin(), info.end(), my_cmp);
Or provide an bool operator<(const data& a) const
in your data
class:
struct data {
string word;
int number;
bool operator<(const data& a) const
{
return word.size() < a.word.size();
}
};
or non-member as Fred said:
struct data {
string word;
int number;
};
bool operator<(const data& a, const data& b)
{
return a.word.size() < b.word.size();
}
and just call std::sort()
:
std::sort(info.begin(), info.end());
In my case, I needed to allow many inactives and only one combination of two keys active, like this:
UUL_USR_IDF UUL_UND_IDF UUL_ATUAL
137 18 0
137 19 0
137 20 1
137 21 0
This seems to work:
CREATE UNIQUE NONCLUSTERED INDEX UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL
ON USER_UND(UUL_USR_IDF, UUL_ATUAL)
WHERE UUL_ATUAL = 1;
Here are my test cases:
SELECT * FROM USER_UND WHERE UUL_USR_IDF = 137
insert into USER_UND values (137, 22, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 23, 0) --I CAN
insert into USER_UND values (137, 24, 0) --I CAN
DELETE FROM USER_UND WHERE UUL_USR_ID = 137
insert into USER_UND values (137, 22, 1) --I CAN
insert into USER_UND values (137, 27, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 28, 0) --I CAN
insert into USER_UND values (137, 29, 0) --I CAN
To add to Dave's answer:
div { position: relative; }
div div { position: absolute; top: 0; left: 0; }
You should keep an eye on the timezone information, as you might get into trouble when comparing non-tz-aware datetimes with tz-aware ones.
It's probably the best to always make them tz-aware (even if only as UTC), unless you really know why it wouldn't be of any use to do so.
#-----------------------------------------------
import datetime
import pytz
import dateutil.parser
#-----------------------------------------------
utc = pytz.utc
BERLIN = pytz.timezone('Europe/Berlin')
#-----------------------------------------------
def to_iso8601(when=None, tz=BERLIN):
if not when:
when = datetime.datetime.now(tz)
if not when.tzinfo:
when = tz.localize(when)
_when = when.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
return _when[:-8] + _when[-5:] # Remove microseconds
#-----------------------------------------------
def from_iso8601(when=None, tz=BERLIN):
_when = dateutil.parser.parse(when)
if not _when.tzinfo:
_when = tz.localize(_when)
return _when
#-----------------------------------------------
You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.
Sub dedupe_abcd()
Dim icol As Long
With Sheets("Sheet1") '<-set this worksheet reference properly!
icol = Application.Match("abcd", .Rows(1), 0)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=icol, Header:=xlYes
End With
End With
End Sub
Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.
To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.
Input the following into the script:
cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"
*Each command needs to be put on a new line calling cmd.exe again.
This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd
directly.
It is a much safer way than running batch files!
I try to get in the habit of using HostingEnvironment
instead of Server
as it works within the context of WCF services too.
HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");
Order By
is applied after union
, so just
add an order by
clause at the end of the statements:
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like '%a%'
Order By name
"The goal you specified requires a project to execute": The answer is in your question. I faced the same issue. Run the "mvn command" within the project folder, Also make sure sure its a maven configured project and hence contains the "POM.xml" file and you should be good to go!
//pull the last two digits of the year_x000D_
//logs to console_x000D_
//creates a new date object (has the current date and time by default)_x000D_
//gets the full year from the date object (currently 2017)_x000D_
//converts the variable to a string_x000D_
//gets the substring backwards by 2 characters (last two characters) _x000D_
console.log(new Date().getFullYear().toString().substr(-2));
_x000D_
JavaScript:
//A function for formatting a date to MMddyy_x000D_
function formatDate(d)_x000D_
{_x000D_
//get the month_x000D_
var month = d.getMonth();_x000D_
//get the day_x000D_
//convert day to string_x000D_
var day = d.getDate().toString();_x000D_
//get the year_x000D_
var year = d.getFullYear();_x000D_
_x000D_
//pull the last two digits of the year_x000D_
year = year.toString().substr(-2);_x000D_
_x000D_
//increment month by 1 since it is 0 indexed_x000D_
//converts month to a string_x000D_
month = (month + 1).toString();_x000D_
_x000D_
//if month is 1-9 pad right with a 0 for two digits_x000D_
if (month.length === 1)_x000D_
{_x000D_
month = "0" + month;_x000D_
}_x000D_
_x000D_
//if day is between 1-9 pad right with a 0 for two digits_x000D_
if (day.length === 1)_x000D_
{_x000D_
day = "0" + day;_x000D_
}_x000D_
_x000D_
//return the string "MMddyy"_x000D_
return month + day + year;_x000D_
}_x000D_
_x000D_
var d = new Date();_x000D_
console.log(formatDate(d));
_x000D_
JavaScript/jQuery doesn't support the default behavior of links "clicked" programmatically.
Instead, you can create a form and submit it. This way you don't have to use window.location
or window.open
, which are often blocked as unwanted popups by browsers.
This script has two different methods: one that tries to open three new tabs/windows (it opens only one in Internet Explorer and Chrome, more information is below) and one that fires a custom event on a link click.
Here is how:
<html>
<head>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<button id="testbtn">Test</button><br><br>
<a href="https://google.nl">Google</a><br>
<a href="http://en.wikipedia.org/wiki/Main_Page">Wikipedia</a><br>
<a href="https://stackoverflow.com/">Stack Overflow</a>
</body>
</html>
$(function()
{
// Try to open all three links by pressing the button
// - Firefox opens all three links
// - Chrome only opens one of them without a popup warning
// - Internet Explorer only opens one of them WITH a popup warning
$("#testbtn").on("click", function()
{
$("a").each(function()
{
var form = $("<form></form>");
form.attr(
{
id : "formform",
action : $(this).attr("href"),
method : "GET",
// Open in new window/tab
target : "_blank"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
});
});
// Or click the link and fire a custom event
// (open your own window without following
// the link itself)
$("a").on("click", function()
{
var form = $("<form></form>");
form.attr(
{
id : "formform",
// The location given in the link itself
action : $(this).attr("href"),
method : "GET",
// Open in new window/tab
target : "_blank"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
// Prevent the link from opening normally
return false;
});
});
For each link element, it:
Now you have a new tab/window loading "https://google.nl"
(or any URL you want, just replace it). Unfortunately when you try to open more than one window this way, you get an Popup blocked
messagebar when trying to open the second one (the first one is still opened).
More information on how I got to this method is found here:
I have been able to make it work by subclassing a UITabBarController and using private classes:
@interface UITabBarController (private)
- (UITabBar *)tabBar;
@end
@implementation CustomUITabBarController
- (void)viewDidLoad {
[super viewDidLoad];
CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
UIView *v = [[UIView alloc] initWithFrame:frame];
[v setBackgroundColor:kMainColor];
[v setAlpha:0.5];
[[self tabBar] addSubview:v];
[v release];
}
@end
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
It's better to create a new factor variable using cut(). I've added a few options using ggplot2 also.
df <- data.frame(
X1=seq(0, 5, by=0.001),
X2=rnorm(df$X1, mean = 3.5, sd = 1.5)
)
# Create new variable for plotting
df$Colour <- cut(df$X2, breaks = c(-Inf, 1, 3, +Inf),
labels = c("low", "medium", "high"),
right = FALSE)
### Base Graphics
plot(df$X1, df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 21)
plot(df$X1,df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 19, cex = 0.5)
# Using `with()`
with(df,
plot(X1, X2, xlab="POS", ylab="CS", col = Colour, pch=21, cex=1.4)
)
# Using ggplot2
library(ggplot2)
# qplot()
qplot(df$X1, df$X2, colour = df$Colour)
# ggplot()
p <- ggplot(df, aes(X1, X2, colour = Colour))
p <- p + geom_point() + xlab("POS") + ylab("CS")
p
p + facet_grid(Colour~., scales = "free")
If you currently have Red Gate SQL Toolbelt, you will need to unistall that too before continuing. Somehow it adds a reference to the 2005 version of the SQL Management Studio.
In case of Include Program will not terminate and display warning on browser,On the other hand Require program will terminate and display fatal error in case of file not found.
As UncleBens and Naveen have shown, there are good reasons for both. Which one is "better" depends on what behavior you want: Do you want to guarantee constant-time behavior, or do you want it to fall back to linear time when necessary?
it - vec.begin()
takes constant time, but the operator -
is only defined on random access iterators, so the code won't compile at all with list iterators, for example.
std::distance(vec.begin(), it)
works for all iterator types, but will only be a constant-time operation if used on random access iterators.
Neither one is "better". Use the one that does what you need.
Clustered Index
Non Clustered Index
Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.
Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.
SQL Server will normally only use an index if its selectivity is above 95%.
In addition to the answer, $ yarn cache clean
removes all libraries from cache. If you want to remove a specific lib's cache run $ yarn cache dir
to get the right yarn cache directory path for your OS, then $ cd
to that directory and remove the folder with the name
+ version
of the lib you want to cleanup.
Posting it from my project.
<select name="parent" id="parent"><option value="0">None</option>
<?php
$select="select=selected";
$allparent=mysql_query("select * from tbl_page_content where parent='0'");
while($parent=mysql_fetch_array($allparent))
{?>
<option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
<?php
}
?></select>
All the answers so far retain local commits. If you're really serious, you can discard all local commits and all local edits by doing:
git reset --hard origin/branchname
For example:
git reset --hard origin/master
This makes your local repository exactly match the state of the origin (other than untracked files).
If you accidentally did this after just reading the command, and not what it does :), use git reflog to find your old commits.
.NET 4+
IList<string> strings = new List<string>{"1","2","testing"};
string joined = string.Join(",", strings);
Detail & Pre .Net 4.0 Solutions
IEnumerable<string>
can be converted into a string array very easily with LINQ (.NET 3.5):
IEnumerable<string> strings = ...;
string[] array = strings.ToArray();
It's easy enough to write the equivalent helper method if you need to:
public static T[] ToArray(IEnumerable<T> source)
{
return new List<T>(source).ToArray();
}
Then call it like this:
IEnumerable<string> strings = ...;
string[] array = Helpers.ToArray(strings);
You can then call string.Join
. Of course, you don't have to use a helper method:
// C# 3 and .NET 3.5 way:
string joined = string.Join(",", strings.ToArray());
// C# 2 and .NET 2.0 way:
string joined = string.Join(",", new List<string>(strings).ToArray());
The latter is a bit of a mouthful though :)
This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) this one.
As of .NET 4.0, there are more overloads available in string.Join
, so you can actually just write:
string joined = string.Join(",", strings);
Much simpler :)
Use Python's decimal
module, which provides the Decimal
class.
From the comments:
It is worth noting that if you're doing math-heavy work and you don't absolutely need the precision from decimal, this can really bog things down. Floats are way, way faster to deal with, but imprecise. Decimals are extremely precise but slow.
This is python code for the ping in range of the 192.168.0.0-192.168.0.100
. You can change for loop as you comfort.
# -*- coding: utf-8 -*-
import socket
import os
import sys
up_ip =[] #list to store the ip-addresses of server online
for x in range(100): #here range is 0-100. You can change the range according to your comfort
server_ip = '192.168.0.'+ str(x)
print "Trying ,server_ip,... \n"
rep = os.system('ping -c 1 ' + server_ip)
if rep == 0:
up_ip.append(server_ip)
print '******************* Server Is Up **************** \n'
else:
print 'server is down \n'
print up_ip
You don't need to be echoing the info within the php file. A php include
will automatically include any HTML within that file.
Make sure you're actually using a index file with a .php
extension, .html
won't work with php includes. (Unless you're telling your server to treat .html files otherwise)
Make sure your paths are correctly set up. From your description, the way you've set it up your header.php/navbar.php/image.php files should be in your root directory. So your root directory should look like this:
index.php
navbar.php
image.php
header.php
Otherwise if those PHP files are in a folder called /includes/
, it should look like so:
<?php include ('includes/headings.php'); ?>
In researching this issue, I found something that will be important to anyone running into this same issue and looking for a solution.
From the original post, the following line of code:
$qb->add('where', $qb->expr()->in('r.winner', array('?1')));
Wrapping the named parameter as an array causes the bound parameter number issue. By removing it from its array wrapping:
$qb->add('where', $qb->expr()->in('r.winner', '?1'));
This issue should be fixed. This might have been a problem in previous versions of Doctrine, but it is fixed in the most recent versions of 2.0.
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.
jpanel1.setVisible(false);
In the Project’s Settings, add /FORCE:MULTIPLE
to the Linker’s Command Line options.
From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."
There are some changes required to JavaScript code to handle rendering based on user liking or not liking the page mandated by Facebook moving to Auth2.0 authorization.
Change is fairly simple:-
sessions has to be replaced by authResponse and uid by userID
Moreover given the requirement of the code and some issues faced by people(including me) in general with FB.login, use of FB.getLoginStatus is a better alternative. It saves query to FB in case user is logged in and has authenticated your app.
Refer to Response and Sessions Object section for info on how this might save query to FB server. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
Issues with FB.login and its fixes using FB.getLoginStatus. http://forum.developers.facebook.net/viewtopic.php?id=70634
Here is the code posted above with changes which worked for me.
$(document).ready(function(){
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid=" + user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
});
Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below
=====================
Yes, you need to import the operator:
import 'rxjs/add/operator/catch';
Or import Observable
this way:
import {Observable} from 'rxjs/Rx';
But in this case, you import all operators.
See this question for more details:
How about this: location.href.slice(0, - ((location.search + location.hash).length))
At the place I'm currently working, the official coding standard stipulates a maximum line length of eighty characters. The rational was to enable hard-copies of the code to be formatted. Needless to say, this led to very odd code layout. I've worked to eliminate this standard, mainly through the argument of 'when was the last time you made a hard-copy of code?' Readability now versus chance of making a hard-copy on an eighty column DMP?
Skizz
Instead of:
$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00' AND created<='{$end} 23:59:59' ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
$result.="{$row['email']},";
$result.="\n";
echo $result;
}
Use:
$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00' AND created<='{$end} 23:59:59' ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
echo implode(",", $row)."\n";
}
In a few words,
I think you should build a dataset/datatable in code and bind the grid to that.
Code check:
This is offtopic here but the people over at CodeReview are more than happy to help you.
I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.
Lists:
As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List
.
Lists are very straightforward to use but take a look at the related documentation anyway.
A very simple example to keep multiple bikes in a list:
List<Motorbike> bikes = new List<Motorbike>();
bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });
And to iterate over the list you can use the foreach
statement:
foreach(var bike in bikes) {
Console.WriteLine(bike.make);
}