Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent
is the door, which needs to be closed (reset) manually. The AutoResetEvent
is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.
I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate
instead.
I know you asked what enumerate means, but when I understood the following, I also understood how enumerate
makes iterating over a list while knowing the index of the current item easier (and more readable).
list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
letter = list_of_letters[i]
print (i, letter)
The output is:
0 a
1 b
2 c
I also used to do something, even sillier before I read about the enumerate
function.
i = 0
for n in list_of_letters:
print (i, n)
i += 1
It produces the same output.
But with enumerate
I just have to write:
list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
print (i, letter)
Try using the QueryDefs. Create the query with parameters. Then use something like this:
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("Your Query Name")
qdf.Parameters("Parameter 1").Value = "Parameter Value"
qdf.Parameters("Parameter 2").Value = "Parameter Value"
qdf.Execute
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
<Button x:Name="mybtnSave" FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="813,614,0,0" VerticalAlignment="Top" Width="223" Height="53" BorderBrush="#FF2B3830" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" TabIndex="107" Click="mybtnSave_Click" >
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF080505" Offset="1"/>
<GradientStop Color="White" Offset="0.536"/>
</LinearGradientBrush>
</Button.Background>
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
<StackPanel HorizontalAlignment="Stretch" Cursor="Hand" >
<StackPanel.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF3ED82E" Offset="0"/>
<GradientStop Color="#FF3BF728" Offset="1"/>
<GradientStop Color="#FF212720" Offset="0.52"/>
</LinearGradientBrush>
</StackPanel.Background>
<Image HorizontalAlignment="Left" Source="image/Append Or Save 3.png" Height="36" Width="203" />
<TextBlock HorizontalAlignment="Center" Width="145" Height="22" VerticalAlignment="Top" Margin="0,-31,-35,0" Text="Save Com F12" FontFamily="Tahoma" FontSize="14" Padding="0,4,0,0" Foreground="White" />
</StackPanel>
</Button>ente[![enter image description here][1]][1]r image description here
Perhaps uuid.uuid4()
might do the job. See uuid for more information.
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.
The easiest way to handle this is to rename the column, copy the data over, then drop the original column:
alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;
alter table EVAPP_FEES add AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_OLD;
alter table EVAPP_FEES drop column AMOUNT_OLD;
If you really want to retain the column ordering, you can move the data twice instead:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
It has already been answered, the best way work-around is to convert the Stored Procedure into an SQL Function or a View.
The short answer, just as mentioned above, is that you cannot directly JOIN a Stored Procedure in SQL, not unless you create another stored procedure or function using the stored procedure's output into a temporary table and JOINing the temporary table, as explained above.
I will answer this by converting your Stored Procedure into an SQL function and show you how to use it inside a query of your choice.
CREATE FUNCTION fnMyFunc()
RETURNS TABLE AS
RETURN
(
SELECT tenant.ID AS TenantID,
SUM(ISNULL(trans.Amount,0)) AS TenantBalance
FROM tblTenant tenant
LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
GROUP BY tenant.ID
)
Now to use that function, in your SQL...
SELECT t.TenantName,
t.CarPlateNumber,
t.CarColor,
t.Sex,
t.SSNO,
t.Phone,
t.Memo,
u.UnitNumber,
p.PropertyName
FROM tblTenant t
LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
LEFT JOIN tblProperty p ON u.PropertyID = p.ID
LEFT JOIN dbo.fnMyFunc() AS a
ON a.TenantID = t.TenantID
ORDER BY p.PropertyName, t.CarPlateNumber
If you wish to pass parameters into your function from within the above SQL, then I recommend you use CROSS APPLY
or CROSS OUTER APPLY
.
Read up on that here.
Cheers
I've seen this error in a similar situation to mentioned in Joe's answer:
description: Too high 5xx responses rate: {{ .Value }} > 0.05
We have a colon in description value. So, the problem is in missing quotes around description value. It can be resolved by adding quotes:
description: 'Too high 5xx responses rate: {{ .Value }} > 0.05'
The following is an easy method to convert dates to different formats.
// Create a new DateTime object
$date = DateTime::createFromFormat('Y-m-d', '2016-03-25');
// Output the date in different formats
echo $date->format('Y-m-d')."\n";
echo $date->format('d-m-Y')."\n";
echo $date->format('m-d-Y')."\n";
Setting the table's separatorStyle
to UITableViewCellSeparatorStyleNone
(in code or in IB) should do the trick.
I had this problem, a an AJAX Post request that returned some JSON would fail, eventually returning abort, with the:
SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3
error in the console. On other browsers (Chrome, Firefox, Safari) the exact same AJAX request was fine.
Tracked my issue down - investigation revealed that the response was missing the status code. In this case it should have been 500 internal error. This was being generated as part of a C# web application using service stack that requires an error code to be explicitly set.
IE seemed to leave the connection open to the server, eventually it timed out and it 'aborted' the request; despite receiving the content and other headers.
Perhaps there is an issue with how IE is handling the headers in posts.
Updating the web application to correctly return the status code fixed the issue.
Hope this helps someone!
The SQL:2003 standard changed some precedence rules so a JOIN statement takes precedence over a "comma" join. This can actually change the results of your query depending on how it is setup. This cause some problems for some people when MySQL 5.0.12 switched to adhering to the standard.
So in your example, your queries would work the same. But if you added a third table: SELECT ... FROM table1, table2 JOIN table3 ON ... WHERE ...
Prior to MySQL 5.0.12, table1 and table2 would be joined first, then table3. Now (5.0.12 and on), table2 and table3 are joined first, then table1. It doesn't always change the results, but it can and you may not even realize it.
I never use the "comma" syntax anymore, opting for your second example. It's a lot more readable anyway, the JOIN conditions are with the JOINs, not separated into a separate query section.
A much easier and shorted way which I am using to accomplish the same, using answer from another post, is like this:
var checkedCities = $('input[name=city]:checked').map(function() {
return this.value;
}).get();
Originally the cities are retrieved from a MySQL database, and looped in PHP while loop:
while ($data = mysql_fetch_assoc($all_cities)) {
<input class="city" name="city" id="<?php echo $data['city_name']; ?>" type="checkbox" value="<?php echo $data['city_id']; ?>" /><?php echo $data['city_name']; ?><br />
<?php } ?>
Now, using the above jQuery code, I get all the city_id values, and submit back to the database using $.get(...)
This has made my life so easy since now the code is fully dynamic. In order to add more cities, all I need to do is to add more cities in my database, and no worries on PHP or jQuery end.
The question says "How to declare array of zeros ..." but then the sample code references the Python list:
buckets = [] # this is a list
However, if someone is actually wanting to initialize an array, I suggest:
from array import array
my_arr = array('I', [0] * count)
The Python purist might claim this is not pythonic and suggest:
my_arr = array('I', (0 for i in range(count)))
The pythonic version is very slow and when you have a few hundred arrays to be initialized with thousands of values, the difference is quite noticeable.
U can also try this
$("#dialog").dialog({
autoOpen: false,
resizable: true,
height: 400,
width: 150,
position: 'center',
title: 'Term Sheet',
beforeClose: function(event, ui) {
console.log('Event Fire');
},
modal: true,
buttons: {
"Submit": function () {
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
JavaScript encodes strings as UTF-16, just like C#'s UnicodeEncoding
, so the byte arrays should match exactly using charCodeAt()
, and splitting each returned byte pair into 2 separate bytes, as in:
function strToUtf16Bytes(str) {
const bytes = [];
for (ii = 0; ii < str.length; ii++) {
const code = str.charCodeAt(ii); // x00-xFFFF
bytes.push(code & 255, code >> 8); // low, high
}
return bytes;
}
For example:
strToUtf16Bytes('');
// [ 60, 216, 53, 223 ]
However, If you want to get a UTF-8 byte array, you must transcode the bytes.
The solution feels somewhat non-trivial, but I used the code below in a high-traffic production environment with great success (original source).
Also, for the interested reader, I published my unicode helpers that help me work with string lengths reported by other languages such as PHP.
/**
* Convert a string to a unicode byte array
* @param {string} str
* @return {Array} of bytes
*/
export function strToUtf8Bytes(str) {
const utf8 = [];
for (let ii = 0; ii < str.length; ii++) {
let charCode = str.charCodeAt(ii);
if (charCode < 0x80) utf8.push(charCode);
else if (charCode < 0x800) {
utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
} else if (charCode < 0xd800 || charCode >= 0xe000) {
utf8.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
} else {
ii++;
// Surrogate pair:
// UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
// splitting the 20 bits of 0x0-0xFFFFF into two halves
charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff));
utf8.push(
0xf0 | (charCode >> 18),
0x80 | ((charCode >> 12) & 0x3f),
0x80 | ((charCode >> 6) & 0x3f),
0x80 | (charCode & 0x3f),
);
}
}
return utf8;
}
These answers are all very good, but I wanted to share another thing I discovered on stackoverflow that is really quite useful, here is the direct link
Basically, @DidzisElferts shows how you can get all the colours, coordinates, etc that ggplot uses to build a plot you created. Very nice!
p <- ggplot(mpg,aes(x=class,fill=class)) + geom_bar()
ggplot_build(p)$data
[[1]]
fill y count x ndensity ncount density PANEL group ymin ymax xmin xmax
1 #F8766D 5 5 1 1 1 1.111111 1 1 0 5 0.55 1.45
2 #C49A00 47 47 2 1 1 1.111111 1 2 0 47 1.55 2.45
3 #53B400 41 41 3 1 1 1.111111 1 3 0 41 2.55 3.45
4 #00C094 11 11 4 1 1 1.111111 1 4 0 11 3.55 4.45
5 #00B6EB 33 33 5 1 1 1.111111 1 5 0 33 4.55 5.45
6 #A58AFF 35 35 6 1 1 1.111111 1 6 0 35 5.55 6.45
7 #FB61D7 62 62 7 1 1 1.111111 1 7 0 62 6.55 7.45
Setting command timeout to 2 minutes.
scGetruntotals.CommandTimeout = 120;
but you can optimize your stored Procedures to decrease that time! like
A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).
Here is a test to prove this point:
div { border-color: blue; border-style: solid; margin: 2px; }
div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
Which gives the illusion that the last DIV
has a smaller border width, because the blue border blends more with the white background.
Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.
.container {
border-style: solid;
border-width: 1px;
margin-bottom: 10px;
}
.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
For me, view.window
is null on iOS 14.
extension UIViewController {
var topBarHeight: CGFloat {
var top = self.navigationController?.navigationBar.frame.height ?? 0.0
if #available(iOS 13.0, *) {
top += UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
} else {
top += UIApplication.shared.statusBarFrame.height
}
return top
}
}
The main difference is that Boolean is an object and boolean is an primitive.
Assuming you're referring to MS-DOS batch files: as it is simply a text file with a special extension, a .bat
file doesn't store an icon of its own.
You can, however, create a shortcut in the .lnk
format that stores an icon.
Pretty much all the answers currently add either leading spaces, trailing spaces or some other separator issue. To select from the fourth field where the separator is whitespace and the output separator is a single space using awk
would be:
awk '{for(i=4;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' file
To parametrize the starting field you could do:
awk '{for(i=n;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' n=4 file
And also the ending field:
awk '{for(i=n;i<=m=(m>NF?NF:m);i++)printf "%s",$i (i==m?ORS:OFS)}' n=4 m=10 file
The following are the ways to pass a arguments/parameters to function in C++.
1. by value.
// passing parameters by value . . .
void foo(int x)
{
x = 6;
}
2. by reference.
// passing parameters by reference . . .
void foo(const int &x) // x is a const reference
{
x = 6;
}
// passing parameters by const reference . . .
void foo(const int &x) // x is a const reference
{
x = 6; // compile error: a const reference cannot have its value changed!
}
3. by object.
class abc
{
display()
{
cout<<"Class abc";
}
}
// pass object by value
void show(abc S)
{
cout<<S.display();
}
// pass object by reference
void show(abc& S)
{
cout<<S.display();
}
Basically speaking, the answer is: it depends. There are many many benchmarks focusing on different kinds of application.
My benchmark on my app is: gcc > icc > clang.
There are rare IO, but many CPU float and data structure operations.
compile flags is -Wall -g -DNDEBUG -O3.
https://github.com/zhangyafeikimi/ml-pack/blob/master/gbdt/profile/benchmark
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
strtotime()
, as in date("F j, Y", strtotime("yesterday"));
def touch(fname):
if os.path.exists(fname):
os.utime(fname, None)
else:
open(fname, 'a').close()
Multiple people have put the answer to this simple problem up here, but I have one thing to add, considering how frustrated I was until I figured out what I was doing wrong.
As mentioned the most straightforward way to do this is like so..
html {
position: relative;
min-height: 100%;
}
body {
background-color: transparent;
position: static;
height: 100%;
margin-bottom: 30px;
}
.site-footer {
position: absolute;
height: 30px;
bottom: 0px;
left: 0px;
right: 0px;
}
However the property not mentioned in posts, presumably because it is usually default, is the position: static on the body tag. Position relative will not work!
My wordpress theme had overridden the default body display and it confused me for an obnoxiously long time.
A simple but effective technique, is to use the filter
method in combination with the filter function(value, index){ return this.indexOf(value) == index }
.
var data = [2,3,4,5,5,4];_x000D_
var filter = function(value, index){ return this.indexOf(value) == index };_x000D_
var filteredData = data.filter(filter, data );_x000D_
_x000D_
document.body.innerHTML = '<pre>' + JSON.stringify(filteredData, null, '\t') + '</pre>';
_x000D_
See also this Fiddle.
Not sure about Win but n *nix (OS X, Linux, etc.) its in ~/.subversion
Because, at least in HTML 4.01 and XHTML 1(.1), the type
attribute for <script>
elements is required.
In HTML 5, type
is no longer required.
In fact, while you should use text/javascript
in your HTML source, many servers will send the file with Content-type: application/javascript
. Read more about these MIME types in RFC 4329.
Notice the difference between RFC 4329, that marked text/javascript
as obsolete and recommending the use of application/javascript
, and the reality in which some browsers freak out on <script>
elements containing type="application/javascript"
(in HTML source, not the HTTP Content-type header of the file that gets send). Recently, there was a discussion on the WHATWG mailing list about this discrepancy (HTML 5's type
defaults to text/javascript
), read these messages with subject Will you consider about RFC 4329?
The FOR loop worked well, I modified it a tiny bit:
#include<iostream>
using namespace std;
int main ()
{
int sum = 0;
int number;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout << "Enter number: \n";
cin >> number;
sum=sum+number;
}
cout<<"sum is: "<< sum<<endl;
}
HOWEVER, the WHILE loop has got some errors on line 11 (Count was not declared in this scope). What could be the issue? Also, if you would have a solution using DO,WHILE loop it would be wonderful. Thanks
You Could remove old reference of provisioning file. Then after import new provisioning Profile and selecting Xcode builder.
I used this for getting Date and Time in a fragment.
private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_head_screen, container, false);
dateTextView = root.findViewById(R.id.dateView);
hourTv = root.findViewById(R.id.hourView);
Thread thread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
//Calendario para obtener fecha & hora
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");
String currentDate = date_sdf.format(currentTime);
String currentHour = hour_sdf.format(currentTime);
dateTextView.setText(currentDate);
hourTv.setText(currentHour);
}
});
}
} catch (InterruptedException e) {
Log.v("InterruptedException", e.getMessage());
}
}
};
}
Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.
PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name")
This solution doesn't require you to put a scrollable class on all your scrollable divs so is more general. Scrolling is allowed on all elements which are, or are children of, INPUT elements contenteditables and overflow scroll or autos.
I use a custom selector and I also cache the result of the check in the element to improve performance. No need to check the same element every time. This may have a few issues as only just written but thought I'd share.
$.expr[':'].scrollable = function(obj) {
var $el = $(obj);
var tagName = $el.prop("tagName");
return (tagName !== 'BODY' && tagName !== 'HTML') && (tagName === 'INPUT' || $el.is("[contentEditable='true']") || $el.css("overflow").match(/auto|scroll/));
};
function preventBodyScroll() {
function isScrollAllowed($target) {
if ($target.data("isScrollAllowed") !== undefined) {
return $target.data("isScrollAllowed");
}
var scrollAllowed = $target.closest(":scrollable").length > 0;
$target.data("isScrollAllowed",scrollAllowed);
return scrollAllowed;
}
$('body').bind('touchmove', function (ev) {
if (!isScrollAllowed($(ev.target))) {
ev.preventDefault();
}
});
}
If you are using this to get a LINQ to SQL which I do and wanted for my Visual Developer, 1) get the free Visual WEB Developer, use that to connect to SQL Server instance, create your LINQ interface, then copy the generated files into your Vis-Dev project (I don't use VD because it sounds funny). Include only the *.dbml files. The Vis-Dev environment will take a second or two to recognize the supporting files. It is a little extra step but for sure better than doing it by hand or giving up on it altogether or EVEN WORSE, paying for it. Mooo ha ha haha.
This can also happen if you don't have Modify permissions on the symbol cache directory configured in Tools, Options, Debugging, Symbols.
i want to replace last ',' with space
if (fieldName.endsWith(",")) {
fieldName = fieldName.substring(0, fieldName.length() - 1) + " ";
}
If you want to remove the trailing comma, simply get rid of the + " "
.
Try below code snippet
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
/* This is one ajax call */
}
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
What worked for me was excluding the hamcrest group from the junit test compile.
Here is the code from my build.gradle:
testCompile ('junit:junit:4.11') {
exclude group: 'org.hamcrest'
}
If you're running IntelliJ you may need to run gradle cleanIdea idea clean build
to detect the dependencies again.
In android studio add/change this line at the end of gradle.properties (Global Properties)
:
...
org.gradle.jvmargs=-XX\:MaxHeapSize\=1024m -Xmx1024m
if it doesn't work you can retry with bigger than 1024 heap size.
a few other managed wrappers for you to check out
Writing your own interop wrappers can be a time-consuming and difficult process in .NET. There are some advantages to writing a C++ library for the interop - particularly as it allows you to greatly simplify the interface that the C# code. However, if you are only needing a subset of the library, it might make your life easier to just do the interop in C#.
By "constant reference" I am guessing you really mean "reference to constant data". Pointers on the other hand, can be a constant pointer (the pointer itself is constant, not the data it points to), a pointer to constant data, or both.
If you have control over the structure of the list, the most pythonic thing to do would probably be to change it from:
l=[1,2,3,4]
to:
l=[(1,2),(3,4)]
Then, your loop would be:
for i,j in l:
print i, j
Here's the current (September 2018) extensions for running Python code:
Official Python extension: This is a must install.
Code Runner: Incredibly useful for all sorts of languages, not just Python. I would highly recommend installing.
AREPL: Real-time Python scratchpad that displays your variables in a side window. I'm the creator of this, so obviously I think it's great, but I can't give a unbiased opinion ¯\(?)/¯
Wolf: Real-time Python scratchpad that displays results inline
And of course if you use the integrated terminal you can run Python code in there and not have to install any extensions.
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
There is no direct string compare function in SQL Server
CASE
WHEN str1 = str2 THEN 0
WHEN str1 < str2 THEN -1
WHEN str1 > str2 THEN 1
ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END
Notes
select a.orgName,b.duplicate, a.id
from organizations a
inner join (
SELECT orgName, COUNT(*) AS duplicate
FROM organizations
GROUP BY orgName
HAVING COUNT(*) > 1
) b on o.orgName = oc.orgName
group by a.orgName,a.id
you can extend LinkedHashSet
adding your desired getIndex()
method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));
The above answer shows it for today
Little performance tip if somebody has a datastore kind of service with key -> value pairs:
If you have a service called dataStore, you can update a timestamp whenever your big data object changes. This way instead of deep watching the whole object, you are only watching a timestamp for change.
app.factory('dataStore', function () {
var store = { data: [], change: [] };
// when storing the data, updating the timestamp
store.setData = function(key, data){
store.data[key] = data;
store.setChange(key);
}
// get the change to watch
store.getChange = function(key){
return store.change[key];
}
// set the change
store.setChange = function(key){
store.change[key] = new Date().getTime();
}
});
And in a directive you are only watching the timestamp to change
app.directive("myDir", function ($scope, dataStore) {
$scope.dataStore = dataStore;
$scope.$watch('dataStore.getChange("myKey")', function(newVal, oldVal){
if(newVal !== oldVal && newVal){
// Data changed
}
});
});
How about converting the integer to a binary string and count the ones?
php solution:
substr_count( decbin($integer), '1' );
replace(ltrim(replace(Fieldname.TableName, '0', '')), '', '0')
The suggestion from Thomas G worked for our needs.
The field in our case was already string and only the leading zeros needed to be trimmed. Mostly it's all numeric but sometimes there are letters so the previous INT conversion would crash.
If you are a regular Eclipse user than you might have got this error many times. The error simply says, “you’ve made changes in files in your workspace from outside eclipse”. The simplest solution would be to select the project and press F5 (Right click -> Refresh).
if you need more explanation you can read from this web site
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
every minute:
* * * * * /path/to/php /var/www/html/a.php
every 24hours (every midnight):
0 0 * * * /path/to/php /var/www/html/reset.php
See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml
A portable approach that works equally well on Linux or Windows (where there is no /dev/null):
echo | gcc -dM -E -
For c++ you may use (replace c++11
with whatever version you use):
echo | gcc -x c++ -std=c++11 -dM -E -
It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters
). If you want to know what defines are added when you include a header file you can use -dD
option which is similar to -dM but does not include predefined macros:
echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -
Note, however, that empty input still produces lots of defines with -dD
option.
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
To get bytes back just:
new BigInteger(bytes).toByteArray()
If I'm not mislead, you just need to set your local branches to track their pairs in the origin server.
Using your command line, you can try
git checkout mybranch
git branch --set-upstream-to=origin/mybranch
That will configure something as an equivalent of your local branch in the server. I'll bet that Android Studio is complaining about the lack of that.
If someone knows how to do this using the GUI of that IDE, that would be interesting to read. :)
First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.
If not you have some compilation errors in your java classes.
According to the Python doc, we can also use class.__mro__
attribute or class.mro()
method:
class Suit:
pass
class Heart(Suit):
pass
class Spade(Suit):
pass
class Diamond(Suit):
pass
class Club(Suit):
pass
>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)
Suit in Heart.mro() # True
object in Heart.__mro__ # True
Spade in Heart.mro() # False
Like pretty much everyone has stated already:
A period (.
) indicates a class, and a hash (#
) indicates an ID.
The fundamental difference between is that you can reuse a class on your page over and over, whereas an ID can be used once. That is, of course, if you are sticking to WC3 standards.
A page will still render if you have multiple elements with the same ID, but you will run into problems if/when you try to dynamically update said elements by calling them with their ID, since they are not unique.
It is also useful to note that ID properties will supersede class properties.
On my machine, port is in /opt/local/bin/port
- try typing that into a terminal on its own.
You need to stop the submission if an error occured:
HTML
<form name ="myform" onsubmit="return validation();">
JS
if (document.myform.username.value == "") {
document.getElementById('errors').innerHTML="*Please enter a username*";
return false;
}
Here's the signature.
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
What you are doing is mixing the values
and the htmlAttributes
together. values
are for URL routing.
You might want to do this.
@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null,
new { @style="text-transform:capitalize;" });
This code works for me
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:X-HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Also, you can create your own outerHeight
for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle
, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
You can simply use this bootstrap helper to dialogs (only 5 kB)
it has support for ajax request, iframes, common dialogs, confirm and prompt!
you can use it as:
eModal.iframe('http://someUrl.com', 'This is a tile for iframe', callbackIfNeeded);
eModal.alert('The message', 'This title');
eModal.ajax('/mypage.html', 'This is a ajax', callbackIfNeeded);
eModal.confirm('the question', 'The title', theMandatoryCallback);
eModal.prompt('Form question', 'This is a ajax', theMandatoryCallback);
this provide a loading progress while loading the iframe!
No html required.
You can use a object literal as parameter to extra options.
Check the site form more details.
best,
You can implement like a below logic. Suppose you want an array of values.
let test = [ {name:'test',lastname:'kumar',age:30},
{name:'test',lastname:'kumar',age:30},
{name:'test3',lastname:'kumar',age:47},
{name:'test',lastname:'kumar',age:28},
{name:'test4',lastname:'kumar',age:30},
{name:'test',lastname:'kumar',age:29}]
let result1 = test.map(element =>
{
if (element.age === 30)
{
return element.lastname;
}
}).filter(notUndefined => notUndefined !== undefined);
output : ['kumar','kumar','kumar']
I am using an older Data Structure and Algs book that comes with Java Applets for practice. So I needed to store and run some applets locally. I am currently running Windows 10 OS with Edge, Chrome, and IE 11.
Running applets seem to only be allowed in IE11, and as other have mentioned you have to add the applet to the exception list. My issue was since I am storing these locally, and opening them in IE, it opened with path starting with "C:\..." Adding the full path using, "file///..." like mentioned in one of the other answers didn't work for me.
The fix: So, I just added(without the quotes), "file:///" to the exception site list and finally got it working. This also allows me to run any applet stored locally, and I do not have to explicitly add an exception for each applet path.
I plan to remove the exception from the list once I am done using the programs, and only add it back as necessary.
#!/bin/sh
as most scripts do not need specific bash feature and should be written for sh.
Also, this makes scripts work on the BSDs, which do not have bash per default.
If your columns should not contain NULL
values, you need to define the columns as NOT NULL
as well, otherwise the passed in NULL
will be used instead of the default and not produce an error.
If you don't pass in any value to these fields (which requires you to specify the fields that you do want to use), the defaults will be used:
INSERT INTO
table1 (field1, field3)
VALUES (5,10)
For your reference, I believe you can "hard cut" commits out of your current branch not only with git reset --hard, but also with the following command:
git checkout -B <branch-name> <SHA>
In fact, if you don't care about checking out, you can set the branch to whatever you want with:
git branch -f <branch-name> <SHA>
This would be a programmatic way to remove commits from a branch, for instance, in order to copy new commits to it (using rebase).
Suppose you have a branch that is disconnected from master because you have taken sources from some other location and dumped it into the branch.
You now have a branch in which you have applied changes, let's call it "topic".
You will now create a duplicate of your topic branch and then rebase it onto the source code dump that is sitting in branch "dump":
git branch topic_duplicate topic
git rebase --onto dump master topic_duplicate
Now your changes are reapplied in branch topic_duplicate based on the starting point of "dump" but only the commits that have happened since "master". So your changes since master are now reapplied on top of "dump" but the result ends up in "topic_duplicate".
You could then replace "dump" with "topic_duplicate" by doing:
git branch -f dump topic_duplicate
git branch -D topic_duplicate
Or with
git branch -M topic_duplicate dump
Or just by discarding the dump
git branch -D dump
Perhaps you could also just cherry-pick after clearing the current "topic_duplicate".
What I am trying to say is that if you want to update the current "duplicate" branch based off of a different ancestor you must first delete the previously "cherrypicked" commits by doing a git reset --hard <last-commit-to-retain>
or git branch -f topic_duplicate <last-commit-to-retain>
and then copying the other commits over (from the main topic branch) by either rebasing or cherry-picking.
Rebasing only works on a branch that already has the commits, so you need to duplicate your topic branch each time you want to do that.
Cherrypicking is much easier:
git cherry-pick master..topic
So the entire sequence will come down to:
git reset --hard <latest-commit-to-keep>
git cherry-pick master..topic
When your topic-duplicate branch has been checked out. That would remove previously-cherry-picked commits from the current duplicate, and just re-apply all of the changes happening in "topic" on top of your current "dump" (different ancestor). It seems a reasonably convenient way to base your development on the "real" upstream master while using a different "downstream" master to check whether your local changes also still apply to that. Alternatively you could just generate a diff and then apply it outside of any Git source tree. But in this way you can keep an up-to-date modified (patched) version that is based on your distribution's version while your actual development is against the real upstream master.
So just to demonstrate:
Hope this helps someone. I was meaning to rewrite this, but I cannot manage now. Regards.
Yes.
It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.
The following example will show you the use of multiple classes.
The first class makes the text color
red.
The second class makes the background-color
blue.
See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.
Result: multiple CSS statements in different classes will stack up.
You can read more about CSS Specificity.
.class1 {
color:red;
}
.class2 {
background-color:blue;
}
<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>
I have been researching this for a few days, following endless leads that got close, but not quite, to what I was after.
My need is for a simple list of 'symbol, sector, industry'. I'm working in Java and don't want to use any platform native code.
It seems that most other data, like quotes, etc., is readily available.
Finally, followed a suggestion to look at 'finviz.com'. Looks like just the ticket. Try using the following:
http://finviz.com/export.ashx?v=111&t=aapl,cat&o=ticker This comes back as lines, csv style, with a header row, ordered by ticker symbol. You can keep adding tickers. In code, you can read the stream. Or you can let the browser ask you whether to open or save the file.
http://finviz.com/export.ashx?v=111&&o=ticker Same csv style, but pulls all available symbols (a lot, across global exchanges)
Replace 'export' with 'screener' and the data will show up in the browser.
There are many more options you can use, one for every screener element on the site.
So far, this is the most powerful and convenient programmatic way to get the few pieces of data I couldn't otherwise seem to easily get. And, it looks like this site could well be a single source for most of what you might need other than real- or near-real-time quotes.
OpenURI is the best; it's as simple as
require 'open-uri'
response = open('http://example.com').read
It should be like import package_name.Class_Name
--> If you want to import a specific class
(or)
import package_name.*
--> To import all classes in a package
The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.
Once changing this value to DEFAULT, run the following command:
/usr/bin/update-crypto-policies --set DEFAULT
Rerun the curl command and it should work.
As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.
var json = jQuery.parseJSON(s); //If you have jQuery.
Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
Change the above code to
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
Eg:
$(document).ready(function() {
var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
s = jQuery.parseJSON(s);
alert( s[0]["Select"] );
});
And then use the parse function. It'll surely work.
EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON
Edit (30 April 2020):
Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")
The following does not return a response:
You must return anything like return afunction()
or return 'a string'
.
This can solve the issue
Best way is to handle this in an Ant script. You can create 2 different tasks for the 2 jar files. Specify class A as the main class in the manifst file for the first jar. similarly specify class B as the main class in the manifest file for the second jar.
you can easily run the Ant tasks from Netbeans.
Excel 2010 driver is 64 bit, while the default SSMS import export wizard is 32 therefore the error message.
You can import using the Import Export Data (64 bit) tool. ("C:\Program Files\Microsoft SQL Server\110\DTS\Binn\DTSWizard.exe") notice the path is not Program Files x86.
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
left: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
This isn't part of numpy
, but it will work with numpy.ndarray
objects. A numpy.matrix
can be converted to a numpy.ndarray
and a numpy.ndarray
can be converted to a numpy.matrix
.
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(A, B)
See Scikit Learn mean_squared_error for documentation on how to control axis.
Your quotes are in the wrong spot. Here's a simple example:
<div style={{backgroundColor: "#FF0000"}}>red</div>
If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
});
Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)
Well, I think it would be a bad idea to replicate the code which is already present in classes like SimpleDateFormat
.
On the other hand, personally I'd suggest avoiding Calendar
and Date
entirely if you can, and using Joda Time instead, as a far better designed date and time API. For example, you need to be aware that SimpleDateFormat
is not thread-safe, so you either need thread-locals, synchronization, or a new instance each time you use it. Joda parsers and formatters are thread-safe.
I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:
import numpy as np
from sklearn import linear_model
from sklearn import svm
classifiers = [
svm.SVR(),
linear_model.SGDRegressor(),
linear_model.BayesianRidge(),
linear_model.LassoLars(),
linear_model.ARDRegression(),
linear_model.PassiveAggressiveRegressor(),
linear_model.TheilSenRegressor(),
linear_model.LinearRegression()]
trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ])
trainingScores = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData = np.array([ [2.5, 2.4, 2.7], [2.7, 3.2, 1.2] ])
for item in classifiers:
print(item)
clf = item
clf.fit(trainingData, trainingScores)
print(clf.predict(predictionData),'\n')
If you are allowing anonymous users as well as those logged in with email you can use firebase.auth().currentUser.isAnonymous
, which will return either true
or false
.
Watermark solution in the original post works great. Thanks for it. In case anyone needs it, here is an angular directive for it.
(function () {
'use strict';
angular.module('app')
.directive('placeholder', function () {
return {
restrict: 'A',
link: function (scope, element, attributes) {
if (element.prop('nodeName') === 'TEXTAREA') {
var placeholderText = attributes.placeholder.trim();
if (placeholderText.length) {
// support for both '\n' symbol and an actual newline in the placeholder element
var placeholderLines = Array.prototype.concat
.apply([], placeholderText.split('\n').map(line => line.split('\\n')))
.map(line => line.trim());
if (placeholderLines.length > 1) {
element.watermark(placeholderLines.join('<br>\n'));
}
}
}
}
};
});
}());
From the documentation of the HttpWebRequest.Timeout property:
A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.
Is it possible that your DNS query is the cause of the timeout?
Easy way by using commons-lang-2.3.jar that library of java to clone list
link download commons-lang-2.3.jar
How to use
oldList.........
List<YourObject> newList = new ArrayList<YourObject>();
foreach(YourObject obj : oldList){
newList.add((YourObject)SerializationUtils.clone(obj));
}
I hope this one can helpful.
:D
Sometimes you just don't have a choice about having to store numbers mixed with text. In one of our applications, the web site host we use for our e-commerce site makes filters dynamically out of lists. There is no option to sort by any field but the displayed text. When we wanted filters built off a list that said things like 2" to 8" 9" to 12" 13" to 15" etc, we needed it to sort 2-9-13, not 13-2-9 as it will when reading the numeric values. So I used the SQL Server Replicate function along with the length of the longest number to pad any shorter numbers with a leading space. Now 20 is sorted after 3, and so on.
I was working with a view that gave me the minimum and maximum lengths, widths, etc for the item type and class, and here is an example of how I did the text. (LBnLow and LBnHigh are the Low and High end of the 5 length brackets.)
REPLICATE(' ', LEN(LB5Low) - LEN(LB1High)) + CONVERT(NVARCHAR(4), LB1High) + '" and Under' AS L1Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB2Low)) + CONVERT(NVARCHAR(4), LB2Low) + '" to ' + CONVERT(NVARCHAR(4), LB2High) + '"' AS L2Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB3Low)) + CONVERT(NVARCHAR(4), LB3Low) + '" to ' + CONVERT(NVARCHAR(4), LB3High) + '"' AS L3Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB4Low)) + CONVERT(NVARCHAR(4), LB4Low) + '" to ' + CONVERT(NVARCHAR(4), LB4High) + '"' AS L4Text,
CONVERT(NVARCHAR(4), LB5Low) + '" and Over' AS L5Text
If you're targeting browsers supporting flexible boxes you could do the following.. http://jsfiddle.net/meyertee/AH3pE/
HTML
<div class="container">
<header><h1>Header</h1></header>
<div class="body">Body</div>
<footer><h3>Footer</h3></footer>
</div>
CSS
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
flex-wrap: nowrap;
}
header {
flex-shrink: 0;
}
.body{
flex-grow: 1;
overflow: auto;
min-height: 2em;
}
footer{
flex-shrink: 0;
}
Update:
See "Can I use" for browser support of flexible boxes.
Just a note that all the above may not work for you with tomcat7 unless you've also done this:
sudo apt-get install tomcat7-admin
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
To be able to build with C# 6 syntax use this in path:
C:\Program Files (x86)\MSBuild\14.0\Bin
The nodejs package tecfu/tty-table can be globally installed to do precisely this:
apt-get install nodejs
npm i -g tty-table
cat data.csv | tty-table
It can also handle streams.
For more info, see the docs for terminal usage here.
The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:
I've made an example for you showing how this could be done.
Notice the js but also that I changed #value into an input element
<input id="value" type="hidden" style="width:300px"/>
and that I am triggering the change
event for getting the initial values
$('#attribute').select2().on('change', function() {
$('#value').select2({data:data[$(this).val()]});
}).trigger('change');
Edit:
In the current version of select2 the class attribute is being transferred from the hidden input into the root element created by select2, even the select2-offscreen
class which positions the element way outside the page limits.
To fix this problem all that's needed is to add removeClass('select2-offscreen')
before applying select2 a second time on the same element.
$('#attribute').select2().on('change', function() {
$('#value').removeClass('select2-offscreen').select2({data:data[$(this).val()]});
}).trigger('change');
I've added a new Code Example to address this issue.
Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:
why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.
Solution:
check write permissions on registers
a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it
b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log
c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"
d. run the following command netsh int ipv6 reset reset.log
and repeat step c)
unistall all not-working miniports
a. go to device managers (windows+x -> device manager)
b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)
c. unistall these not working devices
d. reboot your computer
e. Repeat steps a) - d) until you will not see any yellow mark on miniports
delete your vpn connection and create a new one.
that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)
references:
I ended up finding MinimalistTelnet and adapted it to my uses. I ended up needing to be able to heavily modify the code due to the unique** device that I am attempting to attach to.
** Unique in this instance can be validly interpreted as brain-dead.
These examples cover the three types of shifts applied to both a positive and a negative number:
// Signed left shift on 626348975
00100101010101010101001110101111 is 626348975
01001010101010101010011101011110 is 1252697950 after << 1
10010101010101010100111010111100 is -1789571396 after << 2
00101010101010101001110101111000 is 715824504 after << 3
// Signed left shift on -552270512
11011111000101010000010101010000 is -552270512
10111110001010100000101010100000 is -1104541024 after << 1
01111100010101000001010101000000 is 2085885248 after << 2
11111000101010000010101010000000 is -123196800 after << 3
// Signed right shift on 626348975
00100101010101010101001110101111 is 626348975
00010010101010101010100111010111 is 313174487 after >> 1
00001001010101010101010011101011 is 156587243 after >> 2
00000100101010101010101001110101 is 78293621 after >> 3
// Signed right shift on -552270512
11011111000101010000010101010000 is -552270512
11101111100010101000001010101000 is -276135256 after >> 1
11110111110001010100000101010100 is -138067628 after >> 2
11111011111000101010000010101010 is -69033814 after >> 3
// Unsigned right shift on 626348975
00100101010101010101001110101111 is 626348975
00010010101010101010100111010111 is 313174487 after >>> 1
00001001010101010101010011101011 is 156587243 after >>> 2
00000100101010101010101001110101 is 78293621 after >>> 3
// Unsigned right shift on -552270512
11011111000101010000010101010000 is -552270512
01101111100010101000001010101000 is 1871348392 after >>> 1
00110111110001010100000101010100 is 935674196 after >>> 2
00011011111000101010000010101010 is 467837098 after >>> 3
export const a = 1;
export const b = 2;
export const c = 3;
This will work w/ Babel transforms today and should take advantage of all the benefits of ES2016 modules whenever that feature actually lands in a browser.
You can also add export default {a, b, c};
which will allow you to import all the values as an object w/o the * as
, i.e. import myModule from 'my-module';
Sources:
I would like to suggest to use a single RecyclerView
and populate your list items dynamically. I've added a github project to describe how this can be done. You might have a look. While the other solutions will work just fine, I would like to suggest, this is a much faster and efficient way of showing multiple lists in a RecyclerView
.
The idea is to add logic in your onCreateViewHolder
and onBindViewHolder
method so that you can inflate proper view for the exact positions in your RecyclerView
.
I've added a sample project along with that wiki too. You might clone and check what it does. For convenience, I am posting the adapter that I have used.
public class DynamicListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int FOOTER_VIEW = 1;
private static final int FIRST_LIST_ITEM_VIEW = 2;
private static final int FIRST_LIST_HEADER_VIEW = 3;
private static final int SECOND_LIST_ITEM_VIEW = 4;
private static final int SECOND_LIST_HEADER_VIEW = 5;
private ArrayList<ListObject> firstList = new ArrayList<ListObject>();
private ArrayList<ListObject> secondList = new ArrayList<ListObject>();
public DynamicListAdapter() {
}
public void setFirstList(ArrayList<ListObject> firstList) {
this.firstList = firstList;
}
public void setSecondList(ArrayList<ListObject> secondList) {
this.secondList = secondList;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// List items of first list
private TextView mTextDescription1;
private TextView mListItemTitle1;
// List items of second list
private TextView mTextDescription2;
private TextView mListItemTitle2;
// Element of footer view
private TextView footerTextView;
public ViewHolder(final View itemView) {
super(itemView);
// Get the view of the elements of first list
mTextDescription1 = (TextView) itemView.findViewById(R.id.description1);
mListItemTitle1 = (TextView) itemView.findViewById(R.id.title1);
// Get the view of the elements of second list
mTextDescription2 = (TextView) itemView.findViewById(R.id.description2);
mListItemTitle2 = (TextView) itemView.findViewById(R.id.title2);
// Get the view of the footer elements
footerTextView = (TextView) itemView.findViewById(R.id.footer);
}
public void bindViewSecondList(int pos) {
if (firstList == null) pos = pos - 1;
else {
if (firstList.size() == 0) pos = pos - 1;
else pos = pos - firstList.size() - 2;
}
final String description = secondList.get(pos).getDescription();
final String title = secondList.get(pos).getTitle();
mTextDescription2.setText(description);
mListItemTitle2.setText(title);
}
public void bindViewFirstList(int pos) {
// Decrease pos by 1 as there is a header view now.
pos = pos - 1;
final String description = firstList.get(pos).getDescription();
final String title = firstList.get(pos).getTitle();
mTextDescription1.setText(description);
mListItemTitle1.setText(title);
}
public void bindViewFooter(int pos) {
footerTextView.setText("This is footer");
}
}
public class FooterViewHolder extends ViewHolder {
public FooterViewHolder(View itemView) {
super(itemView);
}
}
private class FirstListHeaderViewHolder extends ViewHolder {
public FirstListHeaderViewHolder(View itemView) {
super(itemView);
}
}
private class FirstListItemViewHolder extends ViewHolder {
public FirstListItemViewHolder(View itemView) {
super(itemView);
}
}
private class SecondListHeaderViewHolder extends ViewHolder {
public SecondListHeaderViewHolder(View itemView) {
super(itemView);
}
}
private class SecondListItemViewHolder extends ViewHolder {
public SecondListItemViewHolder(View itemView) {
super(itemView);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
if (viewType == FOOTER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_footer, parent, false);
FooterViewHolder vh = new FooterViewHolder(v);
return vh;
} else if (viewType == FIRST_LIST_ITEM_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list, parent, false);
FirstListItemViewHolder vh = new FirstListItemViewHolder(v);
return vh;
} else if (viewType == FIRST_LIST_HEADER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list_header, parent, false);
FirstListHeaderViewHolder vh = new FirstListHeaderViewHolder(v);
return vh;
} else if (viewType == SECOND_LIST_HEADER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list_header, parent, false);
SecondListHeaderViewHolder vh = new SecondListHeaderViewHolder(v);
return vh;
} else {
// SECOND_LIST_ITEM_VIEW
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list, parent, false);
SecondListItemViewHolder vh = new SecondListItemViewHolder(v);
return vh;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
if (holder instanceof SecondListItemViewHolder) {
SecondListItemViewHolder vh = (SecondListItemViewHolder) holder;
vh.bindViewSecondList(position);
} else if (holder instanceof FirstListHeaderViewHolder) {
FirstListHeaderViewHolder vh = (FirstListHeaderViewHolder) holder;
} else if (holder instanceof FirstListItemViewHolder) {
FirstListItemViewHolder vh = (FirstListItemViewHolder) holder;
vh.bindViewFirstList(position);
} else if (holder instanceof SecondListHeaderViewHolder) {
SecondListHeaderViewHolder vh = (SecondListHeaderViewHolder) holder;
} else if (holder instanceof FooterViewHolder) {
FooterViewHolder vh = (FooterViewHolder) holder;
vh.bindViewFooter(position);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
int firstListSize = 0;
int secondListSize = 0;
if (secondList == null && firstList == null) return 0;
if (secondList != null)
secondListSize = secondList.size();
if (firstList != null)
firstListSize = firstList.size();
if (secondListSize > 0 && firstListSize > 0)
return 1 + firstListSize + 1 + secondListSize + 1; // first list header, first list size, second list header , second list size, footer
else if (secondListSize > 0 && firstListSize == 0)
return 1 + secondListSize + 1; // second list header, second list size, footer
else if (secondListSize == 0 && firstListSize > 0)
return 1 + firstListSize; // first list header , first list size
else return 0;
}
@Override
public int getItemViewType(int position) {
int firstListSize = 0;
int secondListSize = 0;
if (secondList == null && firstList == null)
return super.getItemViewType(position);
if (secondList != null)
secondListSize = secondList.size();
if (firstList != null)
firstListSize = firstList.size();
if (secondListSize > 0 && firstListSize > 0) {
if (position == 0) return FIRST_LIST_HEADER_VIEW;
else if (position == firstListSize + 1)
return SECOND_LIST_HEADER_VIEW;
else if (position == secondListSize + 1 + firstListSize + 1)
return FOOTER_VIEW;
else if (position > firstListSize + 1)
return SECOND_LIST_ITEM_VIEW;
else return FIRST_LIST_ITEM_VIEW;
} else if (secondListSize > 0 && firstListSize == 0) {
if (position == 0) return SECOND_LIST_HEADER_VIEW;
else if (position == secondListSize + 1) return FOOTER_VIEW;
else return SECOND_LIST_ITEM_VIEW;
} else if (secondListSize == 0 && firstListSize > 0) {
if (position == 0) return FIRST_LIST_HEADER_VIEW;
else return FIRST_LIST_ITEM_VIEW;
}
return super.getItemViewType(position);
}
}
There is another way of keeping your items in a single ArrayList
of objects so that you can set an attribute tagging the items to indicate which item is from first list and which one belongs to second list. Then pass that ArrayList
into your RecyclerView
and then implement the logic inside adapter to populate them dynamically.
Hope that helps.
For your code to compile you need to cast the result to an int.
int abc = (int) (Math.random() * 100);
However, if you instead use the java.util.Random class it has built in method for you
Random random = new Random();
int abc = random.nextInt(100);
Like the others have said there is no way to do this, but if you're using Sql Server a trick that I use is to change the output to comma separated, then do
select top 1 * from table
and cut the whole list of columns from the output window. Then you can choose which columns you want without having to type them all in.
You need to add your ORACLE_HOME
definition in your listener.ora file. Right now its not registered with any ORACLE_HOME
.
Sample listener.ora
abc =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
)
)
SID_LIST_abc =
(SID_LIST =
(SID_DESC =
(ORACLE_HOME= /abc/DbTier/11.2.0)
(SID_NAME = abc)
)
)
What do you mean timestamp? If you mean milliseconds since the Unix epoch:
GregorianCalendar cal = new GregorianCalendar(2007, 9 - 1, 23);
long millis = cal.getTimeInMillis();
If you want an actual java.sql.Timestamp object:
Timestamp ts = new Timestamp(millis);
axios signature for post is axios.post(url[, data[, config]])
. So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
I had the same error and fixed it. It turned out to be a silly reason.
This was the culprit:
<script src="app.js"/>
Fix:
<script src="app.js"></script>
Make sure your script tag is ended properly!
I am set Tooltips On My Working Project That Is 100% Working
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
.tooltip {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border-bottom: 1px dotted black;_x000D_
}_x000D_
_x000D_
.tooltip .tooltiptext {_x000D_
visibility: hidden;_x000D_
width: 120px;_x000D_
background-color: black;_x000D_
color: #fff;_x000D_
text-align: center;_x000D_
border-radius: 6px;_x000D_
padding: 5px 0;_x000D_
_x000D_
/* Position the tooltip */_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
visibility: visible;_x000D_
}_x000D_
.size_of_img{_x000D_
width:90px}_x000D_
</style>_x000D_
_x000D_
<body style="text-align:center;">_x000D_
_x000D_
<p>Move the mouse over the text below:</p>_x000D_
_x000D_
<div class="tooltip"><img class="size_of_img" src="https://babeltechreviews.com/wp-content/uploads/2018/07/rendition1.img_.jpg" alt="Image 1" /><span class="tooltiptext">grewon.pdf</span></div>_x000D_
_x000D_
<p>Note that the position of the tooltip text isn't very good. Check More Position <a href="https://www.w3schools.com/css/css_tooltip.asp">GO</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The at
command exists specifically for this purpose (unlike cron
which is intended for scheduling recurring tasks).
at $(cat file) </path/to/script
We can easily create and export/download the excel file with any separator (in this answer I am using the comma separator) using javascript. I am not using any external package for creating the excel file.
var Head = [[_x000D_
'Heading 1',_x000D_
'Heading 2', _x000D_
'Heading 3', _x000D_
'Heading 4'_x000D_
]];_x000D_
_x000D_
var row = [_x000D_
{key1:1,key2:2, key3:3, key4:4},_x000D_
{key1:2,key2:5, key3:6, key4:7},_x000D_
{key1:3,key2:2, key3:3, key4:4},_x000D_
{key1:4,key2:2, key3:3, key4:4},_x000D_
{key1:5,key2:2, key3:3, key4:4}_x000D_
];_x000D_
_x000D_
for (var item = 0; item < row.length; ++item) {_x000D_
Head.push([_x000D_
row[item].key1,_x000D_
row[item].key2,_x000D_
row[item].key3,_x000D_
row[item].key4_x000D_
]);_x000D_
}_x000D_
_x000D_
var csvRows = [];_x000D_
for (var cell = 0; cell < Head.length; ++cell) {_x000D_
csvRows.push(Head[cell].join(','));_x000D_
}_x000D_
_x000D_
var csvString = csvRows.join("\n");_x000D_
let csvFile = new Blob([csvString], { type: "text/csv" });_x000D_
let downloadLink = document.createElement("a");_x000D_
downloadLink.download = 'MYCSVFILE.csv';_x000D_
downloadLink.href = window.URL.createObjectURL(csvFile);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
downloadLink.click();
_x000D_
Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/
Plus:
fade in / fade out
animation:hover
Tested and working!
I think with async, it is possible to have a more elegant solution and not having deadlocks even when using both standardOutput and standardError:
using (Process process = new Process())
{
process.StartInfo.FileName = filename;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
var tStandardOutput = process.StandardOutput.ReadToEndAsync();
var tStandardError = process.StandardError.ReadToEndAsync();
if (process.WaitForExit(timeout))
{
string output = await tStandardOutput;
string errors = await tStandardError;
// Process completed. Check process.ExitCode here.
}
else
{
// Timed out.
}
}
It is base on Mark Byers answer.
If you are not in an async method, you can use string output = tStandardOutput.result;
instead of await
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
You can also use REGEXP
's synonym RLIKE
as well.
For example:
SELECT *
FROM TABLE_NAME
WHERE COLNAME RLIKE 'REGEX1|REGEX2|REGEX3'
For SQL 2008 you can backup log to nul
device:
BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10
And then use DBCC SHRINKFILE
to truncate the log file.
For another one-liner solution:
def count_letters(word): return len(filter(lambda x: x not in " ", word))
This works by using the filter function, which lets you pick the elements of a list that return true when passed to a boolean-valued function that you pass as the first argument. I'm using a lambda function to make a quick, throwaway function for that purpose.
>>> count_letters("This is a test")
11
You could easily extend this to exclude any selection of characters you like:
def count_letters(word, exclude): return len(filter(lambda x: x not in exclude, word))
>>> count_letters ("This is a test", "aeiou ")
7
Edit: However, you wanted to get your own code to work, so here are some thoughts. The first problem is that you weren't setting a list for the Counter object to count. However, since you're looking for the total number of letters, you need to join the words back together again rather than counting each word individually. Looping to add up the number of each letter isn't really necessary because you can pull out the list of values and use "sum" to add them.
Here's a version that's as close to your code as I could make it, without the loop:
from collections import Counter
import string
def count_letters(word):
wordsList = string.split(word)
count = Counter("".join(wordsList))
return sum(dict(count).values())
word = "The grey old fox is an idiot"
print count_letters(word)
Edit: In response to a comment asking why not to use a for loop, it's because it's not necessary, and in many cases using the many implicit ways to perform repetitive tasks in Python can be faster, simpler to read, and more memory-efficient.
For example, I could have written
joined_words = []
for curr_word in wordsList:
joined_words.extend(curr_word)
count = Counter(joined_words)
but in doing this I wind up allocating an extra array and executing a loop through the Python interpreter that my solution:
count = Counter("".join(wordsList))
would execute in a chunk of optimized, compiled C code. My solution isn't the only way to simplify that loop, but it's one way.
You can create an Answer in Mockito. Let's assume, we have an interface named Application with a method myFunction.
public interface Application {
public String myFunction(String abc);
}
Here is the test method with a Mockito answer:
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (String) args[0];
}
});
assertEquals("someString",mock.myFunction("someString"));
assertEquals("anotherString",mock.myFunction("anotherString"));
}
Since Mockito 1.9.5 and Java 8, you can also use a lambda expression:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);
I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id)
function:
$post = Post::find($id);
$post->fill($request->input())->save();
keep in mind that you have to name your inputs with the same column name. The fill()
function will do all the work for you :)
I used
System.Data.Linq.SqlClient.SqlMethods.Like(row.Name, "test")
in my query.
This performs a case-insensitive comparison.
You can use the code below:
document.body.addEventListener('click', function (evt) {
if (evt.target.className === 'databox') {
alert(this)
}
}, false);
ISSUE 1:
Started by user anonymous
That does not mean that Jenkins started as an anonymous user.
It just means that the person who started the build was not logged in. If you enable Jenkins security, you can create usernames for people and when they log in, the
"Started by anonymous"
will change to
"Started by < username >".
Note: You do not have to enable security in order to run jenkins or to clone correctly.
If you want to enable security and create users, you should see the options at Manage Jenkins > Configure System
.
ISSUE 2:
The "can't clone" error is a different issue altogether. It has nothing to do with you logging in to jenkins or enabling security. It just means that Jenkins does not have the credentials to clone from your git SCM.
Check out the Jenkins Git Plugin to see how to set up Jenkins to work with your git repository.
Hope that helps.
After my initial struggle with the link
and controller
functions and reading quite a lot about them, I think now I have the answer.
First lets understand,
How do angular directives work in a nutshell:
We begin with a template (as a string or loaded to a string)
var templateString = '<div my-directive>{{5 + 10}}</div>';
Now, this templateString
is wrapped as an angular element
var el = angular.element(templateString);
With el
, now we compile it with $compile
to get back the link function.
var l = $compile(el)
Here is what happens,
$compile
walks through the whole template and collects all the directives that it recognizes.link
functions are collected.link
functions are wrapped in a new link
function and returned as l
.Finally, we provide scope
function to this l
(link) function which further executes the wrapped link functions with this scope
and their corresponding elements.
l(scope)
This adds the template
as a new node to the DOM
and invokes controller
which adds its watches to the scope which is shared with the template in DOM.
Comparing compile vs link vs controller :
Every directive is compiled only once and link function is retained for re-use. Therefore, if there's something applicable to all instances of a directive should be performed inside directive's compile
function.
Now, after compilation we have link
function which is executed while attaching the template to the DOM. So, therefore we perform everything that is specific to every instance of the directive. For eg: attaching events, mutating the template based on scope, etc.
Finally, the controller is meant to be available to be live and reactive while the directive works on the DOM
(after getting attached). Therefore:
(1) After setting up the view[V] (i.e. template) with link. $scope
is our [M] and $controller
is our [C] in M V C
(2) Take advantage the 2-way binding with $scope by setting up watches.
(3) $scope
watches are expected to be added in the controller since this is what is watching the template during run-time.
(4) Finally, controller
is also used to be able to communicate among related directives. (Like myTabs
example in https://docs.angularjs.org/guide/directive)
(5) It's true that we could've done all this in the link
function as well but its about separation of concerns.
Therefore, finally we have the following which fits all the pieces perfectly :
You seem to be using grep()
like the Unix grep
utility, which is wrong.
Perl's grep()
in scalar context evaluates the expression for each element of a list and returns the number of times the expression was true.
So when $match
contains any "true" value, grep($match, @array)
in scalar context will always return the number of elements in @array
.
Instead, try using the pattern matching operator:
if (grep /$match/, @array) {
print "found it\n";
}
Best explanation I have found when I was learning that myself is here:http://www.elated.com/articles/php-recursive-functions/
Its because one thing:
The function when its called is created in memory (new instance is created)
So the recursive function IS NOT CALLLING ITSELF, but its calling other instance - so its not one function in memory doing some magic. Its couple of instances in memory which are returning themselves some values - and this behavior is the same when for example function a is calling function b. You have two instances as well as if recursive function called new instance of itself.
Try draw memory with instances on paper - it will make sense.
For anyone who needs to run a program in the background "without PHP waiting for it to finish" do this:
pclose(popen("start /B ".$cmd, "r"));
where $cmd
is the string command for the program that you need to run (e.g. $cmd
can equal notepad.exe
or node Path\to\server.js
).
Source: https://www.php.net/manual/en/function.exec.php (see Arno van den Brink's note in the section titled "User Contributed Notes").
Yes, there is a shortcut for commenting out lines in Python 3.6 (Spyder).
For Single Line Comment, you can use Ctrl+1. It will look like this #This is a sample piece of code
For multi-line comments, you can use Ctrl+4. It will look like this
#=============
\#your piece of code
\#some more code
\#=============
Note : \
represents that the code is carried to another line.
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
You might want to have a look at Process Lasso.
Try:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
The +
operator is overridden in python to concatenate strings.
A couple things
(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.
(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:
.button:after {
content: "";
width: 30px;
height: 30px;
background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
top: 10px;
right: 5px;
position: absolute;
display: inline-block;
}
I updated your jsFiddle to this and it showed the image.
Running as admin didn't help me. (also got errors with syscall: rename)
Turns out this error can also occur if files are locked by Windows.
This can occur if :
Running as admin doesn't get around windows file locking.
I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error
Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.
I've resolved this issue by inferring the produced return type into the first GET requestMethod. The important part here is the
produces="application/json;charset=UTF-8
So every one how use /account/**, Spring will return application/json;charset=UTF-8 content type.
@Controller
@Scope("session")
@RequestMapping(value={"/account"}, method = RequestMethod.GET,produces="application/json;charset=UTF-8")
public class AccountController {
protected final Log logger = LogFactory.getLog(getClass());
....//More parameters and method here...
@RequestMapping(value={"/getLast"}, method = RequestMethod.GET)
public @ResponseBody String getUltimo(HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{
ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
Account account = accountDao.getLast();
return writer.writeValueAsString(account);
}
catch (Exception e) {
return errorHandler(e, response, writer);
}
}
So, you do not have to set up for each method in your Controller, you can do it for the entire class. If you need more control over a specific method, you just only have to infer the produces return content type.
I received this error because I had made a mistake in the definition of my method. I had declared the method to accept a generic type (notice the "T" after the method name):
protected int InsertRecord<T>(CoasterModel model, IDbConnection con)
However, when I called the method, I did not use the type which, in my case, was the correct usage:
int count = InsertRecord(databaseToMigrateFrom, con);
I just removed the generic casting and it worked.
It's the Unicode Character 'ZERO WIDTH SPACE' (U+200B).
this character is intended for line break control; it has no width, but its presence between two characters does not prevent increased letter spacing in justification
As per the given code sample, the entity is entirely superfluous in this context. It must be inserted by some accident, most likely by a buggy editor trying to do smart things with whitespace or highlighting, or an enduser using a keyboard language wherein this character is natively been used, such as Arabic.
If you are using UI router then you can use a decorator and update $templateFactory service and append a query string parameter to templateUrl, and the browser will always load the new template from the server.
function configureTemplateFactory($provide) {
// Set a suffix outside the decorator function
var cacheBust = Date.now().toString();
function templateFactoryDecorator($delegate) {
var fromUrl = angular.bind($delegate, $delegate.fromUrl);
$delegate.fromUrl = function (url, params) {
if (url !== null && angular.isDefined(url) && angular.isString(url)) {
url += (url.indexOf("?") === -1 ? "?" : "&");
url += "v=" + cacheBust;
}
return fromUrl(url, params);
};
return $delegate;
}
$provide.decorator('$templateFactory', ['$delegate', templateFactoryDecorator]);
}
app.config(['$provide', configureTemplateFactory]);
I am sure you can achieve the same result by decorating the "when" method in $routeProvider.
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
it should end up like this in the $_POST[] array (PHP format for easy visualization)
$_POST[] = array(
'firstname'=>'value',
'lastname'=>'value',
'email'=>'value',
'address'=>'value',
'tree' => array(
'tree1'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree2'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree3'=>array(
'fruit'=>'value',
'height'=>'value'
)
)
)
You could try this:
{% if not profile.user.first_name.value %}
<p> -- </p>
{% else %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}
This way, you're essentially checking to see if the form field first_name
has any value associated with it. See {{ field.value }}
in Looping over the form's fields in Django Documentation.
I'm using Django 3.0.
Depending on the device, sometimes you are getting "The folder you specified doesn't contain a compatible software" error because the first interface isn't actually the ADB interface.
Try installing it as a generic "USB composite device" instead (from the 'pick from a list' driver install option); once the standard composite driver installs it will allow Windows to communicate with the device and detect the associated ADB driver interface and install it properly.
Obviously that previous posts are useful, but any of above are not helpful in my case. The reason was in wrong sequence of loading scripts. For example, in my case, controller editCtrl.js depends on (uses) ui-bootstrap-tpls.js, so it should be loaded first. This caused an error:
<script src="scripts/app/station/editCtrl.js"></script>
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
This is right, works:
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
<script src="scripts/app/station/editCtrl.js"></script>
So, to fix the error you need first declare all scripts without dependencies, and then scripts that depends on previously declared.
Please run this below command from the console to skip the user table verification while launching mysql database from command prompt
mysqld -skip-grant-tables
We can use calc() from css
p{
font-size: calc(48px + (56 - 48) * ((100vw - 300px) / (1600 - 300))) !important;
}
The mathematical formula is calc(minsize + (maxsize - minsize) * (100vm - minviewportwidth) / (maxwidthviewoport - minviewportwidth)))
From Docker documentation:
docker export
does not export the contents of volumes associated with the container. If a volume is mounted on top of an existing directory in the container,docker export
will export the contents of the underlying directory, not the contents of the volume. Refer to Backup, restore, or migrate data volumes in the user guide for examples on exporting data in a volume.
You can use a list comprehension:
[x for x in j if x >= 5]
I was unable to use the JSONConvert method suggested by xhafan
In .Net 4.5 even after adding the "System.Web.Extensions" assembly reference I was still unable to access the JSONConvert.
However, once you add the reference you can get the same string print out using:
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonstring = js.Serialize(yourClassObject);
Tortoise SVN on Windows happens to lose sync quite often with the real file status.
In that case try doing an svn cleanup
.
Another thing, it may also depend where your source files are located, different drive, network drive, etc. There's an option in Tortoise to allow icon overlay or not, on remote drives.
Check this out in: TortoiseSVN / Settings / Icon Overlays / Drive types
This is actually a modified version of the selected answer in order to support Unicode characters but I don't have enough reputation to comment there.
CREATE FUNCTION SPLIT_STRING(str VARCHAR(255) CHARSET utf8, delim VARCHAR(12), pos INT) RETURNS varchar(255) CHARSET utf8
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
CHAR_LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
delim, '')
The modifications are the following:
utf8
utf8
CHAR_LENGTH()
instead of LENGTH()
to calculate the character length and not the byte length.private void DeleteProductButton_Click(object sender, EventArgs e)
{
string ProductID = deleteProductButton.Text;
if (string.IsNullOrEmpty(ProductID))
{
MessageBox.Show("Please enter valid ProductID");
deleteProductButton.Focus();
}
try
{
string SelectDelete = "Delete from Products where ProductID=" + deleteProductButton.Text;
SqlCommand command = new SqlCommand(SelectDelete, Conn);
command.CommandType = CommandType.Text;
command.CommandTimeout = 15;
DialogResult comfirmDelete = MessageBox.Show("Are you sure you want to delete this record?");
if (comfirmDelete == DialogResult.No)
{
return;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
I made my own version, based in the code presented above by @Tats_innit . The difference is the pause function. Works a little better in that aspect.
(function ($) {
var timeVar, width=0;
$.fn.textWidth = function () {
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function (args) {
var that = $(this);
if (width == 0) { width = that.width(); };
var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);
function go() {
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i <= args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width=width-2;
}
if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
if (args.pause == true) { clearTimeout(timeVar); };
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
timeVar = setTimeout(function () { go() }, 100);
return dfd.promise();
};
})(jQuery);
usage:
for start: $('#Text1').marquee()
pause: $('#Text1').marquee({ pause: true })
resume: $('#Text1').marquee({ pause: false })
Worked for me:
Download package (see links below), name it lp.cab and place it to your C:
drive
Run the following commands as Administrator:
2.1 installing new language
dism /Online /Add-Package /PackagePath:C:\lp.cab
2.2 get installed packages
dism /Online /Get-Packages
2.3 remove original package
dism /Online /Remove-Package /PackageName:Microsoft-Windows-Client-LanguagePack-Package~31bf3856ad364e35~amd64~ru-RU~10.0.10240.16384
If you don't know which is your original package you can check your installed packages with this line
dism /Online /Get-Packages | findstr /c:"LanguagePack"
List of MUI for Windows 10:
For LPs for Windows 10 version 1607 build 14393, follow this link.
Windows 10 x64 (Build 10240):
zh-CN: Chinese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_9949b0581789e2fc205f0eb005606ad1df12745b.cab
hr-HR: Croatian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_c3bde55e2405874ec8eeaf6dc15a295c183b071f.cab
cs-CZ: Czech download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_d0b2a69faa33d1ea1edc0789fdbb581f5a35ce2d.cab
da-DK: Danish download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_15e50641cef50330959c89c2629de30ef8fd2ef6.cab
nl-NL: Dutch download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_8658b909525f49ab9f3ea9386a0914563ffc762d.cab
en-us: English download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_75d67444a5fc444dbef8ace5fed4cfa4fb3602f0.cab
fr-FR: French download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_206d29867210e84c4ea1ff4d2a2c3851b91b7274.cab
de-DE: German download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_3bb20dd5abc8df218b4146db73f21da05678cf44.cab
hi-IN: Hindi download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_e9deaa6a8d8f9dfab3cb90986d320ff24ab7431f.cab
it-IT: Italian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_42c622dc6957875eab4be9d57f25e20e297227d1.cab
ja-JP: Japanese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_adc2ec900dd1c5e94fc0dbd8e010f9baabae665f.cab
kk-KZ: Kazakh download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_a03ed475983edadd3eb73069c4873966c6b65daf.cab
ko-KR: Korean download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_24411100afa82ede1521337a07485c65d1a14c1d.cab
pt-BR: Portuguese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_894199ed72fdf98e4564833f117380e45b31d19f.cab
ru-RU: Russian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_d85bb9f00b5ee0b1ea3256b6e05c9ec4029398f0.cab
es-ES: Spanish download.windowsupdate.com/c/msdownload/update/software/updt/2015/07/lp_7b21648a1df6476b39e02476c2319d21fb708c7d.cab
uk-UA: Ukrainian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_131991188afe0ef668d77c8a9a568cb71b57f09f.cab
Windows 10 x86 (Build 10240):
zh-CN: Chinese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_e7d13432345bcf589877cd3f0b0dad4479785f60.cab
hr-HR: Croatian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_60856d8b4d643835b30d8524f467d4d352395204.cab
cs-CZ: Czech download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_dfa71b93a76b4500578b67fd3bf6b9f10bf5beaa.cab
da-DK: Danish download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_af0ea4318f43d9cb30bcfa5ce7279647f10bc3b3.cab
nl-NL: Dutch download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_cbcdf4818eac2a15cfda81e37595f8ffeb037fd7.cab
en-us: English download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_41877260829bb5f57a52d3310e326c6828d8ce8f.cab
fr-FR: French download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_80fa697f051a3a949258797a0635a4313a448c29.cab
de-DE: German download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_7ea2648033099f99f87642e47e6d959172c6cab8.cab
hi-IN: Hindi download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_78a11997f4e4bf73bbdb1da8011ebfb218bd1bac.cab
it-IT: Italian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_9e62d9a8b141e0eb6434af5a44c4f9468b60a075.cab
ja-JP: Japanese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_79bd099ac811cb1771e6d9b03d640e5eca636b23.cab
kk-KZ: Kazakh download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_59e690df497799cacb96ab579a706250e5a0c8b6.cab
ko-KR: Korean download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_a88379b0461479ab8b5b47f65c4c3241ef048c04.cab
pt-BR: Portuguese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_bb9f192068fe42fde8787591197a53c174dce880.cab
ru-RU: Russian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_280bf97bbe34cec1b0da620fa1b2dfe5bdb3ea07.cab
es-ES: Spanish download.windowsupdate.com/c/msdownload/update/software/updt/2015/07/lp_31400c38ffea2f0a44bb2dfbd80086aa3cad54a9.cab
uk-UA: Ukrainian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_41cd48aa22d21f09fbcedc69197609c1f05f433d.cab
The bin/XXX.apk
file can be built automatically as soon as you save any source file:
Window/Preferences, Android/Build, uncheck "skip packaging and indexing..."
I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)
try:
connection = manager.connect("I2Cx")
except KeyError as e:
print(e.message)
Don't forget you can always do:
<input type="hidden" name="NonFormName" value="NonFormValue" />
in your actual form, which may be better for your code depending on the case.
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
Since 2011, if you can change function1
, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
Notice also that I fixed your broken object definition (aClass a();
declares a function).
I would use Application Context to get a System Service in the constructor. This eases testing & benefits from composition
public class MyActivity extends Activity {
private final NotificationManager notificationManager;
public MyActivity() {
this(MyApp.getContext().getSystemService(NOTIFICATION_SERVICE));
}
public MyActivity(NotificationManager notificationManager) {
this.notificationManager = notificationManager;
}
// onCreate etc
}
Test class would then use the overloaded constructor.
Android would use the default constructor.
Capturing group (pattern)
creates a group that has capturing property.
A related one that you might often see (and use) is (?:pattern)
, which creates a group without capturing property, hence named non-capturing group.
A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+
, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$
(^
, then 0*1
or 1*0
, then $
) versus ^0*1|1*0$
(^0*1
or 1*0$
).
A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern)
. Using your example, (.*):
, .*
matches ABC
and :
matches :
, and since .*
is inside capturing group (.*)
, the text ABC
is recorded for the capturing group 1.
The whole pattern is defined to be group number 0.
Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:
(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
| | | | | | || | |
1-----1 | | 4------4 |5-------5 |
| 3---------------3 |
2-----------------------------------------2
The group numbers are used in back-reference \n
in pattern and $n
in replacement string.
In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.
You can access the text matched by certain group with Matcher.group(int group)
. The group numbers can be identified with the rule stated above.
In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.
From Java 7, you can define a named capturing group (?<name>pattern)
, and you can access the content matched with Matcher.group(String name)
. The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.
The group names are used in back-reference \k<name>
in pattern and ${name}
in replacement string.
Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group)
.
Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.
I use eUML2 plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. This tool is useful up to Eclipse 4.4.x
Forcing the buttons stay in the same line will make them go beyond the fixed width of the div they are in. If you are okay with that then you can make another div inside the div you already have. The new div in turn will hold the buttons and have the fixed width of however much space the two buttons need to stay in one line.
Here is an example:
<div id="parentDiv" style="width: [less-than-what-buttons-need]px;">
<div id="holdsButtons" style="width: [>=-than-buttons-need]px;">
<button id="button1">1</button>
<button id="button2">2</button>
</div>
</div>
You may want to consider overflow property for the chunk of the content outside of the parentDiv
border.
Good luck!
You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.
Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000, 'localhost');
server.on('listening', function() {
console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});
This works just fine in nodejs v0.6+ and Express v3.0+.
You can groupby
on all the columns and call size
the index indicates the duplicate values:
In [28]:
df.groupby(df.columns.tolist(),as_index=False).size()
Out[28]:
one three two
False False True 1
True False False 2
True True 1
dtype: int64
Use height()
:
var result = $("#myDiv").height();
alert(result);
This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.
If you want to do it without jQuery, you can use plain JavaScript:
var result = document.getElementById("myDiv").offsetHeight;
I prefer to use:
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
What does ToFileTime() do?
Converts the value of the current DateTime object to a Windows file time.
public long ToFileTime()
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.
As long as your objects contain JSON-serializable content (no functions, no Number.POSITIVE_INFINITY
, etc.) there is no need for any loops to clone arrays or objects. Here is a pure vanilla one-line solution.
var clonedArray = JSON.parse(JSON.stringify(nodesArray))
To summarize the comments below, the primary advantage of this approach is that it also clones the contents of the array, not just the array itself. The primary downsides are its limit of only working on JSON-serializable content, and it's performance (which is significantly worse than a slice
based approach).
With the Material Components Library you can use the com.google.android.material.textfield.TextInputLayout
.
You can apply a custom style to change the colors.
To change the hint color you have to use these attributes:
hintTextColor
and android:textColorHint
.
<style name="Custom_textinputlayout_filledbox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
<!-- The color of the label when it is collapsed and the text field is active -->
<item name="hintTextColor">?attr/colorPrimary</item>
<!-- The color of the label in all other text field states (such as resting and disabled) -->
<item name="android:textColorHint">@color/selector_hint_text_color</item>
</style>
You should use a selector for the android:textColorHint
. Something like:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:alpha="0.38" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
<item android:alpha="0.6" android:color="?attr/colorOnSurface"/>
</selector>
To change the bottom line color you have to use the attribute: boxStrokeColor
.
<style name="Custom_textinputlayout_filledbox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
....
<item name="boxStrokeColor">@color/selector_stroke_color</item>
</style>
Also in this case you should use a selector. Something like:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?attr/colorPrimary" android:state_focused="true"/>
<item android:alpha="0.87" android:color="?attr/colorOnSurface" android:state_hovered="true"/>
<item android:alpha="0.12" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
<item android:alpha="0.38" android:color="?attr/colorOnSurface"/>
</selector>
You can also apply these attributes in your layout:
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
app:boxStrokeColor="@color/selector_stroke_color"
app:hintTextColor="?attr/colorPrimary"
android:textColorHint="@color/selector_hint_text_color"
...>
An object has exactly one instance (you can not call new MyObject
). You can have multiple instances of a class.
Object serves the same (and some additional) purposes as the static methods and fields in Java.
Try doing this if you're running Visual Studio Code on a Windows machine and getting this error (I'm using Windows 10).
Go to the settings and change the Python path to the location of YOUR python installation.
I.e.,
Change: "python.pythonPath": "python"
To: "python.pythonPath": "C:\\Python36\\python.exe"
And then: Save and reload Visual Studio Code.
Now when you get the prompt telling you that "Linter pylint is not installed", just select the option to 'install pylint'.
Since you've now provided the correct path to your Python installation, the Pylint installation will be successfully completed in the Windows PowerShell Terminal.
Look at the filter
function.
If you just need a 1-pole low-pass filter, it's
xfilt = filter(a, [1 a-1], x);
where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.
Here's the corresponding high-pass filter:
xfilt = filter([1-a a-1],[1 a-1], x);
If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
I did it by passing the cookie through the HttpContext:
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
response = client.execute(httppost, localContext);
Gradle 6.3, Java library. The code from "jar task" adds the dependencies to the "build/libs/xyz.jar" when running "gradle build" task.
plugins {
id 'java-library'
}
jar {
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
Example code (without exception-handling):
XMLGregorianCalendar xgc =
DatatypeFactory // Data-type converter.
.newInstance() // Instantiate a converter object.
.newXMLGregorianCalendar( // Converter going from `GregorianCalendar` to `XMLGregorianCalendar`.
GregorianCalendar.from( // Convert from modern `ZonedDateTime` class to legacy `GregorianCalendar` class.
LocalDate // Modern class for representing a date-only, without time-of-day and without time zone.
.parse( "2014-01-07" ) // Parsing strings in standard ISO 8601 format is handled by default, with no need for custom formatting pattern.
.atStartOfDay( ZoneOffset.UTC ) // Determine the first moment of the day as seen in UTC. Returns a `ZonedDateTime` object.
) // Returns a `GregorianCalendar` object.
) // Returns a `XMLGregorianCalendar` object.
;
XMLGregorianCalendar
classAvoid the terrible legacy date-time classes whenever possible, such as XMLGregorianCalendar
, GregorianCalendar
, Calendar
, and Date
. Use only modern java.time classes.
When presented with a string such as "2014-01-07"
, parse as a LocalDate
.
LocalDate.parse( "2014-01-07" )
To get a date with time-of-day, assuming you want the first moment of the day, specify a time zone. Let java.time determine the first moment of the day, as it is not always 00:00:00.0 in some zones on some dates.
LocalDate.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
This returns a ZonedDateTime
object.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
;
zdt.toString() = 2014-01-07T00:00-05:00[America/Montreal]
But apparently, you want the start-of-day as seen in UTC (an offset of zero hours-minutes-seconds). So we specify ZoneOffset.UTC
constant as our ZoneId
argument.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneOffset.UTC )
;
zdt.toString() = 2014-01-07T00:00Z
The Z
on the end means UTC (an offset of zero), and is pronounced “Zulu”.
If you must work with legacy classes, convert to GregorianCalendar
, a subclass of Calendar
.
GregorianCalendar gc = GregorianCalendar.from( zdt ) ;
gc.toString() = java.util.GregorianCalendar[time=1389052800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
Apparently, you really need an object of the legacy class XMLGregorianCalendar
. If the calling code cannot be updated to use java.time, convert.
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc )
;
Actually, that code requires a try-catch.
try
{
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
xgc = 2014-01-07T00:00:00.000Z
Putting that all together, with appropriate exception-handling.
// Given an input string such as "2014-01-07", return a `XMLGregorianCalendar` object
// representing first moment of the day on that date as seen in UTC.
static public XMLGregorianCalendar getXMLGregorianCalendar ( String input )
{
Objects.requireNonNull( input );
if( input.isBlank() ) { throw new IllegalArgumentException( "Received empty/blank input string for date argument. Message # 11818896-7412-49ba-8f8f-9b3053690c5d." ) ; }
XMLGregorianCalendar xgc = null;
ZonedDateTime zdt = null;
try
{
zdt =
LocalDate
.parse( input )
.atStartOfDay( ZoneOffset.UTC );
}
catch ( DateTimeParseException e )
{
throw new IllegalArgumentException( "Faulty input string for date does not comply with standard ISO 8601 format. Message # 568db0ef-d6bf-41c9-8228-cc3516558e68." );
}
GregorianCalendar gc = GregorianCalendar.from( zdt );
try
{
xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
Objects.requireNonNull( xgc );
return xgc ;
}
Usage.
String input = "2014-01-07";
XMLGregorianCalendar xgc = App.getXMLGregorianCalendar( input );
Dump to console.
System.out.println( "xgc = " + xgc );
xgc = 2014-01-07T00:00:00.000Z
Do not conflate a date-time value with its textual representation. We parse strings to get a date-time object, and we ask the date-time object to generate a string to represent its value. The date-time object has no ‘format’, only strings have a format.
So shift your thinking into two separate modes: model and presentation. Determine the date-value you have in mind, applying appropriate time zone, as the model. When you need to display that value, generate a string in a particular format as expected by the user.
The Question and other Answers all use old troublesome date-time classes now supplanted by the java.time classes.
Your input string "2014-01-07"
is in standard ISO 8601 format.
The T
in the middle separates date portion from time portion.
The Z
on the end is short for Zulu and means UTC.
Fortunately, the java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2014-01-07" ) ;
ld.toString(): 2014-01-07
ZonedDateTime
If you want to see the first moment of that day, specify a ZoneId
time zone to get a moment on the timeline, a ZonedDateTime
. The time zone is crucial because the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Never assume the day begins at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day may begin at another time-of-day such as 01:00:00. Let java.time determine the first moment.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2014-01-07T00:00:00Z
For your desired format, generate a string using the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME
and then replace the T
in the middle with a SPACE.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;
2014-01-07 00:00:00
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
The AppBar widget has a property called automaticallyImplyLeading
. By default it's value is true
. If you don't want flutter automatically build the back button for you then just make the property false
.
appBar: AppBar(
title: Text("YOUR_APPBAR_TITLE"),
automaticallyImplyLeading: false,
),
To add your custom back button
appBar: AppBar(
title: Text("YOUR_APPBAR_TITLE"),
automaticallyImplyLeading: false,
leading: YOUR_CUSTOM_WIDGET(),
),
See below code this is working for me
iv.setImageResource(getResources().getIdentifier(
"imagename", "drawable", "com.package.application"));
These two schools are not really excluding.
Here is the scenario where you simply have to use
Task.Run(() => AsyncOperation()).Wait();
or something like
AsyncContext.Run(AsyncOperation);
I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.
The library I need is async as it is expected to run async.
The only option. Run it as a normal sync call.
I am just saying to each its own.
On Windows:-
Go to File -> Settings.
And open the 'Build,Execution,Deployment'
. Then open the
Build Tools -> Gradle
Then uncheck -> Offline work on the right.
Click the OK button.
Then Rebuild the Project.
On Mac OS:-
go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image
[
Just a note with Xcode 4: in the organizer there are two different sections in the left pane:
Library > Provisioning profiles
Devices > your device > Provisioning profiles
I was always puttings my provisioning profiles into 2. and even after cleaning and installing properly it was not working. Then I discovered 1. and finally I found the refresh button. If you select 'Automatic device provisioning' in 1. and click on refresh, then everything got validated (no yellow warning in 2. anymore).
I got this error message after making the following change in my top-level build.gradle
to update to the latest version of gradle:
//classpath 'com.android.tools.build:gradle:2.3.2' old
classpath 'com.android.tools.build:gradle:2.3.3' //new
I foolishly made the change while I was connected behind a hostile workplace proxy. The proxy caused the .jar
files for the new version of gradle to become corrupt. This can be verified by inspecting the jars to see if they are an unusual size or whether they can be unzipped.
In order to fix the mistake, I connected to my network at home (which is not behind a proxy) and did a refresh dependencies from the Terminal:
./gradlew --refresh-dependencies
This caused the newer version of gradle to be re-downloaded and the error no longer occurs.
After opening up an issue with the SciPy team, we found that you need to upgrade pip with:
pip install --upgrade pip
And in Python 3
this works:
python3 -m pip install --upgrade pip
for SciPy to install properly. Why? Because:
Older versions of pip have to be told to use wheels, IIRC with --use-wheel. Or you can upgrade pip itself, then it should pick up the wheels.
Upgrading pip solves the issue, but you might be able to just use the --use-wheel
flag as well.
Use Math.Round and specify the number of decimal places.
Math.Round(pay,2);
Math.Round Method (Double, Int32)
Rounds a double-precision floating-point value to a specified number of fractional digits.
Or Math.Round Method (Decimal, Int32)
Rounds a decimal value to a specified number of fractional digits.
These modules can't be installed using npm.
Actually you can install a module by specifying instead of a name a local path. As long as the repository has a valid package.json
file it should work.
Type npm -l
and a pretty help will appear like so :
CLI:
...
install npm install <tarball file>
npm install <tarball url>
npm install <folder>
npm install <pkg>
npm install <pkg>@<tag>
npm install <pkg>@<version>
npm install <pkg>@<version range>
Can specify one or more: npm install ./foo.tgz bar@stable /some/folder
If no argument is supplied and ./npm-shrinkwrap.json is
present, installs dependencies specified in the shrinkwrap.
Otherwise, installs dependencies from ./package.json.
What caught my eyes was: npm install <folder>
In my case I had trouble with mrt
module so I did this (in a temporary directory)
Clone the repo
git clone https://github.com/oortcloud/meteorite.git
And I install it globally with:
npm install -g ./meteorite
One can also install in the same manner the repo to a local npm project with:
npm install ../meteorite
And also one can create a link to the repo, in case a patch in development is needed:
npm link ../meteorite
Nowadays npm supports also github and git repositories (see https://docs.npmjs.com/cli/v6/commands/npm-install), as a shorthand you can run :
npm i github.com:some-user/some-repo
There are a number of ways to get information on the attributes of your DataFrame or Series.
Create Sample DataFrame and Series
df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df
a b
0 5.0 9
1 2.0 2
2 NaN 4
s = df['a']
s
0 5.0
1 2.0
2 NaN
Name: a, dtype: float64
shape
AttributeThe shape
attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.
df.shape
(3, 2)
s.shape
(3,)
len
functionTo get the number of rows of a DataFrame or get the length of a Series, use the len
function. An integer will be returned.
len(df)
3
len(s)
3
size
attributeTo get the total number of elements in the DataFrame or Series, use the size
attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len
function:
df.size
6
s.size
3
ndim
attributeThe ndim
attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:
df.ndim
2
s.ndim
1
count
methodThe count
method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.
df.count() # by default, get the count of each column
a 2
b 3
dtype: int64
df.count(axis='columns') # change direction to get count of each row
0 2
1 2
2 1
dtype: int64
For a Series, there is only one axis for computation and so it just returns a scalar:
s.count()
2
info
method for retrieving metadataThe info
method returns the number of non-missing values and data types of each column
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a 2 non-null float64
b 3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes
Since this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:
This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.
The span
element is an inline element, you can't change its width in CSS.
You can add the following CSS to your span so you will be able to change its width.
display: block;
Another way, which usually makes more sense, is to use a <p>
element as a parent for your <span>
.
<li id="CN2787">
<img class="fav_star" src="images/fav.png">
<p>
<span>Text, text and more text</span>
</p>
</li>
Since <p>
is a block
element, you can set its width using CSS, without having to change anything.
But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.
li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}
P.S. Instead of float:left
on the image, you can also put float:right
on li p
but in that case, you will also need text-align:left
to realign the text correctly.
P.S.S. If you went ahead with the first solution of not adding a <p>
element, your CSS should look like so:
li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}
for a simple way to get all tables on the server, try this:
SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
INSERT INTO @AllTables (CompleteTableName)
EXEC sp_msforeachdb 'select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id'
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1
it will return a single column that contains the server+database+schema+table name: sample output:
CompleteTableName
--------------------------------------------
YourServer.YourDatabase1.YourSchema1.YourTable1
YourServer.YourDatabase1.YourSchema1.YourTable2
YourServer.YourDatabase1.YourSchema2.YourTable1
YourServer.YourDatabase1.YourSchema2.YourTable2
YourServer.YourDatabase2.YourSchema1.YourTable1
if you are not on SQL Server 2005 or up, replace the DECLARE @AllTables table
with CREATE TABLE #AllTables
and then every @AllTables
with #AllTables
and it will work.
EDIT
here is a version that will allow a search parameter to be used on any part or parts of the server+database+schema+table names:
SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
,@SQL nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''
INSERT INTO @AllTables (CompleteTableName)
EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1
set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.
There is a known issue with the new NDIS6 driver, you can install it to use the old NDIS5 driver
Steps I followed:
1.Uninstall Virtualbox and try reinstalling it using command prompt.
2. Run command Prompt in administrative mode;
3.Check your Network Drivers if you are using NDIS6 or 6.+ ;
Write >VirtualBox-5.0.11-104101-Win.exe -msiparams NETWORKTYPE=NDIS5;
4.Now Follow the install steps and finish installation steps.
5. Now try starting device with VirtualBox.
This worked for me.
You might have tried using Microsoft's Excel XML in zip container (.xlsx and .xslm) for version control and found the vba was stored in vbaProject.bin (which is useless for version control).
The solution is simple.
When you repeat this with the next version of the spreadsheet you'll have to make sure you make the folder's files exactly match those in the zip container (and don't leave any deleted files behind).
I found too simple hack just do this add new element in AndroidManifest
as:-
<activity android:name=".activityName"
android:label="@string/app_name"
android:noHistory="true"/>
the android:noHistory
will clear your unwanted activity from Stack.
There is one more way, i got the same situation in my project. i solved this way
List<Object[]> list = HQL.list();
In above hibernate query language i know at which place what are my objects so what i did is :
for(Object[] obj : list){
String val = String.valueOf(obj[1]);
int code =Integer.parseint(String.valueof(obj[0]));
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
It depends upon the context. Some possible contexts in HTML:
See OWASP's Cross Site Scripting Prevention Cheat Sheet, especially the "Why Can't I Just HTML Entity Encode Untrusted Data?" and "XSS Prevention Rules" sections. However, it's best to read the whole document.
gero's solution worked for me.
In Visual Studios 2012, take the following steps.
- Go to Solution Explorer
- Right click on your project
- Go to Properties
- Configuration Properties -> General
- Platform Toolset -> change to Windows7.1SDK