I like using the following to prevent things being outside my div
elements. It helps with CSS rollovers too.
.marquee{
overflow:hidden;
}
this will hide anything that moves/is outside of the div which will prevent the browser expanding and causing a scroll bar to appear.
I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.
Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div
is restored, forcing the animations to restart.
All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head>
section of your page:
<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>
BTW, the closing </head>
in your code is misplaced: it must be before the starting <body>
.
This is old I know, but just a pointer to anyone using this ass a reference. I have just tried this and if you are using Oracle, JOIN does not work in DELETE statements. You get a the following message:
ORA-00933: SQL command not properly ended.
Just another solution using the datetime
module for Python 3+.
round(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
From http://www.coderanch.com/t/236675/java-programmer-SCJP/certification/xff
The hex literal 0xFF is an equal int(255). Java represents int as 32 bits. It look like this in binary:
00000000 00000000 00000000 11111111
When you do a bit wise AND with this value(255) on any number, it is going to mask(make ZEROs) all but the lowest 8 bits of the number (will be as-is).
... 01100100 00000101 & ...00000000 11111111 = 00000000 00000101
& is something like % but not really.
And why 0xff? this in ((power of 2) - 1). All ((power of 2) - 1) (e.g 7, 255...) will behave something like % operator.
Then
In binary, 0 is, all zeros, and 255 looks like this:
00000000 00000000 00000000 11111111
And -1 looks like this
11111111 11111111 11111111 11111111
When you do a bitwise AND of 0xFF and any value from 0 to 255, the result is the exact same as the value. And if any value higher than 255 still the result will be within 0-255.
However, if you do:
-1 & 0xFF
you get
00000000 00000000 00000000 11111111
, which does NOT equal the original value of -1 (11111111
is 255 in decimal).
Few more bit manipulation: (Not related to the question)
X >> 1 = X/2
X << 1 = 2X
Check any particular bit is set(1) or not (0) then
int thirdBitTobeChecked = 1 << 2 (...0000100)
int onWhichThisHasTobeTested = 5 (.......101)
int isBitSet = onWhichThisHasTobeTested & thirdBitTobeChecked;
if(isBitSet > 0) {
//Third Bit is set to 1
}
Set(1) a particular bit
int thirdBitTobeSet = 1 << 2 (...0000100)
int onWhichThisHasTobeSet = 2 (.......010)
onWhichThisHasTobeSet |= thirdBitTobeSet;
ReSet(0) a particular bit
int thirdBitTobeReSet = ~(1 << 2) ; //(...1111011)
int onWhichThisHasTobeReSet = 6 ;//(.....000110)
onWhichThisHasTobeReSet &= thirdBitTobeReSet;
XOR
Just note that if you perform XOR operation twice, will results the same value.
byte toBeEncrypted = 0010 0110
byte salt = 0100 1011
byte encryptedVal = toBeEncrypted ^ salt == 0110 1101
byte decryptedVal = encryptedVal ^ salt == 0010 0110 == toBeEncrypted :)
One more logic with XOR is
if A (XOR) B == C (salt)
then C (XOR) B == A
C (XOR) A == B
The above is useful to swap two variables without temp like below
a = a ^ b; b = a ^ b; a = a ^ b;
OR
a ^= b ^= a ^= b;
By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.
Hopefully this one piece of an alternate solution will be as valuable to someone else as it was for me.
Situation:
In an HTML5 page I had a menu that was a nav element inside a header (not THE header but a header in another element).
I wanted the navigation to stick to the top once a user scrolled to it, but previous to this the header was absolute positioned (so I could have it overlay something else slightly).
The solutions above never triggered a change because .offsetTop was not going to change as this was an absolute positioned element. Additionally the .scrollTop property was simply the top of the top most element... that is to say 0 and always would be 0.
Any tests I performed utilizing these two (and same with getBoundingClientRect results) would not tell me if the top of the navigation bar ever scrolled to the top of the viewable page (again, as reported in console, they simply stayed the same numbers while scrolling occurred).
Solution
The solution for me was utilizing
window.visualViewport.pageTop
The value of the pageTop property reflects the viewable section of the screen, therefore allowing me to track where an element is in reference to the boundaries of the viewable area.
This allowed a simple function assigned to the scroll event of the window to detect when the top of the navigation bar intersected with the top of the viewable area and apply the styling to make it stick to the top.
Probably unnecessary to say, anytime I am dealing with scrolling I expect to use this solution to programatically respond to movement of elements being scrolled.
Hope it helps someone else.
If you use an =
statement to assign a value to a var
with an object on the right side, javascript will not copy but reference the object.
You can use lodash's clone
method
var obj = {a: 25, b: 50, c: 75};
var A = _.clone(obj);
Or lodash's cloneDeep
method if your object has multiple object levels
var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.cloneDeep(obj);
Or lodash's merge
method if you mean to extend the source object
var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.merge({}, obj, {newkey: "newvalue"});
Or you can use jQuerys extend
method:
var obj = {a: 25, b: 50, c: 75};
var A = $.extend(true,{},obj);
Here is jQuery 1.11 extend method's source code :
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.
@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {
@ApiObjectField(description = "The code which is to be verified.")
@NotBlank(message = "mandatory")
private final String code;
@ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
private final String maskedMobileNumber;
public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
public String getcode() {
return code;
}
public String getMaskedMobileNumber() {
return maskedMobileNumber;
}
}
The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been
public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
You are inside vim. To save changes and quit, type:
<esc> :wq <enter>
That means:
:wq
An alternative that stdcall in the comments mentions is:
Z
twice).I've been learning android for the last few months, so I'm far from an expert, but I've been really disappointed with the documentation on ANRs.
Most of the advice seems to be geared towards avoiding them or fixing them by blindly looking through your code, which is great, but I couldn't find anything on analyzing the trace.
There are three things you really need to look for with ANR logs.
1) Deadlocks: When a thread is in the WAIT state, you can look through the details to find who it's "heldby=". Most of the time, it'll be held by itself, but if it's held by another thread, that's likely to be a danger sign. Go look at that thread and see what it's held by. You might find a loop, which is a clear sign that something has gone wrong. This is pretty rare, but it's the first point because when it happens, it's a nightmare
2) Main thread Waiting: If your main thread is in the WAIT state, check if it's held by another thread. This shouldn't happen, because your UI thread shouldn't be held by a background thread.
Both of these scenarios, mean you need to rework your code significantly.
3) Heavy operations on the main thread: This is the most common cause of ANRs, but sometimes one of the harder to find and fix. Look at the main thread details. Scroll down the stack trace and until you see classes you recognize (from your app). Look at the methods in the trace and figure out if you're making network calls, db calls, etc. in these places.
Finally, and I apologize for shamelessly plugging my own code, you can use the python log analyzer I wrote at https://github.com/HarshEvilGeek/Android-Log-Analyzer This will go through your log files, open ANR files, find deadlocks, find waiting main threads, find uncaught exceptions in your agent logs and print it all out on the screen in a relatively easy to read manner. Read the ReadMe file (which I'm about to add) to learn how to use it. It's helped me a ton in the last week!
The difference between undefined
and null
is minimal, but there is a difference. A variable whose value is undefined
has never been initialized. A variable whose value is null
was explicitly given a value of null
, which means that the variable was explicitly set to have no value. If you compare undefined
and null
by using the null==undefined
expression, they will be equal.
Repeat:
UIImage *img = [UIImage imageNamed:@"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];
Stretched
UIImage *img = [UIImage imageNamed:@"bg.png"];
view.layer.contents = img.CGImage;
Looks like most of the answers on this thread have not kept up. iOS Safari on iPads have fullscreen support now and it's very easy to implement using javascript.
Here's my full article on how to implement fullscreen capability on your web app.
Some versions of Tomcat and Jetty seem to ignore a entity body if it is present. Which can be a nuisance if you intended to receive it.
List<String> list = new ArrayList<String>(listOfTopicAuthors);
You forgot to declare double as a return type
public double diameter()
{
double d = radius * 2;
return d;
}
As of Python 3.5, you can use enhanced generators for async functions.
import asyncio
import datetime
Enhanced generator syntax:
@asyncio.coroutine
def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
yield from asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
New async/await
syntax:
async def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
On my Gentoo/Funtoo linux system I am having similar problems:
I gotting always not the correct device description and insufficient permissions:
# sudo ./adb devices
List of devices attached
???????????? no permissions
# ./adb usb
error: insufficient permissions for device
For me helps the howto from Google. In my case I needed to add the udev rule:
# cat /etc/udev/rules.d/51-android.rules
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev"
and setting up the filesystem rights
# chmod a+r /etc/udev/rules.d/51-android.rules
After replugging my smartphone the access to the phone was successful, it also appears now in Eclipse' Android Device Chooser:
# sudo ./adb devices
List of devices attached
3XXXXXXXXXXXXXC device
# sudo ./adb usb
restarting in USB mode
You also have to check the membership of your user to the plugdev-group.
Check out java.io.ByteArrayInputStream
In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN
like this
SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1
via raw query like this -
String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
+ " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
+ " WHERE " + RefuelTable.ID + " = " + id;
Cursor c = db.rawQuery(
rawQuery,
null
);
because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -
SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1
and hence be able to take advanatage of the SQLiteDatabase.query() helper method
Cursor c = db.query(
RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " + id,
null,
null,
null,
null
);
For a detailed blog post check this http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery
use fastcopy, a free tool. it has a delete option that is a lot faster then the way windows deletes files.
I don't know if you can do it on-demand, but you can enable the option "Track Active Item in Solution Explorer" (Tools->Options->Projects and Solutions->General) which will always select the active tab item in the solution explorer.
If you really want _.pluck
support back, you can use a mixin:
const _ = require("lodash")
_.mixin({
pluck: _.map
})
Because map
now supports a string (the "iterator") as an argument instead of a function.
For the SQL Server Owner, you should be able to use:
select suser_sname(owner_sid) as 'Owner', state_desc, *
from sys.databases
For a list of SQL Users:
select * from master.sys.server_principals
Ref. SQL Server Tip: How to find the owner of a database through T-SQL
From the documentation:
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called
static
in your package or next to your module and it will be available at/static
on the application.To generate URLs for static files, use the special
'static'
endpoint name:url_for('static', filename='style.css')
The file has to be stored on the filesystem as
static/style.css
.
If you would like to insert multiple values lets say from multiple inputs that have different post values but the same table to insert into then simply use:
mysql_query("INSERT INTO `table` (a,b,c,d,e,f,g) VALUES
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g')")
or die (mysql_error()); // Inserts 3 times in 3 different rows
I've written a little php script which rotates the image. Be sure to store the image in favour of just recalculate it each request.
<?php
header("Content-type: image/jpeg");
$img = 'IMG URL';
$exif = @exif_read_data($img,0,true);
$orientation = @$exif['IFD0']['Orientation'];
if($orientation == 7 || $orientation == 8) {
$degrees = 90;
} elseif($orientation == 5 || $orientation == 6) {
$degrees = 270;
} elseif($orientation == 3 || $orientation == 4) {
$degrees = 180;
} else {
$degrees = 0;
}
$rotate = imagerotate(imagecreatefromjpeg($img), $degrees, 0);
imagejpeg($rotate);
imagedestroy($rotate);
?>
Cheers
Tab is [HT], or character number 9, in the unicode library.
Rails4 has some added datatypes for Postgres.
For example, railscast #400 names two of them:
Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.
Besides, you can also use cidr, inet and macaddr. For more information:
You should try @bryn command but with the ` delimiter otherwise you will also extract the tables having a prefix or a suffix, this is what I usually do:
sed -n -e '/DROP TABLE.*`mytable`/,/UNLOCK TABLES/p' dump.sql > mytable.sql
Also for testing purpose, you may want to change the table name before importing:
sed -n -e 's/`mytable`/`mytable_restored`/g' mytable.sql > mytable_restored.sql
To import you can then use the mysql command:
mysql -u root -p'password' mydatabase < mytable_restore.sql
if use Toolbar
,you can try this
Drawable drawable = toolbar.getNavigationIcon();
drawable.setColorFilter(ContextCompat.getColor(appCompatActivity, colorId), PorterDuff.Mode.SRC_ATOP);
My Windows 10 machine was automagically updated today. Looks like the "Windows 10 Anniversary update" When I restarted Virtualbox my server with a bridged adapter showed same as OP. I tried rerunning the VirtualBox installer (it did a Repair) - that did not fix the issue. I tried running the installer again as Admin (it did a Repair) - that did not fix. I ran the installer and selected UnInstall, then ran it again to Install. And the Network adapter settings looked good. Server started and connected to my network as usual. Whew. Hope this helps someone.
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctness in Java. This usage of const
in C++ is much different than just declaring constant variables, if you didn't know. Essentially, it ensures that an object is immutable when accessed through a special kind of pointer called a const-pointer When in Java, in places where I'd normally want to return a const-pointer, I instead return a reference with an interface type containing only methods that shouldn't have side effects. Unfortunately, this isn't enforced by the langauge.
Wikipedia offers the following information on the subject:
Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.
You can use the update()
method to build a new dictionary containing all the items:
dall = {}
dall.update(d1)
dall.update(d2)
dall.update(d3)
Or, in a loop:
dall = {}
for d in [d1, d2, d3]:
dall.update(d)
In Mysql, you can not update one table by subquery the same table.
You can separate the query in two parts, or do
UPDATE TABLE_A AS A INNER JOIN TABLE_A AS B ON A.field1 = B.field1 SET field2 = ?
If it doesn't need to be a macro, then just put =A1*1.1
into (say) D7, then drag the formula fill handle across, then down.
If you strictly want to remove duplicates based on one property, you can reduce
the array into and object based on the place
property, since the object can only have unique keys, you can then just get the values
to get back to an array:
const unique = Object.values(things.thing.reduce((o, t) => ({ ...o, [t.place]: t }), {}))
issue the command:
SET time_zone = 'America/New_York';
(Or whatever time zone GMT+1 is.: http://www.php.net/manual/en/timezones.php)
This is the command to set the MySQL timezone for an individual client, assuming that your clients are spread accross multiple time zones.
This command should be executed before every SQL command involving dates. If your queries go thru a class, then this is easy to implement.
For mobile app i use only VH and VW
<div class="container">
<div class="title">Title</div>
<div class="content">Content</div>
<div class="footer">Footer</div>
</div>
.container {
width: 100vw;
height: 100vh;
font-size: 5vh;
}
.title {
height: 20vh;
background-color: red;
}
.content {
height: 60vh;
background: blue;
}
.footer {
height: 20vh;
background: green;
}
Use:
if (function_exists('curl_file_create')) { // php 5.5+
$cFile = curl_file_create($file_name_with_full_path);
} else { //
$cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
You can also refer:
http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/
Important hint for PHP 5.5+:
Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
It's an eclipse setup issue, not a Jersey issue.
From this thread ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
Right click your eclipse project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Gradle Dependencies -> Finish.
So Eclipse wasn't using the Gradle dependencies when Apache was starting .
I believe you are having the same problem here.
The sheet must be active before you can select a range on it.
Also, don't omit the sheet name qualifier:
Sheets("BxWsn Simulation").Select
Sheets("BxWsn Simulation").Range("Result").Select
Or,
With Sheets("BxWsn Simulation")
.Select
.Range("Result").Select
End WIth
which is the same.
This doesn't necessarily touch on OOP capabilities but in our last set of interviews we used a selection of buggy code from the Bug of the Month list. Watching the candidates find the bugs shows their analytical capabilities, shows the know how to interpret somebody elses code
If you want to run inside a background service and take the data in foreground use the below one, it is tested and verified.
public class MyService extends Service
implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private static final int ASHIS = 1234;
Intent intentForPendingIntent;
HandlerThread handlerThread;
Looper looper;
GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRrequest;
private static final int UPDATE_INTERVAL = 1000;
private static final int FASTEST_INTERVAL = 100;
private static final int DSIPLACEMENT_UPDATES = 1;
;
private Handler handler1;
private Runnable runable1;
private Location mLastLocation;
private float waitingTime;
private int waiting2min;
private Location locationOld;
private double distance;
private float totalWaiting;
private float speed;
private long timeGpsUpdate;
private long timeOld;
private NotificationManager mNotificationManager;
Notification notification;
PendingIntent resultPendingIntent;
NotificationCompat.Builder mBuilder;
// Sets an ID for the notification
int mNotificationId = 001;
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "speedExceeded";
private final Handler handler = new Handler();
Intent intentforBroadcast;
int counter = 0;
private Runnable sendUpdatesToUI;
@Nullable
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(MyService.this, "binder", Toast.LENGTH_SHORT).show();
return null;
}
@Override
public void onCreate() {
showNotification();
intentforBroadcast = new Intent(BROADCAST_ACTION);
Toast.makeText(MyService.this, "created", Toast.LENGTH_SHORT).show();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
createLocationRequest();
mGoogleApiClient.connect();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void showNotification() {
mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_media_play)
.setContentTitle("Total Waiting Time")
.setContentText(totalWaiting+"");
Intent resultIntent = new Intent(this, trackingFusion.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
startForeground(001, mBuilder.getNotification());
}
@Override
public void onLocationChanged(Location location) {
//handler.removeCallbacks(runable);
Toast.makeText(MyService.this, "speed" + speed, Toast.LENGTH_SHORT).show();
timeGpsUpdate = location.getTime();
float delta = (timeGpsUpdate - timeOld) / 1000;
if (location.getAccuracy() < 100) {
speed = location.getSpeed();
distance += mLastLocation.distanceTo(location);
Log.e("distance", "onLocationChanged: " + distance);
//mLastLocation = location;
//newLocation = mLastLocation;
Log.e("location:", location + "");
//speed = (long) (distance / delta);
locationOld = location;
mLastLocation = location;
diaplayViews();
}
diaplayViews();
/*if (map != null) {
map.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}*/
}
private void createLocationRequest() {
mLocationRrequest = new LocationRequest();
mLocationRrequest.setInterval(UPDATE_INTERVAL);
mLocationRrequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRrequest.setSmallestDisplacement(DSIPLACEMENT_UPDATES);
}
private void methodToCalculateWaitingTime() {
if (handler1 != null) {
handler1.removeCallbacks(runable1);
}
Log.e("Here", "here1");
handler1 = new Handler(Looper.getMainLooper());
runable1 = new Runnable() {
public void run() {
Log.e("Here", "here2:" + mLastLocation.getSpeed());
if (mLastLocation != null) {
diaplayViews();
if ((mLastLocation.getSpeed() == 0.0)) {
increaseTime();
} else {
if (waitingTime <= 120) {
waiting2min = 0;
}
}
handler1.postDelayed(this, 10000);
} else {
if (ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastLocation = locationOld;
}
}
};
handler1.postDelayed(runable1, 10000);
}
private void diaplayViews() {
float price = (float) (14 + distance * 0.5);
//textDistance.setText(waitingTime);a
}
private void increaseTime() {
waiting2min = waiting2min + 10;
if (waiting2min >= 120)
{
if (waiting2min == 120) {
waitingTime = waitingTime + 2 * 60;
} else {
waitingTime = waitingTime + 10;
}
totalWaiting = waitingTime / 60;
showNotification();
Log.e("waiting Time", "increaseTime: " + totalWaiting);
}
}
@Override
public void onDestroy() {
Toast.makeText(MyService.this, "distroyed", Toast.LENGTH_SHORT).show();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
mGoogleApiClient.disconnect();
}
@Override
public void onConnected(Bundle bundle) {
Log.e("Connection_fusion", "connected");
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
}
private void startLocationUpdates() {
Location location = plotTheInitialMarkerAndGetInitialGps();
if (location == null) {
plotTheInitialMarkerAndGetInitialGps();
} else {
mLastLocation = location;
methodToCalculateWaitingTime();
}
}
private Location plotTheInitialMarkerAndGetInitialGps() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRrequest, this);
locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if ((locationOld != null)) {
mLastLocation = locationOld;
timeOld = locationOld.getTime();
} else {
startLocationUpdates();
}
return mLastLocation;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
Toast.makeText(MyService.this, "start command", Toast.LENGTH_SHORT).show();
sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 10000); // 5 seconds
}
};
handler.postDelayed(sendUpdatesToUI, 10000); // 1 second
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
@Override
public void onStart(Intent intent, int startId) {
sendUpdatesToUI = new Runnable() {
public void run() {
Log.e("sent", "sent");
DisplayLoggingInfo();
handler.postDelayed(this, 5000); // 5 seconds
}
};
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
Log.i("LocalService", "Received start id " + startId + ": " + intent);
super.onStart(intent, startId);
}
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intentforBroadcast.putExtra("distance", distance);
LocalBroadcastManager.getInstance(this).sendBroadcast(intentforBroadcast);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onMapReady(GoogleMap googleMap) {
}
}
gb = df.groupby(['A'])
gb_groups = grouped_df.groups
If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..
gb_groups.keys()
key_list = [key1, key2, key3 and so on...]
for key, values in gb_groups.iteritems():
if key in key_list:
print df.ix[values], "\n"
You can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :
db.sivaUserInfo.aggregate([
{
$lookup: {
from: "sivaUserRole",
localField: "userId",
foreignField: "userId",
as: "userRole"
}
},
{
$unwind: "$userRole"
},
{
$lookup: {
from: "sivaUserInfo",
localField: "userId",
foreignField: "userId",
as: "userInfo"
}
},
{
$unwind: "$userInfo"
}
])
This will return the following structure :
{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"phone" : "0000000000",
"userRole" : {
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"role" : "admin"
},
"userInfo" : {
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"phone" : "0000000000"
}
}
Maybe this could be considered an anti-pattern because MongoDB wasn't meant to be relational but it is useful.
Note this
function FollowMouse() {
for(var i=0; i< arguments.length; i++) {
arguments[i].style.top = event.clientY+"px";
arguments[i].style.left = event.clientX+"px";
}
};
//---------------------------
html page
<body onmousemove="FollowMouse(d1,d2,d3)">
<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>
</body>
can call function with any Args
<body onmousemove="FollowMouse(d1,d2)">
or
<body onmousemove="FollowMouse(d1)">
I suggest to use ReactiveProperty. This is the shortest method except Fody.
public class Data : INotifyPropertyChanged
{
// boiler-plate
...
// props
private string name;
public string Name
{
get { return name; }
set { SetField(ref name, value, "Name"); }
}
}
instead
public class Data
{
// Don't need boiler-plate and INotifyPropertyChanged
// props
public ReactiveProperty<string> Name { get; } = new ReactiveProperty<string>();
}
(DOCS)
<div class="headerdivider"></div>
and
.headerdivider {
border-left: 1px solid #38546d;
background: #16222c;
width: 1px;
height: 80px;
position: absolute;
right: 250px;
top: 10px;
}
Try it.
$data = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
$maxKey = current(array_keys($data, max($data)));
var_dump($maxKey);
Get the router from the container.
$router = $this->get('router');
Then use the router to generate the Url
$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox
var queue = [];
function checking(id){
queue.push(id)
if (queue.length===3){
queue[0].checked = false
queue.shift()
}
}
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
I think 'input' simply works here the same way 'oninput' does in the DOM Level O Event Model.
Incidentally:
Just as silkfire commented it, I too googled for 'jQuery input event'. Thus I was led to here and astounded to learn that 'input' is an acceptable parameter to jquery's bind() command. In jQuery in Action (p. 102, 2008 ed.) 'input' is not mentionned as a possible event (against 20 others, from 'blur' to 'unload'). It is true that, on p. 92, the contrary could be surmised from rereading (i.e. from a reference to different string identifiers between Level 0 and Level 2 models). That is quite misleading.
Say you have a FaceView
which is some sort of image. You're going to have many of them on screen (or, in a collection view, table, stack view or other list).
In the class FaceView
you will need a variable "index"
class FaceView: UIView {
var index: Int
so that each FaceView can be self-aware of "which" face it is on screen.
So you must add var index: Int
to the class in question.
So you are adding many FaceView to your screen ...
let f = FaceView()
f.index = 73
.. you add f to your stack view, screen, or whatever.
You now add a click to f
f.addGestureRecognizer(UITapGestureRecognizer(target: self,
action: #selector(tapOneOfTheFaces)))
@objc func tapOneOfTheFaces(_ sender: UITapGestureRecognizer) {
if let tapped = sender.view as? CirclePerson {
print("we got it: \(tapped.index)")
You now know "which" face was clicked in your table, screen, stack view or whatever.
It's that easy.
Inspired by TheIT, I just got this to work by manipulating the manifest file but in a slightly different fashion. Set the icon in the application setting so that the majority of the activities get the icon. On the activity where you want to show the logo, add the android:logo attribute to the activity declaration. In the following example, only LogoActivity should have the logo, while the others will default to icon.
<application
android:name="com.your.app"
android:icon="@drawable/your_icon"
android:label="@string/app_name">
<activity
android:name="com.your.app.LogoActivity"
android:logo="@drawable/your_logo"
android:label="Logo Activity" >
<activity
android:name="com.your.app.IconActivity1"
android:label="Icon Activity 1" >
<activity
android:name="com.your.app.IconActivity2"
android:label="Icon Activity 2" >
</application>
Hope this helps someone else out!
Please remove the servlet jar from web project,as any how, the application/web server already had.
Use HAVING MIN(...)
Something like:
SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;
Use r.URL.Query()
when you appending to existing query, if you are building new set of params use the url.Values
struct like so
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
// if you appending to existing query this works fine
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
// or you can create new url.Values struct and encode that like so
q := url.Values{}
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
I ended creating my own functions:
@Component({
selector: 'cookie-consent',
template: cookieconsent_html,
styles: [cookieconsent_css]
})
export class CookieConsent {
private isConsented: boolean = false;
constructor() {
this.isConsented = this.getCookie(COOKIE_CONSENT) === '1';
}
private getCookie(name: string) {
let ca: Array<string> = document.cookie.split(';');
let caLen: number = ca.length;
let cookieName = `${name}=`;
let c: string;
for (let i: number = 0; i < caLen; i += 1) {
c = ca[i].replace(/^\s+/g, '');
if (c.indexOf(cookieName) == 0) {
return c.substring(cookieName.length, c.length);
}
}
return '';
}
private deleteCookie(name) {
this.setCookie(name, '', -1);
}
private setCookie(name: string, value: string, expireDays: number, path: string = '') {
let d:Date = new Date();
d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
let expires:string = `expires=${d.toUTCString()}`;
let cpath:string = path ? `; path=${path}` : '';
document.cookie = `${name}=${value}; ${expires}${cpath}`;
}
private consent(isConsent: boolean, e: any) {
if (!isConsent) {
return this.isConsented;
} else if (isConsent) {
this.setCookie(COOKIE_CONSENT, '1', COOKIE_CONSENT_EXPIRE_DAYS);
this.isConsented = true;
e.preventDefault();
}
}
}
If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false
like this:
function DoAction(id, name)
{
// your code
return false;
}
In my case just add using System;
solve the issue.
If you want to include both - accept on enter and accept on click then do -
<div class="form-group">
<input class="form-control" type="text"
name="search" placeholder="Enter Search Text"
[(ngModel)]="filterdata"
(keyup.enter)="searchByText(filterdata)">
<button type="submit"
(click)="searchByText(filterdata)" >
</div>
I think I got it. It's:
"SVN Client Path" /command:update / path:"My folder path"
Node : http://www.w3schools.com/js/js_htmldom_nodes.asp
The Node object represents a single node in the document tree. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.
Element : http://www.w3schools.com/js/js_htmldom_elements.asp
The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.
duplicate :
One liners for saving/reading to/from String
, using java.nio
.
import java.nio.file.{Paths, Files, StandardOpenOption}
import java.nio.charset.{StandardCharsets}
import scala.collection.JavaConverters._
def write(filePath:String, contents:String) = {
Files.write(Paths.get(filePath), contents.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE)
}
def read(filePath:String):String = {
Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8).asScala.mkString
}
This isn't suitable for large files, but will do the job.
Some links:
java.nio.file.Files.write
java.lang.String.getBytes
scala.collection.JavaConverters
scala.collection.immutable.List.mkString
You don't need to use .html()
. You should go with .val()
.
From the doc of .val()
:
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. When called on an empty collection, it returnsundefined
.
var message = $('#message').val();
1 - Change Your tables search engine from 'My ISAM' to 'Inno DB' by Operations tab 2 - you must do this for all tables that you want make relationship between 3 - localhost/phpmyadmin/tbl_relation.php?db=your_database_name&table=your_table_name then replace this url in browser, then you will be able to see the relationship page
Use 'a'
, 'a'
means append
. Anything written to a file opened with 'a'
attribute is written at the end of the file.
with open('file.txt', 'a') as file:
file.write('input')
You should definitely avoid using <jsp:...>
tags. They're relics from the past and should always be avoided now.
Use the JSTL.
Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a
public SomeType getQuestionPaperID() {
//...
}
method in your bean.
Once you have that, you can display the value of this property using this code :
<c:out value="${Questions.questionPaperID}" />
or, to specifically target the session scoped attributes (in case of conflicts between scopes) :
<c:out value="${sessionScope.Questions.questionPaperID}" />
Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.
Um, shouldn't the destructor be calling delete, rather than delete[]?
to remove the height:
$('div#someDiv').css('height', '');
$('div#someDiv').css('height', null);
like John pointed out, set height to auto
:
$('div#someDiv').css('height', 'auto');
(checked with jQuery 1.4)
I've been usually doing generic filtering over rows like this:
criterion = lambda row: row['countries'] not in countries
not_in = df[df.apply(criterion, axis=1)]
Just in case, you are using the GMaps.js library, which makes it a bit simpler to do things like Geocoding and custom pins, here's how you solve this issue using the techniques learned from the previous answers.
var Gmap = new GMaps({
div: '#main-map', // FYI, this setting property used to be 'el'. It didn't need the '#' in older versions
lat: 51.044308,
lng: -114.0630914,
zoom: 15
});
// To access the Native Google Maps object use the .map property
if(Gmap.map) {
// Disabling mouse wheel scroll zooming
Gmap.map.setOptions({ scrollwheel: false });
}
special_func to avoid try-except repetition:
def special_func(test_case_dict):
final_dict = {}
exception_dict = {}
def try_except_avoider(test_case_dict):
try:
for k,v in test_case_dict.items():
final_dict[k]=eval(v) #If no exception evaluate the function and add it to final_dict
except Exception as e:
exception_dict[k]=e #extract exception
test_case_dict.pop(k)
try_except_avoider(test_case_dict) #recursive function to handle remaining functions
finally: #cleanup
final_dict.update(exception_dict)
return final_dict #combine exception dict and final dict
return try_except_avoider(test_case_dict)
Run code:
def add(a,b):
return (a+b)
def sub(a,b):
return (a-b)
def mul(a,b):
return (a*b)
case = {"AddFunc":"add(8,8)","SubFunc":"sub(p,5)","MulFunc":"mul(9,6)"}
solution = special_func(case)
Output looks like:
{'AddFunc': 16, 'MulFunc': 54, 'SubFunc': NameError("name 'p' is not defined")}
To convert to variables:
locals().update(solution)
Variables would look like:
AddFunc = 16, MulFunc = 54, SubFunc = NameError("name 'p' is not defined")
I personally really hate the alternate syntax. One nice thing about the braces is that most IDEs, vim, etc all have bracket highlighting. In my text editor I can double click a brace and it will highlight the whole chunk so I can see where it ends and begins very easily.
I don't know of a single editor that can highlight endif, endforeach, etc.
you can probably ping the server via ajax inside javascript. The php file might look something like:
<?php
session_start();
$id = session_id();
echo $id;
?>
This will return you the current session id. Was this what you were looking for.
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
You can use below code to get the batch of list.
Iterable<List<T>> batchIds = Iterables.partition(list, batchSize);
You need to import Google Guava library to use above code.
do like this-paste your html code inside your separate html file using GET method.
$mail->IsHTML(true);
$mail->WordWrap = 70;
$mail->addAttachment= $_GET['addattachment']; $mail->AltBody
=$_GET['AltBody']; $mail->Subject = $_GET['subject']; $mail->Body = $_GET['body'];
On RHEL 6 this worked for me also:
umount -f -a -t cifs -l FOLDER_NAME
It depends on where your postgresql server is installed. You use the pg_ctl to manually start the server like below.
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
Before this line at main.js:
mainWindow = new BrowserWindow({width: 800, height: 900})
mainWindow.setMenu(null) //this will r menu bar
First initialize webservices:
$client = new SoapClient("http://example.com/webservices?wsdl");
Then set and pass the parameters:
$params = array (
"arg0" => $contactid,
"arg1" => $desc,
"arg2" => $contactname
);
$response = $client->__soapCall('methodname', array($params));
Note that the method name is available in WSDL as operation name, e.g.:
<operation name="methodname">
Here's one reason you may want to use one over the other - password retrieval.
If you only store a hash of a user's password, you can't offer a 'forgotten password' feature.
Another solution is to migrate the database to e.g 2012 when you "export" the DB from e.g. Sql Server manager 2014. This is done in menu Tasks-> generate scripts when right-click on DB. Just follow this instruction:
https://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/
It generates an scripts with everything and then in your SQL server manager e.g. 2012 run the script as specified in the instruction. I have performed the test with success.
So, if you have a statement something like the following, you're saying that you get no 'print' result?
select * from sysobjects PRINT 'Just selected * from sysobjects'
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like
raiserror ('My Print Statement', 10,1) with nowait
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.
http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getName()
From http://www.xinotes.org/notes/note/774/ :
Java has built-in functions to get the basename and dirname for a given file path, but the function names are not so self-apparent.
import java.io.File;
public class JavaFileDirNameBaseName {
public static void main(String[] args) {
File theFile = new File("../foo/bar/baz.txt");
System.out.println("Dirname: " + theFile.getParent());
System.out.println("Basename: " + theFile.getName());
}
}
Here is a simple trick to remember the difference between slice
vs splice
var a=['j','u','r','g','e','n'];
// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]
//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]
Trick to remember:
Think of "spl" (first 3 letters of splice)
as short for "specifiy length", that the second argument should be a length not an index
its very simple
just write:
//first create table named test....
create table test (name varchar2(10),age number(5));
//when you run the above code a table will be created....
//now we have to insert a name & an age..
Make sure age will be inserted via opening a form that seeks our help to enter the value in it
insert into test values('Deepak', :age);
//now run the above code and you'll get "1 row inserted" output...
/now run the select query to see the output
select * from test;
//that's all ..Now i think no one has any queries left over accepting a user data...
you can do like this in your typescript code
onNavigate(){
var location="https://google.com",
}
In your html code add an anchor tag and pass that variable(location)
<a href="{{location}}" target="_blank">Redirect Location</a>
Suppose you have url like this www.google.com
without http
and you are not getting redirected to the given url then add http://
to the location
like this
var location = 'http://'+ www.google.com
I've used:
pg_restore -c -d database_name filename.dump
I actually prefer to use the html button form element and make it runat=server. The button element can hold other elements inside it. You can even add formatting inside it with span's or strong's. Here is an example:
<button id="BtnSave" runat="server"><img src="Images/save.png" />Save</button>
I am currently using Rob de la Cruz's reply:
Object.keys(obj)
And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.
if (!Object.keys) {
Object.keys = function(object) {
var keys = [];
for (var o in object) {
if (object.hasOwnProperty(o)) {
keys.push(o);
}
}
return keys;
};
}
I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.
Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.
As a side-note, you can enable/disable individual warnings using #pragma
. You can have a look at the documentation here
From the documentation:
// pragma_warning.cpp
// compile with: /W1
#pragma warning(disable:4700)
void Test() {
int x;
int y = x; // no C4700 here
#pragma warning(default:4700) // C4700 enabled after Test ends
}
int main() {
int x;
int y = x; // C4700
}
As long as your List is a concrete class, you can simply call the contains() method as long as you have implemented your equals() method on MyItem.
// given
// some input ... you to complete
// when
List<MyItems> results = service.getMyItems();
// then
assertTrue(results.contains(new MyItem("foo")));
assertTrue(results.contains(new MyItem("bar")));
Assumes you have implemented a constructor that accepts the values you want to assert on. I realise this isn't on a single line, but it's useful to know which value is missing rather than checking both at once.
Yes definitely you can connect to the MySql online database for that you need to create a web service. This web service will provide you access to the MySql database. Then you can easily pull and push data to MySql Database. PHP will be a good option for creating web service its simple to implement. Good luck...
What works for me is that:
This time it works for me. But I don't know why it doesn't have my key file information at first when the instance was launched. Check this link too https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html#TroubleshootingInstancesConnectingMindTerm
Node.js runs on top of the V8 Javascript engine, which itself optimizes performance by compiling javascript code into native code... so no reason really for compiling then, is there?
CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml
file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.
Unique format:
server {
listen 80;
server_name "~^www\.(.*)$" ;
return 301 https://$1$request_uri ;
}
For me, this solution worked like a charm: http://home.pacific.net.hk/~edx/bin/readmeocx.txt
Fix these two lines like that:
Object={F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0; COMDLG32.OCX
Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCX
Search the files (.vbp and .frm) for lines like this:
Begin ComctlLib.ImageList ILTree
Begin ComctlLib.StatusBar StatusBar1
Begin ComctlLib.Toolbar Toolbar1`
The lines may be like this:
Begin MSComctlLib.ImageList ILTree
Begin MSComctlLib.StatusBar StatusBar1
Begin MSComctlLib.Toolbar Toolbar1`
This may not me a so good of a answer but if you first select all the files you want to access by pressing on them in the side bar, so that they pop up on top of your screen for example: script.js, index.html, style.css. Close all the files you don't need at the top.
When you're done with that you press Ctrl+B on windows and linux, i don't know what it is on mac.
But there you have it. please send no hate
Go to your workspace folder
Now it will show what all the files can be committed.
Git uses "the index" to prepare commits. You can add and remove changes from the index before you commit (in your paste you already have deleted ~10 files with git rm
). When the index looks like you want it, run git commit
.
Usually this will fire up vim
. To insert text hit i
, <esc>
goes back to normal mode, hit ZZ
to save and quit (ZQ
to quit without saving). voilà, there's your commit
None of those worked for me. Try this.
console.log($(canvasjQueryElement)[0].width)
it has changed and its docked to the right bottom of your android studio by default.
if you dont have that you can open it through view -> tool windows -> device file explorer
the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..
It might either be a header file or your own function Declaration..
Use this:
android:gravity="top"
or
android:gravity="top|left"
As a side-note...this can also happen when there is a problem with (internal) data-mapping from SQL Objects.
For instance...
I created a SQL Scalar Function
that accidentally returned a VARCHAR
...and then...used it to generate a column in a VIEW
. The VIEW
was correctly mapped in the DbContext
...so Linq was calling it just fine. However, the Entity expected DateTime? and the VIEW
was returning String.
Which ODDLY throws...
"There is already an open DataReader associated with this Command which must be closed first"
It was hard to figure out...but after I corrected the return parameters...all was well
For a VARBINARY(MAX)
column, I had to use NVARCHAR(MAX)
:
cast(Content as nvarchar(max))
Or
CONVERT(NVARCHAR(MAX), Content, 0)
VARCHAR(MAX) didn't show the entire value
You are trying to set the timezone for date_time which already has a timezone.
Use replace
and astimezone
functions.
local_tz = pytz.timezone('Asia/Kolkata')
current_time = datetime.now().replace(tzinfo=pytz.utc).astimezone(local_tz)
Like Renat said, remove: db.Books.Attach(book);
Also, change your result query to use "AsNoTracking", because this query is throwing off entity framework's model state. It thinks "result" is the book to track now and you don't want that.
var result = db.Books.AsNoTracking().SingleOrDefault(b => b.BookNumber == bookNumber);
You can calculate the offset
of the element and then compare that with the scroll
value like:
$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
console.log('H1 on the view!');
}
});
Check this Demo Fiddle
Updated Demo Fiddle no alert -- instead FadeIn() the element
Updated code to check if the element is inside the viewport or not. Thus this works whether you are scrolling up or down adding some rules to the if statement:
if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
//Do something
}
If any one had the same problem as me and the charset was already correct, simply do this:
After trying a few of these answers and finding they don't scale well with multiple links (for example the accepted answer requires a line of jquery for every link you have), I came across a way that requires minimal code to get working, and it also appears to work perfectly, at least on Chrome.
You add this line to activate it:
$('[data-toggle="popover"]').popover();
And these settings to your anchor links:
data-toggle="popover" data-trigger="hover"
See it in action here, I'm using the same imports as the accepted answer so it should work fine on older projects.
Throwing this in for PowerShell 2.0 and upwards:
Run New-EventLog
once to register the event source:
New-EventLog -LogName Application -Source MyApp
Then use Write-EventLog
to write to the log:
Write-EventLog
-LogName Application
-Source MyApp
-EntryType Error
-Message "Immunity to iocaine powder not detected, dying now"
-EventId 1
You don't really need the directive, can achieve it by using the ng-init and ng-checked. below demo link shows how to set the initial value for checkbox in angularjs.
<form>
<div>
Released<input type="checkbox" ng-model="Released" ng-bind-html="ACR.Released" ng-true-value="true" ng-false-value="false" ng-init='Released=true' ng-checked='true' />
Inactivated<input type="checkbox" ng-model="Inactivated" ng-bind-html="Inactivated" ng-true-value="true" ng-false-value="false" ng-init='Inactivated=false' ng-checked='false' />
Title Changed<input type="checkbox" ng-model="Title" ng-bind-html="Title" ng-true-value="true" ng-false-value="false" ng-init='Title=false' ng-checked='false' />
</div>
<br/>
<div>Released value is <b>{{Released}}</b></div>
<br/>
<div>Inactivated value is <b>{{Inactivated}}</b></div>
<br/>
<div>Title value is <b>{{Title}}</b></div>
<br/>
</form>
// Code goes here
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
});
First, JavaScript's switch
is no faster than if/else
(and sometimes much slower).
Second, the only way to use switch
with multiple variables is to combine them into one primitive (string, number, etc) value:
var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
case "foo-bar": ...
...
}
But, personally, I would rather see a set of if
/else
statements.
Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
The exit codes only have meaning as assigned by the script author. The Unix tradition is that exit code 0 means 'success', anything else is failure. The only way to be sure what the exit codes for a given script mean is to examine the script itself.
This is another option:
export default function Counter() {
}
use explode() .
Example from the docs.
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
note that explode has a limit function. So you could do something like
$message = implode(" ", explode(" ", $long_message, 20));
A technique that is handy on a Linux system is using domain sockets:
import socket
import sys
import time
def get_lock(process_name):
# Without holding a reference to our socket somewhere it gets garbage
# collected when the function exits
get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
# The null byte (\0) means the socket is created
# in the abstract namespace instead of being created
# on the file system itself.
# Works only in Linux
get_lock._lock_socket.bind('\0' + process_name)
print 'I got the lock'
except socket.error:
print 'lock exists'
sys.exit()
get_lock('running_test')
while True:
time.sleep(3)
It is atomic and avoids the problem of having lock files lying around if your process gets sent a SIGKILL
You can read in the documentation for socket.close
that sockets are automatically closed when garbage collected.
Simplest & most correct way is:
from distutils.util import strtobool
parser.add_argument('--feature', dest='feature',
type=lambda x: bool(strtobool(x)))
Do note that True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
This isn't possible due to security reasons. At least not on modern browsers. This is because any code getting access to the path of the file can be considered dangerous and a security risk. Either you'll end up with an undefined value, an empty string or an error will be thrown.
When a file form is submitted, the browser buffers the file temporarily into an upload directory and only the temporary file name of that file and basename of that file is submitted.
Douglas Crockford has some very good explanations of inheritance in JavaScript:
I think may be you should try to convert the data to json format. It can be done by using gson lib. Try something like below.
I don't know it is a best solutions or not but you could do it this way.It worked for me
example : `
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response info(@HeaderParam("Accept") String accept) {
Info information = new Info();
information.setInfo("Calc Application Info");
System.out.println(accept);
if (!accept.equals(MediaType.APPLICATION_JSON)) {
return Response.status(Status.ACCEPTED).entity(information).build();
} else {
Gson jsonConverter = new GsonBuilder().create();
return Response.status(Status.ACCEPTED).entity(jsonConverter.toJson(information)).build();
}
}
In the first example must change those to:
requestStream.Flush();
requestStream.Close();
First flush and after that close.
The angular/cli
versions and their installed angular/compiler
versions:
Can be confirmed by reviewing the angular/cli
's package.json
file in the repository newer repository. One would have to install the specific cli version to get the specific angular version:
npm -g install @angular/[email protected].* # For ^5.0.0
use labelpad parameter:
pl.xlabel("...", labelpad=20)
or set it after:
ax.xaxis.labelpad = 20
Initialize your now
variable.
time_t now = time(0); // Get the system time
The localtime
function is used to convert the time value in the passed time_t
to a struct tm
, it doesn't actually retrieve the system time.
git fetch && git merge origin/develop
It is not exactly for Xcode5 but this question links people who want to check where are provisioning profiles:
Following documentation https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html
Ten you can start context menu on each profile and click "Show in Finder" or "Move to Trash".
Fatal error: Call to undefined function pg_connect()...
I had this error when I was installing Lampp or xampp in Archlinux,
The solution was edit the php.ini, it is located in /opt/lampp/etc/php.ini
then find this line and uncomment
extension="pgsql.so"
then restart the server apache with xampp and test...
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.
Try compiling with -g3
remove any optimization flag.
Then it might work.
HTH!
Try it.. It will first look for anchor tag that contain span with class "ui-icon-circle-triangle-w", then it set the text of span to "<<".
$('a span.ui-icon-circle-triangle-w').text('<<');
I host it with my other js files on my own server, and, that's that point, combine and minify them (with django-compresser, here, but that's not the point) to be served as just one js file, with everything the site needs put into it. You'll need to serve your own js files anyway, so I see no reason to not add the extra jquery bytes there too - some more kbs are much more cheaper to transfer, than more requests to be made. You are not dependent to anyone, and as soon as your minified js is cached, you're super fast as well.
On first load, a CDN based solution might win, because you must load the additional jquery kilobytes from your own server (but, without an additional request). I doubt the difference is noticable, though. And then, on a first load with cleared cache, your own hosted solution will probably always be much faster, because of more requests (and DNS lookups) needed, to fetch the CDN jquery.
I wonder how this point is almost never mentioned, and how CDNs seem to take over the world :)
pop
is also useful to remove and keep an item from a list. Where del
actually trashes the item.
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
Best one
String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date);
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;
The appref-ms file does not point to the exe. When you hit that shortcut, it invokes the deployment manifest at the deployment provider url and checks for updates. It checks the application manifest (yourapp.exe.manifest) to see what files to download, and this file contains the definition of the entry point (i.e. the exe).
A div is a block element, and will span the width of the container unless a width is set. A span is an inline element, and will have the width of the text inside it. Currently, you are trying to set align as a CSS property. Align is an attribute.
<span align="center" style="border:1px solid red;">
This is some text in a div element!
</span>
However, the align attribute is deprecated. You should use the CSS text-align
property on the container.
<div style="text-align: center;">
<span style="border:1px solid red;">
This is some text in a div element!
</span>
</div>
In the code you posted, you're sending the setDownloadURL:
setter to ClassA
— that is, the class itself. You want to set the property of an instance.
Another way to do this would be to add before adding lines in your output, the following line :
output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))
The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.
You don't need to add the concat package, you can do this via cssmin like this:
cssmin : {
options: {
keepSpecialComments: 0
},
minify : {
expand : true,
cwd : '/library/css',
src : ['*.css', '!*.min.css'],
dest : '/library/css',
ext : '.min.css'
},
combine : {
files: {
'/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
}
}
}
And for js, use uglify like this:
uglify: {
my_target: {
files: {
'/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
}
}
}
Just wondering.. is that really possible in MySQL? it will delete t1 and t2? or I just misunderstood the question.
But if you just want to delete table1 with multiple join conditions, just don't alias the table you want to delete
this:
DELETE t1,t2
FROM table1 AS t1
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...
should be written like this to work in MSSQL:
DELETE table1
FROM table1
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...
to contrast how the other two common RDBMS do a delete operation:
http://mssql-to-postgresql.blogspot.com/2007/12/deleting-duplicates-in-postgresql-ms.html
You can do this:
DB::transaction(function() {
//
});
Everything inside the Closure executes within a transaction. If an exception occurs it will rollback automatically.
git reset HEAD <file>
for removing a particular file from the index.
and
git reset HEAD
for removing all indexed files.
The command uptime
gives you load averages for the past 1, 5, and 15 minutes.
There is also another straight and more clear way
git commit -m "Title" -m "Description ..........";
Here's the exact way sup uses:
.superscript{
vertical-align:super;
font-size:smaller;
}
Found this via google chrome inspect element.
Syntax for AngularJS v1.4.8 + (v1.5.0)
$http.post(url, data, config)
.then(
function (response) {
// success callback
},
function (response) {
// failure callback
}
);
Eg:
var url = "http://example.com";
var data = {
"param1": "value1",
"param2": "value2",
"param3": "value3"
};
var config = {
headers: {
'Content-Type': "application/json"
}
};
$http.post(url, data, config)
.then(
function (response) {
// success callback
},
function (response) {
// failure callback
}
);
I tried all the above solutions. but it didn't work.
The solution was to restart eclipse !!!!!!!
hope this will help someone :)
A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes of the resource held by the subscription.
import { interval } from 'rxjs';
const observable = interval(1000);
const subscription = observable.subscribe(a=> console.log(a));
/** This cancels the ongoing Observable execution which
was started by calling subscribe with an Observer.*/
subscription.unsubscribe();
A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions.
import { interval } from 'rxjs';
const observable1 = interval(400);
const observable2 = interval(300);
const subscription = observable1.subscribe(x => console.log('first: ' + x));
const childSubscription = observable2.subscribe(x => console.log('second: ' + x));
subscription.add(childSubscription);
setTimeout(() => {
// It unsubscribes BOTH subscription and childSubscription
subscription.unsubscribe();
}, 1000);
According to the official documentation, Angular should unsubscribe for you, but apparently, there is a bug.
Your print
is messing things up, because it resets @@ROWCOUNT
. Whenever you use @@ROWCOUNT
, my advice is to always set it immediately to a variable. So:
DECLARE @RC int;
WHILE @RC > 0 or @RC IS NULL
BEGIN
SET rowcount 5;
UPDATE TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123 AND Value <> 'abc1';
SET @RC = @@ROWCOUNT;
PRINT(@@ROWCOUNT)
END;
SET rowcount = 0;
And, another nice feature is that you don't need to repeat the update
code.
you declare your function as returning boolean, but it never returns anything.
You will get this error when you call any of the setXxx()
methods on PreparedStatement
, while the SQL query string does not have any placeholders ?
for this.
For example this is wrong:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
You need to fix the SQL query string accordingly to specify the placeholders.
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
Note the parameter index starts with 1
and that you do not need to quote those placeholders like so:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";
Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.
You can do it in a less than a minute with Google Drive (and free, no hassles)
• Bulk Upload all your images on imgur.com
• Copy the Links of all the images together, appended with .jpg. Only imgur lets you do copy all the image links together, do that using the image tab top right.
• Use http://TextMechanic.co to prepend and append each line with this:
Prefix : =image("
AND
Suffix : ", 1)
So that it looks like this =image("URL", 1)
• Copy All
• Paste it in Google Spreadsheet
• Voila!
References :
http://www.labnol.org/internet/images-in-google-spreadsheet/18167/
https://support.google.com/drive/bin/answer.py?hl=en&answer=87037&from=1068225&rd=1
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM
to obtain 2011?5?31?
. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat
. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date
nor a modern LocalDate
can have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.
Native methods are usually used to interface with system calls or libraries written in other programming languages.
If you want more datesource configs e.g.
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1
you could use below code
@Bean
public DataSource dataSource() {
DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
dataSource.setValidationQuery(validationQuery);
return dataSource;
}
refer: Spring boot jdbc Connection
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
I was able to figure it out. In case someone wants to know below the code that worked for me:
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);
Let me know if there is a simpler way o doing it.
I found I COULD use "if-then" statements in a lambda. For instance:
eval_op = {
'|' : lambda x,y: eval(y) if (eval(x)==0) else eval(x),
'&' : lambda x,y: 0 if (eval(x)==0) else eval(y),
'<' : lambda x,y: 1 if (eval(x)<eval(y)) else 0,
'>' : lambda x,y: 1 if (eval(x)>eval(y)) else 0,
}
Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)
I was having trouble coloring rows in table using bootstrap table-striped class then realized delete table-striped class and do this in css file
tr:nth-of-type(odd)
{
background-color: red;
}
tr:nth-of-type(even)
{
background-color: blue;
}
The bootstrap table-striped class will over ride your selectors.
I think you want to MODIFY
the column as described for the ALTER TABLE
command. It might be something like this:
ALTER TABLE users MODIFY id INTEGER NOT NULL AUTO_INCREMENT;
Before running above ensure that id
column has a Primary index.
I have simply replaced the "\n
" with "<br>
" tag. Worked fine. It seems TCPDF render the text as HTML
$strText = str_replace("\n","<br>",$strText);
$pdf->MultiCell($width, $height,$strText, 0, 'J', 0, 1, '', '', true, null, true);
sort file | sponge file
This is in the following Fedora package:
moreutils : Additional unix utilities
Repo : fedora
Matched from:
Filename : /usr/bin/sponge
round
does take negative ndigits
parameter!
>>> round(46,-1)
50
may solve your case.
The below are the typical situation where we shall get ERR_FILE_NOT_FOUND even file avail in respective folder.
Code:
@font-face {
font-family: Eau_Sans_Bold;
src: url("/fonts/eau_sans_bold.otf") format("opentype");
}
Error:
GET file:///C:/fonts/eau_sans_bold.otf net::ERR_FILE_NOT_FOUND
Answer or Solution.:
@font-face {
font-family: Eau_Sans_Book;
src: url("../fonts/eau_sans_book.otf") format("opentype");
}
Basically browser not able to pick if we metion just /font/. We should to mention ../fonts/ This will work. So, we wont get ERR_FILE_NOT_FOUND.
You can use Mockito.isA()
for that:
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;
verify(bar).doStuff(isA(Foo[].class));
http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)
For those not sure about which peak-finding algorithms to use in Python, here a rapid overview of the alternatives: https://github.com/MonsieurV/py-findpeaks
Wanting myself an equivalent to the MatLab findpeaks
function, I've found that the detect_peaks function from Marcos Duarte is a good catch.
Pretty easy to use:
import numpy as np
from vector import vector, plot_peaks
from libs import detect_peaks
print('Detect peaks with minimum height and distance filters.')
indexes = detect_peaks.detect_peaks(vector, mph=7, mpd=2)
print('Peaks are: %s' % (indexes))
Which will give you:
If you don't have any error messages and don't know what the problem is - why PowerShell scripts don't want to start from a Scheduled Task do the following steps to get the answer:
You should be able to see all error notifications.
In case of one of my script it was:
"Unable to find type [System.ServiceProcess.ServiceController]. Make sure that the assembly that contains this type is loaded."
And in this case I have to add additional line at the begining of the script to load the missing assembly:
Add-Type -AssemblyName "System.ServiceProcess"
And next errors:
Exception calling "GetServices" with "1" argument(s): "Cannot open Service Control Manager on computer ''. This operation might require other privileges."
select : The property cannot be processed because the property "Database Name" already exists
You need to remove the /
before the [
. Predicates (the parts in [
]
) shouldn't have slashes immediately before them. Also, to select the Employee element itself, you should leave off the /text()
at the end or otherwise you'd just be selecting the whitespace text values immediately under the Employee element.
//Employee[@id='4']
Edit: As Jens points out in the comments, //
can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with is going to be consistent, you are probably best off using a full path, for example:
/Employees/Employee[@id='4']
You can do this using NSAttributedString
Example:
let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue]
let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine", attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString
EDIT
To have the same attributes for all texts of one UILabel, I suggest you to subclass UILabel and overriding text, like that:
Swift 5
Same as Swift 4.2 but: You should prefer the Swift initializer NSRange
over the old NSMakeRange
, you can shorten to .underlineStyle
and linebreaks improve readibility for long method calls.
class UnderlinedLabel: UILabel {
override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSRange(location: 0, length: text.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}
Swift 4.2
class UnderlinedLabel: UILabel {
override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSMakeRange(0, text.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSAttributedString.Key.underlineStyle , value: NSUnderlineStyle.single.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}
Swift 3.0
class UnderlinedLabel: UILabel {
override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSMakeRange(0, text.characters.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}
And you put your text like this :
@IBOutlet weak var label: UnderlinedLabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = "StringWithUnderLine"
}
OLD:
Swift (2.0 to 2.3):
class UnderlinedLabel: UILabel {
override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSMakeRange(0, text.characters.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}
Swift 1.2:
class UnderlinedLabel: UILabel {
override var text: String! {
didSet {
let textRange = NSMakeRange(0, count(text))
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}
Click the mse7.exe
installed along with Office typically at \Program Files\Microsoft Office\OFFICE11
.
This will open up the debugger, open the file and then run the debugger in the GUI mode.
When I run your code, I get the following output for example.
<usb.Device object at 0xef38c0>
Device: 001
idVendor: 7531 (0x1d6b)
idProduct: 1 (0x0001)
Manufacturer: 3
Serial: 1
Product: 2
Noteworthy are that a) I have usb.Device
objects whereas you have usb.legacy.Device
objects, and b) I have device filenames.
Each usb.Bus
has a dirname
field and each usb.Device
has the filename. As you can see, the filename is something like 001
, and so is the dirname. You can combine these to get the bus file. For dirname=001
and filname=001
, it should be something like /dev/bus/usb/001/001.
You should first, though figure out what this "usb.legacy" situation is. I'm running the latest version and I don't even have a legacy
sub-module.
Finally, you should use the idVendor
and idProduct
fields to uniquely identify the device when it's plugged in.
int[] b = new int[a.length +1];
System.arraycopy(a,0,b,0,4);
//System.arraycopy(srcArray, srcPosition, destnArray, destnPosition, length)
b[4]=87;
System.arraycopy(a,4,b,5,2);
b array would be created as {1, 2, 3, 4, 87, 5,6};
Specifically, I want to mention one situation, by which you may confuse.
What is the difference between "\0" and ""?
The answer is that "\0"
represents in array is {0 0}
and ""
is {0}
.
Because "\0"
is still a string literal and it will also add "\0"
at the end of it. And ""
is empty but also add "\0"
.
Understanding of this will help you understand "\0"
deeply.
You can use:
$("#tagscloud span").text("Your text here");
The same code will also work for the second case. You could also use:
$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");
A more memory efficient way to iterate over a slice of a list would be to use islice()
from the itertools
module:
from itertools import islice
listOfStuff = (['a','b'], ['c','d'], ['e','f'], ['g','h'])
for item in islice(listOfStuff, 1, 3):
print item
# ['c', 'd']
# ['e', 'f']
However, this can be relatively inefficient in terms of performance if the start value of the range is a large value sinceislice
would have to iterate over the first start value-1 items before returning items.
I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
I got an error. But if I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
everything was OK.
Yes you need javascript. The simplest way is to just put this at the bottom of your HTML page:
<script type="text/javascript">
alert("Hello world");
</script>
There are more preferred methods, like using jQuery's ready function, but this method will work.
var server = app.listen();
server.setTimeout(500000);
inspired by https://github.com/expressjs/express/issues/3330
or
app.use(function(req, res, next){
res.setTimeout(500000, function(){
// call back function is called when request timed out.
});
next();
});
Use this:
style="height: 150px; max-height: 300px; overflow: auto;"
fixe a height, it will be the default height and then a scroll bar come to access to the entire height
As mentioned already, the contents are stored at the server. However the session is identified by a session-id, which is stored at the client and send with each request. Usually the session-id is stored in a cookie, but it can also be appended to urls. (That's the PHPSESSID
query-parameter you some times see)
Interesting that Firefox will stop further processing of JavaScript after the relocate function. Chrome and IE will continue to display any other alerts and then reload the page. Try it:
<script type="text/javascript">
alert('foo');
window.location.reload(true);
alert('bar');
window.location.reload(true);
alert('foobar');
window.location.reload(true);
</script>
The core team responsible for Postgres is gradually phasing out OIDs.
The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:
CREATE TABLE … WITH OIDS
commanddefault_with_oids (boolean)
compatibility settingThe data type OID
remains in Postgres 12. You can explicitly create a column of the type OID
.
After migrating to Postgres 12, any optionally-defined system column oid
will no longer be invisible by default. Performing a SELECT *
will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.
Use android:gravity="center"
in TextView
instead of layout_gravity
.
Since you are using angularFire, it doesn't make any sense if you are going back to default firebase methods for your implementation. AngularFire itself has the proper mechanisms implemented. Just have to use it.
valueChanges()
method of angularFire provides an overload for getting the ID of each document of the collection by simply adding a object as a parameter to the method.
valueChanges({ idField: 'id' })
Here 'idField' must be same as it is. 'id' can be anything that you want your document IDs to be called.
Then the each document object on the returned array will look like this.
{
field1 = <field1 value>,
field2 = <field2 value>,
..
id = 'whatEverTheDocumentIdWas'
}
Then you can easily get the document ID by referencing to the field that you named.
AngularFire 5.2.0
I've implemented and tested this one; it should cover most bases:
public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
int size = list.size();
if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
return Collections.emptyList();
}
fromIndex = Math.max(0, fromIndex);
toIndex = Math.min(size, toIndex);
return list.subList(fromIndex, toIndex);
}
You can use find
find . -type d > output.txt
or tree
tree -d > output.txt
tree
, If not installed on your system.
If you are using ubuntu
sudo apt-get install tree
If you are using mac os
.
brew install tree
Just to be really clear, this has nothing to do with enumerate
and everything to do with list comprehension syntax.
This list comprehension returns a list of tuples:
[(i,j) for i in range(3) for j in 'abc']
this a list of dicts:
[{i:j} for i in range(3) for j in 'abc']
a list of lists:
[[i,j] for i in range(3) for j in 'abc']
a syntax error:
[i,j for i in range(3) for j in 'abc']
Which is inconsistent (IMHO) and confusing with dictionary comprehensions syntax:
>>> {i:j for i,j in enumerate('abcdef')}
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}
And a set of tuples:
>>> {(i,j) for i,j in enumerate('abcdef')}
set([(0, 'a'), (4, 'e'), (1, 'b'), (2, 'c'), (5, 'f'), (3, 'd')])
As Óscar López stated, you can just pass the enumerate tuple directly:
>>> [t for t in enumerate('abcdef') ]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]
The guarantees the standard gives you go like this:
1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)
So it's perfectly valid for sizeof (int)
and sizeof (long)
to be equal, and many platforms choose to go with this approach. You will find some platforms where int
is 32 bits, long
is 64 bits, and long long
is 128 bits, but it seems very common for sizeof (long)
to be 4.
(Note that long long
is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.)