Drupal initially relied on the <base>
tag, and later on took the decision to not use due to problems with HTTP crawlers & caches.
I generally don't like to post links. But this one is really worth sharing as it could benefit those looking for the details of a real-world experience with the <base>
tag:
Previously, you would do this through NPAPI plugins.
However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.
I have used Rational Rose and Rational Rhapsody for reverse engineering large projects. I would prefer Rational Rhapsody for getting the UML class files for C++ !
You can use axis
:
> axis(side=1, at=c(0:23))
That is, something like this:
plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()
You should use this one too:
./gradlew :app:dependencies
(Mac and Linux) -With ./
gradlew :app:dependencies
(Windows) -Without ./
The libs you are using internally using any other versions of google play service.If yes then remove or update those libs.
For the sake of generations to come I add here the accepted answer in Python.
import numpy as np
import colorsys
def _get_colors(num_colors):
colors=[]
for i in np.arange(0., 360., 360. / num_colors):
hue = i/360.
lightness = (50 + np.random.rand() * 10)/100.
saturation = (90 + np.random.rand() * 10)/100.
colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))
return colors
If Short.TryParse(editTransactionRow.pay_id, New Short) Then editTransactionRow.pay_id.ToString()
In SQL
, you do it this way:
SELECT CASE WHEN @selectField1 = 1 THEN Field1 ELSE NULL END,
CASE WHEN @selectField2 = 1 THEN Field2 ELSE NULL END
FROM Table
Relational model does not imply dynamic field count.
Instead, if you are not interested in a field value, you just select a NULL
instead and parse it on the client.
In Swift 3, you can simply use CGPoint.zero
or CGRect.zero
in place of CGRectZero
or CGPointZero
.
However, in Swift 4, CGRect.zero
and 'CGPoint.zero'
will work
Use ON DUPLICATE KEY UPDATE ...
,
Negative : because the UPDATE
uses resources for the second action.
Use INSERT IGNORE ...
,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.
Attach the function to the onchange method of the input type file /onchange="validateimg(this)"/
function validateimg(ctrl) {
var fileUpload = ctrl;
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (fileUpload.files) != "undefined") {
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
if (height < 1100 || width < 750) {
alert("At least you can upload a 1100*750 photo size.");
return false;
}else{
alert("Uploaded image has valid Height and Width.");
return true;
}
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
}
The easiest way is to use a for loop template tag.
Given the view:
def MyView(request):
...
query_results = YourModel.objects.all()
...
#return a response to your template and add query_results to the context
You can add a snippet like this your template...
<table>
<tr>
<th>Field 1</th>
...
<th>Field N</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.field1 }}</td>
...
<td>{{ item.fieldN }}</td>
</tr>
{% endfor %}
</table>
This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.
SelectedText = this.combobox.SelectionBoxItem.ToString();
jQuery dialog has an isOpen
property that can be used to check if a jQuery dialog is open or not.
You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html
Function is not a property/method from range.
If you want to sum values then use the following:
Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))
EDIT:
if you want the formula then use as follows:
Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"
'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).
In case you are allways going to use the same range address then you can use as Rory sugested:
Range("A1").Formula ="=Sum(A2:B3)"
public function convertToUtf8($text) {
if(!$this->html)
$this->html = cURL('http://'.$this->url, array('timeout' => 15));
$html = $this->html;
preg_match('/<meta.*?charset=(|\")(.*?)("|\")/i', $html, $matches);
$charset = $matches[2];
if($charset)
return mb_convert_encoding($text, 'UTF-8', $charset);
else
return $text;
}
cURL default options:
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
I tried something like this. It helped me. If found on meta charset info, I'm converting, otherwise doing nothing.
I suppose you could get a good guess by running top
and looking for active processes using a lot of memory. Doing this programatically is harder---just look at the endless debates about the Linux OOM killer heuristics.
Swapping is a function of having more memory in active use than is installed, so it is usually hard to blame it on a single process. If it is an ongoing problem, the best solution is to install more memory, or make other systemic changes.
You just need to use single quotes:
$ echo "$TEST"
test
$ echo '$TEST'
$TEST
Inside single quotes special characters are not special any more, they are just normal characters.
Using JSONSerialization
always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable
in Swift 4. If you wield a [String:Any]
in front of a simple struct
it will ... hurt. Check out this in a Playground:
import Cocoa
let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!
struct Form: Codable {
let id: Int
let name: String
let description: String?
private enum CodingKeys: String, CodingKey {
case id = "form_id"
case name = "form_name"
case description = "form_desc"
}
}
do {
let f = try JSONDecoder().decode([Form].self, from: data)
print(f)
print(f[0])
} catch {
print(error)
}
With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.
I tested your answers and only Stefan Reich's one worked for me. Although I couldn't manage to restore the window to its previous state (maximized/normal). I found this mutation better:
view.setState(java.awt.Frame.ICONIFIED);
view.setState(java.awt.Frame.NORMAL);
That is setState
instead of setExtendedState
.
There's a function that does exactly this:
http://api.jquery.com/serialize/
var data = $('form').serialize();
$.post('url', data);
The FASTEST way of doing this in python is using Pandas (version 0.16 and up).
Dump one table:
db = sqlite3.connect('database.db')
table = pd.read_sql_query("SELECT * from table_name", db)
table.to_csv(table_name + '.csv', index_label='index')
Dump all tables:
import sqlite3
import pandas as pd
def to_csv():
db = sqlite3.connect('database.db')
cursor = db.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
table.to_csv(table_name + '.csv', index_label='index')
cursor.close()
db.close()
As I mentioned in your other question:
The problem to do with that fact, that you invented your own non-standard attributes (which you shouldn't have done in the first place), and now new standardized attributes (or attributes in the process of being standardized) are colliding with them.
The proper solution is to completely remove your invented attributes and replace them with
something sensible, for example classes (class="Montantetextfield fieldname-Montante required allow-decimal-values"
), or store them in JavaScript:
var validationData = {
"Montante": {fieldname: "Montante", required: true, allowDecimalValues: true}
}
If the proper solution isn't viable, you'll have to rename them. In that case you should use the prefix data-
... because that is reserved by HTML5 for such purposes, and it's less likely to collide with something - but it still could, so you should seriously consider the first solution - even it is more work to change.
Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar
, you can use
gradle run --args='foo --bar'
The answer of @derek73 is very neat, but it cannot be pickled nor (deep)copied, and it returns None
for missing keys. The code below fixes this.
Edit: I did not see the answer above that addresses the exact same point (upvoted). I'm leaving the answer here for reference.
class dotdict(dict):
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
Perhaps 0
or '\u0000'
would do?
I got this error message when sending data from a html form (Post method). All I had to do was change the encoding in the form from "text/plain" to "application/x-www-form-urlencoded" or "multipart/form-data". The error message was very misleading.
I am using @wim 's answer above, with dict.pop() when renaming keys, but I found a gotcha. Cycling through the dict to change the keys, without separating the list of old keys completely from the dict instance, resulted in cycling new, changed keys into the loop, and missing some existing keys.
To start with, I did it this way:
for current_key in my_dict:
new_key = current_key.replace(':','_')
fixed_metadata[new_key] = fixed_metadata.pop(current_key)
I found that cycling through the dict in this way, the dictionary kept finding keys even when it shouldn't, i.e., the new keys, the ones I had changed! I needed to separate the instances completely from each other to (a) avoid finding my own changed keys in the for loop, and (b) find some keys that were not being found within the loop for some reason.
I am doing this now:
current_keys = list(my_dict.keys())
for current_key in current_keys:
and so on...
Converting the my_dict.keys() to a list was necessary to get free of the reference to the changing dict. Just using my_dict.keys() kept me tied to the original instance, with the strange side effects.
Fix for this issue is simple :
and sometimes you might see there's an update available next to it, you just need to let it finish the update
Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!
Here's a more Pythonic version of the straightforward iterative solution:
def find_nth(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
Example:
>>> find_nth("foofoofoofoo", "foofoo", 2)
6
If you want to find the nth overlapping occurrence of needle
, you can increment by 1
instead of len(needle)
, like this:
def find_nth_overlapping(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+1)
n -= 1
return start
Example:
>>> find_nth_overlapping("foofoofoofoo", "foofoo", 2)
3
This is easier to read than Mark's version, and it doesn't require the extra memory of the splitting version or importing regular expression module. It also adheres to a few of the rules in the Zen of python, unlike the various re
approaches:
or if your using vi mode, hit Esc followed by cc
to get back what you just erased, Esc and then p :)
I would try to set a flag on the window.onfocus
and window.onblur
events.
The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:
var isTabActive;
window.onfocus = function () {
isTabActive = true;
};
window.onblur = function () {
isTabActive = false;
};
// test
setInterval(function () {
console.log(window.isTabActive ? 'active' : 'inactive');
}, 1000);
Try it out here.
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
Here is a complete Kotlin + androidx solution, building upon the answer from @Stanislas Heili. I hope it may be useful to others. It's for the case when you have an activity that hosts multiple fragments, with only one fragment active at the same time.
In your activity:
private lateinit var customTitle: AppCompatTextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// stuff here
customTitle = createCustomTitleTextView()
// other stuff here
}
private fun createCustomTitleTextView(): AppCompatTextView {
val mTitleTextView = AppCompatTextView(this)
TextViewCompat.setTextAppearance(mTitleTextView, R.style.your_style_or_null);
val layoutParams = ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT
)
layoutParams.gravity = Gravity.CENTER
supportActionBar?.setCustomView(mTitleTextView, layoutParams)
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
return mTitleTextView
}
override fun setTitle(title: CharSequence?) {
customTitle.text = title
}
override fun setTitle(titleId: Int) {
customTitle.text = getString(titleId)
}
In your fragments:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity?.title = "some title for fragment"
}
This always works fine for me:
for url in list_of_urls:
urls.setdefault(url, 0)
urls[url] += 1
Actually an enum
's default is the first element in the enum
whose value is 0
.
So for example:
public enum Animals
{
Cat,
Dog,
Pony = 0,
}
//its value will actually be Cat not Pony unless you assign a non zero value to Cat.
Animals animal;
While you can't yet get Firefox to remove the dropdown arrow (see MatTheCat's post), you can hide your "stylized" background image from showing in Firefox.
-moz-background-position: -9999px -9999px!important;
This will position it out of frame, leaving you with the default select box arrow – while keeping the stylized version in Webkit.
Assuming you are trying to pass the command line arguments as well.
import sys
import myModule
def main():
# this will just pass all of the system arguments as is
myModule.main(*sys.argv)
# all the argv but the script name
myModule.main(*sys.argv[1:])
Razor is a view engine for ASP.NET MVC, and also a template engine. Razor code and ASP.NET inline code (code mixed with markup) both get compiled first and get turned into a temporary assembly before being executed. Thus, just like C# and VB.NET both compile to IL which makes them interchangable, Razor and Inline code are both interchangable.
Therefore, it's more a matter of style and interest. I'm more comfortable with razor, rather than ASP.NET inline code, that is, I prefer Razor (cshtml) pages to .aspx pages.
Imagine that you want to get a Human
class, and render it. In cshtml files you write:
<div>Name is @Model.Name</div>
While in aspx files you write:
<div>Name is <%= Human.Name %></div>
As you can see, @
sign of razor makes mixing code and markup much easier.
"Functions have only READ-ONLY Database Access" If DML operations would be allowed in functions then function would be prety similar to stored Procedure.
If you want to add an interval before executing the cron the next time you can add a sleep
for i in
{1..100}
; do echo $i && curl "http://URL" >> /tmp/output.log && sleep 120; done
If you don't mind a small library dependency, Flurl.Http [disclosure: I'm the author] makes this uber-simple. Its PostJsonAsync
method takes care of both serializing the content and setting the content-type
header, and ReceiveJson
deserializes the response. If the accept
header is required you'll need to set that yourself, but Flurl provides a pretty clean way to do that too:
using Flurl.Http;
var result = await "http://example.com/"
.WithHeader("Accept", "application/json")
.PostJsonAsync(new { ... })
.ReceiveJson<TResult>();
Flurl uses HttpClient and Json.NET under the hood, and it's a PCL so it'll work on a variety of platforms.
PM> Install-Package Flurl.Http
Dim result2 = From s In mySession.Query(Of CSucursal)()
Where (From c In mySession.Query(Of CCiudad)()
From cs In mySession.Query(Of CCiudadSucursal)()
Where cs.id_ciudad Is c
Where cs.id_sucursal Is s
Where c.id = IdCiudad
Where s.accion <> "E" AndAlso s.accion <> Nothing
Where cs.accion <> "E" AndAlso cs.accion <> Nothing
Select c.descripcion).Single() Is Nothing
Where s.accion <> "E" AndAlso s.accion <> Nothing
Select s.id, s.Descripcion
I am deploying VB6 IIS Applications to my remote dedicated server with 75 folders. The reason I was getting this error is the Default Document was not set on one of the folders, an oversight, so the URL hitting that folder did not know which page to server up, and thus threw the error mentioned in this thread.
Use RETURN QUERY
:
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (txt text -- also visible as OUT parameter inside function
, cnt bigint
, ratio bigint) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt
, count(*) AS cnt -- column alias only visible inside
, (count(*) * 100) / _max_tokens -- I added brackets
FROM (
SELECT t.txt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
LIMIT _max_tokens
) t
GROUP BY t.txt
ORDER BY cnt DESC; -- potential ambiguity
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM word_frequency(123);
Explanation:
It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE
is one way to do that. There are others. Data types of OUT
parameters have to match exactly what is returned by the query.
Choose names for OUT
parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.
But note the potential naming conflict between the OUT
parameter cnt
and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...
) Postgres uses the column alias over the OUT
parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:
ORDER BY 2 DESC
. Example:
ORDER BY count(*)
.plpgsql.variable_conflict
or use the special command #variable_conflict error | use_variable | use_column
in the function. See:
Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt
and cnt
in my examples.
Added a missing ;
and corrected a syntax error in the header. (_max_tokens int)
, not (int maxTokens)
- type after name.
While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric
(or a floating point type). See below.
This is what I think your query should actually look like (calculating a relative share per token):
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (txt text
, abs_cnt bigint
, relative_share numeric) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt, t.cnt
, round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2) -- AS relative_share
FROM (
SELECT t.txt, count(*) AS cnt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
GROUP BY t.txt
ORDER BY cnt DESC
LIMIT _max_tokens
) t
ORDER BY t.cnt DESC;
END
$func$ LANGUAGE plpgsql;
The expression sum(t.cnt) OVER ()
is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.
A final explicit RETURN
statement is not required (but allowed) when working with OUT
parameters or RETURNS TABLE
(which makes implicit use of OUT
parameters).
round()
with two parameters only works for numeric
types. count()
in the subquery produces a bigint
result and a sum()
over this bigint
produces a numeric
result, thus we deal with a numeric
number automatically and everything just falls into place.
I could solve this in another way. I didn't find the library on my system. Thus I installed it using an app from PostgreSQL main website. In my case (OS X) I found the file under /Library/PostgreSQL/9.1/include/
once the installation was over. You may also have the file somewhere else depending on your system if you already have PostgreSQL installed.
Thanks to this link on how to add an additional path for gem installation, I could point the gem to the lib with this command:
export CONFIGURE_ARGS="with-pg-include=/Library/PostgreSQL/9.1/include/"
gem install pg
After that, it works, because it now knows where to find the missing library. Just replace the path with the right location for your libpq-fe.h
The following expression will work on any language supported by UTF-16 and will ensure that there's a minimum of two components to the name (i.e. first + last), but will also allow any number of middle names.
/^(\S+ )+\S+$/u
At the time of this writing it seems none of the other answers meet all of that criteria. Even ^\p{L}{2,}$
, which is the closest, falls short because it will also match "invisible" characters, such as U+FEFF
(Zero Width No-Break Space).
Create a pair of classes that provide the various methods that each of these data structures has (push, pop, peek, etc). Now implement the methods. If you're familiar with the concepts behind stack/queue, this should be pretty straightforward. You can implement the stack with an array, and a queue with a linked list, although there are certainly other ways to go about it. Javascript will make this easy, because it is weakly typed, so you don't even have to worry about generic types, which you'd have to do if you were implementing it in Java or C#.
In Chrome Browser go to setting , clear browsing history and then reload the page
There is a built in method which would be the fastest method also, calling tolist
on the .values
np array:
df.values.tolist()
[[0.0, 3.61, 380.0, 3.0],
[1.0, 3.67, 660.0, 3.0],
[1.0, 3.19, 640.0, 4.0],
[0.0, 2.93, 520.0, 4.0]]
To get left/right centering, then applying text-align: center
to the div
and margin: auto
to the p
.
For vertical positioning you should make sure you understand the different ways of doing so, this is a commonly asked problem: Vertical alignment of elements in a div
In conclusion:
distutils
doesn't support install_requires
or entry_points
, setuptools
does.
change from distutils.core import setup
in setup.py to from setuptools import setup
or refactor your setup.py to use only distutils
features.
I came here because I hadn't realized entry_points
was only a setuptools
feature.
If you are here wanting to convert setuptools
to distutils
like me:
install_requires
from setup.py and just use requirements.txt with pip
entry_points
to scripts
(doc) and refactor any modules relying on entry_points
to be full scripts with shebangs and an entry point.Using GNU sed
:
sed 's/.*/\L&/'
Example:
$ foo="Some STRIng";
$ foo=$(echo "$foo" | sed 's/.*/\L&/')
$ echo "$foo"
some string
Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.
In my case this amounted to defining my column as:
`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''
This is in my opinion preferential to adjusting your queries.
ECMAScript 6 introduced String.prototype.includes
:
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
includes
doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf
, which returns -1 when a substring cannot be found:
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
If you are using Bash, you can convert stdout to an array of lines by mapfile
:
find . | grep "FooBar" | (mapfile -t; cp "${MAPFILE[@]}" ~/foobar)
The benefits are:
You can append other arguments to the file names. For cp
, you can also:
find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +
however, some commands don't have such feature.
The disadvantages:
Well... who knows if Bash is available on OS X?
Your state with dictionary update some key without losing other value
state =
{
name:"mjpatel"
parsedFilter:
{
page:2,
perPage:4,
totalPages: 50,
}
}
Solution is below
let { parsedFilter } = this.state
this.setState({
parsedFilter: {
...this.state.parsedFilter,
page: 5
}
});
here update value for key "page" with value 5
this doesn't work:
gcc -ldl dlopentest.c
But this does:
gcc dlopentest.c -ldl
That's one annoying "feature" for sure
I was struggling with it when writing heredoc syntax and found some interesting facts. With CC=Clang
, this works:
$CC -ldl -x c -o app.exe - << EOF
#include <dlfcn.h>
#include <stdio.h>
int main(void)
{
if(dlopen("libc.so.6", RTLD_LAZY | RTLD_GLOBAL))
printf("libc.so.6 loading succeeded\n");
else
printf("libc.so.6 loading failed\n");
return 0;
}
EOF
./app.exe
as well as all of these:
$CC -ldl -x c -o app.exe - << EOF
$CC -x c -ldl -o app.exe - << EOF
$CC -x c -o app.exe -ldl - << EOF
$CC -x c -o app.exe - -ldl << EOF
However, with CC=gcc
, only the last variant works; -ldl
after -
(the stdin argument symbol).
If your SQL database allows Null values for that field try using int? value
like that :
if (this.txtboxname.Text == "" || this.txtboxname.text == null)
value = null;
else
value = Convert.ToInt32(this.txtboxname.Text);
Take care that Convert.ToInt32 of a null value returns 0 !
Convert.ToInt32(null) returns 0
You might try this tool: http://fittextjs.com/
I haven't used this second tool, but it seems similar: https://github.com/zachleat/BigText
What you want is a timer:
// RxJS v6+
import { timer } from 'rxjs';
//emit [1, 2, 3] after 1 second.
const source = timer(1000).map(([1, 2, 3]);
//output: [1, 2, 3]
const subscribe = source.subscribe(val => console.log(val));
I prefer tools with some friendly gui!
I used npm-gui
which gives you list of local and global packages
The package is at https://www.npmjs.com/package/npm-gui and https://github.com/q-nick/npm-gui
//Once
npm install -g npm-gui
cd c:\your-prject-folder
npm-gui localhost:9000
At your browser http:\\localhost:9000
Something like this:
select
*
from sales
where salesDate >= '11/11/2010'
AND salesDate < (Convert(datetime, '11/11/2010') + 1)
Here's mine
public static String dec2Hex(int num)
{
String hex = "";
while (num != 0)
{
if (num % 16 < 10)
hex = Integer.toString(num % 16) + hex;
else
hex = (char)((num % 16)+55) + hex;
num = num / 16;
}
return hex;
}
Syntactic sugar, makes it more obvious to the casual reader that the join isn't an inner one.
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
public void swap(int[] arr,int a,int b)
{
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
public int[] reverseArray(int[] arr){
int size=arr.length-1;
for(int i=0;i<size;i++){
swap(arr,i,size--);
}
return arr;
}
Let's try this
select convert(varchar, getdate(), 108)
Just try a few moment ago
use href
with indexof
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("added-to-cart=555") > -1) {
alert("your url contains the added-to-cart=555");
}
});
</script>
This should do what you are looking for:
<html>
<head>
<style type="text/css">
#header {
text-align: center;
}
#wrapper {
margin:0 auto;
width:600px;
}
#submain {
margin:0 auto;
width:600px;
}
#sub-left {
float:left;
width:300px;
}
#sub-right {
float:right;
width:240px;
text-align: right;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="header"><h1>Head</h1></div>
<div id="sub-main">
<div id="sub-left">
Right
</div>
<div id="sub-right">
Left
</div>
</div>
</div>
</body>
</html>
And you can control the entire document with the wrapper class, or just the two columns with the sub-main class.
Make sure you are running your program in DEBUG mode and not RELEASE mode.
dtTempColumn.Columns["EXCELCOLUMNS"].ColumnName = "COLUMN_NAME";
dtTempColumn.AcceptChanges();
Besides putting the correct entries in your .gitignore file, if you're trying to ignore something already added to the repo, you have to do git rm -r /path/to/dir
and commit that before you add the dir to your .gitignore file. Otherwise the only thing git will ignore is your ignore directive.
Have you thought about using mouseOver and mouseOut to simulate this. Also look into mouseEnter and mouseLeave
If you want to due this in component.ts
HTML:
<button class="class1 class2" (click)="clicked($event)">Click me</button>
Component:
clicked(event) {
event.target.classList.add('class3'); // To ADD
event.target.classList.remove('class1'); // To Remove
event.target.classList.contains('class2'); // To check
event.target.classList.toggle('class4'); // To toggle
}
For more options, examples and browser compatibility visit this link.
Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)
list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});
foreach(var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
row.Index ...
}
Not sure I fully understand your question, but is this what you want to do?
pd.DataFrame(data=dict(s1=s1, s2=s2), index=s1.index)
(index=s1.index
is not even necessary here)
every minute:
* * * * * /path/to/php /var/www/html/a.php
every 24hours (every midnight):
0 0 * * * /path/to/php /var/www/html/reset.php
See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml
I got around this by upgrading both the version of Angular that I was using (from v8 -> v9) and the version of TypeScript (from 3.5.3 -> latest).
A char in C is already a number (the character's ASCII code), no conversion required.
If you want to convert a digit to the corresponding character, you can simply add '0':
c = i +'0';
The '0' is a character in the ASCll table.
A minor but important modification to existing solutions aiming at preserving framework styling (i.e. Bootstrap): replace this.size=0
with this.removeAttribute('size')
.
<select class="custom-select" onmousedown="if(this.options.length>5){this.size=5}"
onchange='this.blur()' onblur="this.removeAttribute('size')">
<option>option1</option>
<option>option2</option>
<option>option3</option>
<option>option4</option>
<option>option5</option>
<option>option6</option>
<option>option7</option>
</select>
In SQL 2005, you first need to show the Database Name column in your trace. The easiest thing to do is to pick the Tuning template, which has that column added already.
Assuming you have the Tuning template selected, to filter:
I always save the trace to a table too so I can do LIKE queries on the trace data after the fact.
For others who ran into this issue in a project that is not using a sonar-runners.property file, you may find (as I did) that you need to tweak your pom.xml file, adding a sonar.host.url property.
For example, I needed to add the following line under the 'properties' element:
<sonar.host.url>https://sonar.my-internal-company-domain.net</sonar.host.url>
Where the url points to our internal sonar deployment.
Have you tried the =DateValue()
function?
To include time value, just add the functions together:
=DateValue(A1)+TimeValue(A1)
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:
Mouse.OverrideCursor = Cursors.Wait;
try
{
// do stuff
}
finally
{
Mouse.OverrideCursor = null;
}
This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.
FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
and decrypt that.
The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.
One can get special keys like ENTER by overriding the IsInputKey method:
public class CustomTextBox : System.Windows.Forms.TextBox
{
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Return)
return true;
return base.IsInputKey(keyData);
}
}
Then one can use the KeyDown event in the following way:
CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Enter key is down
//Capture the text
if (sender is TextBox)
{
TextBox txb = (TextBox)sender;
MessageBox.Show(txb.Text);
}
}
}
In redux-saga, the equivalent of the above example would be
export function* loginSaga() {
while(true) {
const { user, pass } = yield take(LOGIN_REQUEST)
try {
let { data } = yield call(request.post, '/login', { user, pass });
yield fork(loadUserData, data.uid);
yield put({ type: LOGIN_SUCCESS, data });
} catch(error) {
yield put({ type: LOGIN_ERROR, error });
}
}
}
export function* loadUserData(uid) {
try {
yield put({ type: USERDATA_REQUEST });
let { data } = yield call(request.get, `/users/${uid}`);
yield put({ type: USERDATA_SUCCESS, data });
} catch(error) {
yield put({ type: USERDATA_ERROR, error });
}
}
The first thing to notice is that we're calling the api functions using the form yield call(func, ...args)
. call
doesn't execute the effect, it just creates a plain object like {type: 'CALL', func, args}
. The execution is delegated to the redux-saga middleware which takes care of executing the function and resuming the generator with its result.
The main advantage is that you can test the generator outside of Redux using simple equality checks
const iterator = loginSaga()
assert.deepEqual(iterator.next().value, take(LOGIN_REQUEST))
// resume the generator with some dummy action
const mockAction = {user: '...', pass: '...'}
assert.deepEqual(
iterator.next(mockAction).value,
call(request.post, '/login', mockAction)
)
// simulate an error result
const mockError = 'invalid user/password'
assert.deepEqual(
iterator.throw(mockError).value,
put({ type: LOGIN_ERROR, error: mockError })
)
Note we're mocking the api call result by simply injecting the mocked data into the next
method of the iterator. Mocking data is way simpler than mocking functions.
The second thing to notice is the call to yield take(ACTION)
. Thunks are called by the action creator on each new action (e.g. LOGIN_REQUEST
). i.e. actions are continually pushed to thunks, and thunks have no control on when to stop handling those actions.
In redux-saga, generators pull the next action. i.e. they have control when to listen for some action, and when to not. In the above example the flow instructions are placed inside a while(true)
loop, so it'll listen for each incoming action, which somewhat mimics the thunk pushing behavior.
The pull approach allows implementing complex control flows. Suppose for example we want to add the following requirements
Handle LOGOUT user action
upon the first successful login, the server returns a token which expires in some delay stored in a expires_in
field. We'll have to refresh the authorization in the background on each expires_in
milliseconds
Take into account that when waiting for the result of api calls (either initial login or refresh) the user may logout in-between.
How would you implement that with thunks; while also providing full test coverage for the entire flow? Here is how it may look with Sagas:
function* authorize(credentials) {
const token = yield call(api.authorize, credentials)
yield put( login.success(token) )
return token
}
function* authAndRefreshTokenOnExpiry(name, password) {
let token = yield call(authorize, {name, password})
while(true) {
yield call(delay, token.expires_in)
token = yield call(authorize, {token})
}
}
function* watchAuth() {
while(true) {
try {
const {name, password} = yield take(LOGIN_REQUEST)
yield race([
take(LOGOUT),
call(authAndRefreshTokenOnExpiry, name, password)
])
// user logged out, next while iteration will wait for the
// next LOGIN_REQUEST action
} catch(error) {
yield put( login.error(error) )
}
}
}
In the above example, we're expressing our concurrency requirement using race
. If take(LOGOUT)
wins the race (i.e. user clicked on a Logout Button). The race will automatically cancel the authAndRefreshTokenOnExpiry
background task. And if the authAndRefreshTokenOnExpiry
was blocked in middle of a call(authorize, {token})
call it'll also be cancelled. Cancellation propagates downward automatically.
You can find a runnable demo of the above flow
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
If Controls.Find is not found "textBox1" => error. You must add code.
If(tbx != null)
Edit:
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
tbx.Text = "found!";
do
{
// whatever
} while ( !condition );
Simple function that gets you a token that is URL safe and has base64 encoding! It's a combination of 2 answers from above.
const randomToken = () => {
crypto.randomBytes(64).toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
}
Minor addition to what has been said before. You likely want to return a dataframe. This would be done as
import pypyodbc
import pandas as pd
cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=server_name;"
"Database=db_name;"
"uid=User;pwd=password")
df = pd.read_sql_query('select * from table', cnxn)
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
[k for (k, v) in i.iteritems() if v == 0]
Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0}
is perfectly legal.
If you want ordering you either need to use a list or a OrderedDict instance instead:
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
echo Running from `dirname $0`
As I used ul:not(:first-child)
is a perfect solution.
div ul:not(:first-child) {
background-color: #900;
}
Why is this a perfect because by using ul:not(:first-child)
, we can apply CSS on inner elements. Like li, img, span, a
tags etc.
But when used others solutions:
div ul + ul {
background-color: #900;
}
and
div li~li {
color: red;
}
and
ul:not(:first-of-type) {}
and
div ul:nth-child(n+2) {
background-color: #900;
}
These restrict only ul level CSS. Suppose we cannot apply CSS on li
as `div ul + ul li'.
For inner level elements the first Solution works perfectly.
div ul:not(:first-child) li{
background-color: #900;
}
and so on ...
do this in two steps:
and use preg_replace
:
$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);
If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:
i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
if x in d:
d[x] = d[x] + y #or whatever your function needs to be to combine them
else:
d[x] = y
In that example, d == {'a': 3, 'c': 4, 'b': 8}
Keep variables in a separate wxi
include file. Enables re-use, variables are faster to find and (if needed) allows for easier manipulation by an external tool.
Define Platform variables for x86 and x64 builds
<!-- Product name as you want it to appear in Add/Remove Programs-->
<?if $(var.Platform) = x64 ?>
<?define ProductName = "Product Name (64 bit)" ?>
<?define Win64 = "yes" ?>
<?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
<?else ?>
<?define ProductName = "Product Name" ?>
<?define Win64 = "no" ?>
<?define PlatformProgramFilesFolder = "ProgramFilesFolder" ?>
<?endif ?>
Store the installation location in the registry, enabling upgrades to find the correct location. For example, if a user sets custom install directory.
<Property Id="INSTALLLOCATION">
<RegistrySearch Id="RegistrySearch" Type="raw" Root="HKLM" Win64="$(var.Win64)"
Key="Software\Company\Product" Name="InstallLocation" />
</Property>
Note: WiX guru Rob Mensching has posted an excellent blog entry which goes into more detail and fixes an edge case when properties are set from the command line.
Examples using 1. 2. and 3.
<?include $(sys.CURRENTDIR)\Config.wxi?>
<Product ... >
<Package InstallerVersion="200" InstallPrivileges="elevated"
InstallScope="perMachine" Platform="$(var.Platform)"
Compressed="yes" Description="$(var.ProductName)" />
and
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="$(var.PlatformProgramFilesFolder)">
<Directory Id="INSTALLLOCATION" Name="$(var.InstallName)">
The simplest approach is always do major upgrades, since it allows both new installs and upgrades in the single MSI. UpgradeCode is fixed to a unique Guid and will never change, unless we don't want to upgrade existing product.
Note: In WiX 3.5 there is a new MajorUpgrade element which makes life even easier!
Creating an icon in Add/Remove Programs
<Icon Id="Company.ico" SourceFile="..\Tools\Company\Images\Company.ico" />
<Property Id="ARPPRODUCTICON" Value="Company.ico" />
<Property Id="ARPHELPLINK" Value="http://www.example.com/" />
On release builds we version our installers, copying the msi file to a deployment directory. An example of this using a wixproj target called from AfterBuild target:
<Target Name="CopyToDeploy" Condition="'$(Configuration)' == 'Release'">
<!-- Note we append AssemblyFileVersion, changing MSI file name only works with Major Upgrades -->
<Copy SourceFiles="$(OutputPath)$(OutputName).msi"
DestinationFiles="..\Deploy\Setup\$(OutputName) $(AssemblyFileVersion)_$(Platform).msi" />
</Target>
Use heat to harvest files with wildcard (*) Guid. Useful if you want to reuse WXS files across multiple projects (see my answer on multiple versions of the same product). For example, this batch file automatically harvests RoboHelp output.
@echo off
robocopy ..\WebHelp "%TEMP%\WebHelpTemp\WebHelp" /E /NP /PURGE /XD .svn
"%WIX%bin\heat" dir "%TEMP%\WebHelp" -nologo -sfrag -suid -ag -srd -dir WebHelp -out WebHelp.wxs -cg WebHelpComponent -dr INSTALLLOCATION -var var.WebDeploySourceDir
There's a bit going on, robocopy
is stripping out Subversion working copy metadata before harvesting; the -dr
root directory reference is set to our installation location rather than default TARGETDIR; -var
is used to create a variable to specify the source directory (web deployment output).
Easy way to include the product version in the welcome dialog title by using Strings.wxl for localization. (Credit: saschabeaumont. Added as this great tip is hidden in a comment)
<WixLocalization Culture="en-US" xmlns="http://schemas.microsoft.com/wix/2006/localization">
<String Id="WelcomeDlgTitle">{\WixUI_Font_Bigger}Welcome to the [ProductName] [ProductVersion] Setup Wizard</String>
</WixLocalization>
Save yourself some pain and follow Wim Coehen's advice of one component per file. This also allows you to leave out (or wild-card *
) the component GUID.
Rob Mensching has a neat way to quickly track down problems in MSI log files by searching for value 3
. Note the comments regarding internationalization.
When adding conditional features, it's more intuitive to set the default feature level to 0 (disabled) and then set the condition level to your desired value. If you set the default feature level >= 1, the condition level has to be 0 to disable it, meaning the condition logic has to be the opposite to what you'd expect, which can be confusing :)
<Feature Id="NewInstallFeature" Level="0" Description="New installation feature" Absent="allow">
<Condition Level="1">NOT UPGRADEFOUND</Condition>
</Feature>
<Feature Id="UpgradeFeature" Level="0" Description="Upgrade feature" Absent="allow">
<Condition Level="1">UPGRADEFOUND</Condition>
</Feature>
Starting from 4.x the sort methods have been changed. If you are using >4.x. Try using any of the following.
Post.find({}).sort('-date').exec(function(err, docs) { ... });
Post.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Post.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Post.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });
Following is the perfect solution for this. This works fine with me for iOS5 and iOS4.
//---- For providing background image to tabbar
UITabBar *tabBar = [tabBarController tabBar];
if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
// ios 5 code here
[tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
}
else {
// ios 4 code here
CGRect frame = CGRectMake(0, 0, 480, 49);
UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
tabbg_view.backgroundColor = tabbg_color;
[tabBar insertSubview:tabbg_view atIndex:0];
}
(Edit: replaced broken links with archived copies)
Dave Artz of AOL gave a great talk on optimization at jQuery Conference Boston last year. AOL uses a tool called Sonar for on-demand loading based on scroll position. Check the code for the particulars of how it compares scrollTop (and others) to the element offset to detect if part or all of the element is visible.
Dave talks about Sonar in these slides. Sonar starts on slide 46, while the overall "load on demand" discussion starts on slide 33.
Add the css:
html,body{
height:100%;
}
.bg-img {
background: url(image.jpg) no-repeat center top;
background-size: cover;
height:100%;
}
And html is:
<div class="bg-mg"></div>
CSS: stretching background image to 100% width and height of screen?
i had the same problem in visual studio 2019 and it resolved by searching in the searchbar inside visual studio: manage NuGet packages > oracle.ManagedDataAccess (first result) install it. and then it should works!
This will search every column of every table in a specific database. Create the stored procedure on the database that you want to search in.
The Ten Most Asked SQL Server Questions And Their Answers:
CREATE PROCEDURE FindMyData_String
@DataToFind NVARCHAR(4000),
@ExactMatch BIT = 0
AS
SET NOCOUNT ON
DECLARE @Temp TABLE(RowId INT IDENTITY(1,1), SchemaName sysname, TableName sysname, ColumnName SysName, DataType VARCHAR(100), DataFound BIT)
INSERT INTO @Temp(TableName,SchemaName, ColumnName, DataType)
SELECT C.Table_Name,C.TABLE_SCHEMA, C.Column_Name, C.Data_Type
FROM Information_Schema.Columns AS C
INNER Join Information_Schema.Tables AS T
ON C.Table_Name = T.Table_Name
AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
WHERE Table_Type = 'Base Table'
And Data_Type In ('ntext','text','nvarchar','nchar','varchar','char')
DECLARE @i INT
DECLARE @MAX INT
DECLARE @TableName sysname
DECLARE @ColumnName sysname
DECLARE @SchemaName sysname
DECLARE @SQL NVARCHAR(4000)
DECLARE @PARAMETERS NVARCHAR(4000)
DECLARE @DataExists BIT
DECLARE @SQLTemplate NVARCHAR(4000)
SELECT @SQLTemplate = CASE WHEN @ExactMatch = 1
THEN 'If Exists(Select *
From ReplaceTableName
Where Convert(nVarChar(4000), [ReplaceColumnName])
= ''' + @DataToFind + '''
)
Set @DataExists = 1
Else
Set @DataExists = 0'
ELSE 'If Exists(Select *
From ReplaceTableName
Where Convert(nVarChar(4000), [ReplaceColumnName])
Like ''%' + @DataToFind + '%''
)
Set @DataExists = 1
Else
Set @DataExists = 0'
END,
@PARAMETERS = '@DataExists Bit OUTPUT',
@i = 1
SELECT @i = 1, @MAX = MAX(RowId)
FROM @Temp
WHILE @i <= @MAX
BEGIN
SELECT @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName', QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)), 'ReplaceColumnName', ColumnName)
FROM @Temp
WHERE RowId = @i
PRINT @SQL
EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @DataExists = @DataExists OUTPUT
IF @DataExists =1
UPDATE @Temp SET DataFound = 1 WHERE RowId = @i
SET @i = @i + 1
END
SELECT SchemaName,TableName, ColumnName
FROM @Temp
WHERE DataFound = 1
GO
To run it, just do this:
exec FindMyData_string 'google', 0
It works amazingly well!!!
try with screen -d -r
or screen -D -RR
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
In addition,
Not project dependent properities, Eclipse Preferences.
In Mac, Eclipse > Preferences
You are right, that test
"and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test
instruction is used (and exist).
JE
jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF
flag is set. And as it is one of the flags that is set by test
, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.
For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.
The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.
function start(){
document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
}
function addActivityItem(){
//option is selected
alert("yeah");
}
window.addEventListener("load", start, false);
Here I am sharing the script, convert UTC timestamp to Indian timestamp:-
// create a $utc object with the UTC timezone
$IST = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));
// change the timezone of the object without changing it's time
$IST->setTimezone(new DateTimeZone('Asia/Kolkata'));
// format the datetime
echo $IST->format('Y-m-d H:i:s T');
You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:
if let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex) {
println(color) // "Red"
let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
println(imageURLString) // http://hahaha.com/ha.php?color=Red
}
When the workbook first opens, execute this code:
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
Then just have a macro in the workbook called "EventMacro" that will repeat it.
Public Sub EventMacro()
'... Execute your actions here'
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
End Sub
Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using
keytool -list -v -keystore truststore.jks
I know this is an old post but try using an extension method:
public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
{
return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
}
and use it like this
var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));
Feel free to choose your own dates, you don't have to restrict yourself to January 2000.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
One additional thing I would like to mention that some of the answers may have missed is the downside to having both ETags
and Expires/Cache-control
in your headers.
Depending on your needs it may just add extra bytes in your headers which may increase packets which means more TCP overhead. Again, you should see if the overhead of having both things in your headers is necessary or will it just add extra weight in your requests which reduces performance.
You can read more about it on this excellent blog post by Kyle Simpson: http://calendar.perfplanet.com/2010/bloated-request-response-headers/
write() only takes a single string argument, so you could do this:
outf.write(str(num))
or
outf.write('{}'.format(num)) # more "modern"
outf.write('%d' % num) # deprecated mostly
Also note that write
will not append a newline to your output so if you need it you'll have to supply it yourself.
Aside:
Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):
num = 7
outf.write('{:03d}\n'.format(num))
num = 12
outf.write('%03d\n' % num)
to get three spaces, with leading zeros for your integer value followed by a newline:
007
012
format() will be around for a long while, so it's worth learning/knowing.
This causes the error:
MyClass aCoolObj = new MyClass();
aCoolObj.MyCoolStaticMethod();
This is the fix:
MyClass.MyCoolStaticMethod();
Explanation:
You can't call a static method from an instance of an object. The whole point of static methods is to not be tied to instances of objects, but instead to persist through all instances of that object, and/or to be used without any instances of the object.
Try this
frame$twohouses <- ifelse(frame$data>1, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
6 2 2
7 3 2
8 1 1
9 4 2
10 3 2
11 2 2
12 4 2
13 0 1
14 1 1
15 2 2
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
Rewrite rules are pretty much written the same way with nginx: http://wiki.nginx.org/HttpRewriteModule#rewrite
Which rules are causing you trouble? I could help you translate those!
Install zip
sudo apt-get install zip
Zip your folder:
zip -r {filename.zip} {foldername}
Windows does not come with a command-line zip program, despite Windows Explorer natively supporting Zip files since the Plus! pack for Windows 98.
I recommend the open-source 7-Zip utility which includes a command-line executable and supports many different archive file types, especially its own *.7z
format which offers superior compression ratios to traditional (PKZIP) *.zip
files:
Download 7-Zip from the 7-Zip home page
Add the path to 7z.exe
to your PATH
environment variable. See this QA:
How to set the path and environment variables in Windows
Open a new command-prompt window and use this command to create a PKZIP *.zip
file:
7z a -tzip {yourfile.zip} {yourfolder}
If you have the Java JDK installed then you can use the jar
utility to create Zip files, as *.jar
files are essentially just renamed *.zip
(PKZIP) files:
jar -cfM {yourfile.zip} {yourfolder}
Explanation: * -c compress * -f specify filename * -M do not include a MANIFEST file
On top of the answers already given, to open a new tab the javascript command window.open()
can be used.
For example:
# Opens a new tab
self.driver.execute_script("window.open()")
# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])
# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here
You're then able to close the original tab as follows
# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
# Close original tab
self.driver.close()
# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])
Or close the newly opened tab
# Close current tab
self.driver.close()
# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
Hope this helps.
Update: As of jQuery 1.4 you can use the .delay( n )
method. http://api.jquery.com/delay/
$('.notice').fadeIn().delay(2000).fadeOut('slow');
Note: $.show()
and $.hide()
by default are not queued, so if you want to use $.delay()
with them, you need to configure them that way:
$('.notice')
.show({duration: 0, queue: true})
.delay(2000)
.hide({duration: 0, queue: true});
You could possibly use the Queue syntax, this might work:
jQuery(function($){
var e = $('.notice');
e.fadeIn();
e.queue(function(){
setTimeout(function(){
e.dequeue();
}, 2000 );
});
e.fadeOut('fast');
});
or you could be really ingenious and make a jQuery function to do it.
(function($){
jQuery.fn.idle = function(time)
{
var o = $(this);
o.queue(function()
{
setTimeout(function()
{
o.dequeue();
}, time);
});
};
})(jQuery);
which would ( in theory , working on memory here ) permit you do to this:
$('.notice').fadeIn().idle(2000).fadeOut('slow');
Here is another simple solution using np.histogram()
method.
myarray = np.random.random(100)
results, edges = np.histogram(myarray, normed=True)
binWidth = edges[1] - edges[0]
plt.bar(edges[:-1], results*binWidth, binWidth)
You can indeed check that the total sums up to 1 with:
> print sum(results*binWidth)
1.0
This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.
This hinges on the fact that the Firebase REST API offers a shallow=true
parameter.
Assume you have a post
object and each one can have a number of comments
:
{
"posts": {
"$postKey": {
"comments": {
...
}
}
}
}
You obviously don't want to fetch all of the comments, just the number of comments.
Assuming you have the key for a post, you can send a GET
request to
https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true
.
This will return an object of key-value pairs, where each key is the key of a comment and its value is true
:
{
"comment1key": true,
"comment2key": true,
...,
"comment9999key": true
}
The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length
).
This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.
For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-
viewDidLoad()
{
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
var width = UIScreen.main.bounds.width
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
width = width - 10
layout.itemSize = CGSize(width: width / 2, height: width / 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
}
You want to count the number of itemids in your array. Simply use:
int counter=list.size();
Less code increases efficiency. Do not re-invent the wheel...
I was just answering a very similar question about this, and happened to find this when looking for a link to back up my claims, so lucky you :)
My other answer:
The ViewPager does not support wrap_content
as it (usually) never have all its children loaded at the same time, and can therefore not get an appropriate size (the option would be to have a pager that changes size every time you have switched page).
You can however set a precise dimension (e.g. 150dp) and match_parent
works as well.
You can also modify the dimensions dynamically from your code by changing the height
-attribute in its LayoutParams
.
For your needs you can create the ViewPager in its own xml-file, with the layout_height set to 200dp, and then in your code, rather than creating a new ViewPager from scratch, you can inflate that xml-file:
LayoutInflater inflater = context.getLayoutInflater();
inflater.inflate(R.layout.viewpagerxml, layout, true);
I have a nice and easy implementation using bootstrap as follows.
<select class="custom-select" id="list" multiple></select>
<div class="dropdown-menu" id="menu-right-click" style=>
<h6 class="dropdown-header">Actions</h6>
<a class="dropdown-item" href="" onclick="option1();">Option 1</a>
<a class="dropdown-item" href="" onclick="option2();">Option 2</a>
</div>
<script>
$("#menu-right-click").hide();
$(document).on("contextmenu", "#list", function (e) {
$("#menu-right-click")
.css({
position: 'absolute',
left: e.pageX,
top: e.pageY,
display: 'block'
})
return false;
});
function option1() {
// something you want...
$("#menu-right-click").hide();
}
function option2() {
// something else
$("#menu-right-click").hide();
}
</script>
Swift 5.1
You can get class, struct, enum, protocol and NSObject names though Self.self
.
print("\(Self.self)")
Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:
SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
return *this;
}
I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).
As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.
Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory
import lxml.builder as lb
from lxml import etree
nstext = "new story"
story = lb.E.Asset(
lb.E.Attribute(nstext, name="Name", act="set"),
lb.E.Relation(lb.E.Asset(idref="Scope:767"),
name="Scope", act="set")
)
print 'story:\n', etree.tostring(story, pretty_print=True)
Output:
story:
<Asset>
<Attribute name="Name" act="set">new story</Attribute>
<Relation name="Scope" act="set">
<Asset idref="Scope:767"/>
</Relation>
</Asset>
Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.
varLines = Split(.responsetext, """,""")
strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)
The checkbox is in a td
, so need to get the parent first:
$("input:checkbox").on("change", function() {
$(this).parent().next().find("label").text("TESTTTT");
});
Alternatively, find a label which has a for
with the same id
(perhaps more performant than reverse traversal) :
$("input:checkbox").on("change", function() {
$("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});
Or, to be more succinct just this.id
:
$("input:checkbox").on("change", function() {
$("label[for='" + this.id + "']").text("TESTTTT");
});
The RequestContext
is deprecated from Primefaces 6.2. From this version use the following:
if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
PrimeFaces.current().ajax().update(componentID);
}
And to execute javascript from the backbean use this way:
PrimeFaces.current().executeScript(jsCommand);
What worked for me was downgrading from EF 6.1.3
to EF 6.1.1
.
In Visual Studios 2012+
head over to:
Tools - Nuget Package Manager - Package Manager Console`
Then enter:
Install-Package EntityFramework.SqlServerCompact -Version 6.1.1
I did not have to uninstall EF 6.1.3
first because the command above already does that.
In addition, I don't know if it did something, but I also installed SQL Server CE in my project.
Here's the link to the solution I found:
http://www.itorian.com/2014/11/no-entity-framework-provider-found-for.html
A few variants of Andrew Arnott's answer:
If you want to wait for an existing task and find out whether it completed or timed out, but don't want to cancel it if the timeout occurs:
public static async Task<bool> TimedOutAsync(this Task task, int timeoutMilliseconds)
{
if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
if (timeoutMilliseconds == 0) {
return !task.IsCompleted; // timed out if not completed
}
var cts = new CancellationTokenSource();
if (await Task.WhenAny( task, Task.Delay(timeoutMilliseconds, cts.Token)) == task) {
cts.Cancel(); // task completed, get rid of timer
await task; // test for exceptions or task cancellation
return false; // did not timeout
} else {
return true; // did timeout
}
}
If you want to start a work task and cancel the work if the timeout occurs:
public static async Task<T> CancelAfterAsync<T>( this Func<CancellationToken,Task<T>> actionAsync, int timeoutMilliseconds)
{
if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
var taskCts = new CancellationTokenSource();
var timerCts = new CancellationTokenSource();
Task<T> task = actionAsync(taskCts.Token);
if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
timerCts.Cancel(); // task completed, get rid of timer
} else {
taskCts.Cancel(); // timer completed, get rid of task
}
return await task; // test for exceptions or task cancellation
}
If you have a task already created that you want to cancel if a timeout occurs:
public static async Task<T> CancelAfterAsync<T>(this Task<T> task, int timeoutMilliseconds, CancellationTokenSource taskCts)
{
if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
var timerCts = new CancellationTokenSource();
if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
timerCts.Cancel(); // task completed, get rid of timer
} else {
taskCts.Cancel(); // timer completed, get rid of task
}
return await task; // test for exceptions or task cancellation
}
Another comment, these versions will cancel the timer if the timeout does not occur, so multiple calls will not cause timers to pile up.
sjb
You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list
Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.
check the symbolic links if they point to a valid library ...
You can add the path directly in /etc/ld.so.conf, without include...
run ldconfig -p
to see whether your library is well included in the cache.
HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use
HttpContext.Current.Request.Url.Port
Its function depends on the builders that you have in your project (they can choose to interpret clean command however they like) and whether you have auto-build turned on. If auto-build is on, invoking clean is equivalent of a clean build. First artifacts are removed, then a full build is invoked. If auto-build is off, clean will remove the artifacts and stop. You can then invoke build manually later.
Definitely works.
if [[ `pgrep -f $0` != "$$" ]]; then
echo "Exiting ! Exist"
exit
fi
If you don't want to use the libraries and want simple answer then the code is given below:
def swap_alpha(test_string):
new_string = ""
for i in test_string:
if i.upper() in test_string:
new_string += i.lower()
elif i.lower():
new_string += i.upper()
else:
return "invalid "
return new_string
user_string = input("enter the string:")
updated = swap_alpha(user_string)
print(updated)
The git merge-base
command can be used to find a common ancestor. So if my_experiment has not been merged into master yet and my_experiment was created from master you could:
git log --oneline `git merge-base my_experiment master`..my_experiment
It will order first, then get the first 20. A database will also process anything in the WHERE
clause before ORDER BY
.
You can very quickly find an upper bound.
Say, you take three quarters. Then you would only have to fill in the 'gaps' 1-24, 26-49, 51-74, 76-99 with other coins.
Trivially, that would work with 2 dimes, 1 nickel, and 4 pennies.
So, 3 + 4 + 2 + 1 should be an upper bound for your number of coins, Whenever your brute-force algorithm goes above thta, you can instantly stop searching any deeper.
The rest of the search should perform fast enough for any purpose with dynamic programming.
(edit: fixed answer as per Gabe's observation)
Don't use jQuery, just use javascript for correct result:
This includes scrollbar width/height:
var windowWidth = window.innerWidth;_x000D_
var windowHeight = window.innerHeight;_x000D_
_x000D_
alert('viewport width is: '+ windowWidth + ' and viewport height is:' + windowHeight);
_x000D_
This excludes scrollbar width/height:
var widthWithoutScrollbar = document.body.clientWidth;_x000D_
var heightWithoutScrollbar = document.body.clientHeight;_x000D_
_x000D_
alert('viewport width is: '+ widthWithoutScrollbar + ' and viewport height is:' + heightWithoutScrollbar);
_x000D_
As Vinay Kumar pointed out that it will not update global installed Angular CLI. To update it globally just use following commands:
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
Note if you want to update existing project you have to modify existing project, you should change package.json inside your project.
There are no breaking changes in Angular itself but they are in RxJS, so don't forget to use rxjs-compat library to work with legacy code.
npm install --save rxjs-compat
I wrote a good article about installation/updating Angular CLI http://bmnteam.com/angular-cli-installation/
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
This is what i've done works like a charm
private static int _x=0, _y=0;
private static Point _point;
public static Point LocationInForm(Control c)
{
if (c.Parent == null)
{
_x += c.Location.X;
_y += c.Location.Y;
_point = new Point(_x, _y);
_x = 0; _y = 0;
return _point;
}
else if ((c.Parent is System.Windows.Forms.Form))
{
_point = new Point(_x, _y);
_x = 0; _y = 0;
return _point;
}
else
{
_x += c.Location.X;
_y += c.Location.Y;
LocationInForm(c.Parent);
}
return new Point(1,1);
}
Byte swapping with ye olde 3-step-xor trick around a pivot in a template function gives a flexible, quick O(ln2) solution that does not require a library, the style here also rejects 1 byte types:
template<typename T>void swap(T &t){
for(uint8_t pivot = 0; pivot < sizeof(t)/2; pivot ++){
*((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);
*((uint8_t *)&t+sizeof(t)-1- pivot) ^= *((uint8_t *)&t + pivot);
*((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);
}
}
Console.Read()
Console.ReadLine()
Console.ReadKey()
I am working with a Linux environment. I removed all Git files and folders in a recursive way:
rm -rf .git
rm -rf .gitkeep
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
For finding generic type of one field:
((Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]).getSimpleName()
The following section at Android Developers describes a communication mechanism Creating event callbacks to the activity. To quote a line from it:
A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.
Edit:
The fragment has an onStart(...)
which is invoked when the fragment is visible to the user. Similarly an onResume(...)
when visible and actively running. These are tied to their activity counterparts.
In short: use onResume()
No, this will not work. The best you will be able to do is to iterate through all values and check them yourself:
boolean empty = true;
for (Object item : arrayList) {
if (item != null) {
empty = false;
break;
}
}
Rather than changing the RegKey, I was able to put a line in the header of my HTML:
<html>
<head>
<!-- Use lastest version of Internet Explorer -->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- Insert other header tags here -->
</head>
...
</html>
Try this
link_to "+ Service", my_services_new_path(:account_id => acct.id)
it will pass the account_id as you want.
For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
You can use the WSDL2JAVA Codegen (or) You can simply use the 'Web Service/WebServiceClient' Wizard available in the Eclipse IDE. Open the IDE and press 'Ctrl+N', selectfor 'Web Service/WebServiceClient', specify the wsdl URL, ouput folder and select finish.
It creates the complete source files that you would need.
The database must have a name (example DB1), try this one:
OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit");
In case the TNS is not defined you can also try this one:
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit");
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
I've ported Grant Burton's PHP code to an ASP.Net static method callable against the HttpRequestBase. It will optionally skip through any private IP ranges.
public static class ClientIP
{
// based on http://www.grantburton.com/2008/11/30/fix-for-incorrect-ip-addresses-in-wordpress-comments/
public static string ClientIPFromRequest(this HttpRequestBase request, bool skipPrivate)
{
foreach (var item in s_HeaderItems)
{
var ipString = request.Headers[item.Key];
if (String.IsNullOrEmpty(ipString))
continue;
if (item.Split)
{
foreach (var ip in ipString.Split(','))
if (ValidIP(ip, skipPrivate))
return ip;
}
else
{
if (ValidIP(ipString, skipPrivate))
return ipString;
}
}
return request.UserHostAddress;
}
private static bool ValidIP(string ip, bool skipPrivate)
{
IPAddress ipAddr;
ip = ip == null ? String.Empty : ip.Trim();
if (0 == ip.Length
|| false == IPAddress.TryParse(ip, out ipAddr)
|| (ipAddr.AddressFamily != AddressFamily.InterNetwork
&& ipAddr.AddressFamily != AddressFamily.InterNetworkV6))
return false;
if (skipPrivate && ipAddr.AddressFamily == AddressFamily.InterNetwork)
{
var addr = IpRange.AddrToUInt64(ipAddr);
foreach (var range in s_PrivateRanges)
{
if (range.Encompasses(addr))
return false;
}
}
return true;
}
/// <summary>
/// Provides a simple class that understands how to parse and
/// compare IP addresses (IPV4) ranges.
/// </summary>
private sealed class IpRange
{
private readonly UInt64 _start;
private readonly UInt64 _end;
public IpRange(string startStr, string endStr)
{
_start = ParseToUInt64(startStr);
_end = ParseToUInt64(endStr);
}
public static UInt64 AddrToUInt64(IPAddress ip)
{
var ipBytes = ip.GetAddressBytes();
UInt64 value = 0;
foreach (var abyte in ipBytes)
{
value <<= 8; // shift
value += abyte;
}
return value;
}
public static UInt64 ParseToUInt64(string ipStr)
{
var ip = IPAddress.Parse(ipStr);
return AddrToUInt64(ip);
}
public bool Encompasses(UInt64 addrValue)
{
return _start <= addrValue && addrValue <= _end;
}
public bool Encompasses(IPAddress addr)
{
var value = AddrToUInt64(addr);
return Encompasses(value);
}
};
private static readonly IpRange[] s_PrivateRanges =
new IpRange[] {
new IpRange("0.0.0.0","2.255.255.255"),
new IpRange("10.0.0.0","10.255.255.255"),
new IpRange("127.0.0.0","127.255.255.255"),
new IpRange("169.254.0.0","169.254.255.255"),
new IpRange("172.16.0.0","172.31.255.255"),
new IpRange("192.0.2.0","192.0.2.255"),
new IpRange("192.168.0.0","192.168.255.255"),
new IpRange("255.255.255.0","255.255.255.255")
};
/// <summary>
/// Describes a header item (key) and if it is expected to be
/// a comma-delimited string
/// </summary>
private sealed class HeaderItem
{
public readonly string Key;
public readonly bool Split;
public HeaderItem(string key, bool split)
{
Key = key;
Split = split;
}
}
// order is in trust/use order top to bottom
private static readonly HeaderItem[] s_HeaderItems =
new HeaderItem[] {
new HeaderItem("HTTP_CLIENT_IP",false),
new HeaderItem("HTTP_X_FORWARDED_FOR",true),
new HeaderItem("HTTP_X_FORWARDED",false),
new HeaderItem("HTTP_X_CLUSTER_CLIENT_IP",false),
new HeaderItem("HTTP_FORWARDED_FOR",false),
new HeaderItem("HTTP_FORWARDED",false),
new HeaderItem("HTTP_VIA",false),
new HeaderItem("REMOTE_ADDR",false)
};
}
ProgressDialog has become deprecated since API Level 26 https://developer.android.com/reference/android/app/ProgressDialog.html
I include a ProgressBar in my layout
<ProgressBar
android:layout_weight="1"
android:id="@+id/progressBar_cyclic"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="40dp"
android:minWidth="40dp" />
and change its visibility to .GONE | .VISIBLE depending on the use case.
progressBar_cyclic.visibility = View.VISIBLE
int i = 65;
char c = Convert.ToChar(i);
Here is the real life example
@Html.Grid(Model).Columns(columns =>
{
columns.Add()
.Encoded(false)
.Sanitized(false)
.SetWidth(10)
.Titled(string.Empty)
.RenderValueAs(x => @Html.ActionLink("Edit", "UserDetails", "Membership", null, null, "discount", new { @id = @x.Id }, new { @target = "_blank" }));
}).WithPaging(200).EmptyText("There Are No Items To Display")
And the target page has TABS
<ul id="myTab" class="nav nav-tabs" role="tablist">
<li class="active"><a href="#discount" role="tab" data-toggle="tab">Discount</a></li>
</ul>
I had the same issue after I upgraded my JDK from 1.7 to 1.8. I'm using Eclipse 4.4 (Luna). The error is gone after I degrade JDK to 1.7.
If you would like to dynamically access USB devices which can be plugged in while the docker container is already running, for example access a just attached usb webcam at /dev/video0, you can add a cgroup rule when starting the container. This option does not need a --privileged container and only allows access to specific types of hardware.
Check the device major number of the type of device you would like to add. You can look it up in the linux kernel documentation. Or you can check it for your device. For example to check the device major number for a webcam connected to /dev/video0, you can do a ls -la /dev/video0
. This results in something like:
crw-rw----+ 1 root video 81, 0 Jul 6 10:22 /dev/video0
Where the first number (81) is the device major number. Some common device major numbers:
Add rules when you start the docker container:
--device-cgroup-rule='c major_number:* rmw'
rule for every type of device you want access to-v /run/udev:/run/udev:ro
-v /dev:/dev
So to add all usb webcams and serial2usb devices to your docker container, do:
docker run -it -v /dev:/dev --device-cgroup-rule='c 188:* rmw' --device-cgroup-rule='c 81:* rmw' ubuntu bash
INSERT INTO KeyedTable(KeyField, Otherfield)
SELECT n.* FROM
(SELECT 'PossibleDupeLiteral' AS KeyField, 'OtherfieldValue' AS Otherfield
UNION ALL
SELECT 'PossibleDupeLiteral', 'OtherfieldValue2'
)
LEFT JOIN KeyedTable k
ON k.KeyField=n.KeyField
WHERE k.KeyField IS NULL
This tells the Server to look for the same data (hopefully the same speedy way it does to check for duplicate keys) and insert nothing if it finds it.
I like the IGNORE_DUP_KEY solution too, but then anyone who relies on errors to catch problems will be mystified when the server silently ignores their dupe-key errors.
The reason I choose this over Philip Kelley's solution is that you can provide several rows of data and only have the missing ones actually get in:
When you think your git is messed up, you can use this command to do everything up-to-date.
git rm -r --cached .
git add .
git commit -am 'git cache cleared'
git push
Also to revert back last commit use this :
git reset HEAD^ --hard
A very simple example that shows how to fix the footer at the bottom in your application's layout.
/* Styles go here */_x000D_
html{ height: 100%;}_x000D_
body{ min-height: 100%; background: #fff;}_x000D_
.page-layout{ border: none; width: 100%; height: 100vh; }_x000D_
.page-layout td{ vertical-align: top; }_x000D_
.page-layout .header{ background: #aaa; }_x000D_
.page-layout .main-content{ height: 100%; background: #f1f1f1; text-align: center; padding-top: 50px; }_x000D_
.page-layout .main-content .container{ text-align: center; padding-top: 50px; }_x000D_
.page-layout .footer{ background: #333; color: #fff; }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<link data-require="bootstrap@*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />_x000D_
<link rel="stylesheet" href="style.css" />_x000D_
<script src="script.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<table class="page-layout">_x000D_
<tr>_x000D_
<td class="header">_x000D_
<div>_x000D_
This is the site header._x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="main-content">_x000D_
<div>_x000D_
<h1>Fix footer always to the bottom</h1>_x000D_
<div>_x000D_
This is how you can simply fix the footer to the bottom._x000D_
</div>_x000D_
<div>_x000D_
The footer will always stick to the bottom until the main-content doesn't grow till footer._x000D_
</div>_x000D_
<div>_x000D_
Even if the content grows, the footer will start to move down naturally as like the normal behavior of page._x000D_
</div>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="footer">_x000D_
<div>_x000D_
This is the site footer._x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Microsoft Example Rnd Function
https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx
1- Initialize the random-number generator.
Randomize()
2 - Generate random value between 1 and 6.
Dim value As Integer = CInt(Int((6 * Rnd()) + 1))
Optimized (but less readable) implementation:
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.
Examples:
// firstName has a hard-coded value of "hello world"
string firstName = "hello world";
// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();
A hard-coded constant[1]:
float areaOfCircle(int radius)
{
float area = 0;
area = 3.14*radius*radius; // 3.14 is a hard-coded value
return area;
}
Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.
- Hard Coding “Hard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.
The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.- Soft Coding
If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.
In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.
In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.
Sources and Citations:
1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid
Further Reading:
Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding
This is an old question but none of the previous answers has addressed the real issue, i.e. that fact that the problem is with the question itself.
First, if the probabilities have been already calculated, i.e. the histogram aggregated data is available in a normalized way then the probabilities should add up to 1. They obviously do not and that means that something is wrong here, either with terminology or with the data or in the way the question is asked.
Second, the fact that the labels are provided (and not intervals) would normally mean that the probabilities are of categorical response variable - and a use of a bar plot for plotting the histogram is best (or some hacking of the pyplot's hist method), Shayan Shafiq's answer provides the code.
However, see issue 1, those probabilities are not correct and using bar plot in this case as "histogram" would be wrong because it does not tell the story of univariate distribution, for some reason (perhaps the classes are overlapping and observations are counted multiple times?) and such plot should not be called a histogram in this case.
Histogram is by definition a graphical representation of the distribution of univariate variable (see Histogram | NIST/SEMATECH e-Handbook of Statistical Methods & Histogram | Wikipedia) and is created by drawing bars of sizes representing counts or frequencies of observations in selected classes of the variable of interest. If the variable is measured on a continuous scale those classes are bins (intervals). Important part of histogram creation procedure is making a choice of how to group (or keep without grouping) the categories of responses for a categorical variable, or how to split the domain of possible values into intervals (where to put the bin boundaries) for continuous type variable. All observations should be represented, and each one only once in the plot. That means that the sum of the bar sizes should be equal to the total count of observation (or their areas in case of the variable widths, which is a less common approach). Or, if the histogram is normalised then all probabilities must add up to 1.
If the data itself is a list of "probabilities" as a response, i.e. the observations are probability values (of something) for each object of study then the best answer is simply plt.hist(probability)
with maybe binning option, and use of x-labels already available is suspicious.
Then bar plot should not be used as histogram but rather simply
import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375,
0.373117033603708, 0.36813186813186816, 0.32517482517482516,
0.4175257731958763, 0.41025641025641024, 0.39408866995073893,
0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327,
0.35398230088495575]
plt.hist(probability)
plt.show()
with the results
matplotlib in such case arrives by default with the following histogram values
(array([1., 1., 1., 1., 1., 2., 0., 2., 0., 4.]),
array([0.31308411, 0.32380469, 0.33452526, 0.34524584, 0.35596641,
0.36668698, 0.37740756, 0.38812813, 0.39884871, 0.40956928,
0.42028986]),
<a list of 10 Patch objects>)
the result is a tuple of arrays, the first array contains observation counts, i.e. what will be shown against the y-axis of the plot (they add up to 13, total number of observations) and the second array are the interval boundaries for x-axis.
One can check they they are equally spaced,
x = plt.hist(probability)[1]
for left, right in zip(x[:-1], x[1:]):
print(left, right, right-left)
Or, for example for 3 bins (my judgment call for 13 observations) one would get this histogram
plt.hist(probability, bins=3)
with the plot data "behind the bars" being
The author of the question needs to clarify what is the meaning of the "probability" list of values - is the "probability" just a name of the response variable (then why are there x-labels ready for the histogram, it makes no sense), or are the list values the probabilities calculated from the data (then the fact they do not add up to 1 makes no sense).
Ecma script 5 (ES5) which all browser support and precompiled. ES6/ES2015 and ES/2016 came this year with lots of changes so to pop up these changes there is something in between which should take cares about so TypeScript.
• TypeScript is Types -> Means we have to define datatype of each property and methods. If you know C# then Typescript is easy to understand.
• Big advantage of TypeScript is we identify Type related issues early before going to production. This allows unit tests to fail if there is any type mismatch.
Make sure you specify pass header=None
and add usecols=[3,6]
for the 4th and 7th columns.
Take out the MONTHS from your case, and remove the brackets... like this:
CASE
WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
ELSE 'NOTHING'
END AS 'MONTHS'
You can think of this as being equivalent to:
CASE TRUE
WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
ELSE 'NOTHING'
END AS 'MONTHS'
This solution worked for me:
var rawBodySaver = function (req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
}
app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));
When I use solution with req.on('data', function(chunk) { });
it not working on chunked request body.
Starting from tslint v5.8.0
you can set an exclude
property under your linterOptions
key in your tslint.json
file:
{
"extends": "tslint:latest",
"linterOptions": {
"exclude": [
"bin",
"**/__test__",
"lib/*generated.js"
]
}
}
More information on this here.
One major feature of rsync
over scp
(beside the delta algorithm and encryption if used w/ ssh) is that it automatically verifies if the transferred file has been transferred correctly. Scp will not do that, which occasionally might result in corruption when transferring larger files. So in general rsync is a copy with guarantee.
Centos manpages mention this the end of the --checksum
option description:
Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option’s before-the-transfer “Does this file need to be updated?” check.
var junk=new Array();
junk.push('This is a string.');
Et cetera.
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
In my case, a script was running command while redirecting both stdout and stderr to a file, something like:
cmd > log 2>&1
I needed to update it such that when there is a failure, take some actions based on the error messages. I could of course remove the dup 2>&1
and capture the stderr from the script, but then the error messages won't go into the log file for reference. While the accepted answer from @lhunath is supposed to do the same, it redirects stdout
and stderr
to different files, which is not what I want, but it helped me to come up with the exact solution that I need:
(cmd 2> >(tee /dev/stderr)) > log
With the above, log will have a copy of both stdout
and stderr
and I can capture stderr
from my script without having to worry about stdout
.
string[0] = "";
"warning: assignment makes integer from pointer without a cast
Ok, let's dive into the expression ...
0
an int: represents the number of chars (assuming string
is (or decayed into) a char*) to advance from the beginning of the object string
string[0]
: the char
object located at the beginning of the object string
""
: string literal: an object of type char[1]
=
: assignment operator: tries to assign a value of type char[1]
to an object of type char
. char[1]
(decayed to char*
) and char
are not assignment compatible, but the compiler trusts you (the programmer) and goes ahead with the assignment anyway by casting the type char*
(what char[1]
decayed to) to an int
--- and you get the warning as a bonus. You have a really nice compiler :-)
Within the dplyr world, try:
select(iris,contains("Sepal"))
See the Selection section in ?select
for numerous other helpers like starts_with
, ends_with
, etc.
The LDF is the transaction log. It keeps a record of everything done to the database for rollback purposes.
You do not want to delete, but you can shrink it with the dbcc shrinkfile
command. You can also right-click on the database in SQL Server Management Studio and go to Tasks > Shrink.
Delete platforms/android folder and try to rebuild. That helped me a lot.
(Visual Studio Tools for Apache Cordova)
The excellent (free trial) IcoFX allows you to create and edit icons, including multiple sizes up to 256x256, PNG compression, and transparency. I highly recommend it over most of the alternates.
Get your copy here: http://icofx.ro/ . It supports Windows XP onwards.
Windows automatically chooses the proper icon from the file, depending on where it is to be displayed.
For more information on icon design and the sizes/bit depths you should include, see these references:
Use new percentage support library
compile 'com.android.support:percent:24.0.0'
See below example
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
app:layout_marginTopPercent="25%"
app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentRelativeLayout>
Java always takes arguments as a string type...(String args[]) so you need to convert in your desired type.
Integer.parseInt()
to convert your string into Interger.System.out.println()
Example :
int a;
a = Integer.parseInt(args[0]);
and for Standard Input you can use codes like
StdIn.readInt();
StdIn.readString();
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If username/password contains any special characters then inside the camel configuration use RAW for Configuring the values like
RAW(se+re?t&23)
where se+re?t&23
is actual password
RAW({abc.ftp.password})
where {abc.ftp.password}
values comes from a spring property file.
By using RAW, solved my issue.
If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.
Otherwise, stick with multiple if-else statements.
What are -moz- and -webkit-?
CSS properties starting with -webkit-
, -moz-
, -ms-
or -o-
are called vendor prefixes.
Why do different browsers add different prefixes for the same effect?
A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:
Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.
Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.
Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds
-ms-grid
.The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.
UPDATE AS OF THE YEAR 2016
As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.
As mentioned in this glossary about Mozilla's view on Vendor Prefix
on May 3, 2016
,
Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.
For example, just a few years ago, to set a rounded corner on a box you had to write:
-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;
But now that browsers have come to fully support this feature, you really only need the standardized version:
border-radius: 10px 5px;
Finding the right rules for all browsers
As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.
You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.
Input:
a {
column-count: 3;
column-gap: 10px;
column-fill: auto;
}
Output:
a {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
-webkit-column-gap: 10px;
-moz-column-gap: 10px;
column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-fill: auto;
column-fill: auto;
}
I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.
map
is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)
noremap
is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map
. (Think of the nore
prefix to mean "non-recursive".)
(Note that there are also the !
modes like map!
that apply to insert & command-line.)
See below for what "recursive" means in this context.
Prepending a mode letter like n
modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map
wouldn't apply to (e.g. "insert").
Use help map-modes
will show you a few tables that explain how to control which modes the mapping applies to.
Mode letters:
n
: normal onlyv
: visual and selecto
: operator-pendingx
: visual onlys
: select onlyi
: insertc
: command-linel
: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.
The expansion stops when one of these is true:
At that point, Vim's default "meaning" of the final result is applied/executed.
"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.
Example:
nmap K H
nnoremap H G
nnoremap G gg
The above causes K
to expand to H
, then H
to expand to G
and stop. It stops because of the nnoremap
, which expands and stops immediately. The meaning of G
will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).
The mapping of G
to gg
only applies if you press G
, but not if you press K
. This mapping doesn't affect pressing K
regardless of whether G
was mapped recursively or not, since it's line 2 that causes the expansion of K
to stop, so line 3 wouldn't be used.
Use exceljs library for creating and writing into existing excel sheets.
You can check this tutorial for detailed explanation.
Have you tried the "Publish" method? You just right click on the project file in the solution explorer and select "Publish" from the pop-up menu. This creates an installer in a few very simple steps.
You can do more configuration of the installer from the Publish tab in the project properties window.
NB: This method only works for WPF & Windows Forms apps.
Since 2005, Mozilla browsers such as Firefox have supported the non-standard :-moz-broken
CSS pseudo-class that can accomplish exactly this request:
td {_x000D_
min-width:64px; /* for display purposes so you can see the empty cell */_x000D_
}_x000D_
_x000D_
img[alt]:-moz-broken {_x000D_
display:none;_x000D_
}
_x000D_
<table border="1"><tr><td>_x000D_
<img src="error">_x000D_
</td><td>_x000D_
<img src="broken" alt="A broken image">_x000D_
</td><td>_x000D_
<img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png"_x000D_
alt="A bird" style="width: 120px">_x000D_
</td></tr></table>
_x000D_
img[alt]::before
also works in Firefox 64 (though once upon a time it was img[alt]::after
so this is not reliable). I can't get either of those to work in Chrome 71.
You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:
Set MyEmail=CreateObject("CDO.Message")
MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
MyEmail.Configuration.Fields.Update
MyEmail.Send
set MyEmail=nothing
If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update
line:
'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username"
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"
More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm
Here's a solution to the general case that doesn't involve needing to know the length of the array ahead of time, using collect
, or using udf
s. Unfortunately this only works for spark
version 2.1 and above, because it requires the posexplode
function.
Suppose you had the following DataFrame:
df = spark.createDataFrame(
[
[1, 'A, B, C, D'],
[2, 'E, F, G'],
[3, 'H, I'],
[4, 'J']
]
, ["num", "letters"]
)
df.show()
#+---+----------+
#|num| letters|
#+---+----------+
#| 1|A, B, C, D|
#| 2| E, F, G|
#| 3| H, I|
#| 4| J|
#+---+----------+
Split the letters
column and then use posexplode
to explode the resultant array along with the position in the array. Next use pyspark.sql.functions.expr
to grab the element at index pos
in this array.
import pyspark.sql.functions as f
df.select(
"num",
f.split("letters", ", ").alias("letters"),
f.posexplode(f.split("letters", ", ")).alias("pos", "val")
)\
.show()
#+---+------------+---+---+
#|num| letters|pos|val|
#+---+------------+---+---+
#| 1|[A, B, C, D]| 0| A|
#| 1|[A, B, C, D]| 1| B|
#| 1|[A, B, C, D]| 2| C|
#| 1|[A, B, C, D]| 3| D|
#| 2| [E, F, G]| 0| E|
#| 2| [E, F, G]| 1| F|
#| 2| [E, F, G]| 2| G|
#| 3| [H, I]| 0| H|
#| 3| [H, I]| 1| I|
#| 4| [J]| 0| J|
#+---+------------+---+---+
Now we create two new columns from this result. First one is the name of our new column, which will be a concatenation of letter
and the index in the array. The second column will be the value at the corresponding index in the array. We get the latter by exploiting the functionality of pyspark.sql.functions.expr
which allows us use column values as parameters.
df.select(
"num",
f.split("letters", ", ").alias("letters"),
f.posexplode(f.split("letters", ", ")).alias("pos", "val")
)\
.drop("val")\
.select(
"num",
f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
f.expr("letters[pos]").alias("val")
)\
.show()
#+---+-------+---+
#|num| name|val|
#+---+-------+---+
#| 1|letter0| A|
#| 1|letter1| B|
#| 1|letter2| C|
#| 1|letter3| D|
#| 2|letter0| E|
#| 2|letter1| F|
#| 2|letter2| G|
#| 3|letter0| H|
#| 3|letter1| I|
#| 4|letter0| J|
#+---+-------+---+
Now we can just groupBy
the num
and pivot
the DataFrame. Putting that all together, we get:
df.select(
"num",
f.split("letters", ", ").alias("letters"),
f.posexplode(f.split("letters", ", ")).alias("pos", "val")
)\
.drop("val")\
.select(
"num",
f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
f.expr("letters[pos]").alias("val")
)\
.groupBy("num").pivot("name").agg(f.first("val"))\
.show()
#+---+-------+-------+-------+-------+
#|num|letter0|letter1|letter2|letter3|
#+---+-------+-------+-------+-------+
#| 1| A| B| C| D|
#| 3| H| I| null| null|
#| 2| E| F| G| null|
#| 4| J| null| null| null|
#+---+-------+-------+-------+-------+