The string is a .NET string so you can use .NET methods. In your case:
$index = "The string".IndexOf(" ")
will return 3, which is the first occurrence of space in the string. For more information see: http://msdn.microsoft.com/en-us/library/system.string.aspx
For your need try something like:
$s.SubString($s.IndexOf("_") + 1, $s.LastIndexOf(".") - $s.IndexOf("_") - 1)
Or you could use regexps:
if ($s -Match '(_)(.*)(\.)[^.]*$') { $matches[2] }
(has to be adjusted depending on exactly what you need).
If you've already displayed the element on the page previously, you can simply take the height directly from the DOM element (reachable in jQuery with .get(0)), since it is set even when the element is hidden:
$('.hidden-element').get(0).height;
same for the width:
$('.hidden-element').get(0).width;
(thanks to Skeets O'Reilly for correction)
Take a look at this example: MDN Element.scrollHeight
I recommend that check out this example: stackoverflow.com/a/24815216... which implements a cross-browser handling for the scroll action.
You may use the following snippet:
//attaches the "scroll" event
$(window).scroll(function (e) {
var target = e.currentTarget,
scrollTop = target.scrollTop || window.pageYOffset,
scrollHeight = target.scrollHeight || document.body.scrollHeight;
if (scrollHeight - scrollTop === $(target).innerHeight()) {
console.log("? End of scroll");
}
});
If like me you have seen this message while trying to add 'www' as a subdomain inorder to get your own domain working:
'Already used, please remove previous mapping first . '
The above process mentioned in other answers has changed slightly if you are using Google Apps for your domain.
You must now do this as well:
Google Apps -> Service Settings -> Sites. Click 'Web address mapping' and remove the 'www' mapping which has been added by default to Sites.
Then you can add the 'www' subdomain for your App engine app
see this link:
http://groups.google.com/group/google-appengine/web/deleting-existing-www-mapping-from-google-apps
The proper way to do this is like this:
LIBS += -L/path/to -lpsapi
This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.
In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_
variable, e.g.:
LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi
Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.
Operations on integers are exact. double
is a floating point data type, and floating point operations are approximate whenever there's a fraction.
double
also takes up twice as much space as int
in many implementations (e.g. most 32-bit systems) .
Use File
's getParentFile()
method and String.lastIndexOf()
to retrieve just the immediate parent directory.
Mark's comment is a better solution thanlastIndexOf()
:
file.getParentFile().getName();
These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent File
). When getParentFile()
is null you'll need to resort to using lastIndexOf
, or use something like Apache Commons' FileNameUtils.getFullPath()
:
FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd
There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils
class to grab the name from the result, use lastIndexOf
, etc.
Unfortunately SQL Server interprets the quoted comma as a delimiter. This applies to both BCP and bulk insert .
From http://msdn.microsoft.com/en-us/library/ms191485%28v=sql.100%29.aspx
If a terminator character occurs within the data, it is interpreted as a terminator, not as data, and the data after that character is interpreted as belonging to the next field or record. Therefore, choose your terminators carefully to make sure that they never appear in your data.
I just received the same error. I had a % in the destination path that needed to be escaped
c:\projects\%NotAnEnvironmentVariable%
needed to be
c:\projects\%%NotAnEnvironmentVariable%%
SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
MAX([Value])
FOR [Period] IN ([2000], [2001], [2002])
) as pvt
Another way,
SELECT ACCOUNT,
MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account
Maybe you can use arrow function (ES6+) or the simple old function declaration.
Normal function declaration type (Not ES6+):
<link href="#" onClick={function(event){ func1(event); func2();}}>Trigger here</link>
Anonymous function or arrow function type (ES6+)
<link href="#" onClick={(event) => { func1(event); func2();}}>Trigger here</link>
The second one is the shortest road that I know. Hope it helps you!
CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)
If you are looking for content from different domain this will do the trick:
$.ajax({
url:'http://www.corsproxy.com/' +
'en.wikipedia.org/wiki/Briarcliff_Manor,_New_York',
type:'GET',
success: function(data){
$('#content').html($(data).find('#firstHeading').html());
}
});
It's possible to view proxy settings in Google Chrome:
chrome://net-internals/#proxy
Enter this in the address bar of Chrome.
You want:
grep -A 5 '19:55' file
From man grep
:
Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a gup separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.
With the -o or --only-matching option, this has no effect and a warning
is given.
--group-separator=SEP
Use SEP as a group separator. By default SEP is double hyphen (--).
--no-group-separator
Use empty string as a group separator.
I would defiantly give BlackFire a try.
There is this virtualBox I've put together using puphpet, to test different php frameworks which coms with BlackFire, please feel free to fork and/or distribute if required :)
Use a static method when you want to be able to access the method without an instance of the class.
You can use if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
method to detect whether never ask is checked or not.
For more reference : Check this
To check for multiple permissions use:
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
showDialogOK("Service Permissions are required for this app",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
finish();
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
// //proceed with logic by disabling the related features or quit the app.
}
explain() method
private void explain(String msg){
final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
dialog.setMessage(msg)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// permissionsclass.requestPermission(type,code);
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:com.exampledemo.parsaniahardik.marshmallowpermission")));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}
Above code will also show dialog, which will redirect user to app settings screen from where he can give permission if had checked never ask again button.
I have faced to the same problem, i deleted the constraint for the column in question and it worked for me. You can check the folder Constraints.
Capture :
Use glob. There are comprehensive guide how to open all files from dir: PHP: Using functional programming for listing files and directories
For example, you want to sync table todoTable
from MySql
to Sqlite
First, create one column name version (type INT)
in todoTable
for both Sqlite
and MySql
Second, create a table name database_version
with one column name currentVersion(INT)
In MySql
, when you add a new item to todoTable
or update item, you must upgrade the version of this item by +1 and also upgrade the currentVersion
In Android
, when you want to sync (by manual press sync button or a service run with period time):
You will send the request with the Sqlite
currentVersion (currently it is 1) to server.
Then in server, you find what item in MySql
have version value greater than Sqlite
currentVersion(1) then response to Android (in this example the item 3 with version 2 will response to Android)
In SQLite
, you will add or update new item to todoTable
and upgrade the currentVersion
First import Corelocation and MapKit library:
import MapKit
import CoreLocation
inherit from CLLocationManagerDelegate to our class
class ViewController: UIViewController, CLLocationManagerDelegate
create a locationManager variable, this will be your location data
var locationManager = CLLocationManager()
create a function to get the location info, be specific this exact syntax works:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
in your function create a constant for users current location
let userLocation:CLLocation = locations[0] as CLLocation // note that locations is same as the one in the function declaration
stop updating location, this prevents your device from constantly changing the Window to center your location while moving (you can omit this if you want it to function otherwise)
manager.stopUpdatingLocation()
get users coordinate from userLocatin you just defined:
let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
define how zoomed you want your map be:
let span = MKCoordinateSpanMake(0.2,0.2)
combine this two to get region:
let region = MKCoordinateRegion(center: coordinations, span: span)//this basically tells your map where to look and where from what distance
now set the region and choose if you want it to go there with animation or not
mapView.setRegion(region, animated: true)
close your function
}
from your button or another way you want to set the locationManagerDeleget to self
now allow the location to be shown
designate accuracy
locationManager.desiredAccuracy = kCLLocationAccuracyBest
authorize:
locationManager.requestWhenInUseAuthorization()
to be able to authorize location service you need to add this two lines to your plist
get location:
locationManager.startUpdatingLocation()
show it to the user:
mapView.showsUserLocation = true
This is my complete code:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func locateMe(sender: UIBarButtonItem) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.2,0.2)
let region = MKCoordinateRegion(center: coordinations, span: span)
mapView.setRegion(region, animated: true)
}
}
I am not writing anything same here. Just a changelog note from PHP manual.
Changelog for continue
Version Description
7.0.0 - continue outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.
5.4.0 continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.
Changelog for break
Version Description
7.0.0 break outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.
5.4.0 break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.
Try storing the connection string along with the password in a variable and assign the variable in the connection string using expression.I also faced the same issue and I solved like dis.
In my case, I had (relatively) long vm arguments configured. Converting these arguments (whenever possible) to environment variables fixed the issue for me
As @kgrad says, /* */ does not nest and can cause errors. A better answer is:
// LINE *of code* I WANT COMMENTED
// LINE *of code* I WANT COMMENTED
// LINE *of code* I WANT COMMENTED
Most IDEs have a single keyboard command for doing/undoing this, so there's really no reason to use the other style any more. For example: in eclipse, select the block of text and hit Ctrl+/
To undo that type of comment, use Ctrl+\
UPDATE: The Sun coding convention says that this style should not be used for block text comments:
// Using the slash-slash
// style of comment as shown
// in this paragraph of non-code text is
// against the coding convention.
but // can be used 3 other ways:
Such type of encoding are usually part of numpy array. If you are using a numpy array like this :
a = np.array([1,0,3])
then there is very simple way to convert that to 1-hot encoding
out = (np.arange(4) == a[:,None]).astype(np.float32)
That's it.
I think your best shot is a border-left
property that is assigned to each one of the li
s except the first one (You would have to give the first one a class named first
and explicitly remove the border for that).
Even if you are generating the <li>
programmatically, assigning a first
class should be easy.
After trying almost everything on this thread and others, continuing to Google, the only thing that worked for me, in the end, was to start Visual Studio as my AD user via command line:
cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE
runas /netonly /user:<comp\name.surname> devenv.exe
Original issue: [1]: https://developercommunity.visualstudio.com/content/problem/304224/git-failed-with-a-fatal-errorauthentication-failed.html
My situation is I'm on a personal machine connecting to a company's internal/local devops server (not cloud-based) that uses AD authorization. I had no issue with TFS, but with git could not get the clone to work (Git failed with a fatal error. Authentication failed for [url]) until I did that.
If you want to script all table rows then Go with Generate Scripts as described by Daniel Vassallo. You can’t go wrong here
Else Use third party tools such as ApexSQL Script or SSMS Toolpack for more advanced scripting that includes some preprocessing, selective scripting and more.
Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.
Just find the element and then enumerate the options, selecting the option(s) you want.
Here is an example:
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
You can read more in:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver
I stumbled across this question while looking for a way to filter certain elements out of a stream and log them as errors. So I did not really need to split the stream so much as attach a premature terminating action to a predicate with unobtrusive syntax. This is what I came up with:
public class MyProcess {
/* Return a Predicate that performs a bail-out action on non-matching items. */
private static <T> Predicate<T> withAltAction(Predicate<T> pred, Consumer<T> altAction) {
return x -> {
if (pred.test(x)) {
return true;
}
altAction.accept(x);
return false;
};
/* Example usage in non-trivial pipeline */
public void processItems(Stream<Item> stream) {
stream.filter(Objects::nonNull)
.peek(this::logItem)
.map(Item::getSubItems)
.filter(withAltAction(SubItem::isValid,
i -> logError(i, "Invalid")))
.peek(this::logSubItem)
.filter(withAltAction(i -> i.size() > 10,
i -> logError(i, "Too large")))
.map(SubItem::toDisplayItem)
.forEach(this::display);
}
}
In Eclipse do the following:
GIT Repositories > Remotes > Origin > Right click and say fetch
GIT Repositories > Remote Tracking > Select your branch and say merge
Go to project, right click on your file and say Fetch from upstream.
Add this before calling dialog
$( obiect ).css('zIndex',9999);
And remove
zIndex: 700,
from dialog
I've always used it on the command line and not as a library, but HTMLDOC gives me excellent results, and it handles at least some CSS (I couldn't easily see how much).
Here's a sample command line
htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf
we can use createNativeQuery("Here Nagitive SQL Query ");
for Example :
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();
You can give the surrounding div
a
text-align: right
this will leave white space to the left of the image. (= the image will occupy the whole line).
If you want content to be shown to the left hand side of the image, use
float: right
on the image. However, the surrounding div
will then need overflow: auto
to stretch to the needed height.
The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system. Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). GAC is a machine wide a local cache of assemblies maintained by the .NET Framework.
I think the problem is the realpath of the file. For example your script is working on './', your file is inside the directory './xml'. So better check if the file exists or not, before you get filemtime or unlink it:
function deleteOldFiles(){
if ($handle = opendir('./xml')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/^.*\.(xml|xsl)$/i", $file)){
$fpath = 'xml/'.$file;
if (file_exists($fpath)) {
$filelastmodified = filemtime($fpath);
if ( (time() - $filelastmodified ) > 24*3600){
unlink($fpath);
}
}
}
}
closedir($handle);
}
}
To make the edited value of path persists in the next sessions
cd ~/
touch .bash_profile
open .bash_profile
That will open the .bash_profile in editor, write inside the following after adding what you want to the path separating each value by column.
export PATH=$PATH:/usr/local/git/bin:/usr/local/bin:
Save, exit, restart your terminal and enjoy
If you use sass in your own project, you can override the default bootstrap gutter size by copy pasting the sass variables from bootstrap's _variables.scss file into your own projects sass file somewhere, like:
// Grid columns
//
// Set the number of columns and specify the width of the gutters.
$grid-gutter-width-base: 50px !default;
$grid-gutter-widths: (
xs: $grid-gutter-width-base,
sm: $grid-gutter-width-base,
md: $grid-gutter-width-base,
lg: $grid-gutter-width-base,
xl: $grid-gutter-width-base
) !default;
Now your gutters will be 50px instead of 30px. I find this to be the cleanest method to adjust the gutter size.
If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.
The innerHtml property did not work for me. So I experimented with ...
<div id=successAndErrorMessages-1>100% OK</div>
<div id=successAndErrorMessages-2>This is an error mssg!</div>
and toggled one of the two on/off ...
$("#successAndErrorMessages-1").css('display', 'none')
$("#successAndErrorMessages-2").css('display', '')
For some reason I had to fiddle around with the ordering before it worked in all types of browsers.
jvmtop can show the current jvm thread count beside other metrics.
The solution marked as correct didn't work for me, but I found this answer that worked just great: Get list of duplicate rows in MySql
SELECT n1.*
FROM myTable n1
INNER JOIN myTable n2
ON n2.repeatedCol = n1.repeatedCol
WHERE n1.id <> n2.id
I'm using XAMPP 1.6.7 on Windows 7. This article worked for me.
I added the following lines in the file httpd-vhosts.conf
at C:/xampp/apache/conf/extra
.
I had also uncommented the line # NameVirtualHost *:80
<VirtualHost mysite.dev:80>
DocumentRoot "C:/xampp/htdocs/mysite"
ServerName mysite.dev
ServerAlias mysite.dev
<Directory "C:/xampp/htdocs/mysite">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
After restarting the apache, it were still not working.
Then I had to follow the step 9 mentioned in the article by editing the file C:/Windows/System32/drivers/etc/hosts
.
# localhost name resolution is handled within DNS itself.
127.0.0.1 localhost
::1 localhost
127.0.0.1 mysite.dev
Then I got working http://mysite.dev
I found a combination of these answers gave me the best outcome - allowing me to still position the tooltip and attach it to the relevant container:
$('body').on('mouseenter', '[rel=tooltip]', function(){
var el = $(this);
if (el.data('tooltip') === undefined) {
el.tooltip({
placement: el.data("placement") || "top",
container: el.data("container") || false
});
}
el.tooltip('show');
});
$('body').on('mouseleave', '[rel=tooltip]', function(){
$(this).tooltip('hide');
});
Relevant HTML:
<button rel="tooltip" class="btn" data-placement="bottom" data-container=".some-parent" title="Show Tooltip">
<i class="icon-some-icon"></i>
</button>
UPDATE: https://requests.readthedocs.io/en/master/user/advanced/#timeouts
In new version of requests
:
If you specify a single value for the timeout, like this:
r = requests.get('https://github.com', timeout=5)
The timeout value will be applied to both the connect
and the read
timeouts. Specify a tuple if you would like to set the values separately:
r = requests.get('https://github.com', timeout=(3.05, 27))
If the remote server is very slow, you can tell Requests to wait forever for a response, by passing None as a timeout value and then retrieving a cup of coffee.
r = requests.get('https://github.com', timeout=None)
My old (probably outdated) answer (which was posted long time ago):
There are other ways to overcome this problem:
1. Use the TimeoutSauce
internal class
From: https://github.com/kennethreitz/requests/issues/1928#issuecomment-35811896
import requests from requests.adapters import TimeoutSauce class MyTimeout(TimeoutSauce): def __init__(self, *args, **kwargs): connect = kwargs.get('connect', 5) read = kwargs.get('read', connect) super(MyTimeout, self).__init__(connect=connect, read=read) requests.adapters.TimeoutSauce = MyTimeout
This code should cause us to set the read timeout as equal to the connect timeout, which is the timeout value you pass on your Session.get() call. (Note that I haven't actually tested this code, so it may need some quick debugging, I just wrote it straight into the GitHub window.)
2. Use a fork of requests from kevinburke: https://github.com/kevinburke/requests/tree/connect-timeout
From its documentation: https://github.com/kevinburke/requests/blob/connect-timeout/docs/user/advanced.rst
If you specify a single value for the timeout, like this:
r = requests.get('https://github.com', timeout=5)
The timeout value will be applied to both the connect and the read timeouts. Specify a tuple if you would like to set the values separately:
r = requests.get('https://github.com', timeout=(3.05, 27))
kevinburke has requested it to be merged into the main requests project, but it hasn't been accepted yet.
you can do this---
<input type="button" onClic="changebackColor">
function changebackColor(){
document.body.style.backgroundColor = "black";
document.getElementByID("divID").style.backgroundColor = "black";
window.setTimeout("yourFunction()",10000);
}
With flexbox this is easy:
Just add the following to the image container:
.img-container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex; /* add */
justify-content: center; /* add to align horizontal */
align-items: center; /* add to align vertical */
}
I find that nameof
increases the readability of very long and complex SQL statements in my applications. It makes the variables stand out of that sea of strings and eliminates your job of figuring out where the variables are used in your SQL statements.
public bool IsFooAFoo(string foo, string bar)
{
var aVeryLongAndComplexQuery = $@"SELECT yada, yada
-- long query in here
WHERE fooColumn = @{nameof(foo)}
AND barColumn = @{nameof(bar)}
-- long query here";
SqlParameter[] parameters = {
new SqlParameter(nameof(foo), SqlDBType.VarChar, 10){ Value = foo },
new SqlParameter(nameof(bar), SqlDBType.VarChar, 10){ Value = bar },
}
}
Alternatively you can do the following:
Tables.ToList<string>().Count;
<!DOCTYPE html>
<html>
<head>
<title>set caret position</title>
<script type="application/javascript">
//<![CDATA[
window.onload = function ()
{
setCaret(document.getElementById('input1'), 13, 13)
}
function setCaret(el, st, end)
{
if (el.setSelectionRange)
{
el.focus();
el.setSelectionRange(st, end);
}
else
{
if (el.createTextRange)
{
range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', st);
range.select();
}
}
}
//]]>
</script>
</head>
<body>
<textarea id="input1" name="input1" rows="10" cols="30">Happy kittens dancing</textarea>
<p> </p>
</body>
</html>
Just use look-arounds to solve this:
(?<=^|,)garp(?=$|,)
The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.
REST is stateless and doesn’t maintain any states between the requests. Client cookies / headers are set to maintain the user state like authentication. Say Client username/password are validated by third part authentication mechanism – 2nd level OTP gerneation etc. Once user get authenticated – headers /cookies comes to rest service end point exposed and we can assume user as auth since user is coming with valid headers/cookies. Now certain info of user like IP is either maintained in the cache and after that if request is coming from same Ip (mac address) for listed resources User is allowed. And cache is maintained for some particular time which get invalidated once time lapses. So either cache can be used or DB entries can be used to persist info b/w the requests.
Alternatively, you could do the following:
Dictionary<FunkyAttributesEnum, string> description = new Dictionary<FunkyAttributesEnum, string>()
{
{ FunkyAttributesEnum.NameWithoutSpaces1, "Name With Spaces1" },
{ FunkyAttributesEnum.NameWithoutSpaces2, "Name With Spaces2" },
};
And get the description with the following:
string s = description[FunkyAttributesEnum.NameWithoutSpaces1];
In my opinion this is a more efficient way of doing what you want to accomplish, as no reflection is needed..
Quoting from nt.bas answer:
If you are using the newest version of Android Studio, you can let it assist you in this.
Note: I have tested this in Android Studio 3.0 only.
The procedure is as follows:
In the project view (this comes along with captures and structure on the left side of screen), select Project instead of Android.
The name of your project will be the top of the tree (alongside external libraries).
Select your project then go to Refactor -> Copy...
.
Android Studio will ask you the new name and where you want to copy the project. Provide the same.
After the copying is done, open your new project in Android Studio.
Packages will still be under the old project name.
That is the Java classes packages, application ID and everything else that was generated using the old package name.
We need to change that.
In the project view, select Android.
Open the java sub-directory and select the main package.
Then right click on it and go to Refactor
then Rename
.
Android Studio will give you a warning saying that multiple directories correspond to the package you are about to refactor.
Click on Rename package
and not Rename directory
.
After this step, your project is now completely under the new name.
Build -> Clean project
then Build -> Rebuild project
. Up to this point you only rename your whole project name. To rename packaging name you need to follow gnyrfta answer which was described as:
When refactoring the package name in Android Studio, you may need to click the little cogwheel up to the right by the package/android/project/etc - navigator and uncheck 'compact empty middle packages' in order to see each part of the package name as an own directory. Then for individual directories do refactor.
PS: If you're having an
Failed to finalize session : INSTALL_FAILED_INVALID_APK: Split lib_slice_0_apk was defined multiple times
Just delete build folder of appmodule and Rebuild the project!
This will fix the issue!
:hover
is a pseudoclass, so you can put your CSS declarations there:
a:hover {
color: #f00;
}
You can also use a list of selectors to apply CSS declarations to a hovered element or an element with a certain class:
.some-class,
a:hover {
color: #f00;
}
try this....
USE DATABASE
GO
DECLARE @tname VARCHAR(150)
DECLARE @strsql VARCHAR(300)
SELECT @tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' and [name] like N'TableName%' ORDER BY [name])
WHILE @tname IS NOT NULL
BEGIN
SELECT @strsql = 'DROP TABLE [dbo].[' + RTRIM(@tname) +']'
EXEC (@strsql)
PRINT 'Dropped Table : ' + @tname
SELECT @tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' AND [name] like N'TableName%' AND [name] > @tname ORDER BY [name])
END
Its working for me...
from selenium import webdriver
PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=http://%s' % PROXY)
chrome = webdriver.Chrome(chrome_options=chrome_options)
chrome.get("http://whatismyipaddress.com")
I find it very useful to append both stdout and stderr to a log file. I was glad to see a solution by alfonx with exec > >(tee -a)
, because I was wondering how to accomplish this using exec
. I came across a creative solution using here-doc syntax and .
: https://unix.stackexchange.com/questions/80707/how-to-output-text-to-both-screen-and-file-inside-a-shell-script
I discovered that in zsh, the here-doc solution can be modified using the "multios" construct to copy output to both stdout/stderr and the log file:
#!/bin/zsh
LOG=$0.log
# 8 is an arbitrary number;
# multiple redirects for the same file descriptor
# triggers "multios"
. 8<<\EOF /dev/fd/8 2>&2 >&1 2>>$LOG >>$LOG
# some commands
date >&2
set -x
echo hi
echo bye
EOF
echo not logged
It is not as readable as the exec
solution but it has the advantage of allowing you to log just part of the script. Of course, if you omit the EOF then the whole script is executed with logging. I'm not sure how zsh
implements multios, but it may have less overhead than tee
. Unfortunately it seems that one cannot use multios with exec
.
Here are some tips on working with float and decimals.
0.1 x 10 = 1. Seems reasonable, but at computer level you as developer should handle that:
At any programming language (this was tested with Delphi, VBScript, Visual Basic, JavaScript and now with Java/Android):
double total = 0.0;
// do 10 adds of 10 cents
for (int i = 0; i < 10; i++) {
total += 0.1; // adds 10 cents
}
Log.d("round problems?", "current total: " + total);
// looks like total equals to 1.0, don't?
// now, do reverse
for (int i = 0; i < 10; i++) {
total -= 0.1; // removes 10 cents
}
// looks like total equals to 0.0, don't?
Log.d("round problems?", "current total: " + total);
if (total == 0.0) {
Log.d("round problems?", "is total equal to ZERO? YES, of course!!");
} else {
Log.d("round problems?", "is total equal to ZERO? No...");
// so be careful comparing equality in this cases!!!
}
OUTPUT:
round problems?: current total: 0.9999999999999999
round problems?: current total: 2.7755575615628914E-17
round problems?: is total equal to ZERO? No...
You can still access the class, through className
(which returns a String
).
There are actually several ways to get the class, for example classForArchiver
, classForCoder
, classForKeyedArchiver
(all return AnyClass!
).
You can't get the type of a primitive (a primitive is not a class).
Example:
var ivar = [:]
ivar.className // __NSDictionaryI
var i = 1
i.className // error: 'Int' does not have a member named 'className'
If you want to get the type of a primitive, you have to use bridgeToObjectiveC()
. Example:
var i = 1
i.bridgeToObjectiveC().className // __NSCFNumber
When neither sudo nor apt-get is available in container, you can also jump into running container as root user using command
docker exec -u root -t -i container_id /bin/bash
The correct answer to that is the method lists
, it's very simple like this:
$test=test::select('id')->where('id' ,'>' ,0)->lists('id');
Regards!
This error (and also ORA-6413: Connection not open) can also be caused by parentheses in the application executable path and a bug in the 10.2.0.1 or lower oracle client libraries.
You should either upgrade your oracle client library or change the executable path.
Further details see:
Some answers seem to be a little misleading.
.cpp
file for initializing since it can be done in the same Header file.Also, you can even initialize a static object in the same class scope just like a normal variable using the inline
keyword.
Initialize with no values in the same file
#include <string>
class A
{
static std::string str;
static int x;
};
std::string A::str;
int A::x;
Initialize with values in the same file
#include <string>
class A
{
static std::string str;
static int x;
};
std::string A::str = "SO!";
int A::x = 900;
Initialize in the same class scope using the inline
keyword
#include <string>
class A
{
static inline std::string str = "SO!";
static inline int x = 900;
};
gitCloneAllBranches() { # clone all git branches at once easily and cd in
# clone as "bare repo"
git clone --mirror $1
# rename without .git extension
with_extension=$(basename $1)
without_extension=$(echo $with_extension | sed 's/.git//')
mv $with_extension $without_extension
cd $without_extension
# change from "bare repository" to not
git config --bool core.bare false
# check if still bare repository if so
if [[ $(git rev-parse --is-bare-repository) == false ]]; then
echo "ready to go"
else
echo "WARNING: STILL BARE GIT REPOSITORY"
fi
# EXAMPLES:
# gitCloneAllBranches https://github.com/something/something.git
}
If you want to see the full paths, I would recommend to cd
to the top directory (of your drive if using windows)
cd C:\
grep -r somethingtosearch C:\Users\Ozzesh\temp
Or on Linux:
cd /
grep -r somethingtosearch ~/temp
if you really resist on your file name filtering (*.log) AND you want recursive
(files are not all in the same directory), combining find
and grep
is the most flexible way:
cd /
find ~/temp -iname '*.log' -type f -exec grep somethingtosearch '{}' \;
onclick
may not be the best event to attach that action to. Anytime anyone clicks anywhere in the form, it will open the window.
<form action="..." ...
onsubmit="window.open('google.html', '_blank', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');return true;">
// set
$_SESSION['test'] = 1;
// destroy
unset($_SESSION['test']);
I was having the same issue and was searching for a possible idea to solve this.
I had some CSS already in place for my tabs and this is what worked for me:
(Note specifically the padding-bottom: 2px;
inside #tabs #selected a {
. That hides the bottom box-shadow
neatly and worked great for me with the following CSS.)
#tabs {
margin-top: 1em;
margin-left: 0.5em;
}
#tabs li a {
padding: 1 1em;
position: relative;
top: 1px;
background: #FFFFFF;
}
#tabs #selected {
/* For the "selected" tab */
box-shadow: 0 0 3px #666666;
background: #FFFFFF;
}
#tabs #selected a {
position: relative;
top: 1px;
background: #FFFFFF;
padding-bottom: 2px;
}
#tabs ul {
list-style: none;
padding: 0;
margin: 0;
}
#tabs li {
float: left;
border: 1px solid;
border-bottom-width: 0;
margin: 0 0.5em 0 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
Thought I'd put this out there as another possible solution for anyone perusing SO for this.
You can use the forName
method of Class
:
Class cls = Class.forName(clsName);
Object obj = cls.newInstance();
Try this following program for 2d array in java:
public class ArrayTwo2 {
public static void main(String[] args) throws IOException,NumberFormatException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[][] a;
int sum=0;
a=new int[3][2];
System.out.println("Enter array with 5 elements");
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
System.out.print(a[i][j]+" ");
sum=sum+a[i][j];
}
System.out.println();
//System.out.println("Array Sum: "+sum);
sum=0;
}
}
}
None of the following answers are right. All these methods just seem to be alike, but in practice do absolutely different things. It is hard to give short comments. Better to give a link to full documentation about these methods: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html
moment().format(); // "2019-08-12T17:52:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, August 12th 2019, 5:52:00 pm"
moment().format("ddd, hA"); // "Mon, 5PM"
Applying a CORS restriction is a security feature defined by a server and implemented by a browser.
The browser looks at the CORS policy of the server and respects it.
However, the Postman tool does not bother about the CORS policy of the server.
That is why the CORS error appears in the browser, but not in Postman.
Because your image is an inline-block element. You could change it to a block-level element like this:
<img src="queuedError.jpg" style="margin:auto; width:200px;display:block" />
and it will be centered.
@parag's code works great. But while loading some large images you may fail. You should use;
imageView.setImageBitmap(getScaledBitmap(picturePath, 800, 800));
instead of;
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Here are my methods that you can use.
private Bitmap getScaledBitmap(String picturePath, int width, int height) {
BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, sizeOptions);
int inSampleSize = calculateInSampleSize(sizeOptions, width, height);
sizeOptions.inJustDecodeBounds = false;
sizeOptions.inSampleSize = inSampleSize;
return BitmapFactory.decodeFile(picturePath, sizeOptions);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
No need of JQuery simply you can do
if(yourObject['email']){
// what if this property exists.
}
as with any value for email
will return you true
, if there is no such property or that property value is null
or undefined
will result to false
For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code.
To stack vertically (img1 over img2):
vis = np.concatenate((img1, img2), axis=0)
To stack horizontally (img1 to the left of img2):
vis = np.concatenate((img1, img2), axis=1)
To verify:
import cv2
import numpy as np
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)
The out.png image will contain img1 on the left and img2 on the right.
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
This probably has the same table to other schema the reason why you're getting that error.
You need to drop first the child row then the parent row.
When you get a connection to PostgreSQL
it is always to a particular database. To access a different database, you must get a new connection.
Using \c
in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.
Just add this to viewdidload
:
let insets = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
scrollVIew.contentInset = insets
scrollVIew.scrollIndicatorInsets = insets
According to MSDN, timestamp
Is a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The timestamp data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type.
You're probably looking for the datetime
data type instead.
Here is another solution, this way you can fetch all data about the form and use it in a serverside call or something.
$('.form').on('submit', function( e )){
var form = $( this ), // this will resolve to the form submitted
action = form.attr( 'action' ),
type = form.attr( 'method' ),
data = {};
// Make sure you use the 'name' field on the inputs you want to grab.
form.find( '[name]' ).each( function( i , v ){
var input = $( this ), // resolves to current input element.
name = input.attr( 'name' ),
value = input.val();
data[name] = value;
});
// Code which makes use of 'data'.
e.preventDefault();
}
You can then use this with ajax calls:
function sendRequest(action, type, data) {
$.ajax({
url: action,
type: type,
data: data
})
.done(function( returnedHtml ) {
$( "#responseDiv" ).append( returnedHtml );
})
.fail(function() {
$( "#responseDiv" ).append( "This failed" );
});
}
Hope this is of any use for any of you :)
In python 3.1 you can produce a list in a way
lst=list(range(100))
for i in range(100)
print (lst[i],',',end='')
In python 2.7 you can do it as
lst=range(100)
for i in range(100)
print lst[i]+','
Open the file .bash_profile
in your Home folder. It is a hidden file.
Add this path below to the end export PATH line in you .bash_profile
file
:/Applications/Postgres.app/Contents/Versions/latest/bin
The symbol :
separates the paths.
If the file contains:
export PATH=/usr/bin:/bin:/usr/sbin:/sbin
it will become:
export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Postgres.app/Contents/Versions/latest/bin
In Terminal, paste the following: defaults write com.apple.finder AppleShowAllFiles YES
Use the deployment Toolkit's deployJava.js (though this ensures a minimum version, rather than a specific version)
Expanding upon the above code from @dreamlax
char *readFile(char *fileName) {
FILE *file = fopen(fileName, "r");
char *code;
size_t n = 0;
int c;
if (file == NULL) return NULL; //could not open file
fseek(file, 0, SEEK_END);
long f_size = ftell(file);
fseek(file, 0, SEEK_SET);
code = malloc(f_size);
while ((c = fgetc(file)) != EOF) {
code[n++] = (char)c;
}
code[n] = '\0';
return code;
}
This gives you the length of the file, then proceeds to read it character by character.
What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?
If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list.
import pickle
with open('outfile', 'wb') as fp:
pickle.dump(itemlist, fp)
To read it back:
with open ('outfile', 'rb') as fp:
itemlist = pickle.load(fp)
If you don't want anything to display before the redirect, then you will need to use some server side scripting to accomplish the task before the page is served. The page has already begun loading by the time your Javascript is executed on the client side.
If Javascript is your only option, your best best is to make your script the first .js file included in the <head>
of your document.
Instead of Javascript, I recommend setting up your redirect logic in your Apache or nginx server configuration.
I often get such an issue. My pattern that causes cleanup problems.
Closing image viewer where deleted file is opened solves the problem. Maybe other software can block cleanup the same way.
In general. I believe restarting computer may help in such cases.
I would suggest not to use list-style-image
, as it behaves quite differently in different browsers, especially the image position
instead, you can use something like this
ol.widgets,
ol.widgets li { list-style: none; }
ol.widgets li { padding-left: 20px; backgroud: transparent ("image") no-repeat x y; }
it works in all browsers and would give you the identical result in different browsers.
Assuming a and b are the dictionaries you want to merge:
c = {key: value for (key, value) in (a.items() + b.items())}
To convert your string to python dictionary you use the following:
import json
my_dict = json.loads(json_str)
Update: full code using strings:
# test cases for jsonStringA and jsonStringB according to your data input
jsonStringA = '{"error_1395946244342":"valueA","error_1395952003":"valueB"}'
jsonStringB = '{"error_%d":"Error Occured on machine %s in datacenter %s on the %s of process %s"}' % (timestamp_number, host_info, local_dc, step, c)
# now we have two json STRINGS
import json
dictA = json.loads(jsonStringA)
dictB = json.loads(jsonStringB)
merged_dict = {key: value for (key, value) in (dictA.items() + dictB.items())}
# string dump of the merged dict
jsonString_merged = json.dumps(merged_dict)
But I have to say that in general what you are trying to do is not the best practice. Please read a bit on python dictionaries.
Alternative solution:
jsonStringA = get_my_value_as_string_from_somewhere()
errors_dict = json.loads(jsonStringA)
new_error_str = "Error Ocurred in datacenter %s blah for step %s blah" % (datacenter, step)
new_error_key = "error_%d" % (timestamp_number)
errors_dict[new_error_key] = new_error_str
# and if I want to export it somewhere I use the following
write_my_dict_to_a_file_as_string(json.dumps(errors_dict))
And actually you can avoid all these if you just use an array to hold all your errors.
I had problem like this, but with several "actions". My solution looks like this:
<form method="POST" th:object="${searchRequest}" action="searchRequest" >
<input type="text" th:field="*{name}"/>
<input type="submit" value="find" th:value="find" />
</form>
...
<form method="POST" th:object="${commodity}" >
<input type="text" th:field="*{description}"/>
<input type="submit" value="add" />
</form>
And controller
@Controller
@RequestMapping("/goods")
public class GoodsController {
@RequestMapping(value = "add", method = GET)
public String showGoodsForm(Model model){
model.addAttribute(new Commodity());
model.addAttribute("searchRequest", new SearchRequest());
return "goodsForm";
}
@RequestMapping(value = "add", method = POST)
public ModelAndView processAddCommodities(
@Valid Commodity commodity,
Errors errors) {
if (errors.hasErrors()) {
ModelAndView model = new ModelAndView("goodsForm");
model.addObject("searchRequest", new SearchRequest());
return model;
}
ModelAndView model = new ModelAndView("redirect:/goods/" + commodity.getName());
model.addObject(new Commodity());
model.addObject("searchRequest", new SearchRequest());
return model;
}
@RequestMapping(value="searchRequest", method=POST)
public String processFindCommodity(SearchRequest commodity, Model model) {
...
return "catalog";
}
I'm sure - here is not "best practice", but it is works without "Neither BindingResult nor plain target object for bean name available as request attribute".
Use libcurl, here is a simple example.
EDIT: If this is about starting a web browser from C++, you can invoke a shell command with system
on a POSIX system:
system("<mybrowser> http://google.com");
By replacing <mybrowser>
with the browser you want to launch.
To start the standalone Device Monitor application, enter the following on the command line in the android-sdk/tools/
directory:
monitor
You can then link the tool to a connected device by selecting the device from the Devices pane. If you have trouble viewing panes or windows, select Window > Reset Perspective from the menu bar.
reference : https://developer.android.com/studio/profile/monitor.html
=> You Can change minSdkVersion 16
And open Device File Explorer
See Below Image:
Just to complete this with the most stupid method I can come up with: Generate all possible strings of length 1, use equals to compare them to the original string; if they are equal, the string length is 1. If no string matches, generate all possible strings of length 2, compare them, for string length 2. Etc. Continue until you find the string length or the universe ends, whatever happens first.
According to Malcolm Gladwell, it will take you 10,000 hours to get really good. So get cracking.
A variation using just standard color code:
android:textColor="#ff0000"
I'm not 100% sure that I understand your question, so tell me if I'm wrong.
If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.
Then, you should do the following:
convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate
use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)
when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both
For example:
inline int fromJByte(jbyte pixel) {
// cast to unsigned char re-interprets values as 0-255
// cast to int will make intermediate calculations safer
return static_cast<int>(static_cast<unsigned char>(pixel));
}
inline jbyte fromInt(int pixel) {
if(pixel < 0)
pixel = 0;
if(pixel > 255)
pixel = 255;
return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}
jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);
Have you tried the following:
$('#theDiv').prepend('<img id="theImg" src="theImg.png" />')
try this easy
_x000D_
.btn-circle span {_x000D_
top: 0;_x000D_
_x000D_
position: absolute;_x000D_
font-size: 18px;_x000D_
text-align: center;_x000D_
text-decoration: none;_x000D_
-webkit-animation:spin 4s linear infinite;_x000D_
-moz-animation:spin 4s linear infinite;_x000D_
animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">↻</span></button>
_x000D_
I want to add this answer because the DBCC CHECKIDENT
-approach will product problems when you use schemas for tables. Use this to be sure:
DECLARE @Table AS NVARCHAR(500) = 'myschema.mytable';
DBCC CHECKIDENT (@Table, RESEED, 0);
If you want to check the success of the operation, use
SELECT IDENT_CURRENT(@Table);
which should output 0
in the example above.
According to Microsoft documentation, should NEVER use async void
Do not do this: The following example uses
async void
which makes the HTTP request complete when the first await is reached:
Which is ALWAYS a bad practice in ASP.NET Core apps.
Accesses the HttpResponse after the HTTP request is complete.
Crashes the process.
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.
Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.
.url files can be made by saving a favourite with internet exploiter.
I started with node-csvtojson, but it brought too many dependencies for my linking.
Building on your question and the answer by brnd, I used node-csv and underscore.js.
var attribs;
var json:
csv()
.from.string(csvString)
.transform(function(row) {
if (!attribs) {
attribs = row;
return null;
}
return row;
})
.to.array(function(rows) {
json = _.map(rows, function(row) {
return _.object(attribs, row);
});
});
Use tr
to <tr class="paginate">
//Pagination
<div id="page-nav"></div>
//Script
<script>
jQuery(function($) {
// Grab whatever we need to paginate
var pageParts = $(".paginate");
// How many parts do we have?
var numPages = 100;
// How many parts do we want per page?
var perPage = 10;
// When the document loads we're on page 1
// So to start with... hide everything else
pageParts.slice(perPage).hide();
// Apply simplePagination to our placeholder
$("#page-nav").pagination({
items: numPages,
itemsOnPage: perPage,
cssStyle: "light-theme",
// We implement the actual pagination
// in this next function. It runs on
// the event that a user changes page
onPageClick: function(pageNum) {
// Which page parts do we show?
var start = perPage * (pageNum - 1);
var end = start + perPage;
// First hide all page parts
// Then show those just for our page
pageParts.hide()
.slice(start, end).show();
}
});
});
</script>
Give this command to export your database, this will include date as well
mysqldump -u[username] -p[userpassword] --databases yourdatabase | gzip > /home/pi/database_backup/database_`date '+%m-%d-%Y'`.sql.gz
(no space after -p)
The Answer from Steve Sheldon fixed the problem for me, however, as I am scripting certificate permissions with out a gui, I needed a scriptable solution. I struggled to find where my private key was stored . The private key was not in -C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
, eventually I found that it was actually in C:\ProgramData\Microsoft\Crypto\Keys
. Below I describe how I found that out:
I tried FindPrivateKey
but it could not find the private key, and using powershell the $cert.privatekey.cspkeycontainerinfo.uniquekeycontainername
was null/empty.
Luckily, certutil -store my
listed the certificate and gave me the details I needed to script the solution.
================ Certificate 1 ================ Serial Number: 162f1b54fe78c7c8fa9df09 Issuer: CN=*.internal.xxxxxxx.net NotBefore: 23/08/2019 14:04 NotAfter: 23/02/2020 14:24 Subject: CN=*.xxxxxxxnet Signature matches Public Key Root Certificate: Subject matches Issuer Cert Hash(sha1): xxxxa5f0e9f0ac8b7dd634xx Key Container = {407EC7EF-8701-42BF-993F-CDEF8328DD} Unique container name: 8787033f8ccb5836115b87acb_ca96c65a-4b42-a145-eee62128a ##* ^-- filename for private key*## Provider = Microsoft Software Key Storage Provider Private key is NOT plain text exportable Encryption test passed CertUtil: -store command completed successfully.
I then scanned c\ProgramData\Microsoft\Crypto\
folder and found the file 8787033f8ccb5836115b87acb_ca96c65a-4b42-a145-eee62128a in C:\ProgramData\Microsoft\Crypto\Keys .
Giving my service account read access this file fixed the issues for me
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print 'matched'
I found icons were not displaying due to a difference in the casing (ie upper case vs lower case). The CSS file was using "FFFFFF" while the actual file was using "ffffff". Icons displayed for me once I changed the case to match.
Yes, if such precision is required use System.nanoTime()
, but be aware that you are then requiring a Java 5+ JVM.
On my XP systems, I see system time reported to at least 100 microseconds 278 nanoseconds using the following code:
private void test() {
System.out.println("currentTimeMillis: "+System.currentTimeMillis());
System.out.println("nanoTime : "+System.nanoTime());
System.out.println();
testNano(false); // to sync with currentTimeMillis() timer tick
for(int xa=0; xa<10; xa++) {
testNano(true);
}
}
private void testNano(boolean shw) {
long strMS=System.currentTimeMillis();
long strNS=System.nanoTime();
long curMS;
while((curMS=System.currentTimeMillis()) == strMS) {
if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)); }
}
if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)+", Milli: "+(curMS-strMS)); }
}
I know this is an old post, but changing th or td color is not te right way. I was fooled by this post as well.
First load your bootstrap.css and add this in your own css. This way it is only 2 lines if you have a hovered table, else its only 1 line, unless you want to change odd and even :-)
.table-striped>tbody>tr:nth-child(odd) {
background-color: LemonChiffon;
}
.table-hover tbody tr:hover {
background-color: AliceBlue;
}
You should download chgcolor.zip from http://www.mailsend-online.com/blog/setting-text-color-in-a-batch-file.html and also download echoj.zip from www.mailsend-online.com/blog/?p=41 They're both towards the bottom of the page. Extract both folders to the desktop and copy the executables(.exe files) from inside the extracted folders to the C:\Windows directory. This will allow them to be executed from the command line. Open up notepad and copy the following into it:
@echo off
chgcolor 03
echoj "hi "
chgcolor 0d
echoj "world"
chgcolor 07
echoj $0a
Save the file to the Desktop as hi.bat. Now open the command prompt and navigate to your Desktop folder and type "hi.bat" without the quotes. That should get you started besure to read both webpages to get a full tutorial.
Now, adding view-source:
before the site-address.com works on Chrome - Android.
Source: https://www.quora.com/How-can-I-view-a-webpage-source-code-in-Google-chrome-mobile-version
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.
Step by step:
1. pip install chromedriver-binary
2. import the package
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
driver = webdriver.Chrome()
driver.get("http://www.python.org")
You can add a div with runat="server" to the page:
<div runat="server" id="myDiv">
</div>
and then set its InnerHtml property from the code-behind:
myDiv.InnerHtml = "your html here";
If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:
<script type="text/javascript">
Sys.Application.add_load(MyLoad);
function MyLoad(sender) {
$get('<%= div.ClientID %>').innerHTML += " - text added on client";
}
</script>
Isn't this a much simpler solution, if I correctly understand the question, of course.
I want to load email addresses that are in a table called "spam" into a variable.
select email from spam
produces the following list, say:
.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu
To load into the variable @list:
declare @list as varchar(8000)
set @list += @list (select email from spam)
@list may now be INSERTed into a table, etc.
I hope this helps.
To use it for a .csv file or in VB, spike the code:
declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list
and it produces ready-made code to use elsewhere:
".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"
One can be very creative.
Thanks
Nico
One other approach that we have taken successfully is to generate the WS client proxy code using wsimport (from Ant, as an Ant task) and specify the wsdlLocation attribute.
<wsimport debug="true" keep="true" verbose="false" target="2.1" sourcedestdir="${generated.client}" wsdl="${src}${wsdl.file}" wsdlLocation="${wsdl.file}">
</wsimport>
Since we run this for a project w/ multiple WSDLs, the script resolves the $(wsdl.file} value dynamically which is set up to be /META-INF/wsdl/YourWebServiceName.wsdl relative to the JavaSource location (or /src, depending on how you have your project set up). During the build proess, the WSDL and XSDs files are copied to this location and packaged in the JAR file. (similar to the solution described by Bhasakar above)
MyApp.jar
|__META-INF
|__wsdl
|__YourWebServiceName.wsdl
|__YourWebServiceName_schema1.xsd
|__YourWebServiceName_schmea2.xsd
Note: make sure the WSDL files are using relative refrerences to any imported XSDs and not http URLs:
<types>
<xsd:schema>
<xsd:import namespace="http://valueobject.common.services.xyz.com/" schemaLocation="YourWebService_schema1.xsd"/>
</xsd:schema>
<xsd:schema>
<xsd:import namespace="http://exceptions.util.xyz.com/" schemaLocation="YourWebService_schema2.xsd"/>
</xsd:schema>
</types>
In the generated code, we find this:
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2-b05-
* Generated source version: 2.1
*
*/
@WebServiceClient(name = "YourService", targetNamespace = "http://test.webservice.services.xyz.com/", wsdlLocation = "/META-INF/wsdl/YourService.wsdl")
public class YourService_Service
extends Service
{
private final static URL YOURWEBSERVICE_WSDL_LOCATION;
private final static WebServiceException YOURWEBSERVICE_EXCEPTION;
private final static QName YOURWEBSERVICE_QNAME = new QName("http://test.webservice.services.xyz.com/", "YourService");
static {
YOURWEBSERVICE_WSDL_LOCATION = com.xyz.services.webservice.test.YourService_Service.class.getResource("/META-INF/wsdl/YourService.wsdl");
WebServiceException e = null;
if (YOURWEBSERVICE_WSDL_LOCATION == null) {
e = new WebServiceException("Cannot find '/META-INF/wsdl/YourService.wsdl' wsdl. Place the resource correctly in the classpath.");
}
YOURWEBSERVICE_EXCEPTION = e;
}
public YourService_Service() {
super(__getWsdlLocation(), YOURWEBSERVICE_QNAME);
}
public YourService_Service(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
/**
*
* @return
* returns YourService
*/
@WebEndpoint(name = "YourServicePort")
public YourService getYourServicePort() {
return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns YourService
*/
@WebEndpoint(name = "YourServicePort")
public YourService getYourServicePort(WebServiceFeature... features) {
return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class, features);
}
private static URL __getWsdlLocation() {
if (YOURWEBSERVICE_EXCEPTION!= null) {
throw YOURWEBSERVICE_EXCEPTION;
}
return YOURWEBSERVICE_WSDL_LOCATION;
}
}
Perhaps this might help too. It's just a different approach that does not use the "catalog" approach.
Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
I think the previous answers address the topic very well. However, I'd add that in one case when you have Spring Security enabled in your application, you might have to specifically tell Spring to permit requests to other static resource directories like for example "/static/fonts".
In my case I had "/static/css", "/static/js", "/static/images" permited by default , but /static/fonts/** was blocked by my Spring Security implementation.
Below is an example of how I fixed this.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.....
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/fonts/**").permitAll().
//other security configuration rules
}
.....
}
This is probably not suitable for production because it will open the keyboard. Note that the boolean returned by similar functions is not specified in the API and are therefore unreliable. Refer to the documentation here...
public boolean showSoftInput (View view,
int flags,
ResultReceiver resultReceiver)
Note that this method takes a ResultReceiver. It can get the results: RESULT_UNCHANGED_SHOWN, RESULT_UNCHANGED_HIDDEN, RESULT_SHOWN, or RESULT_HIDDEN. If you get RESULT_UNCHANGED_SHOWN, the keyboard was visible. If you need it to stay closed if it was closed, you will need to close it.
>ssh user@serverip -p portnumber
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys
.disabledLink.disabled {pointer-events:none;}
That should do it hope I helped!
For me I got this error because I lost access to the output path for the dist folder set in my angular.json file. After I reconnected to the remote path with updated credentials the error went away.
Try to find a copy of Why's (Poignant) Guide to Ruby online. The original site is offline but I'm sure there are a few mirrors out there. It's not your typical programming guide; it puts a unique (and funny) spin on learning a new language that might suit your friend. Not to mention, Ruby is a great language to learn with.
$q->where("a = 1")
->andWhere("b = 1 OR b = 2")
->andWhere("c = 2 OR c = 2")
;
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
new Date().toString();
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
Dateformatter can make it to any string you want
Set IFS to newline, like this:
IFS='
'
for x in `ls -l $1`; do echo $x; done
Put a sub-shell around it if you don't want to set IFS permanently:
(IFS='
'
for x in `ls -l $1`; do echo $x; done)
Or use while | read instead:
ls -l $1 | while read x; do echo $x; done
One more option, which runs the while/read at the same shell level:
while read x; do echo $x; done << EOF
$(ls -l $1)
EOF
You can do that simple with Files.size(new File(filename).toPath())
.
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
We don't need to plt.ioff()
or plt.show()
(if we use %matplotlib inline
). You can test above code without plt.ioff()
. plt.close()
has the essential role. Try this one:
%matplotlib inline
import pylab as plt
# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')
If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2)
to the end of it, you will see nothing.
In conclusion, if you close figure by plt.close(fig)
, it won't be displayed.
If you're doing any sort of development you need to point to the JDK (Java Development Kit). Otherwise, you can point to the JRE (Java Runtime Environment).
The JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.
You should set JAVA_HOME
based on current Java you are using.
readlink
will print value of a symbolic link for current Java and sed
will adjust it to JRE directory:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
If you want to set up JAVA_HOME to JDK you should go up one folder more:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
There is a huge difference.
As most of the answers have already pointed out the theory, I would like to point out an easy example:
int x = 1;
//would print 1 as first statement will x = x and then x will increase
int x = x++;
System.out.println(x);
Now let's see ++x
:
int x = 1;
//would print 2 as first statement will increment x and then x will be stored
int x = ++x;
System.out.println(x);
This works for spanish operation system.
Script accepts two parameters:
script.bat listofurls.txt output.txt
@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
set SERVER_ADDRESS=No se pudo resolver el host
for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP')
do (
if %%v==Haciendo set SERVER_ADDRESS=%%z
if %%v==Respuesta set SERVER_ADDRESS=%%x
if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)
If you have tried all the ways and failed, try this one command:
setsebool -P httpd_can_network_connect on
Try this
on change event
$("#jodSel").on('change',function(){
var getValue=$(this).val();
alert(getValue);
});
Note: In dropdownlist
if you want to set id,text relation from your database then, set id as value in option tag, not by adding extra id
attribute inside option its not standard paractise though i did both in my answer but i prefer example 1
HTML Markup
Example 1:
<select id="example1">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
Example 2 :
<select id="example2">
<option id="1">one</option>
<option id="2">two</option>
<option id="3">three</option>
<option id="4">four</option>
</select>
Jquery:
$("#example1").on('change', function () {
alert($(this).val());
});
$("#example2").on('change', function () {
alert($(this).find('option:selected').attr('id'));
});
View Demo : For example 1 & 2
Blog Article : Get and Set dropdown list selected value with Jquery
My Blog : jQuery tutorials
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
Something like:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});
To be simple,
Mono is third party implementation of .Net framework for Linux/Android/iOs
.Net Core is microsoft's own implementation for same.
.Net Core is future. and Mono will be dead eventually. Having said that .Net Core is not matured enough. I was struggling to implement it with IBM Bluemix and later dropped the idea. Down the time (may be 1-2 years), it should be better.
Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.
You'll have to uninstall XAMPP 1.7.2 and install XAMPP 1.7.0, which contains PHP 5.2.8.
D:\Documents and Settings\box>php -v
PHP 5.2.8 (cli) (built: Dec 8 2008 19:31:23)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technol
ogies
with Zend Optimizer v3.3.3, Copyright (c) 1998-2007, by Zend Technologies
XAMPP 1.6.8 contains PHP 5.2.6.
D:\Documents and Settings\box>php -v
PHP 5.2.6 (cli) (built: May 2 2008 18:02:07)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technol
ogies
with Zend Optimizer v3.3.3, Copyright (c) 1998-2007, by Zend Technologies
The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:
HTML
<div id="my-div">I want to be centered</div>?
CSS
#my-div {
position: absolute;
bottom: 15px;
text-align: center;
width: 100%;
}
?
I know I'm late on this one:
def convert_keys_to_string(dictionary):
"""Recursively converts dictionary keys to strings."""
if not isinstance(dictionary, dict):
return dictionary
return dict((str(k), convert_keys_to_string(v))
for k, v in dictionary.items())
At the first site is a dropdown field to select the language of phpmyadmin.
In the config.inc.php you can set:
$cfg['Lang'] = '';
More details you can find in the documentation: http://www.phpmyadmin.net/documentation/
We'll do it using just CSS pseudo selectors!
This technique will work with dynamically generated content and different font sizes and widths.
HTML:
<div class='split-color'>Two is better than one.</div>
CSS:
.split-color > span {
white-space: pre-line;
position: relative;
color: #409FBF;
}
.split-color > span:before {
content: attr(data-content);
pointer-events: none; /* Prevents events from targeting pseudo-element */
position: absolute;
overflow: hidden;
color: #264A73;
width: 50%;
z-index: 1;
}
To wrap the dynamically generated string, you could use a function like this:
// Wrap each letter in a span tag and return an HTML string
// that can be used to replace the original text
function wrapString(str) {
var output = [];
str.split('').forEach(function(letter) {
var wrapper = document.createElement('span');
wrapper.dataset.content = wrapper.innerHTML = letter;
output.push(wrapper.outerHTML);
});
return output.join('');
}
// Replace the original text with the split-color text
window.onload = function() {
var el = document.querySelector('.split-color'),
txt = el.innerHTML;
el.innerHTML = wrapString(txt);
}
I'm using this:
extension UILabel {
func setHTML(html: String) {
do {
let attributedString: NSAttributedString = try NSAttributedString(data: html.data(using: .utf8)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
self.attributedText = attributedString
} catch {
self.text = html
}
}
}
color: transparent;
make the tricks for me
#videos-part:before{
font-size: 35px;
line-height: 33px;
width: 16px;
color: transparent;
content: 'AS YOU LIKE';
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
background-size: 25px;
background-repeat: no-repeat;
}
DES is the old "data encryption standard" from the seventies.
best and simple way is to put title inside a span and replace then.
'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
<div class="widget-head ui-widget-header"
style="cursor:move;height:20px;width:130px">'+
'<span id="'+span_id+'" style="float:right; cursor:pointer"
class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>' +
'<span id="spTitle">'+
dialog_title+ '</span>'
'</div></div>
now you can simply use this:
$('#'+div_id+' .widget-head sp#spTitle').text("new dialog title");
I am behind a corporate proxy, so I usually use an intermediate proxy to enable NTLM authentication.
I had hangs problem with npm install when using CNTLM proxy. With NTLM-APS (a similar proxy) the hangs were gone.
I have never ever come across such a strange problem like this! o.O
Do you know what the problem was? $ isn't working. I tried the same code with jQuery like jQuery("#tblEntAttributes tbody").append(newRowContent);
and it works like a charm!
No idea why this strange problem occurs!
The jsonify()
function in flask returns a flask.Response()
object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps()
method will just return an encoded string, which would require manually adding the MIME type header.
See more about the jsonify()
function here for full reference.
Edit:
Also, I've noticed that jsonify()
handles kwargs or dictionaries, while json.dumps()
additionally supports lists and others.
If you install Node using the windows installer, there is nothing you have to do. It adds path to node and npm.
You can also use Windows setx command for changing system environment variables. No reboot is required. Just logout/login. Or just open a new cmd window, if you want to see the changing there.
setx PATH "%PATH%;C:\Program Files\nodejs"
df.loc[df['A'] == df['B'], 'C'] = 0
df.loc[df['A'] > df['B'], 'C'] = 1
df.loc[df['A'] < df['B'], 'C'] = -1
Easy to solve using indexing. The first line of code reads like so, if column A
is equal to column B
then create and set column C
equal to 0.
If you use STS. You must have Lombok installed in your Eclipse by running lombok-abc.jar
Please Following the Steps:
-Include pom in Maven . -Exit/Shutdown STS(must) -Find lombok Jar in ~.m2\repository\org\projectlombok\lombok\1.18.12 -From Command
After then click to update/update
then Quit Installer
Happy Coding
Blockquote
The following approach was inspired by this answer to a related (more general) question.
The approach is to read the MachineGuid
value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
. This value is generated during OS installation.
There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid
value.
However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.
public string GetMachineGuid()
{
string location = @"SOFTWARE\Microsoft\Cryptography";
string name = "MachineGuid";
using (RegistryKey localMachineX64View =
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
{
if (rk == null)
throw new KeyNotFoundException(
string.Format("Key Not Found: {0}", location));
object machineGuid = rk.GetValue(name);
if (machineGuid == null)
throw new IndexOutOfRangeException(
string.Format("Index Not Found: {0}", name));
return machineGuid.ToString();
}
}
}
For bootstrap datetimepicker
, assign decade
value as follow:
$(".years").datetimepicker({
format: "yyyy",
startView: 'decade',
minView: 'decade',
viewSelect: 'decade',
autoclose: true,
});
Here is how I was able to trick Excel to count expired certifications in a list. I didn't have a set date, or date range, just current date. "TODAY()" doesn't work in these for Excel 2013. It sees it as text or condition, not the date value. So these previous didn't work for me. So the word problem/scenario: How many people are expired in this list?
Use: =IFERROR(D5-TODAY(),0) Where D5 is the date to be interrogated.
Then use: =IF(J5>=1,1,0) Where J5 is the cell where the first equation is producing either a positive or negative number. This set, I have hidden on the side of the visible sheet, then I just sum the total for the number of unexpired members.
The third argument is the XMLHttpRequest object, so you can do whatever you want.
$.ajax({
url : 'http://example.com',
type : 'post',
data : 'a=b'
}).done(function(data, statusText, xhr){
var status = xhr.status; //200
var head = xhr.getAllResponseHeaders(); //Detail header info
});
Put the backslash at the end of the line:
alert("Please Select file\
to delete");
Edit I have to note that this is not part of ECMAScript strings as line terminating characters are not allowed at all:
A 'LineTerminator' character cannot appear in a string literal, even if preceded by a backslash
\
. The correct way to cause a line terminator character to be part of the string value of a string literal is to use an escape sequence such as\n
or\u000A
.
So using string concatenation is the better choice.
Update 2015-01-05 String literals in ECMAScript5 allow the mentioned syntax:
A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as
\n
or\u000A
.
Simple Answer: NO
Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.
By personal experience, I would recommed this:
lower_case_table_names
is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.
Although all of the answers above are good, I would like to propose a new method instead of using the symbolic link method in public html directory as proposed BEST in the accepted answer. You need to have access to your server virtual host configurations.
It is about configuring virtual host of your web server directly pointing to the repository directory. In Apache you can do it like:
DocumentRoot /var/www/html/website/your-git-repo
Here is an example of a virtual host file:
<VirtualHost *:443>
ServerName example.com
DocumentRoot /path/to/your-git-repo
...
...
...
...
</VirtualHost>
$(document).prop('title', 'test');
This is simply a JQuery wrapper for:
document.title = 'test';
To add a > periodically you can do:
function changeTitle() {
var title = $(document).prop('title');
if (title.indexOf('>>>') == -1) {
setTimeout(changeTitle, 3000);
$(document).prop('title', '>'+title);
}
}
changeTitle();
You need to write your file to the request stream:
using (var reqStream = req.GetRequestStream())
{
reqStream.Write( ... ) // write the bytes of the file
}
You can use this function to disable the form:
function disableForm(formID){
$('#' + formID).children(':input').attr('disabled', 'disabled');
}
Note that it uses jQuery.
From the update 2 and after narrowing down the problem scope, we can easily find that there is a brace missing at the end of the function addWord
. The compiler will never explicitly identify such a syntax error. instead, it will assume that the missing function definition located in some other object file. The linker will complain about it and hence directly will be categorized under one of the broad the error phrases which is identifier is undefined
. Reasonably, because with the current syntax the next function definition (in this case is ac_search
) will be included under the addWord
scope. Hence, it is not a global function anymore. And that is why compiler will not see this function outside addWord
and will throw this error message stating that there is no such a function. A very good elaboration about the compiler and the linker can be found in this article
How about you just pull the layout params from the view itself if you created it.
$((RelativeLayout)findViewById(R.id.imageButton1)).getLayoutParams();
Could you try this out?
=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0)
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)
Note: Setting Hidden to False will make the row visible
I gave access to "IIS_IUser" but instead it should be "IUSR". That solved the problem.
Well I feel silly, but my problem was that I was in the Debug perspective and they do not show up in that perspective. Switched back to the Java perspective and viola.
All the other answers have two main flaws:
def findall(haystack, needle):
idx = -1
while True:
idx = haystack.find(needle, idx+1)
if idx == -1:
break
yield idx
This iterates through haystack
looking for needle
, always starting at where the previous iteration ended. It uses the builtin str.find
which is much faster than iterating through haystack
character-by-character. It doesn't require any new imports.
Using Classes in Node -
Here we are requiring the ReadWrite module and calling a makeObject(), which returns the object of the ReadWrite class. Which we are using to call the methods. index.js
const ReadWrite = require('./ReadWrite').makeObject();
const express = require('express');
const app = express();
class Start {
constructor() {
const server = app.listen(8081),
host = server.address().address,
port = server.address().port
console.log("Example app listening at http://%s:%s", host, port);
console.log('Running');
}
async route(req, res, next) {
const result = await ReadWrite.readWrite();
res.send(result);
}
}
const obj1 = new Start();
app.get('/', obj1.route);
module.exports = Start;
ReadWrite.js
Here we making a makeObject method, which makes sure that a object is returned, only if a object is not available.
class ReadWrite {
constructor() {
console.log('Read Write');
this.x;
}
static makeObject() {
if (!this.x) {
this.x = new ReadWrite();
}
return this.x;
}
read(){
return "read"
}
write(){
return "write"
}
async readWrite() {
try {
const obj = ReadWrite.makeObject();
const result = await Promise.all([ obj.read(), obj.write()])
console.log(result);
check();
return result
}
catch(err) {
console.log(err);
}
}
}
module.exports = ReadWrite;
For more explanation go to https://medium.com/@nynptel/node-js-boiler-plate-code-using-singleton-classes-5b479e513f74
You can force bundler to use the gems you deploy using "bundle package" and "bundle install --local"
On your development machine:
bundle install
(Installs required gems and makes Gemfile.lock)
bundle package
(Caches the gems in vendor/cache)
On the server:
bundle install --local
(--local means "use the gems from vendor/cache")
Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
or (e.g. with sqlite3 from the Python standard library):
cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))
or others yet (after VALUES
you could have (:1, :2, :3)
, or "named styles" (:fee, :fie, :fo)
or (%(fee)s, %(fie)s, %(fo)s)
where you pass a dict instead of a map as the second argument to execute
). Check the paramstyle
string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!
Use Java's replaceAll(String regex, String replacement)
For example, Use a substitution char for the quotes and then replace that char with \"
String newstring = String.replaceAll("%","\"");
or replace all instances of \"
with \\\"
String newstring = String.replaceAll("\"","\\\"");
You can use java.security.MessageDigest
with SHA
as your algorithm choice.
For reference,
Make sure that the properties of the two fields you are trying to link with a constraint are exactly the same.
Often, the 'unsigned' property on an ID column will catch you out.
ALTER TABLE `dbname`.`tablename` CHANGE `fieldname` `fieldname` int(10) UNSIGNED NULL;
For a soft impact animation solution:
Swift 3:
let indexPath = IndexPath(item: row, section: 0)
tableView.reloadRows(at: [indexPath], with: .fade)
Swift 2.x:
let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
This is another way to protect the app from crashing:
Swift 3:
let indexPath = IndexPath(item: row, section: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
if visibleIndexPaths != NSNotFound {
tableView.reloadRows(at: [indexPath], with: .fade)
}
}
Swift 2.x:
let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.indexOf(indexPath) {
if visibleIndexPaths != NSNotFound {
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
I am using .Net Core 3.1 or higher version.Please follow the solution:
public class UpdateAssignUserRole
{
public string username { get; set; }
public string rolename { get; set; }
public bool IsEdit { get; set; }
}
private async Task UpdateSeedUsers(UserManager<IdentityUser> userManager, UpdateAssignUserRole updateassignUsername)
{
IList<Users> Users = await FindByUserName(updateassignUsername.username);
if (await userManager.FindByNameAsync(updateassignUsername.username) != null)
{
var user = new IdentityUser
{
UserName = updateassignUsername.username,
Email = Users[0].Email,
};
var result = await userManager.FindByNameAsync(updateassignUsername.username);
if (result != null)
{
IdentityResult deletionResult = await userManager.RemoveFromRolesAsync(result, await userManager.GetRolesAsync(result));
if (deletionResult != null)
{
await userManager.AddToRoleAsync(result, updateassignUsername.rolename);
}
}
}
}
Note that jQuery().css()
doesn't change stylesheet rules, it just changes the style of each matched element.
Instead, here's a javascript function I wrote to modify the stylesheet rules themselves.
/**
* Modify an existing stylesheet.
* - sheetId - the id of the <link> or <style> element that defines the stylesheet to be changed
* - selector - the id/class/element part of the rule. e.g. "div", ".sectionTitle", "#chapter2"
* - property - the CSS attribute to be changed. e.g. "border", "font-size"
* - value - the new value for the CSS attribute. e.g. "2px solid blue", "14px"
*/
function changeCSS(sheetId, selector, property, value){
var s = document.getElementById(sheetId).sheet;
var rules = s.cssRules || s.rules;
for(var i = rules.length - 1, found = false; i >= 0 && !found; i--){
var r = rules[i];
if(r.selectorText == selector){
r.style.setProperty(property, value);
found = true;
}
}
if(!found){
s.insertRule(selector + '{' + property + ':' + value + ';}', rules.length);
}
}
Advantages:
<head>
script before the DOM elements are created and therefore prior to the first rendering of the document, avoiding a visually-annoying render, then compute, then re-render. With jQuery, you'd have to wait for the DOM elements to be created, then re-style and re-render them.jQuery(newElement).css()
Caveats:
s.cssRules
defined, so they will fall back to s.rules
which has some peculiarities, such as odd/buggy behavior related to comma-delimited selectors, like "body, p"
. If you avoid those, you might be ok in older IE versions without modification, but I haven't tested it yet."first, second"
i.e the delimiter is a comma followed by a space character.!important
modifier without too much trouble.If you feel like making some improvements to this function, you'll find some useful API docs here: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet
When you first set up this package, I am guessing that either a one or two digit number was the first value in the ShipTo column. Your package reading from the Excel picked a numeric type for that input field and the word "ALL" fails the package since the input spec for that field is numeric. There are several ways to fix this beforehand, but to fix it after the fact, the easiest way is to right click the Excel Source and choose Show Advanced Editor... From there, choose the tab that says Input and Output Properties. In the topmost part of the inputs and outputs section of that dialog box, find the column ShipTo. You will have to drill down to find it. Set the DataType to "string [DT_STR]" and the length to 20.
Click OK then attempt to run your package again.
If it is a big loop with a fixed amount of iterations that is taking a lot of time you can use this function I made. Each iteration of loop adds progress. Where count is the current iteration of the loop, total is the value you are looping to and size(int) is how big you want the bar in increments of 10 i.e. (size 1 =10 chars, size 2 =20 chars)
import sys
def loadingBar(count,total,size):
percent = float(count)/float(total)*100
sys.stdout.write("\r" + str(int(count)).rjust(3,'0')+"/"+str(int(total)).rjust(3,'0') + ' [' + '='*int(percent/10)*size + ' '*(10-int(percent/10))*size + ']')
example:
for i in range(0,100):
loadingBar(i,100,2)
#do some code
output:
i = 50
>> 050/100 [========== ]
Create an Android app using Eclipse.
Create a layout that has a <WebView>
control.
Move your HTML code to /assets
folder.
Load webview with your file:///android_asset/ file.
And you have an android app!
The easiest way to get a sorted Dictionary is to use the built in SortedDictionary
class:
//Sorts sections according to the key value stored on "sections" unsorted dictionary, which is passed as a constructor argument
System.Collections.Generic.SortedDictionary<int, string> sortedSections = null;
if (sections != null)
{
sortedSections = new SortedDictionary<int, string>(sections);
}
sortedSections
will contain the sorted version of sections
WCF = Windows Communication Foundation is used to build service-oriented applications. WPF = Windows Presentation Foundation is used to write platform-independent applications.
[edited]
using your comment about productCode (and assuming product code is a String) as reference...
for(Product p : productList){
s.put(p.getProductCode() , p);
}
function validateForm(){
var success = true;
resetErrorMessages();
var myArray = [];
$(".linkedServiceDonationPurpose").each(function(){
myArray.push($(this).val())
});
$(".linkedServiceDonationPurpose").each(function(){
for ( var i = 0; i < myArray.length; i = i + 1 ) {
for ( var j = i+1; j < myArray.length; j = j + 1 )
if(myArray[i] == myArray[j] && $(this).val() == myArray[j]){
$(this).next( "div" ).html('Duplicate item selected');
success=false;
}
}
});
if (success) {
return true;
} else {
return false;
}
function resetErrorMessages() {
$(".error").each(function(){
$(this).html('');
});``
}
}
To really get the latest revision ("head revision") number on your remote respository, use this:
svn info -r 'HEAD' | grep Revision | egrep -o "[0-9]+"
Outputs for example:
35669
Well, this question was asked years ago. I think technology has changed quite a bit and browser compatibility is much better. You could use vertical-align but I would consider that some what less scaleable and less reusable. I would recommend a flexbox approach.
Here is the same example the original poster used but with flexbox. It styles a single element. If a button size changes for whatever reason, it will continue to be vertically and horizontally centered.
.button {
border: 1px solid #ccc;
height: 40px;
margin: 60px;
padding: 4px;
display: flex;
justify-content: space-around;
align-items: center;
}
Example: JsFiddle
class Rectangle : public Area<int> {
};
Basic JavaScript:
if (document.getElementById("elementId").style.display == 'block') {
alert('this Element is block');
}