For Ubuntu:
add extension=php_curl.so
to php.ini to enable, if necessary. Then sudo service apache2 restart
this is generally taken care of automatically, but there are situations - eg, in shared development environments - where it can become necessary to re-enable manually.
The thumbprint will match all three of these conditions:
Find out the web server user
open up terminal and type
lsof -i tcp:80
This will show you the user of the web server process Here is an example from a raspberry pi running debian:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 7478 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7664 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7794 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
The user is www-data
If you give ownership of the web files to the web server:
chown www-data:www-data -R /opt/lamp/htdocs
And chmod 755 for good measure:
chmod 755 -R /opt/lamp/htdocs
Let me know how you go, maybe you need to use 'sudo' before the command, i.e.
sudo chown www-data:www-data -R /opt/lamp/htdocs
if it doesn't work, please give us the output of:
ls -al /opt/lamp/htdocs
SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'
...is probably what you want.
One of the way is Using below sql queries
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
Taking the value from Command line and showing THE INPUT IS DECIMAL/NON-DECIMAL and NUMBER or not:
NUMBER=$1
IsDecimal=`echo "$NUMBER" | grep "\."`
if [ -n "$IsDecimal" ]
then
echo "$NUMBER is Decimal"
var1=`echo "$NUMBER" | cut -d"." -f1`
var2=`echo "$NUMBER" | cut -d"." -f2`
Digit1=`echo "$var1" | egrep '^-[0-9]+$'`
Digit2=`echo "$var1" | egrep '^[0-9]+$'`
Digit3=`echo "$var2" | egrep '^[0-9]+$'`
if [ -n "$Digit1" ] && [ -n "$Digit3" ]
then
echo "$NUMBER is a number"
elif [ -n "$Digit2" ] && [ -n "$Digit3" ]
then
echo "$NUMBER is a number"
else
echo "$NUMBER is not a number"
fi
else
echo "$NUMBER is not Decimal"
Digit1=`echo "$NUMBER" | egrep '^-[0-9]+$'`
Digit2=`echo "$NUMBER" | egrep '^[0-9]+$'`
if [ -n "$Digit1" ] || [ -n "$Digit2" ]; then
echo "$NUMBER is a number"
else
echo "$NUMBER is not a number"
fi
fi
Adding where to find UPDATE CURRENT_TIMESTAMP
because for new people this is a confusion.
Most people will use phpmyadmin or something like it.
Default value you select CURRENT_TIMESTAMP
Attributes (a different drop down) you select UPDATE CURRENT_TIMESTAMP
To add some more advice combining the suggestions of @kingjeffrey and @CMS: You can use loop
where it is available and fall back on kingjeffrey's event handler when it isn't. There's a good reason why you want to use loop
and not write your own event handler: As discussed in the Mozilla bug report, while loop
currently doesn't loop seamlessly (without a gap) in any browser I know of, it's certainly possible and likely to become standard in the future. Your own event handler will never be seamless in any browser (since it has to pump around through the JavaScript event loop). Therefore, it's best to use loop
where possible instead of writing your own event. As CMS pointed out in a comment on Anurag's answer, you can detect support for loop
by querying the loop
variable -- if it is supported it will be a boolean (false), otherwise it will be undefined, as it currently is in Firefox.
Putting these together:
myAudio = new Audio('someSound.ogg');
if (typeof myAudio.loop == 'boolean')
{
myAudio.loop = true;
}
else
{
myAudio.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
}
myAudio.play();
For the point 2.
I see that no one has suggested to use document.elementFromPoint(x,y)
, to me it is the fastest way to test if an element is nested or hidden by another. You can pass the offsets of the targetted element to the function.
Here's PPK test page on elementFromPoint.
From MDN's documentation:
The
elementFromPoint()
method—available on both the Document and ShadowRoot objects—returns the topmost Element at the specified coordinates (relative to the viewport).
I know this question is super old, but I want to offer 2 options that are more efficient:
1st off, the extension method posted by Paul Walls is good but can be made more efficient by using the StringBuilder class, which is like the string data type but made especially for situations where you will be changing string values more than once. Here is a version I made of the extension method using StringBuilder:
public static string ReplaceChars(this string s, char[] separators, char newVal)
{
StringBuilder sb = new StringBuilder(s);
foreach (var c in separators) { sb.Replace(c, newVal); }
return sb.ToString();
}
I ran this operation 100,000 times and using StringBuilder took 73ms compared to 81ms using string. So the difference is typically negligible, unless you're running many operations or using a huge string.
Secondly, here is a 1 liner loop you can use:
foreach (char c in separators) { s = s.Replace(c, '\n'); }
I personally think this is the best option. It is highly efficient and doesn't require writing an extension method. In my testing this ran the 100k iterations in only 63ms, making it the most efficient. Here is an example in context:
string s = "this;is,\ra\t\n\n\ntest";
char[] separators = new char[] { ' ', ';', ',', '\r', '\t', '\n' };
foreach (char c in separators) { s = s.Replace(c, '\n'); }
Credit to Paul Walls for the first 2 lines in this example.
One thing that hasn't been pointed out, is that there is little to no difference between not having an active environment and and activating the base environment, if you just want to run applications from Conda's (Python's) scripts directory (as @DryLabRebel wants).
You can install and uninstall via conda and conda shows the base environment as active - which essentially it is:
> echo $Env:CONDA_DEFAULT_ENV
> conda env list
# conda environments:
#
base * F:\scoop\apps\miniconda3\current
> conda activate
> echo $Env:CONDA_DEFAULT_ENV
base
> conda env list
# conda environments:
#
base * F:\scoop\apps\miniconda3\current
you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn
List<AttributeHistory> findByValueIn(List<String> values);
SelectListItem
has a Selected
property. If you are creating the SelectListItem
s dynamically, you can just set the one you want as Selected = true
and it will then be the default.
SelectListItem defaultItem = new SelectListItem()
{
Value = 1,
Text = "Default Item",
Selected = true
};
I know it's very late for this one... But here is a (not so simple) oneliner to get what you were looking for:
git show-branch --all 2>/dev/null | grep -E "\[$(git branch | grep -E '^\*' | awk '{ printf $2 }')" | tail -n+2 | sed -E "s/^[^\[]*?\[/[/"
git show-branch
(sending the warnings to /dev/null
).grep -E "\[$BRANCH_NAME"
.$BRANCH_NAME
is obtained with git branch | grep -E '^\*' | awk '{ printf $2 }'
(the branch with a star, echoed without that star).tail -n+2
.[$BRANCH_NAME]
with sed -E "s/^[^\[]*?\[/[/"
.Here it is. Add this code to your web.config file:
<system.webServer>
<rewrite>
<rules>
<rule name="Root Hit Redirect" stopProcessing="true">
<match url="^$" />
<action type="Redirect" url="/menu_1/MainScreen.aspx" />
</rule>
</rules>
</rewrite>
</system.webServer>
It will do 301 Permanent Redirect (URL will be changed in browser). If you want to have such "redirect" to be invisible (rewrite, internal redirect), then use this rule (the only difference is that "Redirect" has been replaced by "Rewrite"):
<system.webServer>
<rewrite>
<rules>
<rule name="Root Hit Redirect" stopProcessing="true">
<match url="^$" />
<action type="Rewrite" url="/menu_1/MainScreen.aspx" />
</rule>
</rules>
</rewrite>
</system.webServer>
You can use the forName
method of Class
:
Class cls = Class.forName(clsName);
Object obj = cls.newInstance();
According to your query
Select * from [User] U where U.DateCreated = '2014-02-07'
SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220
with 2014-02-07 00:00:00.000
for equality). that's why result of comparison is false
Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'
.
You could just try the scandir(Path)
function. it is fast and easy to implement
Syntax:
$files = scandir("somePath");
This Function returns a list of file into an Array.
to view the result, you can try
var_dump($files);
Or
foreach($files as $file)
{
echo $file."< br>";
}
I already found the answer
Swift 4
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "nextView") as! NextViewController
self.present(nextViewController, animated:true, completion:nil)
Swift 3
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)
I don't think there's any need of writing this much big codes.
I've just installed angular-print bower package and all is set to go.
Just inject it in module and you're all set to go Use pre-built print directives & fun is that you can also hide some div if you don't want to print
http://angular-js.in/angularprint/
Mine is working awesome .
The query()
function returns an object, you'll want fetch a record from what's returned from that function. Look at the examples on this page to learn how to print data from mysql
One simple way is by adding the desired font in the project.
Go to File->New->New Resource Directory Select font
This will create a new directory, font, in your resources.
Download your font (.ttf). I use https://fonts.google.com for the same
Add that to your fonts folder then use them in the XML or programmatically.
XML -
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/your_font"/>
Programatically -
Typeface typeface = ResourcesCompat.getFont(this, R.font.your_font);
textView.setTypeface(typeface);
Curiously in gmail for android %0D%0A
doesn't work and <br>
works:
<a href="mailto:[email protected]?subject=This%20is%20Subject&body=First line<br>Second line">
click here to mail me
</a>
Just want to point out something on @codingbadger answer. When using "ProgressBarRenderer" you should always check for "ProgressBarRenderer.IsSupported" before using the class. For me, this has been a nightmare with Visual Styles errors in Win7 that I couldn't fix. So, a better approach and workaround for the solution would be:
Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
if (ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawHorizontalChunks(g, clip);
else
g.FillRectangle(new SolidBrush(this.ForeColor), clip);
Notice that the fill will be a simple rectangle and not chunks. Chunks will be used only if ProgressBarRenderer is supported
This function tells the entity referenced by REF that it is now an object in the CLASSNAME package, or the current package if CLASSNAME is omitted. Use of the two-argument form of bless is recommended.
Example:
bless REF, CLASSNAME
bless REF
Return Value
This function returns the reference to an object blessed into CLASSNAME.
Example:
Following is the example code showing its basic usage, the object reference is created by blessing a reference to the package's class -
#!/usr/bin/perl
package Person;
sub new
{
my $class = shift;
my $self = {
_firstName => shift,
_lastName => shift,
_ssn => shift,
};
# Print all the values just for clarification.
print "First Name is $self->{_firstName}\n";
print "Last Name is $self->{_lastName}\n";
print "SSN is $self->{_ssn}\n";
bless $self, $class;
return $self;
}
An alternative, useful, pattern is:
sed -e 'script script' index.html > index.html.tmp && mv index.html.tmp index.html
That has much the same effect, without using the -i
option, and additionally means that, if the sed script fails for some reason, the input file isn't clobbered. Further, if the edit is successful, there's no backup file left lying around. This sort of idiom can be useful in Makefiles.
Quite a lot of seds have the -i
option, but not all of them; the posix sed is one which doesn't. If you're aiming for portability, therefore, it's best avoided.
Using ignore Duplicates
on the unique index as suggested by IanC here was my solution for a similar issue, creating the index with the Option WITH IGNORE_DUP_KEY
In backward compatible syntax
, WITH IGNORE_DUP_KEY is equivalent to WITH IGNORE_DUP_KEY = ON.
Ref.: index_option
Once you have your image, you can use
$ docker tag <image> <newName>/<repoName>:<tagName>
Build and tag the image with creack/node:latest
$ ID=$(docker build -q -t creack/node .)
Add a new tag
$ docker tag $ID creack/node:0.10.24
You can use this and skip the -t part from build
$ docker tag $ID creack/node:latest
You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.
ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz
FOREIGN KEY (xyz)
REFERENCES ChildTable (xyz) ON DELETE CASCADE
It's useful to work with Deferred Object in this case, and return promise:
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr= new FileReader();
fr.onload = function(e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL( files[0] );
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
And above function could be used in this way:
var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
alert(base64Data);
});
Or in your case:
$(input).on('change',function(){
readImage($(this)).done(function(base64Data){ alert(base64Data); });
});
I am using Visual Studio and also had this problem. It took me some time, but in my program it was caused because I accidentally deleted a Class named "Program" that is generated automatically.
Is there a way in which I can update the plot just by adding more point[s] to it...
There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.
Each method basically sets the data
property of the object being drawn, so doesn't require clearing the screen or figure. The data
property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).
Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:
import matplotlib.pyplot as plt
import numpy
hl, = plt.plot([], [])
def update_line(hl, new_data):
hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
plt.draw()
Then when you receive data from the serial port just call update_line
.
The only thing that worked for me (under windows) was to reopen the IDE as administrator. All worked smoothly after that.
I've discovered that it's difficult to find an answer that you can use out-of-the box in your Swift 3 project. The main problem of other answers that they don't honor the alpha-channel of the image. Here is the technique that I'm using in my projects.
extension UIImage {
func scaledToFit(toSize newSize: CGSize) -> UIImage {
if (size.width < newSize.width && size.height < newSize.height) {
return copy() as! UIImage
}
let widthScale = newSize.width / size.width
let heightScale = newSize.height / size.height
let scaleFactor = widthScale < heightScale ? widthScale : heightScale
let scaledSize = CGSize(width: size.width * scaleFactor, height: size.height * scaleFactor)
return self.scaled(toSize: scaledSize, in: CGRect(x: 0.0, y: 0.0, width: scaledSize.width, height: scaledSize.height))
}
func scaled(toSize newSize: CGSize, in rect: CGRect) -> UIImage {
if UIScreen.main.scale == 2.0 {
UIGraphicsBeginImageContextWithOptions(newSize, !hasAlphaChannel, 2.0)
}
else {
UIGraphicsBeginImageContext(newSize)
}
draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? UIImage()
}
var hasAlphaChannel: Bool {
guard let alpha = cgImage?.alphaInfo else {
return false
}
return alpha == CGImageAlphaInfo.first ||
alpha == CGImageAlphaInfo.last ||
alpha == CGImageAlphaInfo.premultipliedFirst ||
alpha == CGImageAlphaInfo.premultipliedLast
}
}
Example of usage:
override func viewDidLoad() {
super.viewDidLoad()
let size = CGSize(width: 14.0, height: 14.0)
if let image = UIImage(named: "barbell")?.scaledToFit(toSize: size) {
let imageView = UIImageView(image: image)
imageView.center = CGPoint(x: 100, y: 100)
view.addSubview(imageView)
}
}
This code is a rewrite of Apple's extension with added support for images with and without alpha channel.
As a further reading I recommend checking this article for different image resizing techniques. Current approach offers decent performance, it operates high-level APIs and easy to understand. I recommend sticking to it unless you find that image resizing is a bottleneck in your performance.
In order to get current Visible fragment from ViewPager. I am using this simple statement and it's working fine.
public Fragment getFragmentFromViewpager()
{
return ((Fragment) (mAdapter.instantiateItem(mViewPager, mViewPager.getCurrentItem())));
}
How about custom module based .htaccess script (like its used in CodeIgniter)? I tried and it worked good in CodeIgniter apps. Any ideas to use it on other apps?
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.
If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.
for color in ['r', 'b', 'g', 'k', 'm']:
plot(x, y, color=color)
For versions 6.6+ you need to uncheck "Remember the current session for next launch" on Settings -> Preferences -> Backup
.
For older versions you need to uncheck "Remember the current session for next launch"
on Settings -> Preferences
.
The 2nd parameter in the get
call is a config object. You want something like this:
$http
.get('accept.php', {
params: {
source: link,
category_id: category
}
})
.success(function (data,status) {
$scope.info_show = data
});
See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
You could make a helper function:
function setAttributes(el, attrs) {
for(var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
Call it like this:
setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});
The main difference is that SurfaceView
can be drawn on by background theads but Views
can't.
SurfaceViews
use more resources though so you don't want to use them unless you have to.
Static methods don't need to be invoked on the object and that is when you use it. Example: your Main() is a static and you don't create an object to call it.
With plt.scatter
, I can only think of one: to use a proxy artist:
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
x=ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
ccm=x.get_cmap()
circles=[Line2D(range(1), range(1), color='w', marker='o', markersize=10, markerfacecolor=item) for item in ccm((array([4,6,8])-4.0)/4)]
leg = plt.legend(circles, ['4','6','8'], loc = "center left", bbox_to_anchor = (1, 0.5), numpoints = 1)
And the result is:
I had similar issue with selenium: I downgraded my selenium using NuGet and got the same error message. My solution was to remove the newer version lines from the app.config file.
Since newcol
is the ID of the radio button, You can simply use it as below.
$("#"+newcol).attr('checked',true);
What you are doing, you are executing test1
$(test1)
in a sub-shell( child shell ) and Child shells cannot modify anything in parent.
You can find it in bash manual
Please Check: Things results in a subshell here
If you give your table a unique id, its easier:
<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
onmouseup="checkMultipleSelection(this,event);">
<table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table"
cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="width:50px; text-align:left;">09:15 AM</td>
<td style="width:50px; text-align:left;">Item001</td>
<td style="width:50px; text-align:left;">10</td>
<td style="width:50px; text-align:left;">Address1</td>
<td style="width:50px; text-align:left;">46545465</td>
<td style="width:50px; text-align:left;">ref1</td>
</tr>
</table>
</div>
var multiselect =
document.getElementById(
'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
).rows[0].cells,
timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];
//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];
The best option would be to put any element you want to be centered in a div
like this:
<div class="center"> <img src="images/logo.png" /> </div>
and css or inline style:
.center { text-align:center }
For me, I used margin-left: auto; which is more responsive with horizontal resizing.
Having tried $customer = new WC_Customer();
and global $woocommerce; $customer = $woocommerce->customer;
I was still getting empty address data even when I logged in as a non-admin user.
My solution was as follows:
function mwe_get_formatted_shipping_name_and_address($user_id) {
$address = '';
$address .= get_user_meta( $user_id, 'shipping_first_name', true );
$address .= ' ';
$address .= get_user_meta( $user_id, 'shipping_last_name', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_company', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_address_1', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_address_2', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_city', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_state', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_postcode', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_country', true );
return $address;
}
...and this code works regardless of whether you are logged in as admin or not.
for me, the problem was from require('jquery-validation')
i added in the begging of that js file which Validate method used which is necessary as an npm module
unfortunately, when web pack compiles the js files, they aren't in order, so that the validate method is before defining it! and the error comes
so better to use another js file for compiling this library or use local validate method file or even using CDN but in all cases make sure you attached jquery before
It also happens when I just want to compile opencv2.3.2 with mingw32 (in tdm-gcc suites). Often when I install the tdm-gcc, I would like to rename the mingw32-make.exe to make.exe. And I thinks this could be the question. If cmake is asked to generated a MinGW Makefiles, It would try to find ming32-make.exe instead of make.exe. So I copy the make.exe to mingw32-make.exe and reconfigure in Cmake-gui. Finally it works! So I'd like to advise to find whether you have mingw32-make.exe or not to solve this question.
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
You can try with this code
var result = (from item in List
select new
{
EmpLoc = item.empLoc,
EmpPL= item.empPL,
EmpShift= item.empShift
})
.ToList()
.Distinct();
Very useful. I modified it to copy a JavaScript variable value to clipboard:
function copyToClipboard(val){
var dummy = document.createElement("input");
dummy.style.display = 'none';
document.body.appendChild(dummy);
dummy.setAttribute("id", "dummy_id");
document.getElementById("dummy_id").value=val;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
well, I know that I'm a bit too late, but I tried all of your solutions and with no success!
So here is how I managed to do it.
First of all, I'm working on an Asp.Net MVC project.
The Only thing I changed was in my c# method getInvitation
:
public ActionResult getInvitation (Guid s_ID)
{
using (var db = new cRM_Verband_BWEntities())
{
var listSidsMit = (from data in db.TERMINEINLADUNGEN where data.RECID_KOMMUNIKATIONEN == s_ID select data.RECID_MITARBEITER.ToString()).ToArray();
return Json(listSidsMit);
}
}
SuccessFunction in JS :
function successFunction(result) {
console.log(result);
}
I changed the Method Type from string[]
to ActionResult
and of course at the end I wrapped my array listSidsMit
with the Json method.
I'd suggest to modify the primary constructor and add a default value to each parameter:
data class Activity(
var updated_on: String = "",
var tags: List<String> = emptyList(),
var description: String = "",
var user_id: List<Int> = emptyList(),
var status_id: Int = -1,
var title: String = "",
var created_at: String = "",
var data: HashMap<*, *> = hashMapOf<Any, Any>(),
var id: Int = -1,
var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
)
You can also make values nullable by adding ?
and then you can assing null
:
data class Activity(
var updated_on: String? = null,
var tags: List<String>? = null,
var description: String? = null,
var user_id: List<Int>? = null,
var status_id: Int? = null,
var title: String? = null,
var created_at: String? = null,
var data: HashMap<*, *>? = null,
var id: Int? = null,
var counts: LinkedTreeMap<*, *>? = null
)
In general, it is a good practice to avoid nullable objects - write the code in the way that we don't need to use them. Non-nullable objects are one of the advantages of Kotlin compared to Java. Therefore, the first option above is preferable.
Both options will give you the desired result:
val activity = Activity()
activity.title = "New Computer"
sendToServer(activity)
The solution by mrule is correct but has a bug: if the child sends back a large amount of data, it can fill the pipe's buffer, blocking on the child's pipe.send()
, while the parent is waiting for the child to exit on pipe.join()
. The solution is to read the child's data before join()
ing the child. Furthermore the child should close the parent's end of the pipe to prevent a deadlock. The code below fixes that. Also be aware that this parmap
creates one process per element in X
. A more advanced solution is to use multiprocessing.cpu_count()
to divide X
into a number of chunks, and then merge the results before returning. I leave that as an exercise to the reader so as not to spoil the conciseness of the nice answer by mrule. ;)
from multiprocessing import Process, Pipe
from itertools import izip
def spawn(f):
def fun(ppipe, cpipe,x):
ppipe.close()
cpipe.send(f(x))
cpipe.close()
return fun
def parmap(f,X):
pipe=[Pipe() for x in X]
proc=[Process(target=spawn(f),args=(p,c,x)) for x,(p,c) in izip(X,pipe)]
[p.start() for p in proc]
ret = [p.recv() for (p,c) in pipe]
[p.join() for p in proc]
return ret
if __name__ == '__main__':
print parmap(lambda x:x**x,range(1,5))
Using the accepted answer you have to access each record by using Customers[i].customer
, and you need an extra CustomerJson
class, which is a little annoying. If you don't want to do that, you can use the following:
public class CustomerList
{
[JsonConverter(typeof(MyListConverter))]
public List<Customer> customer { get; set; }
}
Note that I'm using a List<>
, not an Array. Now create the following class:
class MyListConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Values())
{
var childToken = child.Children().First();
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(childToken.CreateReader(), newObject);
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards
You could have the active class be dependent upon a boolean data value:
<th
class="initial "
v-on="click: myFilter"
v-class="{active: isActive}">
<span class="wkday">M</span>
</th>
new Vue({
el: '#my-container',
data: {
isActive: false
},
methods: {
myFilter: function() {
this.isActive = !this.isActive;
// some code to filter users
}
}
})
to ckeck the status use the below command, which worked on debian....
/etc/init.d/mysql status
to start my sql server use the below command
/etc/init.d/mysql start
to stop the server use the below command
/etc/init.d/mysql stop
MultipleIE , IETester there are many similar to those.
Multiple IE supports IE3 IE4.01 IE5 IE5.5 and IE6 and "is no longer maintained and there are no plans to continue maintaining it! Thanks and good luck!".
IETester seems a better choice : IE10, IE9, IE8, IE7 IE 6 and IE5.5 on Windows 8 desktop, Windows 7, Vista and XP
Numeric primitives in class scope are initialized to zero when not explicitly initialized.
Numeric primitives in local scope (variables in methods) must be explicitly initialized.
If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.
if(value != 0)
//divide by value is safe when value is not exactly zero.
Otherwise when checking if a floating point value like double
or float
is 0, an error threshold is used to detect if the value is near 0, but not quite 0.
public boolean isZero(double value, double threshold){
return value >= -threshold && value <= threshold;
}
From my experience the fastest way is to take each row for which there is no newer row in the table.
Another advantage is that the syntax used is very simple, and that the meaning of the query is rather easy to grasp (take all rows such that no newer row exists for the username being considered).
SELECT username, value
FROM t
WHERE NOT EXISTS (
SELECT *
FROM t AS witness
WHERE witness.username = t.username AND witness.date > t.date
);
SELECT username, value
FROM (
SELECT username, value, row_number() OVER (PARTITION BY username ORDER BY date DESC) AS rn
FROM t
) t2
WHERE rn = 1
SELECT t.username, t.value
FROM t
INNER JOIN (
SELECT username, MAX(date) AS date
FROM t
GROUP BY username
) tm ON t.username = tm.username AND t.date = tm.date;
SELECT username, value
FROM t
LEFT OUTER JOIN t AS w ON t.username = w.username AND t.date < w.date
WHERE w.username IS NULL
You need to give the WebClient object the credentials. Something like this...
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
The best example of an abstract class is GenericServlet
. GenericServlet
is the parent class of HttpServlet
. It is an abstract class.
When inheriting 'GenericServlet' in a custom servlet class, the service()
method must be overridden.
the OOP way to do this in ES5 is to make that variable into a property using the this keyword.
function first(){
this.nameContent=document.getElementById('full_name').value;
}
function second() {
y=new first();
alert(y.nameContent);
}
I use buffers like tabs, using the BufExplorer plugin and a few macros:
" CTRL+b opens the buffer list
map <C-b> <esc>:BufExplorer<cr>
" gz in command mode closes the current buffer
map gz :bdelete<cr>
" g[bB] in command mode switch to the next/prev. buffer
map gb :bnext<cr>
map gB :bprev<cr>
With BufExplorer you don't have a tab bar at the top, but on the other hand it saves space on your screen, plus you can have an infinite number of files/buffers open and the buffer list is searchable...
The important needs to be inside the ;
td.rule2 div { background-color: #ffff00 !important; }
in fact i believe this should override it
td.rule2 { background-color: #ffff00 !important; }
Another way to do this with simple if/else range. For ex:
$watermarkSize = 0;
if (($originalImageWidth >= 0) && ($originalImageWidth <= 640)) {
$watermarkSize = 10;
} else if (($originalImageWidth >= 641) && ($originalImageWidth <= 1024)) {
$watermarkSize = 25;
} else if (($originalImageWidth >= 1025) && ($originalImageWidth <= 2048)) {
$watermarkSize = 50;
} else if (($originalImageWidth >= 2049) && ($originalImageWidth <= 4096)) {
$watermarkSize = 100;
} else {
$watermarkSize = 200;
}
In the light of the evolving thread, I have updated the below:
* html .ie6 {property:value;}
or
.ie6 { _property:value;}
*+html .ie7 {property:value;}
or
*:first-child+html .ie7 {property:value;}
@media screen\9 {
.ie67 {property:value;}
}
or
.ie67 { *property:value;}
or
.ie67 { #property:value;}
@media \0screen\,screen\9 {
.ie678 {property:value;}
}
html>/**/body .ie8 {property:value;}
or
@media \0screen {
.ie8 {property:value;}
}
.ie8 { property /*\**/: value\9 }
@media screen\0 {
.ie8910 {property:value;}
}
@media screen and (min-width:0\0) and (min-resolution: .001dpcm) {
// IE9 CSS
.ie9{property:value;}
}
@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
// IE9+ CSS
.ie9up{property:value;}
}
@media screen and (min-width:0) {
.ie910{property:value;}
}
_:-ms-lang(x), .ie10 { property:value\9; }
_:-ms-lang(x), .ie10up { property:value; }
or
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.ie10up{property:value;}
}
The use of -ms-high-contrast
means that MS Edge will not be targeted, as Edge does not support -ms-high-contrast
.
_:-ms-fullscreen, :root .ie11up { property:value; }
Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element
Javascript:
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');
Adds (e.g) the below to html
element:
data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'
Allowing very targetted CSS selectors, e.g.:
html[data-useragent*='Chrome/13.0'] .nav{
background:url(img/radial_grad.png) center bottom no-repeat;
}
If possible, identify and fix any issue(s) without hacks. Support progressive enhancement and graceful degradation. However, this is an 'ideal world' scenario not always obtainable, as such- the above should help provide some good options.
You will need to store the image in the database as a BLOB.
you will want to create a column called PHOTO in your table and set it as a mediumblob.
Then you will want to get it from the form like so:
$data = file_get_contents($_FILES['photo']['tmp_name']);
and then set the column to the value in $data.
Of course, this is bad practice and you would probably want to store the file on the system with a name that corresponds to the users account.
One way to block commenting in YAML is by using a text editor like Notepad++ to add a # (comment) tag to multiple lines at once.
In Notepad++ you can do that using the "Block Comment" right-click option for selected text.
Make sure you wrap the condition in the correct precedence
ng-disabled="((!product.img) || (!product.name))"
:1,.d
deletes lines 1 to current.
:1,.-1d
deletes lines 1 to above current.
(Personally I'd use dgg
or kdgg
like the other answers, but TMTOWTDI.)
The array has a Length
property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1
.
string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
When declaring an array in C#, the number you give is the length of the array:
string[] items = new string[5]; // five items, index ranging from 0 to 4.
This page might interest you: http://msdn.microsoft.com/en-us/magazine/dd722812.aspx
You can generate the XML documentation file using either the command-line compiler or through the Visual Studio interface. If you are compiling with the command-line compiler, use options /doc or /doc+. That will generate an XML file by the same name and in the same path as the assembly. To specify a different file name, use /doc:file.
If you are using the Visual Studio interface, there's a setting that controls whether the XML documentation file is generated. To set it, double-click My Project in Solution Explorer to open the Project Designer. Navigate to the Compile tab. Find "Generate XML documentation file" at the bottom of the window, and make sure it is checked. By default this setting is on. It generates an XML file using the same name and path as the assembly.
#include <stdio.h>
#include <stdlib.h>
// ....
system("my_bash_script.sh");
If you are asking whether there's shorthand version of operator ..
- no there isn't. You cannot write a ..= b
. You'll have to type it in full: filename = filename .. ".tmp"
As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:
There is one and only one instance of NoneType i.e. None is a singleton. Consequently foo == None
and foo is None
mean the same. However the is
test is faster and the Pythonic convention is to use foo is None
.
If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for foo
is bar
.
True and False are also (now) singletons, but there is no use-case for foo == True
and no use case for foo is True
.
SELECT FROM_UNIXTIME(mycolumn)
FROM mytable
At least in PostgreSQL you can use the column number in the resultset in your GROUP BY clause:
SELECT
itemName as ItemName,
substring(itemName, 1,1) as FirstLetter,
Count(itemName)
FROM table1
GROUP BY 1, 2
Of course this starts to be a pain if you are doing this interactively and you edit the query to change the number or order of columns in the result. But still.
I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.
Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.
Similar to the accepted answer, but without cloning:
$("#foo").contents().not($("#foo").children()).text();
And here is a jQuery plugin for this purpose:
$.fn.immediateText = function() {
return this.contents().not(this.children()).text();
};
Here is how to use this plugin:
$("#foo").immediateText(); // get the text without children
I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect
function simpleObjInspect(oObj, key, tabLvl)
{
key = key || "";
tabLvl = tabLvl || 1;
var tabs = "";
for(var i = 1; i < tabLvl; i++){
tabs += "\t";
}
var keyTypeStr = " (" + typeof key + ")";
if (tabLvl == 1) {
keyTypeStr = "(self)";
}
var s = tabs + key + keyTypeStr + " : ";
if (typeof oObj == "object" && oObj !== null) {
s += typeof oObj + "\n";
for (var k in oObj) {
if (oObj.hasOwnProperty(k)) {
s += simpleObjInspect(oObj[k], k, tabLvl + 1);
}
}
} else {
s += "" + oObj + " (" + typeof oObj + ") \n";
}
return s;
}
Usage
alert(simpleObjInspect(anyObject));
or
console.log(simpleObjInspect(anyObject));
@Transient
complies with your needs.
Ruby 2.4 introduced the method Hash#transform_values!
, which you could use.
{ :a=>'a' , :b=>'b' }.transform_values! { |v| "%#{v}%" }
# => {:a=>"%a%", :b=>"%b%"}
a less-jquerish approach:
$('#mytable tr').each(function() {
if (!this.rowIndex) return; // skip first row
var customerId = this.cells[0].innerHTML;
});
this can obviously be changed to work with not-the-first cells.
ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"
def op(a=4,b=6):
add = a+b
print add
i)op() [o/p: will be (4+6)=10]
ii)op(99) [o/p: will be (99+6)=105]
iii)op(1,1) [o/p: will be (1+1)=2]
Note:
If none or one parameter is passed the default passed parameter will be considered for the function.
Try this:
$("div.subtab_left li.notebook a").click(function(e) {
e.preventDefault();
});
Just replace following line
exec -a "$0" "$HERE/chrome" "$@"
with
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir
all things will be right.
Here's a solution where security checking is disabled (for example, conversing with the localhost) Also, some of the solutions I've seen now contain deprecated methods and such.
/**
* @param configFilePath
* @param ipAddress
* @param userId
* @param password
* @throws MalformedURLException
*/
public Upgrade(String aConfigFilePath, String ipAddress, String userId, String password) {
configFilePath = aConfigFilePath;
baseUri = "https://" + ipAddress + ":" + PORT + "/";
restTemplate = new RestTemplate(createSecureTransport(userId, password, ipAddress, PORT));
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
}
ClientHttpRequestFactory createSecureTransport(String username,
String password, String host, int port) {
HostnameVerifier nullHostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
HttpClient client = HttpClientBuilder.create()
.setSSLHostnameVerifier(nullHostnameVerifier)
.setSSLContext(createContext())
.setDefaultCredentialsProvider(credentialsProvider).build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(client);
return requestFactory;
}
private SSLContext createContext() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
} };
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
SSLContext.setDefault(sc);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return sc;
} catch (Exception e) {
}
return null;
}
I had the same exception, this is how I solved the problem:
Preconditions:
Junit class (and test), that extended another class.
ApplicationContext initialized using spring, that init the project.
The Application context was initialized in @Before method
Solution:
Init the application context from @BeforeClass method, since the parent class also required some classes that were initialized from within the application context.
Hope this will help.
function assert_exit_code {
rc=$?; if [[ $rc != 0 ]]; then echo "$1" 1>&2; fi
}
...
execute.sh
assert_exit_code "execute.sh has failed"
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
I am a newbie and these methods are not working for me. However, I tried a margin-top property in css and simply added the value of content pixels +5.
Example: my content layout had a height of 1000px so I put a margin-top value of 1005px in the footer css which gave me a 5px border and a footer that sits delightfully at the bottom of my site.
Probably an amateur way of doing it, but EFFECTIVE!!!
I am agree with @Chad Grant
Also right if you convert to string then you can use that value as numeric as said in the question
int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2
I tried to create a more simple and understandable example
char v = '1';
int vv = (int)char.GetNumericValue(v);
char.GetNumericValue(v) returns as double and converts to (int)
More Advenced usage as an array
int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();
You should try
if (row.Table.Columns.Contains("US_OTHERFRIEND"))
I don't believe that row has a columns property itself.
A search landed me at this page, but it wasn't quite what I was looking for. Posting here in case someone else looking for what I was lands at this page too.
There is two ways to do it if you only have a string value.
.NET way:
Same as @Canavar, but you can instantiate a new Uri Object
String URL = "http://localhost:1302/TESTERS/Default6.aspx";
System.Uri uri = new System.Uri(URL);
which means you can use the same methods, e.g.
string url = uri.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string host = uri.host
// localhost
Regex way:
JToken
is the base class for JObject
, JArray
, JProperty
, JValue
, etc. You can use the Children<T>()
method to get a filtered list of a JToken's children that are of a certain type, for example JObject
. Each JObject
has a collection of JProperty
objects, which can be accessed via the Properties()
method. For each JProperty
, you can get its Name
. (Of course you can also get the Value
if desired, which is another JToken
.)
Putting it all together we have:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}
Output:
MobileSiteContent
PageContent
Just to quote Boot Docs:
You can set
spring.data.mongodb.uri
property to change the url, or alternatively specify ahost/port
. For example, you might declare the following in yourapplication.properties
:
spring.data.mongodb.host=mongoserver
spring.data.mongodb.port=27017
All available options for spring.data.mongodb
prefix are fields of MongoProperties
:
private String host;
private int port = DBPort.PORT;
private String uri = "mongodb://localhost/test";
private String database;
private String gridFsDatabase;
private String username;
private char[] password;
Directly use df.fillna(df.mean())
to fill all the null value with mean
If you want to fill null value with mean of that column then you can use this
suppose x=df['Item_Weight']
here Item_Weight
is column name
here we are assigning (fill null values of x with mean of x into x)
df['Item_Weight'] = df['Item_Weight'].fillna((df['Item_Weight'].mean()))
If you want to fill null value with some string then use
here Outlet_size
is column name
df.Outlet_Size = df.Outlet_Size.fillna('Missing')
You could do this but it is hacky
.application-title {
background:url("/path/to/image.png");
/* set these dims according to your image size */
width:500px;
height:500px;
}
.application-title img {
display:none;
}
Here is a working example:
Sessions - what Chris Thompson said.
Instantiation - a servlet is instantiated when the container receives the first request mapped to the servlet (unless the servlet is configured to load on startup with the <load-on-startup>
element in web.xml
). The same instance is used to serve subsequent requests.
In Spring Boot 2 the property in e.g. application.properties
is server.servlet.context-path=/myWebApp
to set the context path.
You'll have to make a join:
SELECT A.SalesOrderID, B.Foo
FROM A
JOIN B bo ON bo.id = (
SELECT TOP 1 id
FROM B bi
WHERE bi.SalesOrderID = a.SalesOrderID
ORDER BY bi.whatever
)
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
, assuming that b.id
is a PRIMARY KEY
on B
In MS SQL 2005
and higher you may use this syntax:
SELECT SalesOrderID, Foo
FROM (
SELECT A.SalesOrderId, B.Foo,
ROW_NUMBER() OVER (PARTITION BY B.SalesOrderId ORDER BY B.whatever) AS rn
FROM A
JOIN B ON B.SalesOrderID = A.SalesOrderID
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
) i
WHERE rn
This will select exactly one record from B
for each SalesOrderId
.
I can't recommend the use of Moment enough. If you are able to use third-party libraries, I highly recommend doing so. Beyond just formatting, it deals with timezones, parsing, durations and time travel extremely well and will pay dividends in simplicity and time (at the small expense of size, abstraction and performance).
You wanted something that looked like this:
Friday 2:00pm 1 Feb 2013
Well, with Moment all you need you to do is this:
import Moment from "moment";
Moment().format( "dddd h:mma D MMM YYYY" ); //=> "Wednesday 9:20am 9 Dec 2020"
And if you wanted to match that exact date and time, all you would need to do is this:
import Moment from "moment";
Moment( "2013-2-1 14:00:00" ).format( "dddd h:mma D MMM YYYY" ) ); //=> "Friday 2:00pm 1 Feb 2013"
There's a myriad of other formatting options that can be found here.
Go to their home page to see more detailed instructions, but if you're using npm or yarn it's as simple as:
npm install moment --save
or
yarn add moment
You should include a path to your command, since cron runs with an extensively cut-down environment. You won't have all the environment variables you have in your interactive shell session.
It's a good idea to specify an absolute path to your script/binary, or define PATH in the crontab itself. To help debug any issues I would also redirect stdout/err to a log file.
If your data.frame
is a data.table
, you can use special symbol .I
:
data[, ID := .I]
Use Shift+Del.
More info: Shift+Del combination key set a field to null when you filled a field by a value and you changed your decision and you want to make it null. It is useful and I amazed from the other answers that give strange solutions.
You may find my MSDN article on the subject helpful; I took a lot of space in that article describing when you should use async
on ASP.NET, not just how to use async
on ASP.NET.
I have some concerns using async actions in ASP.NET MVC. When it improves performance of my apps, and when - not.
First, understand that async
/await
is all about freeing up threads. On GUI applications, it's mainly about freeing up the GUI thread so the user experience is better. On server applications (including ASP.NET MVC), it's mainly about freeing up the request thread so the server can scale.
In particular, it won't:
await
. await
only "yields" to the ASP.NET thread pool, not to the browser.First question is - is it good to use async action everywhere in ASP.NET MVC?
I'd say it's good to use it everywhere you're doing I/O. It may not necessarily be beneficial, though (see below).
However, it's bad to use it for CPU-bound methods. Sometimes devs think they can get the benefits of async
by just calling Task.Run
in their controllers, and this is a horrible idea. Because that code ends up freeing up the request thread by taking up another thread, so there's no benefit at all (and in fact, they're taking the penalty of extra thread switches)!
Shall I use async/await keywords when I want to query database (via EF/NHibernate/other ORM)?
You could use whatever awaitable methods you have available. Right now most of the major players support async
, but there are a few that don't. If your ORM doesn't support async
, then don't try to wrap it in Task.Run
or anything like that (see above).
Note that I said "you could use". If you're talking about ASP.NET MVC with a single database backend, then you're (almost certainly) not going to get any scalability benefit from async
. This is because IIS can handle far more concurrent requests than a single instance of SQL server (or other classic RDBMS). However, if your backend is more modern - a SQL server cluster, Azure SQL, NoSQL, etc - and your backend can scale, and your scalability bottleneck is IIS, then you can get a scalability benefit from async
.
Third question - How many times I can use await keywords to query database asynchronously in ONE single action method?
As many as you like. However, note that many ORMs have a one-operation-per-connection rule. In particular, EF only allows a single operation per DbContext; this is true whether the operation is synchronous or asynchronous.
Also, keep in mind the scalability of your backend again. If you're hitting a single instance of SQL Server, and your IIS is already capable of keeping SQLServer at full capacity, then doubling or tripling the pressure on SQLServer is not going to help you at all.
You can pause on any XHR pattern which I find very useful during debugging these kind of scenarios.
For example I have given breakpoint on an URL pattern containing "/"
Note that you can also determine in pure js in what browser you script is beeing executed through : window.navigator.userAgent
However, that's not a recommended way as it's configurable in the browser settings. More info available there: https://developer.mozilla.org/fr/docs/DOM/window.navigator.userAgent
If you're using the ReSharper plugin, you can do that using the Shift + Alt + L shortcut or navigate via menu as shown.
The best, I think, is to use the format() function:
>>> print("financial return of outcome 1 = $ " + format(str(out1), '.2f'))
// Should print: financial return of outcome 1 = $ 752.60
But I have to say: don't use round or format when working with financial values.
I think this one is fast...
def issublist(subList, myList, start=0):
if not subList: return 0
lenList, lensubList = len(myList), len(subList)
try:
while lenList - start >= lensubList:
start = myList.index(subList[0], start)
for i in xrange(lensubList):
if myList[start+i] != subList[i]:
break
else:
return start, start + lensubList - 1
start += 1
return False
except:
return False
Try This... It's very simple just use confirm dialog box for alert with YES|NO.
if(confirm("Do you want to upgrade?")){ Your code }
I have made something for this on CodePlex.
It works by intercepting the TextChanged event. If the result is a good number it will be stored. If it is something wrong, the last good value will be restored. The source is a bit too large to publish here, but here is a link to the class that handles the core of this logic.
Run your cmd
as administrator this will solve my issues.
Thanks.
select p.post_title,m.meta_value sale_price ,n.meta_value regular_price
from wp_postmeta m
inner join wp_postmeta n
on m.post_id = n.post_id
inner join wp_posts p
ON m.post_id=p.id
and m.meta_key = '_sale_price'
and n.meta_key = '_regular_price'
AND p.post_type = 'product';
update wp_postmeta m
inner join wp_postmeta n
on m.post_id = n.post_id
inner join wp_posts p
ON m.post_id=p.id
and m.meta_key = '_sale_price'
and n.meta_key = '_regular_price'
AND p.post_type = 'product'
set m.meta_value = n.meta_value;
Here is solution for Hibernate 4.3.7.Final.
pacakge-info.java contains
@TypeDefs(
{
@TypeDef(
name = "javaUtilDateType",
defaultForType = java.util.Date.class,
typeClass = JavaUtilDateType.class
)
})
package some.pack;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
And JavaUtilDateType:
package some.other.or.same.pack;
import java.sql.Timestamp;
import java.util.Comparator;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.LiteralType;
import org.hibernate.type.StringType;
import org.hibernate.type.TimestampType;
import org.hibernate.type.VersionType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor;
import org.hibernate.type.descriptor.sql.TimestampTypeDescriptor;
/**
* Note: Depends on hibernate implementation details hibernate-core-4.3.7.Final.
*
* @see
* <a href="http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch06.html#types-custom">Hibernate
* Documentation</a>
* @see TimestampType
*/
public class JavaUtilDateType
extends AbstractSingleColumnStandardBasicType<Date>
implements VersionType<Date>, LiteralType<Date> {
public static final TimestampType INSTANCE = new TimestampType();
public JavaUtilDateType() {
super(
TimestampTypeDescriptor.INSTANCE,
new JdbcTimestampTypeDescriptor() {
@Override
public Date fromString(String string) {
return new Date(super.fromString(string).getTime());
}
@Override
public <X> Date wrap(X value, WrapperOptions options) {
return new Date(super.wrap(value, options).getTime());
}
}
);
}
@Override
public String getName() {
return "timestamp";
}
@Override
public String[] getRegistrationKeys() {
return new String[]{getName(), Timestamp.class.getName(), java.util.Date.class.getName()};
}
@Override
public Date next(Date current, SessionImplementor session) {
return seed(session);
}
@Override
public Date seed(SessionImplementor session) {
return new Timestamp(System.currentTimeMillis());
}
@Override
public Comparator<Date> getComparator() {
return getJavaTypeDescriptor().getComparator();
}
@Override
public String objectToSQLString(Date value, Dialect dialect) throws Exception {
final Timestamp ts = Timestamp.class.isInstance(value)
? (Timestamp) value
: new Timestamp(value.getTime());
// TODO : use JDBC date literal escape syntax? -> {d 'date-string'} in yyyy-mm-dd hh:mm:ss[.f...] format
return StringType.INSTANCE.objectToSQLString(ts.toString(), dialect);
}
@Override
public Date fromStringValue(String xml) throws HibernateException {
return fromString(xml);
}
}
This solution mostly relies on TimestampType implementation with adding additional behaviour through anonymous class of type JdbcTimestampTypeDescriptor.
This error will arise when using the utility pass
if the terminal window is too small!
Just make the terminal window a few lines taller.
Very confusing.
You can use the @NamedEntityGraph
annotation to your entity to create a loadable query that set which collections you want to load on your query.
The main advantage of this choice is that hibernate makes one single query to retrieve the entity and its collections and only when you choose to use this graph, like this:
Entity configuration
@Entity
@NamedEntityGraph(name = "graph.myEntity.addresesAndPersons",
attributeNodes = {
@NamedAttributeNode(value = "addreses"),
@NamedAttributeNode(value = "persons"
})
Usage
public MyEntity findNamedGraph(Object id, String namedGraph) {
EntityGraph<MyEntity> graph = em.getEntityGraph(namedGraph);
Map<String, Object> properties = new HashMap<>();
properties.put("javax.persistence.loadgraph", graph);
return em.find(MyEntity.class, id, properties);
}
Appending single space to output file with stream variable.
// declare output file stream varaible and open file
ofstream fout;
fout.open("flux_capacitor.txt");
fout << var << " ";
This is a modified version of @Aleksandr Fedorenko's answer adding a WHERE clause:
UPDATE x
SET x.CODE_DEST = x.New_CODE_DEST
FROM (
SELECT CODE_DEST, ROW_NUMBER() OVER (ORDER BY [RS_NOM]) AS New_CODE_DEST
FROM DESTINATAIRE_TEMP
) x
WHERE x.CODE_DEST <> x.New_CODE_DEST AND x.CODE_DEST IS NOT NULL
By adding a WHERE clause I found the performance improved massively for subsequent updates. Sql Server seems to update the row even if the value already exists and it takes time to do so, so adding the where clause makes it just skip over rows where the value hasn't changed. I have to say I was astonished as to how fast it could run my query.
Disclaimer: I'm no DB expert, and I'm using PARTITION BY for my clause so it may not be exactly the same results for this query. For me the column in question is a customer's paid order, so the value generally doesn't change once it is set.
Also make sure you have indexes, especially if you have a WHERE clause on the SELECT statement. A filtered index worked great for me as I was filtering based on payment statuses.
My query using PARTITION by
UPDATE UpdateTarget
SET PaidOrderIndex = New_PaidOrderIndex
FROM
(
SELECT PaidOrderIndex, SimpleMembershipUserName, ROW_NUMBER() OVER(PARTITION BY SimpleMembershipUserName ORDER BY OrderId) AS New_PaidOrderIndex
FROM [Order]
WHERE PaymentStatusTypeId in (2,3,6) and SimpleMembershipUserName is not null
) AS UpdateTarget
WHERE UpdateTarget.PaidOrderIndex <> UpdateTarget.New_PaidOrderIndex AND UpdateTarget.PaidOrderIndex IS NOT NULL
-- test to 'break' some of the rows, and then run the UPDATE again
update [order] set PaidOrderIndex = 2 where PaidOrderIndex=3
The 'IS NOT NULL' part isn't required if the column isn't nullable.
When I say the performance increase was massive I mean it was essentially instantaneous when updating a small number of rows. With the right indexes I was able to achieve an update that took the same amount of time as the 'inner' query does by itself:
SELECT PaidOrderIndex, SimpleMembershipUserName, ROW_NUMBER() OVER(PARTITION BY SimpleMembershipUserName ORDER BY OrderId) AS New_PaidOrderIndex
FROM [Order]
WHERE PaymentStatusTypeId in (2,3,6) and SimpleMembershipUserName is not null
if you need to keep only a few rows, consider
DELETE FROM tablename WHERE id NOT IN (5,124,221);
This will keep only some records and discard others.
//Inheritance
class A {
int i = 10;
public String getVal() {
return "I'm 'A'";
}
}
class B extends A {
int j = 20;
public String getVal() {
return "I'm 'B'";
}
}
class C extends B {
int k = 30;
public String getVal() {
return "I'm 'C'";
}
}
//Methods
public static boolean isInheritedClass(Object parent, Object child) {
if (parent == null || child == null) {
return false;
} else {
return isInheritedClass(parent.getClass(), child.getClass());
}
}
public static boolean isInheritedClass(Class<?> parent, Class<?> child) {
if (parent == null || child == null) {
return false;
} else {
if (parent.isAssignableFrom(child)) {
// is child or same class
return parent.isAssignableFrom(child.getSuperclass());
} else {
return false;
}
}
}
// Test the code
System.out.println("isInheritedClass(new A(), new B()):" + isInheritedClass(new A(), new B()));
System.out.println("isInheritedClass(new A(), new C()):" + isInheritedClass(new A(), new C()));
System.out.println("isInheritedClass(new A(), new A()):" + isInheritedClass(new A(), new A()));
System.out.println("isInheritedClass(new B(), new A()):" + isInheritedClass(new B(), new A()));
System.out.println("isInheritedClass(A.class, B.class):" + isInheritedClass(A.class, B.class));
System.out.println("isInheritedClass(A.class, C.class):" + isInheritedClass(A.class, C.class));
System.out.println("isInheritedClass(A.class, A.class):" + isInheritedClass(A.class, A.class));
System.out.println("isInheritedClass(B.class, A.class):" + isInheritedClass(B.class, A.class));
//Result
isInheritedClass(new A(), new B()):true
isInheritedClass(new A(), new C()):true
isInheritedClass(new A(), new A()):false
isInheritedClass(new B(), new A()):false
isInheritedClass(A.class, B.class):true
isInheritedClass(A.class, C.class):true
isInheritedClass(A.class, A.class):false
isInheritedClass(B.class, A.class):false
The way a select box is rendered is determined by the browser itself. So every browser will show you the height of the option list box in another height. You can't influence that. The only way you can change that is to make an own select from the scratch.
Use block level buttons, those that span the full width of a parent
You can achieve this by adding btn-block
class your button element.
Documentation here
If you need to copy object please refer to object cloning, because objects are passed by reference, which is good for performance by the way, object creation is expensive.
Here is article to refer to: Deep cloning objects
Hi This is my solution
Javascript code
var base64before = document.querySelector('img').src;
var base64 = base64before.replace(/^data:image\/(png|jpg);base64,/, "");
var httpPost = new XMLHttpRequest();
var path = "your url";
var data = JSON.stringify(base64);
httpPost.open("POST", path, false);
// Set the content type of the request to json since that's what's being sent
httpPost.setRequestHeader('Content-Type', 'application/json');
httpPost.send(data);
This is my Java code.
public void saveImage(InputStream imageStream){
InputStream inStream = imageStream;
try {
String dataString = convertStreamToString(inStream);
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
// write the image to a file
File outputfile = new File("/Users/paul/Desktop/testkey/myImage.png");
ImageIO.write(image, "png", outputfile);
}catch(Exception e) {
System.out.println(e.getStackTrace());
}
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
Again, not a direct answer to the question, but was led here by a web search. Ended up exposing the inner function without using return, etc. by simply assigning it to a global variable.
var fname;
function outer() {
function inner() {
console.log("hi");
}
fname = inner;
}
Now just
fname();
The mozilla docs for setDate() don't indicate that it will handle end of month scenarios. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
setDate()
That is why I use setTime() when I need to add days.
You can use multiple. But you can also use multiple functions inside one document.ready as well:
$(document).ready(function() {
// Jquery
$('.hide').hide();
$('.test').each(function() {
$(this).fadeIn();
});
// Reqular JS
function test(word) {
alert(word);
}
test('hello!');
});
Just add UILongPressGestureRecognizer to the given prototype cell in storyboard, then pull the gesture to the viewController's .m file to create an action method. I made it as I said.
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
<a href="#test100">Test link</a>
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?
Also, to use your new namespaced class you can also do
var jenine:com.newnamespace.subspace.Jenine = com.newnamespace.subspace.Jenine()
Find the <SHA#>
for the commit you want to go. You can find it in github or by typing git log
or git reflog show
at the command line and then do
git reset --hard <SHA#>
How about putting all content inside link?
<li><a href="#" onClick="..." ... >Backpack <img ... /></a></li>
Seems like the most natural thing to try.
Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.
Try something like this:
start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"
It's pretty straightforward with some simple rules:
then
, return it - any promise you don't return will not be waited for outside..all
them - that way it waits for all the promises and no error from any of them are silenced.then
s, you can typically return in the middle - then
chains are usually at most 1 level deep.And some tips:
.map
than with for/push
- if you're mapping values with a function, map
lets you concisely express the notion of applying actions one by one and aggregating the results.Promise.all
than to execute things one after the other - each waiting before the next.Ok, so let's get started:
var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns
var actions = items.map(fn); // run the function over all items
// we now have a promises array and we want to wait for it
var results = Promise.all(actions); // pass array of promises
results.then(data => // or just .then(console.log)
console.log(data) // [2, 4, 6, 8, 10]
);
// we can nest this of course, as I said, `then` chains:
var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
data => Promise.all(data.map(fn))
).then(function(data){
// the next `then` is executed after the promise has returned from the previous
// `then` fulfilled, in this case it's an aggregate promise because of
// the `.all`
return Promise.all(data.map(fn));
}).then(function(data){
// just for good measure
return Promise.all(data.map(fn));
});
// now to get the results:
res2.then(function(data){
console.log(data); // [16, 32, 48, 64, 80]
});
Are you trying to make it responsive? If you are then I would just recommend the following:
.tales {
width: 100%;
}
.carousel-inner{
width:100%;
max-height: 200px !important;
}
However, the best way to handle this responsively would be thru the use of media queries like such:
/* Smaller than standard 960 (devices and browsers) */
@media only screen and (max-width: 959px) {}
/* Tablet Portrait size to standard 960 (devices and browsers) */
@media only screen and (min-width: 768px) and (max-width: 959px) {}
/* All Mobile Sizes (devices and browser) */
@media only screen and (max-width: 767px) {}
/* Mobile Landscape Size to Tablet Portrait (devices and browsers) */
@media only screen and (min-width: 480px) and (max-width: 767px) {}
/* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */
@media only screen and (max-width: 479px) {}
This is fastest way I know of, even though you said you didn't want to use regular expressions:
Regex.Replace(XML, @"\s+", "")
The slider
object contains the slide count as property.
$('.slideshow').slick({
slide: 'img',
autoplay: true,
dots: true,
dotsClass: 'custom_paging',
customPaging: function (slider, i) {
//FYI just have a look at the object to find available information
//press f12 to access the console in most browsers
//you could also debug or look in the source
console.log(slider);
return (i + 1) + '/' + slider.slideCount;
}
});
var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');
$slickElement.on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
//currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
var i = (currentSlide ? currentSlide : 0) + 1;
$status.text(i + '/' + slick.slideCount);
});
$slickElement.slick({
slide: 'img',
autoplay: true,
dots: true
});
var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');
$slickElement.on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
//currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
var i = (currentSlide ? currentSlide : 0) + 1;
$status.text(i + '/' + slick.slideCount);
});
$slickElement.slick({
autoplay: true,
dots: true
});
slidesToShow
var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');
$slickElement.on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
// no dots -> no slides
if(!slick.$dots){
return;
}
//currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
var i = (currentSlide ? currentSlide : 0) + 1;
// use dots to get some count information
$status.text(i + '/' + (slick.$dots[0].children.length));
});
$slickElement.slick({
infinite: false,
slidesToShow: 4,
autoplay: true,
dots: true
});
If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
// handle route changes
});
});
Just do the database operations in a separate Thread. Like this (Kotlin):
Thread {
//Do your database´s operations here
}.start()
In Postgresql:
select *
from comments
where id in (1,3,2,4)
order by position(id::text in '1,3,2,4')
Use the correct call: strptime
is a classmethod of the datetime.datetime
class, it's not a function in the datetime
module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime
, which would bind the datetime
name to the datetime
class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime
: that's the module (that's what you have right now).from datetime import datetime
: that's the class.Turn the string into array, cut a character at specified index and turn back to string
let str = 'Hello World'.split('')
str.splice(3, 1)
str = str.join('')
// str = 'Helo World'.
list
has a count
method:
>>> [True,True,False].count(True)
2
This is actually more efficient than sum
, as well as being more explicit about the intent, so there's no reason to use sum
:
In [1]: import random
In [2]: x = [random.choice([True, False]) for i in range(100)]
In [3]: %timeit x.count(True)
970 ns ± 41.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %timeit sum(x)
1.72 µs ± 161 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Here's how I do it, which I think is the most straightforward way to do it:
var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2
IMHO the method UserForm_Initialize should remain private bacause it is event handler for Initialize event of the UserForm.
This event handler is called when new instance of the UserForm is created. In this even handler u can initialize the private members of UserForm1 class.
Example:
Standard module code:
Option Explicit
Public Sub Main()
Dim myUserForm As UserForm1
Set myUserForm = New UserForm1
myUserForm.Show
End Sub
User form code:
Option Explicit
Private m_initializationDate As Date
Private Sub UserForm_Initialize()
m_initializationDate = VBA.DateTime.Date
MsgBox "Hi from UserForm_Initialize event handler.", vbInformation
End Sub
Using the DataFormatter
this issue is resolved. Thanks to "Gagravarr" for the initial post.
DataFormatter formatter = new DataFormatter();
String empno = formatter.formatCellValue(cell0);
Here is another experience I'd like to share with you guys. The problem showed up after I implemented the following code to check for BLE access permission:
final String requiredPermission = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && targetSdkVersion >= Build.VERSION_CODES.Q) ?
android.Manifest.permission.ACCESS_FINE_LOCATION :
android.Manifest.permission.ACCESS_COARSE_LOCATION;
I meant to distinguish between FINE and COARSE location permission requests, both had been defined in the manifest. When checking for ACCESS_COARSE_LOCATION permission, the "Request permission" dialog never poped up but onRequestPermissionsResult
was always called with PERMISSION_DENIED (in case permission was not enabled in app settings). So I removed the check for BUILD.SDK and checked only for ACCESS_FINE_LOCATION
and voilla the missing dialog showed up.
final String requiredPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
did the trick.
The Manifest source contains:
<uses-permission android:name="android.permission.COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
but the apk contained android.permission.ACCESS_FINE_LOCATION
only. Sometime during build, the COARSE_LOCATION
had been removed.
I hope this might help somebody having the same issue.
Here is what I did to solve just by 2 ways:
make ID column as int
type
if you are using autogenerate in ID dont assing value in the setter of ID. If your mapping the some then sometimes autogenetated ID is not concedered. (I dont know why)
try using @GeneratedValue(strategy=GenerationType.SEQUENCE)
if possible
Your function prototype states your function will return a char. Thus, you can't return a string in your function.
Set the JRE in the project (project properties -> Java Build Path-> Libraries, typically last entry), or global default in preferences (Java->Installed JREs) to a JDK, not a JRE.
Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.
To change the priority of the connections:
Issue because connection establishment or communication with a client failed to complete within the allotted time interval. This may be a result of network or system delays.
Best option would be
Add a compare validator to the web form. Set its controlToValidate. Set its Type property to Date. Set its operator property to DataTypeCheck eg:
<asp:CompareValidator
id="dateValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="txtDatecompleted"
ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>
If this error appears whenever you click on the <a>
tag. Try the code below.
CORRECT :
<a href="javascript:void(0)">
This malfunction occurs because your href is set to # inside of your <a>
tag. Basically, your app is trying to find href which does not exist. The right way to set empty href is shown above.
WRONG :
<a href="#">
Remove the dot and import absolute_import in the beginning of your file
from __future__ import absolute_import
from p_02_paying_debt_off_in_a_year import compute_balance_after
I think it is because %
has often be associated with the modulus operator in many programming languages.
It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).
Check permissions for you upload directory. You can find its path inside /etc/phpmyadmin/apache.conf
file.
In my case (Ubuntu 14.04) it was:
php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
So I checked permissions for /var/lib/phpmyadmin/tmp
and it turns out that the directory wasn't writable for my Apache user (which is by default www-data
). It could be the case especially if you changed your apache user like I do.
select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/
Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.
The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:
SQL> create table t23 (id number not null primary key)
2 /
Table created.
SQL> select constraint_name, constraint_type
2 from user_constraints
3 where table_name = 'T23'
4 /
CONSTRAINT_NAME C
------------------------------ -
SYS_C00935190 C
SYS_C00935191 P
SQL>
'C'
for check, 'P'
for primary.
Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191
.
To be honest most people don't bother naming NOT NULL constraints.
you can try this way
Pseudocode
var ifr = document.createElement('iframe');
var frm = document.createElement('form');
frm.setAttribute("action", "yoururl");
frm.setAttribute("method", "post");
// create hidden inputs, add them
// not shown, but similar (create, setAttribute, appendChild)
ifr.appendChild(frm);
document.body.appendChild(ifr);
frm.submit();
You probably want to style the iframe, to be hidden and absolutely positioned. Not sure cross site posting will be allowed by the browser, but if so, this is how to do it.
Try the following, in order:
Smaller buffer size. Writing ~2 MiB at a time might be a good start. On my last laptop, ~512 KiB was the sweet spot, but I haven't tested on my SSD yet.
Note: I've noticed that very large buffers tend to decrease performance. I've noticed speed losses with using 16-MiB buffers instead of 512-KiB buffers before.
Use _open
(or _topen
if you want to be Windows-correct) to open the file, then use _write
. This will probably avoid a lot of buffering, but it's not certain to.
Using Windows-specific functions like CreateFile
and WriteFile
. That will avoid any buffering in the standard library.
I would suggest that you do not use the solutions that use a <span>
wrapper because it isn't valid HTML, which could cause problems down the road. I think the preferred solution is to actually remove any options that you wish to hide, and restore them as needed. Using jQuery, you'll only need these 3 functions:
The first function will save the original contents of the select. Just to be safe, you may want to call this function when you load the page.
function setOriginalSelect ($select) {
if ($select.data("originalHTML") == undefined) {
$select.data("originalHTML", $select.html());
} // If it's already there, don't re-set it
}
This next function calls the above function to ensure that the original contents have been saved, and then simply removes the options from the DOM.
function removeOptions ($select, $options) {
setOriginalSelect($select);
$options.remove();
}
The last function can be used whenever you want to "reset" back to all the original options.
function restoreOptions ($select) {
var ogHTML = $select.data("originalHTML");
if (ogHTML != undefined) {
$select.html(ogHTML);
}
}
Note that all these functions expect that you're passing in jQuery elements. For example:
// in your search function...
var $s = $('select.someClass');
var $optionsThatDontMatchYourSearch= $s.find('options.someOtherClass');
restoreOptions($s); // Make sure you're working with a full deck
removeOptions($s, $optionsThatDontMatchYourSearch); // remove options not needed
Here is a working example: http://jsfiddle.net/9CYjy/23/
I had the same problem. You can list the regex matches in a new tab, every match in new line in PSPad Editor, which is very similar as Notepad++.
Hit Ctrl + F to search, check the regexp opion, put the regexp and click on List.
I had the same problem. When i was trying and testing on a browser on my PC machine i didn't have the "not a function" error, but when i tried on a virtual machine the error was popping. I'd solved it by adding the slick files on my web server and adding the urls of the css and js files from my web server to my html. Before that i was pulling the css and js from CDN.
Solution 1:
clang++ your.cpp
Solution 2:
clang your.cpp -lstdc++
Solution 3:
clang -x c++ your.cpp
It may be worth pointing out that ?
s are only allowed in method names, not variables. In the process of learning Ruby, I assumed that ?
designated a boolean return type so I tried adding them to flag variables, leading to errors. This led to me erroneously believing for a while that there was some special syntax involving ?
s.
Relevant: Why can't a variable name end with `?` while a method name can?
If some one is still finding difficulties, i have made a video on this
https://www.youtube.com/watch?v=tbLAHKhjjI4
Because the new version of Apple does not support bash shell so i have explained in details how do we set variables in 2020.
Well first you try to assign strings not chars, even if they are just one character. use ',' instead of ",". Next thing is, enums only take integral types without char
you could use the unicode value, but i would strongly advice you not to do so.
If you are certain that these values stay the same, in differnt cultures and languages, i would use a static class with const strings.
The normal idea would be to run the command and then use $?
to get the exit code. However, some times you have multiple cases in which you need to get the exit code. For example, you might need to hide it's output but still return the exit code, or print both the exit code and the output.
ec() { [[ "$1" == "-h" ]] && { shift && eval $* > /dev/null 2>&1; ec=$?; echo $ec; } || eval $*; ec=$?; }
This will give you the option to suppress the output of the command you want the exit code for. When the output is suppressed for the command, the exit code will directly be returned by the function.
I personally like to put this function in my .bashrc
file
Below I demonstrate a few ways in which you can use this:
# In this example, the output for the command will be
# normally displayed, and the exit code will be stored
# in the variable $ec.
$ ec echo test
test
$ echo $ec
0
# In this example, the exit code is output
# and the output of the command passed
# to the `ec` function is suppressed.
$ echo "Exit Code: $(ec -h echo test)"
Exit Code: 0
# In this example, the output of the command
# passed to the `ec` function is suppressed
# and the exit code is stored in `$ec`
$ ec -h echo test
$ echo $ec
0
Solution to your code using this function
#!/bin/bash
if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then
echo "Error when executing command: 'grep p' [$ec]"
exit $ec;
fi
You should also note that the exit code you will be seeing will be for the
grep
command that's being run, as it is the last command being executed. Not thels
.
public void DeleteUserIMP(UserIMP useriamp) {
synchronized (ListUserIMP) {
if (ListUserIMP.isEmpty()) {
System.out.println("user is empty");
} else {
Iterator<UserIMP> it = ListUserIMP.iterator();
while (it.hasNext()) {
UserIMP user = it.next();
if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
it.remove();
System.out.println("remove it");
}
}
// ListUserIMP.remove(useriamp);
System.out.println(" this user removed");
}
Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
// System.out.println("This user Deleted " + Constants.MESSAGE_OK);
}
}
__construct is always called when creating new objects or they are invoked when initialization takes place.it is suitable for any initialization that the object may need before it is used. __construct method is the first method executed in class.
class Test
{
function __construct($value1,$value2)
{
echo "Inside Construct";
echo $this->value1;
echo $this->value2;
}
}
//
$testObject = new Test('abc','123');
In Java 8 you can use CompletableFuture. Here's an example I had in my code where I'm using it to fetch users from my user service, map them to my view objects and then update my view or show an error dialog (this is a GUI application):
CompletableFuture.supplyAsync(
userService::listUsers
).thenApply(
this::mapUsersToUserViews
).thenAccept(
this::updateView
).exceptionally(
throwable -> { showErrorDialogFor(throwable); return null; }
);
It executes asynchronously. I'm using two private methods: mapUsersToUserViews
and updateView
.
Basically set up your css like:
element {
border: 1px solid #fff;
transition: border .5s linear;
}
element.saved {
border: 1px solid transparent;
}
in python intended block mean there is every thing must be written in manner in my case I written it this way
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code
def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)
Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:
String value = "";//any text you are pre-filling in the EditText
final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (et.getCompoundDrawables()[2] == null) {
return false;
}
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
et.setText("");
et.setCompoundDrawables(null, null, null, null);
}
return false;
}
});
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
}
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
If you're really talking about the static text
<title>Foo & Bar</title>
stored in some file on the hard disk and served directly by a server, then yes: it probably doesn't need to be escaped.
However, since there is very little HTML content nowadays that's completely static, I'll add the following disclaimer that assumes that the HTML content is generated from some other source (database content, user input, web service call result, legacy API result, ...):
If you don't escape a simple &
, then chances are you also don't escape a &
or a
or <b>
or <script src="http://attacker.com/evil.js">
or any other invalid text. That would mean that you are at best displaying your content wrongly and more likely are suspectible to XSS attacks.
In other words: when you're already checking and escaping the other more problematic cases, then there's almost no reason to leave the not-totally-broken-but-still-somewhat-fishy standalone-& unescaped.
Posting it here as it might help others. In string it might be necessary to pass the quotes to jq. To do the following with jq:
.items[] | select(.name=="string")
in bash you could do
EMAILID=$1
projectID=$(cat file.json | jq -r '.resource[] | select(.username=='\"$EMAILID\"') | .id')
essentially escaping the quotes and passing it on to jq
I am not sure but as per my knowledge I share my views. I always accept best answer if I am wrong .
Alarm Manager
The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive()
method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive()
returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive()
method completes. If your alarm receiver called Context.startService()
, it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver
and Service
will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
Timer
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
\\ here your todo;
}
}, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));
Timer
has some drawbacks that are solved by ScheduledThreadPoolExecutor
. So it's not the best choice
ScheduledThreadPoolExecutor.
You can use java.util.Timer
or ScheduledThreadPoolExecutor
(preferred) to schedule an action to occur at regular intervals on a background thread.
Here is a sample using the latter:
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
// call service
}
}, 0, 10, TimeUnit.MINUTES);
So I preferred ScheduledExecutorService
But Also think about that if the updates will occur while your application is running, you can use a Timer
, as suggested in other answers, or the newer ScheduledThreadPoolExecutor
.
If your application will update even when it is not running, you should go with the AlarmManager
.
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.
My script:
echo "WARNINGS: $warningsFound WARNINGS FOUND:\n$warningStrings
Output:
WARNING : 2 WARNINGS FOUND:\nWarning, found the following local orphaned signature file:
On my bash script I was getting mad as you until I've just tried:
echo "WARNING : $warningsFound WARNINGS FOUND:
$warningStrings"
Just hit enter where you want to insert that jump. Output now is:
WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:
Try to use this free way to this, https://freenetexcel.codeplex.com
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"..\..\parts.xls",ExcelVersion.Version97to2003);
//Initialize worksheet
Worksheet sheet = workbook.Worksheets[0];
DataTable dataTable = sheet.ExportDataTable();
Thanks to @Birchlabs' comment, now it is tons easier with this special Mac-only DNS name available:
docker run -e DB_PORT=5432 -e DB_HOST=docker.for.mac.host.internal
From 17.12.0-cd-mac46, docker.for.mac.host.internal
should be used instead of docker.for.mac.localhost
. See release note for details.
@helmbert's answer well explains the issue. But Docker for Mac does not expose the bridge network, so I had to do this trick to workaround the limitation:
$ sudo ifconfig lo0 alias 10.200.10.1/24
Open /usr/local/var/postgres/pg_hba.conf
and add this line:
host all all 10.200.10.1/24 trust
Open /usr/local/var/postgres/postgresql.conf
and edit change listen_addresses
:
listen_addresses = '*'
Reload service and launch your container:
$ PGDATA=/usr/local/var/postgres pg_ctl reload
$ docker run -e DB_PORT=5432 -e DB_HOST=10.200.10.1 my_app
What this workaround does is basically same with @helmbert's answer, but uses an IP address that is attached to lo0
instead of docker0
network interface.
Now that jQuery adapter exists, this answer needs to be updated:
Say you initiated the editor with $('.ckeditor').ckeditor(opt)
then you get the value with $('.ckeditor').val()
If you backup a table in Oracle Database. You try the statement below.
CREATE TABLE name_table_bk
AS
SELECT *
FROM name_table;
I am using Oracle Database 12c.
For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:
# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
Model.where(attributes).first || Model.create(attributes)
end
Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.
Define a function like this:
getUserName() {
echo $1 | cut -d : -f 1 | xargs basename
}
And pass the string as a parameter:
userName=$(getUserName "/var/cpanel/users/joebloggs:DNS9=domain.com")
echo $userName
I had same issue . I passed my data as key->value in "Body" section by choosing "form-data" option and it worked fine.
[Update April 2016] This answer is now outdated, custom naked domain mapping is supported, see Lawrence Mok's answer.
I have figured it out!
First off: it is impossible to link something like mydomain.com
with your appspot app. This is considered a naked domain, which is not supported by Google App Engine (anymore). Strictly speaking, the answer to my question has to be "impossible". Read on...
All you can do is add subdomains pointing to your app, e.g myappid.mydomain.com
. The key to get your top level domain linked to your app is to realize that www
is a subdomain like any other!
myappid.mydomain.com
is treated exactly the same as www.mydomain.com
!
Here are the steps:
www
and click Addwww
for your domain and point to ghs.googlehosted.com
Now you have www.mydomain.com
linked to your app.
I wished this would have been more obvious in the documentation...Good luck!
Also i got this error if i had the comment in tn top level of template among with the actual root element.
<!-- Just a commented out stuff -->
<div>test of {{value}}</div>
This answer does not directly answer the question but may be a good solution outside of the box.
I upvoted gnovice's solution, but want to offer another solution: Use the system dependent command of your operating system:
tic
asdfList = getAllFiles('../TIMIT_FULL/train');
toc
% Elapsed time is 19.066170 seconds.
tic
[status,cmdout] = system('find ../TIMIT_FULL/train/ -iname "*.wav"');
C = strsplit(strtrim(cmdout));
toc
% Elapsed time is 0.603163 seconds.
Positive:
*.wav
files.Negative: