For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
I was facing the same problem. This way I was able to solved it. As CQM said, using Color.parseColor() is a good solution to this issue.
Here is the code I used:
this.Button_C.setTextColor(Color.parseColor(prefs.getString("color_prefs", String.valueOf(R.color.green))));
In this case my target was to change the Button's text color (Button_C) when I change the color selection from my Preferences (color_prefs).
Kotlin has FileTreeWalk
for this purpose. For example:
dataDir.walkTopDown().filter { !it.isDirectory }.joinToString("\n") {
"${it.toRelativeString(dataDir)}: ${it.length()}"
}
Will produce a text list of all the non-directory files under a given root, one file per line with the path relative to the root and length.
Somthing like this should workL
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()
CSS min() and max() have fairly good usage rates in 2020.
The code below uses max() to get the largest of the [variablevalue] and [minimumvalue] and then passes that through to min() against the [maximumvalue] to get the smaller of the two. This creates an allowable font range (3.5rem is minimum, 6.5rem is maximum, 6vw is used only when in between).
font-size: min(max([variablevalue], [minimumvalue]), [maximumvalue]);
font-size: min(max(6vw, 3.5rem), 6.5rem);
I'm using this specifically with font-awesome as a video-play icon over an image within a bootstrap container element where max-width is set.
If you want to install a npm module globally, make sure to use the new -g
flag, for example:
npm install forever -g
The general recommendations concerning npm module installation since 1.0rc (taken from blog.nodejs.org):
- If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
- If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.
I just recently used this recommendations and it went down pretty smoothly. I installed forever globally (since it is a command line tool) and all my application modules locally.
However, if you want to use some modules globally (i.e. express or mongodb), take this advice (also taken from blog.nodejs.org):
Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following:
- Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs.
- Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.
The first option is the best in my opinion. Simple, clear, explicit. The second is really handy if you are going to re-use the same library in a bunch of different projects. (More on npm link in a future installment.)
I did not test one of those variations, but they seem to be pretty straightforward.
Use Comparable
:
Use Comparator
:
Comparable
.Comparable
) behaviour.Simplest way to accomplish this task
If you want the query to be case-sensitive
db.getCollection("users").find({'username':/Son/})
If you want the query to be case-insensitive
db.getCollection("users").find({'username':/Son/i})
class ShadowContainer extends StatelessWidget {
ShadowContainer({
Key key,
this.margin = const EdgeInsets.fromLTRB(0, 10, 0, 8),
this.padding = const EdgeInsets.symmetric(horizontal: 8),
this.circular = 4,
this.shadowColor = const Color.fromARGB(
128, 158, 158, 158), //Colors.grey.withOpacity(0.5),
this.backgroundColor = Colors.white,
this.spreadRadius = 1,
this.blurRadius = 3,
this.offset = const Offset(0, 1),
@required this.child,
}) : super(key: key);
final Widget child;
final EdgeInsetsGeometry margin;
final EdgeInsetsGeometry padding;
final double circular;
final Color shadowColor;
final double spreadRadius;
final double blurRadius;
final Offset offset;
final Color backgroundColor;
@override
Widget build(BuildContext context) {
return Container(
margin: margin,
padding: padding,
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(circular),
boxShadow: [
BoxShadow(
color: shadowColor,
spreadRadius: spreadRadius,
blurRadius: blurRadius,
offset: offset,
),
],
),
child: child,
);
}
}
Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host')
is deprecated, that's why giving Undefined
.
Use,
req.header('Origin');
req.header('Host');
// this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.
An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).
If you are using SQL Azure Reporting Services, the "format" function is unsupported. This is really the only way to format a tooltip in a chart in SSRS. So the workaround is to return a column that has a string representation of the formatted number to use for the tooltip. So, I do agree that SQL is not the place for formatting. Except in cases like this where the tool does not have proper functions to handle display formatting.
In my case I needed to show a number formatted with commas and no decimals (type decimal 2) and ended up with this gem of a calculated column in my dataset query:
,Fmt_DDS=reverse(stuff(reverse(CONVERT(varchar(25),cast(SUM(kv.DeepDiveSavingsEst) as money),1)), 1, 3, ''))
It works, but is very ugly and non-obvious to whoever maintains the report down the road. Yay Cloud!
If selected more 1 file:
$("input[type="file"]").change(function() {
var files = $("input[type="file"]").prop("files");
var names = $.map(files, function(val) { return val.name; });
$(".some_div").text(names);
});
files
will be a FileList
object. names
is an array of strings (file names).
try following
try {
String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
Process p = Runtime.getRuntime().exec(command);
} catch (IOException ex) {
}
You should use BottomNavigationView from v25 Android Support Library. It represents a standard bottom navigation bar for application.
Here is a post on Medium that has a step by step guide: https://medium.com/@hitherejoe/exploring-the-android-design-support-library-bottom-navigation-drawer-548de699e8e0#.9vmiekxze
Try this:
git add .
git commit -m "your commit message"
git remote add origin *remote repository URL*
git push origin *your-branch-name*
Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.
<span class="inputname">
Project Images:
<a href="#" class="add_project_file">
<img src="images/add_small.gif" border="0" />
</a>
</span>
<ul class="project_images">
<li><input name="upload_project_images[]" type="file" /></li>
</ul>
Wrapping the file inputs inside li
elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:
// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
e.preventDefault();
$(".project_images").append(
'<li>'
+ '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
+ '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
+ '</li>');
});
// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
e.preventDefault();
$(this).parent().remove();
});
Some people seem to be confusing these macros with assert()
.
These macros implement a compile-time test, while assert()
is a runtime test.
Here's a short example of immutable records using built-in collections.namedtuple
:
def record(name, d):
return namedtuple(name, d.keys())(**d)
and a usage example:
rec = record('Model', {
'train_op': train_op,
'loss': loss,
})
print rec.loss(..)
This question is confusing. A regular object, {}
doesn't have a length
property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in
statement on the object, since length
is not set, and increment a counter.
I'm confused as to why you need the length
. Are you manually setting 0
on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';
. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length
is already set.
A more simplified approach based on the accepted answer:
static public string Beautify(this XmlDocument doc) {
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
doc.Save(writer);
}
return sb.ToString();
}
Setting the new line is not necessary. Indent characters also has the default two spaces so I preferred not to set it as well.
Simply put, Git is a version control system that lets you manage and keep track of your source code history. GitHub is a cloud-based hosting service that lets you manage Git repositories. If you have open-source projects that use Git, then GitHub is designed to help you better manage them.
You can set padding to your view by pro grammatically throughout below code -
view.setPadding(0,1,20,3);
And, also there are different type of padding available -
These, links will refer Android Developers site. Hope this helps you lot.
Make sure you specify pass header=None
and add usecols=[3,6]
for the 4th and 7th columns.
IE doesn't support outline-offset so another solution would be to create 2 div tags, one nested into the other one. The inner one would have a border and be slightly smaller than the container.
.container {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
width: 400px;_x000D_
height: 100px;_x000D_
background: #000000;_x000D_
padding: 10px;_x000D_
}_x000D_
.inner {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: #000000;_x000D_
border: 1px dashed #ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="inner"></div>_x000D_
</div>
_x000D_
I would go a step further than just saying "use a docstring". Pick a documentation generation tool, such as pydoc or epydoc (I use epydoc in pyparsing), and use the markup syntax recognized by that tool. Run that tool often while you are doing your development, to identify holes in your documentation. In fact, you might even benefit from writing the docstrings for the members of a class before implementing the class.
After following the steps from @Johnride, I still got the same error.
This fixed the problem:
Tools-> Options-> Select no proxy
No. Scroll speed is determined by the browser (and usually directly by the settings on the computer/device). CSS and Javascript don't (or shouldn't) have any way to affect system settings.
That being said, there are likely a number of ways you could try to fake a different scroll speed by moving your own content around in such a way as to counteract scrolling. However, I think doing so is a HORRIBLE idea in terms of usability, accessibility, and respect for your users, but I would start by finding events that your target browsers fire that indicate scrolling.
Once you can capture the scroll event (assuming you can), then you would be able to adjust your content dynamically so that the portion you want is visible.
Another approach would be to deal with this in Flash, which does give you at least some level of control over scrolling events.
For pattern matching use LIKE. For exact match =.
you must change php_admin_value max_execution_time
in your Alias config (\XAMPP\alias\phpmyadmin.conf)
answer is here: WAMPServer phpMyadmin Maximum execution time of 360 seconds exceeded
We can hide close button on form by setting this.ControlBox=false;
Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.
Here is the script in Python.
You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.
element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)
Do I understand right that you assume that DATE_ADD("2011-01-01", INTERVAL 6 MONTH)
should give you '2011-06-30' instead of '2011-07-01'? Of course, 2011-01-01 + 6 months is 2011-07-01. You want something like DATE_SUB(DATE_ADD("2011-01-01", INTERVAL 6 MONTH), INTERVAL 1 DAY)
.
I prefer a non blocking approach:
Dim aw1=GenerateCodeAsync().GetAwaiter()
While Not aw1.IsCompleted
Application.DoEvents()
End While
If you want to use LinearLayout, you can do alignment with layout_weight
with Space
element.
E.g. following layout places textView
and textView2
next to each other and textView3
will be right-aligned
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView2" />
<Space
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView3" />
</LinearLayout>
you can achieve the same effect without Space
if you would set layout_weight
to textView2
. It's just that I like things more separated, plus to demonstrate Space
element.
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView2" />
Note that you should (not must though) set layout_width
explicitly as it will be recalculated according to it's weight anyway (same way you should set height in elements of vertical LinearLayout
). For other layout performance tips see Android Layout Tricks series.
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
To remove rows based on Nan value of particular column:
d= pd.DataFrame([[2,3],[4,None]]) #creating data frame
d
Output:
0 1
0 2 3.0
1 4 NaN
d = d[np.isfinite(d[1])] #Select rows where value of 1st column is not nan
d
Output:
0 1
0 2 3.0
Another method utilizing the dplyr package:
library(dplyr)
df <- mtcars %>%
filter(mpg > 25)
Without the chain (%>%) operator:
library(dplyr)
df <- filter(mtcars, mpg > 25)
Use x11docker by mviereck:
https://github.com/mviereck/x11docker#hardware-acceleration says
Hardware acceleration
Hardware acceleration for OpenGL is possible with option -g, --gpu.
This will work out of the box in most cases with open source drivers on host. Otherwise have a look at wiki: feature dependencies. Closed source NVIDIA drivers need some setup and support less x11docker X server options.
This script is really convenient as it handles all the configuration and setup. Running a docker image on X with gpu is as simple as
x11docker --gpu imagename
I would suggest using System.Runtime.Serialization.Json
that is part of .NET 4.5.
[DataContract]
public class Foo
{
[DataMember(Name = "data")]
public Dictionary<string,string> Data { get; set; }
}
Then use it like this:
var serializer = new DataContractJsonSerializer(typeof(List<Foo>));
var jsonParams = @"{""data"": [{""Key"":""foo"",""Value"":""bar""}] }";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));
var obj = serializer.ReadObject(stream);
Console.WriteLine(obj);
The money datatype on SQL Server has four digits after the decimal.
From SQL Server 2000 Books Online:
Monetary data represents positive or negative amounts of money. In Microsoft® SQL Server™ 2000, monetary data is stored using the money and smallmoney data types. Monetary data can be stored to an accuracy of four decimal places. Use the money data type to store values in the range from -922,337,203,685,477.5808 through +922,337,203,685,477.5807 (requires 8 bytes to store a value). Use the smallmoney data type to store values in the range from -214,748.3648 through 214,748.3647 (requires 4 bytes to store a value). If a greater number of decimal places are required, use the decimal data type instead.
Here is the plugin that is useful for preventing parent scroll while scrolling a specific div and has a bunch of options to play with.
Check it out here:
https://github.com/MohammadYounes/jquery-scrollLock
Usage
Trigger Scroll Lock via JavaScript:
$('#target').scrollLock();
Trigger Scroll Lock via Markup:
<!-- HTML -->
<div data-scrollLock
data-strict='true'
data-selector='.child'
data-animation='{"top":"top locked","bottom":"bottom locked"}'
data-keyboard='{"tabindex":0}'
data-unblock='.inner'>
...
</div>
<!-- JavaScript -->
<script type="text/javascript">
$('[data-scrollLock]').scrollLock()
</script>
View Demo
on tomcat v.7 (vanilla installation)
in your conf/server.xml add the following bit towards the end of the file, just before the </Host>
closing tag:
<Context path="" docBase="app_name">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
Note that docBase attribute. It's the important bit. You either make sure you've deployed app_name before you change your root web app, or just copy your unpacked webapp (app_name) into your tomcat's webapps folder. Startup, visit root, see your app_name there!
I made my own way based on Caitlin Morris's answer for fetching all folowers and followings on Instagram. Just copy this code, paste in browser console and wait for a few seconds.
You need to use browser console from instagram.com tab to make it works.
let username = 'USERNAME'
let followers = [], followings = []
try {
let res = await fetch(`https://www.instagram.com/${username}/?__a=1`)
res = await res.json()
let userId = res.graphql.user.id
let after = null, has_next = true
while (has_next) {
await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
id: userId,
include_reel: true,
fetch_mutual: true,
first: 50,
after: after
}))).then(res => res.json()).then(res => {
has_next = res.data.user.edge_followed_by.page_info.has_next_page
after = res.data.user.edge_followed_by.page_info.end_cursor
followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
return {
username: node.username,
full_name: node.full_name
}
}))
})
}
console.log('Followers', followers)
has_next = true
after = null
while (has_next) {
await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
id: userId,
include_reel: true,
fetch_mutual: true,
first: 50,
after: after
}))).then(res => res.json()).then(res => {
has_next = res.data.user.edge_follow.page_info.has_next_page
after = res.data.user.edge_follow.page_info.end_cursor
followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
return {
username: node.username,
full_name: node.full_name
}
}))
})
}
console.log('Followings', followings)
} catch (err) {
console.log('Invalid username')
}
As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).
Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from
.
Using compose (1.6.2 in my machine), the docker-compose.yml
file would read:
version: "2"
services:
nginx:
build:
context: .
dockerfile: nginx/Dockerfile
ports:
- "80:80"
links:
- fpm
volumes_from:
- data
fpm:
image: php:fpm
volumes_from:
- data
data:
build:
context: .
dockerfile: data/Dockerfile
volumes:
- /var/www/html
Note that data
publishes a volume that is linked to the nginx
and fpm
services. Then the Dockerfile
for the data service, that contains your source code:
FROM busybox
# content
ADD path/to/source /var/www/html
And the Dockerfile
for nginx, that just replaces the default config:
FROM nginx
# config
ADD config/default.conf /etc/nginx/conf.d
For the sake of completion, here's the config file required for the example to work:
server {
listen 0.0.0.0:80;
root /var/www/html;
location / {
index index.php index.html;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass fpm:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
}
which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT
, which is fpm:9000
thanks to the hostnames defined by compose, and the SCRIPT_FILENAME
).
Could find nothing simpler and better than this solution. Also see the doc.
@register.filter
def dictitem(dictionary, key):
return dictionary.get(key)
But there's a problem (also discussed here) that the returned item is an object and I need to reference a field of this object. Expressions like {{ (schema_dict|dictitem:schema_code).name }}
are not supported, so the only solution I found was:
{% with schema=schema_dict|dictitem:schema_code %}
<p>Selected schema: {{ schema.name }}</p>
{% endwith %}
UPDATE:
@register.filter
def member(obj, name):
return getattr(obj, name, None)
So no need for a with
tag:
{{ schema_dict|dictitem:schema_code|member:'name' }}
double click the button and add write // this.close();
private void buttonClick(object sender, EventArgs e)
{
this.Close();
}
This is what works for me:
I had to put my local server address in the PHP Server configuration like this:
Note: that address, is the one I configure in my Apache .conf file.
Note: the only breakpoint that was working was the 'Break at first line', after that, the breakpoints didn't work.
Note: check your xdebug properties in your php.ini file, and remove any you think is not required.
Probably the worst python line I've written so far:
f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])
If x == 2 you print,
if x != 2 you raise.
Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send
System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:
Here is what the trace log looked like on the machine where the client certificate failed.
System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.
Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL
Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)
After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.
gradle --recompile-scripts
seems to do a sync without building anything. you can enable automatic building by
gradle --recompile-scripts --continuous
Please refer the docs for more info:
https://docs.gradle.org/current/userguide/gradle_command_line.html
For me, the problem was I was using a package that isn't included in package.json
nor installed.
import { ToastrService } from 'ngx-toastr';
So when the compiler tried to compile this, it threw an error.
(I installed it locally, and when running a build on an external server the error was thrown)
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
Hm.
You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo)
Following code works well for me
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
Point p = e.GetPosition(this);
}
I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow
will help you.
<script>
arr = []
arr[0] = "ab"
arr[1] = "abcdefgh"
arr[2] = "sdfds"
arr.sort(function(a,b){
return a.length<b.length
})
document.write(arr)
</script>
The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do
In file /etc/ssh/sshd_config
# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication no
Uncomment the second line, and, if needed, change yes to no.
Then run
service ssh restart
you can simply try this. it will return you current machine time
var _d = new Date(), t = 0, d = new Date(t*1000 + _d.getTime())
As Brad Wilson states in his answer here:
ModelState.IsValid tells you if any model errors have been added to ModelState.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
Try using :-
if (!ModelState.IsValid)
{
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
// Breakpoint, Log or examine the list with Exceptions.
}
If it helps catching you the error. Courtesy this and this
I have your answer, as I just had the same problem today:
Someone made a working vba code that changes the vba protection password to "macro", for all excel files, including .xlsm (2007+ versions). You can see how it works by browsing his code.
This is the guy's blog: http://lbeliarl.blogspot.com/2014/03/excel-removing-password-from-vba.html Here's the file that does the work: https://docs.google.com/file/d/0B6sFi5sSqEKbLUIwUTVhY3lWZE0/edit
Pasted from a previous post from his blog:
For Excel 2007/2010 (.xlsm) files do following steps:
Find and copy the value from parameter DPB (value in quotation mark), example: DPB="282A84CBA1CBA1345FCCB154E20721DE77F7D2378D0EAC90427A22021A46E9CE6F17188A". (This value generated for 'macro' password. You can use this DPB value to skip steps 1-8)
Do steps 4-7 for file with unknown password (file you want to unlock).
Change DBP value in this file on value that you have copied in step 8.
If copied value is shorter than in encrypted file you should populate missing characters with 0 (zero). If value is longer - that is not a problem (paste it as is).
Save the 'vbaProject.bin' file and exit from hex editor.
I didn't like bhavya's answer because of using AppDelegate
inside View Controllers and setting rootViewController
has no animation. And Trevor's answer has issue with flashing view controller on iOS8.
UPD 07/18/2015
AppDelegate inside View Controllers:
Changing AppDelegate state (properties) inside view controller breaks encapsulation.
Very simple hierarchy of objects in every iOS project:
AppDelegate (owns window
and rootViewController
)
ViewController (owns view
)
It's ok that objects from the top change objects at the bottom, because they are creating them. But it's not ok if objects on the bottom change objects on top of them (I described some basic programming/OOP principle : DIP (Dependency Inversion Principle : high level module must not depend on the low level module, but they should depend on abstractions)).
If any object will change any object in this hierarchy, sooner or later there will be a mess in the code. It might be ok on the small projects but it's no fun to dig through this mess on the bit projects =]
UPD 07/18/2015
I replicate modal controller animations using UINavigationController
(tl;dr: check the project).
I'm using UINavigationController
to present all controllers in my app. Initially I displayed login view controller in navigation stack with plain push/pop animation. Than I decided to change it to modal with minimal changes.
How it works:
Initial view controller (or self.window.rootViewController
) is UINavigationController with ProgressViewController as a rootViewController
. I'm showing ProgressViewController because DataModel can take some time to initialize because it inits core data stack like in this article (I really like this approach).
AppDelegate is responsible for getting login status updates.
DataModel handles user login/logout and AppDelegate is observing it's userLoggedIn
property via KVO. Arguably not the best method to do this but it works for me. (Why KVO is bad, you can check in this or this article (Why Not Use Notifications? part).
ModalDismissAnimator and ModalPresentAnimator are used to customize default push animation.
How animators logic works:
AppDelegate sets itself as a delegate of self.window.rootViewController
(which is UINavigationController).
AppDelegate returns one of animators in -[AppDelegate navigationController:animationControllerForOperation:fromViewController:toViewController:]
if necessary.
Animators implement -transitionDuration:
and -animateTransition:
methods. -[ModalPresentAnimator animateTransition:]
:
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
[[transitionContext containerView] addSubview:toViewController.view];
CGRect frame = toViewController.view.frame;
CGRect toFrame = frame;
frame.origin.y = CGRectGetHeight(frame);
toViewController.view.frame = frame;
[UIView animateWithDuration:[self transitionDuration:transitionContext]
animations:^
{
toViewController.view.frame = toFrame;
} completion:^(BOOL finished)
{
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
}
Test project is here.
No Gemfile.lock means:
-> Always check in Gemfile.lock, make travis delete it if you want to be extra thorough https://grosser.it/2015/08/14/check-in-your-gemfile-lock/
Backup
..PLAIN
for Format USE INSERT COMMANDS
Use Column Inserts
if you want column names in your inserts.Backup
buttonI have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause
DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave
I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered
From my experience the default location is /var/lib/mongodb
after I do
sudo apt-get install -y mongodb-org
Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().
Spread syntax for object literals was introduced in ECMAScript 2018):
const a = { "one": 1, "two": 2 };
const b = { "three": 3 };
const c = { "four": 4, "five": 5 };
const result = {...a, ...b, ...c};
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }
Spread (...) operator is supported in many modern browsers but not all of them.
So, it is recommend to use a transpiler like Babel to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
This is the equivalent code Babel will generate for you:
"use strict";
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var a = { "one": 1, "two": 2 };
var b = { "three": 3 };
var c = { "four": 4, "five": 5 };
var result = _extends({}, a, b, c);
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }
ng-click "$watch(edit($index), open())"
You must use CSS. Can't be done with PHP.
ToggleImageButton
which implements Checkable
interface and supports OnCheckedChangeListener
and android:checked
xml attribute:
public class ToggleImageButton extends ImageButton implements Checkable {
private OnCheckedChangeListener onCheckedChangeListener;
public ToggleImageButton(Context context) {
super(context);
}
public ToggleImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
setChecked(attrs);
}
public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setChecked(attrs);
}
private void setChecked(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
a.recycle();
}
@Override
public boolean isChecked() {
return isSelected();
}
@Override
public void setChecked(boolean checked) {
setSelected(checked);
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, checked);
}
}
@Override
public void toggle() {
setChecked(!isChecked());
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
public OnCheckedChangeListener getOnCheckedChangeListener() {
return onCheckedChangeListener;
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
}
}
res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToggleImageButton">
<attr name="android:checked" />
</declare-styleable>
</resources>
Please do yourself a favor and just hit the easy button:
download Web Inspector (Open Source) from the Play store.
A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:
console.log('one', 'two', 'three');
you will only see
one
logged to the console. You'll need to manually wrap the params in an Array and join, like so:
console.log([ 'one', 'two', 'three' ].join(' '));
to see the expected output.
But the app is open source! A patch may be imminent! The patcher could even be you!
Here is my simplistic log4j2.xml
that prints to console and writes to a daily rolling file:
// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);
// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="logPath">target/cucumber-logs</Property>
<Property name="rollingFileName">cucumber</Property>
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
</Console>
<RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
<PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
<Policies>
<!-- Causes a rollover if the log file is older than the current JVM's start time -->
<OnStartupTriggeringPolicy />
<!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="DEBUG" additivity="false">
<AppenderRef ref="console" />
<AppenderRef ref="rollingFile" />
</Root>
</Loggers>
</Configuration>
TimeBasedTriggeringPolicy
interval (integer) - How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.
modulate (boolean) - Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.
Source: https://logging.apache.org/log4j/2.x/manual/appenders.html
Output:
[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000
A new log file will be created daily with previous day automatically renamed to:
cucumber_yyyy-MM-dd.log
In a Maven project, you would put the log4j2.xml
in src/main/resources
or src/test/resources
.
Here are the primary differences:
Syntax: module.service( 'serviceName', function );
Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service
.
Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending ( )
to the injected function reference. Could also be run with injectedArg.call( this )
or similar.
Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory
.
Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.
Here is example using services and factory. Read more about AngularJS Service vs Factory.
You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.
On Windows Powershell I run this:
git stash apply "stash@{1}"
Maybe you should use a display inline-block too:
.circle {
display: inline-block;
height: 25px;
width: 25px;
background-color: #bbb;
border-radius: 50%;
z-index: -1;
}
For a view you can set opacity by the following.
view_name.setAlpha(float_value);
The property view.setAlpha(int)
is deprecated for the API version greater than 11. Henceforth, property like .setAlpha(0.5f)
is used.
I believe the Ajax response handler uses the HTTP status code to check if there was an error.
So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.
I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.
I then set the Response.StatusCode
to either 500 or 200 whether I had an error or not.
Based on an Aptana Studio support response, it was confirmed that the Aptana plugin and Android Development Tools collide on this port (i.e. Aptana's Comet server overlapped on this port). Aptana opened a ticket back in 2010.
Unfortunately, it does not appear that Aptana has fixed it yet or made their Comet server port configurable. Changing the port number in eclipse and restarting adb did NOT fix it for me. I finally was forced to uninstall the Aptana plugin.
It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
pno (*AddClient)(client_t *);
};
pno client_t_AddClient(client_t *self) { /* code */ }
int main()
{
client_t client;
client.AddClient = client_t_AddClient; // probably really done in some init fn
//code ..
client.AddClient(&client);
}
It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.
You may also need to provide your contact info, bank info, and tax info in this page so it will allow your last release on App Store:
https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/6.0
For attached properties you can either call SetValue on the object for which you want to assign the value:
tblock.SetValue(Grid.RowProperty, 4);
Or call the static Set method (not as an instance method like you tried) for the property on the owner type, in this case SetRow:
Grid.SetRow(tblock, 4);
instead of writing listb.pop[0]
write
listb.pop()[0]
^
|
Isodate seems to have the most complete support.
To make it just show up in your JSP pages, you can use the Spring Security Tag Lib:
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html
To use any of the tags, you must have the security taglib declared in your JSP:
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
Then in a jsp page do something like this:
<security:authorize access="isAuthenticated()">
logged in as <security:authentication property="principal.username" />
</security:authorize>
<security:authorize access="! isAuthenticated()">
not logged in
</security:authorize>
NOTE: As mentioned in the comments by @SBerg413, you'll need to add
use-expressions="true"
to the "http" tag in the security.xml config for this to work.
Your code work fine, provided the value in Sheet2!D2
exists in Sheet1!A:A
. If it does not then error 1004 is raised.
To handle this case, try
Sub Demo()
Dim MyStringVar1 As Variant
On Error Resume Next
MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
Worksheets("Sheet1").Range("A:C"), 1, False)
On Error GoTo 0
If IsEmpty(MyStringVar1) Then
MsgBox "Value not found!"
End If
Range("E2") = MyStringVar1
End Sub
You really should try to google first.
Wikipedia has a explanation of leap years. The algorithm your describing is for the Proleptic Gregorian calendar.
More about the math around it can be found in the article Calendar Algorithms.
since PHP 5.4 you can use http_response_code()
for get and set header status code.
here an example:
<?php
// Get the current response code and set a new one
var_dump(http_response_code(404));
// Get the new response code
var_dump(http_response_code());
?>
here is the document of this function in php.net:
JAVA_HOME = C:\Program Files\Java\jdk(JDK version number)
Example: C:\Program Files\Java\jdk-10
And then restart you command prompt it works.
Your jQuery code works perfectly. The hidden field is being updated.
I had a similar situation but the following worked best for me..
=Iif(Fields!Sales_Diff.Value)>1,Fields!Sales_Diff.Value),"")
As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:
<style>
input:not([value=""]){
border:2px solid red;
}
</style>
<input type="text" onkeyup="this.setAttribute('value', this.value);"/>
I am using those two collectors:
public static <T> Collector<T, ?, Optional<T>> zeroOrOne() {
return Collectors.reducing((a, b) -> {
throw new IllegalStateException("More than one value was returned");
});
}
public static <T> Collector<T, ?, T> onlyOne() {
return Collectors.collectingAndThen(zeroOrOne(), Optional::get);
}
Setting the underlying socket ReceiveTimeout
property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout
. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
Here is the code for the short version of if-then-else statement:
( [ $a -eq 1 ] || [ $b -eq 2 ] ) && echo "ok" || echo "nok"
Pay attention to the following:
||
and &&
operands inside if condition (i.e. between round parentheses) are logical operands (or/and)
||
and &&
operands outside if condition mean then/else
Practically the statement says:
if (a=1 or b=2) then "ok" else "nok"
From MSDN
To execute a stored procedure returning rows programmatically using a command object
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
someVar = reader(0)
someVar2 = reader(1)
someVar3 = reader("NamedField")
End If
sqlConnection1.Close()
If you are using
a = [];
Then you are assigning new array reference to a, if reference in a is already assigned to any other variable, then it will not empty that array too and hence garbage collector will not collect that memory.
For ex.
var a=[1,2,3];
var b=a;
a=[];
console.log(b);// It will print [1,2,3];
or
a.length = 0;
When we specify a.length
, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector.
Instead of these two solutions are better.
a.splice(0,a.length)
and
while(a.length > 0) {
a.pop();
}
As per previous answer by kenshou.html, second method is faster.
You can SSH in to docker container as root by using
docker exec -it --user root <container_id> /bin/bash
Then change root password using this
passwd root
Make sure sudo is installed check by entering
sudo
if it is not installed install it
apt-get install sudo
If you want to give sudo permissions for user dev you can add user dev to sudo group
usermod -aG sudo dev
Now you'll be able to run sudo level commands from your dev user while inside the container or else you can switch to root inside the container by using the password you set earlier.
To test it login as user dev and list the contents of root directory which is normally only accessible to the root user.
sudo ls -la /root
Enter password for dev
If your user is in the proper group and you entered the password correctly, the command that you issued with sudo should run with root privileges.
I see it is an old thread but I had the same error.
I found the explanation here: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
void execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
void execSQL(String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
Acknowledging the fact that the asker specifically requested jQuery and that the answer selected is correct, it should be noted that this problem doesn't actually need jQuery per say. If one desires to solve this problem without it, one can simply set the onClick
attribute of the checkboxes that he or she wants to add additional functionality to, like so:
HTML:
<form id="myform">
<input type="checkbox" name="check1" value="check1" onClick="cbChanged(this);">
<input type="checkbox" name="check2" value="check2" onClick="cbChanged(this);">
</form>
javascript:
function cbChanged(checkboxElem) {
if (checkboxElem.checked) {
// Do something special
} else {
// Do something else
}
}
Fiddle: http://jsfiddle.net/Y9f66/1/
If you need to create each ArrayList item in a single line then you can use this code
private void createFile(String file, ArrayList<String> arrData)
throws IOException {
FileWriter writer = new FileWriter(file + ".txt");
int size = arrData.size();
for (int i=0;i<size;i++) {
String str = arrData.get(i).toString();
writer.write(str);
if(i < size-1)**//This prevent creating a blank like at the end of the file**
writer.write("\n");
}
writer.close();
}
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
I agree with @pkozlowski.opensource answer, but ng-clock class did't work for me for using with ng-repeat. so I would like to recommend you to use class for simple delimiter expression like {{name}} and ngCloak directive for ng-repeat.
<div class="ng-cloak">{{name}}<div>
and
<li ng-repeat="item in items" ng-cloak>{{item.name}}<li>
The first argument should be the path to the executable program. So
gdb progname 12271
The API was designed to support a solution that matches closely to business requirements
import static java.time.temporal.TemporalAdjusters.*;
LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.with(firstDayOfMonth());
LocalDate end = initial.with(lastDayOfMonth());
However, Jon's solutions are also fine.
I changed to type text and back to type to file using setAttribute
'<input file-model="thefilePic" style="width:95%;" type="file" name="file" id="filepicture" accept="image/jpeg" />'
'var input=document.querySelector('#filepicture');'
if(input != null)
{
input.setAttribute("type", "text");
input.setAttribute("type", "file");
}
So you're using screen to keep the experiments running in the background, or what? If so, why not just start it in the background?
./experiment &
And if you're asking how to get notification the job i done, how about stringing the experiment together with a mail command?
./experiment && echo "the deed is done" | mail youruser@yourlocalworkstation -s "job on server $HOSTNAME is done"
ffmpeg supports the mov_text
subtitle encoder which is about the only one supported in an MP4 container and playable by iTunes, Quicktime, iOS etc.
Your line would read:
ffmpeg -i input.mp4 -i input.srt -map 0:0 -map 0:1 -map 1:0 -c:s mov_text output.mp4
Try below code if you want to use php loop to display
<span>
<select name="birth_month">
<?php for( $m=1; $m<=12; ++$m ) {
$month_label = date('F', mktime(0, 0, 0, $m, 1));
?>
<option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
<?php } ?>
</select>
</span>
<span>
<select name="birth_day">
<?php
$start_date = 1;
$end_date = 31;
for( $j=$start_date; $j<=$end_date; $j++ ) {
echo '<option value='.$j.'>'.$j.'</option>';
}
?>
</select>
</span>
<span>
<select name="birth_year">
<?php
$year = date('Y');
$min = $year - 60;
$max = $year;
for( $i=$max; $i>=$min; $i-- ) {
echo '<option value='.$i.'>'.$i.'</option>';
}
?>
</select>
</span>
Recursive function example:
def recursive(string, num):
print "#%s - %s" % (string, num)
recursive(string, num+1)
Run it with:
recursive("Hello world", 0)
use #include "ClasseAusiliaria.c"
[Dont use angle brackets (< >) ]
and I prefer save file with .h
extension in the same Directory/folder.
#include "ClasseAusiliaria.h"
Had the same exception. In my case, I had to run Command Prompt with Administrator Rights.
From the Start Menu, right click on Command Prompt, select "Run as administrator".
When you convert your variable to Date
:
date <- as.Date('10/30/2018','%m/%d/%Y')
you can then cut out the elements you want and make new variables, like year:
year <- as.numeric(format(date,'%Y'))
or month:
month <- as.numeric(format(date,'%m'))
from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;
Hope this helps
Putting *args
and/or **kwargs
as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:
def my_sum(*args):
return sum(args)
It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.
You don’t actually have to call them args
and kwargs
, that’s just a convention. It’s the *
and **
that do the magic.
The official Python documentation has a more in-depth look.
Siddharth's answer is terrific.
However, this technique can hit trouble when working with a large set of data (my computer froze up on 50,000 rows). Some less processor-intensive methods:
Single uniqueness check
Use a formula that looks at less data
=IF(SUMPRODUCT(($A2:$A3=A2)*($B2:$B3=B2))>1,0,1)
Multiple uniqueness checks
If you need to check uniqueness in different columns, you can't rely on two sorts.
Instead,
Add formula covering the maximum number of records for each grouping. If ABC might have 50 rows, the formula will be
=IF(SUMPRODUCT(($A2:$A49=A2)*($B2:$B49=B2))>1,0,1)
It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?
My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.
Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.
you can also use Recursion
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.
Here are a variety of ways to do this in base R
including an alternative aggregate
approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:
Using ave
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))
my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data
Using by
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)
my.data <- merge(my.data, by.month, by = 'Month')
my.data
Using lapply
and split
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)
my.data <- merge(my.data, ly.mean, by = 'Month')
my.data
Using sapply
and split
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data
sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data
Using aggregate
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month),
FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))
my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary
my.data <- merge(my.data, my.summary, by = 'Month')
my.data
EDIT: June 28, 2020
Here I use aggregate
to obtain the column means
of an entire matrix
by group where group is defined in an external vector
:
my.group <- c(1,2,1,2,2,3,1,2,3,3)
my.data <- matrix(c( 1, 2, 3, 4, 5,
10, 20, 30, 40, 50,
2, 4, 6, 8, 10,
20, 30, 40, 50, 60,
20, 18, 16, 14, 12,
1000, 1100, 1200, 1300, 1400,
2, 3, 4, 3, 2,
50, 40, 30, 20, 10,
1001, 2001, 3001, 4001, 5001,
1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data
my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
# Group.1 X1 X2 X3 X4 X5
#1 1 1.666667 3.000 4.333333 5.000 5.666667
#2 2 25.000000 27.000 29.000000 31.000 33.000000
#3 3 1000.333333 1700.333 2400.333333 3100.333 3800.333333
if you want to use signalr you haveto add startup.cs Class in your project
Right Click In You Project Then Add New Item And Select OWIN Startup Class
then inside Configuration Method Add Code Below
app.MapSignalR();
I Hope it will be useful for you
If you go to your android-sdk/tools
folder I think you'll find a message :
The adb tool has moved to platform-tools/
If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"
Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.
So you should also add C:/android-sdk/platform-tools
to you environment path. Also after you modify the PATH
variable make sure that you start a new CommandPrompt
window.
Addition to @Binary Nerd
If you are using Spark, use the following to get the Spark version:
spark-submit --version
or
Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster
It's very simple. Just try:
start chrome https://www.google.co.in/
it will open the Google page in the Chrome browser.
If you wish to open the page in Firefox, try:
start firefox https://www.google.co.in/
Have Fun!
If you are using a mac/linux and you want to retrieve local parameters to the machine you're using, this is what you'll do:
In the accepted answer
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
should be
public Node(T data, Node<T> parent) {
this.data = data;
this.setParent(parent);
}
otherwise the parent does not have the child in its children list
You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:
root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}
#we capture release hash
$curr_os = $os['release']
case $curr_os['major'] {
'7': { .... something }
*: {something}
}
That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.
The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.
I presume this would be a fine solution also - if you want to get contents of all text nodes that are direct children of selected element.
$(selector).contents().filter(function(){ return this.nodeType == 3; }).text();
Note: jQuery documentation uses similar code to explain contents function: https://api.jquery.com/contents/
P.S. There's also a bit uglier way to do that, but this shows more in depth how things work, and allows for custom separator between text nodes (maybe you want a line break there)
$(selector).contents().filter(function(){ return this.nodeType == 3; }).map(function() { return this.nodeValue; }).toArray().join("");
You can append to the end of a list:
foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])
print(foo) # [1, 2, 3, 4, 5, 4, [8, 7]]
You can edit items in the list like this:
foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4
print(foo) # [1, 2, 3, 8, 5]
Insert integers into the middle of a list:
x = [2, 5, 10]
x.insert(2, 77)
print(x) # [2, 5, 77, 10]
shape()
consists of array having two arguments rows and columns.
if you search shape[0]
then it will gave you the number of rows.
shape[1]
will gave you number of columns.
Right-click (or control-click) the application in question and choose "Open"
You can go for this :
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
I would say the most elegant way is this:
<div class="toggle"></div>
<div class="content">...</div>
then css:
.toggle{
display:inline-block;
height:48px;
width:48px; background:url("http://icons.iconarchive.com/icons/pixelmixer/basic/48/plus-icon.png");
}
.toggle.expanded{
background:url("http://cdn2.iconfinder.com/data/icons/onebit/PNG/onebit_32.png");
}
and js:
$(document).ready(function(){
var $content = $(".content").hide();
$(".toggle").on("click", function(e){
$(this).toggleClass("expanded");
$content.slideToggle();
});
});
The problem was that clicking the anchor still triggered a click in your <div>
. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading
which also have #ancherComplaint
as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
In SSMS 2012 there is a documented way to delete the server name from the "Connect to Server" dialog. Now, we can remove the server name by selecting it in the dialog and pressing DELETE.
one is Big "O"
one is Big Theta
http://en.wikipedia.org/wiki/Big_O_notation
Big O means your algorithm will execute in no more steps than in given expression(n^2)
Big Omega means your algorithm will execute in no fewer steps than in the given expression(n^2)
When both condition are true for the same expression, you can use the big theta notation....
You can add atom beauty package for formatting text in atom..
file --> setting --> Install
then you type atom-beautify in search area.
then click Package button.. select atom beuty and install it.
next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents
You can use a regular expression to delete white spaces , try that snippet:
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine().replaceAll(" ", ""));
I don't exactly know what causes that, but I solve it this way.
Reinstall whole project but remember that webpack-dev-server must be globally installed.
I walk through some server errors like webpack cant be found, so I linked Webpack using link command.
In output Resolving some absolute path issues.
In devServer object: inline: false
webpack.config.js
module.exports = {
entry: "./src/js/main.js",
output: {
path:__dirname+ '/dist/',
filename: "bundle.js",
publicPath: '/'
},
devServer: {
inline: false,
contentBase: "./dist",
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude:/(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
package.json
{
"name": "react-flux-architecture-es6",
"version": "1.0.0",
"description": "egghead",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"repository": {
"type": "git",
"url": "git+https://github.com/cichy/react-flux-architecture-es6.git"
},
"keywords": [
"React",
"flux"
],
"author": "Jaroslaw Cichon",
"license": "ISC",
"bugs": {
"url": "https://github.com/cichy/react-flux-architecture-es6/issues"
},
"homepage": "https://github.com/cichy/react-flux-architecture-es6#readme",
"dependencies": {
"flux": "^3.1.2",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "^3.0.2"
},
"devDependencies": {
"babel-core": "^6.22.1",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0"
}
}
You can set the value in the HTML and then init datepicker to start/highlight the actual date
<input name="datefrom" type="text" class="datepicker" value="20-1-2011">
<input name="dateto" type="text" class="datepicker" value="01-01-2012">
<input name="dateto2" type="text" class="datepicker" >
$(".datepicker").each(function() {
$(this).datepicker('setDate', $(this).val());
});
The above even works with danish date formats
var fileName = @"C:\ExcelFile.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
var adapter = new OleDbDataAdapter(cmd);
var ds = new DataSet();
adapter.Fill(ds);
}
}
[Ljava.lang.Object;
is the name for Object[].class
, the java.lang.Class
representing the class of array of Object
.
The naming scheme is documented in Class.getName()
:
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).
If this class object represents a primitive type or
void
, then the name returned is the Java language keyword corresponding to the primitive type orvoid
.If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more
'['
characters representing the depth of the array nesting. The encoding of element type names is as follows:Element Type Encoding boolean Z byte B char C double D float F int I long J short S class or interface Lclassname;
Yours is the last on that list. Here are some examples:
// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx
The reason why the toString()
method on arrays returns String
in this format is because arrays do not @Override
the method inherited from Object
, which is specified as follows:
The
toString
method for classObject
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())
Note: you can not rely on the toString()
of any arbitrary object to follow the above specification, since they can (and usually do) @Override
it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass()
on it (a final
method inherited from Object
) and then reflecting on the returned Class
object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).
toString
for arraysjava.util.Arrays
provides toString
overloads for primitive arrays and Object[]
. There is also deepToString
that you may want to use for nested arrays.
Here are some examples:
int[] nums = { 1, 2, 3 };
System.out.println(nums);
// [I@xxxxx
System.out.println(Arrays.toString(nums));
// [1, 2, 3]
int[][] table = {
{ 1, },
{ 2, 3, },
{ 4, 5, 6, },
};
System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]
System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]
There are also Arrays.equals
and Arrays.deepEquals
that perform array equality comparison by their elements, among many other array-related utility methods.
You can use (mouseover)
and (mouseout)
events.
component.ts
changeText:boolean=true;
component.html
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
<span [hidden]="changeText">Hide</span>
<span [hidden]="!changeText">Show</span>
</div>
This warning is about unsafe use of strcpy. Try IOBname[ii]='\0';
instead.
The first <img />
is invalid - src
is a required attribute. data-src
is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.
I found a post suggesting a solution for that. It's about to run:
svn resolve --accept working <YourPath>
which will claim the local version files as OK.
You can run it for single file or entire project catalogues.
There are two ways to compare three integers and check whether b is between a and c:
if a < b < c:
pass
and
if a < b and b < c:
pass
The first one looks like more readable, but the second one runs faster.
Let's compare using dis.dis:
>>> dis.dis('a < b and b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 COMPARE_OP 0 (<)
6 JUMP_IF_FALSE_OR_POP 14
8 LOAD_NAME 1 (b)
10 LOAD_NAME 2 (c)
12 COMPARE_OP 0 (<)
>> 14 RETURN_VALUE
>>> dis.dis('a < b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 DUP_TOP
6 ROT_THREE
8 COMPARE_OP 0 (<)
10 JUMP_IF_FALSE_OR_POP 18
12 LOAD_NAME 2 (c)
14 COMPARE_OP 0 (<)
16 RETURN_VALUE
>> 18 ROT_TWO
20 POP_TOP
22 RETURN_VALUE
>>>
and using timeit:
~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop
~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop
also, you may use range, as suggested before, however it is much more slower.
The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website.
You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does.
Another reason not mentioned above is that many built-in functions and methods of built-in types modify an object but do not return the modified object. If those modified objects were returned, that would make functional code cleaner and more concise. For example, if some_list.append(some_object) returned some_list with some_object appended.
Use this:
$sheet->getStyle('A1:'.$sheet->getHighestColumn().'1')->getFont()->setBold(true);
Another variation of Ashraf's solution would be to make sure you're taking into account screen sizes. You'll need to get the spinner in onCreate and set the listener after you set the adapter:
//set your adapter with default or custom spinner cell, then://
serverSpinner.setOnItemSelectedListener(spinnerSelector);
serverSpinner.setSelection(defaultServer);
Then you can start changing the text size of the view that's showing before the spinner is clicked:
private AdapterView.OnItemSelectedListener spinnerSelector = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
boolean largeTablet = getResources().getBoolean(R.bool.isLargeTablet);
if (tabletSize) { ((TextView)parent.getChildAt(0)).setTextSize(16); }
else if (largeTablet) { ((TextView)parent.getChildAt(0)).setTextSize(18); }
else { ((TextView)parent.getChildAt(0)).setTextSize(12); }
}
public void onNothingSelected(AdapterView<?> parent) {
}
};
All you need to do is create layout specific folders like this:
values-sw360dp
values-sw600dp
values-sw800dp
an then add an xml file named "bool.xml" into each of those folders:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="isTablet">false</bool>
<bool name="isLargeTablet">false</bool>
</resources>
You're looking for UPDATE not insert.
UPDATE mytable
SET table_column = 'test';
UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).
If you don't want to see the underline and default color which is provided by the browser, you can keep the following code in the top of your main.css file. If you need different color and decoration styling you can easily override the defaults using the below code snippet.
a, a:hover, a:focus, a:active {
text-decoration: none;
color: inherit;
}
You can use ALT+Left to go to your previous tab, or ALT+Right to go to forward. This method is using tab-switching like history, though, so it will go to the previous tab you had open, and forward if you've gone "back" once or more. A bit weird, I know, but it works. You can always "reset" the history by clicking through every tab once.
Update July 2013:
Another grep tool I now use all the time on Windows is AstroGrep:
Its ability to show me more than just the line search (i.e. the --context=NUM of a command-line grep) is invaluable.
And it is fast. Very fast, even on an old computer with non-SSD drive (I know, they used to do this hard drive with spinning disks, called platters, crazy right?)
It is free.
It is portable (simple zip archive to unzip).
Original answer October 2008
Gnu Grep is alright
You can download it for example here: (site ftp)
All the usual options are here.
That, combined with gawk and xargs (includes 'find', from GnuWin32), and you can really script like you were on Unix!
See also the options I am using to grep recursively:
grep --include "*.xxx" -nRHI "my Text to grep" *
It's a good practice to minimize the number of requests each page needs. So if you need several icons, yandex can do a sprite of favicons in one query. Here is an example http://favicon.yandex.net/favicon/google.com/stackoverflow.com/yandex.net/
From your shell run:
pip2 install unicodecsv
And (unlike the original question) presuming you're using Python's built in csv
module, turn
import csv
into
import unicodecsv as csv
in your code.
First Create Bitmap Image
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);
now set bitmap in Notification Builder Icon....
Notification.Builder.setLargeIcon(bmp);
It is better to use implode for that purpose. Implode is easy and awesome:
$array = ['name1', 'name2', 'name3'];
$str = implode(', ', $array);
Output:
name1, name2, name3
*scanf()
family of functions return the number of values converted. So you should check to make sure sscanf()
returns 1 in your case. EOF
is returned for "input failure", which means that ssacnf()
will never return EOF
.
For sscanf()
, the function has to parse the format string, and then decode an integer. atoi()
doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.
You should use strtol()
or strtoul()
functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.
If you want an int
, you can always use strtol()
, and then check the returned value to see if it lies between INT_MIN
and INT_MAX
.
For modern browsers, the best solution is to use Promises.
Go to https://stackoverflow.com/a/63936671/13720928 to find out more!
On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat
instance:
var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
// 42.000.000 in many other locales
if (typeof Intl === "undefined" || !Intl.NumberFormat) {_x000D_
console.log("This browser doesn't support Intl.NumberFormat");_x000D_
} else {_x000D_
var nf = Intl.NumberFormat();_x000D_
var x = 42000000;_x000D_
console.log(nf.format(x)); // 42,000,000 in many locales_x000D_
// 42.000.000 in many other locales_x000D_
}
_x000D_
I'm afraid you can't easily do an in-place sort of a DataTable like it sounds like you want to do.
What you can do is create a new DataTable from a DataView that you create from your original DataTable. Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTable method:
DataView dv = ft.DefaultView;
dv.Sort = "occr desc";
DataTable sortedDT = dv.ToTable();
Using moment.js UTC method;
const moment = require('moment');
const utc = moment.utc(new Date(string));
You can create a large array and then copy it to a new array using System.arrayCopy
int contentLength = 100000000;
byte[] byteArray = new byte[contentLength];
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
while ((bytesRead = inputStream.read()) != -1)
{
byteArray[count++] = (byte)bytesRead;
}
byte[] destArray = new byte[count];
System.arraycopy(byteArray, 0, destArray , 0, count);
destArray will contain the information you want
Updated accepted answer to angular 7.0.1 on stackblitz here: https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts
directives
are no more in Component decorator options. So I have provided sub directive to app module.
thank you @thierry-templier!
This is a limit of the C++ compiler. If you put the function in the header, all the cpp files where it can be inlined can see the "source" of your function and the inlining can be done by the compiler. Otherwhise the inlining would have to be done by the linker (each cpp file is compiled in an obj file separately). The problem is that it would be much more difficult to do it in the linker. A similar problem exists with "template" classes/functions. They need to be instantiated by the compiler, because the linker would have problem instantiating (creating a specialized version of) them. Some newer compiler/linker can do a "two pass" compilation/linking where the compiler does a first pass, then the linker does its work and call the compiler to resolve unresolved things (inline/templates...)
Same issue occurred for me, but before getting this error, my app was running. So I just did undo 2/3 times. And did changes again. And build app.app ran successfully.
Using a function attribute is also very simple
def f():
if not hasattr(f, 'value'):
setattr(f, 'value', singletonvalue)
return f.value
Package "anaconda clean", available from Anaconda platform, should uninstall safely.
conda install anaconda-clean # install the package anaconda clean
anaconda-clean --yes # clean all anaconda related files and directories
rm -rf ~/anaconda3 # removes the entire anaconda directory
rm -rf ~/.anaconda_backup # anaconda clean creates a back_up of files/dirs, remove it
# (conda list; cmd shouldn't respond after the clean up)
Refer: https://docs.anaconda.com/anaconda/install/uninstall for more details.
It is not good practice to hard code strings into your layout files. You should add them to a string resource file and then reference them from your layout.
This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings.xml file.
It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language.
example: XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="yellow">Yellow</string>
</resources>
This layout XML applies a string to a View:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/yellow" />
Similarly colors should be stored in colors.xml and then referenced by using @color/color_name
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Black">#000000</color>
</resources>
if you want to change all the keys:
d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}
In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}
if you want to change single key: You can go with any of the above suggestion.
Well, there's an alternate way! You can use a button instead of hyperlink. Hence, when the button is clicked the web page specified in "name_of_webpage" is opened in the target frame named "name_of_iframe". It works for me!
<form method="post" action="name_of_webpage" target="name_of_iframe">
<input type="submit" value="any_name_you_want" />
</form>
<iframe name="name_of_iframe"></iframe>
ngSanitize
module on your app
eg: var app = angular.module('myApp', ['ngSanitize']);
ng-bind-html
the original html
content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml
directive. (Read the How does it work
section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div>
would do the work.The best move is to just nest a flexbox inside of a flexbox. All you have to do is give the child align-items: center
. This will vertically align the text inside of its parent.
// Assuming a horizontally centered row of items for the parent but it doesn't have to be
.parent {
align-items: center;
display: flex;
justify-content: center;
}
.child {
display: flex;
align-items: center;
}
You can just use "!important" to get your custom color
.navbar {
background-color: yourcolor !important;
}
This works in python 2 and 3 and is a bit cleaner than before, but requires SA>=1.0.
from sqlalchemy.engine.default import DefaultDialect
from sqlalchemy.sql.sqltypes import String, DateTime, NullType
# python2/3 compatible.
PY3 = str is not bytes
text = str if PY3 else unicode
int_type = int if PY3 else (int, long)
str_type = str if PY3 else (str, unicode)
class StringLiteral(String):
"""Teach SA how to literalize various things."""
def literal_processor(self, dialect):
super_processor = super(StringLiteral, self).literal_processor(dialect)
def process(value):
if isinstance(value, int_type):
return text(value)
if not isinstance(value, str_type):
value = text(value)
result = super_processor(value)
if isinstance(result, bytes):
result = result.decode(dialect.encoding)
return result
return process
class LiteralDialect(DefaultDialect):
colspecs = {
# prevent various encoding explosions
String: StringLiteral,
# teach SA about how to literalize a datetime
DateTime: StringLiteral,
# don't format py2 long integers to NULL
NullType: StringLiteral,
}
def literalquery(statement):
"""NOTE: This is entirely insecure. DO NOT execute the resulting strings."""
import sqlalchemy.orm
if isinstance(statement, sqlalchemy.orm.Query):
statement = statement.statement
return statement.compile(
dialect=LiteralDialect(),
compile_kwargs={'literal_binds': True},
).string
Demo:
# coding: UTF-8
from datetime import datetime
from decimal import Decimal
from literalquery import literalquery
def test():
from sqlalchemy.sql import table, column, select
mytable = table('mytable', column('mycol'))
values = (
5,
u'snowman: ?',
b'UTF-8 snowman: \xe2\x98\x83',
datetime.now(),
Decimal('3.14159'),
10 ** 20, # a long integer
)
statement = select([mytable]).where(mytable.c.mycol.in_(values)).limit(1)
print(literalquery(statement))
if __name__ == '__main__':
test()
Gives this output: (tested in python 2.7 and 3.4)
SELECT mytable.mycol
FROM mytable
WHERE mytable.mycol IN (5, 'snowman: ?', 'UTF-8 snowman: ?',
'2015-06-24 18:09:29.042517', 3.14159, 100000000000000000000)
LIMIT 1
I believe the modern way to go is place-items: center
in the parent container
An example can be found here: https://1linelayouts.glitch.me
I would like to add which isn't mentioned in above answers.
From your kibana's dev console, hit following command:
GET /
This is similar to accessing localhost:9200
from browser.
Hope this will help someone.
The easiest way to insert html blocks is to use template strings (backticks). It will also allow you to insert dynamic content via ${...}:
document.getElementById("log-menu").innerHTML = `
<a href="#">
${data.user.email}
</a>
<div class="dropdown-menu p-3 dropdown-menu-right">
<div class="form-group">
<label for="email1">Logged in as:</label>
<p>${data.user.email}</p>
</div>
<button onClick="getLogout()" ">Sign out</button>
</div>
`
Your current code works, you can try it here: http://jsfiddle.net/s4UyH/
You have something outside the example triggering another .click()
, check for other handlers that are also triggering a click
event on that element.
It's not clear from the question, but assuming this is something happening on a development or test client, and given that you are already using Fiddler you can have Fiddler respond with an allow response:
AutoResponder
tabAdd Rule
and edit the rule to:
Method:OPTIONS http://localhost
*CORSPreflightAllow
Unmatched requests passthrough
Enable Rules
A couple notes:
If you want the last 5 rows, ordered in ascending order, you need a subquery:
SELECT *
FROM
( SELECT id, name, form_id, DATE(updated_at) AS updated_date, updated_at
FROM wp_frm_items
WHERE user_id = 11
AND form_id=9
ORDER BY updated_at DESC
LIMIT 5
) AS tmp
ORDER BY updated_at
After reading the question for 10th time, this may be (just maybe) what you want. Order by Date descending and then order by time (on same date) ascending:
SELECT id, name, form_id, DATE(updated_at) AS updated_date
FROM wp_frm_items
WHERE user_id = 11
AND form_id=9
ORDER BY DATE(updated_at) DESC
, updated_at ASC
This works for MVC 5:
<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
Link text
</a>
A simple way to do that in VBA is:
YourText = "c:\excel\text.txt"
xString = Mid(YourText, 2 + Len(YourText) - InStr(StrReverse(YourText), "\" ))
In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:
In [1]: float_formatter = "{:.2f}".format
The f
here means fixed-point format (not 'scientific'), and the .2
means two decimal places (you can read more about string formatting here).
Let's test it out with a float value:
In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'
To make numpy print all float arrays this way, you can pass the formatter=
argument to np.set_printoptions
:
In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})
Now numpy will print all float arrays this way:
In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]
Note that this only affects numpy arrays, not scalars:
In [5]: np.pi
Out[5]: 3.141592653589793
It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.
You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.
For example:
In [6]: a = np.array([1E-9])
In [7]: a
Out[7]: array([0.00])
In [8]: a == 0
Out[8]: array([False], dtype=bool)
numpy prints a
as if it were equal to 0
, but it is not - it still equals 1E-9
.
If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round
, as others have already pointed out.
I suggest that you give an if to the div than:
$("#my_div_id").html();
Also, the Common function config_item()
works pretty much everywhere throughout the CodeIgniter instance. Controllers, models, views, libraries, helpers, hooks, whatever.
From the Wiki.
Motivation for creating the Java Persistence API
Many enterprise Java developers use lightweight persistent objects provided by open-source frameworks or Data Access Objects instead of entity beans: entity beans and enterprise beans had a reputation of being too heavyweight and complicated, and one could only use them in Java EE application servers. Many of the features of the third-party persistence frameworks were incorporated into the Java Persistence API, and as of 2006 projects like Hibernate (version 3.2) and Open-Source Version TopLink Essentials have become implementations of the Java Persistence API.
As told in the JCP page the Eclipse link is the Reference Implementation for JPA. Have look at this answer for bit more on this.
JPA itself has features that will make up for a standard ORM framework. Since JPA is a part of Java EE spec, you can use JPA alone in a project and it should work with any Java EE compatible Servers. Yes, these servers will have the implementations for the JPA spec.
Hibernate is the most popular ORM framework, once the JPA got introduced hibernate conforms to the JPA specifications. Apart from the basic set of specification that it should follow hibernate provides whole lot of additional stuff.
Try using below:
SELECT
(RTRIM(LTRIM(col_1))) + (RTRIM(LTRIM(col_2))) AS Col_newname,
col_1,
col_2
FROM
s_cols
WHERE
col_any_condition = ''
;
mysql_*
extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.
The simpler option is PDO which has a neat helper function fetchColumn()
:
$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();
You can do the same with MySQLi, but it is more complicated:
$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;
fetch_assoc()
could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.
The best way is to use fixtures.
Note: Keep in mind that fixtures do direct inserts and don't use your model so if you have callbacks that populate data you will need to find a workaround.
Use backticks for system commands, which helps to store their results into Perl variables.
my $pid = 5892;
my $not = ``top -H -p $pid -n 1 | grep myprocess | wc -l`;
print "not = $not\n";
You can get any query string data i.e www.example.com?id=2&name=r
You must get data using $_GET['id']
or $_REQUEST['id']
.
Post data means like form <form action='' method='POST'>
you must use $_POST
or $_REQUEST
.
Pattern phoneNumber = Pattern.compile("(\\d{3})(\\d{3})(\\d{4})");
// ...
Matcher matcher = phoneNumber(numberAsLineOf10Symbols);
if (matcher.matches) {
return "(" + matcher.group(1) + ")-" +matcher.group(2) + "-" + matcher.group(3);
}
var charCount = "string with periods...".Count(x => '.' == x);
There is no way how to declare an unsigned long or int in Java 8 or Java 9. But some methods treat them as if they were unsigned, for example:
static long values = Long.parseUnsignedLong("123456789012345678");
but this is not declaration of the variable.
Try javax.net.ssl.keyStorePassword
instead of javax.net.ssl.keyPassword
: the latter isn't mentioned in the JSSE ref guide.
The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmException
s are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.
You could also use -Djavax.net.debug=ssl
, or at least -Djavax.net.debug=ssl,keymanager
, to get more debugging information, if the information in the stack trace isn't sufficient.
SimpleDateFormat
is great, just note that HH
is different from hh
when working with hours. HH
will return 24 hour based hours and hh will return 12 hour based hours.
For example, the following will return 12 hour time:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
While this will return 24 hour time:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String[][] shades = new String[intSize][intSize];
// print array in rectangular form
for (int r=0; r<shades.length; r++) {
for (int c=0; c<shades[r].length; c++) {
shades[r][c]="hello";//your value
}
}