There is an example in the official python docs about how to use sscanf
from libc
:
# import libc
from ctypes import CDLL
if(os.name=="nt"):
libc = cdll.msvcrt
else:
# assuming Unix-like environment
libc = cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6") # alternative
# allocate vars
i = c_int()
f = c_float()
s = create_string_buffer(b'\000' * 32)
# parse with sscanf
libc.sscanf(b"1 3.14 Hello", "%d %f %s", byref(i), byref(f), s)
# read the parsed values
i.value # 1
f.value # 3.14
s.value # b'Hello'
To get the 2 chars ISO 639-1 language identifier use:
System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
Another possibility for windows would be to have a directory filled with .bat files that have your shortcuts in them. The name of the file is the shortcut to be used. Simply add the directory to your PATH environment variable and you have all the shortcuts to your disposal in the cmd window.
For example (gc.bat):
git commit -m %1
Then you can execute the following command in the console:
gc "changed stuff"
The reason I'm adding this as an answer is because when using this you aren't limited to git ...
only commands.
I tried several, and Procyon seemed to work the best for me. It's under active development and supports many features of the latest versions of Java.
These are the others I tried:
-skip
command-line flag so it wouldn't stop on errors. Actively developed, and interestingly enough it's written in Python.I know this post is old, however, to get the effect you are looking for, you may want to try the following:
#define TAKE_ADVANTAGE
/* Forward declaration of "struct Cell" as type Cell. */
typedef struct Cell Cell;
#ifdef TAKE_ADVANTAGE
/*
Define Cell structure taking advantage of forward declaration.
*/
struct Cell
{
int isParent;
Cell *child;
};
#else
/*
Or...you could define it as other posters have mentioned without taking
advantage of the forward declaration.
*/
struct Cell
{
int isParent;
struct Cell *child;
};
#endif
/*
Some code here...
*/
/* Use the Cell type. */
Cell newCell;
In either of the two cases mentioned in the code fragment above, you MUST declare your child Cell structure as a pointer. If you do not, then you will get the "field 'child' has incomplete type" error. The reason is that "struct Cell" must be defined in order for the compiler to know how much space to allocate when it is used.
If you attempt to use "struct Cell" inside the definition of "struct Cell", then the compiler cannot yet know how much space "struct Cell" is supposed to take. However, the compiler already knows how much space a pointer takes, and (with the forward declaration) it knows that "Cell" is a type of "struct Cell" (although it doesn't yet know how big a "struct Cell" is). So, the compiler can define a "Cell *" within the struct that is being defined.
Maven absolutely was designed for this type of dependency.
mvn package
won't install anything in your local repository it just packages the project and leaves it in the target folder.
Do mvn install
in parent project (A), with this all the sub-modules will be installed in your computer's Maven repository, if there are no changes you just need to compile/package the sub-module (B) and Maven will take the already packaged and installed dependencies just right.
You just need to a mvn install
in the parent project if you updated some portion of the code.
If you only need to replace
then you can use a far simpler regex:
var textWithNBSpaceReplaced = originalText.replace(/ /g, ' ');
Also, there is a typo in your div example, it says &nnbsp;
instead of
.
In my case root cause of this issue was multiple http bindings defined at parent web site i.e. InetMgr->Sites->Mysite->properties->EditBindings. I deleted one http binding which was not required and problem got resolved.
You can copy your crontab into an image, in order for the container launched from said image to run the job.
See "Run a cron job with Docker" from Julien Boulay in his Ekito/docker-cron
:
Let’s create a new file called "
hello-cron
" to describe our job.
* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
# An empty line is required at the end of this file for a valid cron file.
If you are wondering what is 2>&1, Ayman Hourieh explains.
The following Dockerfile describes all the steps to build your image
FROM ubuntu:latest
MAINTAINER [email protected]
RUN apt-get update && apt-get -y install cron
# Copy hello-cron file to the cron.d directory
COPY hello-cron /etc/cron.d/hello-cron
# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/hello-cron
# Apply cron job
RUN crontab /etc/cron.d/hello-cron
# Create the log file to be able to run tail
RUN touch /var/log/cron.log
# Run the command on container startup
CMD cron && tail -f /var/log/cron.log
(see Gaafar's comment and How do I make apt-get
install less noisy?:
apt-get -y install -qq --force-yes cron
can work too)
As noted by Nathan Lloyd in the comments:
Quick note about a gotcha:
If you're adding a script file and telling cron to run it, remember to
RUN chmod 0744 /the_script
Cron fails silently if you forget.
OR, make sure your job itself redirect directly to stdout/stderr instead of a log file, as described in hugoShaka's answer:
* * * * * root echo hello > /proc/1/fd/1 2>/proc/1/fd/2
Replace the last Dockerfile line with
CMD ["cron", "-f"]
See also (about cron -f
, which is to say cron "foreground") "docker ubuntu cron -f
is not working"
Build and run it:
sudo docker build --rm -t ekito/cron-example .
sudo docker run -t -i ekito/cron-example
Be patient, wait for 2 minutes and your commandline should display:
Hello world
Hello world
Eric adds in the comments:
Do note that
tail
may not display the correct file if it is created during image build.
If that is the case, you need to create or touch the file during container runtime in order for tail to pick up the correct file.
See "Output of tail -f
at the end of a docker CMD
is not showing".
For Android SDK, setEndpoint solves the problem, although it's been deprecated.
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
context, "identityPoolId", Regions.US_EAST_1);
AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
s3.setEndpoint("s3.us-east-2.amazonaws.com");
Best answer:
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($arr as $a) {
// This is the line that does the checking
if (!each($arr)) echo "End!\n";
echo $a."\n";
}
If your code is dealing with XmlElements
objects (rather than XmlNodes
) then there is the method XmlElement.HasAttribute(string name).
So if you are only looking for attributes on elements (which it looks like from the OP) then it may be more robust to cast as an element, check for null, and then use the HasAttribute method.
foreach (XmlNode xNode in nodeListName)
{
XmlElement xParentEle = xNode.ParentNode as XmlElement;
if((xParentEle != null) && xParentEle.HasAttribute("split"))
{
parentSplit = xParentEle.Attributes["split"].Value;
}
}
There is a much easier way to get the smooth scroll effect without javascript. In your CSS just target the entire html tag and give it scroll-behavior: smooth;
html {_x000D_
scroll-behavior: smooth;_x000D_
}_x000D_
_x000D_
a {_x000D_
text-decoration: none;_x000D_
color: black;_x000D_
} _x000D_
_x000D_
#down {_x000D_
margin-top: 100%;_x000D_
padding-bottom: 25%;_x000D_
}
_x000D_
<html>_x000D_
<a href="#down">Click Here to Smoothly Scroll Down</a>_x000D_
<div id="down">_x000D_
<h1>You are down!</h1>_x000D_
</div>_x000D_
</html
_x000D_
The "scroll-behavior" is telling the page how it should scroll and is so much easier than using javascript. Javascript will give you more options on speed and the smoothness but this will deliver without all of the confusing code.
Using UNION
automatically removes duplicate rows unless you specify UNION ALL
:
http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx
@[User::path] ="MDS/Material/"+(DT_STR, 4, 1252) DATEPART("yy" , GETDATE())+ "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
You missed the second statement: 1) NOT LIKE A, AND 2) NOT LIKE B
SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'
Darin's answer works great. It creates a 302 redirect. Here's the code modified so that it creates a permanent 301 redirect:
<%@ Page Language="C#" %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
Response.RedirectPermanent("new.aspx");
base.OnLoad(e);
}
</script>
To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.
Click the Clone or download button and choose your method. I placed these into a dev/py/libs
directory in my user home directory. It does not matter where they are saved, because they will not be installed there.
You will need to run the following inside the setup-tools directory.
python bootstrap.py
python setup.py install
Now you can navigate to the more-itertools direcotry and install it as normal.
cd ...
) into the directory containing setup.py
python setup.py install
You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME
There are a number of properties on the StringComparer
static class that return comparers for any type of case-sensitivity you might want:
For instance, you can call
StringComparer.CurrentCultureIgnoreCase.Equals(string1, string2)
or
StringComparer.CurrentCultureIgnoreCase.Compare(string1, string2)
It's a bit cleaner than the string.Equals
or string.Compare
overloads that take a StringComparison
argument.
I worked on Access Denied for User 'root'@'localhost' (using password: YES) for several hours, I have found following solution,
The answer to this problem was that in the my.cnf located within
/etc/mysql/my.cnf
the line was either
bind-address = 127.0.0.1
(or)
bind-address = localhost
(or)
bind-address = 0.0.0.0
I should prefer that 127.0.0.1
I should also prefer 0.0.0.0, it is more flexible
because which will allow all connections
if you are using target sdk as 23 add below code in your build.gradle
android{
useLibrary 'org.apache.http.legacy'
}
additional note here: dont try using the gradle versions of those files. they are broken (28.08.15). I tried over 5 hours to get it to work. it just doesnt. not working:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
another thing dont use:
'org.apache.httpcomponents:httpclient-android:4.3.5.1'
its referring 21 api level.
Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use Exists
SELECT t1.*,t2.*
FROM books t1
WHERE EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
t2.act between @fdate and @tdate and t2.stat ='close' )
document.addEventListener('touchstart', function (e) {
e.preventDefault();
});
Do not use the ontouchmove
property to register the event handler as you are running at risk of overwriting an existing event handler(s). Use addEventListener instead (see the note about IE on the MDN page).
Beware that preventing default for the touchstart
event on the window
or document
will disable scrolling of the descending areas.
To prevent the scrolling of the document but leave all the other events intact prevent default for the first touchmove
event following touchstart
:
var firstMove;
window.addEventListener('touchstart', function (e) {
firstMove = true;
});
window.addEventListener('touchmove', function (e) {
if (firstMove) {
e.preventDefault();
firstMove = false;
}
});
The reason this works is that mobile Safari is using the first move to determine if body of the document is being scrolled. I have realised this while devising a more sophisticated solution.
In case this would ever stop working, the more sophisticated solution is to inspect the touchTarget
element and its parents and make a map of directions that can be scrolled to. Then use the first touchmove
event to detect the scroll direction and see if it is going to scroll the document or the target element (or either of the target element parents):
var touchTarget,
touchScreenX,
touchScreenY,
conditionParentUntilTrue,
disableScroll,
scrollMap;
conditionParentUntilTrue = function (element, condition) {
var outcome;
if (element === document.body) {
return false;
}
outcome = condition(element);
if (outcome) {
return true;
} else {
return conditionParentUntilTrue(element.parentNode, condition);
}
};
window.addEventListener('touchstart', function (e) {
touchTarget = e.targetTouches[0].target;
// a boolean map indicating if the element (or either of element parents, excluding the document.body) can be scrolled to the X direction.
scrollMap = {}
scrollMap.left = conditionParentUntilTrue(touchTarget, function (element) {
return element.scrollLeft > 0;
});
scrollMap.top = conditionParentUntilTrue(touchTarget, function (element) {
return element.scrollTop > 0;
});
scrollMap.right = conditionParentUntilTrue(touchTarget, function (element) {
return element.scrollWidth > element.clientWidth &&
element.scrollWidth - element.clientWidth > element.scrollLeft;
});
scrollMap.bottom =conditionParentUntilTrue(touchTarget, function (element) {
return element.scrollHeight > element.clientHeight &&
element.scrollHeight - element.clientHeight > element.scrollTop;
});
touchScreenX = e.targetTouches[0].screenX;
touchScreenY = e.targetTouches[0].screenY;
disableScroll = false;
});
window.addEventListener('touchmove', function (e) {
var moveScreenX,
moveScreenY;
if (disableScroll) {
e.preventDefault();
return;
}
moveScreenX = e.targetTouches[0].screenX;
moveScreenY = e.targetTouches[0].screenY;
if (
moveScreenX > touchScreenX && scrollMap.left ||
moveScreenY < touchScreenY && scrollMap.bottom ||
moveScreenX < touchScreenX && scrollMap.right ||
moveScreenY > touchScreenY && scrollMap.top
) {
// You are scrolling either the element or its parent.
// This will not affect document.body scroll.
} else {
// This will affect document.body scroll.
e.preventDefault();
disableScroll = true;
}
});
The reason this works is that mobile Safari is using the first touch move to determine if the document body is being scrolled or the element (or either of the target element parents) and sticks to this decision.
The problem is that you have not included bootstrap.min.css
. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
if (x instanceof Collection<?>){
}
if (x instanceof Map<?,?>){
}
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
In my case it was: - My system account contained two words -- Name and Surname, like "Vasya Pupkin", so web platform installer saw only first "Vasya", so you need to rename system user to "VasyaPupkin" without space symbol, or install under different account. - Also I've noticed error in PowerShell env path, so check System variables PSModulePath, and remove unnecessary - symbol (") (SQL server path contains error, \PowerShell\Modules")
To change Edittext’s underline color:
If you want the entire app to share this style, then you can do the following way.
(1) go to styles.xml file. Your AppTheme that inherits the parent of Theme.AppCompat.Light.DarkActionBar (in my case) will be the base parent of all they style files in your app. Change the name of it to “AppBaseTheme’. Make another style right under it that has the name of AppTheme and inherits from AppBaseTheme that you just edited. It will look like following:
<!-- Base application theme. -->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="windowActionBar">false</item>
<!--see http://www.google.com/design/spec/style/color.html#color-color-palette-->
<item name="colorPrimary">@color/material_brown_500</item>
<item name="colorPrimaryDark">@color/material_brown_700</item>
<item name="colorAccent">@color/flamingo</item>
<style name="AppTheme" parent="AppBaseTheme">
<!-- Customize your theme here. -->
</style>
Then change the “colorAccent” to whatever the color you want your EditText line color to be.
(2) If you have other values folders with style.xml, this step is very important. Because that file will inherit from your previous parent xml file. For example, I have values-19/styles.xml. This is specifically for Kitkat and above. Change its parent to AppBaseTheme and make sure to get rid of “colorAccent” so that it doesn’t override the parent’s color. Also you need to keep the items that are specific to version 19. Then it will look like this.
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowTranslucentStatus">true</item>
</style>
</resources>
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
(I don't have enough rep points to add a comment, but I want to add some clarity on the answers here)
Application.AskToUpdateLinks = False is probably not what you want.
If set to False, then MS Excel will attempt to update the links automatically it just won't prompt the user beforehand, sorta counter-intuitive.
The correct solution, if you're looking to open a file without updating links should be:
Workbook.Open(UpdateLinks:=0)
Related link: Difference in AskToUpdateLinks=False and UpdateLinks:=0
Try This with Capital Letters, Small Letters, Numeric(s) and Special Characters
function generatePassword($_len) {
$_alphaSmall = 'abcdefghijklmnopqrstuvwxyz'; // small letters
$_alphaCaps = strtoupper($_alphaSmall); // CAPITAL LETTERS
$_numerics = '1234567890'; // numerics
$_specialChars = '`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|'; // Special Characters
$_container = $_alphaSmall.$_alphaCaps.$_numerics.$_specialChars; // Contains all characters
$password = ''; // will contain the desired pass
for($i = 0; $i < $_len; $i++) { // Loop till the length mentioned
$_rand = rand(0, strlen($_container) - 1); // Get Randomized Length
$password .= substr($_container, $_rand, 1); // returns part of the string [ high tensile strength ;) ]
}
return $password; // Returns the generated Pass
}
Let's Say we need 10 Digit Pass
echo generatePassword(10);
Example Output(s) :
,IZCQ_IV\7
@wlqsfhT(d
1!8+1\4@uD
This should do it for you ^wp.*php$
Matches
wp-comments-post.php
wp.something.php
wp.php
Doesn't match
something-wp.php
wp.php.txt
I was also having the trouble to route to a different view using navlink.
My implementation was as follows and works perfectly;
<NavLink tag='li'>
<div
onClick={() =>
this.props.history.push('/admin/my- settings')
}
>
<DropdownItem className='nav-item'>
Settings
</DropdownItem>
</div>
</NavLink>
Wrap it with a div, assign the onClick handler to the div. Use the history object to push a new view.
I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.
public static readonly DependencyProperty CustomerProperty =
DependencyProperty.Register("Customer", typeof(Customer),
typeof(CustomerDetailView),
new PropertyMetadata(OnCustomerChangedCallBack));
public Customer Customer {
get { return (Customer)GetValue(CustomerProperty); }
set { SetValue(CustomerProperty, value); }
}
private static void OnCustomerChangedCallBack(
DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
CustomerDetailView c = sender as CustomerDetailView;
if (c != null) {
c.OnCustomerChanged();
}
}
protected virtual void OnCustomerChanged() {
// Grab related data.
// Raises INotifyPropertyChanged.PropertyChanged
OnPropertyChanged("Customer");
}
The answer of Pascal Thivent helped me out, too.
But if you manage your plugins within the <pluginManagement>
element, you have to define the assembly again outside of the plugin management, or else the dependencies are not packed in the jar if you run mvn install
.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>main.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins> <!-- did NOT work without this -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<!-- dependencies commented out to shorten example -->
</dependencies>
</project>
These are listed in RFC3986. See the Collected ABNF for URI to see what is allowed where and the regex for parsing/validation.
import datetime
now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)
This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration
As stated, git diff -b
or git diff --ignore-space-change
will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:
git config --global core.whitespace trailing-space
In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:
git diff --ignore-cr-at-eol
or
git config --global core.whitespace cr-at-eol
from here.
You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.
You can link libraries from cdn (Content delivery network):
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
Or link libraries locally, add css files in the css folder and jquery in js folder. You have to keep both folders in the laravel public folder then you can link like below:
<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>
or else
{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}
If you link js files and css files locally (like in the last two examples) you need to add js
and css
files to the js
and css
folders which are in public\js
or public\css
not in resources\assets
.
Please check this link. Which will allow animations like L2R, R2L, T2B, B2T animations.
This code shows animation from left to right
TranslateAnimation animate = new TranslateAnimation(0,view.getWidth(),0,0);
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
if you want to do it from R2L then use
TranslateAnimation animate = new TranslateAnimation(0,-view.getWidth(),0,0);
for top to bottom as
TranslateAnimation animate = new TranslateAnimation(0,0,0,view.getHeight());
and vice a versa..
I've been trying to just make a simple bash script that emails out html formatted content-type and all these are great but I don't want to be creating local files on the filesystem to be passing into the script and also on our version of mailx(12.5+) the -a parameter for mail doesn't work anymore since it adds an attachment and I couldn't find any replacement parameter for additional headers so the easiest way for me was to use sendmail.
Below is the simplest 1 liner I created to run in our bash script that works for us. It just basically passes the Content-Type: text/html, subject, and the body and works.
printf "Content-Type: text/html\nSubject: Test Email\nHTML BODY<b>test bold</b>" | sendmail <Email Address To>
If you wanted to create an entire html page from a variable an alternative method I used in the bash script was to pass the variable as below.
emailBody="From: <Email Address From>
Subject: Test
Content-Type: text/html; charset=\"us-ascii\"
<html>
<body>
body
<b> test bold</b>
</body>
</html>
"
echo "$emailBody" | sendmail <Email Address To>
I saw that everybody's posting their takes on the problem despite the fact that few top answers already include all the necessary info to tailor for the specific use case.
And since I want to be hip as well - here's my unnecessary and a bit cumbersome solution, which is:
a) Readable (I hope!)
b) Easily customizable
c) Doesn't print any zeroes
drum roll
function durationToDDHHMMSSMS(durms) {
if (!durms) return "??";
var HHMMSSMS = new Date(durms).toISOString().substr(11, 12);
if (!HHMMSSMS) return "??";
var HHMMSS = HHMMSSMS.split(".")[0];
if (!HHMMSS) return "??";
var MS = parseInt(HHMMSSMS.split(".")[1],10);
var split = HHMMSS.split(":");
var SS = parseInt(split[2],10);
var MM = parseInt(split[1],10);
var HH = parseInt(split[0],10);
var DD = Math.floor(durms/(1000*60*60*24));
var string = "";
if (DD) string += ` ${DD}d`;
if (HH) string += ` ${HH}h`;
if (MM) string += ` ${MM}m`;
if (SS) string += ` ${SS}s`;
if (MS) string += ` ${MS}ms`;
return string;
},
Note that this code uses ES6 template strings, I'm sure that such a smarty-pants as you are will have no difficulties replacing them with regular strings if required.
You need "VT-x supported processor" at least to run Android emulator with Hardware acceleration.
If you have enabled or installed "Hyper-V" in your windows 8 then please remove it and disable the "Hyper threading" and enable "Virtualization".
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
Not exactly answering your question, but if you could move away from your self-made wrapper then there is Simple Logging Facade for Java (SLF4J) which Hibernate has now switched to (instead of commons logging).
SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).
SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.
Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.
I got this when I accidentally passed too many parameters into a jquery function that only expected one callback parameter.
For others troubleshooting: make sure you check all your jquery function calls for extra parameters.
you want something like:
SELECT count(id), SUM(hour) as totHour, SUM(kind=1) as countKindOne;
Note that your second example was close, but the IF() function always takes three arguments, so it would have had to be COUNT(IF(kind=1,1,NULL))
. I prefer the SUM() syntax shown above because it's concise.
The default Gson implementation of Map serialization uses toString()
on the key:
Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));
Will give:
{
"java.awt.Point[x\u003d1,y\u003d2]": "a",
"java.awt.Point[x\u003d3,y\u003d4]": "b"
}
enableComplexMapKeySerialization
If you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization. This will return an array of arrays of key-value pairs:
Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));
Will return:
[
[
{
"x": 1,
"y": 2
},
"a"
],
[
{
"x": 3,
"y": 4
},
"b"
]
]
More details can be found here.
If you want to reload the page , you can easily go to your component then do :
location.reload();
Note: The command in the question uses Start-Process
, which prevents direct capturing of the target program's output. Generally, do not use Start-Process
to execute console applications synchronously - just invoke them directly, as in any shell. Doing so keeps the application connected to the calling console's standard streams, allowing its output to be captured by simple assignment $output = netdom ...
, as detailed below.
Fundamentally, capturing output from external programs works the same as with PowerShell-native commands (you may want a refresher on how to execute external programs; <command>
is a placeholder for any valid command below):
$cmdOutput = <command> # captures the command's success stream / stdout output
Note that $cmdOutput
receives an array of objects if <command>
produces more than 1 output object, which in the case of an external program means a string[1] array containing the program's output lines.
If you want to make sure that the result is always an array - even if only one object is output, type-constrain the variable as an array, or wrap the command in @()
, the array-subexpression operator):
[array] $cmdOutput = <command> # or: $cmdOutput = @(<command>)
By contrast, if you want $cmdOutput
to always receive a single - potentially multi-line - string, use Out-String
, though note that a trailing newline is invariably added:
# Note: Adds a trailing newline.
$cmdOutput = <command> | Out-String
With calls to external programs - which by definition only ever return strings in PowerShell[1] - you can avoid that by using the -join
operator instead:
# NO trailing newline.
$cmdOutput = (<command>) -join "`n"
Note: For simplicity, the above uses "`n"
to create Unix-style LF-only newlines, which PowerShell happily accepts on all platforms; if you need platform-appropriate newlines (CRLF on Windows, LF on Unix), use [Environment]::NewLine
instead.
To capture output in a variable and print to the screen:
<command> | Tee-Object -Variable cmdOutput # Note how the var name is NOT $-prefixed
Or, if <command>
is a cmdlet or advanced function, you can use common parameter
-OutVariable
/ -ov
:
<command> -OutVariable cmdOutput # cmdlets and advanced functions only
Note that with -OutVariable
, unlike in the other scenarios, $cmdOutput
is always a collection, even if only one object is output. Specifically, an instance of the array-like [System.Collections.ArrayList]
type is returned.
See this GitHub issue for a discussion of this discrepancy.
To capture the output from multiple commands, use either a subexpression ($(...)
) or call a script block ({ ... }
) with &
or .
:
$cmdOutput = $(<command>; ...) # subexpression
$cmdOutput = & {<command>; ...} # script block with & - creates child scope for vars.
$cmdOutput = . {<command>; ...} # script block with . - no child scope
Note that the general need to prefix with &
(the call operator) an individual command whose name/path is quoted - e.g., $cmdOutput = & 'netdom.exe' ...
- is not related to external programs per se (it equally applies to PowerShell scripts), but is a syntax requirement: PowerShell parses a statement that starts with a quoted string in expression mode by default, whereas argument mode is needed to invoke commands (cmdlets, external programs, functions, aliases), which is what &
ensures.
The key difference between $(...)
and & { ... }
/ . { ... }
is that the former collects all input in memory before returning it as a whole, whereas the latter stream the output, suitable for one-by-one pipeline processing.
Redirections also work the same, fundamentally (but see caveats below):
$cmdOutput = <command> 2>&1 # redirect error stream (2) to success stream (1)
However, for external commands the following is more likely to work as expected:
$cmdOutput = cmd /c <command> '2>&1' # Let cmd.exe handle redirection - see below.
Considerations specific to external programs:
External programs, because they operate outside PowerShell's type system, only ever return strings via their success stream (stdout); similarly, PowerShell only ever sends strings to external programs via the pipeline.[1]
On sending data via the pipeline to external programs, PowerShell uses the encoding stored in the $OutVariable
preference variable; which in Windows PowerShell defaults to ASCII(!) and in PowerShell [Core] to UTF-8.
On receiving data from an external program, PowerShell uses the encoding stored in [Console]::OutputEncoding
to decode the data, which in both PowerShell editions defaults to the system's active OEM code page.
See this answer for more information; this answer discusses the still-in-beta (as of this writing) Windows 10 feature that allows you to set UTF-8 as both the ANSI and the OEM code page system-wide.
If the output contains more than 1 line, PowerShell by default splits it into an array of strings. More accurately, the output lines are stored in an array of type [System.Object[]]
whose elements are strings ([System.String]
).
If you want the output to be a single, potentially multi-line string, use the -join
operator (you can alternatively pipe to Out-String
, but that invariably adds a trailing newline):
$cmdOutput = (<command>) -join [Environment]::NewLine
Merging stderr into stdout with 2>&1
, so as to also capture it as part of the success stream, comes with caveats:
To do this at the source, let cmd.exe
handle the redirection, using the following idioms (works analogously with sh
on Unix-like platforms):
$cmdOutput = cmd /c <command> '2>&1' # *array* of strings (typically)
$cmdOutput = (cmd /c <command> '2>&1') -join "`r`n" # single string
cmd /c
invokes cmd.exe
with command <command>
and exits after <command>
has finished.
Note the single quotes around 2>&1
, which ensures that the redirection is passed to cmd.exe
rather than being interpreted by PowerShell.
Note that involving cmd.exe
means that its rules for escaping characters and expanding environment variables come into play, by default in addition to PowerShell's own requirements; in PS v3+ you can use special parameter --%
(the so-called stop-parsing symbol) to turn off interpretation of the remaining parameters by PowerShell, except for cmd.exe
-style environment-variable references such as %PATH%
.
Note that since you're merging stdout and stderr at the source with this approach, you won't be able to distinguish between stdout-originated and stderr-originated lines in PowerShell; if you do need this distinction, use PowerShell's own 2>&1
redirection - see below.
Use PowerShell's 2>&1
redirection to know which lines came from what stream:
Stderr output is captured as error records ([System.Management.Automation.ErrorRecord]
), not strings, so the output array may contain a mix of strings (each string representing a stdout line) and error records (each record representing a stderr line). Note that, as requested by 2>&1
, both the strings and the error records are received through PowerShell's success output stream).
Note: The following only applies to Windows PowerShell - these problems have been corrected in PowerShell [Core] v6+, though the filtering technique by object type shown below ($_ -is [System.Management.Automation.ErrorRecord]
) can also be useful there.
In the console, the error records print in red, and the 1st one by default produces multi-line display, in the same format that a cmdlet's non-terminating error would display; subsequent error records print in red as well, but only print their error message, on a single line.
When outputting to the console, the strings typically come first in the output array, followed by the error records (at least among a batch of stdout/stderr lines output "at the same time"), but, fortunately, when you capture the output, it is properly interleaved, using the same output order you would get without 2>&1
; in other words: when outputting to the console, the captured output does NOT reflect the order in which stdout and stderr lines were generated by the external command.
If you capture the entire output in a single string with Out-String
, PowerShell will add extra lines, because the string representation of an error record contains extra information such as location (At line:...
) and category (+ CategoryInfo ...
); curiously, this only applies to the first error record.
To work around this problem, apply the .ToString()
method to each output object instead of piping to Out-String
:
$cmdOutput = <command> 2>&1 | % { $_.ToString() }
;
in PS v3+ you can simplify to:
$cmdOutput = <command> 2>&1 | % ToString
(As a bonus, if the output isn't captured, this produces properly interleaved output even when printing to the console.)
Alternatively, filter the error records out and send them to PowerShell's error stream with Write-Error
(as a bonus, if the output isn't captured, this produces properly interleaved output even when printing to the console):
$cmdOutput = <command> 2>&1 | ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) {
Write-Error $_
} else {
$_
}
}
[1] As of PowerShell 7.1, PowerShell knows only strings when communicating with external programs. There is generally no concept of raw byte data in a PowerShell pipeline. If you want raw byte data returned from an external program, you must shell out to cmd.exe /c
(Windows) or sh -c
(Unix), save to a file there, then read that file in PowerShell. See this answer for more information.
I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/
You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.
const noGuest = 3;_x000D_
_x000D_
Array(noGuest).fill(noGuest).map(guest => {_x000D_
console.log(guest);_x000D_
});
_x000D_
Example:
renderPayments(noGuest) {
return Array(noGuest).fill(noGuest).map((guess, index) => {
return(
<View key={index}>
<View><TextInput /></View>
<View><TextInput /></View>
<View><TextInput /></View>
</View>
);
}
}
Then use it where you want it
render() {
return(
const { guest } = this.state;
...
{this.renderPayments(guest)}
);
}
Hope you got the idea.
If you want to understand this in simple Javascript check Array.prototype.fill()
Dupx
Dupx is a simple *nix utility to redirect standard output/input/error of an already running process.
Motivation
I've often found myself in a situation where a process I started on a remote system via SSH takes much longer than I had anticipated. I need to break the SSH connection, but if I do so, the process will die if it tries to write something on stdout/error of a broken pipe. I wish I could suspend the process with ^Z and then do a
bg %1 >/tmp/stdout 2>/tmp/stderr
Unfortunately this will not work (in shells I know).
JavaScript code is usually called from the onclick
event of a link. For example, you could instead do:
In Head Section of HTML Document
<script type='text/javascript'>
function myFunction(){
//...script code
}
</script>
In Body of HTML Document
<a href="#" id="mylink" onclick="myFunction(); return false">Call JavaScript </a>
Alternatively, you can also attach your function to the link using the links' ID, and HTML DOM or a framework like JQuery.
For example:
In Head Section of HTML Document
<script type='text/javascript'>
document.getElementById("mylink").onclick = function myFunction(){ ...script code};
</script>
In Body of HTML Document
<a href="#" id="mylink">Call JavaScript </a>
Gummi is the best LaTeX editor. It is a free, open source, cross-platform, program, featuring a live preview pane.
http://gummi.midnightcoding.org/
e4 http://gummi.midnightcoding.org/wp-content/uploads/20091012-1large(1).png
Groovy is a dynamically typed language, whose syntax is very close to Java, with a number of syntax improvements that allow for lighter code and less boilerplate. It can run through an interpreter as well as being compiled, which makes it good for fast prototyping, scripts, and learning dynamic languages without having to learn a new syntax (assuming you know Java). As of Groovy 2.0, it also has growing support for static compilation. Groovy supports closures and has support for programming in a somewhat functional style, although it's still fairly far from the traditional definition of functional programming.
Clojure is a dialect of Lisp with a few advanced features like Software Transactional Memory. If you like Lisp and would like to use something like it under the JVM, Clojure is for you. It's possibly the most functional language running on the JVM, and certainly the most famous one. Also, it has a stronger emphasis on immutability than other Lisp dialects, which takes it closer to the heart of functional language enthusiasts.
Scala is a fully object oriented language, more so than Java, with one of the most advanced type systems available on non-research languages, and certainly the most advanced type system on the JVM. It also combines many concepts and features of functional languages, without compromising the object orientation, but its compromise on functional language characteristics put off some enthusiasts of the latter.
Groovy has good acceptance and a popular web framework in Grails. It also powers the Gradle build system, which is becoming a popular alternative to Maven. I personally think it is a language with limited utility, particularly as Jython and JRuby start making inroads on the JVM-land, compared to the others.
Clojure, even discounting some very interesting features, has a strong appeal just by being a Lisp dialect on JVM. It might limit its popularity, granted, but I expect it will have loyal community around it for a long time.
Scala can compete directly with Java, and give it a run for its money on almost all aspects. It can't compete in popularity at the moment, of course, and the lack of a strong corporate backing may hinder its acceptance on corporate environments. It's also a much more dynamic language than Java, in the sense of how the language evolves. From the perspective of the language, that's a good thing. From the perspective of users who plan on having thousands of lines of code written in it, not so.
As a final disclosure, I'm very familiar with Scala, and only acquainted with the other two.
This is big endian test from a configure script:
#include <inttypes.h>
int main(int argc, char ** argv){
volatile uint32_t i=0x01234567;
// return 0 for big endian, 1 for little endian.
return (*((uint8_t*)(&i))) == 0x67;
}
Your code looks correct but sometimes google blocks an IP when you try to send a email from an unusual location. You can try to unblock it by visiting https://accounts.google.com/DisplayUnlockCaptcha from the IP and following the prompts.
Reference: https://support.google.com/accounts/answer/6009563
If you're using jQuery-UI, you must include the jQuery UI CSS package, otherwise the UI components don't know how to be styled.
If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied.
Here's an example and some possible fixes.
Here's a demo in Stack Snippets without jquery-ui.css (doesn't work)
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
There is a project that created a Bootstrap-esque theme for jQuery-UI components called jquery-ui-bootstrap. Just grab the stylesheet from there and you should be all set.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using.
After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's autocomplete.css and theme.css to figure out what styles you'll need to manually replace.
You can use bootstrap's dropdowns.less for inspiration.
Here's a sample CSS that fits pretty well with Bootstrap's default theme:
.ui-autocomplete {
position: absolute;
z-index: 1000;
cursor: default;
padding: 0;
margin-top: 2px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.ui-autocomplete > li {
padding: 3px 20px;
}
.ui-autocomplete > li.ui-state-focus {
background-color: #DDD;
}
.ui-helper-hidden-accessible {
display: none;
}
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
.ui-autocomplete {_x000D_
position: absolute;_x000D_
z-index: 1000;_x000D_
cursor: default;_x000D_
padding: 0;_x000D_
margin-top: 2px;_x000D_
list-style: none;_x000D_
background-color: #ffffff;_x000D_
border: 1px solid #ccc_x000D_
-webkit-border-radius: 5px;_x000D_
-moz-border-radius: 5px;_x000D_
border-radius: 5px;_x000D_
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
}_x000D_
.ui-autocomplete > li {_x000D_
padding: 3px 20px;_x000D_
}_x000D_
.ui-autocomplete > li.ui-state-focus {_x000D_
background-color: #DDD;_x000D_
}_x000D_
.ui-helper-hidden-accessible {_x000D_
display: none;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group ui-widget">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group ui-widget">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control" />_x000D_
</div>_x000D_
</div>
_x000D_
Tip: Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with
.ui-autocomplete
and removedisplay: none;
.
echo "No" | copy/-Y c:\source c:\Dest\
If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:
var myID = "xxx";
var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";
The solution for the error is to add this line at the top of the code:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
First import this:
from django.http import HttpResponse
If you have the JSON already:
def your_method(request):
your_json = [{'key1': value, 'key2': value}]
return HttpResponse(your_json, 'application/json')
If you get the JSON from another HTTP request:
def your_method(request):
response = request.get('https://www.example.com/get/json')
return HttpResponse(response, 'application/json')
It's too late, however the best example, how to add pseudo element in jQuery style
$(document).ready(function(){_x000D_
$("a.dummy").css({"background":"#003d79","color":"#fff","padding": "5px 10px","border-radius": "3px","text-decoration":"none"});_x000D_
$("a.dummy").hover(function() {_x000D_
$(this).css("background-color","#0670c9")_x000D_
}).mouseout(function(){_x000D_
$(this).css({"background-color":"#003d79",});_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>_x000D_
<a class="dummy" href="javascript:void()">Just Link</a>
_x000D_
An answer without jQuery, with HTML elements as parameters:
This is a better approach that checks the real position of the elements as they are being shown on the viewport, even if they're absolute, relative or have been manipulated via transformations:
function isCollide(a, b) {
var aRect = a.getBoundingClientRect();
var bRect = b.getBoundingClientRect();
return !(
((aRect.top + aRect.height) < (bRect.top)) ||
(aRect.top > (bRect.top + bRect.height)) ||
((aRect.left + aRect.width) < bRect.left) ||
(aRect.left > (bRect.left + bRect.width))
);
}
A more complete answer would be it is not possible with ftp(at least the ftp program installed on centos 6).
Since you wanted an un-attended process, "pts"'s answer will work fine.
Do the unattended upload with curl instead of ftp:
curl -u user:password -T file ftp://server/dir/file
%40 doesn't appear to work.
[~]# ftp domain.com
ftp: connect: Connection refused
ftp> quit
[~]# ftp some_user%[email protected]
ftp: some_user%[email protected]: Name or service not known
ftp> quit
All I've got is to open the ftp program and use the domain and enter the user when asked. Usually, a password is required anyway, so the interactive nature probably isn't problematic.
[~]# ftp domain.com
Connected to domain.com (173.254.13.235).
220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 2 of 1000 allowed.
220-Local time is now 02:47. Server port: 21.
220-This is a private system - No anonymous login
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.
Name (domain.com:user): [email protected]
331 User [email protected] OK. Password required
Password:
230 OK. Current restricted directory is /
Remote system type is UNIX.
Using binary mode to transfer files.
I also had the similar issue. Logs were not creating.
Please check logger attribute name should match with your LogManager.GetLogger("name")
<logger name="Mylog">
<level value="All"></level>
<appender-ref ref="RollingLogFileAppender" />
</logger>
private static readonly ILog Log = LogManager.GetLogger("Mylog");
The problem in your initial definition of the class is that you've written:
class name(object, name):
This means that the class inherits the base class called "object", and the base class called "name". However, there is no base class called "name", so it fails. Instead, all you need to do is have the variable in the special init method, which will mean that the class takes it as a variable.
class name(object):
def __init__(self, name):
print name
If you wanted to use the variable in other methods that you define within the class, you can assign name to self.name, and use that in any other method in the class without needing to pass it to the method.
For example:
class name(object):
def __init__(self, name):
self.name = name
def PrintName(self):
print self.name
a = name('bob')
a.PrintName()
bob
Here's what worked for me in IntelliJ (Not Studio), in addition to the replies presented above:
You need to attach an Android facet to an existing Android module. To do this, select the module from the module list in 'Module Settings', hit the '+' button on top and select 'Android'. See https://www.jetbrains.com/idea/webhelp/enabling-android-support.html.
For those using Spring's Java configuration classes, you might write the following:
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClasses(Foo.class);
sessionBuilder.addAnnotatedClasses(Bar.class);
sessionBuilder.addAnnotatedClasses(Bat.class);
return sessionBuilder.buildSessionFactory();
}
I have solved this problem, please just make few changes
1- all controller class name should start with capital letter. i mean first letter of class should be capital . eg we have controler with class name Pages
so it should be Pages not pages
2- save the controller class Pages as Pages.php
not pages.php
so first letter must be capital
same for model, model class first letter should be capital and also save model class as Pages_model.php
not page_model.php
hope this will solve ur problem
Many ways
pipe your input
echo "yes
no
maybe" | your_program
redirect from a file
your_program < answers.txt
use a here document (this can be very readable)
your_program << ANSWERS
yes
no
maybe
ANSWERS
use a here string
your_program <<< $'yes\nno\nmaybe\n'
The powershell script solution:
Based on the information in the answer from @kayleeFrye_onDeck
I have created a powershell script that checks and installs the versions the user specifies, i haven't done extensive testing with it, but for my own CI (Continuous Integration) scenario it work perfectly.
The full script and info on github
The approach i used was based on checking the regkeys based on information provided here. The following is the gist of what the script does:
function Test-RegistryValue {
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$Path,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$Value
)
try {
Get-ItemProperty -Path "$($Path+$Value)" -ErrorAction Stop | Out-Null
return $true
}
catch {
return $false
}
}
The checking/downloading/silently installing based on $redistInfo
which contains the compiled information from kayleeFrye_onDeck's.
$redistInstalled = Test-RegistryValue -Path $redistInfo.RegPath -Value $redistInfo.RegValue
if($redistInstalled -eq $False) {
Invoke-WebRequest -Uri $redistInfo.DownloadUrl -OutFile $downloadTargetPath
Start-Process -FilePath $downloadTargetPath -ArgumentList "$($redistInfo.SilentInstallArgs)" -Wait -NoNewWindow | Wait-Process
}
The full script and more information can be found on github
Anyone is welcome to contribute, if i have time i will do more extensive testing of the script and keep trying to add new packages as information is added here.
Use something like this:
page1.php
<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>
Any other PHP page:
<?php
session_start();
echo $_SESSION['myValue'];
?>
A few notes to keep in mind though: You need to call session_start()
BEFORE any output, HTML, echos - even whitespace.
You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.
The setting of the variable itself can be done in one of a number of ways:
$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];
And if you want to check if the variable is set before getting a potential error, use something like this:
if(!empty($_SESSION['myValue'])
{
echo $_SESSION['myValue'];
}
else
{
echo "Session not set yet.";
}
This is how you do it:
<bean id="systemPrereqs" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" scope="prototype">
<property name="targetObject" value="#{@systemProperties}" />
<property name="targetMethod" value="putAll" />
<property name="arguments">
<util:properties>
<prop key="deployment.env">dev</prop>
</util:properties>
</property>
</bean>
But remember spring gets loaded first and then it will load this bean MethodInvokingFactoryBean. So if you are trying to use this for your test case then make sure that you use depends-on. For e.g. in this case
In case you are using it for your main class better to set this property using your pom.xml as
<systemProperty>
<name>deployment.env</name>
<value>dev</value>
</systemProperty>
path_src=./folder1
path_dst=./folder2
date=$(date +"%m%d%y")
for file_src in $path_src/*; do
file_dst="$path_dst/$(basename $file_src | \
sed "s/^\(.*\)\.\(.*\)/\1$date.\2/")"
echo mv "$file_src" "$file_dst"
done
Just pass it as normal parameters and access it in PHP using the $argv
array.
php myfile.php daily
and in myfile.php
$type = $argv[1];
For special character I normally use the Unicode definition, for the '&' for example: \u0026 if I am correct. Here is a nice reference page: http://jrgraphix.net/research/unicode_blocks.php?block=0
you would just do this
l = [0, 1, 2, 3, 4]
l.pop(0)
or l = l[1:]
Pros and Cons
Using pop you can retrieve the value
say x = l.pop(0)
x
would be 0
You can install your GCC manually
either through
sudo port install gcc46
or your download the source code from one of the mirrors from here for example here
tar xzvf gcc-4.6.0.tar.gz cd gcc-4.6.0 ./configure make
well if you have multiple version, then through you can choose one
port select --list gcc
remember port
on mac is called macport https://www.macports.org/install.php
and add add the bin into your path export PATH=$PATH:/opt/local/bin
Try this:
select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2
The number in the having should match the amount of people. If you also need the Status to be Complete
use this where
clause instead of the previous one:
where personName in ('Ryan', 'Holly') and status = 'Complete'
You have to get the host and path separately.
@[email protected]
I like using pandas.apply() with python format().
import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])
make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)
Also, it can be easily used with multiple columns...
df = pd.concat([s, s * 2], axis=1)
make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)
You can use plt.subplots_adjust to change the spacing between the subplots Link
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
I write my simplified sticky footer code with padding using LESS. This answer is probably off-topic because the question doesn't talk about padding, so if you're interested check this post for more details.
@footer-padding: 40px; // Set here the footer padding
@footer-inner-height: 150px; // Set here the footer height (without padding)
/* Calculates the overall footer height */
@footer-height: @footer-inner-height + @footer-padding*2;
html {
position: relative;
min-height: 100%;
}
body {
/* This avoids footer to overlap the page content */
margin-bottom: @footer-height;
}
footer{
/* Fix the footer on bottom and give it fixed height */
position: absolute;
bottom: 0;
width: 100%;
height: @footer-height;
padding: @footer-padding 0;
}
First of all this code snippet
char *addr=NULL;
strcpy(addr,retstring().c_str());
is invalid because you did not allocate memory where you are going to copy retstring().c_str().
As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.
I know this is an old question but on Windows, this filters the git output to the files and changed line numbers:
(git diff -p --stat) | findstr "@@ --git"
diff --git a/dir1/dir2/file.cpp b/dir1/dir2/file.cpp
@@ -47,6 +47,7 @@ <some function name>
@@ -97,7 +98,7 @@ <another functon name>
To extract the files and the changed lines from that is a bit more work:
for /f "tokens=3,4* delims=-+ " %f in ('^(git diff -p --stat .^) ^| findstr ^"@@ --git^"') do @echo %f
a/dir1/dir2/file.cpp
47,7
98,7
>>> {i:i for i in range(1, 11)}
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
The directory name seems to be case sensitive. I faced the same issue but when I provided the directory name in upper case it worked.
Add validation groups for your validator elements. This allows you distinguish between different groups which to include in validation. Add validation group also to your submit button
How about using express module?
var app = require('express')();
app.get('/',function(request,response){
response.sendFile(__dirname+'/XXX.html');
});
app.listen('8000');
then, you can use browser to get /localhost:8000
In azure data studio press "cmd+shift+p" and type "intellisense", then you will see an option to refresh intellisense cache.
Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows
function:
public class InfoWindow
{
public IntPtr Handle = IntPtr.Zero;
public FileInfo File = new FileInfo( Application.ExecutablePath );
public string Title = Application.ProductName;
public override string ToString() {
return File.Name + "\t>\t" + Title;
}
}//CLASS
/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{
internal static event EventHandler WindowActivatedChanged;
internal static Timer TimerWatcher = new Timer();
internal static InfoWindow WindowActive = new InfoWindow();
internal static void DoStartWatcher() {
TimerWatcher.Interval = 500;
TimerWatcher.Tick += TimerWatcher_Tick;
TimerWatcher.Start();
}
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
/// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
{
IntPtr shellWindow = GetShellWindow();
Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();
EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
if ( hWnd == shellWindow ) return true;
if ( !IsWindowVisible( hWnd ) ) return true;
int length = GetWindowTextLength( hWnd );
if ( length == 0 ) return true;
StringBuilder builder = new StringBuilder( length );
GetWindowText( hWnd , builder , length + 1 );
var info = new InfoWindow();
info.Handle = hWnd;
info.File = new FileInfo( GetProcessPath( hWnd ) );
info.Title = builder.ToString();
windows[hWnd] = info;
return true;
} ) , 0 );
return windows;
}
private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );
public static string GetProcessPath( IntPtr hwnd )
{
uint pid = 0;
GetWindowThreadProcessId( hwnd , out pid );
if ( hwnd != IntPtr.Zero ) {
if ( pid != 0 ) {
var process = Process.GetProcessById( (int) pid );
if ( process != null ) {
return process.MainModule.FileName.ToString();
}
}
}
return "";
}
[DllImport( "USER32.DLL" )]
private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowTextLength( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern bool IsWindowVisible( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern IntPtr GetShellWindow();
[DllImport( "user32.dll" )]
private static extern IntPtr GetForegroundWindow();
//WARN: Only for "Any CPU":
[DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );
static void TimerWatcher_Tick( object sender , EventArgs e )
{
var windowActive = new InfoWindow();
windowActive.Handle = GetForegroundWindow();
string path = GetProcessPath( windowActive.Handle );
if ( string.IsNullOrEmpty( path ) ) return;
windowActive.File = new FileInfo( path );
int length = GetWindowTextLength( windowActive.Handle );
if ( length == 0 ) return;
StringBuilder builder = new StringBuilder( length );
GetWindowText( windowActive.Handle , builder , length + 1 );
windowActive.Title = builder.ToString();
if ( windowActive.ToString() != WindowActive.ToString() ) {
//fire:
WindowActive = windowActive;
if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
Console.WriteLine( "Window: " + WindowActive.ToString() );
}
}
}//CLASS
Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...
Just try this:
Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();
If bitmapdata
is the byte array then getting Bitmap
is done like this:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
Returns the decoded Bitmap
, or null
if the image could not be decoded.
You can use String.split
(read more here) instead of charAt, you will get good results.
If you want to use charAt
for some reason then try trimming the string before you count the words that way you won't have the extra space and an extra word
Use a slice, not an arrray. Just create it using
reg := []string {"a","b","c"}
An alternative would have been to convert your array to a slice when joining :
fmt.Println(strings.Join(reg[:],","))
Read the Go blog about the differences between slices and arrays.
For deep nested object you can use my snippet for lodash > 4
const removeObjectsWithNull = (obj) => {
return _(obj)
.pickBy(_.isObject) // get only objects
.mapValues(removeObjectsWithNull) // call only for values as objects
.assign(_.omitBy(obj, _.isObject)) // save back result that is not object
.omitBy(_.isNil) // remove null and undefined from object
.value(); // get value
};
Save all Control + S Command + S
Synchronize Control + Alt + Y Command + Option + Y
Maximize/minimize editor Control + Shift + F12 Control + Command + F12
Add to favorites Alt + Shift + F Option + Shift + F
Inspect current file with current profile Alt + Shift + I Option + Shift + I
Quick switch scheme Control + (backquote) Control +
(backquote)
Open settings dialogue Control + Alt + S Command + , (comma)
Open project structure dialog Control + Alt + Shift + S Command + ; (semicolon)
Switch between tabs and tool window Control + Tab Control + Tab
Navigating and searching within Studio
Search everything (including code and menus) Press Shift twice Press Shift twice
Find Control + F Command + F
Find next F3 Command + G
Find previous Shift + F3 Command + Shift + G
Replace Control + R Command + R
Find action Control + Shift + A Command + Shift + A
Search by symbol name Control + Alt + Shift + N Command + Option + O
Find class Control + N Command + O
Find file (instead of class) Control + Shift + N Command + Shift + O
Find in path Control + Shift + F Command + Shift + F
Open file structure pop-up Control + F12 Command + F12
Navigate between open editor tabs Alt + Right/Left Arrow Control + Right/Left Arrow
Jump to source F4 / Control + Enter F4 / Command + Down Arrow
Open current editor tab in new window Shift + F4 Shift + F4
Recently opened files pop-up Control + E Command + E
Recently edited files pop-up Control + Shift + E Command + Shift + E
Go to last edit location Control + Shift + Backspace Command + Shift + Backspace
Close active editor tab Control + F4 Command + W
Return to editor window from a tool window Esc Esc
Hide active or last active tool window Shift + Esc Shift + Esc
Go to line Control + G Command + L
Open type hierarchy Control + H Control + H
Open method hierarchy Control + Shift + H Command + Shift + H
Open call hierarchy Control + Alt + H Control + Option + H
Writing code
Generate code (getters, setters, constructors, hashCode/equals, toString, new file, new class) Alt + Insert Command + N
Override methods Control + O Control + O
Implement methods Control + I Control + I
Surround with (if...else / try...catch / etc.) Control + Alt + T Command + Option + T
Delete line at caret Control + Y Command + Backspace
Collapse/expand current code block Control + minus/plus Command + minus/plus Collapse/expand all code blocks Control + Shift + minus/plus Command + Shift +
minus/plus
Duplicate current line or selection Control + D Command + D
Basic code completion Control + Space Control + Space
Smart code completion (filters the list of methods and variables by expected type)
Control + Shift + Space Control + Shift + Space
Complete statement Control + Shift + Enter Command + Shift + Enter
Quick documentation lookup Control + Q Control + J
Show parameters for selected method Control + P Command + P
Go to declaration (directly) Control + B or Control + Click Command + B or Command + Click
Go to implementations Control + Alt + B Command + Alt + B
Go to super-method/super-class Control + U Command + U
Open quick definition lookup Control + Shift + I Command + Y
Toggle project tool window visibility Alt + 1 Command + 1
Toggle bookmark F11 F3
Toggle bookmark with mnemonic Control + F11 Option + F3
Comment/uncomment with line comment Control + / Command + /
Comment/uncomment with block comment Control + Shift + / Command + Shift + /
Select successively increasing code blocks Control + W Option + Up
Decrease current selection to previous state Control + Shift + W Option + Down
Move to code block start Control + [ Option + Command + [
Move to code block end Control + ] Option + Command + ]
Select to the code block start Control + Shift + [ Option + Command + Shift + [
Select to the code block end Control + Shift + ] Option + Command + Shift + ]
Delete to end of word Control + Delete Option + Delete
Delete to start of word Control + Backspace Option + Backspace
Optimize imports Control + Alt + O Control + Option + O
Project quick fix (show intention actions and quick fixes) Alt + Enter Option + Enter
Reformat code Control + Alt + L Command + Option + L
Auto-indent lines Control + Alt + I Control + Option + I
Indent/unindent lines Tab/Shift + Tab Tab/Shift + Tab
Smart line join Control + Shift + J Control + Shift + J
Smart line split Control + Enter Command + Enter
Start new line Shift + Enter Shift + Enter
Next/previous highlighted error F2 / Shift + F2 F2 / Shift + F2
Build and run
Build Control + F9 Command + F9
Build and run Shift + F10 Control + R
Apply changes (with Instant Run) Control + F10 Control + Command + R
Debugging
Debug Shift + F9 Control + D
Step over F8 F8
Step into F7 F7
Smart step into Shift + F7 Shift + F7
Step out Shift + F8 Shift + F8
Run to cursor Alt + F9 Option + F9
Evaluate expression Alt + F8 Option + F8
Resume program F9 Command + Option + R
Toggle breakpoint Control + F8 Command + F8
View breakpoints Control + Shift + F8 Command + Shift + F8
Refactoring
Copy F5 F5
Move F6 F6
Safe delete Alt + Delete Command + Delete
Rename Shift + F6 Shift + F6
Change signature Control + F6 Command + F6
Inline Control + Alt + N Command + Option + N
Extract method Control + Alt + M Command + Option + M
Extract variable Control + Alt + V Command + Option + V
Extract field Control + Alt + F Command + Option + F
Extract constant Control + Alt + C Command + Option + C
Extract parameter Control + Alt + P Command + Option + P
Version control / local history
Commit project to VCS Control + K Command + K
Update project from VCS Control + T Command + T
View recent changes Alt + Shift + C Option + Shift + C
Open VCS popup Alt + ` (backquote) Control + V
try this
combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"
timespec_get from C11 returns up to nanoseconds, rounded to the resolution of the implementation.
#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
More details here: https://stackoverflow.com/a/36095407/895245
Had a similar problem, I propose this solution althought is not supported in IE 10 and under.
Given
<div id='example' data-example-update='1'></div>
The Javascript standard defines a property called dataset to update data-example-update.
document.getElementById('example').dataset.exampleUpdate = 2;
Note: use camel case notation to access the correct data attribute.
Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
First of all, you should never use the money datatype. If you do any calculations you will get truncated results. Run the following to see what I mean
DECLARE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)
SELECT
@mon1 = 100, @mon2 = 339, @mon3 = 10000,
@num1 = 100, @num2 = 339, @num3 = 10000
SET @mon4 = @mon1/@mon2*@mon3
SET @num4 = @num1/@num2*@num3
SELECT @mon4 AS moneyresult,
@num4 AS numericresult
Output: 2949.0000 2949.8525
Now to answer your question (it was a little vague), the money datatype always has two places after the decimal point. Use the integer datatype if you don't want the fractional part or convert to int.
Perhaps you want to use the decimal or numeric datatype?
The following solution worked well for me. Navigate to the command prompt shortcut in the start menu:
C:\Users\ your username \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt
Right click on the shortcut file to open the properties dialog. Inside the "Start in:" textbox you should see %HOMEDRIVE%%HOMEPATH%. If you want the prompt to start in C:\ just replace the variables with "C:\" (without quotes).
update
It appears that Microsoft has changed this behavior recently and so now an additional step is required. After performing the steps above copy the modified shortcut "Command Prompt" and rename it to "cmd". Then when typing "cmd" in the start menu it should once again work.
Another way, There is check box Page Layout tab with Gridlines [ ] View which should be checked.
$(document).ready(function () {
// using ascii 17 for ctrl, 18 for alt and 83 for "S"
// ctr+alt+S
var map = { 17: false, 18: false, 83: false };
$(document).keyup(function (e) {
if (e.keyCode in map) {
map[e.keyCode] = true;
if (map[17] && map[18] && map[83]) {
// Write your own code here, what you want to do
map[17] = false;
map[18] = false;
map[83] = false;
}
}
else {
// if u press any other key apart from that "map" will reset.
map[17] = false;
map[18] = false;
map[83] = false;
}
});
});
Is it "safe" to use
$_SERVER['HTTP_HOST']
for all links on a site without having to worry about XSS attacks, even when used in forms?
Yes, it's safe to use $_SERVER['HTTP_HOST']
, (and even $_GET
and $_POST
) as long as you verify them before accepting them. This is what I do for secure production servers:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$reject_request = true;
if(array_key_exists('HTTP_HOST', $_SERVER)){
$host_name = $_SERVER['HTTP_HOST'];
// [ need to cater for `host:port` since some "buggy" SAPI(s) have been known to return the port too, see http://goo.gl/bFrbCO
$strpos = strpos($host_name, ':');
if($strpos !== false){
$host_name = substr($host_name, $strpos);
}
// ]
// [ for dynamic verification, replace this chunk with db/file/curl queries
$reject_request = !array_key_exists($host_name, array(
'a.com' => null,
'a.a.com' => null,
'b.com' => null,
'b.b.com' => null
));
// ]
}
if($reject_request){
// log errors
// display errors (optional)
exit;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
echo 'Hello World!';
// ...
The advantage of $_SERVER['HTTP_HOST']
is that its behavior is more well-defined than $_SERVER['SERVER_NAME']
. Contrast ??:
Contents of the Host: header from the current request, if there is one.
with:
The name of the server host under which the current script is executing.
Using a better defined interface like $_SERVER['HTTP_HOST']
means that more SAPIs will implement it using reliable well-defined behavior. (Unlike the other.) However, it is still totally SAPI dependent ??:
There is no guarantee that every web server will provide any of these [
$_SERVER
entries]; servers may omit some, or provide others not listed here.
To understand how to properly retrieve the host name, first and foremost you need to understand that a server which contains only code has no means of knowing (pre-requisite for verifying) its own name on the network. It needs to interface with a component that supplies it its own name. This can be done via:
local config file
local database
hardcoded source code
external request (curl)
client/attacker's Host:
request
etc
Usually its done via the local (SAPI) config file. Note that you have configured it correctly, e.g. in Apache ??:
A couple of things need to be 'faked' to make the dynamic virtual host look like a normal one.
The most important is the server name which is used by Apache to generate self-referential URLs, etc. It is configured with the
ServerName
directive, and it is available to CGIs via theSERVER_NAME
environment variable.The actual value used at run time is controlled by the UseCanonicalName setting.
With
UseCanonicalName Off
the server name comes from the contents of theHost:
header in the request. WithUseCanonicalName DNS
it comes from a reverse DNS lookup of the virtual host's IP address. The former setting is used for name-based dynamic virtual hosting, and the latter is used for** IP-based hosting.If Apache cannot work out the server name because there is no
Host:
header or the DNS lookup fails then the value configured withServerName
is used instead.
min_element
and max_element
return iterators, not values. So you need *min_element...
and *max_element...
.
[id^='someId']
will match all ids starting with someId
.
[id$='someId']
will match all ids ending with someId
.
[id*='someId']
will match all ids containing someId
.
If you're looking for the name
attribute just substitute id
with name
.
If you're talking about the tag name of the element I don't believe there is a way using querySelector
Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax()
method. Or if you wanted to do it using plain javascript, here's a tutorial.
Command line arguments are accessible via String[] args
parameter of main
method.
For first argument you can check args[0]
entire code would look like
public static void main(String[] args) {
if ("a".equals(args[0])) {
// do something
}
}
I figured out this answer based on previous solution and it's comment and added some adjustments of my own. This works for me on the responsive table.
table {
display: inline-block;
overflow-x: auto;
white-space: nowrap;
// make fixed table width effected by overflow-x
max-width: 100%;
// hide all borders that make rows not filled with the table width
border: 0;
}
// add missing borders
table td {
border: 1px solid;
}
If you want to show the name of processes and kill them by the command of the kill, I recommended using this script to kill all python3 running process and set your ram memory free :
ps auxww | grep 'python3' | awk '{print $2}' | xargs kill -9
Below is the Flex-box approach to get desired result
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>Flex-box approach</title>_x000D_
<style>_x000D_
.tabs{_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
width: 500px;_x000D_
height: 250px;_x000D_
background-color: grey;_x000D_
margin: 0 auto;_x000D_
_x000D_
}_x000D_
.f{_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
margin: 20px;_x000D_
background-color: yellow;_x000D_
margin: 0 auto;_x000D_
display: inline; /*for vertically aligning */_x000D_
top: 9%; /*for vertically aligning */_x000D_
position: relative; /*for vertically aligning */_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="tabs">_x000D_
<div class="f">first</div>_x000D_
<div class="f">second</div> _x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Flex answer
.div1 {
width:300px;
background-color: grey;
border:1px solid;
overflow:auto;
display: flex;
}
.div2 {
width:150px;
background-color: #F4A460;
}
.div3 {
width:150px;
background-color: #FFFFE0;
}
Check the fiddle at http://jsfiddle.net/germangonzo/E4Zgj/575/
A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :
@Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
1
2
Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.
So this is a Queue only if used in conjunction with add.
Try this :
@Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.push(1);
queue.push(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
2
1
You can cast the numerator or the denominator to float...
int operations usually return int, so you have to change one of the operanding numbers.
This should work.
$(".formData").val("valuesgoeshere")
For empty
$(".formData").val("")
If this does not work, you should post a jsFiddle.
Demo:
$(function() {_x000D_
$(".resetInput").on("click", function() {_x000D_
$(".formData").val("");_x000D_
});_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" class="formData" value="yoyoyo">_x000D_
_x000D_
_x000D_
<button class="resetInput">Click Here to reset</button>
_x000D_
Just use
<a [ngClass]="{'disabled': your_condition}"> This a tag is disabled</a>
Example:
<a [ngClass]="{'disabled': name=='junaid'}"> This a tag is disabled</a>
Since the soft keyboard is part of the OS, more often than not, you won't be able to hide it - also, on iOS, hiding the keyboard drops focus from the element.
However, if you use the onFocus
attribute on the input, and then blur()
the text input immediately, the keyboard will hide itself and the onFocus
event can set a variable to define which text input was focused last.
Then alter your on-page keyboard to only alter the last-focused (check using the variable) text input, rather than simulating a key press.
This BFS-like solution is pretty straightforward. Simply jumps levels one-by-one.
def getHeight(self,root, method='links'):
c_node = root
cur_lvl_nodes = [root]
nxt_lvl_nodes = []
height = {'links': -1, 'nodes': 0}[method]
while(cur_lvl_nodes or nxt_lvl_nodes):
for c_node in cur_lvl_nodes:
for n_node in filter(lambda x: x is not None, [c_node.left, c_node.right]):
nxt_lvl_nodes.append(n_node)
cur_lvl_nodes = nxt_lvl_nodes
nxt_lvl_nodes = []
height += 1
return height
May be this time stamp fit you better Code
Function LastInputTimeStamp() As Date
LastInputTimeStamp = Now()
End Function
and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this
=IF(C36>0,LastInputTimeStamp(),"")
Your calculation is correct for DATE
types, but if your values are timestamps, you should probably use EXTRACT
(or DATE_PART) to be sure to get only the difference in full days;
EXTRACT(DAY FROM MAX(joindate)-MIN(joindate)) AS DateDifference
An SQLfiddle to test with. Note the timestamp difference being 1 second less than 2 full days.
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
A pivot is used to convert one of the columns in your data set from rows into columns (this is typically referred to as the spreading column). In the example you have given, this means converting the PhaseID
rows into a set of columns, where there is one column for each distinct value that PhaseID
can contain - 1, 5 and 6 in this case.
These pivoted values are grouped via the ElementID
column in the example that you have given.
Typically you also then need to provide some form of aggregation that gives you the values referenced by the intersection of the spreading value (PhaseID
) and the grouping value (ElementID
). Although in the example given the aggregation that will be used is unclear, but involves the Effort
column.
Once this pivoting is done, the grouping and spreading columns are used to find an aggregation value. Or in your case, ElementID
and PhaseIDX
lookup Effort
.
Using the grouping, spreading, aggregation terminology you will typically see example syntax for a pivot as:
WITH PivotData AS
(
SELECT <grouping column>
, <spreading column>
, <aggregation column>
FROM <source table>
)
SELECT <grouping column>, <distinct spreading values>
FROM PivotData
PIVOT (<aggregation function>(<aggregation column>)
FOR <spreading column> IN <distinct spreading values>));
This gives a graphical explanation of how the grouping, spreading and aggregation columns convert from the source to pivoted tables if that helps further.
In case you need more shorting your code, you can creating new type for helper
type Strings []string
func (ss Strings) ToInterfaceSlice() []interface{} {
iface := make([]interface{}, len(ss))
for i := range ss {
iface[i] = ss[i]
}
return iface
}
then
a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()
This could help;
Path.GetDirectoryName(Application.ExecutablePath);
also here is the reference
ViewPager.setOnPageChangeListener
is deprecated now. You now need to use ViewPager.addOnPageChangeListener
instead.
for example,
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.
var mySkus = myLines.Select(x => x.Sku);
Or if you want it as an Array just do...
var mySkus = myLines.Select(x => x.Sku).ToArray();
While this works:
<%-- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ht_tv1.Default" %> --%>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Blank._Default" %>
This won't.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" <%--Inherits="ht_tv1.Default"--%> Inherits="Blank._Default" %>
So you can't comment out part of something which is what I want to do 99.9995% of the time.
Shared service is a good solution for this issue. If you want to store some activity information too, you can add Shared Service to your main modules (app.module) provider list.
@NgModule({
imports: [
...
],
bootstrap: [
AppComponent
],
declarations: [
AppComponent,
],
providers: [
SharedService,
...
]
});
Then you can directly provide it to your components,
constructor(private sharedService: SharedService)
With Shared Service you can either use functions or you can create a Subject to update multiple places at once.
@Injectable()
export class SharedService {
public clickedItemInformation: Subject<string> = new Subject();
}
In your list component you can publish clicked item information,
this.sharedService.clikedItemInformation.next("something");
and then you can fetch this information at your detail component:
this.sharedService.clikedItemInformation.subscribe((information) => {
// do something
});
Obviously, the data that list component shares can be anything. Hope this helps.
About your command line:
root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
You are already authenticated as root
so sudo
is redundant there.
You are missing the -j
or --jump
just before the ACCEPT
parameter (just tought that was a typo and you are inserting it correctly).
About yout question:
If you are inserting the iptables
rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.
If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:
check your vmachine network settings and:
if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.
if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.
if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.
Hope this helps.
I agree with the image in absolute div with 100% width and height. Make sure you set 100% width and height for the body in the CSS and set margins and padding to zero. Another issue you will find with this method is that when selecting text, the selection area can sometimes encompass the background image, which has the unfortunate effect of making the full page have the selected state. You can get round this by using the user-select:none
CSS rule, like so:
<html>
<head>
<style type="text/css">
html,body {
height: 100%;
width: 100%
margin: none;
padding: none;
}
#background {
width: 100%;
height: 100%;
position: fixed;
left: 0px;
top: 0px;
z-index: -99999;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
#background img {
width: 100%;
height: 100%;
}
#main{ z-index:10;}
</style>
</head>
<body>
<div id="main">
content here
</div>
<div id="background"><img src="bg.jpg"></div>
</body>
</html>
Again, Internet Explorer is the bad guy here, because it doesn't recognise the user-select option - not even Internet Explorer 10 preview supports it, so you have the option of either using JavaScript to prevent background image selection (for example, http://www.felgall.com/jstip35.htm ) or using CSS 3 background-stretch method.
Also, for SEO I would put the background image at the bottom of the page, but if the background image takes too long to load (that is, with a white background initially), you could move to the top of the page.
So this question has been answered but to me the code used is not simple enough or complete. To me this bit here is what I was looking for and possibly some other people will like this as well.
string dateString = "198101";
if (DateTime.TryParse(dateString, out DateTime Temp) == true)
{
//do stuff
}
The output is stored in Temp
and not needed afterwards, datestring
is the input string to be tested.
Seems like you're #inline_content
isn't there! Remove the jQuery-Selector or check the parent elements, maybe you have a typo or forgot to add the id.
(made you a jsfiddle, works after adding a parent <div id="inline_content">
: http://jsfiddle.net/J5HdN/)
Using 'minifyEnabled'
instead of 'runProguard'
works properly.
Previous code:
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
Current code:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
Hope this helps.
TL:DR
row lock = A$5
column lock = $A5
Both = $A$5
Below are examples of how to use the Excel lock reference $
when creating your formulas
To prevent increments when moving from one row to another put the $ after the column letter and before the row number. e.g. A$5
To prevent increments when moving from one column to another put the $ before the row number. e.g. $A5
To prevent increments when moving from one column to another or from one row to another put the $ before the row number and before the column letter. e.g. $A$5
Using the lock reference will also prevent increments when dragging cells over to duplicate calculations.
You may want to take a look at this jQuery plugin. They have lots of examples on their site. http://www.asual.com/jquery/address/
This is not another answer, but more an overview and clarification to the already existed answers like Displaying Windows command prompt output and redirecting it to a file and others
I've found for myself that there is a set of issues what makes a set of tee implementations are not reliable in the Windows (Windows 7
in mine case).
I need to use specifically a tee implementation because have already uses a batch script with self redirection:
@echo off
setlocal
... some conditions here ..
rem the redirection
"%COMSPEC%" /C call %0 %* 2>&1 | "<path_to_tee_utililty>" ".log\<log_file_name_with_date_and_time>.%~nx0.log"
exit /b
:IMPL
... here the rest of script ...
The script and calls to some utilities inside the script can break the output if used together with a tee utility.
http://gnuwin32.sourceforge.net/packages/coreutils.htm
Pros:
\r
character is heavily used.Cons:
Cwrite error: No such file or directory
because seems the cmd interpreter closes the pipe/stdout too early and can not self close after that (spamming until termination).pause
command (Press any key to continue...
) in the console window.https://code.google.com/archive/p/wintee/
https://github.com/rbuhl/wintee
Pros:
pause
command (Press any key to continnue...
) in the console window.Cons:
\r
character, output is mixed and messed (https://code.google.com/archive/p/wintee/issues/7 ).http://unxutils.sourceforge.net/
https://sourceforge.net/projects/unxutils/files/unxutils/current/
Pros
\r
character.pause
command (Press any key to continnue...
) in the console window.Cons
Not yet found
http://ss64.net/westlake/nt/tee.zip
Pros:
Cons:
\r
character, output is mixed and messedpause
command (Press any key to continnue...
) in the console window AFTER a key press.https://ritchielawrence.github.io/mtee
https://github.com/ritchielawrence/mtee
Pros
\r
character.pause
command (Press any key to continnue...
) in the console window.doskey
(/E
flag, Windows command interpreter: how to obtain exit code of first piped command )Cons
So, if you are choosing the tee utility implementation between the above, then a better choice is the UnxUtils
or mtee
.
In my case value was not an integer but a String. getNameByCode method can be added to the enum to get name of a String value-
enum CODE {
SUCCESS("SCS"), DELETE("DEL");
private String status;
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status
* the status to set
*/
public void setStatus(String status) {
this.status = status;
}
private CODE(String status) {
this.status = status;
}
public static String getNameByCode(String code) {
for (int i = 0; i < CODE.values().length; i++) {
if (code.equals(CODE.values()[i].status))
return CODE.values()[i].name();
}
return null;
}
You could use the Fisher-Yates Shuffle (code adapted from this site):
function shuffle(array) {
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
In case you can't for some reason use the same Random
again and again, try initializing it with something that changes all the time, like the time itself.
new Random(new System.DateTime().Millisecond).Next();
Remember this is bad practice though.
EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN:
Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.
The code below is probably your best option:
new Random().Next();
Something like this should do the trick.
function Timer(fn, countdown) {
var ident, complete = false;
function _time_diff(date1, date2) {
return date2 ? date2 - date1 : new Date().getTime() - date1;
}
function cancel() {
clearTimeout(ident);
}
function pause() {
clearTimeout(ident);
total_time_run = _time_diff(start_time);
complete = total_time_run >= countdown;
}
function resume() {
ident = complete ? -1 : setTimeout(fn, countdown - total_time_run);
}
var start_time = new Date().getTime();
ident = setTimeout(fn, countdown);
return { cancel: cancel, pause: pause, resume: resume };
}
Here is another solution which uses any/2
map(select(any(.Names[]; contains("data"))|not)|.Id)[]
with the sample data and the -r
option it produces
cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19
This enables you to write something like:
void doSomething() {
List<String>list = new ArrayList<String>();
//do something
}
Later on, you might want to change it to:
void doSomething() {
List<String>list = new LinkedList<String>();
//do something
}
without having to change the rest of the method.
However, if you want to use a CopyOnWriteArrayList
for example, you would need to declare it as such, and not as a List if you wanted to use its extra methods (addIfAbsent for example):
void doSomething() {
CopyOnWriteArrayList<String>list = new CopyOnWriteArrayList<String>();
//do something, for example:
list.addIfAbsent("abc");
}
>>> L = [1,2,3]
>>> " ".join(str(x) for x in L)
'1 2 3'
Some details about transposing 4x4 square float (I will discuss 32-bit integer later) matrices with x86 hardware. It's helpful to start here in order to transpose larger square matrices such as 8x8 or 16x16.
_MM_TRANSPOSE4_PS(r0, r1, r2, r3)
is implemented differently by different compilers. GCC and ICC (I have not checked Clang) use unpcklps, unpckhps, unpcklpd, unpckhpd
whereas MSVC uses only shufps
. We can actually combine these two approaches together like this.
t0 = _mm_unpacklo_ps(r0, r1);
t1 = _mm_unpackhi_ps(r0, r1);
t2 = _mm_unpacklo_ps(r2, r3);
t3 = _mm_unpackhi_ps(r2, r3);
r0 = _mm_shuffle_ps(t0,t2, 0x44);
r1 = _mm_shuffle_ps(t0,t2, 0xEE);
r2 = _mm_shuffle_ps(t1,t3, 0x44);
r3 = _mm_shuffle_ps(t1,t3, 0xEE);
One interesting observation is that two shuffles can be converted to one shuffle and two blends (SSE4.1) like this.
t0 = _mm_unpacklo_ps(r0, r1);
t1 = _mm_unpackhi_ps(r0, r1);
t2 = _mm_unpacklo_ps(r2, r3);
t3 = _mm_unpackhi_ps(r2, r3);
v = _mm_shuffle_ps(t0,t2, 0x4E);
r0 = _mm_blend_ps(t0,v, 0xC);
r1 = _mm_blend_ps(t2,v, 0x3);
v = _mm_shuffle_ps(t1,t3, 0x4E);
r2 = _mm_blend_ps(t1,v, 0xC);
r3 = _mm_blend_ps(t3,v, 0x3);
This effectively converted 4 shuffles into 2 shuffles and 4 blends. This uses 2 more instructions than the implementation of GCC, ICC, and MSVC. The advantage is that it reduces port pressure which may have a benefit in some circumstances. Currently all the shuffles and unpacks can go only to one particular port whereas the blends can go to either of two different ports.
I tried using 8 shuffles like MSVC and converting that into 4 shuffles + 8 blends but it did not work. I still had to use 4 unpacks.
I used this same technique for a 8x8 float transpose (see towards the end of that answer). https://stackoverflow.com/a/25627536/2542702. In that answer I still had to use 8 unpacks but I manged to convert the 8 shuffles into 4 shuffles and 8 blends.
For 32-bit integers there is nothing like shufps
(except for 128-bit shuffles with AVX512) so it can only be implemented with unpacks which I don't think can be convert to blends (efficiently). With AVX512 vshufi32x4
acts effectively like shufps
except for 128-bit lanes of 4 integers instead of 32-bit floats so this same technique might be possibly with vshufi32x4
in some cases. With Knights Landing shuffles are four times slower (throughput) than blends.
I can't reproduce this issue in a simple .NET 4.0 console application:
static class Program
{
static void Main(string[] args)
{
var myDict = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
Console.ReadKey();
}
}
Can you try to reproduce it in a simple Console application and go from there? It seems likely that you're targeting .NET 2.0 (which doesn't support it) or client profile framework, rather than a version of .NET that supports initialization syntax.
Convert.ToString(value, CultureInfo.InvariantCulture);
Try this.
@Query("Select c from Registration c where c.place like '%'||:place||'%'")
It is possible to increase heap size allocated by the JVM by using command line options Here we have 3 options
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
java -Xms16m -Xmx64m ClassName
In the above line we can set minimum heap to 16mb and maximum heap 64mb
In Go 1.1 and newer the most simple way to do this is with a bufio.Scanner
. Here is a simple example that reads lines from a file:
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("/path/to/file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
This is the cleanest way to read from a Reader
line by line.
There is one caveat: Scanner does not deal well with lines longer than 65536 characters. If that is an issue for you then then you should probably roll your own on top of Reader.Read()
.
I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.
$http({
url:'/login/user',
method : 'POST',
headers: {
'Content-Type': 'application/json'
},
data: userData
}).success(function(loginDetails){
$scope.updLoginDetails = loginDetails;
if($scope.updLoginDetails.successful == true)
{
loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
$window.location='/login/homepage';
}
else
alert('No access available.');
}).error(function(err,status){
alert('No access available.');
});
And it worked for me.
If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:
if(data !== null && data !== '') {
// do something
}
Notice that I changed your code to check for type equality (!==
|===
).
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false
).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if
. But, on the second one, every true-ish value will enter the if
: false
, 0
, null
, undefined
and empty strings, would not.
Using absolute
as position
is not responsive + mobile friendly. I would suggest using a div
with a background-image
and then placing text in the div
will place text over the image. Depending on your html, you might need to use height
with vh
value
If you're on Windows I suggest manually uninstalling node and installing chocolatey to handle your node installation. choco
is a great CLI for provisioning a ton of popular software.
Then you can just do,
choco install nodejs --version $VersionNumber
and if you already have it installed via chocolatey you can do,
choco uninstall nodejs
choco install nodejs --version $VersionNumber
For example,
choco uninstall nodejs
choco install nodejs --version 12.9.1
To all:
Note that the accepted answer has a bug in it relating to nullable types and the DataTable. The fix is available at the linked site (http://www.chinhdo.com/20090402/convert-list-to-datatable/) or in my modified code below:
///###############################################################
/// <summary>
/// Convert a List to a DataTable.
/// </summary>
/// <remarks>
/// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "ToDataTable"
/// <para/>Code modifications made by Nick Campbell.
/// <para/>Source code provided on this web site (chinhdo.com) is under the MIT license.
/// <para/>Copyright © 2010 Chinh Do
/// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
/// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
/// <para/>THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/// <para/>(As per http://www.chinhdo.com/20080825/transactional-file-manager/)
/// </remarks>
/// <typeparam name="T">Type representing the type to convert.</typeparam>
/// <param name="l_oItems">List of requested type representing the values to convert.</param>
/// <returns></returns>
///###############################################################
/// <LastUpdated>February 15, 2010</LastUpdated>
public static DataTable ToDataTable<T>(List<T> l_oItems) {
DataTable oReturn = new DataTable(typeof(T).Name);
object[] a_oValues;
int i;
//#### Collect the a_oProperties for the passed T
PropertyInfo[] a_oProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
//#### Traverse each oProperty, .Add'ing each .Name/.BaseType into our oReturn value
//#### NOTE: The call to .BaseType is required as DataTables/DataSets do not support nullable types, so it's non-nullable counterpart Type is required in the .Column definition
foreach(PropertyInfo oProperty in a_oProperties) {
oReturn.Columns.Add(oProperty.Name, BaseType(oProperty.PropertyType));
}
//#### Traverse the l_oItems
foreach (T oItem in l_oItems) {
//#### Collect the a_oValues for this loop
a_oValues = new object[a_oProperties.Length];
//#### Traverse the a_oProperties, populating each a_oValues as we go
for (i = 0; i < a_oProperties.Length; i++) {
a_oValues[i] = a_oProperties[i].GetValue(oItem, null);
}
//#### .Add the .Row that represents the current a_oValues into our oReturn value
oReturn.Rows.Add(a_oValues);
}
//#### Return the above determined oReturn value to the caller
return oReturn;
}
///###############################################################
/// <summary>
/// Returns the underlying/base type of nullable types.
/// </summary>
/// <remarks>
/// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "GetCoreType"
/// <para/>Code modifications made by Nick Campbell.
/// <para/>Source code provided on this web site (chinhdo.com) is under the MIT license.
/// <para/>Copyright © 2010 Chinh Do
/// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
/// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
/// <para/>THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/// <para/>(As per http://www.chinhdo.com/20080825/transactional-file-manager/)
/// </remarks>
/// <param name="oType">Type representing the type to query.</param>
/// <returns>Type representing the underlying/base type.</returns>
///###############################################################
/// <LastUpdated>February 15, 2010</LastUpdated>
public static Type BaseType(Type oType) {
//#### If the passed oType is valid, .IsValueType and is logicially nullable, .Get(its)UnderlyingType
if (oType != null && oType.IsValueType &&
oType.IsGenericType && oType.GetGenericTypeDefinition() == typeof(Nullable<>)
) {
return Nullable.GetUnderlyingType(oType);
}
//#### Else the passed oType was null or was not logicially nullable, so simply return the passed oType
else {
return oType;
}
}
Note that both of these example are NOT extension methods like the example above.
Lastly... apologies for my extensive/excessive comments (I had a anal/mean prof that beat it into me! ;)
From a quick google search it seems that the problem is a file or url couldn't be found be the HTTPservice.
Here are the links where I found this information:
http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/
Add a "User-Agent" header to your request.
Some servers attempt to block spidering programs and scrapers from accessing their server because, in earlier days, requests did not send a user agent header.
You can either try to set a custom user agent value or use some value that identifies a Browser like "Mozilla/5.0 Firefox/26.0"
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("user-agent", "Mozilla/5.0 Firefox/26.0");
headers.set("user-key", "your-password-123"); // optional - in case you auth in headers
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Game[]> respEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Game[].class);
logger.info(respEntity.toString());
Simply add Templates URL:
<a href="{% url 'service_data' d.id %}">
...XYZ
</a>
Used in django 2.0
merge into x as target using y as Source on target.ID = Source.ID
when not matched by target then insert
when matched then update
when not matched by source and target.ID is not null then
update whatevercolumn = 'isdeleted' ;
@Corey - It just simply strips out all invalid characters. However, your comment made me think of the answer.
The problem was that many of the fields in my database are nullable. When using SqlBulkCopy, an empty string is not inserted as a null value. So in the case of my fields that are not varchar (bit, int, decimal, datetime, etc) it was trying to insert an empty string, which obviously is not valid for that data type.
The solution was to modify my loop where I validate the values to this (repeated for each datatype that is not string)
//--- convert decimal values
foreach (DataColumn DecCol in DecimalColumns)
{
if(string.IsNullOrEmpty(dr[DecCol].ToString()))
dr[DecCol] = null; //--- this had to be set to null, not empty
else
dr[DecCol] = Helpers.CleanDecimal(dr[DecCol].ToString());
}
After making the adjustments above, everything inserts without issues.
The unwanted side effects of simple folder delete or installing over existing installation have been removed by a script written by Kyle Fuller - deintegrate and here is the proper workflow:
Install clean:
$ sudo gem install cocoapods-clean
Run deintegrate in the folder of the project:
$ pod deintegrate
Clean (this tool is no longer available):
$ pod clean
Modify your podfile (delete the lines with the pods you don't want to use anymore) and run:
$ pod install
Done.
I would be careful with setting the display
of the element to block. Different elements have the standard display as different things. For example setting display to block for a table row in firefox causes the width of the cells to be incorrect.
Is the name of the element actually test1. I know that .NET can add extra things onto the start or end. The best way to find out if your selector is working properly is by doing this.
alert($('#text1').length);
You might just need to remove the visibility attribute
$('#text1').removeAttr('visibility');
I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:
<projectDescription>
<name>Project-Name</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
2- Now instead of "Project-Name", write your project name, maybe current directory name
3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )
4- Now go to Eclips and open project and add your files to it.
DOM is a logical model that can be implemented in any convenient manner.It is based on an object structure that closely resembles the structure of the documents it models.
For More Information on DOM : Click Here
MySql have an application to import db from microsoft sql. Steps:
```javascript
{ "some": "json" }
```
I tried using json
but didn't like the way it looked. javascript
looks a bit more pleasing to my eye.
I am using unix system.
In eclipse project-> Properties -> Java Compiler -> Errors/Warning -> Forbidden Access(access rule) -> Turn it to warning/Ignore(Previously it was set to Error).
In Android Studio I was trying to set the compileSdkVersion
and targetSdkVersion
to 19
.
My solution was to replace at the bottom of build.gradle
, from this:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
}
To the older version of the appcompat library:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:19.+'
}
To export the output to file on a continuous basis (here every five seconds) and save to a CSV file with the Unix date as the filename:
while ($true) {
[int]$date = get-date -Uformat %s
$exportlocation = New-Item -type file -path "c:\$date.csv"
Get-Counter -Counter "\Processor(_Total)\% Processor Time" | % {$_} | Out-File $exportlocation
start-sleep -s 5
}
If using jruby, here is a code snippet to return an array of all tables in a db.
require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"
def get_database_tables(connection, db_name)
md = connection.get_meta_data
rs = md.get_tables(db_name, nil, '%',["TABLE"])
tables = []
count = 0
while rs.next
tables << rs.get_string(3)
end #while
return tables
end
Switch to the develop branch:
$ git checkout develop
Creates feature/foo branch of develop.
$ git checkout -b feature/foo develop
merge the changes to develop without a fast-forward
$ git checkout develop
$ git merge --no-ff myFeature
Now push changes to the server
$ git push origin develop
$ git push origin feature/foo
This example uses jquery-cookie
Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):
if($.cookie('popup') != 'seen'){
$.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
};
As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,
var json = [{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}];_x000D_
_x000D_
json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":'));_x000D_
_x000D_
document.write(JSON.stringify(json));
_x000D_
This will convert given JSON data to string and replace "_id" to "id" then converting it back to the required JSON format. But I used split
and join
instead of replace
, because replace
will replace only the first occurrence of the string.
If you're wanting to style the button using CSS, make it a type="submit" button instead of type="image". type="image" expects a SRC, which you can't set in CSS.
Note that Safari won't let you style any button in the manner you're looking for. If you need Safari support, you'll need to place an image and have an onclick function that submits the form.
The below code will give you list of all the rows:-
df[df['C'] != 'XYZ']
To store the values from the above code into a dataframe :-
newdf = df[df['C'] != 'XYZ']
Update
Since extract_numeric
is deprecated, we can use parse_number
from readr
package.
library(readr)
parse_number(years)
Here is another option with extract_numeric
library(tidyr)
extract_numeric(years)
#[1] 20 1
my solution was - just remove '*' character from the expression ^__^
<div ngFor="let talk in talks">
The question is about MySQL so I say there is a significant difference. If it was about Oracle (which stores numbers as string - yes, I couldn't believe it at first) then not much difference.
Storage in the table is not the issue but updating and referring to the index is. Queries involving looking up a record based on its primary key are frequent - you want them to occur as fast as possible because they happen so often.
The thing is a CPU deals with 4 byte and 8 byte integers naturally, in silicon. It's REALLY fast for it to compare two integers - it happens in one or two clock cycles.
Now look at a string - it's made up of lots of characters (more than one byte per character these days). Comparing two strings for precedence can't be done in one or two cycles. Instead the strings' characters must be iterated until a difference is found. I'm sure there are tricks to make it faster in some databases but that's irrelevant here because an int comparison is done naturally and lightning fast in silicon by the CPU.
My general rule - every primary key should be an autoincrementing INT especially in OO apps using an ORM (Hibernate, Datanucleus, whatever) where there's lots of relationships between objects - they'll usually always be implemented as a simple FK and the ability for the DB to resolve those fast is important to your app' s responsiveness.
Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes
Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class
Example Code:
abstract class A {
public function test1() {
echo 'Hello World';
}
abstract protected function f1();
abstract public function f2();
protected function test2(){
echo 'Hello World test';
}
}
class B extends A {
public $a = 'India';
public function f1() {
echo "F1 Method Call";
}
public function f2() {
echo "F2 Method Call";
}
}
$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";
Output:
Hello World
India
Hello World test
F1 Method Call
F2 Method Call
I, too, lost my overlays after upgrading to 1.6.8 on Windows 7 x64. I only installed the x64 version and not the 32-bit version. To fix, I ran a repair with the original installer and rebooted. The overlays displayed normally thereafter.
Since /deep/, >>>, and ::ng-deep are all deprecated. The best approach is to use the following in your child component styling
:host-context(.theme-light) h2 {
background-color: #eef;
}
This will look for the theme-light in any of the ancestors of your child component. See docs here: https://angular.io/guide/component-styles#host-context
One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.
>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0
Therefore, I use the following to test if a numpy array has elements:
>>> def elements(array):
... return array.ndim and array.size
>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24
this
is a HTML element.
$(this)
is a jQuery object that encapsulates the HTML element.
Use $(this).text()
to retrieve the element's inner text.
I suggest you refer to the jQuery API documentation for further information.
If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:
<script>
const meta = document.querySelector('[property="og:image"]');
const body = document.querySelector("body");
body.style.background = `url(${meta.content})`;
</script>
The above uses document.querySelector
and Attribute Selectors to assign meta
the first Open Graph image it selects. A similar task is performed to get the body
. Finally, string interpolation is used to assign body
the background.style
the value of the path to the Open Graph image.
If you want the image to cover the entire viewport and stay fixed set background-size
like so:
body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';
Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload
event, thereby reducing perceived latency.
Try this easy and it works
let input = elem.querySelector('input[type="file"]');
input.outerHTML=input.outerHTML;
this will reset the input
Use the FileSystemObject
object, namely, its CreateFolder
and CopyFile
methods. Basically, this is what your script will look like:
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
' Create a new folder
oFSO.CreateFolder "C:\MyFolder"
' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"
You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder
raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:
Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not oFSO.FolderExists(strFolder) Then
oFSO.CreateFolder strFolder
End If
oFSO.CopyFile strFile, strFolder, Overwrite
For Ubuntu 14.04 and Android try:
hcitool scan #get hardware address
sudo bluetooth-agent PIN HARDWARE-ADDRESS
PIN dialog pops up on Android device. Enter same PIN.
Note: sudo apt-get install bluez-utils
might be necessary.
Note2: If PIN dialog does not appear, try pairing from Android first (will fail because of wrong PIN). Then try again as described above.
If any other solution is in the debug mode then first stop them all and after that restart the visual studio. It worked for me.
Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:
from ..Common import Common
As a caveat, this will only work if you run your python as a module, from outside of the package. For example:
python -m Proj
This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.
You can add Common/ to your sys.path (the list of paths python looks at to import things):
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common
os.path.dirname(__file__)
just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.
"1".PadLeft(4, '0');
Use like below code.
if(number >=0 ) {
System.out.println("Number is natural and positive.");
}
I did this once for my project, to close one application and open another application.
System.Threading.Thread newThread;
Form1 frmNewForm = new Form1;
newThread = new System.Threading.Thread(new System.Threading.ThreadStart(frmNewFormThread));
this.Close();
newThread.SetApartmentState(System.Threading.ApartmentState.STA);
newThread.Start();
And add the following Method. Your newThread.Start will call this method.
public void frmNewFormThread)()
{
Application.Run(frmNewForm);
}
Here is an example that lists all the files on my desktop. you should change the path variable to your path.
Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.
public static void main(String[] args) {
File path = new File("c:/documents and settings/Zachary/desktop");
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i]);
}
}
}
Well, you could use nohup to run whatever you are running on 'non-blocking mode'. So you can just keep checking if whatever it was supposed to run, ran, otherwise exit.
nohup ./my-script-that-may-take-long-to-finish.sh & ./check-if-previous-script-ran-or-exit.sh
echo "Script ended on Feb 15, 2011, 9:20AM" > /tmp/done.txt
So in the second one you just check if the file exists.
Remove the width:100%;
declarations.
Block elements should take up the whole available width by default.
You might also be able to use pstree:
pstree -p user
This typically gives a text representation of all the processes for the "user" and the -p option gives the process-id. It does not depend, as far as I understand, on having the processes be owned by the current shell. It also shows forks.