Expanding on @gecco 's answer, the following is an example that'll show you the difference:
def foo(**kwargs):
for entry in kwargs.items():
print("Key: {}, value: {}".format(entry[0], entry[1]))
# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})
# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")
Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails
It's very simple....
import nltk
nltk.download()
The title attribute also works well with other html elements, for example a link...
<a title="hover text" ng-href="{{getUrl()}}"> download link
</a>
If the files already have the +x flag set, git update-index --chmod=+x
does nothing and git thinks there's nothing to commit, even though the flag isn't being saved into the repo.
You must first remove the flag, run the git command, then put the flag back:
chmod -x <file>
git update-index --chmod=+x <file>
chmod +x <file>
then git sees a change and will allow you to commit the change.
There are two ways to assign argument values to function parameters, both are used.
By Position. Positional arguments do not have keywords and are assigned first.
By Keyword. Keyword arguments have keywords and are assigned second, after positional arguments.
Note that you have the option to use positional arguments.
If you don't use positional arguments, then -- yes -- everything you wrote turns out to be a keyword argument.
When you call a function you make a decision to use position or keyword or a mixture. You can choose to do all keywords if you want. Some of us do not make this choice and use positional arguments.
Core jQuery doesn't have anything special for touch events, but you can easily build your own using the following events
For example, the touchmove
document.addEventListener('touchmove', function(e) {
e.preventDefault();
var touch = e.touches[0];
alert(touch.pageX + " - " + touch.pageY);
}, false);
This works in most WebKit based browsers (incl. Android).
In Eclipse
, go to File
-> Switch Workspace
, choose or create a new workspace.
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
In mysqli_query(first parameter should be connection,your sql statement) so
$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');
but best practice is
$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);
If start time is a datetime type then you can use something like
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime >= '2012-03-08 00:00:00.000'
AND StartTime <= '2012-03-08 01:00:00.000'
Obviously you would want to use your own values for the times but this should give you everything in that 1 hour period inclusive of both the upper and lower limit.
You can use the GETDATE() function to get todays current date.
This is a repackaging of the accepted answer - but in a way that lets you compare them all to each other for yourself - the top 3 algorithms are compared (and comments explain why other methods are excluded) and you can run against your own setup to see how they each perform with the size of sequence that you desire.
SET NOCOUNT ON;
--
-- Set the count of numbers that you want in your sequence ...
--
DECLARE @NumberOfNumbers int = 10000000;
--
-- Some notes on choosing a useful length for your sequence ...
-- For a sequence of 100 numbers -- winner depends on preference of min/max/avg runtime ... (I prefer PhilKelley algo here - edit the algo so RowSet2 is max RowSet CTE)
-- For a sequence of 1k numbers -- winner depends on preference of min/max/avg runtime ... (Sadly PhilKelley algo is generally lowest ranked in this bucket, but could be tweaked to perform better)
-- For a sequence of 10k numbers -- a clear winner emerges for this bucket
-- For a sequence of 100k numbers -- do not test any looping methods at this size or above ...
-- the previous winner fails, a different method is need to guarantee the full sequence desired
-- For a sequence of 1MM numbers -- the statistics aren't changing much between the algorithms - choose one based on your own goals or tweaks
-- For a sequence of 10MM numbers -- only one of the methods yields the desired sequence, and the numbers are much closer than for smaller sequences
DECLARE @TestIteration int = 0;
DECLARE @MaxIterations int = 10;
DECLARE @MethodName varchar(128);
-- SQL SERVER 2017 Syntax/Support needed
DROP TABLE IF EXISTS #TimingTest
CREATE TABLE #TimingTest (MethodName varchar(128), TestIteration int, StartDate DateTime2, EndDate DateTime2, ElapsedTime decimal(38,0), ItemCount decimal(38,0), MaxNumber decimal(38,0), MinNumber decimal(38,0))
--
-- Conduct the test ...
--
WHILE @TestIteration < @MaxIterations
BEGIN
-- Be sure that the test moves forward
SET @TestIteration += 1;
/* -- This method has been removed, as it is BY FAR, the slowest method
-- This test shows that, looping should be avoided, likely at all costs, if one places a value / premium on speed of execution ...
--
-- METHOD - Fast looping
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);
-- Method information
SET @MethodName = 'FastLoop';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
DECLARE @i INT = 1;
WHILE @i <= @NumberOfNumbers
BEGIN
INSERT INTO [Numbers].[Test](Number) VALUES (@i);
SELECT @i = @i + 1;
END;
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
*/
/* -- This method requires GO statements, which would break the script, also - this answer does not appear to be the fastest *AND* seems to perform "magic"
--
-- METHOD - "Semi-Looping"
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);
-- Method information
SET @MethodName = 'SemiLoop';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
INSERT [Numbers].[Test] values (1);
-- GO --required
INSERT [Numbers].[Test] SELECT Number + (SELECT COUNT(*) FROM [Numbers].[Test]) FROM [Numbers].[Test]
-- GO 14 --will create 16384 total rows
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
*/
--
-- METHOD - Philip Kelley's algo
-- (needs tweaking to match the desired length of sequence in order to optimize its performance, relies more on the coder to properly tweak the algorithm)
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);
-- Method information
SET @MethodName = 'PhilKelley';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
; WITH
RowSet0 as (select 1 as Item union all select 1), -- 2 rows -- We only have to name the column in the first select, the second/union select inherits the column name
RowSet1 as (select 1 as Item from RowSet0 as A, RowSet0 as B), -- 4 rows
RowSet2 as (select 1 as Item from RowSet1 as A, RowSet1 as B), -- 16 rows
RowSet3 as (select 1 as Item from RowSet2 as A, RowSet2 as B), -- 256 rows
RowSet4 as (select 1 as Item from RowSet3 as A, RowSet3 as B), -- 65536 rows (65k)
RowSet5 as (select 1 as Item from RowSet4 as A, RowSet4 as B), -- 4294967296 rows (4BB)
-- Add more RowSetX to get higher and higher numbers of rows
-- Each successive RowSetX results in squaring the previously available number of rows
Tally as (select row_number() over (order by Item) as Number from RowSet5) -- This is what gives us the sequence of integers, always select from the terminal CTE expression
-- Note: testing of this specific use case has shown that making Tally as a sub-query instead of a terminal CTE expression is slower (always) - be sure to follow this pattern closely for max performance
INSERT INTO [Numbers].[Test] (Number)
SELECT o.Number
FROM Tally o
WHERE o.Number <= @NumberOfNumbers
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
--
-- METHOD - Mladen Prajdic answer
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);
-- Method information
SET @MethodName = 'MladenPrajdic';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
INSERT INTO [Numbers].[Test](Number)
SELECT TOP (@NumberOfNumbers) row_number() over(order by t1.number) as N
FROM master..spt_values t1
CROSS JOIN master..spt_values t2
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
--
-- METHOD - Single INSERT
--
-- Prep for the test
DROP TABLE IF EXISTS [Numbers].[Test];
-- The Table creation is part of this algorithm ...
-- Method information
SET @MethodName = 'SingleInsert';
-- Record the start of the test
INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
SELECT @MethodName, @TestIteration, GETDATE()
-- Run the algorithm
SELECT TOP (@NumberOfNumbers) IDENTITY(int,1,1) AS Number
INTO [Numbers].[Test]
FROM sys.objects s1 -- use sys.columns if you don't get enough rows returned to generate all the numbers you need
CROSS JOIN sys.objects s2 -- use sys.columns if you don't get enough rows returned to generate all the numbers you need
ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)
-- Record the end of the test
UPDATE tt
SET
EndDate = GETDATE()
FROM #TimingTest tt
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
-- And the stats about the numbers in the sequence
UPDATE tt
SET
ItemCount = results.ItemCount,
MaxNumber = results.MaxNumber,
MinNumber = results.MinNumber
FROM #TimingTest tt
CROSS JOIN (
SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
) results
WHERE tt.MethodName = @MethodName
and tt.TestIteration = @TestIteration
END
-- Calculate the timespan for each of the runs
UPDATE tt
SET
ElapsedTime = DATEDIFF(MICROSECOND, StartDate, EndDate)
FROM #TimingTest tt
--
-- Report the results ...
--
SELECT
MethodName, AVG(ElapsedTime) / AVG(ItemCount) as TimePerRecord, CAST(AVG(ItemCount) as bigint) as SequenceLength,
MAX(ElapsedTime) as MaxTime, MIN(ElapsedTime) as MinTime,
MAX(MaxNumber) as MaxNumber, MIN(MinNumber) as MinNumber
FROM #TimingTest tt
GROUP by tt.MethodName
ORDER BY TimePerRecord ASC, MaxTime ASC, MinTime ASC
You need to copy the dependency you need for project.
Having these in hand please clear all the <dependency>
tag embedded into <dependencies>
tag
from POM.XML file in your project.
After saving the file you will not see Maven Dependencies in your Libraries
.
Then please paste those <dependency>
you have copied earlier.
The required jars will be automatically downloaded by Maven, you can see that too in
the generated Maven Dependencies Libraries
after saving the file.
Thanks.
Whatever goes to softmax
is logit, this is what J. Hinton repeats in coursera videos all the time.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
The enctype attribute can be used only if method="post".
No characters are encoded. This value is required when you are using forms that have a file upload control
From W3Schools
Though this is an old question, I thought I'd post my answer anyway, if that helps someone in future
JArray array = JArray.Parse(jsonString);
foreach (JObject obj in array.Children<JObject>())
{
foreach (JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
//Do something with name and value
//System.Windows.MessageBox.Show("name is "+name+" and value is "+value);
}
}
This solution uses Newtonsoft library, don't forget to include using Newtonsoft.Json.Linq;
Calling the destructor manually is required if the object was constructed using an overloaded form of operator new()
, except when using the "std::nothrow
" overloads:
T* t0 = new(std::nothrow) T();
delete t0; // OK: std::nothrow overload
void* buffer = malloc(sizeof(T));
T* t1 = new(buffer) T();
t1->~T(); // required: delete t1 would be wrong
free(buffer);
Outside managing memory on a rather low level as above calling destructors explicitly, however, is a sign of bad design. Probably, it is actually not just bad design but outright wrong (yes, using an explicit destructor followed by a copy constructor call in the assignment operator is a bad design and likely to be wrong).
With C++ 2011 there is another reason to use explicit destructor calls: When using generalized unions, it is necessary to explicitly destroy the current object and create a new object using placement new when changing the type of the represented object. Also, when the union is destroyed, it is necessary to explicitly call the destructor of the current object if it requires destruction.
You can also use ng-template, I think that would be more efficient while run time :)
<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
<div>2</div>
</ng-template>
Cheers
If you want your result concatenated, as you show in your question, you could try something like:
>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world"))
'10410110810811132119111114108100'
I got the same error when issuing a URL without the protocol (like localhost:4200
) instead of a correct one also specifying the protocol (e.g. http://localhost:4200).
Google Chrome works fine without the protocol (it takes http as the default), but Firefox crashes with this error.
In the interest of completeness, it should be pointed out that there are representations of strings on various platforms in which the number of bytes per character varies depending on the character. Old-school programmers would refer to this as DBCS (Double Byte Character Set). Modern programmers more commonly encounter this in UTF-8 (as well as UTF-16 and others). There are other such encodings as well.
In any of these variable-width encoding schemes, the simple algorithms posted here (evil, non-evil or otherwise) would not work correctly at all! In fact, they could even cause the string to become illegible or even an illegal string in that encoding scheme. See Juan Pablo Califano's answer for some good examples.
std::reverse() potentially would still work in this case, as long as your platform's implementation of the Standard C++ Library (in particular, string iterators) properly took this into account.
I had the same problem. I was running CentOS 8 with SELinux enforcing, and I was getting the error mentioned in the question (mysqli_real_connect(): (HY000/2002): No such file or directory
) despite having all the configurations fixed correctly. I later got out of trouble after allowing MySQL connections through SELinux.
Check SELinux status using this command:
sestatus
Allow Apache to connect database through SELinux
setsebool httpd_can_network_connect_db 1
Use -P
option makes the change permanent. Without this option, the boolean would be reset to 0 at reboot.
setsebool -P httpd_can_network_connect_db 1
I've tried this in Python 3.6.9
>>> hours, minutes, seconds = 9, 33, 35
>>> time = f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
>>> print (time)
09:33:35 am
>>> type(time)
<class 'str'>
This is a solution/hack I'm using:
tasks/main.yml:
- name: parametrized template - a
template:
src: test.j2
dest: /tmp/templateA
with_items: var_a
- name: parametrized template - b
template:
src: test.j2
dest: /tmp/templateB
with_items: var_b
vars/main.yml
var_a:
- 'this is var_a'
var_b:
- 'this is var_b'
templates/test.j2:
{{ item }}
After running this, you get this is var_a
in /tmp/templateA and this is var_b
in /tmp/templateB.
Basically you abuse with_items
to render the template with each item in the one-item list. This works because you can control what the list is when using with_items
.
The downside of this is that you have to use item
as the variable name in you template.
If you want to pass more than one variable this way, you can dicts as your list items like this:
var_a:
-
var_1: 'this is var_a1'
var_2: 'this is var_a2'
var_b:
-
var_1: 'this is var_b1'
var_2: 'this is var_b2'
and then refer to them in your template like this:
{{ item.var_1 }}
{{ item.var_2 }}
I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.
Guide link below:
https://docs.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN
Seems there is another format now
where: {
LastName: "Doe",
$or: [
{
FirstName:
{
$eq: "John"
}
},
{
FirstName:
{
$eq: "Jane"
}
},
{
Age:
{
$gt: 18
}
}
]
}
Will generate
WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)
See the doc: http://docs.sequelizejs.com/en/latest/docs/querying/#where
You can also use SUM + IF
which is shorter than SUM + CASE
:
SELECT
count(id)
, SUM(IF(kind=1, 1, 0)) AS countKindOne
, SUM(CASE WHEN kind=2 THEN 1 ELSE 0 END) AS countKindTwo
If you just need an int to a string as you suggest, I've found the easiest way is to do as below:
[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]
If you're rolling your own modules specific to your application, you can either:
Keep those (and only those) in your application's /node_modules
folder and move out all the other dependencies to parent ../node_modules
folder. This will work because of how NodeJS CommonJS modules system works by moving up to the parent directory, and so on, until the root of the tree is reached. See: https://nodejs.org/api/modules.html
Or gitignore all /node_modules/*
except your /node_modules/your-modules
. See: Make .gitignore ignore everything except a few files
This use case is pretty awesome. It lets you keep modules you created specifically for your application nicely with it and doesn't clutter with dependencies which can be installed later.
If you are using Express as back-end you just have to install cors and import and use it in app.use(cors());. If it is not resolved then try switching ports. It will surely resolve after switching ports
If you like to call an activity method from within a custom layout class(non-Activity Class).You should create a delegate using interface.
It is untested and i coded it right . but i am conveying a way to achieve what you want.
First of all create and Interface
interface TaskCompleteListener<T> {
public void onProfileClicked(T result);
}
public class ProfileView extends LinearLayout
{
private TaskCompleteListener<String> callback;
TextView profileTitleTextView;
ImageView profileScreenImageButton;
boolean isEmpty;
ProfileData data;
String name;
public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
{
super(context, attrs);
......
......
}
public setCallBack( TaskCompleteListener<String> cb)
{
this.callback = cb;
}
//Heres where things get complicated
public void onClick(View v)
{
callback.onProfileClicked("Pass your result or any type");
}
}
And implement this to any Activity.
and call it like
ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
pv.setCallBack(new TaskCompleteListener
{
public void onProfileClicked(String resultStringFromProfileView){}
});
Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.
To remove a property from an object in JavaScript you use the delete
operator:
const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false
Note that when delete
is applied to an index property of an Array
, you will create a sparsely populated array (ie. an array with a missing index).
When working with instances of Array
, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice
or Array#pop
.
Note that the delete
operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o
, then o
will subsequently be garbage collected in the normal way.
Using the delete
operator can affect JavaScript engines' ability to optimise code.
this worked fine for me:
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.ReadOnlyField(source='category.name')
class Meta:
model = Item
fields = "__all__"
There are two Things you can do
use
int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();
or
int noOfColumns = sh.getRow(0).getLastCellNum();
There is a fine difference between them
Updated for Numpy 1.7.0:(Hat-tip to @Rolf Bartstra.)
a=np.empty(n); a.fill(5)
is fastest.
In descending speed order:
%timeit a=np.empty(1e4); a.fill(5)
100000 loops, best of 3: 5.85 us per loop
%timeit a=np.empty(1e4); a[:]=5
100000 loops, best of 3: 7.15 us per loop
%timeit a=np.ones(1e4)*5
10000 loops, best of 3: 22.9 us per loop
%timeit a=np.repeat(5,(1e4))
10000 loops, best of 3: 81.7 us per loop
%timeit a=np.tile(5,[1e4])
10000 loops, best of 3: 82.9 us per loop
Okay, this question was a year ago but I recently got this problem as well.
So what I did :
When I did the first two steps it still doesn't remove the error so the last step is important. It didn't automatically change the build path for jre.
you may use like that
System.out.println(Integer.decode("0x4d2")) // output 1234
//and vice versa
System.out.println(Integer.toHexString(1234); // output is 4d2);
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
In Python 3.6
a, b=1, 2
print ("Value of variable a is: ", a, "and Value of variable b is :", b)
print(f"Value of a is: {a}")
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context
We can use the formula method of aggregate
. The variables on the 'rhs' of ~
are the grouping variables while the .
represents all other variables in the 'df1' (from the example, we assume that we need the mean
for all the columns except the grouping), specify the dataset and the function (mean
).
aggregate(.~id1+id2, df1, mean)
Or we can use summarise_each
from dplyr
after grouping (group_by
)
library(dplyr)
df1 %>%
group_by(id1, id2) %>%
summarise_each(funs(mean))
Or using summarise
with across
(dplyr
devel version - ‘0.8.99.9000’
)
df1 %>%
group_by(id1, id2) %>%
summarise(across(starts_with('val'), mean))
Or another option is data.table
. We convert the 'data.frame' to 'data.table' (setDT(df1)
, grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD
) and get the mean
.
library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)]
df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b",
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"),
val1 = c(1L,
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L,
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))
I had to use:
table, tbody {
width: 100%;
}
The table
alone wasn't enough, the tbody
was also needed for it to work for me.
You don't need to install sqlite3
module. It is included in the standard library (since Python 2.5).
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
Using the -n /usr/local/bin flag does work, BUT I had to come back to this page every time I wanted to update a package again. So I figured out a permanent fix for this.
For those interested in fixing this permanently:
Create a ~/.gemrc file
vim .gemrc
With the following content:
:gemdir:
- ~/.gem/ruby
install: -n /usr/local/bin
Now you can run your command normally without the -n flag.
Enjoy!
If you can change the order of the elements, floating will work.
section {_x000D_
position: relative;_x000D_
width: 50%;_x000D_
border: 1px solid;_x000D_
}_x000D_
h1 {_x000D_
display: inline;_x000D_
}_x000D_
div {_x000D_
float: right;_x000D_
}
_x000D_
<section>_x000D_
<div>_x000D_
<button>button</button>_x000D_
</div>_x000D_
_x000D_
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>_x000D_
</section>
_x000D_
?By placing the div
before the h1
and floating it to the right
, you get the desired effect.
for an array of objects, I used something like this, while following the custom method for php < 5.4:
$jsArray=array();
//transaction is an array of the class transaction
//which implements the method to_json
foreach($transactions as $tran)
{
$jsArray[]=$tran->to_json();
}
echo json_encode($jsArray);
It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:
http://www.microsoft.com/sqlserver/en/us/editions/express.aspx
and the one for 64 bit WITH the management tools (management studio) is here:
http://www.microsoft.com/sqlserver/en/us/editions/express.aspx
From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.
The only way is to modify the file src/http/ngx_http_header_filter_module.c . I changed nginx on line 48 to a different string.
What you can do in the nginx config file is to set server_tokens to off. This will prevent nginx from printing the version number.
To check things out, try curl -I http://vurbu.com/ | grep Server
It should return
Server: Hai
This is normal if you are using async/await functionalities in your application.
I'd go for:
conds = iter([a, b, c])
if any(conds) and not any(conds):
# okay...
I think this should short-circuit fairly efficiently
Explanation
By making conds
an iterator, the first use of any
will short circuit and leave the iterator pointing to the next element if any item is true; otherwise, it will consume the entire list and be False
. The next any
takes the remaining items in the iterable, and makes sure than there aren't any other true values... If there are, the whole statement can't be true, thus there isn't one unique element (so short circuits again). The last any
will either return False
or will exhaust the iterable and be True
.
note: the above checks if only a single condition is set
If you want to check if one or more items, but not every item is set, then you can use:
not all(conds) and any(conds)
You can also use a visual diff.
For example, if you are using Sourcetree, you can simply select any two commits in log view.
(I personally prefer using a GUI in most cases for this, and I'm posting this for those who may not be familiar with GUI options.)
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
When it comes to applications that run on a server, including web sites and other back-end services, the time zone setting of the server should be ignored by the application.
The common advice is to set the server's time zone to UTC. This is indeed a good best practice, but it's there as a band-aid for applications that do not follow other best practices. For example, a service might be writing to log files with local timestamps instead of UTC-based timestamps, thus creating ambiguities during the daylight saving time fall-back transition. Setting the server's time zone to UTC will fix that application. However the real fix would be for the application to log using UTC to begin with.
Server-side code, including web sites, should never expect the local time zone of the server to be anything in particular.
In some languages, the local time zone can easily creep in to application code. For example, the DateTime.ToUniversalTime
method in .NET will convert from the local time zone to UTC, and the DateTime.Now
property returns the current time in the local time zone. Also, the Date
constructor in JavaScript uses the computer's local time zone. There are many other examples like this. It is important to practice defensive programming, avoiding any code that uses the computer's local time zone setting.
Reserve using the local time zone for client-side code, such as desktop applications, mobile applications, and client-side JavaScript.
Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.
http://iphone.trac.wordpress.org/browser/trunk
The files you want are:
Then to show it use something like:
[[WPActivityIndicator sharedActivityIndicator] show];
And hide with:
[[WPActivityIndicator sharedActivityIndicator] hide];
I tried all of the above which did not work for me. I ended up just going with PUT (inspiration found here) and just changed my server side logic to perform a delete on this url call. (django rest framework function override).
e.g.
.put(`http://127.0.0.1:8006/api/updatetoken/20`, bayst)
.then((response) => response.data)
.catch((error) => { throw error.response.data; });
see to it that the argument of Class. forName method is exactly "com. mysql. jdbc. Driver". If yes then see to it that mysql connector is present in lib folder of the project. if yes then see to it that the same mysql connector . jar file is in the ClassPath variable (system variable)..
Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile
type qualifier.
// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];
The volatile
type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile
is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.
This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma
or __attribute__
syntax.
Ultimately no. You can query for listings with a search string from an RSS feed such as this:
http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString
As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.
Craigslist Automated Posting API?
Write a note to craigslist asking them to open their API,
If you are using SQLAlchemy's ORM rather than the expression language, you might find yourself wanting to convert an object of type sqlalchemy.orm.query.Query
to a Pandas data frame.
The cleanest approach is to get the generated SQL from the query's statement attribute, and then execute it with pandas's read_sql()
method. E.g., starting with a Query object called query
:
df = pd.read_sql(query.statement, query.session.bind)
I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface)
class Foo(WebService):
@webmethod
def bar(self, arg1, arg2):
...
then I can define
def webmethod(func):
func.is_webmethod = True
return func
Then, when a webservice call arrives, I look up the method, check whether the underlying function has the is_webmethod attribute (the actual value is irrelevant), and refuse the service if the method is absent or not meant to be called over the web.
I currently use this simple synchronous method which requires no extra files in your projects or delegates.
Import:
#import <SystemConfiguration/SCNetworkReachability.h>
Create this method:
+(bool)isNetworkAvailable
{
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef address;
address = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com" );
Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
CFRelease(address);
bool canReach = success
&& !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
&& (flags & kSCNetworkReachabilityFlagsReachable);
return canReach;
}
Then, if you've put this in a MyNetworkClass
:
if( [MyNetworkClass isNetworkAvailable] )
{
// do something networky.
}
If you are testing in the simulator, turn your Mac's wifi on and off, as it appears the simulator will ignore the phone setting.
Update:
In the end I used a thread/asynchronous callback to avoid blocking the main thread; and regularly re-testing so I could use a cached result - although you should avoid keeping data connections open unnecessarily.
As @thunk described, there are better URLs to use, which Apple themselves use. http://cadinc.com/blog/why-your-apple-ios-7-device-wont-connect-to-the-wifi-network
I was trying to work with that solutions but it doesn't work. But later I was realize that the function it wasn't declared so I watch in to the dropzone.com page and take the example to call events. So finally work on my site. For those like me who don't understand JavaScript very well, I leave you the example.
<script type="text/javascript" src="/js/dropzone.js"></script>
<script type="text/javascript">
// This example uses jQuery so it creates the Dropzone, only when the DOM has
// loaded.
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
// or disable for specific dropzone:
// Dropzone.options.myDropzone = false;
$(function() {
// Now that the DOM is fully loaded, create the dropzone, and setup the
// event listeners
var myDropzone = new Dropzone(".dropzone");
myDropzone.on("queuecomplete", function(file, res) {
if (myDropzone.files[0].status != Dropzone.SUCCESS ) {
alert('yea baby');
} else {
alert('cry baby');
}
});
});
</script>
SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.
As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.
Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.
As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).
Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.
The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.
Currently Swift does not support any built in mechanism for observing property changes of objects other than 'self', so no, it does not support KVO.
However, KVO is such a fundamental part of Objective-C and Cocoa that it seems quite likely that it will be added in the future. The current documentation seems to imply this:
Key-Value Observing
Information forthcoming.
In my case I was using jackson-databind-2.8.8.jar
that is not compatible with JDK 1.6
I need to use so Spring wasn't loading this converter. I downgraded the version and it works now.
You should create a method within your fragment that accepts the type of object you wish to pass into it. In this case i named it "setObject" (creative huh? :) ) That method can then perform whatever action you need with that object.
MyFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
fragment = new MyFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, detailsFragment)
.commit();
} else {
fragment = (MyFragment) getSupportFragmentManager().findFragmentById(
android.R.id.content);
}
fragment.setObject(yourObject); //create a method like this in your class "MyFragment"
}
Note that i'm using the support library and calls to getSupportFragmentManager() might be just getFragmentManager() for you depending on what you're working with
I seem to be able to get along with simply:
$gpg <path_to_file>
Which outputs like this:
$ gpg /tmp/keys/something.asc
pub 1024D/560C6C26 2014-11-26 Something <[email protected]>
sub 2048g/0C1ACCA6 2014-11-26
The op didn't specify in particular what key info is relevant. This output is all I care about.
In Oracle, there is two views that describe columns:
DBA_TAB_COLUMNS describes the columns of all tables, views, and clusters in the database.
USER_TAB_COLUMNS describes the columns of the tables, views, and
clusters owned by the current user. This view does not display the
OWNER column.
I think you should use some 3d party server to support the JWT token and there is no out of the box JWT support in WEB API 2.
However there is an OWIN project for supporting some format of signed token (not JWT). It works as a reduced OAuth protocol to provide just a simple form of authentication for a web site.
You can read more about it e.g. here.
It's rather long, but most parts are details with controllers and ASP.NET Identity that you might not need at all. Most important are
Step 9: Add support for OAuth Bearer Tokens Generation
Step 12: Testing the Back-end API
There you can read how to set up endpoint (e.g. "/token") that you can access from frontend (and details on the format of the request).
Other steps provide details on how to connect that endpoint to the database, etc. and you can chose the parts that you require.
node does something like this:
module.exports = exports = {}
module.exports and exports refer to same object.
This is done just for convenience. so instead of writing something like this
module.exports.PI = 3.14
we can write
exports.PI = 3.14
so it is ok to add a property to exports but assigning it to a different object is not ok
exports.add = function(){
.
.
}
? this is OK and same as module.exports.add = function(){...}
exports = function(){
.
.
}
? this is not ok and and empty object will be returned as module.exports still refers to {} and exports refer to different object.
This works for me!
$('#<%= ddlstuff.ClientID %>').change(function () {
alert('Change Happened');
$('#<%= txtBoxToClear.ClientID %>').val('');
});
I was using node v12.13.1, so I've downgraded to v10.19.0 and works fine after that.
Either encode the needed XML entities or use CDATA.
<arg0>
<!--Optional:-->
<parameter1><test>like this</test></parameter1>
<!--Optional:-->
<parameter2><![CDATA[<test>or like this</test>]]></parameter2>
</arg0>
Answer has been moved here - https://stackoverflow.com/a/26944636/2377343
I resolved by doing the following: Check if there is a module called rewrite.load in your apache at:
cd /etc/apache2/mods-enabled/
If it does not exist execute the following excerpt:
sudo a2enmod rewrite
Otherwise, change the Apache configuration file to consolidate use of the "friendly URL".
sudo nano /etc/apache2/apache2.conf
Find the following code inside the editor:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
Change to:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
After that restart the Apache server via:
sudo /etc/init.d/apache2 restart
Edit : for an in-depth understanding of the mental model of decorators, take a look at this awesome Pycon Talk. well worth the 30 minutes.
One way of thinking about decorators with arguments is
@decorator
def foo(*args, **kwargs):
pass
translates to
foo = decorator(foo)
So if the decorator had arguments,
@decorator_with_args(arg)
def foo(*args, **kwargs):
pass
translates to
foo = decorator_with_args(arg)(foo)
decorator_with_args
is a function which accepts a custom argument and which returns the actual decorator (that will be applied to the decorated function).
I use a simple trick with partials to make my decorators easy
from functools import partial
def _pseudo_decor(fun, argument):
def ret_fun(*args, **kwargs):
#do stuff here, for eg.
print ("decorator arg is %s" % str(argument))
return fun(*args, **kwargs)
return ret_fun
real_decorator = partial(_pseudo_decor, argument=arg)
@real_decorator
def foo(*args, **kwargs):
pass
Update:
Above, foo
becomes real_decorator(foo)
One effect of decorating a function is that the name foo
is overridden upon decorator declaration. foo
is "overridden" by whatever is returned by real_decorator
. In this case, a new function object.
All of foo
's metadata is overridden, notably docstring and function name.
>>> print(foo)
<function _pseudo_decor.<locals>.ret_fun at 0x10666a2f0>
functools.wraps gives us a convenient method to "lift" the docstring and name to the returned function.
from functools import partial, wraps
def _pseudo_decor(fun, argument):
# magic sauce to lift the name and doc of the function
@wraps(fun)
def ret_fun(*args, **kwargs):
# pre function execution stuff here, for eg.
print("decorator argument is %s" % str(argument))
returned_value = fun(*args, **kwargs)
# post execution stuff here, for eg.
print("returned value is %s" % returned_value)
return returned_value
return ret_fun
real_decorator1 = partial(_pseudo_decor, argument="some_arg")
real_decorator2 = partial(_pseudo_decor, argument="some_other_arg")
@real_decorator1
def bar(*args, **kwargs):
pass
>>> print(bar)
<function __main__.bar(*args, **kwargs)>
>>> bar(1,2,3, k="v", x="z")
decorator argument is some_arg
returned value is None
You don't have to specify ':3306' after the IP, it's the default port for MySQL.
And if your MySQL server runs with another port than 3306, then you have to add '-P [port]' instead of adding it to the IP address.
The MySQL client won't recognize the syntax "host:port", you HAVE to use -P [port] instead.
And btw, if you use '-p password', it won't work and will ask you the password again. You have to stick the password to the -p : -ppassword. (still, it's a very bad habit, because anyone that could do a PS on your server could see the plain password...)
when I started xampp on my windows 10 there were many options available, unfortunately every one of them failed. I ll list them so that you don't go through all of them again.
1) i installed xampp initially in a different drive and not c because of UAC issues so i uninstalled Xampp and installed it again in c (didn't work) 2) while reinstalling i deactivated the antivirus as setup said that some installing might not end up properly(realized it doesn't matter :) lmao) 3) i tried to change ports several times of xampp from 80 to some different number like 8080 etc. still nothing happened 4) i then tried using firefox as it is believed that internet explorer or internet edge is not a good browser for xampp 5) after that i went to config file i.e config.inc inside phpmyadmin folder and did some crap as were given in the instructions. Failure it was 6) then i closed laptop and went to sleep(XD srry leave this point) 7) then i tried searching for windows web services in the services.msc to disable it. i couldn't find it
On eighth time i got success.This is what i did 8)In control panel, where you have actions , modules PIDs, Ports you will see Services under which you will see gray boxes which are actually checkboxes but are empty initially. i checked it so that xampp services start and apache services start. now you will see them ticked. After that just change the port of xampp and apache to 80.
I hope it helps. cheers ;)
a = (b = 'string is truthy'); // b gets string; a gets b, which is a primitive (copy)
a = (b = { c: 'yes' }); // they point to the same object; a === b (not a copy)
(a && b)
is logically (a ? b : a)
and behaves like multiplication (eg. !!a * !!b
)
(a || b)
is logically (a ? a : b)
and behaves like addition (eg. !!a + !!b
)
(a = 0, b)
is short for not caring if a
is truthy, implicitly return b
a = (b = 0) && "nope, but a is 0 and b is 0"; // b is falsey + order of operations
a = (b = "b is this string") && "a gets this string"; // b is truthy + order of ops
JavaScript Operator Precedence (Order of Operations)
Note that the comma operator is actually the least privileged operator, but parenthesis are the most privileged, and they go hand-in-hand when constructing one-line expressions.
Eventually, you may need 'thunks' rather than hardcoded values, and to me, a thunk is both the function and the resultant value (the same 'thing').
const windowInnerHeight = () => 0.8 * window.innerHeight; // a thunk
windowInnerHeight(); // a thunk
Why didn't someone tell me I was being a total noob? All I had to do was copy the dateutil
directory to someplace in my Python path, and it was good to go.
If you don't want to disable this exception, all you need to do is to let your application pump some messages at least once every 60 seconds. It will prevent this exception to happen. Try calling System.Threading.Thread.CurrentThread.Join(10) once in a while. There are other calls you can do that let the messages pump.
React Native's layout has the display
property support, similar to CSS.
Possible values: none
and flex
(default).
https://facebook.github.io/react-native/docs/layout-props#display
<View style={{display: 'none'}}> </View>
Using LIKE:
SELECT *
FROM TABLE
WHERE column LIKE '%cats%' --case-insensitive
You can use jasper report.
iReport is a very effective tool to develop jasper reports.
It supports almost all the facilities provided by crystal report like formatting, grouping, creation of charts etc.
Refer the link for tutorial:
I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.
let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size
Try
=IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))
Now incorporate your left
argument
=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))
Also note your usage of left, your argument doesn't specify the number of characters, but a set.
7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet
, but I rather link to official sources.
Hope to add more value by providing the normal formatter including the year, month and day with the time. You can use this formatter for more than just a year
[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
hdfs dfs -rm -r /path/to/directory
You can use the instanceof
operator:
if (obj instanceof jQuery){
console.log('object is jQuery');
}
Explanation: the jQuery
function (aka $
) is implemented as a constructor function. Constructor functions are to be called with the new
prefix.
When you call $(foo)
, internally jQuery translates this to new jQuery(foo)
1. JavaScript proceeds to initialize this
inside the constructor function to point to a new instance of jQuery
, setting it's properties to those found on jQuery.prototype
(aka jQuery.fn
). Thus, you get a new
object where instanceof jQuery
is true
.
1It's actually new jQuery.prototype.init(foo)
: the constructor logic has been offloaded to another constructor function called init
, but the concept is the same.
I realize that this is an old question, with an established answer. The reason I'm posting is that is the accepted answer has many elements of k-NN (k-nearest neighbors), a different algorithm.
Both k-NN and NaiveBayes are classification algorithms. Conceptually, k-NN uses the idea of "nearness" to classify new entities. In k-NN 'nearness' is modeled with ideas such as Euclidean Distance or Cosine Distance. By contrast, in NaiveBayes, the concept of 'probability' is used to classify new entities.
Since the question is about Naive Bayes, here's how I'd describe the ideas and steps to someone. I'll try to do it with as few equations and in plain English as much as possible.
Before someone can understand and appreciate the nuances of Naive Bayes', they need to know a couple of related concepts first, namely, the idea of Conditional Probability, and Bayes' Rule. (If you are familiar with these concepts, skip to the section titled Getting to Naive Bayes')
Conditional Probability in plain English: What is the probability that something will happen, given that something else has already happened.
Let's say that there is some Outcome O. And some Evidence E. From the way these probabilities are defined: The Probability of having both the Outcome O and Evidence E is: (Probability of O occurring) multiplied by the (Prob of E given that O happened)
One Example to understand Conditional Probability:
Let say we have a collection of US Senators. Senators could be Democrats or Republicans. They are also either male or female.
If we select one senator completely randomly, what is the probability that this person is a female Democrat? Conditional Probability can help us answer that.
Probability of (Democrat and Female Senator)= Prob(Senator is Democrat) multiplied by Conditional Probability of Being Female given that they are a Democrat.
P(Democrat & Female) = P(Democrat) * P(Female | Democrat)
We could compute the exact same thing, the reverse way:
P(Democrat & Female) = P(Female) * P(Democrat | Female)
Conceptually, this is a way to go from P(Evidence| Known Outcome) to P(Outcome|Known Evidence). Often, we know how frequently some particular evidence is observed, given a known outcome. We have to use this known fact to compute the reverse, to compute the chance of that outcome happening, given the evidence.
P(Outcome given that we know some Evidence) = P(Evidence given that we know the Outcome) times Prob(Outcome), scaled by the P(Evidence)
The classic example to understand Bayes' Rule:
Probability of Disease D given Test-positive =
P(Test is positive|Disease) * P(Disease)
_______________________________________________________________
(scaled by) P(Testing Positive, with or without the disease)
Now, all this was just preamble, to get to Naive Bayes.
So far, we have talked only about one piece of evidence. In reality, we have to predict an outcome given multiple evidence. In that case, the math gets very complicated. To get around that complication, one approach is to 'uncouple' multiple pieces of evidence, and to treat each of piece of evidence as independent. This approach is why this is called naive Bayes.
P(Outcome|Multiple Evidence) =
P(Evidence1|Outcome) * P(Evidence2|outcome) * ... * P(EvidenceN|outcome) * P(Outcome)
scaled by P(Multiple Evidence)
Many people choose to remember this as:
P(Likelihood of Evidence) * Prior prob of outcome
P(outcome|evidence) = _________________________________________________
P(Evidence)
Notice a few things about this equation:
base rates
and they are a way to scale our predicted probabilities.Just run the formula above for each possible outcome. Since we are trying to classify, each outcome is called a class
and it has a class label.
Our job is to look at the evidence, to consider how likely it is to be this class or that class, and assign a label to each entity.
Again, we take a very simple approach: The class that has the highest probability is declared the "winner" and that class label gets assigned to that combination of evidences.
Let's try it out on an example to increase our understanding: The OP asked for a 'fruit' identification example.
Let's say that we have data on 1000 pieces of fruit. They happen to be Banana, Orange or some Other Fruit. We know 3 characteristics about each fruit:
This is our 'training set.' We will use this to predict the type of any new fruit we encounter.
Type Long | Not Long || Sweet | Not Sweet || Yellow |Not Yellow|Total
___________________________________________________________________
Banana | 400 | 100 || 350 | 150 || 450 | 50 | 500
Orange | 0 | 300 || 150 | 150 || 300 | 0 | 300
Other Fruit | 100 | 100 || 150 | 50 || 50 | 150 | 200
____________________________________________________________________
Total | 500 | 500 || 650 | 350 || 800 | 200 | 1000
___________________________________________________________________
We can pre-compute a lot of things about our fruit collection.
The so-called "Prior" probabilities. (If we didn't know any of the fruit attributes, this would be our guess.) These are our base rates.
P(Banana) = 0.5 (500/1000)
P(Orange) = 0.3
P(Other Fruit) = 0.2
Probability of "Evidence"
p(Long) = 0.5
P(Sweet) = 0.65
P(Yellow) = 0.8
Probability of "Likelihood"
P(Long|Banana) = 0.8
P(Long|Orange) = 0 [Oranges are never long in all the fruit we have seen.]
....
P(Yellow|Other Fruit) = 50/200 = 0.25
P(Not Yellow|Other Fruit) = 0.75
Let's say that we are given the properties of an unknown fruit, and asked to classify it. We are told that the fruit is Long, Sweet and Yellow. Is it a Banana? Is it an Orange? Or Is it some Other Fruit?
We can simply run the numbers for each of the 3 outcomes, one by one. Then we choose the highest probability and 'classify' our unknown fruit as belonging to the class that had the highest probability based on our prior evidence (our 1000 fruit training set):
P(Banana|Long, Sweet and Yellow)
P(Long|Banana) * P(Sweet|Banana) * P(Yellow|Banana) * P(banana)
= _______________________________________________________________
P(Long) * P(Sweet) * P(Yellow)
= 0.8 * 0.7 * 0.9 * 0.5 / P(evidence)
= 0.252 / P(evidence)
P(Orange|Long, Sweet and Yellow) = 0
P(Other Fruit|Long, Sweet and Yellow)
P(Long|Other fruit) * P(Sweet|Other fruit) * P(Yellow|Other fruit) * P(Other Fruit)
= ____________________________________________________________________________________
P(evidence)
= (100/200 * 150/200 * 50/200 * 200/1000) / P(evidence)
= 0.01875 / P(evidence)
By an overwhelming margin (0.252 >> 0.01875
), we classify this Sweet/Long/Yellow fruit as likely to be a Banana.
Look at what it eventually comes down to. Just some counting and multiplication. We can pre-compute all these terms, and so classifying becomes easy, quick and efficient.
Let z = 1 / P(evidence).
Now we quickly compute the following three quantities.
P(Banana|evidence) = z * Prob(Banana) * Prob(Evidence1|Banana) * Prob(Evidence2|Banana) ...
P(Orange|Evidence) = z * Prob(Orange) * Prob(Evidence1|Orange) * Prob(Evidence2|Orange) ...
P(Other|Evidence) = z * Prob(Other) * Prob(Evidence1|Other) * Prob(Evidence2|Other) ...
Assign the class label of whichever is the highest number, and you are done.
Despite the name, Naive Bayes turns out to be excellent in certain applications. Text classification is one area where it really shines.
Hope that helps in understanding the concepts behind the Naive Bayes algorithm.
Old question but still relevant.
I recommend using negative text-indent
.
list-style-position
must be outside
.
Pros:
Cons:
Docs: https://www.timkay.com/solo/
solo is a very simple script (10 lines) that prevents a program from running more than one copy at a time. It is useful with cron to make sure that a job doesn't run before a previous one has finished.
Example
* * * * * solo -port=3801 ./job.pl blah blah
I was looking for a listing of macOS but found nothing, maybe this helps someone.
Output on macOS Catalina (10.15.7) using net5.0
# SpecialFolders (Only with value)
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.System: /System
SpecialFolder.UserProfile: /Users/$USER
# SpecialFolders (All)
SpecialFolder.AdminTools:
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CDBurning:
SpecialFolder.CommonAdminTools:
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.CommonDesktopDirectory:
SpecialFolder.CommonDocuments:
SpecialFolder.CommonMusic:
SpecialFolder.CommonOemLinks:
SpecialFolder.CommonPictures:
SpecialFolder.CommonProgramFiles:
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonPrograms:
SpecialFolder.CommonStartMenu:
SpecialFolder.CommonStartup:
SpecialFolder.CommonTemplates:
SpecialFolder.CommonVideos:
SpecialFolder.Cookies:
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.History:
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.LocalizedResources:
SpecialFolder.MyComputer:
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.MyVideos:
SpecialFolder.NetworkShortcuts:
SpecialFolder.PrinterShortcuts:
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.ProgramFilesX86:
SpecialFolder.Programs:
SpecialFolder.Recent:
SpecialFolder.Resources:
SpecialFolder.SendTo:
SpecialFolder.StartMenu:
SpecialFolder.Startup:
SpecialFolder.System: /System
SpecialFolder.SystemX86:
SpecialFolder.Templates:
SpecialFolder.UserProfile: /Users/$USER
SpecialFolder.Windows:
I have replaced my username with $USER.
Code Snippet from pogosama.
foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
string commonAppData = Environment.GetFolderPath(f);
Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();
If you know what will be in the view, you can also set the default value from Controller as well rather then set up it into the view/cshtml file. No need to set default value from HTML side.
In the Controller file.
commission.TypeofCommission = 1;
return View(commission);
In the .cshtml file.
@Html.DropDownListFor(row => row.TypeofCommission, new SelectList(Model.commissionTypeModelList, "type", "typeName"), "--Select--")
I was getting this same error installing PHP 7 on Windows Server 2008 R2. I resolved this by installing the Visual C++ Redistributable for Visual Studio 2015.
try
.insertAfter()
here
$(content).insertAfter('#bla');
The key is to use background-color: inherit;
on the pseudo element.
See: http://jsfiddle.net/EdUmc/
A simple way is to use python. in python terminal type
r"C:\Users\surfcat\Desktop\2006_dissimilarity.csv" and you'll get back 'C:\Users\surfcat\Desktop\2006_dissimilarity.csv'
My problem was that I could no longer run an emulator that had worked because I had quit the emulator application but the process wasn't fully ended, so I was trying to launch another emulator while the previous one was still running. On a mac, I had to use the Activity Monitor to see the other process and kill it. Steps:
Just iterate the old-fashion way, because you need explicit index handling:
List myList = ...
...
int length = myList.size();
for(int i = 0; i < length; i++) {
String s = myList.get(i);
// add items here, if you want to
}
It seems that this is the correct way window.location.assign("http://www.mozilla.org");
Another graphical alternative - plot_missing
function from excellent DataExplorer
package:
Docs also points out to the fact that you can save this results for additional analysis with missing_data <- plot_missing(data)
.
Searching
AttributeError: 'module' object has no attribute 'BinaryField'
landed me here.
The above answers did not solve the problem, so I'm posting my answer.
BinaryField
was added since Django 1.6. If you have an older version, it will give you the above error.
You may want to check the spelling of the attribute first, as suggested in the above answers, and then check to make sure the module in the Django version indeed has the attribute.
For those still having issues with Renderscript support library on x86 chipsets, please have a look at this post by the creator of the library. It looks like the fix he prepared didn't make it somehow to the Build Tools v20.0.0, so he provides the files to fix it manually and a brief explanation of how to do it.
You can set environment variables as mentioned in the other answers (like here)
or
you can open Start > CMD as administrator and write
C:\xampp\php phpfile.php
Run the following immediately after the dialog is called in the Ajax:
$(".ui-dialog-titlebar").hide();
$(".ui-dialog").addClass("customclass");
This applies just to the dialog that is opened, so it can be changed for each one used.
(This quick answer is based on another response on Stack Overflow.)
Can be done without the constants (like 3600000 ms is 1h)
public static Date addMinutesToDate(Date date, int minutes) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, minutes);
return calendar.getTime();
}
public static Date addHoursToDate(Date date, int hours) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hours);
return calendar.getTime();
}
example of usage:
System.out.println(new Date());
System.out.println(addMinutesToDate(new Date(), 5));
Tue May 26 16:16:14 CEST 2020
Tue May 26 16:21:14 CEST 2020
By looping it can be done the following way :)
num1= int(input('Enter the number'))
sum1 = num1 #making a alt int to store the value of the orginal so it wont be affected
y = [] #making a list
while True:
if(sum1==0):#checking if the number is not zero so it can break if it is
break
d = sum1%10 #last number of your integer is saved in d
sum1 = int(sum1/10) #integer is now with out the last number ie.4320/10 become 432
y.append(d) # appending the last number in the first place
y.reverse()#as last is in first , reversing the number to orginal form
print(y)
Answer becomes
Enter the number2342
[2, 3, 4, 2]
Do you want to find elements that contain "match", or that equal "match"?
This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2
):
//*[text()='match']
This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2
):
//*[normalize-space(text())='match']
This will find all elements that contain 'match' in the text node value (matches random2
and random3
):
//*[contains(text(),'match')]
This XPATH 2.0 solution uses the matches()
function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^
) or a word boundary (i.e. \W
) and terminated by the end of the string (i.e. $
) or a word boundary. The third parameter i
evaluates the regex pattern case-insensitive. (matches random2
)
//*[matches(text(),'(^|\W)match($|\W)','i')]
SIMPLE method may not be the best for all cases
<%
if (Session["Utype"].ToString() == "1")
{
%>
<li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>
<li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
<%
}
else
{
%>
<li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
<%
}
%>
I assume that you are looking for intuitive definitions, since the technical definitions require quite some time to understand. First of all, let's remember a preliminary needed concept to understand those definitions.
Now, let us define those complexity classes.
P is a complexity class that represents the set of all decision problems that can be solved in polynomial time.
That is, given an instance of the problem, the answer yes or no can be decided in polynomial time.
Example
Given a connected graph G
, can its vertices be coloured using two colours so that no edge is monochromatic?
Algorithm: start with an arbitrary vertex, color it red and all of its neighbours blue and continue. Stop when you run out of vertices or you are forced to make an edge have both of its endpoints be the same color.
NP is a complexity class that represents the set of all decision problems for which the instances where the answer is "yes" have proofs that can be verified in polynomial time.
This means that if someone gives us an instance of the problem and a certificate (sometimes called a witness) to the answer being yes, we can check that it is correct in polynomial time.
Example
Integer factorisation is in NP. This is the problem that given integers n
and m
, is there an integer f
with 1 < f < m
, such that f
divides n
(f
is a small factor of n
)?
This is a decision problem because the answers are yes or no. If someone hands us an instance of the problem (so they hand us integers n
and m
) and an integer f
with 1 < f < m
, and claim that f
is a factor of n
(the certificate), we can check the answer in polynomial time by performing the division n / f
.
NP-Complete is a complexity class which represents the set of all problems X
in NP for which it is possible to reduce any other NP problem Y
to X
in polynomial time.
Intuitively this means that we can solve Y
quickly if we know how to solve X
quickly. Precisely, Y
is reducible to X
, if there is a polynomial time algorithm f
to transform instances y
of Y
to instances x = f(y)
of X
in polynomial time, with the property that the answer to y
is yes, if and only if the answer to f(y)
is yes.
Example
3-SAT
. This is the problem wherein we are given a conjunction (ANDs) of 3-clause disjunctions (ORs), statements of the form
(x_v11 OR x_v21 OR x_v31) AND
(x_v12 OR x_v22 OR x_v32) AND
... AND
(x_v1n OR x_v2n OR x_v3n)
where each x_vij
is a boolean variable or the negation of a variable from a finite predefined list (x_1, x_2, ... x_n)
.
It can be shown that every NP problem can be reduced to 3-SAT. The proof of this is technical and requires use of the technical definition of NP (based on non-deterministic Turing machines). This is known as Cook's theorem.
What makes NP-complete problems important is that if a deterministic polynomial time algorithm can be found to solve one of them, every NP problem is solvable in polynomial time (one problem to rule them all).
Intuitively, these are the problems that are at least as hard as the NP-complete problems. Note that NP-hard problems do not have to be in NP, and they do not have to be decision problems.
The precise definition here is that a problem X
is NP-hard, if there is an NP-complete problem Y
, such that Y
is reducible to X
in polynomial time.
But since any NP-complete problem can be reduced to any other NP-complete problem in polynomial time, all NP-complete problems can be reduced to any NP-hard problem in polynomial time. Then, if there is a solution to one NP-hard problem in polynomial time, there is a solution to all NP problems in polynomial time.
Example
The halting problem is an NP-hard problem. This is the problem that given a program P
and input I
, will it halt? This is a decision problem but it is not in NP. It is clear that any NP-complete problem can be reduced to this one. As another example, any NP-complete problem is NP-hard.
My favorite NP-complete problem is the Minesweeper problem.
This one is the most famous problem in computer science, and one of the most important outstanding questions in the mathematical sciences. In fact, the Clay Institute is offering one million dollars for a solution to the problem (Stephen Cook's writeup on the Clay website is quite good).
It's clear that P is a subset of NP. The open question is whether or not NP problems have deterministic polynomial time solutions. It is largely believed that they do not. Here is an outstanding recent article on the latest (and the importance) of the P = NP problem: The Status of the P versus NP problem.
The best book on the subject is Computers and Intractability by Garey and Johnson.
There is merge!
.
h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}
the function Position
in funprog {base} also does the job. It allows you to pass an arbitrary function, and returns the first or last match.
Position(f, x, right = FALSE, nomatch = NA_integer)
<input class="form-control search-query input_style" placeholder="Search…" name="" title="Search for:" type="text">
.input_style
{
padding-left:20px;
}
Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}
then you create a menu strip item to exit the application.
cheers
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
It's a formal way of specifying a correlation name for an entity so that you can address it easily in another part of the query.
There is a standard ArgumentException that you could use, or you could subclass and make your own. There are several specific ArgumentException classes:
http://msdn.microsoft.com/en-us/library/system.argumentexception(VS.71).aspx
Whichever one works best.
Easiest: http://www.addthis.com/
Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...
It depends on your mark-up, but it can certainly be made to work, I used the following:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).siblings('p').slideToggle();
}
);
}
);
<table>
<thead>
<tr>
<th>Actor</th>
<th>Which Doctor</th>
<th>Significant companion</th>
</tr>
</thead>
<tbody>
<tr>
<td><h2>William Hartnell</h2></td>
<td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Patrick Troughton</h2></td>
<td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Jon Pertwee</h2></td>
<td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
</tbody>
</table>
The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp()
as the paragraphs were hidden, and still leave an element, h2
to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.
As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p
elements this would work:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).closest('tr').find('p').slideToggle();
}
);
}
);
I made modifications on only controller initialization by adding listener on action button:
$(document).on('click', '#action-button', function () {
$timeout(function () {
angular.element($('#input')).triggerHandler('input');
});
});
Other solutions did not work in my case.
You could also pass points to the function: Small example:
def test(points):
addpoint = raw_input ("type ""add"" to add a point")
if addpoint == "add":
points = points + 1
else:
print "asd"
return points;
if __name__ == '__main__':
points = 0
for i in range(10):
points = test(points)
print points
<textarea style="width:300px; height:150px;" ></textarea>
My solution to hiding a DB-Password in Spring Boot App's application.properties does implemented here.
Scenario: some fake password already reading and saved from application.properties on start, in global Spring object ConfigurableEnvironment will be, in Run-Time replaced programmaticaly, by real DB-Password. The real password will be reading from another config file, saved in safe, project-outer place.
Don't forget: call the the Bean from main class with:
@Autowired
private SchedUtilility utl;
For ExpressJS applications you can use:
app.use((req, res, next) => {
const corsWhitelist = [
'https://domain1.example',
'https://domain2.example',
'https://domain3.example'
];
if (corsWhitelist.indexOf(req.headers.origin) !== -1) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
}
next();
});
Yes, let's use Select
as an example
sample code: Columns("A").select
How to loop through Columns:
Method 1: (You can use index to replace the Excel Address)
For i = 1 to 100
Columns(i).Select
next i
Method 2: (Using the address)
For i = 1 To 100
Columns(Columns(i).Address).Select
Next i
EDIT: Strip the Column for OP
columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")
e.g. you want to get the 27th Column --> AA, you can get it this way
You can use Regular Expressions with a dynamic pattern.
var text = "something";
var output = " ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);
outputs:
"something "
This replaces text.length
of whitespace characters at the beginning of the string output
.
The RegExp
means ^\
- beginning of a line \s
any white space character, repeated {n}
times, in this case text.length
. Use \\
to \
escape backslashes when building this kind of patterns out of strings.
I would avoid to do a query for each entry.
if(is_array($EMailArr)){
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ";
$valuesArr = array();
foreach($EMailArr as $row){
$R_ID = (int) $row['R_ID'];
$email = mysql_real_escape_string( $row['email'] );
$name = mysql_real_escape_string( $row['name'] );
$valuesArr[] = "('$R_ID', '$email', '$name')";
}
$sql .= implode(',', $valuesArr);
mysql_query($sql) or exit(mysql_error());
}
I wrote all about tabs in vim, which gives a few interesting things you didn't ask about. To automatically indent braces, use:
:set cindent
To indent two spaces (instead of one tab of eight spaces, the vim default):
:set shiftwidth=2
To keep vim from converting eight spaces into tabs:
:set expandtab
If you ever want to change the indentation of a block of text, use < and >. I usually use this in conjunction with block-select mode (v, select a block of text, < or >).
(I'd try to talk you out of using two-space indentation, since I (and most other people) find it hard to read, but that's another discussion.)
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
How to without a dummy initial view controller
Ensure all initial view controllers have a Storyboard ID.
In the storyboard, uncheck the "Is initial View Controller" attribute from the first view controller.
If you run your app at this point you'll read:
Failed to instantiate the default view controller for UIMainStoryboardFile 'MainStoryboard' - perhaps the designated entry point is not set?
And you'll notice that your window property in the app delegate is now nil.
In the app's setting, go to your target and the Info
tab. There clear the value of Main storyboard file base name
. On the General
tab, clear the value for Main Interface
. This will remove the warning.
Create the window and desired initial view controller in the app delegate's application:didFinishLaunchingWithOptions:
method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = // determine the initial view controller here and instantiate it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
return YES;
}
Try to work with EditText by make it unclickable and unfocusable, also you can display a scrollbar and delete the EditText's underbar.
Here is an example:
<EditText
android:id="@+id/my_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_parent"
android:inputType="textMultiLine" <!-- multiline -->
android:clickable="false" <!-- unclickable -->
android:focusable="false" <!-- unfocusable -->
android:scrollbars="vertical" <!-- enable scrolling vertically -->
android:background="@android:color/transparent" <!-- hide the underbar of EditText -->
/>
Hope this helps :)
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
I resolved this issue by excluding byte-buddy dependency from springfox
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
export default class MyComponent extends React.Component {
onSubmit(e) {
e.preventDefault();
var title = this.title.value; //added .value
console.log(title);
}
render(){
return (
...
<form className="form-horizontal">
...
<input type="text" className="form-control" ref={input => this.title = input} name="title" />
...
</form>
...
<button type="button" onClick={this.onSubmit} className="btn">Save</button>
...
);
}
};
In the jQuery source code we have jQuery.fn = jQuery.prototype = {...}
since jQuery.prototype
is an object the value of jQuery.fn
will simply be a reference to the same object that jQuery.prototype
already references.
To confirm this you can check jQuery.fn === jQuery.prototype
if that evaluates true
(which it does) then they reference the same object
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td>
<table border="0">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>one</td>
</tr>
</table>
</td>
</tr>
</table>
select count(e.empno), d.deptno, d.dname
from emp e, dep d
where e.DEPTNO = d.DEPTNO
group by d.deptno, d.dname;
You are using the wrong type. The Array(...)
function returns a Variant
, not a String
.
Thus, in the Declaration section of your module (it does not need to be a different module!), you define
Public colHeader As Variant
and somewhere at the beginning of your program code (for example, in the Workbook_Open
event) you initialize it with
colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Another (simple) alternative would be to create a function that returns the array, e.g. something like
Public Function GetHeaders() As Variant
GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function
This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.
I didn't try all these. I restarted by laptop/machine . And everything was back to normal after that.
Does
$ git log -p
do what you need?
Check out the chapter on Git Log in the Git Community Book for more examples. (Or look at the the documentation.)
Update: As others (Jakub and Bombe) already pointed out: although the above works, git show is actually the command that is intended to do exactly what was asked for.
The question specifically mentions a full box and not an empty box and not using proof
environment from amsthm
package. Hence, an option may be to use the command \QED
from the package stix
. It reproduces the character U+220E
(end of proof, ?).
Just put this line :
builder.setAutoCancel(true);
And the full code is :
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
builder.setContentTitle("Notifications Title");
builder.setContentText("Your notification content here.");
builder.setSubText("Tap to view the website.");
Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder.setAutoCancel(true);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
The cin.clear()
clears the error flag on cin
(so that future I/O operations will work correctly), and then cin.ignore(10000, '\n')
skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.
If you want to create your picker in IB, you can post-resize it to a smaller size. Check to make sure it still draws correctly though, as there comes a point where it looks heinous.
Trying to handle the URI with content:// scheme by calling ContentResolver.query()
is not a good solution. On HTC Desire running 4.2.2 you could get NULL as a query result.
Why not to use ContentResolver instead? https://stackoverflow.com/a/29141800/3205334
I was getting the same "cannot find symbol" error when I did Build -> Make Project
. I fixed this by deleting my Maven /target
folder, right clicking my project module and doing Maven -> Reimport
, and doing Build -> Rebuild Project
. This was on IntelliJ Idea 13.1.5.
It turns out the Maven -> Reimport
was key, since the problem resurfaced a few times before I finally did that.
Goto Properties -> maven Remove the pom.xml from the activate profiles and follow the below steps.
Steps :
Try using border=0
in the img
tag to make the ugly square go away.
<img src="someimage.png" border="0" alt="some alternate text" />
I didnt know about css3pie.com, a very useful site after seeing this post:
But what after testing it out it didnt work for me either. However I found that wrapping it in the .PHP file worked fine. So instead of:
behavior: url(PIE.htc);
use this:
behavior: url(PIE.php);
I put mine in a folder called jquery, so mine was:
behavior: url(jquery/PIE.php);
So goto their downloads or get it here:
http://css3pie.com/download-latest
And use their PHP file. Inside the PHP file it explains that some servers are not configured for proper .HTC usage. And that was the problem I had.
Try it! I did, it works. Hope this helps others out too.
The primary key is already protecting you from inserting duplicate values, as you're experiencing when you get that error. Adding another unique constraint isn't necessary to do that.
The "duplicate key" error is telling you that the work was not done because it would produce a duplicate key, not that it discovered a duplicate key already commited to the table.
aws s3api list-objects --bucket bucket-name
For more details see here - http://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects.html
None of the 13 existing answers worked for me. However, I could resolve the issue by first removing all modules:
File
> Project Structure...
,Modules
tab,then removing all remaining Maven modules from Maven
tool window:
Remove projects
,and then adding them again in Project
tool window:
pom.xml
,Add as Maven project
,now unignoring any ignored modules from Maven
tool window:
Unignore
,and finally rebuilding using Build
> Rebuild project
. This assumes that a mvn clean install
already happened.
You can simply write
hex(x)[2:]
to get the first two characters removed.
Use the put method: https://developer.android.com/reference/org/json/JSONObject.html
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
You can use toSql method - the easiest way
DB::table('users')->toSql();
And also if you have bindings in your query and want to see the query with bindings. You cant use somthing like that:
$query = DB::table('table')->whereIn('some_field', [1,2,30]);
$sql_with_bindings = str_replace_array('?', $query->getBindings(), $query->toSql());
dd($sql_with_bindings);
Another option is the SimpleXML extension (I believe it comes standard with most php installs.)
http://php.net/manual/en/book.simplexml.php
The syntax looks something like this for your example
$xml = new SimpleXMLElement($xmlString);
echo $xml->bbb->cccc->dddd['Id'];
echo $xml->bbb->cccc->eeee['name'];
// or...........
foreach ($xml->bbb->cccc as $element) {
foreach($element as $key => $val) {
echo "{$key}: {$val}";
}
}
solution - 1) Make sure you're in the root
folder of your app. eg app/db/schema.sql.
solution - 2) open/reveal the folder on your window and drag&&
drop in the command line next to keywork source
(space) filesource. eg source User/myMAC/app/db/schema.sql
It is not a good idea to use a Runnable when exit the application, I recently figure out a much simpler way to record and compare the period between two BACK button clicks. Sample code as following:
private static long back_pressed_time;
private static long PERIOD = 2000;
@Override
public void onBackPressed()
{
if (back_pressed_time + PERIOD > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed_time = System.currentTimeMillis();
}
This will do the trick to exit the application by a double BACK button clicks within a certain delay period which is 2000 millisecond in sample.
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
First you need to determine the revision ID of the last known commit. You can use HEAD^
or HEAD~{1}
if you know you need to reverse exactly one commit.
git reset --hard <revision_id_of_last_known_good_commit>
git push --force
The only way to do explicit scaling in CSS is to use tricks such as found here.
IE6 only, you could also use filters (check out PNGFix). But applying them automatically to the page will need javascript, though that javascript could be embedded in the CSS file.
If you are going to require javascript, then you might want to just have javascript fill in the missing value for the height by inspecting the image once the content has loaded. (Sorry I do not have a reference for this technique).
Finally, and pardon me for this soapbox, you might want to eschew IE6 support in this matter. You could add _width: auto
after your width: 75px
rule, so that IE6 at least renders the image reasonably, even if it is the wrong size.
I recommend the last solution simply because IE6 is on the way out: 20% and going down almost a percent a month. Also, I note that your site is recreational and in the UK. Both of these help the demographic lean to be away from IE6: IE6 usage drops nearly 40% during weekends (no citation sorry), and UK has a much lower IE6 demographic (again no citation, sorry).
Good luck!
How about dumping the list of list into pickle and restoring it with pickle module? It's quite convenient.
>>> import pickle
>>>
>>> mylist = [1, 'foo', 'bar', {1, 2, 3}, [ [1,4,2,6], [3,6,0,10]]]
>>> with open('mylist', 'wb') as f:
... pickle.dump(mylist, f)
>>> with open('mylist', 'rb') as f:
... mylist = pickle.load(f)
>>> mylist
[1, 'foo', 'bar', {1, 2, 3}, [[1, 4, 2, 6], [3, 6, 0, 10]]]
>>>
Explanation: You can *ngFor on the arrays. You have your users declared as the array. But, the response from the Get returns you an object. You cannot ngFor on the object. You should have an array for that. You can explicitly cast the object to array and that will solve the issue. data to [data]
Solution
getusers() {
this.http.get(`https://api.github.com/
search/users?q=${this.input1.value}`)
.map(response => response.json())
.subscribe(
data => this.users = [data], //Cast your object to array. that will do it.
error => console.log(error)
)
If you label the if statement you can use break.
breakme: if (condition) {
// Do stuff
if (condition2){
// do stuff
} else {
break breakme;
}
// Do more stuff
}
You can even label and break plain blocks.
breakme: {
// Do stuff
if (condition){
// do stuff
} else {
break breakme;
}
// Do more stuff
}
It's not a commonly used pattern though, so might confuse people and possibly won't be optimised by compliers. It might be better to use a function and return, or better arrange the conditions.
( function() {
// Do stuff
if ( condition1 ) {
// Do stuff
} else {
return;
}
// Do other stuff
}() );
First I think int&const icr=i;
is just int& icr = i
, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).
const int x = 10;
// int& const y = x; // Compiler error here
Second, constant reference just means you cannot change the value of variable through reference.
const int x = 10;
const int& y = x;
//y = 20; // Compiler error here
Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.
float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340
The problem here is that you are including commands.c
in commands.h
before the function prototype. Therefore, the C pre-processor inserts the content of commands.c
into commands.h
before the function prototype. commands.c
contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.
The content of commands.h
after the pre-processor phase looks like this:
#ifndef COMMANDS_H_
#define COMMANDS_H_
// function definition
void f123(){
}
// function declaration
void f123();
#endif /* COMMANDS_H_ */
This is an error because you can't declare a function after its definition in C. If you swapped #include "commands.c"
and the function declaration the error shouldn't happen because, now, the function prototype comes before the function declaration.
However, including a .c
file is a bad practice and should be avoided. A better solution for this problem would be to include commands.h
in commands.c
and link the compiled version of command to the main file. For example:
commands.h
#ifndef COMMANDS_H_
#define COMMANDS_H_
void f123(); // function declaration
#endif
commands.c
#include "commands.h"
void f123(){} // function definition
d = dict([(x,0) for x in a])
**edit Tim's solution is better because it uses generators see the comment to his answer.
The .egg
file is a distribution format for Python packages. It’s just an alternative to a source code distribution or Windows exe
. But note that for pure Python
, the .egg
file is completely cross-platform.
The .egg
file itself is essentially a .zip
file. If you change the extension to “zip
”, you can see that it will have folders inside the archive.
Also, if you have an .egg
file, you can install it as a package using easy_install
Example:
To create an .egg
file for a directory say mymath
which itself may have several python scripts, do the following step:
# setup.py
from setuptools import setup, find_packages
setup(
name = "mymath",
version = "0.1",
packages = find_packages()
)
Then, from the terminal do:
$ python setup.py bdist_egg
This will generate lot of outputs, but when it’s completed you’ll see that you have three new folders: build, dist, and mymath.egg-info. The only folder that we care about is the dist folder where you'll find your .egg
file, mymath-0.1-py3.5.egg
with your default python (installation) version number(mine here: 3.5)
Source: Python library blog
This answer is pretty similar to Oz.'s, using <chrono>
for C++ -- I didn't grab it from Oz. though...
I picked up the original snippet at the bottom of this page, and slightly modified it to be a complete console app. I love using this lil' ol' thing. It's fantastic if you do a lot of scripting and need a reliable tool in Windows to get the epoch in actual milliseconds without resorting to using VB, or some less modern, less reader-friendly code.
#include <chrono>
#include <iostream>
int main() {
unsigned __int64 now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
std::cout << now << std::endl;
return 0;
}
If none of the above work, double-check your code. Sometimes the reason why the breakpoint appears to not be hitting is due to the block of code containing the breakpoint is not being executed for sometimes inadvertant reasons.
For example, forgetting the "Handles Me.Load" has gotten me a few times when copying and pasting code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
--this block of code will not execute
End Sub
vs
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
--this block executes
End Sub
Perhaps a function along these lines is what you're after:
def add_unique_to_dict_list(dict_list, key, value):
for d in dict_list:
if key in d:
return d[key]
dict_list.append({ key: value })
return value
Here's a table to help find the required flags for different permission combinations.
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ ¦ ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦ files ¦ ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦ ¦ Propagation ¦ none ¦ none ¦ none ¦ none ¦ InheritOnly ¦ InheritOnly ¦ InheritOnly ¦ ¦ Inheritance ¦ none ¦ Container|Object ¦ Container ¦ Object ¦ Container|Object ¦ Container ¦ Object ¦ +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
So, as David said, you'll want
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
Better solution here;
Dictionary<int, string> userListDictionary = new Dictionary<int, string>();
foreach (var user in users)
{
userListDictionary.Add(user.Id,user.Name);
}
cmbUser.DataSource = new BindingSource(userListDictionary, null);
cmbUser.DisplayMember = "Value";
cmbUser.ValueMember = "Key";
Retreive Data
MessageBox.Show(cmbUser.SelectedValue.ToString());
You also need to include the Log4J JAR file in the classpath.
Note that slf4j-log4j12-1.6.4.jar
is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.
To bind the data to ComboBox
List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });
cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";
cbotest.SelectedValue = "2";
ComboData
looks like:
public class ComboData
{
public int Id { get; set; }
public string Value { get; set; }
}
(note that Id
and Value
have to be properties, not class fields)
Null OR an empty string?
if (!empty($user)) {}
Use empty().
After realizing that $user ~= $_POST['user'] (thanks matt):
var uservariable='<?php
echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';
Add this attribute in Edittext tag and enjoy:
android:backgroundTint="@color/colorWhite"
Ok, I figured it out, this is pretty simple with a little html trick:
HTML
<body>
<div id="background">.
</div>
<p>hello world</p>
<p>hello world</p>
<p>hello world</p>
<p>hello world</p>
</body>?
javascript
$(document).ready(function(){
$('#background').animate({ opacity: 1 }, 3000);
});?
CSS
#background {
background-image: url("http://media.noupe.com//uploads/2009/10/wallpaper-pattern.jpg");
opacity: 0;
margin: 0;
padding: 0;
z-index: -1;
position: absolute;
width: 100%;
height: 100%;
}?
alter table table_name change old_col_name new_col_name new_col_type;
Here is the example
hive> alter table test change userVisit userVisit2 STRING;
OK
Time taken: 0.26 seconds
hive> describe test;
OK
uservisit2 string
category string
uuid string
Time taken: 0.213 seconds, Fetched: 3 row(s)
The well-established "pattern" for reverse-iterating through closed-open ranges looks as follows
// Iterate over [begin, end) range in reverse
for (iterator = end; iterator-- != begin; ) {
// Process `*iterator`
}
or, if you prefer,
// Iterate over [begin, end) range in reverse
for (iterator = end; iterator != begin; ) {
--iterator;
// Process `*iterator`
}
This pattern is useful, for example, for reverse-indexing an array using an unsigned index
int array[N];
...
// Iterate over [0, N) range in reverse
for (unsigned i = N; i-- != 0; ) {
array[i]; // <- process it
}
(People unfamiliar with this pattern often insist on using signed integer types for array indexing specifically because they incorrectly believe that unsigned types are somehow "unusable" for reverse indexing)
It can be used for iterating over an array using a "sliding pointer" technique
// Iterate over [array, array + N) range in reverse
for (int *p = array + N; p-- != array; ) {
*p; // <- process it
}
or it can be used for reverse-iteration over a vector using an ordinary (not reverse) iterator
for (vector<my_class>::iterator i = my_vector.end(); i-- != my_vector.begin(); ) {
*i; // <- process it
}
In my case String(describing: self) returned something like:
< My_project.ExampleViewController: 0x10b2bb2b0>
But I'd like to have something like getSimpleName
on Android.
So I've created a little extension:
extension UIViewController {
func getSimpleClassName() -> String {
let describing = String(describing: self)
if let dotIndex = describing.index(of: "."), let commaIndex = describing.index(of: ":") {
let afterDotIndex = describing.index(after: dotIndex)
if(afterDotIndex < commaIndex) {
return String(describing[afterDotIndex ..< commaIndex])
}
}
return describing
}
}
And now it returns:
ExampleViewController
Extending NSObject instead of UIViewController should also work. Function above is also fail-safe :)
I have found the selected answer to have problems with upscaling, and so I have made (yet) another version (which I have tested):
public static Point scaleFit(Point src, Point bounds) {
int newWidth = src.x;
int newHeight = src.y;
double boundsAspectRatio = bounds.y / (double) bounds.x;
double srcAspectRatio = src.y / (double) src.x;
// first check if we need to scale width
if (boundsAspectRatio < srcAspectRatio) {
// scale width to fit
newWidth = bounds.x;
//scale height to maintain aspect ratio
newHeight = (newWidth * src.y) / src.x;
} else {
//scale height to fit instead
newHeight = bounds.y;
//scale width to maintain aspect ratio
newWidth = (newHeight * src.x) / src.y;
}
return new Point(newWidth, newHeight);
}
Written in Android terminology :-)
as for the tests:
@Test public void scaleFit() throws Exception {
final Point displaySize = new Point(1080, 1920);
assertEquals(displaySize, Util.scaleFit(displaySize, displaySize));
assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x / 2, displaySize.y / 2), displaySize));
assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x * 2, displaySize.y * 2), displaySize));
assertEquals(new Point(displaySize.x, displaySize.y * 2), Util.scaleFit(new Point(displaySize.x / 2, displaySize.y), displaySize));
assertEquals(new Point(displaySize.x * 2, displaySize.y), Util.scaleFit(new Point(displaySize.x, displaySize.y / 2), displaySize));
assertEquals(new Point(displaySize.x, displaySize.y * 3 / 2), Util.scaleFit(new Point(displaySize.x / 3, displaySize.y / 2), displaySize));
}
Another cause: you add a project reference from project A to project B in solution X. However, solution Y that already contains project A is now broken, until you also add project B to solution Y.
new setup should first run python manage.py createsuperuser
to create user. It seems like there is no default username password to login into admin.
The best way now is to use the "Quit" button that is just to the left of the "Logout" button. I have to admit that I do not understand the utility of the Logout button. However, I am glad that they have added the exceedingly useful Quit button.
This provides you to retrieve information from your URI strings
$this->uri->segment(n); // n=1 for controller, n=2 for method, etc
Consider this example:
http://example.com/index.php/controller/action/1stsegment/2ndsegment
it will return
$this->uri->segment(1); // controller
$this->uri->segment(2); // action
$this->uri->segment(3); // 1stsegment
$this->uri->segment(4); // 2ndsegment
Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
for col in row:
im = col.imshow(data, cmap='bone')
divider = make_axes_locatable(col)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
Use pick
method of lodash library if you are already using.
var obj = { 'a': 1, 'b': '2', 'c': 3 };
_.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }
Why not just, a=a(~~a)
or a(~a)=[]
. It's equivalent to the other approaches but certainly less key strokes.
Here's my 2 cents:
The sequence Start New Instance->Close Current Instance should work even for the applications that don't allow running multiple copies simultaneously as in this case the new instance may be passed a command-line argument which will indicate that there is a restart in progress so checking for other instances running will not be necessary. Waiting for the first instance to actually finish my be implemented too if it's absolutely imperative that no two intstances are running in parallel.
Disable ARC on MULTIPLE files:
;)
Transfer is entirely server-side. Client address bar stays constant. Some complexity about the transfer of context between requests. Flushing and restarting page handlers can be expensive so do your transfer early in the pipeline e.g. in an HttpModule during BeginRequest. Read the MSDN docs carefully, and test and understand the new values of HttpContext.Request - especially in Postback scenarios. We usually use Server.Transfer for error scenarios.
Redirect terminates the request with a 302 status and client-side roundtrip response with and internally eats an exception (minor server perf hit - depends how many you do a day) Client then navigates to new address. Browser address bar & history updates etc. Client pays the cost of an extra roundtrip - cost varies depending on latency. In our business we redirect a lot we wrote our own module to avoid the exception cost.
This worked for me:
git fsck --full --no-reflogs --unreachable --lost-found
git show d6e883ff45be514397dcb641c5a914f40b938c86
git branch helpme 15e521b0f716269718bb4e4edc81442a6c11c139
Running Catalina 10.15.4 I ran the permissions command below to get brew to install
sudo chown -R $(whoami):admin /usr/local/* && sudo chmod -R g+rwx /usr/local/*
starting from the chad's answer, here is the COMPLETE working solution to parse UML, with propper handling of comments, with just 2 little functions (more than 2 bu you can mix them all). I don't say chad's one didn't work at all, but it had too much issues with badly formated XML files: So you have to be a bit more tricky to handle comments and misplaced spaces/CR/TAB/etc.
The purpose of this answer is to give ready-2-use, out of the box bash functions to anyone needing parsing UML without complex tools using perl, python or anything else. As for me, I cannot install cpan, nor perl modules for the old production OS i'm working on, and python isn't available.
First, a definition of the UML words used in this post:
<!-- comment... -->
<tag attribute="value">content...</tag>
EDIT: updated functions, with handle of:
xml_read_dom() {
# https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash
local ENTITY IFS=\>
if $ITSACOMMENT; then
read -d \< COMMENTS
COMMENTS="$(rtrim "${COMMENTS}")"
return 0
else
read -d \< ENTITY CONTENT
CR=$?
[ "x${ENTITY:0:1}x" == "x/x" ] && return 0
TAG_NAME=${ENTITY%%[[:space:]]*}
[ "x${TAG_NAME}x" == "x?xmlx" ] && TAG_NAME=xml
TAG_NAME=${TAG_NAME%%:*}
ATTRIBUTES=${ENTITY#*[[:space:]]}
ATTRIBUTES="${ATTRIBUTES//xmi:/}"
ATTRIBUTES="${ATTRIBUTES//xmlns:/}"
fi
# when comments sticks to !-- :
[ "x${TAG_NAME:0:3}x" == "x!--x" ] && COMMENTS="${TAG_NAME:3} ${ATTRIBUTES}" && ITSACOMMENT=true && return 0
# http://tldp.org/LDP/abs/html/string-manipulation.html
# INFO: oh wait it doesn't work on IBM AIX bash 3.2.16(1):
# [ "x${ATTRIBUTES:(-1):1}x" == "x/x" -o "x${ATTRIBUTES:(-1):1}x" == "x?x" ] && ATTRIBUTES="${ATTRIBUTES:0:(-1)}"
[ "x${ATTRIBUTES:${#ATTRIBUTES} -1:1}x" == "x/x" -o "x${ATTRIBUTES:${#ATTRIBUTES} -1:1}x" == "x?x" ] && ATTRIBUTES="${ATTRIBUTES:0:${#ATTRIBUTES} -1}"
return $CR
}
and the second one :
xml_read() {
# https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash
ITSACOMMENT=false
local MULTIPLE_ATTR LIGHT FORCE_PRINT XAPPLY XCOMMAND XATTRIBUTE GETCONTENT fileXml tag attributes attribute tag2print TAGPRINTED attribute2print XAPPLIED_COLOR PROSTPROCESS USAGE
local TMP LOG LOGG
LIGHT=false
FORCE_PRINT=false
XAPPLY=false
MULTIPLE_ATTR=false
XAPPLIED_COLOR=g
TAGPRINTED=false
GETCONTENT=false
PROSTPROCESS=cat
Debug=${Debug:-false}
TMP=/tmp/xml_read.$RANDOM
USAGE="${C}${FUNCNAME}${c} [-cdlp] [-x command <-a attribute>] <file.xml> [tag | \"any\"] [attributes .. | \"content\"]
${nn[2]} -c = NOCOLOR${END}
${nn[2]} -d = Debug${END}
${nn[2]} -l = LIGHT (no \"attribute=\" printed)${END}
${nn[2]} -p = FORCE PRINT (when no attributes given)${END}
${nn[2]} -x = apply a command on an attribute and print the result instead of the former value, in green color${END}
${nn[1]} (no attribute given will load their values into your shell; use '-p' to print them as well)${END}"
! (($#)) && echo2 "$USAGE" && return 99
(( $# < 2 )) && ERROR nbaram 2 0 && return 99
# getopts:
while getopts :cdlpx:a: _OPT 2>/dev/null
do
{
case ${_OPT} in
c) PROSTPROCESS="${DECOLORIZE}" ;;
d) local Debug=true ;;
l) LIGHT=true; XAPPLIED_COLOR=END ;;
p) FORCE_PRINT=true ;;
x) XAPPLY=true; XCOMMAND="${OPTARG}" ;;
a) XATTRIBUTE="${OPTARG}" ;;
*) _NOARGS="${_NOARGS}${_NOARGS+, }-${OPTARG}" ;;
esac
}
done
shift $((OPTIND - 1))
unset _OPT OPTARG OPTIND
[ "X${_NOARGS}" != "X" ] && ERROR param "${_NOARGS}" 0
fileXml=$1
tag=$2
(( $# > 2 )) && shift 2 && attributes=$*
(( $# > 1 )) && MULTIPLE_ATTR=true
[ -d "${fileXml}" -o ! -s "${fileXml}" ] && ERROR empty "${fileXml}" 0 && return 1
$XAPPLY && $MULTIPLE_ATTR && [ -z "${XATTRIBUTE}" ] && ERROR param "-x command " 0 && return 2
# nb attributes == 1 because $MULTIPLE_ATTR is false
[ "${attributes}" == "content" ] && GETCONTENT=true
while xml_read_dom; do
# (( CR != 0 )) && break
(( PIPESTATUS[1] != 0 )) && break
if $ITSACOMMENT; then
# oh wait it doesn't work on IBM AIX bash 3.2.16(1):
# if [ "x${COMMENTS:(-2):2}x" == "x--x" ]; then COMMENTS="${COMMENTS:0:(-2)}" && ITSACOMMENT=false
# elif [ "x${COMMENTS:(-3):3}x" == "x-->x" ]; then COMMENTS="${COMMENTS:0:(-3)}" && ITSACOMMENT=false
if [ "x${COMMENTS:${#COMMENTS} - 2:2}x" == "x--x" ]; then COMMENTS="${COMMENTS:0:${#COMMENTS} - 2}" && ITSACOMMENT=false
elif [ "x${COMMENTS:${#COMMENTS} - 3:3}x" == "x-->x" ]; then COMMENTS="${COMMENTS:0:${#COMMENTS} - 3}" && ITSACOMMENT=false
fi
$Debug && echo2 "${N}${COMMENTS}${END}"
elif test "${TAG_NAME}"; then
if [ "x${TAG_NAME}x" == "x${tag}x" -o "x${tag}x" == "xanyx" ]; then
if $GETCONTENT; then
CONTENT="$(trim "${CONTENT}")"
test ${CONTENT} && echo "${CONTENT}"
else
# eval local $ATTRIBUTES => eval test "\"\$${attribute}\"" will be true for matching attributes
eval local $ATTRIBUTES
$Debug && (echo2 "${m}${TAG_NAME}: ${M}$ATTRIBUTES${END}"; test ${CONTENT} && echo2 "${m}CONTENT=${M}$CONTENT${END}")
if test "${attributes}"; then
if $MULTIPLE_ATTR; then
# we don't print "tag: attr=x ..." for a tag passed as argument: it's usefull only for "any" tags so then we print the matching tags found
! $LIGHT && [ "x${tag}x" == "xanyx" ] && tag2print="${g6}${TAG_NAME}: "
for attribute in ${attributes}; do
! $LIGHT && attribute2print="${g10}${attribute}${g6}=${g14}"
if eval test "\"\$${attribute}\""; then
test "${tag2print}" && ${print} "${tag2print}"
TAGPRINTED=true; unset tag2print
if [ "$XAPPLY" == "true" -a "${attribute}" == "${XATTRIBUTE}" ]; then
eval ${print} "%s%s\ " "\${attribute2print}" "\${${XAPPLIED_COLOR}}\"\$(\$XCOMMAND \$${attribute})\"\${END}" && eval unset ${attribute}
else
eval ${print} "%s%s\ " "\${attribute2print}" "\"\$${attribute}\"" && eval unset ${attribute}
fi
fi
done
# this trick prints a CR only if attributes have been printed durint the loop:
$TAGPRINTED && ${print} "\n" && TAGPRINTED=false
else
if eval test "\"\$${attributes}\""; then
if $XAPPLY; then
eval echo "\${g}\$(\$XCOMMAND \$${attributes})" && eval unset ${attributes}
else
eval echo "\$${attributes}" && eval unset ${attributes}
fi
fi
fi
else
echo eval $ATTRIBUTES >>$TMP
fi
fi
fi
fi
unset CR TAG_NAME ATTRIBUTES CONTENT COMMENTS
done < "${fileXml}" | ${PROSTPROCESS}
# http://mywiki.wooledge.org/BashFAQ/024
# INFO: I set variables in a "while loop" that's in a pipeline. Why do they disappear? workaround:
if [ -s "$TMP" ]; then
$FORCE_PRINT && ! $LIGHT && cat $TMP
# $FORCE_PRINT && $LIGHT && perl -pe 's/[[:space:]].*?=/ /g' $TMP
$FORCE_PRINT && $LIGHT && sed -r 's/[^\"]*([\"][^\"]*[\"][,]?)[^\"]*/\1 /g' $TMP
. $TMP
rm -f $TMP
fi
unset ITSACOMMENT
}
and lastly, the rtrim, trim and echo2 (to stderr) functions:
rtrim() {
local var=$@
var="${var%"${var##*[![:space:]]}"}" # remove trailing whitespace characters
echo -n "$var"
}
trim() {
local var=$@
var="${var#"${var%%[![:space:]]*}"}" # remove leading whitespace characters
var="${var%"${var##*[![:space:]]}"}" # remove trailing whitespace characters
echo -n "$var"
}
echo2() { echo -e "$@" 1>&2; }
oh and you will need some neat colorizing dynamic variables to be defined at first, and exported, too:
set -a
TERM=xterm-256color
case ${UNAME} in
AIX|SunOS)
M=$(${print} '\033[1;35m')
m=$(${print} '\033[0;35m')
END=$(${print} '\033[0m')
;;
*)
m=$(tput setaf 5)
M=$(tput setaf 13)
# END=$(tput sgr0) # issue on Linux: it can produces ^[(B instead of ^[[0m, more likely when using screenrc
END=$(${print} '\033[0m')
;;
esac
# 24 shades of grey:
for i in $(seq 0 23); do eval g$i="$(${print} \"\\033\[38\;5\;$((232 + i))m\")" ; done
# another way of having an array of 5 shades of grey:
declare -a colorNums=(238 240 243 248 254)
for num in 0 1 2 3 4; do nn[$num]=$(${print} "\033[38;5;${colorNums[$num]}m"); NN[$num]=$(${print} "\033[48;5;${colorNums[$num]}m"); done
# piped decolorization:
DECOLORIZE='eval sed "s,${END}\[[0-9;]*[m|K],,g"'
Either you know how to create functions and load them via FPATH (ksh) or an emulation of FPATH (bash)
If not, just copy/paste everything on the command line.
xml_read [-cdlp] [-x command <-a attribute>] <file.xml> [tag | "any"] [attributes .. | "content"]
-c = NOCOLOR
-d = Debug
-l = LIGHT (no \"attribute=\" printed)
-p = FORCE PRINT (when no attributes given)
-x = apply a command on an attribute and print the result instead of the former value, in green color
(no attribute given will load their values into your shell as $ATTRIBUTE=value; use '-p' to print them as well)
xml_read server.xml title content # print content between <title></title>
xml_read server.xml Connector port # print all port values from Connector tags
xml_read server.xml any port # print all port values from any tags
With Debug mode (-d) comments and parsed attributes are printed to stderr
Also seems nobody noticed -x operator on symlinks. A symlink (chain) to a regular file (not classified as executable) fails the test.