<html>
<head>
<title>HTML Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="hover-id">
Hello World
</div>
<script>
jQuery(document).ready(function($){
$(document).on('mouseover', '#hover-id', function(){
$(this).css('color','yellowgreen');
});
$(document).on('mouseout', '#hover-id', function(){
$(this).css('color','black');
});
});
</script>
</body>
</html>
When you say $(document).ready(f)
, you tell script engine to do the following:
$
and select it, since it's not in local scope, it must do a hash table lookup, which may or may not have collisions.ready
of selected object, which involves another hash table lookup into the selected object to find the method and invoke it.In the best case, this is 2 hash table lookups, but that's ignoring the heavy work done by jQuery, where $
is the kitchen sink of all possible inputs to jQuery, so another map is likely there to dispatch the query to correct handler.
Alternatively, you could do this:
window.onload = function() {...}
which will
onload
is a property or not by doing a hash table lookup, since it is, it is called like a function.In the best case, this costs a single hash table lookup, which is necessary because onload
must be fetched.
Ideally, jQuery would compile their queries to strings that can be pasted to do what you wanted jQuery to do but without the runtime dispatching of jQuery. This way you have an option of either
eval
.Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.
If you're on GNU Make, use the :=
assignment instead of =
. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.
FILES := $(shell ...) # expand now; FILES is now the result of $(shell ...)
FILES = $(shell ...) # expand later: FILES holds the syntax $(shell ...)
If you use the =
assignment, it means that every single occurrence of $(FILES)
will be expanding the $(shell ...)
syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.
You don't. strings.xml
is just here to define the raw text messages. You should (must) use styles.xml
to define reusable visual styles to apply to your widgets.
Think of it as a good practice to separate the concerns. You can work on the visual styles independently from the text messages.
JavaScript is fired on client side and JSP is on server-side. So I can say that it is impossible.
Using the values from MSDN:
int BrowserVer, RegVal;
// get the installed IE version
using (WebBrowser Wb = new WebBrowser())
BrowserVer = Wb.Version.Major;
// set the appropriate IE version
if (BrowserVer >= 11)
RegVal = 11001;
else if (BrowserVer == 10)
RegVal = 10001;
else if (BrowserVer == 9)
RegVal = 9999;
else if (BrowserVer == 8)
RegVal = 8888;
else
RegVal = 7000;
// set the actual key
using (RegistryKey Key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", RegistryKeyPermissionCheck.ReadWriteSubTree))
if (Key.GetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe") == null)
Key.SetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe", RegVal, RegistryValueKind.DWord);
StringUtils.isEmpty(str)
or StringUtils.isNotEmpty(str)
StringUtils.isBlank(str)
or StringUtils.isNotBlank(str)
from Apache commons-lang.
The difference between empty
and blank
is : a string consisted of whitespaces only is blank
but isn't empty
.
I generally prefer using apache-commons if possible, instead of writing my own utility methods, although that is also plausible for simple ones like these.
I kept getting this error on my web forms project in visual studio 2015. I shutdown Visual Studio and I killed the ScriptedSandbox64.exe, Microsoft.VsHub.Server.HttpHostx64.exe, Microsoft.VsHub.Server.HttpHostx.exe *32, Microsoft.VisualStudio.Web.Host.exe *32 processes and it seemed to help fix the issue.
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
I think it's better to use the Microsoft.VisualBasic.FileIO.TextFieldParser Class if you're working with comma separated values text files.
About looping through a hash:
$Q = @{"ONE"="1";"TWO"="2";"THREE"="3"}
$Q.GETENUMERATOR() | % { $_.VALUE }
1
3
2
$Q.GETENUMERATOR() | % { $_.key }
ONE
THREE
TWO
Adding to the other answers and doing nothing more of what @Maleta explained in a comment on https://stackoverflow.com/a/28481374/1626594, doing alpha*255 then round then to hex. Here's a quick converter http://jsfiddle.net/8ajxdLap/4/
function rgb2hex(rgb) {_x000D_
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?((?:[0-9]*[.])?[0-9]+)[\s+]?\)/i);_x000D_
if (rgbm && rgbm.length === 5) {_x000D_
return "#" +_x000D_
('0' + Math.round(parseFloat(rgbm[4], 10) * 255).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
} else {_x000D_
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);_x000D_
if (rgbm && rgbm.length === 4) {_x000D_
return "#" +_x000D_
("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
} else {_x000D_
return "cant parse that";_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
$('button').click(function() {_x000D_
var hex = rgb2hex($('#in_tb').val());_x000D_
$('#in_tb_result').html(hex);_x000D_
});
_x000D_
body {_x000D_
padding: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Convert RGB/RGBA to hex #RRGGBB/#AARRGGBB:<br>_x000D_
<br>_x000D_
<input id="in_tb" type="text" value="rgba(200, 90, 34, 0.75)"> <button>Convert</button><br>_x000D_
<br> Result: <span id="in_tb_result"></span>
_x000D_
Why complicating too much? Solution is very simple
css:
.active-div{
position:relative;
}
.menu-div{
position:absolute;
top:0;
right:0;
display:none;
}
jquery:
$(function(){
$(".active-div").hover(function(){
$(".menu-div").prependTo(".active-div").show();
},function(){$(".menu-div").hide();
})
It works even if,
If you want to give your user all read permissions, you could use:
EXEC sp_addrolemember N'db_datareader', N'your-user-name'
That adds the default db_datareader
role (read permission on all tables) to that user.
There's also a db_datawriter
role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:
EXEC sp_addrolemember N'db_datawriter', N'your-user-name'
If you need to be more granular, you can use the GRANT
command:
GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName
and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.
This is all very well documented in the MSDN Books Online for SQL Server.
And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users
, right-click on that user you want to give permissions to, then Properties
adn at the bottom you see "Database role memberships" where you can add the user to db roles.
you must have gcc,json_pure
i collect some information from several post
sudo gem uninstall sass_x000D_
sudo gem uninstall compass_x000D_
sudo gem update --system_x000D_
gem install json_pure (if you have already have continued to next step)_x000D_
sudo yum install gcc gcc-c++ (if you have already have continued to next step)_x000D_
sudo gem install sass_x000D_
_x000D_
sudo gem install compass
_x000D_
Hi if ** sudo gem update --system ** not working you got an error in the update then use
sudo gem update --system 2.7.8
Spinner
<Spinner
android:id="@+id/To_Units"
style="@style/spinner_style" />
style.xml
<style name="spinner_style">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/gradient_spinner</item>
<item name="android:layout_margin">10dp</item>
<item name="android:paddingLeft">8dp</item>
<item name="android:paddingRight">20dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">5dp</item>
<item name="android:popupBackground">#DFFFFFFF</item>
</style>
gradient_spinner.xml (in drawable folder)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item><layer-list>
<item><shape>
<gradient android:angle="90" android:endColor="#B3BBCC" android:startColor="#E8EBEF" android:type="linear" />
<stroke android:width="1dp" android:color="#000000" />
<corners android:radius="4dp" />
<padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
</shape></item>
<item ><bitmap android:gravity="bottom|right" android:src="@drawable/spinner_arrow" />
</item>
</layer-list></item>
</selector>
@drawable/spinner_arrow
is your bottom right corner image
Five options:
Use the free jsonutils web tool without installing anything.
If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.
Use the free jsonclassgenerator.exe
The web tool app.quicktype.io does not require installing anything.
The web tool json2csharp also does not require installing anything.
Pros and Cons:
jsonclassgenerator converts to PascalCase but the others do not.
app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.
You can do that on javascript side .
<input type="submit" value="Send It!" onClick="return ActionDeterminator();">
When clicked, the JavaScript function ActionDeterminator() determines the alternate action URL. Example code.
function ActionDeterminator() {
if(document.myform.reason[0].checked == true) {
document.myform.action = 'http://google.com';
}
if(document.myform.reason[1].checked == true) {
document.myform.action = 'http://microsoft.com';
document.myform.method = 'get';
}
if(document.myform.reason[2].checked == true) {
document.myform.action = 'http://yahoo.com';
}
return true;
}
Collections.singletonList(object)
the list created by this method is immutable.
if you set style="height:100px;" on a td if the td has content that grows the cell more than that, it will do so no need for min height on a td.
Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:
The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
POP and IMAP bandwidth limits
Limit Per day
Download via IMAP 2500 MB
Download via POP 1250 MB
Upload via IMAP 500 MB
Instead of all the complicated JavaScript, you can actually achieve this with simple CSS
: just use two CSS files, one for your normal screen display, and another for the display of ONLY the content you wish to print. In this latter file, hide everything you don't want printed, display only the pop up.
Remember to define the media
attribute of both CSS files:
<link rel="stylesheet" href="screen-css.css" media="all" />
<link rel="stylesheet" href="print-css.css" media="print" />
If you are on a mac you can install haxm
using homebrew via cask which is a built-in extension (as of 2015) which allows installing non-open-source and desktop apps (i.e. chrome, firefox, eclipse, etc.):
brew cask install intel-haxm
If you are using Android Studio then you can achieve the same result from the menu Tools ? SDK Manager, and then on the SDK Tools tab, select the checkbox for Intel x86 Emulator Accelerator (HAXM installer), and click Ok.
in IntelliJ 2020 in the pom.xml
view one should be able to apply pom changes by following key combination: CTRG + SHIFT + O.
And as correctly commented before - IntelliJ additionally shows a balloon widget to import changes.
if this code does not work even under document ready, most probable you assigned a return false;
somewhere in your js file to that button, if it is button try to change it to a ,span, anchor or div and test if it is working.
$(document).on("click","#test-element",function() {
alert("click bound to document listening for #test-element");
});
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
You can automatically encode into Json, your complex entity with:
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($entity, 'json');
yourArray.indexOf(yourArrayKeyName) > -1
fruit = ['apple', 'grapes', 'banana']
fruit.indexOf('apple') > -1
true
fruit = ['apple', 'grapes', 'banana']
fruit.indexOf('apple1') > -1
false
The simplest way to do this is by using object-fit
:
<div class="container">
<img src="path/to/image.jpg">
</div>
.container{
height: 300px;
}
.container img{
height: 100%;
width: 100%;
object-fit: cover;
}
If you're using Bootstrap, just add the img-responsive
class and change to
.container img{
object-fit: cover;
}
<div>
with some proportions
div {
position: relative;
width: 100%;
height: 100%;
}
<img>
's with their own proportions
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: auto; /* to keep proportions */
height: auto; /* to keep proportions */
max-width: 100%; /* not to stand out from div */
max-height: 100%; /* not to stand out from div */
margin: auto auto 0; /* position to bottom and center */
}
I got it working using FileStream, get help from these
http://alperguc.blogspot.in/2008/11/c-generic-error-occurred-in-gdi.html
http://csharpdotnetfreak.blogspot.com/2010/02/resize-image-upload-ms-sql-database.html
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(fuImage.PostedFile.InputStream);
int imageHeight = imageToBeResized.Height;
int imageWidth = imageToBeResized.Width;
int maxHeight = 240;
int maxWidth = 320;
imageHeight = (imageHeight * maxWidth) / imageWidth;
imageWidth = maxWidth;
if (imageHeight > maxHeight)
{
imageWidth = (imageWidth * maxHeight) / imageHeight;
imageHeight = maxHeight;
}
Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] image = new byte[stream.Length + 1];
stream.Read(image, 0, image.Length);
System.IO.FileStream fs
= new System.IO.FileStream(Server.MapPath("~/image/a.jpg"), System.IO.FileMode.Create
, System.IO.FileAccess.ReadWrite);
fs.Write(image, 0, image.Length);
Unless you're using spaces in there, you should be able to use | wc -w
on the first line.
wc
is "Word Count", which simply counts the words in the input file. If you send only one line, it'll tell you the amount of columns.
Bob Lee said once in a presentation:
whats the point of an interface if you have only one implementation.
so, you start off with one implementation i.e. without an interface. later on you decide, well, there is a need for an interface here, so you convert your class to an interface.
then it becomes obvious: your original class was called User. your interface is now called User. maybe you have a UserProdImpl and a UserTestImpl. if you designed your application well, every class (except the ones that instantiate User) will be unchanged and will not notice that suddenly they get passed an interface.
so it gets clear -> Interface User implementation UserImpl.
If you don't need atomicity you can use os module:
import os
if not os.path.exists('/tmp/test'):
os.mknod('/tmp/test')
UPDATE:
As Cory Klein mentioned, on Mac OS for using os.mknod() you need a root permissions, so if you are Mac OS user, you may use open() instead of os.mknod()
import os
if not os.path.exists('/tmp/test'):
with open('/tmp/test', 'w'): pass
You can use system
:
system("/usr/local/bin/foo.sh");
This will block while executing it using sh -c
, then return the status code.
The notation that is used in
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
So,
a = '1234'
print a[::2]
would print
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
a = '1234'
print a[3:0:-1]
This would return
432
Note, that it doesn't return 4321 because, the stop index is not included.
Now in your case,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
i.e "1234" -> "4321" -> 4321 -> "4321"
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
You can deserialize directly to a list by using the TypeReference
wrapper. An example method:
public static <T> T fromJSON(final TypeReference<T> type,
final String jsonPacket) {
T data = null;
try {
data = new ObjectMapper().readValue(jsonPacket, type);
} catch (Exception e) {
// Handle the problem
}
return data;
}
And is used thus:
final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);
The documentation on the Maven site is horrible. What dependencyManagement does is simply move your dependency definitions (version, exclusions, etc) up to the parent pom, then in the child poms you just have to put the groupId and artifactId. That's it (except for parent pom chaining and the like, but that's not really complicated either - dependencyManagement wins out over dependencies at the parent level - but if have a question about that or imports, the Maven documentation is a little better).
After reading all of the 'a', 'b', 'c' garbage on the Maven site and getting confused, I re-wrote their example. So if you had 2 projects (proj1 and proj2) which share a common dependency (betaShared) you could move that dependency up to the parent pom. While you are at it, you can also move up any other dependencies (alpha and charlie) but only if it makes sense for your project. So for the situation outlined in the prior sentences, here is the solution with dependencyManagement in the parent pom:
<!-- ParentProj pom -->
<project>
<dependencyManagement>
<dependencies>
<dependency> <!-- not much benefit defining alpha here, as we only use in 1 child, so optional -->
<groupId>alpha</groupId>
<artifactId>alpha</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>zebra</groupId>
<artifactId>zebra</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>charlie</groupId> <!-- not much benefit defining charlie here, so optional -->
<artifactId>charlie</artifactId>
<version>1.0</version>
<type>war</type>
<scope>runtime</scope>
</dependency>
<dependency> <!-- defining betaShared here makes a lot of sense -->
<groupId>betaShared</groupId>
<artifactId>betaShared</artifactId>
<version>1.0</version>
<type>bar</type>
<scope>runtime</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
<!-- Child Proj1 pom -->
<project>
<dependencies>
<dependency>
<groupId>alpha</groupId>
<artifactId>alpha</artifactId> <!-- jar type IS DEFAULT, so no need to specify in child projects -->
</dependency>
<dependency>
<groupId>betaShared</groupId>
<artifactId>betaShared</artifactId>
<type>bar</type> <!-- This is not a jar dependency, so we must specify type. -->
</dependency>
</dependencies>
</project>
<!-- Child Proj2 -->
<project>
<dependencies>
<dependency>
<groupId>charlie</groupId>
<artifactId>charlie</artifactId>
<type>war</type> <!-- This is not a jar dependency, so we must specify type. -->
</dependency>
<dependency>
<groupId>betaShared</groupId>
<artifactId>betaShared</artifactId>
<type>bar</type> <!-- This is not a jar dependency, so we must specify type. -->
</dependency>
</dependencies>
</project>
string filePath = System.IO.Path.GetFullPath("settings.app.config");
var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
try
{
// Open App.Config of executable
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
// Add an Application Setting if not exist
config.AppSettings.Settings.Add("key1", "value1");
config.AppSettings.Settings.Add("key2", "value2");
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException ex)
{
if (ex.BareMessage == "Root element is missing.")
{
File.Delete(filePath);
return;
}
MessageBox.Show(ex.Message);
}
It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:
unsigned int x = N;
In fact, we can create algorithms which evaluate at compile time (from Wikipedia):
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
Look here.
Basically you have to do bind params:
$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)";
$this->db->query($sql, '__COUNTRY_NAME__');
But, like Mr.E said, use joins:
$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?";
$this->db->query($sql, '__COUNTRY_NAME__');
You can also take a look at mechanize. Its meant to handle "stateful programmatic web browsing" (as per their site).
Sure, using the switch
construct you can simulate goto
in JavaScript. Unfortunately, the language doesn't provide goto
, but this is a good enough of a replacement.
let counter = 10
function goto(newValue) {
counter = newValue
}
while (true) {
switch (counter) {
case 10: alert("RINSE")
case 20: alert("LATHER")
case 30: goto(10); break
}
}
Unfortunately, that's not supported in the Django template language. There are a couple of suggestions, but they seem a little complex. I would just put a variable in the context:
...
render_to_response('foo.html', {..., 'range': range(10), ...}, ...)
...
and in the template:
{% for i in range %}
...
{% endfor %}
The best and easiest way to clear a JLIST is:
myJlist.setListData(new String[0]);
If cleaning the project doesn't work and if there is no problem with xml files(If it is a new project). Then go to Androidmanifest.xml,edit it and add some spaces between the lines, save it. Now clean the project, error will vanish.
This happens because of stale R.java file. When we edit android manifest file,R.java is created again.
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param
to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page
var element_position = $('#scroll-to').offset().top;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
UPDATE
I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.
var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if(element_in_view || has_reached_bottom_of_page) {
//Do something
}
});
I found the solution. It's so simple. Follow froger_mcs instructions.
Make sure that you make the src folder a Source folder in Project Structure -> Modules (Sources).
It's called the ternary operator
. For some more info, here's another question I answered regarding this:
There is even a better way to create a Map along with initialization:
Map<String, String> rightHereMap = new HashMap<String, String>()
{
{
put("key1", "value1");
put("key2", "value2");
}
};
For more options take a look here How can I initialise a static Map?
handleChange({target}) {
const files = target.files
target.value = ''
}
This way you can create a new object with a custom property name.
$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);
Now you can reach it like:
echo $a->foo; //returns bar
As sixty4bit question, if your mysql root user looks to be misconfigured, try to install the configurator extension from mysql official source:
https://dev.mysql.com/downloads/repo/apt/
It will help you to set up a new root user password.
Make sure to update your repository (debian/ubuntu) :
apt-get update
The way to do this using the Extention Methods, instead of the linq query syntax would be like this:
var results = workOrders.Join(plans,
wo => wo.WorkOrderNumber,
p => p.WorkOrderNumber,
(order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);
A couple of answers that should work above but this is how i would write it.
Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.
add-text.tpl.html
<div ng-controller="myController">
<form ng-submit="addText(myText)">
<input type="text" placeholder="Let's Go" ng-model="myText">
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="text in arrayText">{{ text }}</li>
</ul>
</div>
app.js
(function() {
function myController($scope) {
$scope.arrayText = ['hello', 'world'];
$scope.addText = function(myText) {
$scope.arrayText.push(myText);
};
}
angular.module('app', [])
.controller('myController', myController);
})();
capture this
:
auto lambda = [this](){};
use a local reference to the member:
auto& tmp = grid;
auto lambda = [ tmp](){}; // capture grid by (a single) copy
auto lambda = [&tmp](){}; // capture grid by ref
C++14:
auto lambda = [ grid = grid](){}; // capture grid by copy
auto lambda = [&grid = grid](){}; // capture grid by ref
example: https://godbolt.org/g/dEKVGD
You can use string.Format
:
string template = "Hi We have these flights for you: {0}. Which one do you want";
string data = "A, B, C, D";
string message = string.Format(template, data);
You should load template
from your resource file and data
is your runtime values.
Be careful if you're translating to multiple languages, though: in some cases, you'll need different tokens (the {0}
) in different languages.
You can't alter the existing columns for identity.
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.
Alter Table Names
Add Id_new Int Identity(1, 1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
See the following Microsoft SQL Server Forum post for more details:
You can also get a direct link to a view within a folder by using "TreeValue", "TreeField" and "RootFolder".
Example:
http://sharepoint/Docs/YourLibrary/Forms/YourView.aspx?RootFolder=MyFolder&TreeField=Folders&TreeValue=MyFolder
To further explain: I have a SharePoint site, with a docs library called YourLibrary. I have a folder called MyFolder. I created a view that can be used at any level of that Library structure with a URL path of YourView.aspx Using that link, it will take me to the view I created, with all the filters and styles, but only show the results that would occur in the contents of that folder in RootFolder and TreeValue.
The align-items
property of flex-box aligns the items inside a flex container along the cross axis just like justify-content
does along the main axis. (For the default flex-direction: row
the cross axis corresponds to vertical and the main axis corresponds to horizontal. With flex-direction: column
those two are interchanged respectively).
Here's an example of how align-items:center
looks:
But align-content
is for multi line flexible boxes. It has no effect when items are in a single line. It aligns the whole structure according to its value. Here's an example for align-content: space-around;
:
And here's how align-content: space-around;
with align-items:center
looks:
Note the 3rd box and all other boxes in first line change to vertically centered in that line.
Here are some codepen links to play with:
http://codepen.io/asim-coder/pen/MKQWbb
http://codepen.io/asim-coder/pen/WrMNWR
Here's a super cool pen which shows and lets you play with almost everything in flexbox.
If the order of element is not important, you can
select
id, elem, row_number() over (partition by id) as nr
from (
select
id,
unnest(string_to_array(elements, ',')) AS elem
from myTable
) a
I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()
Right I think I know what you mean so lets see....
<div id="con">
<div id="content">Results will go here</div>
<div id="footer">Footer will always be at the bottom</div>
</div>
html,
body {
margin:0;
padding:0;
height:100%;
}
div {
outline: 1px solid;
}
#con {
min-height:100%;
position:relative;
}
#content {
height: 1000px; /* Changed this height */
padding-bottom:60px;
}
#footer {
position:absolute;
bottom:0;
width:100%;
height:60px;
}
This demo have the height of contentheight: 1000px;
so you can see what it would look like scrolling down the bottom.
This demo has the height of content height: 100px;
so you can see what it would look like with no scrolling.
So this will move the footer below the div content
but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.
Updated fiddles so its easier to see with backgrounds.
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
If you only have d1 and d2,
from collections import defaultdict
d = defaultdict(list)
for a, b in d1.items() + d2.items():
d[a].append(b)
another example following @jake stayman:
{% for key, item in row.divs %}
{% if (key not in [1,2,9]) %} // eliminate element 1,2,9
<li>{{ item }}</li>
{% endif %}
{% endfor %}
I know this is a very old question, but I've been asked by someone else something similar.
I don't have TeraData, but can't you do the following?
SELECT employee_number,
course_code,
MAX(course_completion_date) AS max_course_date,
MAX(course_completion_date) OVER (PARTITION BY employee_number) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
The GROUP BY
now ensures one row per course per employee. This means that you just need a straight MAX()
to get the max_course_date
.
Before your GROUP BY
was just giving one row per employee, and the MAX() OVER()
was trying to give multiple results for that one row (one per course).
Instead, you now need the OVER()
clause to get the MAX()
for the employee as a whole. This is now legitimate because each individual row gets just one answer (as it is derived from a super-set, not a sub-set). Also, for the same reason, the OVER()
clause now refers to a valid scalar value, as defined by the GROUP BY
clause; employee_number
.
Perhaps a short way of saying this would be that an aggregate
with an OVER()
clause must be a super-set of the GROUP BY
, not a sub-set.
Create your query with a GROUP BY
at the level that represents the rows you want, then specify OVER()
clauses if you want to aggregate at a higher level.
This is my way to achieve that.
First of all add Root_fragment
inside viewPager
tab in which you want to implement button click fragment
event. Example;
@Override
public Fragment getItem(int position) {
if(position==0)
return RootTabFragment.newInstance();
else
return SecondPagerFragment.newInstance();
}
First of all, RootTabFragment
should be include FragmentLayout
for fragment change.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Then, inside RootTabFragment
onCreateView
, implement fragmentChange
for your FirstPagerFragment
getChildFragmentManager().beginTransaction().replace(R.id.root_frame, FirstPagerFragment.newInstance()).commit();
After that, implement onClick
event for your button inside FirstPagerFragment
and make fragment change like that again.
getChildFragmentManager().beginTransaction().replace(R.id.root_frame, NextFragment.newInstance()).commit();
Hope this will help you guy.
Instead of using the full plugin name (with groupId) like described in Bartosz's answer, you could add
<pluginGroups>
<pluginGroup>org.springframework.boot</pluginGroup>
</pluginGroups>
to your .m2/settings.xml.
I found this work for me!
var fd = new FormData();
$.each($('.modal-banner [type=file]'), function(index, file) {
fd.append('item[]', $('input[type=file]')[index].files[0]);
});
$.ajax({
type: 'POST',
url: 'your/path/',
data: fd,
dataType: 'json',
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
},
error: function(err){
console.log(err);
}
}).done(function() {
// do something....
});
return false;
yes, pt2ph8's answer is right,
but if for some strange reason your contentSize should be higher than the UIScrollView, you can disable the vertical scrolling implementing the UIScrollView protocol method
-(void)scrollViewDidScroll:(UIScrollView *)aScrollView;
just add this in your UIViewController
float oldY; // here or better in .h interface
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
[aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, oldY)];
// or if you are sure you wanna it always on top:
// [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, 0)];
}
it's just the method called when the user scroll your UIScrollView, and doing so you force the content of it to have always the same .y
I just had this error now in server only and the solution was to set a maxItemsInObjectGraph
attribute in wcf web.config
under <behavior>
tag:
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
There is a simple way to solve this: you can execute php file by cron every 1 minute, and inside php executable file make "if" statement to execute when time "now" like this
<?/** suppose we have 1 hour and 1 minute inteval 01:01 */
$interval_source = "01:01";
$time_now = strtotime( "now" ) / 60;
$interval = substr($interval_source,0,2) * 60 + substr($interval_source,3,2);
if( $time_now % $interval == 0){
/** do cronjob */
}
This is a complete solution. I've just updated this example code with the information provided in the answer below by @mad. Also check the solution below from @Khobaib explaining how to deal with picasa images.
I've just reviewed my original answer and created a simple Android Studio project you can checkout from github and import directly on your system.
https://github.com/hanscappelle/SO-2169649
(note that the multiple file selection still needs work)
With support for images from file explorers thanks to user mad.
public class BrowsePictureActivity extends Activity {
// this is the action code we use in our intent,
// this way we know we're looking at the response from our own action
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.Button01)
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
// this is our fallback here
return uri.getPath();
}
}
Since someone requested that information in a comment and it's better to have information gathered.
Set an extra parameter EXTRA_ALLOW_MULTIPLE
on the intent:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
And in the Result handling check for that parameter:
if (Intent.ACTION_SEND_MULTIPLE.equals(data.getAction()))
&& Intent.hasExtra(Intent.EXTRA_STREAM)) {
// retrieve a collection of selected images
ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
// iterate over these images
if( list != null ) {
for (Parcelable parcel : list) {
Uri uri = (Uri) parcel;
// TODO handle the images one by one here
}
}
}
Note that this is only supported by API level 18+.
Most of the options above have shown how to configure Dart in the Windows System (If you have installed Dart and Flutter Doctor is showing all good).
On MacOS this option is available under Android Studio > Preferences ('Command' + ',')
Locate 'Languages and Frameworks / Dart' in the left pane.
Check 'Enable Dart Support' and locate the dart SDK. It will be inside your Flutter SDK Installation Directory '/flutter-installation-directory/flutter/bin/cache/dart-sdk'. Entering this will auto-populate the dart version in the row beneath, pointing that the framework is picked.
Check the box 'Enable Dart Support for the following modules' for your required project.
Click Apply. Click Ok.
As pointed above also, this should solve most of the use-cases. If error still persists, you can go File > Invalidate Caches/Restart.
By default mongodb has no enabled access control, so there is no default user or password.
To enable access control, use either the command line option --auth
or security.authorization configuration file setting.
You can use the following procedure or refer to Enabling Auth in the MongoDB docs.
Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db1
Connect to the instance.
mongo --port 27017
Create the user administrator.
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db1
Authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" \
--authenticationDatabase "admin"
If you have many class level properties then a singleton pattern might be in order. Something like this:
// Foo.h
@interface Foo
+ (Foo *)singleton;
@property 1 ...
@property 2 ...
@property 3 ...
@end
And
// Foo.m
#import "Foo.h"
@implementation Foo
static Foo *_singleton = nil;
+ (Foo *)singleton {
if (_singleton == nil) _singleton = [[Foo alloc] init];
return _singleton;
}
@synthesize property1;
@synthesize property2;
@synthesise property3;
@end
Now access your class-level properties like this:
[Foo singleton].property1 = value;
value = [Foo singleton].property2;
I was running MAMP 4.1 on windows and MYSQL 5.7 .Was having this problem many times and found out a fix for this: For me deleting the log files was not working then just delete
and boom it starts working again. If this also doesn't work for your, remember to delete each file one by one and keep checking if any works for you. Make sure to backup always.
Use the in
keyword without is
.
if "x" in dog:
print "Yes!"
If you'd like to check for the non-existence of a character, use not in
:
if "x" not in dog:
print "No!"
It seems all the answers are adding info to e.args[0], thereby altering the existing error message. Is there a downside to extending the args tuple instead? I think the possible upside is, you can leave the original error message alone for cases where parsing that string is needed; and you could add multiple elements to the tuple if your custom error handling produced several messages or error codes, for cases where the traceback would be parsed programmatically (like via a system monitoring tool).
## Approach #1, if the exception may not be derived from Exception and well-behaved:
def to_int(x):
try:
return int(x)
except Exception as e:
e.args = (e.args if e.args else tuple()) + ('Custom message',)
raise
>>> to_int('12')
12
>>> to_int('12 monkeys')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')
or
## Approach #2, if the exception is always derived from Exception and well-behaved:
def to_int(x):
try:
return int(x)
except Exception as e:
e.args += ('Custom message',)
raise
>>> to_int('12')
12
>>> to_int('12 monkeys')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')
Can you see a downside to this approach?
To call a controller function in parent scope from inside an isolate scope directive, use dash-separated
attribute names in the HTML like the OP said.
Also if you want to send a parameter to your function, call the function by passing an object:
<test color1="color1" update-fn="updateFn(msg)"></test>
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.color1 = "color";
$scope.updateFn = function(msg) {
alert(msg);
}
});
app.directive('test', function() {
return {
restrict: 'E',
scope: {
color1: '=',
updateFn: '&'
},
// object is passed while making the call
template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>
Click</button>",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
In my case, CSS did not fix the issue. I noticed the problem while using jQuery re-render a button.
$("#myButton").html("text")
Try this
$("#myButton").html("<span>text</span>")
I wrote a similar answer to a similar question on Stack Overflow, but here is part of that answer.
The new version of Android Studio (2.1) has support for Java 8 features. Here is an extract from the Android Developers blogspot post:
... Android Studio 2.1 release includes support for the new Jack compiler and support for Java 8.
...
To use Java 8 language features when developing with the N Developer Preview, you need to use the Jack compiler. The New Project Wizard [File? New? Project] generates the correct configurations for projects targeting the N.
Android does not support Java 1.8 yet (it only supports up to 1.7), so you cannot use Java 8 features like lambdas.
This answer gives more detail on Android Studio's compatibility; it states:
If you want to use lambdas, one of the major features of Java 8 in Android, you can use gradle-retrolamba
If you want to know more about using gradle-retrolambda
, this answer gives a lot of detail on doing that.
Follow these steps
1) Go in projects class path
2) Go in library tab
3) click on Add Library
4) In opened dialogue select Maven Managed Dependencies
5) Click on Next
6) In the new dialogue click on Manage Project Settings
7) In opened dialogue select the check box Resolve dependencies from workspace
8) Click on Restore defaults
9) It will do some process and you will have all your dependencies in your library now.
Similar to other answers, but with a func class to setup the padding dinamically:
class UILabelExtendedView: UILabel
{
var topInset: CGFloat = 4.0
var bottomInset: CGFloat = 4.0
var leftInset: CGFloat = 8.0
var rightInset: CGFloat = 8.0
override func drawText(in rect: CGRect)
{
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override public var intrinsicContentSize: CGSize
{
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat){
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}
}
Use the PercentRelativeLayout or PercentFrameLayout from the Percent Supoort Library
<android.support.percent.PercentFrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
app:layout_heightPercent="68%"/>
<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
app:layout_heightPercent="16%"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</android.support.percent.PercentFrameLayout>
You could use a "variable" inside the output filename, for example:
/tmp/FetchBlock-${current_date}.txt
current_date:
Returns the current system time formatted as yyyyMMdd_HHmm. An optional argument can be used to provide alternative formatting. The argument must be valid pattern for java.util.SimpleDateFormat.
Or you can also use a system_property or an env_var to specify something dynamic (either one needs to be specified as arguments)
As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:
with open('my_file.txt', 'rU') as in_file:
data = in_file.read().split('\n')
That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:
with open('new_file.txt', 'w') as out_file:
out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters
Hopefully that fits what you're looking for.
For Linux (Ubuntu 14.04), you can go to
File -> Settings -> Editor -> Auto Import
check all the boxes and insert all imports on paste.
This has to be defined in the interactive shell:
def MyWho():
print [v for v in globals().keys() if not v.startswith('_')]
Then the following code can be used as an example:
>>> import os
>>> import sys
>>> a = 10
>>> MyWho()
['a', 'MyWho', 'sys', 'os']
Use the Len function
length = Len(myString)
Try this answer
https://stackoverflow.com/a/54513168/9236994
with minimal efforts helps to resolve the issue.
To initialize long you need to append "L" to the end.
It can be either uppercase or lowercase.
All the numeric values are by default int
. Even when you do any operation of byte
with any integer, byte
is first promoted to int
and then any operations are performed.
Try this
byte a = 1; // declare a byte
a = a*2; // you will get error here
You get error because 2
is by default int
.
Hence you are trying to multiply byte
with int
.
Hence result gets typecasted to int
which can't be assigned back to byte
.
Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html
<style>
.bottom-three {
margin-bottom: 3cm;
}
</style>
<p class="bottom-three">
This is the first question?
</p>
<p class="bottom-three">
This is the second question?
</p>
In REST, each HTTP verbs has its place and meaning.
For example,
GET is to get the 'resource(s)' that is pointed to in the URL.
POST is to instructure the backend to 'create' a resource of the 'type' pointed to in the URL. You can supplement the POST operation with parameters or additional data in the body of the POST call.
In you case, since you are interested in 'getting' the info using query, thus it should be a GET operation instead of a POST operation.
This wiki may help to further clarify things.
Hope this help!
Schema is a container of objects. It is owned by a user.
Put your if condition inside resize
function:
var windowsize = $(window).width();
$(window).resize(function() {
windowsize = $(window).width();
if (windowsize > 440) {
//if the window is greater than 440px wide then turn on jScrollPane..
$('#pane1').jScrollPane({
scrollbarWidth:15,
scrollbarMargin:52
});
}
});
I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.
But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.
But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.
For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.
You have to distinct sub routines and functions in vba... Generally (as far as I know), sub routines do not return anything and the surrounding parantheses are optional. For functions, you need to write the parantheses.
As for your example, MsgBox is not a function but a sub routine and therefore the parantheses are optional in that case. One exception with functions is, when you do not assign the returned value, or when the function does not consume a parameter, you can leave away the parantheses too.
This answer goes into a bit more detail, but basically you should be on the save side, when you provide parantheses for functions and leave them away for sub routines.
Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.
Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)
Thank You, Vish
Check out this article. It is very exhaustive and you will find how to extract various hardware information.
Quote from the article:
To get hardware information, you need to create an object of ManagementObjectSearcher class.
using System.Management;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
foreach (ManagementObject share in searcher.Get()) {
// Some Codes ...
}
The Key on the code above, is a variable that is replaced with appropriate data. For example, to get the information of the CPU, you have to replace the Key with Win32_Processor.
To get the right ownership, you can set the group setuid bit on the directory with
chmod g+rwxs dirname
This will ensure that files created in the directory are owned by the group. You should then make sure everyone runs with umask 002 or 007 or something of that nature---this is why Debian and many other linux systems are configured with per-user groups by default.
I don't know of a way to force the permissions you want if the user's umask is too strong.
I think you're looking for this:
$('#td_id').removeClass('change_me').addClass('new_class');
Nesting block level elements in anchors is not invalid anymore in HTML5. See http://html5doctor.com/block-level-links-in-html-5/ and http://www.w3.org/TR/html5/the-a-element.html.
I'm not saying you should use it, but in HTML5 it's fine to use <a href="#"><div></div></a>
.
The accepted answer is otherwise the best one. Using JavaScript like others suggested is also bad because it would make the "link" inaccessible (to users without JavaScript, which includes search engines and others).
The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"
Then make sure to access the Observable
class as Rx.Observable
.
The only way I can get this to work is to manually instantiate the section handler type, pass the raw XML to it, and cast the resulting object.
Seems pretty inefficient, but there you go.
I wrote an extension method to encapsulate this:
public static class ConfigurationSectionExtensions
{
public static T GetAs<T>(this ConfigurationSection section)
{
var sectionInformation = section.SectionInformation;
var sectionHandlerType = Type.GetType(sectionInformation.Type);
if (sectionHandlerType == null)
{
throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
}
IConfigurationSectionHandler sectionHandler;
try
{
sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
}
catch (InvalidCastException ex)
{
throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
}
var rawXml = sectionInformation.GetRawXml();
if (rawXml == null)
{
return default(T);
}
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(rawXml);
return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
}
}
The way you would call it in your example is:
var map = new ExeConfigurationFileMap
{
ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();
The main problem is that:
in a constructor, the injection of the dependencies has not yet occurred*
*obviously excluding Constructor Injection
Real-world example:
public class Foo {
@Inject
Logger LOG;
@PostConstruct
public void fooInit(){
LOG.info("This will be printed; LOG has already been injected");
}
public Foo() {
LOG.info("This will NOT be printed, LOG is still null");
// NullPointerException will be thrown here
}
}
IMPORTANT:
@PostConstruct
and @PreDestroy
have been completely removed in Java 11.
To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
#collect
is actually an alias for #map
. That means the two methods can be used interchangeably, and effect the same behavior.
In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract
, the following code replicates the extract(...)
line in Hadleys' answer:
df %>%
gather(question_number, value, starts_with("Q3.")) %>%
mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
select(id, time, loop_number, question_number, value) %>%
spread(key = question_number, value = value)
The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate
in my original solution in the comments to split this column into two columns with equivalent info, a loop_number
column and a question_number
column. spread
can then be used to transform the long form data, which are key value pairs (question_number, value)
to wide form data.
What I normally do is e .
(e-space-dot) which gives me a browsable current directory - then I can /
- search for name fragments, just like finding a word in a text file. I find that generally good enough, simple and quick.
Just pin your tableview (or make it begin) at the absolute top of the view. The additional unwanted space is exactly the height of a navigation bar.
Here's the simple, built-in way:
<span title="My tip">text</span>
That gives you plain text tooltips. If you want rich tooltips, with formatted HTML in them, you'll need to use a library to do that. Fortunately there are loads of those.
You have a typo in the import in your LoginComponent
's file
import { Component } from '@angular/Core';
It's lowercase c
, not uppercase
import { Component } from '@angular/core';
Another example for vertically and horizontally centered div or any object(s):
var obj = $("#divID");
var halfsc = $(window).height()/2;
var halfh = $(obj).height() / 2;
var halfscrn = screen.width/2;
var halfobj =$(obj).width() / 2;
var goRight = halfscrn - halfobj ;
var goBottom = halfsc - halfh;
$(obj).css({marginLeft: goRight }).css({marginTop: goBottom });
Why not do it with one method call:
File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });
which will do the newline for you, and allow you to insert multiple lines at once if you want.
I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar
.
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
See this example:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
Because doA()
does not modify the global total the output is 1 not 11.
may be this will help:
map.setCenter(window.markersArray[2].getPosition());
all the markers info are in markersArray array and it is global. So you can access it from anywhere using window.variablename. Each marker has a unique id and you can put that id in the key of array. so you create marker like this:
window.markersArray[2] = new google.maps.Marker({
position: new google.maps.LatLng(23.81927, 90.362349),
map: map,
title: 'your info '
});
Hope this will help.
buf.erase(buf.size() - 1);
This assumes you know that the string is not empty. If so, you'll get an out_of_range
exception.
As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:
On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):
$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start
As it was said in other answers there is no way to make a POST request using window.location.href, to do it you can create a form and submit it immediately.
You can use this function:
function postForm(path, params, method) {
method = method || 'post';
var form = document.createElement('form');
form.setAttribute('method', method);
form.setAttribute('action', path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', key);
hiddenField.setAttribute('value', params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
postForm('mysite.com/form', {arg1: 'value1', arg2: 'value2'});
After struggling a bit with some of the answers here, I found a library called backoff that worked better for my situation. A basic example:
import backoff
@backoff.on_exception(
backoff.expo,
requests.exceptions.RequestException,
max_tries=5,
giveup=lambda e: e.response is not None and e.response.status_code < 500
)
def publish(self, data):
r = requests.post(url, timeout=10, json=data)
r.raise_for_status()
I'd still recommend giving the library's native functionality a shot, but if you run into any problems or need broader control, backoff is an option.
I had same requirement.
I have used the below way to get it.
I had session scoped bean.
@ManagedBean(name="mb")
@SessionScopedpublic
class ManagedBean {
--------
}
I have used the below code in my servlet doPost() method.
ManagedBean mb = (ManagedBean) request.getSession().getAttribute("mb");
it solved my problem.
Solution that work for me :
var editorInstance = CKEDITOR.instances[this.editorId];
editorInstance.on('focus', function(e) {
console.log("tadaaa");
});
I initialised the slider with one of the properties as
variableWidth: true
then i could set the width of the slides to anything i wanted in CSS with:
.slick-slide {
width: 200px;
}
If all login services use PAM, and all login services have session required pam_env.so
in their respective /etc/pam.d/*
configuration files, then all login sessions will have some environment variables set as specified in pam_env
's configuration file.
On most modern Linux distributions, this is all there by default -- just add your desired global environment variables to /etc/security/pam_env.conf
.
This works regardless of the user's shell, and works for graphical logins too (if xdm/kdm/gdm/entrance/… is set up like this).
Replace all latters from any language in 'A', and if you wish for example all digits to 0:
return str.replace(/[^\s!-@[-`{-~]/g, "A").replace(/\d/g, "0");
I would rather prefer that you use BitBucket, as it is not public and there is an official tutorial by Unity on Bitbucket.
https://unity3d.com/learn/tutorials/topics/cloud-build/creating-your-first-source-control-repository
hope this helps.
You can just do this:
git remote add origin ssh://user@host:1234/srv/git/example
1234
is the ssh port being used
A form is not allowed to be a child element of a table
, tbody
or tr
. Attempting to put one there will tend to cause the browser to move the form to it appears after the table (while leaving its contents — table rows, table cells, inputs, etc — behind).
You can have an entire table inside a form. You can have a form inside a table cell. You cannot have part of a table inside a form.
Use one form around the entire table. Then either use the clicked submit button to determine which row to process (to be quick) or process every row (allowing bulk updates).
HTML 5 introduces the form
attribute. This allows you to provide one form per row outside the table and then associate all the form control in a given row with one of those forms using its id
.
Create APC.php file
foreach(array('user','opcode','') as $v ){
apc_clear_cache($v);
}
Run it from your browser.
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
If you just want to embed an OSM map on a webpage, the easiest way is to get the iframe code directly from the OSM website:
<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" _x000D_
src="https://www.openstreetmap.org/export/embed.html?bbox=-62.04673002474011%2C16.95487694424327%2C-61.60521696321666%2C17.196751341562923&layer=mapnik" _x000D_
style="border: 1px solid black"></iframe>_x000D_
<br/><small><a href="https://www.openstreetmap.org/#map=12/17.0759/-61.8260">View Larger Map</a></small>
_x000D_
If you want to do something more elaborate, see OSM wiki "Deploying your own Slippy Map".
It is good programming practice to return an empty array []
if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}
.
Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.
This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.
Here's a link to that part of his book:
http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html
For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.
The easiest is mine:
<TextInput
style={[
styles.default,
this.props.singleSourceOfTruth ?
{ backgroundColor: 'black' }
: { backgroundColor: 'white' }
]}/>
I will rather do it manually
...database/migrations
folderphp artisan migrate
, log into your phpmyadmin or SQL(whichever the case is) and in your database, delete the table created by the migrationWorks for me, hope it helps!
Here is the Koltin style, I use this in my project and it works very well:
this.yourview.setOnTouchListener(View.OnTouchListener { _, event ->
val x = event.x
val y = event.y
when(event.action) {
MotionEvent.ACTION_DOWN -> {
Log.d(TAG, "ACTION_DOWN \nx: $x\ny: $y")
}
MotionEvent.ACTION_MOVE -> {
Log.d(TAG, "ACTION_MOVE \nx: $x\ny: $y")
}
MotionEvent.ACTION_UP -> {
Log.d(TAG, "ACTION_UP \nx: $x\ny: $y")
}
}
return@OnTouchListener true
})
Below are steps to update cocoapods :
Press cmd + space tab
to open Spotlight then text in terminal
)pod setup
command. This will setup cocoapods master repo.pod --version
command. It works for me, by using double quotes around variables.
I am using batch script to call powershell Send-MailMessage
Batch Script:send_email.bat
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command 'E:\path\send_email.ps1
Pwershell Script send_email.ps1
Send-MailMessage -From "noreply@$env:computername" -To '<[email protected]>' -Subject 'Blah Blah' -SmtpServer 'smtp.domain.com' -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "
Just throwing this out there...Can't you just do:
Collections.sort(myarrayList);
It's been awhile though...
if min=10
and max=100
:
(int)(Math.random() * max) + min
gives a result between 10 and 110, while
(int)(Math.random() * (max - min) + min)
gives a result between 10 and 100, so they are very different formulas. What's important here is clarity, so whatever you do, make sure the code makes it clear what is being generated.
(PS. the first makes more sense if you change the variable 'max' to be called 'range')
All these work:
#include <iostream>
using namespace std;
//Good, because manual memory management isn't needed and this uses
//less heap memory (or no heap memory) so this is safer if
//used in a low memory situation
void f() { throw string("foo"); }
//Valid, but avoid manual memory management if there's no reason to use it
void g() { throw new string("foo"); }
//Best. Just a pointer to a string literal, so no allocation is needed,
//saving on cleanup, and removing a chance for an allocation to fail.
void h() { throw "foo"; }
int main() {
try { f(); } catch (string s) { cout << s << endl; }
try { g(); } catch (string* s) { cout << *s << endl; delete s; }
try { h(); } catch (const char* s) { cout << s << endl; }
return 0;
}
You should prefer h to f to g. Note that in the least preferable option you need to free the memory explicitly.
In the .NET BCL, the class System.Exception
has a property called InnerException
, which points to another exception or else is null
. This forms a linked list.
In System.Type
, the BaseType
property points to another type in the same way.
If you want to ensure keyboard events are fired, consider using sendKeys(CharSequence)
.
Example 1:
from selenium.webdriver.common.keys import Keys
# ...
webElement.sendKeys(Keys.CONTROL + "a");
webElement.sendKeys(Keys.DELETE);
Example 2:
from selenium.webdriver.common.keys import Keys
# ...
webElement.sendKeys(Keys.BACK_SPACE); //do repeatedly, e.g. in while loop
There are many ways to get the required WebElement, e.g.:
webElement.clear();
If this element is a text entry element, this will clear the value.
Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events.
Here's what's actually happening localhost means that you want to open htdocs. First it will search for any file named index.php or index.html. If one of those exist it will open the file. If neither of those exist then it will open all folder/file inside htdocs directory which is what you want.
So, the simplest solution is to rename index.php or index.html to index2.php etc.
The default import method is already "relative", from the PYTHONPATH. The PYTHONPATH is by default, to some system libraries along with the folder of the original source file. If you run with -m to run a module, the current directory gets added to the PYTHONPATH. So if the entry point of your program is inside of Proj, then using import Common.Common
should work inside both Server.py and Client.py.
Don't do a relative import. It won't work how you want it to.
http://jsbin.com/etozop/2/edit
put a div wrapper with WIDTH :
<p><fieldset style="width:60px;">
<div style="border:solid 1px red;width:80px;">
<input type="checkbox" id="a">
<label for="a">a</label>
<input type="checkbox" id="b">
<label for="b">b</label>
</div>
<input type="checkbox" id="c">
<label for="c">c</label>
</fieldset></p>
a name could be " john winston ono lennon" which is very long... so what do you want to do? (youll never know the length)... you could make a function that wraps after x chars like : "john winston o...."
Real VNC server 4.4 includes support for Xrandr, which allows resizing the VNC. Start the server with:
vncserver -geometry 1600x1200 -randr 1600x1200,1440x900,1024x768
Then resize with:
xrandr -s 1600x1200
xrandr -s 1440x900
xrandr -s 1024x768
Actually, if you opt for creating an empty repo on GitHub it gives you exact instructions that you can almost copy and paste into your terminal which are (at this point in time):
…or create a new repository on the command line
echo "# ..." >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin [email protected]:<user>/<repo>.git
git push -u origin master
You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.
As Paul has already mentioned add "-lm
" to link with the math library in the step where you are attempting to generate your executable.
Why for
sin()
in<math.h>
, do we need-lm
option explicitly; but, not forprintf()
in<stdio.h>
?
Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).
This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:
Standard C Library
The Standard C library is automatically searched by
cc
to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.Standard C Mathematical Library
This library supports the Base System math routines, as defined in Volume 1. The
cc
option-lm
is used to search this library.
The reasoning behind this separation was influenced by a number of factors:
The pressures that fed into the decision to put -lm
in a different library probably included, but are not limited to:
sin()
and putting it in a custom built library.In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm
.
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
Had the same problem, I just coerced the id into a string.
My schema:
const product = new mongooseClient.Schema({
retailerID: { type: mongoose.SchemaTypes.ObjectId, required: true, index: true }
});
And then, when inserting:
retailerID: `${retailer._id}`
The ggeasy
package has a function called easy_center_title()
to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5))
and it's so much easier to remember.
ggplot(data = dat, aes(time, total_bill, fill = time)) +
geom_bar(colour = "black", fill = "#DD8888", width = .8, stat = "identity") +
guides(fill = FALSE) +
xlab("Time of day") +
ylab("Total bill") +
ggtitle("Average bill for 2 people") +
ggeasy::easy_center_title()
Note that as of writing this answer you will need to install the development version of ggeasy
from GitHub to use easy_center_title()
. You can do so by running remotes::install_github("jonocarroll/ggeasy")
.
The comment by @s29 should be an answer:
One way to add a directory to the virtual environment is to install virtualenvwrapper (which is useful for many things) and then do
mkvirtualenv myenv
workon myenv
add2virtualenv . #for current directory
add2virtualenv ~/my/path
If you want to remove these path edit the file myenvhomedir/lib/python2.7/site-packages/_virtualenv_path_extensions.pth
Documentation on virtualenvwrapper can be found at http://virtualenvwrapper.readthedocs.org/en/latest/
Specific documentation on this feature can be found at http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html?highlight=add2virtualenv
Found various approaches to refresh the application in selenium :-
1.driver.navigate().refresh();
2.driver.get(driver.getCurrentUrl());
3.driver.navigate().to(driver.getCurrentUrl());
4.driver.findElement(By.id("Contact-us")).sendKeys(Keys.F5);
5.driver.executeScript("history.go(0)");
For live code, please refer the link http://www.ufthelp.com/2014/11/Methods-Browser-Refresh-Selenium.html
Slicing works (and is the preferred approach), but just an alternative if more operations are needed (but then converting to a list wouldn't hurt anyway):
>>> a = '123456789'
>>> b = bytearray(a)
>>> del b[3]
>>> b
bytearray(b'12356789')
>>> str(b)
'12356789'
I tried following with ASP.NET MVC 5, its works for me
var sessionData = "@Session["SessionName"]";
my_string = "hello world";
my_insert = " dear";
my_insert_location = 5;
my_string = my_string.split('');
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');
Another way to achieve @David Baucum's solution in fewer steps:
It could be handier in some cases.
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
DISPLAY=pygame.display.set_mode((500,400),0,32)
WHITE=(255,255,255)
BLUE=(0,0,255)
DISPLAY.fill(WHITE)
pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
main()
This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect
to go about this, and you add the DISPLAY
constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.
Look up pygame.org for more info
xml:space="preserve"
Works like a charm.
Edit: Wrong. Actually, it only works when the content is comprised of white spaces only.
encodeURIComponent(JSON.stringify(object_to_be_serialised))
If you want to center elements inside a div and don't care about division size you could use Flex power. I prefer using flex and don't use exact size for elements.
<div class="outer flex">
<div class="inner">
This is the inner Content
</div>
</div>
As you can see Outer div is Flex container and Inner must be Flex item that specified with flex: 1 1 auto;
for better understand you could see this simple sample. http://jsfiddle.net/QMaster/hC223/
Hope this help.
You can use map
to return just the name, and then use this forEach
trick to check if it exists at least twice:
var areAnyDuplicates = false;
values.map(function(obj) {
return obj.name;
}).forEach(function (element, index, arr) {
if (arr.indexOf(element) !== index) {
areAnyDuplicates = true;
}
});
The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".
The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.
Do you have a table that has all dates? If not, you might want to consider implementing a calendar table and left joining your data onto the calendar table.
You could use:
jQuery('input[type="date"]').live('click', function(e) {e.preventDefault();}).datepicker();
So if someone else stumbles upon this here is a JavaScript solution to this problem:
Step 1: Hook your HTML number input box to an onchange
event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the html code if you so prefer
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
By changing the '2' in toFixed
you can get more or less decimal places if you so prefer.
Starting with the following sample data :
df <- data.frame(v1=letters[1:5],v2=1:5,v3=letters[10:14],stringsAsFactors=FALSE)
v1 v2 v3
1 a 1 j
2 b 2 k
3 c 3 l
4 d 4 m
5 e 5 n
You can use :
data.frame(lapply(df, function(v) {
if (is.character(v)) return(toupper(v))
else return(v)
}))
Which gives :
v1 v2 v3
1 A 1 J
2 B 2 K
3 C 3 L
4 D 4 M
5 E 5 N
This is the best way, I know of to create dynamic variables in python.
my_dict = {}
x = "Buffalo"
my_dict[x] = 4
I found a similar, but not the same question here Creating dynamically named variables from user input
var counter = 15;
var interval = setTimeout(function(){
// your interval code here
window.counter = dynamicValue;
interval();
}, counter);
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
1.> Change File format to .CSV (semicolon delimited)
To achieve the desired result we need to temporary change the delimiter
setting in the Excel
Options:
Move to File -> Options -> Advanced -> Editing Section
Uncheck the “Use system separators” setting and put a comma in the “Decimal Separator” field.
Now save the file in the .CSV
format and it will be saved in the semicolon delimited format.
There is a lot of misinformation out there on this topic, including here on Stack Overflow.
left join on
(aka left outer join on
) returns inner join on
rows union all
unmatched left table rows extended by null
s.
right join (on
aka right outer join on
) returns inner join on
rows union all
unmatched right table rows extended by null
s.
full join on
(aka full outer join on
) returns inner join on
rowsunion all
unmatched left table rows extended by null
s union all
unmatched right table rows extended by null
s.
(SQL Standard 2006 SQL/Foundation 7.7 Syntax Rules 1, General Rules 1 b, 3 c & d, 5 b.)
So don't outer join
until you know what underlying inner join
is involved.
Find out what rows inner join
returns.
The answer for your question:
You can find out the current key-bindings following this link
You can even edit the key-binding as per your preference.
Another simple way:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select
Selection.EntireRow.Delete
or simpler:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete
An equivalent statement would be
select * from [TableName] limit 5
If someone is looking for a PHP solution see "PHP_MySQL_wrapper":
$db = new MySQL_wrapper(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
// this sample gets column names from first row of file
//$db->createTableFromCSV('test_files/countrylist.csv', 'csv_to_table_test');
// this sample generates column names
$db->createTableFromCSV('test_files/countrylist1.csv', 'csv_to_table_test_no_column_names', ',', '"', '\\', 0, array(), 'generate', '\r\n');
/** Create table from CSV file and imports CSV data to Table with possibility to update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg date format or increment (SQL format only @FIELD is variable with content of that field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or generate) - this is important if there is update while inserting (Default: file)
* @param string $newLine - New line delimiter (Default: \n)
* @return number of inserted rows or false
*/
// function createTableFromCSV($file, $table, $delimiter = ',', $enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = '\r\n')
$db->close();
You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.
That's why your example uses Active X, which bypasses the JavaScript security issues.
So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.
Read Alist Apart: Going to Print for a good article on the subject of print stylesheets.
sub.data<-data[ data[,1] != "b" & data[,1] != "d" & data[,1] != "e" , ]
Larger but simple to understand (I guess) and can be used with multiple columns, even with !is.na( data[,1])
.
from datetime import datetime
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DateType
# Creation of a dummy dataframe:
df1 = sqlContext.createDataFrame([("11/25/1991","11/24/1991","11/30/1991"),
("11/25/1391","11/24/1992","11/30/1992")], schema=['first', 'second', 'third'])
# Setting an user define function:
# This function converts the string cell into a date:
func = udf (lambda x: datetime.strptime(x, '%m/%d/%Y'), DateType())
df = df1.withColumn('test', func(col('first')))
df.show()
df.printSchema()
Here is the output:
+----------+----------+----------+----------+
| first| second| third| test|
+----------+----------+----------+----------+
|11/25/1991|11/24/1991|11/30/1991|1991-01-25|
|11/25/1391|11/24/1992|11/30/1992|1391-01-17|
+----------+----------+----------+----------+
root
|-- first: string (nullable = true)
|-- second: string (nullable = true)
|-- third: string (nullable = true)
|-- test: date (nullable = true)
Individual components of a filename (i.e. each subdirectory along the path, and the final filename) are limited to 255 characters, and the total path length is limited to approximately 32,000 characters.
However, on Windows, you can't exceed MAX_PATH
value (259 characters for files, 248 for folders). See http://msdn.microsoft.com/en-us/library/aa365247.aspx for full details.
You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.
Sub deleteCol()
On Error Resume Next
Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer
Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
End If
Next i
End Sub
With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.
EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare)
change the "1" in Cells(1, i)
to whatever row your headers are in.
EDIT 2: Changed the For
section of the code to account for completely empty columns.
The best answer here:
https://www.git-tower.com/learn/git/glossary/origin
In Git, "origin" is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository's URL - and thereby makes referencing much easier.
If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]
If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.
Knowing this, the following will work:
In the markup code:
<input id="responsable" name="checkResp" value="true" type="checkbox" />
And your action method signature:
public ActionResult Index( string responsables, bool checkResp = false)
This will work because when the checkbox is checked, the postback will contain checkResp=true
, and if the checkbox is not checked the parameter will default to false.
According to http://docs.python.org/dev/py3k/library/stdtypes.html#dictionary-view-objects , the keys(), values() and items() methods of a dict will return corresponding iterators whose orders correspond. However, I am unable to find a reference to the official documentation for python 2.x for the same thing.
So as far as I can tell, the answer is yes, but only in python 3.0+
A very basic approach is alert(arrayObj.join('\n'))
, which will display each array element in a row.
In WinForms and WebForms you can do:
txtName.BackColor = Color.Aqua;
Here is an example of the practical significance of the difference and how it can bite you if you don't realize it (document.location being an object and document.location.href being a string):
We use MonoX Social CMS (http://mono-software.com) free version at http://social.ClipFlair.net and we wanted to add the language bar WebPart at some pages to localize them, but at some others (e.g. at discussions) we didn't want to use localization. So we made two master pages to use at all our .aspx (ASP.net) pages, in the first one we had the language bar WebPart and the other one had the following script to remove the /lng/el-GR etc. from the URLs and show the default (English in our case) language instead for those pages
<script>
var curAddr = document.location; //MISTAKE
var newAddr = curAddr.replace(new RegExp("/lng/[a-z]{2}-[A-Z]{2}", "gi"), "");
if (curAddr != newAddr)
document.location = newAddr;
</script>
But this code isn't working, replace function just returns Undefined (no exception thrown) so it tries to navigate to say x/lng/el-GR/undefined instead of going to url x. Checking it out with Mozilla Firefox's debugger (F12 key) and moving the cursor over the curAddr variable it was showing lots of info instead of some simple string value for the URL. Selecting Watch from that popup you could see in the watch pane it was writing "Location -> ..." instead of "..." for the url. That made me realize it was an object
One would have expected replace to throw an exception or something, but now that I think of it the problem was that it was trying to call some non-existent "replace" method on the URL object which seems to just give back "undefined" in Javascript.
The correct code in that case is:
<script>
var curAddr = document.location.href; //CORRECT
var newAddr = curAddr.replace(new RegExp("/lng/[a-z]{2}-[A-Z]{2}", "gi"), "");
if (curAddr != newAddr)
document.location = newAddr;
</script>
If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?
I'm assuming your using a streams here, there are other ways to write a file.
sendStickyBroadcast()
performs a sendBroadcast(Intent)
known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter)
. In all other ways, this behaves the same as sendBroadcast(Intent)
. One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED
. When you call registerReceiver()
for that action -- even with a null BroadcastReceiver
-- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
Indeed, there is type conversion to int. Also you can force type to char by using %hhx specifier.
printf("%hhX", a);
In most cases you will want to set the minimum length as well to fill the second character with zeroes:
printf("%02hhX", a);
ISO/IEC 9899:201x says:
7 The length modifiers and their meanings are: hh Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following
Double-check if you're using full-version of jquery and not some slim version.
I was using the jquery cdn-script link that comes with jquery. The problem is this one by default is slim.jquery.js which doesn't have the ajax
function in it. So, if you're using (copy-pasted from Bootstrap website) slim version jquery script link, use the full version instead.
That is to say use
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
instead of
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
As Jake points out, TARGET_IPHONE_SIMULATOR
is a subset of TARGET_OS_IPHONE
.
Also, TARGET_OS_IPHONE
is a subset of TARGET_OS_MAC
.
So a better approach might be:
#ifdef _WIN64
//define something for Windows (64-bit)
#elif _WIN32
//define something for Windows (32-bit)
#elif __APPLE__
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
// define something for simulator
#elif TARGET_OS_IPHONE
// define something for iphone
#else
#define TARGET_OS_OSX 1
// define something for OSX
#endif
#elif __linux
// linux
#elif __unix // all unices not caught above
// Unix
#elif __posix
// POSIX
#endif
First of all, beware of that method:
As Jesse Ezel says:
"The method might seem convenient, but most of the time I have found that this situation arises from trying to cover up deeper bugs.
Your code should stick to a particular protocol on the use of strings, and you should understand the use of the protocol in library code and in the code you are working with.
The NullOrEmpty protocol is typically a quick fix (so the real problem is still somewhere else, and you got two protocols in use) or it is a lack of expertise in a particular protocol when implementing new code (and again, you should really know what your return values are)."
And if you patch String class... be sure NilClass has not been patch either!
class NilClass
def empty?; true; end
end
Try git rebase -i master
on your feature branch. You can then change all but one 'pick' to 'squash' to combine the commits. See squashing commits with rebase
Finally, you can then do the merge from master branch.
I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:
Your answer (assuming this works, I haven't tried this):
<div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">
Second option:
@if (Model.Details.Count > 0) {
<div class="details show">
}
else {
<div class="details hide">
}
Third option:
<div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">
add:
margin: 0 0 3px 0;
to your #access li
and move
background: #0f84e8; /* Show a solid color for older browsers */
to the #access a
and take out the border-bottom
. Then it will work