Well, I guess if you need to remove an element you will make a copy of the array despising the element to be excluded.
// inserting some items
void* element_2_remove = getElement2BRemove();
for (int i = 0; i < vector->size; i++){
if(vector[i]!=element_2_remove) copy2TempVector(vector[i]);
}
free(vector->items);
free(vector);
fillFromTempVector(vector);
//
Assume that getElement2BRemove()
, copy2TempVector( void* ...)
and fillFromTempVector(...)
are auxiliary methods to handle the temp vector.
Not very clean but it works :)
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr = arr.Concat({newItem}).ToArray
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List
because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList
, Longs.asList
, etc.
this can be done this way
Overloaded Copy Constructor
/*
* Soumil Nitin SHah
* Github: https://github.com/soumilshah1995
*/
#include <iostream>
using namespace std;
class Matrix{
public:
/*
* Declare the Row and Column
*
*/
int r_size;
int c_size;
int **arr;
public:
/*
* Constructor and Destructor
*/
Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
{
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = 0;
}
}
std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
}
~Matrix()
{
std::cout << "Destructpr -- Deleting Array Size ::" << r_size <<" " << c_size << endl;
}
Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
{
for (int row=0; row<source.r_size; row ++)
{
for (int column=0; column < source.c_size; column ++)
{
arr[row][column] = source.arr[row][column];
}
}
cout << "Copy Constructor " << endl;
}
public:
/*
* Operator Overloading
*/
friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
{
int rowCounter = 0;
int columnCOUNTER = 0;
int globalCounter = 0;
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
globalCounter = globalCounter + 1;
}
rowCounter = rowCounter + 1;
}
os << "Total There are " << globalCounter << " Elements" << endl;
os << "Array Elements are as follow -------" << endl;
os << "\n";
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
os << rhs.arr[row][column] << " ";
}
os <<"\n";
}
return os;
}
void operator()(int row, int column , int Data)
{
arr[row][column] = Data;
}
int &operator()(int row, int column)
{
return arr[row][column];
}
Matrix &operator=(Matrix &rhs)
{
cout << "Assingment Operator called " << endl;cout <<"\n";
if(this == &rhs)
{
return *this;
} else
{
delete [] arr;
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = rhs.arr[row][column];
}
}
return *this;
}
}
};
int main()
{
Matrix m1(3,3); // Initialize Matrix 3x3
cout << m1;cout << "\n";
m1(0,0,1);
m1(0,1,2);
m1(0,2,3);
m1(1,0,4);
m1(1,1,5);
m1(1,2,6);
m1(2,0,7);
m1(2,1,8);
m1(2,2,9);
cout << m1;cout <<"\n"; // print Matrix
cout << "Element at Position (1,2) : " << m1(1,2) << endl;
Matrix m2(3,3);
m2 = m1;
cout << m2;cout <<"\n";
print(m2);
return 0;
}
x=[]
for i in range(0,5):
x.append(i)
print(x[i])
As you correctly point out, one can ReDim Preserve
only the last dimension of an array (ReDim Statement on MSDN):
If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array
Hence, the first issue to decide is whether 2-dimensional array is the best data structure for the job. Maybe, 1-dimensional array is a better fit as you need to do ReDim Preserve
?
Another way is to use jagged array as per Pieter Geerkens's suggestion. There is no direct support for jagged arrays in VB6. One way to code "array of arrays" in VB6 is to declare an array of Variant
and make each element an array of desired type (String
in your case). Demo code is below.
Yet another option is to implement Preserve
part on your own. For that you'll need to create a copy of data to be preserved and then fill redimensioned array with it.
Option Explicit
Public Sub TestMatrixResize()
Const MAX_D1 As Long = 2
Const MAX_D2 As Long = 3
Dim arr() As Variant
InitMatrix arr, MAX_D1, MAX_D2
PrintMatrix "Original array:", arr
ResizeMatrix arr, MAX_D1 + 1, MAX_D2 + 1
PrintMatrix "Resized array:", arr
End Sub
Private Sub InitMatrix(a() As Variant, n As Long, m As Long)
Dim i As Long, j As Long
Dim StringArray() As String
ReDim a(n)
For i = 0 To n
ReDim StringArray(m)
For j = 0 To m
StringArray(j) = i * (m + 1) + j
Next j
a(i) = StringArray
Next i
End Sub
Private Sub PrintMatrix(heading As String, a() As Variant)
Dim i As Long, j As Long
Dim s As String
Debug.Print heading
For i = 0 To UBound(a)
s = ""
For j = 0 To UBound(a(i))
s = s & a(i)(j) & "; "
Next j
Debug.Print s
Next i
End Sub
Private Sub ResizeMatrix(a() As Variant, n As Long, m As Long)
Dim i As Long
Dim StringArray() As String
ReDim Preserve a(n)
For i = 0 To n - 1
StringArray = a(i)
ReDim Preserve StringArray(m)
a(i) = StringArray
Next i
ReDim StringArray(m)
a(n) = StringArray
End Sub
Just use the following for a "minimal" C# installation:
vs_Community.exe --layout f:\vs2017c --lang en-US --add Microsoft.VisualStudio.Workload.ManagedDesktop
This works for sure. The error in your first commandline was the trailing backslash. Without it it works. You don't have to download all..
You can add for example the following workloads (or a subset) to the commandline:
Microsoft.VisualStudio.Workload.Data Microsoft.VisualStudio.Workload.NetWeb Microsoft.VisualStudio.Workload.Universal Microsoft.VisualStudio.Workload.NetCoreTools
Sometimes the downloader seems to not like too much packages. But you can download the packages (add the other workloads) step-by-step, this works. Like you want.
The interesting thing. The installer afterwards will download (only) the packages you selected which you have NOT downloaded before, so it is quite smart (in this point).
(Of course there are more packages available).
For synchronous methods, I believe @Johann Gerell's answer is the pattern to use in all cases.
However the TryGet pattern with the out
parameter does not work with Async methods.
With C# 7's Tuple Literals you can now do this:
async Task<(bool success, SomeObject o)> TryGetSomeObjectByIdAsync(Int32 id)
{
if (InternalIdExists(id))
{
o = await InternalGetSomeObjectAsync(id);
return (true, o);
}
else
{
return (false, default(SomeObject));
}
}
Copy the below script "ez_setup.py" from the below URL
https://bootstrap.pypa.io/ez_setup.py
And copy it into your Python location
C:\Python27>
Run the command
C:\Python27? python ez_setup.py
This will install the easy_install under Scripts directory
C:\Python27\Scripts
Run easy install from the Scripts directory >
C:\Python27\Scripts> easy_install
you're comparing the result against a string ('false') not the built-in negative constant (false)
just use
if(ValidateForm() == false) {
or better yet
if(!ValidateForm()) {
also why are you calling validateForm twice?
This InnoSetup code is working for me under Win 10x64 and Office 2016 x86 (using 'HKLM\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' and key 'Platform')
[Code]
const
RegOffice='SOFTWARE\Microsoft\Office\ClickToRun\Configuration';
RegOfficeKey='Platform';
/// <summary>
/// Get current HKLM version
/// </summary>
function GetHKLM: Integer;
begin
if IsWin64 then
Result := HKLM64
else
Result := HKLM32;
end;
/// <summary>
/// Check is Microsoft Office is installed or not
/// </summary>
function IsOfficeInstalled (): Boolean;
var
platform: string;
begin
RegQueryStringValue(GetHKLM(), RegOffice, RegOfficeKey, platform);
if platform = 'x86' then begin
SuppressibleMsgBox('Microsoft Office found (x86 version)' , mbConfirmation, MB_YESNO or MB_DEFBUTTON1, IDYES);
Result := True;
end else if platform = 'x64' then begin
SuppressibleMsgBox('Microsoft Office found (x64 version)', mbConfirmation, MB_YESNO or MB_DEFBUTTON1, IDYES);
Result := True;
end else begin
SuppressibleMsgBox('Microsoft Office NOT found' + platform + '.', mbConfirmation, MB_YESNO or MB_DEFBUTTON1, IDYES);
Result := False;
end;
end;
You can set the size of the picture in pixels, like this:
https://graph.facebook.com/v2.8/me?fields=id,name,picture.width(500).height(500)
In the similar manner, type
parameter can be used
{user-id}/?fields=name,picture.type(large)
From the documentation
type enum{small, normal, album, large, square}
I'm using Rails + Cucumber + Selenium Webdriver + PhantomJS, and I've been using a monkey-patched version of Selenium Webdriver, which keeps PhantomJS browser open between test runs. See this blog post: http://blog.sharetribe.com/2014/04/07/faster-cucumber-startup-keep-phantomjs-browser-open-between-tests/
See also my answer to this post: How do I execute a command on already opened browser from a ruby file
The following query should give the exact stuff you are looking out for.
select datediff(second, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
Here is the link from MSDN for what all you can do with datediff function . https://msdn.microsoft.com/en-us/library/ms189794.aspx
You Only Need to close the bufferedReader i.e reader.close() and it will work fine .
In nano 2.2.6 the line in ~/.nanorc to do this seems to be
set tabsize 4
Setting tabspace gave me the error: 'Unknown flag "tabspace"'
Here is what you can do:-
Exim SSL certificates
By default, the /etc/exim.conf will use the cert/key files:
/etc/exim.cert
/etc/exim.key
so if you're wondering where to set your files, that's where.
They're controlled by the exim.conf's options:
tls_certificate = /etc/exim.cert
tls_privatekey = /etc/exim.key
Intermediate Certificates
If you have a CA Root certificate (ca bundle, chain, etc.) you'll add the contents of your CA into the exim.cert, after your actual certificate.
Probably a good idea to make sure you have a copy of everything elsewhere in case you make an error.
Dovecot and ProFtpd should also read it correctly, so dovecot no longer needs the ssl_ca option. So for both cases, there is no need to make any changes to either the exim.conf or dovecot.conf(/etc/dovecot/conf/ssl.conf)
For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, executable zip files and directories.
python myapp.zip
Where myapp.zip is a zip containing a __main__.py
file which is executed as the script file to be executed. Your package dependencies can also be included in the file:
__main__.py
mypackage/__init__.py
mypackage/someliblibfile.py
You can also execute an egg, but the incantation is not as nice:
# Bourn Shell and derivatives (Linux/OSX/Unix)
PYTHONPATH=myapp.egg python -m myapp
rem Windows
set PYTHONPATH=myapp.egg
python -m myapp
This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:
myapp/__init__.py
myapp/somelibfile.py
And python will run __init__.py
(you should check that __file__=='__main__'
in your app for command line use).
Egg files are just zip files so you might be able to add __main__.py
to your egg with a zip tool and make it executable in python 2.6 and run it like python myapp.egg
instead of the above incantation where the PYTHONPATH environment variable is set.
More information on executable zip files including how to make them directly executable with a shebang can be found on Michael Foord's blog post on the subject.
Use an Iterator
and call remove()
:
Iterator<String> iter = myArrayList.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (someCondition)
iter.remove();
}
MessageBox::Show
uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Note that getImageData returns a snapshot. Implications are:
You can try this
var str = 'hello world !!';
str = str.replace(/\s+/g, '-');
It will even replace multiple spaces with single '-'.
You got different things here:
First:
this
"
keyword). ref: angular.service vs angular.factory
Second:
Keep in mind all providers in AngularJS (value, constant, services, factories) are singletons!
Third:
Using one or the other (service or factory) is about code style. But, the common way in AngularJS is to use factory.
Why ?
Because "The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. Since factories are regular functions, we can also take advantage of a new lexical scope to simulate "private" variables. This is very useful as we can hide implementation details of a given service."
(ref: http://www.amazon.com/Mastering-Web-Application-Development-AngularJS/dp/1782161821).
Service : Could be useful for sharing utility functions that are useful to invoke by simply appending ()
to the injected function reference. Could also be run with injectedArg.call(this)
or similar.
Factory : Could be useful for returning a ‘class’ function that can then be new`ed to create instances.
So, use a factory when you have complex logic in your service and you don't want expose this complexity.
In other cases if you want to return an instance of a service just use service.
But you'll see with time that you'll use factory in 80% of cases I think.
For more details: http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/
UPDATE :
Excellent post here : http://iffycan.blogspot.com.ar/2013/05/angular-service-or-factory.html
"If you want your function to be called like a normal function, use factory. If you want your function to be instantiated with the new operator, use service. If you don't know the difference, use factory."
UPDATE :
AngularJS team does his work and give an explanation: http://docs.angularjs.org/guide/providers
And from this page :
"Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions."
Regarding number of days in month just use static switch command and check if (year % 4 == 0)
in which case February will have 29 days.
Minute, hour, day etc:
var someMillisecondValue = 511111222127;
var date = new Date(someMillisecondValue);
var minute = date.getMinutes();
var hour = date.getHours();
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
alert([minute, hour, day, month, year].join("\n"));
It has to be any one of the given sizes and a minimum of 2 but up to 8 screenshots are accepted in Google Playstore.
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
Try using the following on the JavaScript side:
window.location.href = '@Url.Action("Index", "Controller")';
If you want to pass parameters to the @Url.Action
, you can do this:
var reportDate = $("#inputDateId").val();//parameter
var url = '@Url.Action("Index", "Controller", new {dateRequested = "findme"})';
window.location.href = url.replace('findme', reportDate);
Update for Swift 5 and the simpliest way
let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])
This prints,
["Bob", "hit", "a", "ball", "", "the", "hit", "BALL", "flew", "far", "after", "it", "was", "hit", "", "Hello", "", "Hie", "", "How", "r", "u", ""]
However, if you want to filter out empty string,
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"]).filter({!$0.isEmpty})
Output,
["Bob", "hit", "a", "ball", "the", "hit", "BALL", "flew", "far", "after", "it", "was", "hit", "Hello", "Hie", "How", "r", "u"]
But make sure, Foundation is imported
W/Ads: Failed to load ad: 3
It Means that your code is correct but due to less amount of request to the server your ads are not Visible. To check the Test ADS you Should put the code in loop for some time, and you have to give multiple requests so that your admob receives multiple requests and will load the ads immediately.
Add the below code
for(int i=0;i<1000;i++) {
AdRequest adRequest = new AdRequest
.Builder()
.addTestDevice("B431EE858B5F1986E4D89CA31250F732")
.build();
accountSettingsBinding.adView.loadAd(adRequest);
}
Restart Your application multiple times.
Remove the Loop after you start receiving ads.
Use this code:
QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
QString line = in.readLine();
...
}
inputFile.close();
}
If you are using MySQL, you can use order by FIELD(id, ...)
approach:
Company.findAll({
where: {id : {$in : companyIds}},
order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})
Keep in mind, it might be slow. But should be faster, than manual sorting with JS.
'this' refers to the DOM object to which the event listener has been attached. 'event.target' refers to the DOM object for which the event listener got triggered. A natural question arises as, why the event listener is triggering for other DOM objects. This is because event listener attached parent triggers for child object too.
You can use TreeSet
that automatically order list values:
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
System.out.println("Tree Set Example!\n");
TreeSet <String>tree = new TreeSet<String>();
tree.add("aaa");
tree.add("acbbb");
tree.add("aab");
tree.add("c");
tree.add("a");
Iterator iterator;
iterator = tree.iterator();
System.out.print("Tree set data: ");
//Displaying the Tree set data
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
}
}
I lastly add 'a' but last element must be 'c'.
data = []
with codecs.open('d:\output.txt','rU','utf-8') as f:
for line in f:
data.append(json.loads(line))
Try with this: http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOGL
It will return you all available details about the mentioned stock.
e.g. out put would look like below:
// [ {
"id": "694653"
,"t" : "GOOGL"
,"e" : "NASDAQ"
,"l" : "528.08"
,"l_fix" : "528.08"
,"l_cur" : "528.08"
,"s": "0"
,"ltt":"4:00PM EST"
,"lt" : "Dec 5, 4:00PM EST"
,"lt_dts" : "2014-12-05T16:00:14Z"
,"c" : "-14.50"
,"c_fix" : "-14.50"
,"cp" : "-2.67"
,"cp_fix" : "-2.67"
,"ccol" : "chr"
,"pcls_fix" : "542.58"
}
]
You can have your company stock symbol at the end of this URL to get its details:
http://finance.google.com/finance/info?client=ig&q=<YOUR COMPANY STOCK SYMBOL>
I have experienced similar problems with Visual Studio 2015 Update 3. In my case core issue was corrupted windows installer cache (C:\Windows\Installer)
Here is the line from msi installer log:
MSI (s) (4C:64) [10:40:10:059]: Warning: Local cached package 'C:\WINDOWS\Installer\3442502.msi' is missing.
You should check installation logs if installation cache is corrupted same way. If it is you should pray for sfc utility to recover system integrity or you would reinstall windows from scratch as corrupted windows installer cache is a complete disaster and a reason to perform clear windows installation immediately.
You should consider using a button for this. Links generally should be use for linking. Buttons can be used for other functionality you wish to add. Neals solution works, but its a workaround.
If you use a <button>
instead of a <a>
, your original code should work as expected.
For people who are using Microsoft SQL Server Manager and want to create a Unique but Nullable index you can create your unique index as you normally would then in your Index Properties for your new index, select "Filter" from the left hand panel, then enter your filter (which is your where clause). It should read something like this:
([YourColumnName] IS NOT NULL)
This works with MSSQL 2012
The precision of double
and float
is fixed by their size and the way the IEEE floating point types are implemented.
The number of decimal digits in the output, on the other hand, is a matter of formatting. You are correct that typing the same constant over and over is a bad idea. You should declare a string constant instead, and use its symbolic representation.
private static final String DBL_FMT = "##.####";
Using a symbolic representation would let you change precision in all places the constant is used without searching through your code.
If you have a default scope in your model that specifies an ascending order in Rails 3 you'll need to use reorder rather than order as specified by Arthur Neves above:
Something.limit(5).reorder('id desc')
or
Something.reorder('id desc').limit(5)
The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.
I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.
input[type="checkbox"] {
// Unchecked Styles
}
input[type="checkbox"]:checked {
// Checked Styles
}
I apologize for bringing up an old thread but felt like it could have used a better answer.
EDIT (3/3/2016):
W3C Specs state that :not(:checked)
as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"]
selector. See example below for clarification.
input[type="checkbox"] {
/* Base Styles aka unchecked */
font-weight: 300; // Will be overwritten by :checked
font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
/* Explicit Unchecked Styles */
border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
/* Checked Styles */
font-weight: 900; // Use a bold font when checked
}
Without using :not(:checked)
in the example above the :checked
selector would have needed to use a border: none;
to achieve the same affect.
Use the input[type="checkbox"]
for base styling to reduce duplication.
Use the input[type="checkbox"]:not(:checked)
for explicit unchecked styles that you do not want to apply to the checked state.
!!
it's using NOT
operation twice together, !
convert the value to a boolean
and reverse it, here is a simple example to see how !!
works:
At first, the place you have:
var zero = 0;
Then you do !0
, it will be converted to boolean and be evaluated to true
, because 0 is falsy
, so you get the reversed value and converted to boolean, so it gets evaluated to true
.
!zero; //true
but we don't want the reversed boolean version of the value, so we can reverse it again to get our result! That's why we use another !
.
Basically, !!
make us sure, the value we get is boolean, not falsy, truthy or string etc...
So it's like using Boolean
function in javascript, but easy and shorter way to convert a value to boolean:
var zero = 0;
!!zero; //false
Here is how my code looks like. It also shows an example of how to use query parameters using a dictionary. It works on using Python 3.6:
import cx_Oracle
CONN_INFO = {
'host': 'xxx.xx.xxx.x',
'port': 12345,
'user': 'SOME_SCHEMA',
'psw': 'SECRETE',
'service': 'service.server.com'
}
CONN_STR = '{user}/{psw}@{host}:{port}/{service}'.format(**CONN_INFO)
QUERY = '''
SELECT
*
FROM
USER
WHERE
NAME = :name
'''
class DB:
def __init__(self):
self.conn = cx_Oracle.connect(CONN_STR)
def query(self, query, params=None):
cursor = self.conn.cursor()
result = cursor.execute(query, params).fetchall()
cursor.close()
return result
db = DB()
result = db.query(QUERY, {'name': 'happy'})
You can use the following function
to split the values
by a delimiter
. It'll return a table
and to find the nth occurrence just make a select
on it! Or change it a little for it to return
what you need instead of the table
.
CREATE FUNCTION dbo.Split
(
@RowData nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
Short and effective:
DateFormat.getDateTimeInstance().format(new Date(myMillisValue))
Native browser smooth scrolling in JavaScript is like this:
// scroll to specific values,
// same as window.scroll() method.
// for scrolling a particular distance, use window.scrollBy().
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
// scroll certain amounts from current position
window.scrollBy({
top: 100, // negative value acceptable
left: 0,
behavior: 'smooth'
});
// scroll to a certain element
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});
If you are using Visual Studio, there is a GUI solution as well:
To remove the "keep-alive" header in requests, I just created it from the Request object and then send it with Session
headers = {
'Host' : '1.2.3.4',
'User-Agent' : 'Test client (x86_64-pc-linux-gnu 7.16.3)',
'Accept' : '*/*',
'Accept-Encoding' : 'deflate, gzip',
'Accept-Language' : 'it_IT'
}
url = "https://stream.twitter.com/1/statuses/filter.json"
#r = requests.get(url, headers = headers) #this triggers keep-alive: True
s = requests.Session()
r = requests.Request('GET', url, headers)
Newer versions of the DOMTokenList spec allow for multiple arguments to add()
and remove()
, as well as a second argument to toggle()
to force state.
At the time of writing, Chrome supports multiple arguments to add()
and remove()
, but none of the other browsers do. IE 10 and lower, Firefox 23 and lower, Chrome 23 and lower and other browsers do not support the second argument to toggle()
.
I wrote the following small polyfill to tide me over until support expands:
(function () {
/*global DOMTokenList */
var dummy = document.createElement('div'),
dtp = DOMTokenList.prototype,
toggle = dtp.toggle,
add = dtp.add,
rem = dtp.remove;
dummy.classList.add('class1', 'class2');
// Older versions of the HTMLElement.classList spec didn't allow multiple
// arguments, easy to test for
if (!dummy.classList.contains('class2')) {
dtp.add = function () {
Array.prototype.forEach.call(arguments, add.bind(this));
};
dtp.remove = function () {
Array.prototype.forEach.call(arguments, rem.bind(this));
};
}
// Older versions of the spec didn't have a forcedState argument for
// `toggle` either, test by checking the return value after forcing
if (!dummy.classList.toggle('class1', true)) {
dtp.toggle = function (cls, forcedState) {
if (forcedState === undefined)
return toggle.call(this, cls);
(forcedState ? add : rem).call(this, cls);
return !!forcedState;
};
}
})();
A modern browser with ES5 compliance and DOMTokenList
are expected, but I'm using this polyfill in several specifically targeted environments, so it works great for me, but it might need tweaking for scripts that will run in legacy browser environments such as IE 8 and lower.
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
Replace spaces in URL with + like If url contains dimension1=Incontinence Liners then replace it with dimension1=Incontinence+Liners.
Inspired by Robert K's solution, this version does not strip HTML tags, and is just as secure.
var decode_entities = (function() {
// Remove HTML Entities
var element = document.createElement('div');
function decode_HTML_entities (str) {
if(str && typeof str === 'string') {
// Escape HTML before decoding for HTML Entities
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';');
element.innerHTML = str;
if(element.innerText){
str = element.innerText;
element.innerText = '';
}else{
// Firefox support
str = element.textContent;
element.textContent = '';
}
}
return unescape(str);
}
return decode_HTML_entities;
})();
The following is not listed here, and it was the solution I adopted (SvcUtils was useful in seeing the error message. However, the error I got was wrapper type message cannot be projected as a data contract type since it has multiple namespaces
. Meaning, I followed this lead, and learned about wsdl.exe
via this post).
In my case, simply running wsdl [my-asmx-service-address] generated a problem-free .cs
file, which I included in my project and instanced to use the service.
var app = angular.module('plunkr', [])
app.controller('UploadController', function($scope, fileReader) {
$scope.imageSrc = "";
$scope.$on("fileProgress", function(e, progress) {
$scope.progress = progress.loaded / progress.total;
});
});
app.directive("ngFileSelect", function(fileReader, $timeout) {
return {
scope: {
ngModel: '='
},
link: function($scope, el) {
function getFile(file) {
fileReader.readAsDataUrl(file, $scope)
.then(function(result) {
$timeout(function() {
$scope.ngModel = result;
});
});
}
el.bind("change", function(e) {
var file = (e.srcElement || e.target).files[0];
getFile(file);
});
}
};
});
app.factory("fileReader", function($q, $log) {
var onLoad = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.resolve(reader.result);
});
};
};
var onError = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.reject(reader.result);
});
};
};
var onProgress = function(reader, scope) {
return function(event) {
scope.$broadcast("fileProgress", {
total: event.total,
loaded: event.loaded
});
};
};
var getReader = function(deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var readAsDataURL = function(file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
});
*************** CSS ****************
img{width:200px; height:200px;}
************** HTML ****************
<div ng-app="app">
<div ng-controller="UploadController ">
<form>
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc">
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc2">
<!-- <input type="file" ng-file-select="onFileSelect($files)" multiple> -->
</form>
<img ng-src="{{imageSrc}}" />
<img ng-src="{{imageSrc2}}" />
</div>
</div>
I did it like this for my project:
.btn-outlined.btn-primary {_x000D_
color: #000;_x000D_
}_x000D_
.btn-outlined.btn-primary:active, .btn-outlined.btn-positive:active, .btn-outlined.btn-negative:active {_x000D_
color:#000;_x000D_
}_x000D_
.btn-block {_x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 15px 0;_x000D_
margin-bottom: 10px;_x000D_
font-size: 18px;_x000D_
font-family: Arial, Helvetica, sans-serif;_x000D_
text-align: center;_x000D_
}
_x000D_
<label for="fileUpload" class="btn btn-primary btn-block btn-outlined">Your text</label>_x000D_
<input type="file" id="fileUpload"style="display: none;">
_x000D_
I hate bumping old articles but this is the first result for this in google search and I had a heck of a time with this problem (even with the support of you guys). So here goes nothing...
Hopefully my solution will help those that also was confused.
namespace MyApplication.WebAPI.Controllers
{
public class BaseController : ApiController
{
public T SendResponse<T>(T response, HttpStatusCode statusCode = HttpStatusCode.OK)
{
if (statusCode != HttpStatusCode.OK)
{
// leave it up to microsoft to make this way more complicated than it needs to be
// seriously i used to be able to just set the status and leave it at that but nooo... now
// i need to throw an exception
var badResponse =
new HttpResponseMessage(statusCode)
{
Content = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json")
};
throw new HttpResponseException(badResponse);
}
return response;
}
}
}
and then just inherit from the BaseController
[RoutePrefix("api/devicemanagement")]
public class DeviceManagementController : BaseController
{...
and then using it
[HttpGet]
[Route("device/search/{property}/{value}")]
public SearchForDeviceResponse SearchForDevice(string property, string value)
{
//todo: limit search property here?
var response = new SearchForDeviceResponse();
var results = _deviceManagementBusiness.SearchForDevices(property, value);
response.Success = true;
response.Data = results;
var statusCode = results == null || !results.Any() ? HttpStatusCode.NoContent : HttpStatusCode.OK;
return SendResponse(response, statusCode);
}
Here is an ES6 version
const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");_x000D_
repeat("A",20).forEach((a,b) => console.log(a,b+1))
_x000D_
You might want to consider abstracting it out into a function like this:
function dialog(message, yesCallback, noCallback) {
$('.title').html(message);
var dialog = $('#modal_dialog').dialog();
$('#btnYes').click(function() {
dialog.dialog('close');
yesCallback();
});
$('#btnNo').click(function() {
dialog.dialog('close');
noCallback();
});
}
You can then use it like this:
dialog('Are you sure you want to do this?',
function() {
// Do something
},
function() {
// Do something else
}
);
Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):
# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.
FROM ubuntu
MAINTAINER Kimbro Staken
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen
#RUN echo "" >> /etc/mongodb.conf
CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"]
System.out.println(A.compareTo(B)>0?"Yes":"No")
if the value of A>B it will return "Yes" or "No".
http://php.net/manual/en/function.print-r.php This function can be used to format output,
$output = print_r($array,1);
$output
is a string variable, it can be logged like every other string. In pure php you can use trigger_error
Ex. trigger_error($output);
http://php.net/manual/en/function.trigger-error.php
if you need to format it also in html, you can use <pre>
tag
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file);
returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.
but classes are so 2018
ScrollToTop.js
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return (null);
}
export default withRouter(ScrollToTop);
Usage:
<Router>
<Fragment>
<ScrollToTop />
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</Fragment>
</Router>
ScrollToTop can also be implemented as a wrapper component:
ScrollToTop.js
import React, { useEffect, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history, children }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return <Fragment>{children}</Fragment>;
}
export default withRouter(ScrollToTop);
Usage:
<Router>
<ScrollToTop>
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</ScrollToTop>
</Router>
From the Python documentation wiki, I think you can do:
a = ([[1, 2, 3], [4, 5, 6], [0, 0, 1]]);
a = sorted(a, key=lambda a_entry: a_entry[1])
print a
The output is:
[[[0, 0, 1], [1, 2, 3], [4, 5, 6]]]
What you want to do is this:
set statistics time on
-- your query
set statistics time off
That will have the output looking something like this in your Messages window:
SQL Server Execution Times: CPU time = 6 ms, elapsed time = 6 ms.
Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:
Controller:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
user.user_gender = collection["rdbtnGender"];
return RedirectToAction("Index");
}
catch(Exception e)
{
throw e;
}
}
public ActionResult Edit(int id)
{
CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
ViewBag.UserObj = user;
return View();
}
VIEW:
Create:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label for="rdbtnGender2">FEMALE</label>
Edit:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" @(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" @(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
To formalize what someone else used setNames for:
add_row <- function(original_data, new_vals_list){
# appends row to dataset while assuming new vals are ordered and classed appropriately.
# new_vals must be a list not a single vector.
rbind(
original_data,
setNames(data.frame(new_vals_list), colnames(original_data))
)
}
It preserves class when legal and passes errors elsewhere.
m <- mtcars[ ,1:3]
m$cyl <- as.factor(m$cyl)
str(m)
#'data.frame': 32 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Factor preserved when adding 4, even though it was passed as a numeric.
str(add_row(m, list(20,4,160)))
#'data.frame': 33 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Attempting to pass a non- 4,6,8 would return an error that factor level is invalid.
str(add_row(m, list(20,3,160)))
# 'data.frame': 33 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = 3) :
invalid factor level, NA generated
Executing your pseudo code literally does not even give any error:
try:
something
except:
pass
as if it is a perfectly valid piece of code, instead of throwing a NameError
. I hope this is not what you want.
You can try the following:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Select file to be upload";
fDialog.Filter = "All Files|*.*";
// fDialog.Filter = "PDF Files|*.pdf";
if (fDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fDialog.FileName.ToString();
}
}
Timer for jQuery - smaller, working, tested.
var sec = 0;_x000D_
function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
setInterval( function(){_x000D_
$("#seconds").html(pad(++sec%60));_x000D_
$("#minutes").html(pad(parseInt(sec/60,10)));_x000D_
}, 1000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
Pure JavaScript:
var sec = 0;_x000D_
function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
setInterval( function(){_x000D_
document.getElementById("seconds").innerHTML=pad(++sec%60);_x000D_
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));_x000D_
}, 1000);
_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
Update:
This answer shows how to pad.
Stopping setInterval MDN is achieved with clearInterval MDN
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );
I think the "powershell way" could be :
set-content destination.log -value (get-content c:\FileToAppend_*.log )
.Click() - Perform only click operation as like mouse click.
.Submit() - Perform Enter operation as like keyboard Enter event.
For Example. Consider a login page where it contains username and password and submit button.
On filling password if we want to login without clicking login button. we need to user .submit button on password where .click() operation does not work.[to login into application]
Brif.
driver.get("https:// anyURL");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.id("txtUserId")).sendKeys("[email protected]");
WebElement text = driver.findElement(By.id("txtPassword")); text.sendKeys("password");
Thread.sleep(1000);
text.click(); //This will not work - it will on perform click operation not submit operation
text.submit(); //This will perform submit operation has enter key
Or You can use
grep -n . file1 |tail -LineNumberToStartWith|grep regEx
This will take care of numbering the lines in the file
grep -n . file1
This will print the last-LineNumberToStartWith
tail -LineNumberToStartWith
And finally it will grep your desired lines(which will include line number as in orignal file)
grep regEX
I have solved the issue by the following way.
class MyTrustManager implements X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString)
throws CertificateException {
// TODO Auto-generated method stub
}
private static void disableSSL() {
try {
TrustManager[] trustAllCerts = new TrustManager[] { new MyTrustManager() };
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
This should work for matches that might overlap:
public static void main(String[] args) {
String input = "aaaaaaaa";
String regex = "aa";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
System.out.println(count);
}
SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).
(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).
You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.
It's embedded in a standard XML comment, and looks like this:
<!--#include virtual="top.shtml" -->
It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.
You can read more in this Wikipedia article.
Using base R's rep_len
:
x <- 1:10
n <- 3
split(x, rep_len(1:n, length(x)))
# $`1`
# [1] 1 4 7 10
#
# $`2`
# [1] 2 5 8
#
# $`3`
# [1] 3 6 9
And as already mentioned if you want sorted indices, simply:
split(x, sort(rep_len(1:n, length(x))))
# $`1`
# [1] 1 2 3 4
#
# $`2`
# [1] 5 6 7
#
# $`3`
# [1] 8 9 10
Just a note about the HtmlAgilityPack for posterity. The project contains an example of parsing text to html, which, as noted by the OP, does not handle whitespace at all like anyone writing HTML would envisage. There are full-text rendering solutions out there, noted by others to this question, which this is not (it cannot even handle tables in its current form), but it is lightweight and fast, which is all I wanted for creating a simple text version of HTML emails.
using System.IO;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
//small but important modification to class https://github.com/zzzprojects/html-agility-pack/blob/master/src/Samples/Html2Txt/HtmlConvert.cs
public static class HtmlToText
{
public static string Convert(string path)
{
HtmlDocument doc = new HtmlDocument();
doc.Load(path);
return ConvertDoc(doc);
}
public static string ConvertHtml(string html)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
return ConvertDoc(doc);
}
public static string ConvertDoc (HtmlDocument doc)
{
using (StringWriter sw = new StringWriter())
{
ConvertTo(doc.DocumentNode, sw);
sw.Flush();
return sw.ToString();
}
}
internal static void ConvertContentTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo)
{
foreach (HtmlNode subnode in node.ChildNodes)
{
ConvertTo(subnode, outText, textInfo);
}
}
public static void ConvertTo(HtmlNode node, TextWriter outText)
{
ConvertTo(node, outText, new PreceedingDomTextInfo(false));
}
internal static void ConvertTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo)
{
string html;
switch (node.NodeType)
{
case HtmlNodeType.Comment:
// don't output comments
break;
case HtmlNodeType.Document:
ConvertContentTo(node, outText, textInfo);
break;
case HtmlNodeType.Text:
// script and style must not be output
string parentName = node.ParentNode.Name;
if ((parentName == "script") || (parentName == "style"))
{
break;
}
// get text
html = ((HtmlTextNode)node).Text;
// is it in fact a special closing node output as text?
if (HtmlNode.IsOverlappedClosingElement(html))
{
break;
}
// check the text is meaningful and not a bunch of whitespaces
if (html.Length == 0)
{
break;
}
if (!textInfo.WritePrecedingWhiteSpace || textInfo.LastCharWasSpace)
{
html= html.TrimStart();
if (html.Length == 0) { break; }
textInfo.IsFirstTextOfDocWritten.Value = textInfo.WritePrecedingWhiteSpace = true;
}
outText.Write(HtmlEntity.DeEntitize(Regex.Replace(html.TrimEnd(), @"\s{2,}", " ")));
if (textInfo.LastCharWasSpace = char.IsWhiteSpace(html[html.Length - 1]))
{
outText.Write(' ');
}
break;
case HtmlNodeType.Element:
string endElementString = null;
bool isInline;
bool skip = false;
int listIndex = 0;
switch (node.Name)
{
case "nav":
skip = true;
isInline = false;
break;
case "body":
case "section":
case "article":
case "aside":
case "h1":
case "h2":
case "header":
case "footer":
case "address":
case "main":
case "div":
case "p": // stylistic - adjust as you tend to use
if (textInfo.IsFirstTextOfDocWritten)
{
outText.Write("\r\n");
}
endElementString = "\r\n";
isInline = false;
break;
case "br":
outText.Write("\r\n");
skip = true;
textInfo.WritePrecedingWhiteSpace = false;
isInline = true;
break;
case "a":
if (node.Attributes.Contains("href"))
{
string href = node.Attributes["href"].Value.Trim();
if (node.InnerText.IndexOf(href, StringComparison.InvariantCultureIgnoreCase)==-1)
{
endElementString = "<" + href + ">";
}
}
isInline = true;
break;
case "li":
if(textInfo.ListIndex>0)
{
outText.Write("\r\n{0}.\t", textInfo.ListIndex++);
}
else
{
outText.Write("\r\n*\t"); //using '*' as bullet char, with tab after, but whatever you want eg "\t->", if utf-8 0x2022
}
isInline = false;
break;
case "ol":
listIndex = 1;
goto case "ul";
case "ul": //not handling nested lists any differently at this stage - that is getting close to rendering problems
endElementString = "\r\n";
isInline = false;
break;
case "img": //inline-block in reality
if (node.Attributes.Contains("alt"))
{
outText.Write('[' + node.Attributes["alt"].Value);
endElementString = "]";
}
if (node.Attributes.Contains("src"))
{
outText.Write('<' + node.Attributes["src"].Value + '>');
}
isInline = true;
break;
default:
isInline = true;
break;
}
if (!skip && node.HasChildNodes)
{
ConvertContentTo(node, outText, isInline ? textInfo : new PreceedingDomTextInfo(textInfo.IsFirstTextOfDocWritten){ ListIndex = listIndex });
}
if (endElementString != null)
{
outText.Write(endElementString);
}
break;
}
}
}
internal class PreceedingDomTextInfo
{
public PreceedingDomTextInfo(BoolWrapper isFirstTextOfDocWritten)
{
IsFirstTextOfDocWritten = isFirstTextOfDocWritten;
}
public bool WritePrecedingWhiteSpace {get;set;}
public bool LastCharWasSpace { get; set; }
public readonly BoolWrapper IsFirstTextOfDocWritten;
public int ListIndex { get; set; }
}
internal class BoolWrapper
{
public BoolWrapper() { }
public bool Value { get; set; }
public static implicit operator bool(BoolWrapper boolWrapper)
{
return boolWrapper.Value;
}
public static implicit operator BoolWrapper(bool boolWrapper)
{
return new BoolWrapper{ Value = boolWrapper };
}
}
As an example, the following HTML code...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<header>
Whatever Inc.
</header>
<main>
<p>
Thanks for your enquiry. As this is the 1<sup>st</sup> time you have contacted us, we would like to clarify a few things:
</p>
<ol>
<li>
Please confirm this is your email by replying.
</li>
<li>
Then perform this step.
</li>
</ol>
<p>
Please solve this <img alt="complex equation" src="http://upload.wikimedia.org/wikipedia/commons/8/8d/First_Equation_Ever.png"/>. Then, in any order, could you please:
</p>
<ul>
<li>
a point.
</li>
<li>
another point, with a <a href="http://en.wikipedia.org/wiki/Hyperlink">hyperlink</a>.
</li>
</ul>
<p>
Sincerely,
</p>
<p>
The whatever.com team
</p>
</main>
<footer>
Ph: 000 000 000<br/>
mail: whatever st
</footer>
</body>
</html>
...will be transformed into:
Whatever Inc.
Thanks for your enquiry. As this is the 1st time you have contacted us, we would like to clarify a few things:
1. Please confirm this is your email by replying.
2. Then perform this step.
Please solve this [complex equation<http://upload.wikimedia.org/wikipedia/commons/8/8d/First_Equation_Ever.png>]. Then, in any order, could you please:
* a point.
* another point, with a hyperlink<http://en.wikipedia.org/wiki/Hyperlink>.
Sincerely,
The whatever.com team
Ph: 000 000 000
mail: whatever st
...as opposed to:
Whatever Inc.
Thanks for your enquiry. As this is the 1st time you have contacted us, we would like to clarify a few things:
Please confirm this is your email by replying.
Then perform this step.
Please solve this . Then, in any order, could you please:
a point.
another point, with a hyperlink.
Sincerely,
The whatever.com team
Ph: 000 000 000
mail: whatever st
That problem happens when you try to access from a different domain or different port.
If you're using Visual Studio, then go to Tools > NuGet Package Manager > Package Manager Console. There you have to install the NuGet Package Microsoft.AspNet.WebApi.Cors
Install-Package Microsoft.AspNet.WebApi.Cors
Then, in PROJECT > App_Start > WebApiConfig, enable CORS
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//Enable CORS. Note that the domain doesn't have / in the end.
config.EnableCors(new EnableCorsAttribute("https://tiagoperes.eu",headers:"*",methods:"*"));
....
}
}
Once installed successfully, build the solution and that should suffice
I just fixed my problem right-clicking in the layout folder and clicking in the option Validate. Some windows will appear, you just clik OK and ist fine.
Here's my solution:
@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>
So many answers and not much thorough explanations
The following syntax works Using Databricks Notebook with Spark 2.4
from pyspark.sql.functions import *
df = df.withColumn("COL_NAME", to_date(BLDFm["LOAD_DATE"], "MM-dd-yyyy"))
Note that you have to specify the entry format you have (in my case "MM-dd-yyyy") and the import is mandatory as the to_date is a spark sql function
Also Tried this syntax but got nulls instead of a proper cast :
df = df.withColumn("COL_NAME", df["COL_NAME"].cast("Date"))
(Note I had to use brackets and quotes for it to be syntaxically correct though)
PS : I have to admit this is like a syntax jungle, there are many possible ways entry points, and the official API references lack proper examples.
This will also work.
$('#test').find("select option:contains('B')").filter(":selected");
Just wanted to share an alias I created which does the same thing:
Add the following to your ~/.gitconfig
[alias]
delete-tag = "!f() { \
echo 'deleting tag' $1 'from remote/origin ausing command: git push --delete origin tagName;'; \
git push --delete origin $1; \
echo 'deleting tag' $1 'from local using command: git tag -d tagName;'; \
git tag -d $1; \
}; f"
The usage looks like:
-->git delete-tag v1.0-DeleteMe
deleting tag v1.0-DeleteMe from remote/origin ausing command: git push --delete origin tagName;
To https://github.com/jsticha/pafs
- [deleted] v1.0-DeleteMe
deleting tag v1.0-DeleteMe from local using command: git tag -d tagName;
Deleted tag 'v1.0-DeleteMe' (was 300d3ef22)
Using the ${#VAR}
syntax will calculate the number of characters in a variable.
https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
In PL/SQL you can't use operators such as '=' or '<>' to test for NULL
because all comparisons to NULL
return NULL
. To compare something against NULL
you need to use the special operators IS NULL
or IS NOT NULL
which are there for precisely this purpose. Thus, instead of writing
IF var = NULL THEN...
you should write
IF VAR IS NULL THEN...
In the case you've given you also have the option of using the NVL
built-in function. NVL
takes two arguments, the first being a variable and the second being a value (constant or computed). NVL
looks at its first argument and, if it finds that the first argument is NULL
, returns the second argument. If the first argument to NVL
is not NULL
, the first argument is returned. So you could rewrite
IF var IS NULL THEN
var := 5;
END IF;
as
var := NVL(var, 5);
I hope this helps.
And because it's nearly ten years since I wrote this answer, let's celebrate by expanding it just a bit.
The COALESCE
function is the ANSI equivalent of Oracle's NVL
. It differs from NVL
in a couple of IMO good ways:
It takes any number of arguments, and returns the first one which is not NULL. If all the arguments passed to COALESCE
are NULL, it returns NULL.
In contrast to NVL
, COALESCE
only evaluates arguments if it must, while NVL
evaluates both of its arguments and then determines if the first one is NULL, etc. So COALESCE
can be more efficient, because it doesn't spend time evaluating things which won't be used (and which can potentially cause unwanted side effects), but it also means that COALESCE
is not a 100% straightforward drop-in replacement for NVL
.
I was looking for shortest way to draw an 1px line, as whole load of separated CSS is not the fastest or shortest solution.
Up to HTML5, the WAS a shorter way for 1px hr: <hr noshade> but.. The noshade attribute of <hr> is not supported in HTML5. Use CSS instead. (nor other attibutes used before, as size, width, align)...
Now, this one is quite tricky, but works well if most simple 1px hr needed:
Variation 1, BLACK hr: (best solution for black)
<hr style="border-bottom: 0px">
Output: FF, Opera - black / Safari - dark gray
Variation 2, GRAY hr (shortest!):
<hr style="border-top: 0px">
Output: Opera - dark gray / FF - gray / Safari - light gray
<hr style="border: none; border-bottom: 1px solid red;">
Output: Opera / FF / Safari : 1px red.
Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example
A similar question was asked, but it didn't ask about statics.
A static variable is basically a global variable, even if you cannot access it globally. Usually there is an address for it that is in the executable itself. There is only one copy for the entire program. No matter how many times you go into a function call (or class) (and in how many threads!) the variable is referring to the same memory location.
The heap is a bunch of memory that can be used dynamically. If you want 4kb for an object then the dynamic allocator will look through its list of free space in the heap, pick out a 4kb chunk, and give it to you. Generally, the dynamic memory allocator (malloc, new, et c.) starts at the end of memory and works backwards.
Explaining how a stack grows and shrinks is a bit outside the scope of this answer, but suffice to say you always add and remove from the end only. Stacks usually start high and grow down to lower addresses. You run out of memory when the stack meets the dynamic allocator somewhere in the middle (but refer to physical versus virtual memory and fragmentation). Multiple threads will require multiple stacks (the process generally reserves a minimum size for the stack).
Statics/globals are useful for memory that you know you will always need and you know that you don't ever want to deallocate. (By the way, embedded environments may be thought of as having only static memory... the stack and heap are part of a known address space shared by a third memory type: the program code. Programs will often do dynamic allocation out of their static memory when they need things like linked lists. But regardless, the static memory itself (the buffer) is not itself "allocated", but rather other objects are allocated out of the memory held by the buffer for this purpose. You can do this in non-embedded as well, and console games will frequently eschew the built in dynamic memory mechanisms in favor of tightly controlling the allocation process by using buffers of preset sizes for all allocations.)
Stack variables are useful for when you know that as long as the function is in scope (on the stack somewhere), you will want the variables to remain. Stacks are nice for variables that you need for the code where they are located, but which isn't needed outside that code. They are also really nice for when you are accessing a resource, like a file, and want the resource to automatically go away when you leave that code.
Heap allocations (dynamically allocated memory) is useful when you want to be more flexible than the above. Frequently, a function gets called to respond to an event (the user clicks the "create box" button). The proper response may require allocating a new object (a new Box object) that should stick around long after the function is exited, so it can't be on the stack. But you don't know how many boxes you would want at the start of the program, so it can't be a static.
I've heard a lot lately about how great Garbage Collectors are, so maybe a bit of a dissenting voice would be helpful.
Garbage Collection is a wonderful mechanism for when performance is not a huge issue. I hear GCs are getting better and more sophisticated, but the fact is, you may be forced to accept a performance penalty (depending upon use case). And if you're lazy, it still may not work properly. At the best of times, Garbage Collectors realize that your memory goes away when it realizes that there are no more references to it (see reference counting). But, if you have an object that refers to itself (possibly by referring to another object which refers back), then reference counting alone will not indicate that the memory can be deleted. In this case, the GC needs to look at the entire reference soup and figure out if there are any islands that are only referred to by themselves. Offhand, I'd guess that to be an O(n^2) operation, but whatever it is, it can get bad if you are at all concerned with performance. (Edit: Martin B points out that it is O(n) for reasonably efficient algorithms. That is still O(n) too much if you are concerned with performance and can deallocate in constant time without garbage collection.)
Personally, when I hear people say that C++ doesn't have garbage collection, my mind tags that as a feature of C++, but I'm probably in the minority. Probably the hardest thing for people to learn about programming in C and C++ are pointers and how to correctly handle their dynamic memory allocations. Some other languages, like Python, would be horrible without GC, so I think it comes down to what you want out of a language. If you want dependable performance, then C++ without garbage collection is the only thing this side of Fortran that I can think of. If you want ease of use and training wheels (to save you from crashing without requiring that you learn "proper" memory management), pick something with a GC. Even if you know how to manage memory well, it will save you time which you can spend optimizing other code. There really isn't much of a performance penalty anymore, but if you really need dependable performance (and the ability to know exactly what is going on, when, under the covers) then I'd stick with C++. There is a reason that every major game engine that I've ever heard of is in C++ (if not C or assembly). Python, et al are fine for scripting, but not the main game engine.
you can try this out,if you want to remove origin and then add it:
git remote remove origin
then:
git remote add origin http://your_url_here
I'm late answering this, but there's not one reasonable answer to date, despite being a popular question with highly upvoted answers....
As illustrated by the Standard library's <iosfwd>
header, the proper way to provide forward declarations for others is to have a forward declaration header. For example:
a.fwd.h:
#pragma once
class A;
a.h:
#pragma once
#include "a.fwd.h"
#include "b.fwd.h"
class A
{
public:
void f(B*);
};
b.fwd.h:
#pragma once
class B;
b.h:
#pragma once
#include "b.fwd.h"
#include "a.fwd.h"
class B
{
public:
void f(A*);
};
The maintainers of the A
and B
libraries should each be responsible for keeping their forward declaration headers in sync with their headers and implementation files, so - for example - if the maintainer of "B" comes along and rewrites the code to be...
b.fwd.h:
template <typename T> class Basic_B;
typedef Basic_B<char> B;
b.h:
template <typename T>
class Basic_B
{
...class definition...
};
typedef Basic_B<char> B;
...then recompilation of the code for "A" will be triggered by the changes to the included b.fwd.h
and should complete cleanly.
Say - instead of using a forward declaration header as explained above - code in a.h
or a.cc
instead forward-declares class B;
itself:
a.h
or a.cc
did include b.h
later:
B
(i.e. the above change to B broke A and any other clients abusing forward declarations, instead of working transparently).b.h
- possible if A just stores/passes around Bs by pointer and/or reference)
#include
analysis and changed file timestamps won't rebuild A
(and its further-dependent code) after the change to B, causing errors at link time or run time. If B is distributed as a runtime loaded DLL, code in "A" may fail to find the differently-mangled symbols at runtime, which may or may not be handled well enough to trigger orderly shutdown or acceptably reduced functionality.If A's code has template specialisations / "traits" for the old B
, they won't take effect.
Further to @Udi post this is what the script tried to do, but did not work with me.
I had to the set the following in the PATH
nothing else.
C:\Users\hUTBER\AppData\Local\Programs\Python\Python35
C:\Users\hUTBER\AppData\Local\Programs\Python\Python35\Scripts
Were mine and now python
works in the cmd
Give a class to your cell containing the icon
<td class="icon"><i class="icon-ok"></i></td>
and then
.icon{
text-align: center;
}
I would use x.y.z
kind of versioning
x
- major release
y
- minor release
z
- build number
To test a bit you would do the following: (assuming flags is a 32 bit number)
Test Bit:
if((flags & 0x08) == 0x08)
(If bit 4 is set then its true)
Toggle Back (1 - 0 or 0 - 1): flags = flags ^ 0x08;
Reset Bit 4 to Zero: flags = flags & 0xFFFFFF7F;
I had this challenge when working on a Rails 6 API application in Ubuntu 20.04.
I had already existing models, and I needed to generate corresponding controllers for the models and also add their allowed attributes in the controller params.
Here's how I did it:
I used the rails generate scaffold_controller
to get it done.
I simply ran the following commands:
rails generate scaffold_controller School name:string logo:json motto:text address:text
rails generate scaffold_controller Program name:string logo:json school:references
This generated the corresponding controllers for the models and also added their allowed attributes in the controller params, including the foreign key attributes.
create app/controllers/schools_controller.rb
invoke test_unit
create test/controllers/schools_controller_test.rb
create app/controllers/programs_controller.rb
invoke test_unit
create test/controllers/programs_controller_test.rb
That's all.
I hope this helps
SELECT COUNT(1) FROM FB
WHERE Dte > DATE_SUB(now(), INTERVAL 2 MONTH)
@Context ServletContext ctx;
@Context private HttpServletResponse response;
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/download/{filename}")
public StreamingOutput download(@PathParam("filename") String fileName) throws Exception {
final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");
return new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException,
WebApplicationException {
Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output));
}
};
}
Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.
function myFunction() {_x000D_
var selchbox = [];_x000D_
var inputfields = document.getElementsByName("myCheck");_x000D_
var ar_inputflds = inputfields.length;_x000D_
_x000D_
for (var i = 0; i < ar_inputflds; i++) {_x000D_
if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
selchbox.push(inputfields[i].value);_x000D_
}_x000D_
return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
var selchb = myFunction();_x000D_
console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.
So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.
It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
I'd like to add a correction/update to the bit about $HOME taking precedence. The home directory in /etc/passwd takes precedence over everything.
I'm a long time Cygwin user and I just did a clean install of Windows 7 x64 and Cygwin V1.126. I was going nuts trying to figure out why every time I ran ssh I kept getting:
e:\>ssh foo.bar.com
Could not create directory '/home/dhaynes/.ssh'.
The authenticity of host 'foo.bar.com (10.66.19.19)' can't be established.
...
I add the HOME=c:\users\dhaynes definition in the Windows environment but still it kept trying to create '/home/dhaynes'. I tried every combo I could including setting HOME to /cygdrive/c/users/dhaynes. Googled for the error message, could not find anything, couldn't find anything on the cygwin site. I use cygwin from cmd.exe, not bash.exe but the problem was present in both.
I finally realized that the home directory in /etc/passwd was taking precedence over the $HOME environment variable. I simple re-ran 'mkpasswd -l >/etc/passwd' and that updated the home directory, now all is well with ssh.
That may be obvious to linux types with sysadmin experience but for those of us who primarily use Windows it's a bit obscure.
This is WRONG:
import {
Tabs,
Tabpane
} from 'iview'
This is CORRECT:
import Iview from "iview";
const { Tabs, Tabpane} = Iview;
A char
variable is actually an 8-bit integral value. It will have values from 0
to 255
. These are ASCII codes. 0
stands for the C-null character, and 255
stands for an empty symbol.
So, when you write the following assignment:
char a = 'a';
It is the same thing as:
char a = 97;
So, you can compare two char
variables using the >
, <
, ==
, <=
, >=
operators:
char a = 'a';
char b = 'b';
if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);
First, this code here,
string [] scripts = new String [] ("test3","test4","test5");
should be
String[] scripts = new String [] {"test3","test4","test5"};
Please read this tutorial on Arrays
Second,
Arrays are fixed size, so you can't add new Strings to above array. You may override existing values
scripts[0] = string1;
(or)
Create array with size then keep on adding elements till it is full.
If you want resizable arrays, consider using ArrayList.
This esc
behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.
var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);
If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.
//store default value for all elements on page. set new default on blur
$('input').each( function() {
$(this).data('default', $(this).val());
$(this).blur( function() { $(this).data('default', $(this).val()); });
});
$('input').keyup( function(e) {
if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});
For short codes, there's probably no difference. This is especially true as the table holding these codes are likely to be very small (a couple thousand rows at most) and not change often (when is the last time we added a new US State).
For larger tables with a wider variation among the key, this can be dangerous. Think about using e-mail address/user name from a User table, for example. What happens when you have a few million users and some of those users have long names or e-mail addresses. Now any time you need to join this table using that key it becomes much more expensive.
subprocess.call
will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.
import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
If you've been working on a branch on-and-off, or lots has happened in other branches while you've been working on something, it's best to rebase your branch onto master. This keeps the history tidy and makes things a lot easier to follow.
git checkout master
git pull
git checkout local_branch_name
git rebase master
git push --force # force required if you've already pushed
Notes:
There's a chapter on rebasing at http://git-scm.com/book/ch3-6.html, and loads of other resources out there on the web.
Use a nice editor like SciTe, select your code, press Ctrl + Q and done.
If you don't have an editor that supports block comments you can use a triple quoted string at the start and the end of your code block to 'effectively' comment it out. It is not the best practice though.
If you face an issue of CORS, you can use https://api.ipify.org/.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
publicIp = httpGet("https://api.ipify.org/");
alert("Public IP: " + publicIp);
I agree that using synchronous HTTP call is not good idea. You can use async ajax call then.
I want to make sure this is out there, because it's so hard to get right:
using System.Runtime.InteropServices; //GuidAttribute
using System.Reflection; //Assembly
using System.Threading; //Mutex
using System.Security.AccessControl; //MutexAccessRule
using System.Security.Principal; //SecurityIdentifier
static void Main(string[] args)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid =
((GuidAttribute)Assembly.GetExecutingAssembly().
GetCustomAttributes(typeof(GuidAttribute), false).
GetValue(0)).Value.ToString();
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format( "Global\\{{{0}}}", appGuid );
// Need a place to store a return value in Mutex() constructor call
bool createdNew;
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule =
new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
, null)
, MutexRights.FullControl
, AccessControlType.Allow
);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
{
// edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
// edited by acidzombie24
// mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access");
}
catch (AbandonedMutexException)
{
// Log the fact that the mutex was abandoned in another process,
// it will still get acquired
hasHandle = true;
}
// Perform your work here.
}
finally
{
// edited by acidzombie24, added if statement
if(hasHandle)
mutex.ReleaseMutex();
}
}
}
You were almost there : just add theme(legend.title=element_blank())
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
theme(legend.title=element_blank())
This page on Cookbook for R gives plenty of details on how to customize legends.
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
Based on the example here: http://drupal.org/node/550488
The following will probably work in .htaccess
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
<FilesMatch (\.js|\.html)$>
ExpiresActive Off
</FilesMatch>
</IfModule>
If you don't mind changing your HTML, you can use the data-toggle
attribute on <button>
s. See the Single toggle section of the button examples:
<button type="button" class="btn btn-primary" data-toggle="button">
Single toggle
</button>
When you write the following line of code in TypeScript:
var SUCSS = {};
The type of SUCSS
is inferred from the assignment (i.e. it is an empty object type).
You then go on to add a property to this type a few lines later:
SUCSS.fadeDiv = //...
And the compiler warns you that there is no property named fadeDiv
on the SUCSS
object (this kind of warning often helps you to catch a typo).
You can either... fix it by specifying the type of SUCSS
(although this will prevent you from assigning {}
, which doesn't satisfy the type you want):
var SUCSS : {fadeDiv: () => void;};
Or by assigning the full value in the first place and let TypeScript infer the types:
var SUCSS = {
fadeDiv: function () {
// Simplified version
alert('Called my func');
}
};
Just saw someone mention this question in another and thought I would add a method I didn't see yet:
function clear(el) {
el.parentNode.replaceChild(el.cloneNode(false), el);
}
var myNode = document.getElementById("foo");
clear(myNode);
The clear function is taking the element and using the parent node to replace itself with a copy without it's children. Not much performance gain if the element is sparse but when the element has a bunch of nodes the performance gains are realized.
If you're like me running in a restricted environment without administrative privileges, that means your only way to get node up and running is to grab the executable (node.exe) without using the installer. You also cannot change the path variable which makes it that much more challenging.
Here's what I did (for Windows)
npm install -g express
Running the installers through npm will now auto install packages where they need to be located (node_modules and the root)
Don't forget you will not be able to set the path variable if you do not have proper permissions. So your best route is to open a command prompt in the node.exe directory (shift right-click "Open command window here")
Following SierraX and Peter's suggestion about text manipulation, curly brackets {}
are used to pass a variable to a command, for instance:
Let's say you have a sposi.txt file containing the first line of a well-known Italian novel:
> sposi="somewhere/myfolder/sposi.txt"
> cat $sposi
Ouput: quel ramo del lago di como che volge a mezzogiorno
Now create two variables:
# Search the 2nd word found in the file that "sposi" variable points to
> word=$(cat $sposi | cut -d " " -f 2)
# This variable will replace the word
> new_word="filone"
Now substitute the word variable content with the one of new_word, inside sposi.txt file
> sed -i "s/${word}/${new_word}/g" $sposi
> cat $sposi
Ouput: quel filone del lago di como che volge a mezzogiorno
The word "ramo" has been replaced.
You should check user authentication in two main sites.
'$routeChangeStart'
callbackIf you have homebrew you can also install via brew
$ brew install docker-compose
This is a good way to install on a Mac OS system
As of April 2017, this is the current URL used for sharing:
Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect
First check whether the folder name is right or wrong since while you copying to one folder from other accidently it takes other folder address eg it take C
instead of F
So from OPTION>DIRECTORY
change the folder name
/bin/sh
is usually a link to the system's default shell, which is often bash
but on, e.g., Debian systems is the lighter weight dash
. Either way, the original Bourne shell is sh
, so if your script uses some bash
(2nd generation, "Bourne Again sh") specific features ([[ ]]
tests, arrays, various sugary things, etc.), then you should be more specific and use the later. This way, on systems where bash is not installed, your script won't run. I understand there may be an exciting trilogy of films about this evolution...but that could be hearsay.
Also note that when evoked as sh
, bash
to some extent behaves as POSIX standard sh
(see also the GNU docs about this).
I always use Gliffy works perfectly and does lots of things including class diagrams.
Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/
Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/
Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:
As you gain more experience, you'll start to appreciate the rest of its rich set of features.
I am using Spring STS 3.8.3. I had a similar problem. I fixed it by using information from this thread And also by fixing some maven settings. click Spring Tool Suite -> Preferences -> Maven and uncheck the box that says "Do not automatically update dependencies from remote depositories" Also I checked the boxes that say "Download Artifact Sources" and "download Artifact javadoc".
If you want to see how to do a proper definition go into Sublime Text->Preferences->Key Bindings - Default and search for the command you want to override.
{ "keys": ["f12"], "command": "goto_definition" },
{ "keys": ["super+alt+down"], "command": "goto_definition" }
Those are two that show in my Default.
On Mac I copied the second to override.
in Sublime Text -> Preferences -> Key Bindings - User I added this
/* Beginning of File */
[
{
"keys": ["super+shift+i"], "command": "goto_definition"
}
]
/* End of File */
This binds it to the Command + Shift + 1 combination on mac.
Here is my way . Of course, you could put it into a procedure :-)
SET @median_counter = (SELECT FLOOR(COUNT(*)/2) - 1 AS `median_counter` FROM `data`);
SET @median = CONCAT('SELECT `val` FROM `data` ORDER BY `val` LIMIT ', @median_counter, ', 1');
PREPARE median FROM @median;
EXECUTE median;
You could avoid the variable @median_counter
, if you substitude it:
SET @median = CONCAT( 'SELECT `val` FROM `data` ORDER BY `val` LIMIT ',
(SELECT FLOOR(COUNT(*)/2) - 1 AS `median_counter` FROM `data`),
', 1'
);
PREPARE median FROM @median;
EXECUTE median;
Let me Simplify , first download JDK from Oracle Website : Link
2] Then Extract it
3] Create a folder (jvm) in /usr/lib/ i.e /usr/lib/jvm
4] move the extracted folder from the jdk to /usr/lib/jvm/
*Note : use terminal , sudo , mv command i.e. sudo mv
5] Create a .sh file at /etc/profile.d/ eg: /etc/profile.d/myenvvar.sh
6] In the .sh file type
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0
export PATH=$PATH:$JAVA_HOME/bin
*Note : use terminal , gedit and sudo eg: sudo gedit myenvvar.sh
7] Turn Off the Computer, after all these steps and Restart it
8]Open Terminal , and type
java -version
9] Check the output , then type
echo $JAVA_HOME
10] Check the output and be happy :)
JavaScript is a client-side language and your MySQL database is going to be running on a server.
So you have to rename your file to index.php
for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.
(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)
So after you renamed your file, go to the very top, before <html>
or <!DOCTYPE html>
and type:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
/*Creating variables*/
$name = $_POST["name"];
$address = $_POST["address"];
$age = $_POST["age"];
$dbhost = "localhost"; /*most of the time it's localhost*/
$username = "yourusername";
$password = "yourpassword";
$dbname = "mydatabase";
$mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
$query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
mysqli_query($mysql, $query);
}
?>
<!DOCTYPE html>
<html>
<head>.......
....
<form method="post">
<input name="name" type="text"/>
<input name="address" type="text"/>
<input name="age" type="text"/>
</form>
....
EDIT: I had not realized this was about the data format. You could use
import pandas as pd
import scipy
two_data = pd.DataFrame(data, index=data['Category'])
Then accessing the categories is as simple as
scipy.stats.ttest_ind(two_data.loc['cat'], two_data.loc['cat2'], equal_var=False)
The loc operator
accesses rows by label.
one sided or two sided dependent or independent
If you have two independent samples but you do not know that they have equal variance, you can use Welch's t-test. It is as simple as
scipy.stats.ttest_ind(cat1['values'], cat2['values'], equal_var=False)
For reasons to prefer Welch's test, see https://stats.stackexchange.com/questions/305/when-conducting-a-t-test-why-would-one-prefer-to-assume-or-test-for-equal-vari.
For two dependent samples, you can use
scipy.stats.ttest_rel(cat1['values'], cat2['values'])
You can apply dirname repeatedly to climb higher: dirname(dirname(file))
. This can only go as far as the root package, however. If this is a problem, use os.path.abspath
: dirname(dirname(abspath(file)))
.
Static import is used to import static fields / method of a class instead of:
package test;
import org.example.Foo;
class A {
B b = Foo.B_INSTANCE;
}
You can write :
package test;
import static org.example.Foo.B_INSTANCE;
class A {
B b = B_INSTANCE;
}
It is useful if you are often used a constant from another class in your code and if the static import is not ambiguous.
Btw, in your example "import static org.example.Myclass;" won't work : import is for class, import static is for static members of a class.
'It' requires a dll file called cvextern.dll . 'It' can be either your own cs file or some other third party dll which you are using in your project.
To call native dlls to your own cs file, copy the dll into your project's root\lib directory and add it as an existing item. (Add -Existing item) and use Dllimport with correct location.
For third party , copy the native library to the folder where the third party library resides and add it as an existing item.
After building make sure that the required dlls are appearing in Build folder. In some cases it may not appear or get replaced in Build folder. Delete the Build folder manually and build again.
A good example of where this matters in practice is the ConcurrentSkipListSet
implementation in the JDK, which states:
Beware that, unlike in most collections, the size method is not a constant-time operation.
This is a clear case where isEmpty()
is much more efficient than checking whether size()==0
.
You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.
unlink is the right php function for your use case.
unlink('/path/to/file');
Without more information, I can't tell you what went wrong when you used it.
When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,
ErrorDocument 404 /yourfoldernames/errors/404.html
Java 8 Lambda shortens the sort.
Collections.sort(stdList, (o1, o2) -> o1.getName().compareTo(o2.getName()));
I presume your application uses a masked edit box? This is a relatively well known problem, documented by Microsoft here:
http://support.microsoft.com/kb/177088
The article refers to VB4 and 5, but I am pretty sure the same is true for VB6.
EDIT
On further research, I am finding references to this problem with other controls as well. Recompiling your application on Windows XP for users that are running XP will probably produce them a working version, though it's not an ideal solution...
When you deploy a Java EE web application (using frameworks or not),its structure must follow some requirements/specifications. These specifications come from :
- The servlet container (e.g Tomcat)
- Java Servlet API
- Your application domain
Java Servlet API requirements
Java Servlet API states that your root application directory must have the following structure :
ApplicationName
|
|--META-INF
|--WEB-INF
|_web.xml <-- Here is the configuration file of your web app(where you define servlets, filters, listeners...)
|_classes <--Here goes all the classes of your webapp, following the package structure you defined. Only
|_lib <--Here goes all the libraries (jars) your application need
These requirements are defined by Java Servlet API.
3. Your application domain
Now that you've followed the requirements of the Servlet container(or application server) and the Java Servlet API requirements, you can organize the other parts of your webapp based upon what you need.
- You can put your resources (JSP files, plain text files, script files) in your application root directory. But then, people can access them directly from their browser, instead of their requests being processed by some logic provided by your application. So, to prevent your resources being directly accessed like that, you can put them in the WEB-INF directory, whose contents is only accessible by the server.
-If you use some frameworks, they often use configuration files. Most of these frameworks (struts, spring, hibernate) require you to put their configuration files in the classpath (the "classes" directory).
If you want to sum
all values of one column, it's more efficient to use DataFrame
's internal RDD
and reduce
.
import sqlContext.implicits._
import org.apache.spark.sql.functions._
val df = sc.parallelize(Array(10,2,3,4)).toDF("steps")
df.select(col("steps")).rdd.map(_(0).asInstanceOf[Int]).reduce(_+_)
//res1 Int = 19
Another solution is to create a normal class which implements PropertyChanger like this
public class ViewProps : PropertyChanger
{
private string _MyValue = string.Empty;
public string MyValue
{
get {
return _MyValue
}
set
{
if (_MyValue == value)
{
return;
}
SetProperty(ref _MyValue, value);
}
}
}
Then create a static instance of the class somewhere you wont
public class MyClass
{
private static ViewProps _ViewProps = null;
public static ViewProps ViewProps
{
get
{
if (_ViewProps == null)
{
_ViewProps = new ViewProps();
}
return _ViewProps;
}
}
}
And now use it as static property
<TextBlock Text="{x:Bind local:MyClass.ViewProps.MyValue, Mode=OneWay}" />
And here is PropertyChanger implementation if necessary
public abstract class PropertyChanger : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
SessionState
ViewState
This is impossible as you cannot return from an asynchronous call inside a synchronous method.
In this case you need to pass a callback to foo that will receive the return value
function foo(address, fn){
geocoder.geocode( { 'address': address}, function(results, status) {
fn(results[0].geometry.location);
});
}
foo("address", function(location){
alert(location); // this is where you get the return value
});
The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.
If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.
Here's a Tree
public class Tree<T> : List<Tree<T>>
{
public T Data { get; private set; }
public Tree(T data)
{
this.Data = data;
}
}
In my case, It was returning one output parameter and was not Returning any value.
So changed it to
param.Direction = ParameterDirection.Output;
command.ExecuteScalar();
and then it was throwing size error. so had to set the size as well
SqlParameter param = new SqlParameter("@Name",SqlDbType.NVarChar);
param.Size = 10;
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference
use v5.13.7;
foreach my $key (keys $ad_grp_ref) {
...
}
Note that the reason topicId was "not defined" per the error message is that it existed as a local variable when the setTimeout was executed, but not when the delayed call to postinsql happened. Variable lifetime is especially important to pay attention to, especially when trying something like passing "this" as an object reference.
I heard that you can pass topicId as a third parameter to the setTimeout function. Not much detail is given but I got enough information to get it to work, and it's successful in Safari. I don't know what they mean about the "millisecond error" though. Check it out here:
In SQL Server, you would say:
Select name from users
UNION [ALL]
SELECT 'JASON'
In Oracle, you would say
Select name from user
UNION [ALL]
Select 'JASON' from DUAL
Sure, you just call it from within the SP, there's no special syntax.
Ex:
PROCEDURE some_sp
AS
BEGIN
some_other_sp('parm1', 10, 20.42);
END;
If the procedure is in a different schema than the one the executing procedure is in, you need to prefix it with schema name.
PROCEDURE some_sp
AS
BEGIN
other_schema.some_other_sp('parm1', 10, 20.42);
END;
You can find what you want in windows by looking with the windows dir command, use the administrator account to make it easy:
c:>dir wsdl.exe /s
Here is a bash script that fully answers the (revised) original question. That is, given any .tsv file, it provides the synopsis for each of the columns in turn. Apart from bash itself, it only uses standard *ix/Mac tools: sed tr wc cut sort uniq.
#!/bin/bash
# Syntax: $0 filename
# The input is assumed to be a .tsv file
FILE="$1"
cols=$(sed -n 1p $FILE | tr -cd '\t' | wc -c)
cols=$((cols + 2 ))
i=0
for ((i=1; i < $cols; i++))
do
echo Column $i ::
cut -f $i < "$FILE" | sort | uniq -c
echo
done
Wrap the code within $(document).ready(function(){...........});
handler , also remove the ;
after if
$(document).ready(function(){
$('#purpose').on('change', function() {
if ( this.value == '1')
//.....................^.......
{
$("#business").show();
}
else
{
$("#business").hide();
}
});
});
map.forEach((key, value) -> System.out.println(key + " " + value));
Using java 8 features
Out of your comments to Mike Monkiewicz answer I suggest to use a simpler model: Use regular development branches, but use the squash option of the merge to get a single commit in your master branch:
git checkout -b bug1 # create the development branch
* hack hack hack * # do some work
git commit
* hack hack hack *
git commit
* hack hack hack *
git commit
* hack hack hack *
git commit
git checkout master # go back to the master branch
git merge --squash bug1 # merge the work back
git commit # commit the merge (don't forget
# to change the default commit message)
git branch -D bug1 # remove the development branch
The advantage of this procedure is that you can use the normal git work flow.
This javascript will add absolute positioned div's with pagenumbers on the right bottom corner and works in all browsers.
A4 height = 297mm = 1123px(96dpi)
<html>
<head>
<style type="text/css">
@page {
size: A4;
margin: 0;
}
body {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload = addPageNumbers;
function addPageNumbers() {
var totalPages = Math.ceil(document.body.scrollHeight / 1123); //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi,
for (var i = 1; i <= totalPages; i++) {
var pageNumberDiv = document.createElement("div");
var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
pageNumberDiv.style.position = "absolute";
pageNumberDiv.style.top = "calc((" + i + " * (297mm - 0.5px)) - 40px)"; //297mm A4 pageheight; 0,5px unknown needed necessary correction value; additional wanted 40px margin from bottom(own element height included)
pageNumberDiv.style.height = "16px";
pageNumberDiv.appendChild(pageNumber);
document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
pageNumberDiv.style.left = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
}
}
</script>
<div id="content">
Lorem ipsum....
</div>
</body>
</html>
There's no need to fiddle around with ssh configurations. Use a configuration file (not a Dockerfile) that contains environment variables, and have a shell script update your docker file at runtime. You keep tokens out of your Dockerfiles and you can clone over https (no need to generate or pass around ssh keys).
Go to Settings > Personal Access Tokens
repo
scope enabled.git clone https://[email protected]/user-or-org/repo
Some commenters have noted that if you use a shared Dockerfile, this could expose your access key to other people on your project. While this may or may not be a concern for your specific use case, here are some ways you can deal with that:
sed
or similar, i.e. calling the script with sh rundocker.sh MYTOKEN=foo
which would replace on https://{{MY_TOKEN}}@github.com/user-or-org/repo
. Note that you could also use a configuration file (in .yml or whatever format you want) to do the same thing but with environment variables.Others have suggested ways to make newlist after filtering e.g.
newl = [x for x in l if x not in [2,3,7]]
or
newl = filter(lambda x: x not in [2,3,7], l)
but from your question it looks you want in-place modification for that you can do this, this will also be much much faster if original list is long and items to be removed less
l = range(1,10)
for o in set([2,3,7,11]):
try:
l.remove(o)
except ValueError:
pass
print l
output: [1, 4, 5, 6, 8, 9]
I am checking for ValueError exception so it works even if items are not in orginal list.
Also if you do not need in-place modification solution by S.Mark
is simpler.
First, you really need to keep in mind that it's never impossible to reverse-engineer something. Everything is hackable. A smart developer using a smart IDE can already get far enough.
Well, you can find here a list. ProGuard is pretty good. I've used it myself, but only to "minify" Java code.
IMPORTANT: I'm extending the question/answer to strip either single or double quotes. And I interpret the question to mean that BOTH quotes must be present, and matching, to perform the strip. Otherwise, the string is returned unchanged.
To "dequote" a string representation, that might have either single or double quotes around it (this is an extension of @tgray's answer):
def dequote(s):
"""
If a string has single or double quotes around it, remove them.
Make sure the pair of quotes match.
If a matching pair of quotes is not found, return the string unchanged.
"""
if (s[0] == s[-1]) and s.startswith(("'", '"')):
return s[1:-1]
return s
Explanation:
startswith
can take a tuple, to match any of several alternatives. The reason for the DOUBLED parentheses ((
and ))
is so that we pass ONE parameter ("'", '"')
to startswith()
, to specify the permitted prefixes, rather than TWO parameters "'"
and '"'
, which would be interpreted as a prefix and an (invalid) start position.
s[-1]
is the last character in the string.
Testing:
print( dequote("\"he\"l'lo\"") )
print( dequote("'he\"l'lo'") )
print( dequote("he\"l'lo") )
print( dequote("'he\"l'lo\"") )
=>
he"l'lo
he"l'lo
he"l'lo
'he"l'lo"
(For me, regex expressions are non-obvious to read, so I didn't try to extend @Alex's answer.)
This one evaluates to the same but a bit smaller
+!![]+''+(+[])
so is evaluates to
+(true) + '' + (0)
1 + '' + 0
"10"
So now you got that, try this one:
_=$=+[],++_+''+$
The answer is in this line of the output of readelf -a
in the original question
[Requesting program interpreter: /lib/ld-linux.so.2]
I was missing the /lib/ld-linux.so.2 file, which is needed to run 32-bit apps. The Ubuntu package that has this file is libc6-i386.
You can convert a datetime object to a date with the date() method of the date time object, as follows:
<datetime_object>.date()
You can use the toggle-event
(docs) method to assign 2 (or more) handlers that toggle with each click.
Example: http://jsfiddle.net/SQHQ2/1/
$("#topbar").toggle(function(){
$(this).animate({height:40},200);
},function(){
$(this).animate({height:10},200);
});
or you could create your own toggle behavior:
Example: http://jsfiddle.net/SQHQ2/
$("#topbar").click((function() {
var i = 0;
return function(){
$(this).animate({height:(++i % 2) ? 40 : 10},200);
}
})());
I know it is not a good habit to answer an old question but I'm putting this answer for people who would see the question afterwards.
The best way to change the state in JQuery now is through
$("#input").prop('disabled', true);
$("#input").prop('disabled', false);
Please check this link for full illustration. Disable/enable an input with jQuery?
Here a different approach to get meta data. This very helpful SQL command returns you the table / view definition as text:
SELECT text FROM syscomments WHERE id = OBJECT_ID('MySchema.MyTable') ORDER BY number, colid2, colid
Enjoy Patrick
If you are in a directory or folder where the script file is available then simply change the file permission in executable mode by doing
chmod +x your_filename.sh
After that you will run the script by using the following command.
$ sudo ./your_filename.sh
Above the "." represent the current directory. Note! If you are not in the directory where the bash script file is present then you change the directory where the file is located by using
cd Directory_name/write the complete path
command. Otherwise your script can not run.
For CentOS: When installing php-gd you need to specify the version. I fixed it by running: sudo yum install php55-gd
If the numbers aren't supposed to be absurdly huge, maybe use:
new RegExp(
'^' + // No leading content.
'[-+]?' + // Optional sign.
'(?:[0-9]{0,30}\\.)?' + // Optionally 0-30 decimal digits of mantissa.
'[0-9]{1,30}' + // 1-30 decimal digits of integer or fraction.
'(?:[Ee][-+]?[1-2]?[0-9])?' + // Optional exponent 0-29 for scientific notation.
'$' // No trailing content.
)
This tries to avoid some scenarios, just in case:
1E-323
.Infinity
when a finite number is expected (try 1E309
or -1E309
).This might work for you:
cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david
here is my solution. base on spring-boot.1.2.5.RELEASE.
application.properties
first.datasource.driver-class-name=com.mysql.jdbc.Driver
first.datasource.url=jdbc:mysql://127.0.0.1:3306/test
first.datasource.username=
first.datasource.password=
first.datasource.validation-query=select 1
second.datasource.driver-class-name=com.mysql.jdbc.Driver
second.datasource.url=jdbc:mysql://127.0.0.1:3306/test2
second.datasource.username=
second.datasource.password=
second.datasource.validation-query=select 1
DataSourceConfig.java
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix="first.datasource")
public DataSource firstDataSource() {
DataSource ds = DataSourceBuilder.create().build();
return ds;
}
@Bean
@ConfigurationProperties(prefix="second.datasource")
public DataSource secondDataSource() {
DataSource ds = DataSourceBuilder.create().build();
return ds;
}
}
I got the same same error.
I was using gmail account and Google's SMTP server to send emails. The problem was due to SMTP server refusing to authorize as it considered my web host (through whom I sent email) as an intruder.
I followed Google's process to identify my web host as an valid entity to send email through my account and problem was solved.
Using Abizern code for swift 2.2
let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)
Quick and Simple Answer
I solved using a "manual" deserialization. I'll explain in code
public ActionResult MyMethod([System.Web.Http.FromBody] MyModel model)
{
if (module.Fields == null && !string.IsNullOrEmpty(Request.Form["fields"]))
{
model.Fields = JsonConvert.DeserializeObject<MyFieldModel[]>(Request.Form["fields"]);
}
//... more code
}
First things first ,
they are not always equal
select 'Hello' from dual where 'Hello ' like 'Hello';
select 'Hello' from dual where 'Hello ' = 'Hello';
when things are not always equal , talking about their performance isn't that relevant.
If you are working on strings and only char variables , then you can talk about performance . But don't use like and "=" as being generally interchangeable .
As you would have seen in many posts ( above and other questions) , in cases when they are equal the performance of like is slower owing to pattern matching (collation)
You may want to use something like this:
NSDateComponents *components;
NSInteger days;
components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit
fromDate: startDate toDate: endDate options: 0];
days = [components day];
I believe this method accounts for situations such as dates that span a change in daylight savings.
The localStorage
can only store string content and you are trying to store a jQuery object since html(htmlString)
returns a jQuery object.
You need to set the string content instead of an object. And use the setItem
method to add data and getItem
to get data.
window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));
If this is the offending line:
db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();
Then it's because there is no object in Responses
for which the ResponseId == item.ResponseId
, and you can't get the First()
record if there are no matches.
Try this instead:
var response
= db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();
if (response != null)
{
// take some alternative action
}
else
temp.Response = response;
The FirstOrDefault()
extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null
.
In my case the problem occurred due to closing my PC while visual studio were remain open, so in result csproj.user file saved empty. Thankfully i have already backup, so i just copied all xml from csproj.user and paste in my affected project csproj.user file ,so it worked perfectly.
This file just contain building device info and some more.
if (rs == null || !rs.first()) { //empty } else { //not empty }
Note that after this method call, if the resultset is not empty, it is at the beginning.
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
This is my aproximation:
Declare
Variableclob Clob;
Temp_Save Varchar2(32767); //whether it is greater than 4000
Begin
Select reportClob Into Temp_Save From Reporte Where Id=...;
Variableclob:=To_Clob(Temp_Save);
Dbms_Output.Put_Line(Variableclob);
End;
Are you just trying to derive from Area<int>
? In which case you do this:
class Rectangle : public Area<int>
{
// ...
};
EDIT: Following the clarification, it seems you're actually trying to make Rectangle
a template as well, in which case the following should work:
template <typename T>
class Rectangle : public Area<T>
{
// ...
};
its
selenium.getTable("tablename".rowNumber.colNumber)
not
selenium.getTable("tablename".colNumber.rowNumber)
Use valueAsNumber
instead of .val()
.
input . valueAsNumber [ = value ]
Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.
There's another way with post
instead of ajax
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
Apart from reachability you may also use the Simple Ping helper library. It works really nice and is simple to integrate.
Here this should help you
The below jsfiddle link will help you understand how to rotate a image.I used the same one to rotate the dial of a clock.
var rotation = function (){
$("#image").rotate({
angle:0,
animateTo:360,
callback: rotation,
easing: function (x,t,b,c,d){
return c*(t/d)+b;
}
});
}
rotation();
Where: • t: current time,
• b: begInnIng value,
• c: change In value,
• d: duration,
• x: unused
No easing (linear easing): function(x, t, b, c, d) { return b+(t/d)*c ; }
Its Working
MenuItem tourchmeMenuItem; // Declare Global .......
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.search, menu);
menu.findItem(R.id.action_search).setVisible(false);
tourchmeMenuItem = menu.findItem(R.id.done);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
case R.id.done:
if(LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).getIsFlashLight()){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mScannerView.setFlash(false);
LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(false);
tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_white_32));
}
}else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mScannerView.setFlash(true);
LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(true);
tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_cross_white_32));
}
}
break;
}
That would be the modulo operator, which produces the remainder of the division of two numbers.
Whilst there is no portable #define or something to rely upon, platforms do provide standard functions for converting to and from your 'host' endian.
Generally, you do storage - to disk, or network - using 'network endian', which is BIG endian, and local computation using host endian (which on x86 is LITTLE endian). You use htons()
and ntohs()
and friends to convert between the two.
I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.
This is good for little widgets you want to reuse on different UIViewController objects.
$out.='<option value="'.$key.'">'.$value["name"];
me funciono con esta
"<a href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";
Yes you can use .is(':visible')
in jquery. But while the code is running under the safari browser
.is(':visible')
is won't work.
So please use the below code
if( $(".example").offset().top > 0 )
The above line will work both IE as well as safari also.
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
Based on Daniel's answer, I wrote this SASS mixin with interpolation (#{}
) for a youtube video's iframe that is inside a Bootstrap modal dialog:
@mixin responsive-modal-wiframe($height: 9, $width: 16.5,
$max-w-allowed: 90, $max-h-allowed: 60) {
$sides-adjustment: 1.7;
iframe {
width: #{$width / $height * ($max-h-allowed - $sides-adjustment)}vh;
height: #{$height / $width * $max-w-allowed}vw;
max-width: #{$max-w-allowed - $sides-adjustment}vw;
max-height: #{$max-h-allowed}vh;
}
@media only screen and (max-height: 480px) {
margin-top: 5px;
.modal-header {
padding: 5px;
.modal-title {font-size: 16px}
}
.modal-footer {display: none}
}
}
Usage:
.modal-dialog {
width: 95vw; // the modal should occupy most of the screen's available space
text-align: center; // this will center the titles and the iframe
@include responsive-modal-wiframe();
}
HTML:
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Video</h4>
</div>
<div class="modal-body">
<iframe src="https://www.youtube-nocookie.com/embed/<?= $video_id ?>?rel=0" frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
<div class="modal-footer">
<button class="btn btn-danger waves-effect waves-light"
data-dismiss="modal" type="button">Close</button>
</div>
</div>
</div>
</div>
This will always display the video without those black parts that youtube adds to the iframe when the width or height is not proportional to the video. Notes:
$sides-adjustment
is a slight adjustment to compensate a tiny part of these black parts showing up on the sides;.modal-footer
;.modal-dialog
;.modal-header
.After a lot of testing, this is working flawlessly for me now.
If you are in Javascript already, couldn't you just use Date.Parse() to validate a date instead of using regEx.
RegEx for date is actually unwieldy and hard to get right especially with leap years and all.
In the form closest to your original:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return now
If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime
, use this instead:
return (now - datetime.datetime(1970, 1, 1)).total_seconds()
Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:
utc_now = datetime.datetime.utcnow