npm install node-v8-clone
Fastest cloner, it open native clone method from node.js
var clone = require('node-v8-clone').clone;
var newObj = clone(obj, true); //true - deep recursive clone
I'd like to add to the above answers, you could directly use
df = pd.read_fwf('output_list.txt')
fwf stands for fixed width formatted lines.
The most up-to-date answer to this is: they are listed under the 'Network' button in the developer tools, no longer under 'Resources' like it used to be.
This worked for me.
create extension IF NOT EXISTS "uuid-ossp" schema pg_catalog version "1.1";
make sure the extension should by on pg_catalog and not in your schema...
Although this is somewhat old I would like to add a slightly improved version that really changes column order. Here are the steps (assuming we have a table TAB1 with columns COL1, COL2, COL3):
alter table TAB1 add (NEW_COL number);
create table tempTAB1 as select NEW_COL as COL0, COL1, COL2, COL3 from TAB1;
drop table TAB1;
rename tempTAB1 to TAB1;
The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:
$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pkg/main1.py", line 1, in <module>
import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>>
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>>
In particular:
$ python2 pkg/main2.py
Traceback (most recent call last):
File "pkg/main2.py", line 1, in <module>
from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>>
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Note that python2 pkg/main2.py
has a different behaviour then launching python2
and then importing pkg.main2
(which is equivalent to using the -m
switch).
If you ever want to run a submodule of a package always use the -m
switch which prevents the interpreter for chaining the sys.path
list and correctly handles the semantics of the submodule.
Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.
Yes you can use setValue to set value for edit/update purpose.
this.personalform.setValue({
name: items.name,
address: {
city: items.address.city,
country: items.address.country
}
});
You can refer http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ to understand how to use Reactive forms for add/edit feature by using setValue. It saved my time
I have Wondows 7 64 bit (MacBook Pro), installed both Java JDK x86 and x64 with JAVA_HOME
pointing at x32 during installation of Android SDK, later after installation JAVA_HOME
pointing at x64.
My problem was that Android SDK manager didn't launch, cmd window just flashes for a second and that's it. Like many others looked around and tried many suggestions with no juice!
My solution was in adding bin the JAVA_HOME
path:
C:\Program Files\Java\jdk1.7.0_09\bin
instead of what I entered for the start:
C:\Program Files\Java\jdk1.7.0_09
Hope this helps others.... good luck!
Use XML processing:
var appPath = AppDomain.CurrentDomain.BaseDirectory;
var configPath = Path.Combine(appPath, baseFileName);;
var root = XElement.Load(configPath);
// can call root.Elements(...)
From GC Performance Tuning training documents of Oracle:
-Xmn[size]: Size of young generation heap space.
Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.
In short, it sets the NewSize and MaxNewSize values of New generation to the same value.
I found the error because i was new to git you must check whether you have entered the correct syntax
i made a mistake and wrote
git commit
and got the same error
use
git commit -m 'some comment'
and you wont be seeing the page with
I added the control to the Triggers
tag in the update panel:
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="exportLinkButton" />
</Triggers>
</asp:UpdatePanel>
This way the exportLinkButton will trigger the UpdatePanel to update.
More info here.
I had issues like this especially when debugging actively through my phone; at times it took 27 minutes. I did the following things and take note of the explanation under each - one may work for you:
org.gradle.daemon=true
org.gradle.configureondemand=true
org.gradle.parallel=true
android.enableBuildCache=true
org.gradle.caching=true
org.gradle.jvmargs=-Xmx8000m -XX:MaxPermSize=5000m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
File -> Settings/Preferences -> Build, Execution, Deployment -> Gradle
Global Gradle Settings (at the bottom)
Mark the checkbox named: Offline Work.
File -> Settings/Preferences -> Build, Execution, Deployment -> Instant Run
Checked : Enable Instant Run to hot swap code...
Checked: restart activity on code changes ...
The move above was erratic also and therefore I sought to find out if the problem may be the processes/memory that ran directly on either my phone and computer. Here I freed up a little memory space in my phone and storage (which was at 98% utilized - down to 70%) and also on task manager (Windows), increased the priority of both Android Studio and Java.exe to High. Take this step cautiously; depends on your computer's memory.
After all this my build time while debugging actively on my phone at times went down to 1 ~ 2 minutes but at times spiked. I decided to do a hack which surprised me by taking it down to seconds best yet on the same project that gave me 22 - 27 minutes was 12 seconds!:
Connect phone for debugging then click RUN
After it starts, unplug the phone - the build should continue faster and raise an error at the end indicating this : Session 'app': Error Installing APKs
Reconnect back the phone and click on RUN again...
ALTERNATIVELY
If the script/function/method I'm debugging is purely JAVA, not JAVA-android e.g. testing an API with JSONArrays/JSONObjects, I test my java functions/methods on Netbeans which can compile a single file and show the output faster then make necessary changes on my Android Studio files. This also saves me a lot of time.
EDIT
I tried creating a new android project in local storage and copied all my files from the previous project into the new one - java, res, manifest, gradle app and gradle project (with latest gradle classpath dependency). And now I can build on my phone in less than 15 seconds.
The 'pidof' command will not display pids of shell/perl/python scripts. So to find the process id’s of my Perl script I had to use the -x option i.e. 'pidof -x perlscriptname'
If the array contains strings, you can use the String
's join
method:
var array = ["1", "2", "3"]
let stringRepresentation = "-".join(array) // "1-2-3"
In Swift 2:
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
This can be useful if you want to use a specific separator (hypen, blank, comma, etc).
Otherwise you can simply use the description
property, which returns a string representation of the array:
let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"
Hint: any object implementing the Printable
protocol has a description
property. If you adopt that protocol in your own classes/structs, you make them print friendly as well
In Swift 3
join
becomes joined
, example [nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
becomes joined(separator:)
(only available to Array of Strings)In Swift 4
var array = ["1", "2", "3"]
array.joined(separator:"-")
To update a subset of fields, you can use update_fields
:
survey.save(update_fields=["active"])
The update_fields
argument was added in Django 1.5. In earlier versions, you could use the update()
method instead:
Survey.objects.filter(pk=survey.pk).update(active=True)
The documentation (or The Definitive Guide) says, that you can also use the next query to delete all indices:
curl -XDELETE 'http://localhost:9200/*'
And there's an important note:
For some, the ability to delete all your data with a single command is a very scary prospect. If you want to eliminate the possibility of an accidental mass-deletion, you can set the following to
true
in yourelasticsearch.yml
:
action.destructive_requires_name: true
An easy way that works:
private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
foreach (var item in e.AddedCells)
{
var col = item.Column as DataGridColumn;
var fc = col.GetCellContent(item.Item);
if (fc is CheckBox)
{
Debug.WriteLine("Values" + (fc as CheckBox).IsChecked);
}
else if(fc is TextBlock)
{
Debug.WriteLine("Values" + (fc as TextBlock).Text);
}
//// Like this for all available types of cells
}
}
export PATH=$PATH:/usr/local/git/bin:/usr/local/bin
One note: you don't need quotation marks here because it's on the right hand side of an assignment, but in general, and especially on Macs with their tradition of spacy pathnames, expansions like $PATH
should be double-quoted as "$PATH"
.
There is a attribute on every HTMLElement, "previousElementSibling".
Ex:
<div id="a">A</div>
<div id="b">B</div>
<div id="c">c</div>
<div id="result">Resultado: </div>
var b = document.getElementById("c").previousElementSibling;
document.getElementById("result").innerHTML += b.innerHTML;
This is how I would do it (assuming I understand the question)
SELECT * FROM pieces ORDER BY price ASC LIMIT 1
If you are trying to select multiple rows where each of them may have the same price (which is the minimum) then @JohnWoo's answer should suffice.
Basically here we are just ordering the results by the price in ASCending order (increasing) and taking the first row of the result.
Curt makes a good point: the second version is clearer and will fail at load time rather than later, and unexpectedly.
Normally I don't worry about the efficiency of loading modules, since it's (a) pretty fast, and (b) mostly only happens at startup.
If you have to load heavyweight modules at unexpected times, it probably makes more sense to load them dynamically with the __import__
function, and be sure to catch ImportError
exceptions, and handle them in a reasonable manner.
This warning is useful for programmers that would mistakenly write 'test'
where they should have written "test"
.
This happen much more often than programmers that do actually want multi-char int constants.
You have to use CASE Statement/Expression
Select * from Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND
(C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND
CASE @Value
WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL)
WHEN 3 THEN (CASE WHEN I.RecurringCharge like
'%'+cast(@Total as varchar(50))+'%'
or @Total is NULL )
END
In my case this worked :
Delete R.Java file in /Gen folder
+
Delete all "R.Android" imports that Eclipse added to some of my java classes !!!
and rebuild the project.
After perusing your previous questions I eventually determined you are probably on SQL Server 2005. For US format you would use style 101
select Subject,
CONVERT(varchar,DeliveryDate,101) as DeliveryDate
from Email_Administration
where MerchantId =@MerchantID
You can use regular expressions:
if (d.matches(".*Hey.*")) {
c.setText("OUTPUT: SUCCESS!");
} else {
c.setText("OUTPUT: FAIL!");
}
.*
-> 0 or more of any characters
Hey
-> The string you want
If you will be checking this often, it is better to compile the regular expression in a Pattern
object and reuse the Pattern
instance to do the checking.
private static final Pattern HEYPATTERN = Pattern.compile(".*Hey.*");
[...]
if (HEYPATTERN.matcher(d).matches()) {
c.setText("OUTPUT: SUCCESS!");
} else {
c.setText("OUTPUT: FAIL!");
}
Just note this will also match "Heyburg"
for example since you didn't specify you're searching for "Hey"
as an independent word. If you only want to match Hey
as a word, you need to change the regex to .*\\bHey\\b.*
As mentioned by Santosh, I think this query is suitably fast, while not querying all the table.
To return integer result of number of data records, for a specific tablename in a particular database:
select TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA = 'database'
AND table_name='tablename';
This will be faster than a full sort depending on the size of your original array and the size of your selection:
>>> A = np.random.randint(0,10,10)
>>> A
array([5, 1, 5, 5, 2, 3, 2, 4, 1, 0])
>>> B = np.zeros(3, int)
>>> for i in xrange(3):
... idx = np.argmax(A)
... B[i]=idx; A[idx]=0 #something smaller than A.min()
...
>>> B
array([0, 2, 3])
It, of course, involves tampering with your original array. Which you could fix (if needed) by making a copy or replacing back the original values. ...whichever is cheaper for your use case.
A back link is a link that moves the browser backwards one page, as if the user had clicked the Back button available in most browsers. Back links use JavaScript. It moves the browser back one page if your browser supports JavaScript (which it does) and if it supports the window.history
object, which is necessary for back links.
Simple ways are
<a href="#" onClick="history.go(-1)">Go Back</a>
OR:
function goBack() {_x000D_
window.history.back()_x000D_
}
_x000D_
<a href="#" onclick="goBack()" />Go Back</a>
_x000D_
Generally speaking a back link isn't necessary… the Back button usually suffices quite nicely, and usually you can also simply link to the previous page in your site. However, sometimes you might want to provide a link back to one of several "previous" pages, and that's where a back link comes in handy. So I refer you below tutorial if you want to do in more advanced way:
http://www.htmlcodetutorial.com/linking/linking_famsupp_108.html
This one works in Textmate and it matches everything in a CSS file between the curly brackets.
\{(\s*?.*?)*?\}
selector {.
.
matches here
including white space.
.
.}
If you want to further be able to return the content, then wrap it all in one more set of parentheses like so:
\{((\s*?.*?)*?)\}
and you can access the contents via $1.
This also works for functions, but I haven't tested it with nested curly brackets.
How to differentiate between single clicks and double clicks on one and the same element?
If you don't need to mix them, you can rely on click
and dblclick
and each will do the job just fine.
A problem arises when trying to mix them: a dblclick
event will actually trigger a click
event as well, so you need to determine whether a single click is a "stand-alone" single click, or part of a double click.
In addition: you shouldn't use both click
and dblclick
on one and the same element:
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
Source: https://api.jquery.com/dblclick/
Now on to the good news:
You can use the event's detail
property to detect the number of clicks related to the event. This makes double clicks inside of click
fairly easy to detect.
The problem remains of detecting single clicks and whether or not they're part of a double click. For that, we're back to using a timer and setTimeout
.
Wrapping it all together, with use of a data attribute (to avoid a global variable) and without the need to count clicks ourselves, we get:
<div class="clickit" style="font-size: 200%; margin: 2em; padding: 0.25em; background: orange;">Double click me</div>
<div id="log" style="background: #efefef;"></div>
<script>
var clickTimeoutID;
$( document ).ready(function() {
$( '.clickit' ).click( function( event ) {
if ( event.originalEvent.detail === 1 ) {
$( '#log' ).append( '(Event:) Single click event received.<br>' );
/** Is this a true single click or it it a single click that's part of a double click?
* The only way to find out is to wait it for either a specific amount of time or the `dblclick` event.
**/
clickTimeoutID = window.setTimeout(
function() {
$( '#log' ).append( 'USER BEHAVIOR: Single click detected.<br><br>' );
},
500 // how much time users have to perform the second click in a double click -- see accessibility note below.
);
} else if ( event.originalEvent.detail === 2 ) {
$( '#log' ).append( '(Event:) Double click event received.<br>' );
$( '#log' ).append( 'USER BEHAVIOR: Double click detected.<br>' );
window.clearTimeout( clickTimeoutID ); // it's a dblclick, so cancel the single click behavior.
} // triple, quadruple, etc. clicks are ignored.
});
});
</script>
It took a while to find a satisfying solution, I hope this helps!
Your function signature needs to be:
const char * myFunction()
{
return "My String";
}
Background:
It's so fundamental to C & C++, but little more discussion should be in order.
In C (& C++ for that matter), a string is just an array of bytes terminated with a zero byte - hence the term "string-zero" is used to represent this particular flavour of string. There are other kinds of strings, but in C (& C++), this flavour is inherently understood by the language itself. Other languages (Java, Pascal, etc.) use different methodologies to understand "my string".
If you ever use the Windows API (which is in C++), you'll see quite regularly function parameters like: "LPCSTR lpszName". The 'sz' part represents this notion of 'string-zero': an array of bytes with a null (/zero) terminator.
Clarification:
For the sake of this 'intro', I use the word 'bytes' and 'characters' interchangeably, because it's easier to learn this way. Be aware that there are other methods (wide-characters, and multi-byte character systems (mbcs)) that are used to cope with international characters. UTF-8 is an example of an mbcs. For the sake of intro, I quietly 'skip over' all of this.
Memory:
This means that a string like "my string" actually uses 9+1 (=10!) bytes. This is important to know when you finally get around to allocating strings dynamically.
So, without this 'terminating zero', you don't have a string. You have an array of characters (also called a buffer) hanging around in memory.
Longevity of data:
The use of the function this way:
const char * myFunction()
{
return "My String";
}
int main()
{
const char* szSomeString = myFunction(); // Fraught with problems
printf("%s", szSomeString);
}
... will generally land you with random unhandled-exceptions/segment faults and the like, especially 'down the road'.
In short, although my answer is correct - 9 times out of 10 you'll end up with a program that crashes if you use it that way, especially if you think it's 'good practice' to do it that way. In short: It's generally not.
For example, imagine some time in the future, the string now needs to be manipulated in some way. Generally, a coder will 'take the easy path' and (try to) write code like this:
const char * myFunction(const char* name)
{
char szBuffer[255];
snprintf(szBuffer, sizeof(szBuffer), "Hi %s", name);
return szBuffer;
}
That is, your program will crash because the compiler (may/may not) have released the memory used by szBuffer
by the time the printf()
in main()
is called. (Your compiler should also warn you of such problems beforehand.)
There are two ways to return strings that won't barf so readily.
std::string
) to handle the longevity of data (which requires changing the function's return value), orNote that it is impossible to use strings without using pointers in C. As I have shown, they are synonymous. Even in C++ with template classes, there are always buffers (that is, pointers) being used in the background.
So, to better answer the (now modified question). (There are sure to be a variety of 'other answers' that can be provided.)
Safer Answers:
Example 1, using statically allocated strings:
const char* calculateMonth(int month)
{
static char* months[] = {"Jan", "Feb", "Mar" .... };
static char badFood[] = "Unknown";
if (month<1 || month>12)
return badFood; // Choose whatever is appropriate for bad input. Crashing is never appropriate however.
else
return months[month-1];
}
int main()
{
printf("%s", calculateMonth(2)); // Prints "Feb"
}
What the 'static' does here (many programmers do not like this type of 'allocation') is that the strings get put into the data segment of the program. That is, it's permanently allocated.
If you move over to C++ you'll use similar strategies:
class Foo
{
char _someData[12];
public:
const char* someFunction() const
{ // The final 'const' is to let the compiler know that nothing is changed in the class when this function is called.
return _someData;
}
}
... but it's probably easier to use helper classes, such as std::string
, if you're writing the code for your own use (and not part of a library to be shared with others).
Example 2, using caller-defined buffers:
This is the more 'foolproof' way of passing strings around. The data returned isn't subject to manipulation by the calling party. That is, example 1 can easily be abused by a calling party and expose you to application faults. This way, it's much safer (albeit uses more lines of code):
void calculateMonth(int month, char* pszMonth, int buffersize)
{
const char* months[] = {"Jan", "Feb", "Mar" .... }; // Allocated dynamically during the function call. (Can be inefficient with a bad compiler)
if (!pszMonth || buffersize<1)
return; // Bad input. Let junk deal with junk data.
if (month<1 || month>12)
{
*pszMonth = '\0'; // Return an 'empty' string
// OR: strncpy(pszMonth, "Bad Month", buffersize-1);
}
else
{
strncpy(pszMonth, months[month-1], buffersize-1);
}
pszMonth[buffersize-1] = '\0'; // Ensure a valid terminating zero! Many people forget this!
}
int main()
{
char month[16]; // 16 bytes allocated here on the stack.
calculateMonth(3, month, sizeof(month));
printf("%s", month); // Prints "Mar"
}
There are lots of reasons why the second method is better, particularly if you're writing a library to be used by others (you don't need to lock into a particular allocation/deallocation scheme, third parties can't break your code, and you don't need to link to a specific memory management library), but like all code, it's up to you on what you like best. For that reason, most people opt for example 1 until they've been burnt so many times that they refuse to write it that way anymore ;)
Disclaimer:
I retired several years back and my C is a bit rusty now. This demo code should all compile properly with C (it is OK for any C++ compiler though).
Very quick and easy visual instructions to change this (and the select top 1000) for 2008 R2 through SSMS GUI
http://bradmarsh.net/index.php/2008/04/21/sql-2008-change-edit-top-200-rows/
Summary:
With Python 3.6 you can use:
from datetime import datetime
datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
Output:
'2019-05-10 09:08:53.155'
More info here: https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat
PowerShell has aliases for several common commands like echo
. Type the following in PowerShell:
Get-Alias echo
to get a response:
CommandType Name Version Source
----------- ---- ------- ------
Alias echo -> Write-Output
Even Get-Alias has an alias gal -> Get-Alias
. You could write gal echo
to get the alias for echo
.
gal echo
Other aliases are listed here: https://docs.microsoft.com/en-us/powershell/scripting/learn/using-familiar-command-names?view=powershell-6
cat dir mount rm cd echo move rmdir chdir erase popd sleep clear h ps sort cls history pushd tee copy kill pwd type del lp r write diff ls ren
Generally you can just cast the variable to become a short
.
You can also get problems like this that can be confusing. This is because the +
operator promotes them to an int
Casting the elements won't help:
You need to cast the expression:
To load your data in WebView. Call loadData() method of WebView
wv.loadData(yourData, "text/html", "UTF-8");
You can check this example
http://developer.android.com/reference/android/webkit/WebView.html
[Edit 1]
You should add -- \ -- before -- " -- for example --> name=\"spanish press\"
below string worked for me
String webData = "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
"<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";
Do this to convert safely a PNG to JPG with the transparency in white.
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
double num = 5;
That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:
Widening primitive conversions do not lose information about the overall magnitude of a numeric value.
[...]
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).
5 can be expressed exactly as a double.
This is usually needed when you want to include header.php or whatever page.
In Java it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Java function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php I.e convert the php include function to Java function in script tag and place all your content in that included file.
I'm guessing that you meant to do this:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use ^
Well, if you are writing to a CSV file, then why do you use space as a delimiter? CSV files use commas or semicolons (in Excel) as cell delimiters, so if you use delimiter=' '
, you are not really producing a CSV file. You should simply construct csv.writer
with the default delimiter and dialect. If you want to read the CSV file later into Excel, you could specify the Excel dialect explicitly just to make your intention clear (although this dialect is the default anyway):
example = csv.writer(open("test.csv", "wb"), dialect="excel")
You are using two WHERE
clauses but only one is allowed. Use it like this:
SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
table1.f_com_id = '430'
AND table1.f_status = 'Submitted'
AND table2.f_type = 'InProcess'
To cherry pick from a commit id up to the tip of the branch, you can use:
git cherry-pick commit_id^..branch_name
There is one important thing to mention:
$("#txt_name").val();
will return the current real value of a text field, for example if the user typed something there after a page load.
But:
$("#txt_name").attr('value')
will return value from DOM/HTML.
Why javascript when you can use just css?
a[aria-expanded="true"]{_x000D_
background-color: #42DCA3;_x000D_
}
_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> _x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> _x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>
_x000D_
Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.
In your posted question, there is one extra space after try:
, and there are 12 extra spaces after pass
:
>>> post_text = '''\
... if self.tagname and self.tagname2 in list1:
... try:
... question = soup.find("div", "post-text")
... title = soup.find("a", "question-hyperlink")
... self.list2.append(str(title)+str(question)+url)
... current += 1
... except AttributeError:
... pass
... logging.info("%s questions passed, %s questions \
... collected" % (count, current))
... count += 1
... return self.list2
... '''
>>> for line in post_text.splitlines():
... if line.rstrip() != line:
... print(repr(line))
...
' try: '
' pass '
See where the strings end? There are spaces before the lines (indentation), but also spaces after.
Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.
find -type f -print0 | xargs -0 ls -t
Drawback: Works only to a certain amount of files. If you have extremly large amounts of files you need something more complicated
No need to go with GSON for this; Jackson can do either plain Maps/Lists:
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);
or more convenient JSON Tree:
JsonNode rootNode = mapper.readTree(json);
By the way, there is no reason why you could not actually create Java classes and do it (IMO) more conveniently:
public class Library {
@JsonProperty("libraryname")
public String name;
@JsonProperty("mymusic")
public List<Song> songs;
}
public class Song {
@JsonProperty("Artist Name") public String artistName;
@JsonProperty("Song Name") public String songName;
}
Library lib = mapper.readValue(jsonString, Library.class);
Assuming (!) the strings are of equal length, why not convert the strings to byte arrays and then XOR the bytes. The resultant byte arrays may be of different lengths too depending on your encoding (e.g. UTF8 will expand to different byte lengths for different characters).
You should be careful to specify the character encoding to ensure consistent/reliable string/byte conversion.
$('.load_more').live("click",function() { //When user clicks
var newcurrentpageTemp = parseInt($(this).attr("id")) + 1
dosomething(newcurrentpageTemp );
});
Something simple like this can be done using subqueries in the select
clause:
select ((select sum(hours) from resource) +
(select sum(hours) from projects-time)
) as totalHours
For such a simple query as this, such a subselect is reasonable.
In some databases, you might have to add from dual
for the query to compile.
If you want to output each individually:
select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
If you want both and the sum, a subquery is handy:
select ResourceHours, ProjectHours, (ResourceHours+ProjecctHours) as TotalHours
from (select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
) t
You can use display:inline-block
instead of float
and vertical-align:middle
with this CSS:
.col-lg-4, .col-lg-8 {
float:none;
display:inline-block;
vertical-align:middle;
margin-right:-4px;
}
The demo http://bootply.com/94402
Use this to limit the depth to 2:
Get-ChildItem \*\*\*,\*\*,\*
The way it works is that it returns the children at each depth 2,1 and 0.
Explanation:
This command
Get-ChildItem \*\*\*
returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.
In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.
extensionsToCheck = ('.pdf', '.doc', '.xls')
'test.doc'.endswith(extensionsToCheck) # returns True
'test.jpg'.endswith(extensionsToCheck) # returns False
You may also use --keyid-format
switch to show short or long key ID:
$ gpg2 -n --with-fingerprint --keyid-format=short --show-keys <filename>
which outputs like this (example from PostgreSQL CentOS repo key):
pub dsa1024/442DF0F8 2008-01-08 [SCA] ¦
Key fingerprint = 68C9 E2B9 1A37 D136 FE74 D176 1F16 D2E1 442D F0F8 ¦ honor-keyserver-url
uid PostgreSQL RPM Building Project <[email protected]> ¦ When using --refresh-keys, if the key in question has a preferred keyserver URL, then use that
sub elg2048/D43F1AF8 2008-01-08 [E]
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
Either of the latter two, since val
could potentially be of a type that defines __eq__()
to return true when passed None
.
C++ inline is totally different to C inline.
#include <iostream>
extern inline int i[];
int i [5];
struct c {
int function (){return 1;} //implicitly inline
static inline int j = 3; //explicitly inline
};
int main() {
c j;
std::cout << i;
}
inline
on its own affects the compiler, assembler and the linker. It is a directive to the compiler saying only emit a symbol for this function/data if it's used in the translation unit, and if it is, then like class methods, tell the assembler to store them in the section .section .text.c::function(),"axG",@progbits,c::function(),comdat
or .section .bss.i,"awG",@nobits,i,comdat
for data. Template instantiations also go in their own comdat groups.
This follows .section name, "flags"MG, @type, entsize, GroupName[, linkage]
. For instance, the section name is .text.c::function()
. axG
means the section is allocatable, executable and in a group i.e. a group name will be specified (and there is no M flag so no entsize will be specified); @progbits
means the section contains data and isn't blank; c::function()
is the group name and the group has comdat
linkage meaning that in all object files, all sections encountered with this group name tagged with comdat will be removed from the final executable except for 1 i.e. the compiler makes sure that there is only one definition in the translation unit and then tells the assembler to put it in its own group in the object file (1 section in 1 group) and then the linker will make sure that if any object files have a group with the same name, then only include one in the final .exe. The difference between inline
and not using inline
is now visible to the assembler and as a result the linker, because it's not stored in the regular .data
or .text
etc by the assembler due to their directives.
static inline
in a class means this it a type definition and not declaration (allows static member to be defined in the class) and make it inline; it now behaves as above.
static inline
at file scope only affects the compiler. It means to the compiler: only emit a symbol for this function/data if it's used in the translation unit and do so as a regular static symbol (store in.text /.data without .globl directive). To the assembler there is now no difference between static
and static inline
extern inline
is a declaration that means you must define this symbol in the translation unit or throw compiler error; if it's defined then treat it as a regular inline
and to the assembler and linker there will be no difference between extern inline
and inline
, so this is a compiler guard only.
extern inline int i[];
extern int i[]; //allowed repetition of declaration with incomplete type, inherits inline property
extern int i[5]; //declaration now has complete type
extern int i[5]; //allowed redeclaration if it is the same complete type or has not yet been completed
extern int i[6]; //error, redeclaration with different complete type
int i[5]; //definition, must have complete type and same complete type as the declaration if there is a declaration with a complete type
The whole of the above without the error line collapses to inline int i[5]
. Obviously if you did extern inline int i[] = {5};
then extern
would be ignored due to the explicit definition through assignment.
In an .htaccess
file you need to use
Deny from all
Put this in site/includes/.htaccess
to make it specific to the includes
directory
If you just wish to disallow a listing of directory files you can use
Options -Indexes
I have recently tried the following approach which seems to work fine, although I am not 100% sure if there might be any side effects:
'use strict';
import * as models from "../../models";
module.exports = {
up: function (queryInterface, Sequelize) {
return queryInterface.createTable(models.Role.tableName, models.Role.attributes)
.then(() => queryInterface.createTable(models.Team.tableName, models.Team.attributes))
.then(() => queryInterface.createTable(models.User.tableName, models.User.attributes))
},
down: function (queryInterface, Sequelize) {
...
}
};
When running the migration above using sequelize db:migrate
, my console says:
Starting 'db:migrate'...
Finished 'db:migrate' after 91 ms
== 20160113121833-create-tables: migrating =======
== 20160113121833-create-tables: migrated (0.518s)
All the tables are there, everything (at least seems to) work as expected. Even all the associations are there if they are defined correctly.
This is the correct way:
You should declare the length of the array after "="
Veicle[] cars = new Veicle[N];
Guys thank you for your help. I think all of this answers works. However i think my byte array contains raw bytes. That's why all of those solutions didnt work for my code.
However i found a solution. Maybe this solution helps other coders who have problem like mine.
static byte[] PadLines(byte[] bytes, int rows, int columns) {
int currentStride = columns; // 3
int newStride = columns; // 4
byte[] newBytes = new byte[newStride * rows];
for (int i = 0; i < rows; i++)
Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
return newBytes;
}
int columns = imageWidth;
int rows = imageHeight;
int stride = columns;
byte[] newbytes = PadLines(imageData, rows, columns);
Bitmap im = new Bitmap(columns, rows, stride,
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));
im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");
This solutions works for 8bit 256 bpp (Format8bppIndexed). If your image has another format you should change PixelFormat
.
And there is a problem with colors right now. As soon as i solved this one i will edit my answer for other users.
*PS = I am not sure about stride value but for 8bit it should be equal to columns.
And also this function Works for me.. This function copies 8 bit greyscale image into a 32bit layout.
public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
byte[] data = new byte[width * height * 4];
int o = 0;
for (int i = 0; i < width * height; i++)
{
byte value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
unsafe
{
fixed (byte* ptr = data)
{
using (Bitmap image = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(Path.ChangeExtension(fileName, ".jpg"));
}
}
}
}
from item in db.vw_Dropship_OrderItems
where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
(listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
select item;
Might give strange behavior if both listMerchants and listStatus are both null.
In phpmyadmin, If you need to add a boolean datatype column to an existing table with default value true:
ALTER TABLE books
isAvailable boolean default true;
another easier way is using multiple desktop apps, like what i am doing, using account A on Github desktop, while using account B on Github Kraken
I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.
Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.
To quote the documentation:
Key words and unquoted identifiers are case insensitive. Therefore:
UPDATE MY_TABLE SET A = 5;
can equivalently be written as:
uPDaTE my_TabLE SeT a = 5;
You could also write it using quoted identifiers:
UPDATE "my_table" SET "a" = 5;
Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO
, foo
, and "foo"
are considered the same by PostgreSQL, but "Foo"
and "FOO"
are different from these three and each other.
If you want to write portable applications you are advised to always quote a particular name or never quote it.
Now in 2020, with matplotlib 3.2.2 you can set your legend fonts with
plt.legend(title="My Title", fontsize=10, title_fontsize=15)
where fontsize
is the font size of the items in legend and title_fontsize
is the font size of the legend title. More information in matplotlib documentation
I'd suggest you store the result of the lookup in a temp variable, test if the temp variable is nil and then use it. That way you don't look the same object up twice:
id obj = [dict objectForKey:@"blah"];
if (obj) {
// use obj
} else {
// Do something else
}
For modern browsers, use toLocaleString
:
var num = 1.345;
num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });
Specify a locale tag as first parameter to control the decimal separator. For a dot, use for example English U.S. locale:
num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
which gives:
1.35
Most countries in Europe use a comma as decimal separator, so if you for example use Swedish/Sweden locale:
num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
it will give:
1,35
The second formula on that page uses the GCD function of the Analysis ToolPak, you can add it from Tools > Add-Ins.
=A1/GCD(A1,B1)&":"&B1/GCD(A1,B1)
This is a more mathematical formula rather than a text manipulation based on.
Late, but relevant to request and hopefully helpful. If using an external service (as suggested in the reply by CommonsWare) then Docmosis has a cloud service that might help - offloading processing to a cloud service that does the heavy processing. That approach is ideal in some circumstances but of course relies on being net-connected.
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);
If you need the index of the first occurrence of only one value, you can use nonzero
(or where
, which amounts to the same thing in this case):
>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>> nonzero(t == 8)[0][0]
6
If you need the first index of each of many values, you could obviously do the same as above repeatedly, but there is a trick that may be faster. The following finds the indices of the first element of each subsequence:
>>> nonzero(r_[1, diff(t)[:-1]])
(array([0, 3, 5, 6, 7, 8]),)
Notice that it finds the beginning of both subsequence of 3s and both subsequences of 8s:
[1, 1, 1, 2, 2, 3, 8, 3, 8, 8]
So it's slightly different than finding the first occurrence of each value. In your program, you may be able to work with a sorted version of t
to get what you want:
>>> st = sorted(t)
>>> nonzero(r_[1, diff(st)[:-1]])
(array([0, 3, 5, 7]),)
You can use a variable and change the variable instead.
````setInterval([the function], [the variable])```
The other answers didn't work for me, this is what ended up doing the trick for apache2:
1) Enable the headers mod:
sudo a2enmod headers
2) Create the /etc/apache2/mods-enabled/headers.conf
file and insert:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
3) Restart your server:
sudo service apache2 restart
Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.
You can either:
The Safe Area Layout Guide helps avoid underlapping System UI elements when positioning content and controls.
The Safe Area is the area in between System UI elements which are Status Bar, Navigation Bar and Tool Bar or Tab Bar. So when you add a Status bar to your app, the Safe Area shrink. When you add a Navigation Bar to your app, the Safe Area shrinks again.
On the iPhone X, the Safe Area provides additional inset from the top and bottom screen edges in portrait even when no bar is shown. In landscape, the Safe Area is inset from the sides of the screens and the home indicator.
This is taken from Apple's video Designing for iPhone X where they also visualize how different elements affect the Safe Area.
If you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
If tomcat is installed locally, type the following url in a browser window: { localhost:8080 }
This will display Tomcat home page with the following message.
If you're seeing this, you've successfully installed Tomcat. Congratulations!
If tomcat is installed on a separate server, you can type replace localhost by a valid hostname or Iess where tomcat is installed.
The above applies for a standard installation wherein tomcat uses the default port 8080
When it comes to Google Analytics I found raik's answer at Secure Google tracking cookies very useful. It set secure and samesite to a value.
ga('create', 'UA-XXXXX-Y', {
cookieFlags: 'max-age=7200;secure;samesite=none'
});
Also more info in this blog post
If you're using a JFrame, try this
JFrame frame = new JFrame();
//...
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
An answer using css flex layout and justify-content
p {
display: flex;
justify-content: space-between;
}
_x000D_
<p>
<span>This text is left aligned</span>
<span>This text is right aligned</span>
</p>
_x000D_
Note: if you are trying to get this information for tables that are in a different SCHEMA use the all_tab_columns view, we have this problem as our Applications use a different SCHEMA for security purposes.
use the following:
EG:
SELECT
data_length
FROM
all_tab_columns
WHERE
upper(table_name) = 'MY_TABLE_NAME' AND upper(column_name) = 'MY_COL_NAME'
I'm using macOS Sierra (v10.12.1) Xcode v8.1 Swift 3.0.1 and here's what worked for me in ViewController.swift:
//
// ViewController.swift
// UIWebViewExample
//
// Created by Scott Maretick on 1/2/17.
// Copyright © 2017 Scott Maretick. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController {
//added this code
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Your webView code goes here
let url = URL(string: "https://www.google.com")
if UIApplication.shared.canOpenURL(url!) {
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
//If you want handle the completion block than
UIApplication.shared.open(url!, options: [:], completionHandler: { (success) in
print("Open url : \(success)")
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
};
Serialization provides default functionality to store and later recreate the object. It uses verbose format to define the whole graph of objects to be stored e.g. suppose you have a linkedList and you code like below, then the default serialization will discover all the objects which are linked and will serialize. In default serialization the object is constructed entirely from its stored bits, with no constructor calls.
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("/Users/Desktop/files/temp.txt"));
oos.writeObject(linkedListHead); //writing head of linked list
oos.close();
But if you want restricted serialization or don't want some portion of your object to be serialized then use Externalizable. The Externalizable interface extends the Serializable interface and adds two methods, writeExternal() and readExternal(). These are automatically called while serialization or deserialization. While working with Externalizable we should remember that the default constructer should be public else the code will throw exception. Please follow the below code:
public class MyExternalizable implements Externalizable
{
private String userName;
private String passWord;
private Integer roll;
public MyExternalizable()
{
}
public MyExternalizable(String userName, String passWord, Integer roll)
{
this.userName = userName;
this.passWord = passWord;
this.roll = roll;
}
@Override
public void writeExternal(ObjectOutput oo) throws IOException
{
oo.writeObject(userName);
oo.writeObject(roll);
}
@Override
public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException
{
userName = (String)oi.readObject();
roll = (Integer)oi.readObject();
}
public String toString()
{
StringBuilder b = new StringBuilder();
b.append("userName: ");
b.append(userName);
b.append(" passWord: ");
b.append(passWord);
b.append(" roll: ");
b.append(roll);
return b.toString();
}
public static void main(String[] args)
{
try
{
MyExternalizable m = new MyExternalizable("nikki", "student001", 20);
System.out.println(m.toString());
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/Desktop/files/temp1.txt"));
oos.writeObject(m);
oos.close();
System.out.println("***********************************************************************");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/Desktop/files/temp1.txt"));
MyExternalizable mm = (MyExternalizable)ois.readObject();
mm.toString();
System.out.println(mm.toString());
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
}
catch(IOException ex)
{
Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Here if you comment the default constructer then the code will throw below exception:
java.io.InvalidClassException: javaserialization.MyExternalizable;
javaserialization.MyExternalizable; no valid constructor.
We can observe that as password is sensitive information, so i am not serializing it in writeExternal(ObjectOutput oo) method and not setting the value of same in readExternal(ObjectInput oi). That's the flexibility that is provided by Externalizable.
The output of the above code is as per below:
userName: nikki passWord: student001 roll: 20
***********************************************************************
userName: nikki passWord: null roll: 20
We can observe as we are not setting the value of passWord so it's null.
The same can also be achieved by declaring the password field as transient.
private transient String passWord;
Hope it helps. I apologize if i made any mistakes. Thanks.
From http://pyyaml.org/wiki/PyYAMLDocumentation:
add_path_resolver(tag, path, kind)
adds a path-based implicit tag resolver. A path is a list of keys that form a path to a node in the representation graph. Paths elements can be string values, integers, or None. The kind of a node can be str, list, dict, or None.
#!/usr/bin/env python
import yaml
class Person(yaml.YAMLObject):
yaml_tag = '!person'
def __init__(self, name):
self.name = name
yaml.add_path_resolver('!person', ['Person'], dict)
data = yaml.load("""
Person:
name: XYZ
""")
print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}
print data['Person'].name
# XYZ
Your code is technically correct. If you looked at the headers of that blank page, you'd see a 404 header, and other computers/programs would be able to correctly identify the response as file not found.
Of course, your users are still SOL. Normally, 404s are handled by the web server.
The problem is, once the web server starts processing the PHP page, it's already passed the point where it would handle a 404
In addition to providing a 404 header, PHP is now responsible for outputting the actual 404 page.
var x = condition || null;
Here's another option. Use Excel's built in 'Text to Columns' wizard. It's found under the Data tab in Excel 2007.
If you have one column selected, the defaults for file type and delimiters should work, then it prompts you to change the data format of the column. Choosing text forces it to text format, to make sure that it's not stored as a date.
On Windows the path is:
C:\Users\<current_user>\AppData\Local\Google\Chrome\User Data\<Profile 1>\Cookies(Type:File)
Chrome doesn't store each cookies in separate text file. It stores all of the cookies together in a single file in the profile folder. That file is not readable.
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);
access arr
like normal int[]
.
I put this before the yield container:
<div id="fix-for-navbar-fixed-top-spacing" style="height: 42px;"> </div>
I like this approach because it documents the hack needed to get it work, plus it also works for the mobile nav.
EDIT - this works much better:
@media (min-width: 980px) {
body {
padding-top: 60px;
padding-bottom: 42px;
}
}
This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.
package main
import (
"fmt"
"os"
)
func main() {
if err := ensureDir("/test-dir"); err != nil {
fmt.Println("Directory creation failed with error: " + err.Error())
os.Exit(1)
}
// Proceed forward
}
func ensureDir(dirName string) error {
err := os.MkdirAll(dirName, os.ModeDir)
if err == nil || os.IsExist(err) {
return nil
} else {
return err
}
}
I find the jQuery select box manipulation plugin useful for this type of thing.
You can easily remove an item by index, value, or regex.
removeOption(index/value/regex/array[, selectedOnly])
Remove an option by
- index: $("#myselect2").removeOption(0);
- value: $("#myselect").removeOption("Value");
- regular expression: $("#myselect").removeOption(/^val/i);
- array $("#myselect").removeOption(["myselect_1", "myselect_2"]);
To remove all options, you can do $("#myselect").removeOption(/./);
.
To set image on your imageView use below line of code,
self.imgObj.image=[UIImage imageNamed:@"yourImage.png"];
Selecting target element from the list. It is easy to select particular element from the list of same elements.
component code:
export class AppComponent {
title = 'app';
listEvents = [
{'name':'item1', 'class': ''}, {'name':'item2', 'class': ''},
{'name':'item3', 'class': ''}, {'name':'item4', 'class': ''}
];
selectElement(item: string, value: number) {
console.log("item="+item+" value="+value);
if(this.listEvents[value].class == "") {
this.listEvents[value].class='selected';
} else {
this.listEvents[value].class= '';
}
}
}
html code:
<ul *ngFor="let event of listEvents; let i = index">
<li (click)="selectElement(event.name, i)" [class]="event.class">
{{ event.name }}
</li>
css code:
.selected {
color: red;
background:blue;
}
You can also use get and set minutes to achieve it:
var endDate = somedate;
var startdate = new Date(endDate);
var durationInMinutes = 20;
startdate.setMinutes(endDate.getMinutes() - durationInMinutes);
you can use this command
pg_dump --table=yourTable --data-only --column-inserts yourDataBase > file.sql
you should change yourTable, yourDataBase to your case
If I have understood it correctly, you are trying to convert a String representing a given date, to another type.
Note: (As @Samson Scharfrichter has mentioned)
There are a few ways to do it. And you are close to the solution. I would use the CAST (which converts to a DATE_TYPE):
SELECT cast('2018-06-05' as date);
Result: 2018-06-05 DATE_TYPE
or (depending on your pattern)
select cast(to_date(from_unixtime(unix_timestamp('05-06-2018', 'dd-MM-yyyy'))) as date)
Result: 2018-06-05 DATE_TYPE
And if you decide to convert ISO8601 to a date type:
select cast(to_date(from_unixtime(unix_timestamp(regexp_replace('2018-06-05T08:02:59Z', 'T',' ')))) as date);
Result: 2018-06-05 DATE_TYPE
Hive has its own functions, I have written some examples for the sake of illustration of these date- and cast- functions:
Date and timestamp functions examples:
Convert String/Timestamp/Date to DATE
SELECT cast(date_format('2018-06-05 15:25:42.23','yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_date(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_timestamp(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
Convert String/Timestamp/Date to BIGINT_TYPE
SELECT to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
SELECT to_unix_timestamp(current_date(),'yyyy/MM/dd HH:mm:ss'); -- 1528205000 BIGINT_TYPE
SELECT to_unix_timestamp(current_timestamp(),'yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
Convert String/Timestamp/Date to STRING
SELECT date_format('2018-06-05 15:25:42.23','yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_timestamp(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_date(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
Convert BIGINT unixtime to STRING
SELECT to_date(from_unixtime(unixtime,'yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 STRING_TYPE
Convert String to BIGINT unixtime
SELECT unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP; -- 1528149600 BIGINT_TYPE
Convert String to TIMESTAMP
SELECT cast(unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP); -- 1528149600 TIMESTAMP_TYPE
Idempotent (String -> String)
SELECT from_unixtime(to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 15:25:42 STRING_TYPE
Idempotent (Date -> Date)
SELECT cast(current_date() as date); -- 2018-06-26 DATE_TYPE
Current date / timestamp
SELECT current_date(); -- 2018-06-26 DATE_TYPE
SELECT current_timestamp(); -- 2018-06-26 14:03:38.285 TIMESTAMP_TYPE
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
try this Simple Automatic Number Plate Recognition System
Open source and written with C#
I have faced the same situation while designing custom notification. I have tried with the following attribute set with true.
android:layout_centerInParent.
would be a work around if you're only after the spacing.
I got this error too.
The problem turned out to be simply that I had to manually create the full directory structure for the file locations of the MDF & LDF files.
Shame on SQL-Server for not properly reporting the missing directory!
You whack the subitems into an array and add the array as a list item.
The order in which you add values to the array dictates the column they appear under so think of your sub item headings as [0],[1],[2] etc.
Here's a code sample:
//In this example an array of three items is added to a three column listview
string[] saLvwItem = new string[3];
foreach (string wholeitem in listofitems)
{
saLvwItem[0] = "Status Message";
saLvwItem[1] = wholeitem;
saLvwItem[2] = DateTime.Now.ToString("dddd dd/MM/yyyy - HH:mm:ss");
ListViewItem lvi = new ListViewItem(saLvwItem);
lvwMyListView.Items.Add(lvi);
}
<meta http-equiv="refresh" content="2; url=http://example.com/" />
Here 2
is delay in seconds.
Replace a string :
$str = str_replace("\n", '', $str);
u using also like, (%n, %t, All Special characters, numbers, char,. etc)
which means any thing u can replace in a string.
Do you want to make a string out of them?
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
Note that
String b = "b";
String s = "a" + b + "c";
Actually compiles to
String s = new StringBuilder("a").append(b).append("c").toString();
Edit: as litb pointed out, you can also do this:
"" + char1 + char2 + char3;
That compiles to the following:
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.
The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.
if(strcmp(sr1,str2)) // this returns 0 if strings r equal
flag=0;
else flag=1; // then last check the variable flag value and print the message
OR
char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);
for(int i=0;str1[i]!='\0';i++)
{
if(str[i]==str2[i])
flag=0;
else {flag=1; break;}
}
//check the value of flag if it is 0 then strings r equal simple :)
You should not make an ajax call, just put the src of the img element as the url of the image.
This would be useful if you use GET instead of POST
<script type="text/javascript" >
$(document).ready( function() {
$('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
} );
</script>
If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme
You'll need to encode the data
to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data>
into the img src
as example:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />
To encode to base64:
For the given json format as in file ~/my-app/src/db/abc.json:
[
{
"name":"Ankit",
"id":1
},
{
"name":"Aditi",
"id":2
},
{
"name":"Avani",
"id":3
}
]
inorder to import to .js file like ~/my-app/src/app.js:
const json = require("./db/abc.json");
class Arena extends React.Component{
render(){
return(
json.map((user)=>
{
return(
<div>{user.name}</div>
)
}
)
}
);
}
}
export default Arena;
Output:
Ankit Aditi Avani
for my experience, Ellipsis works only if below two attributes are set.
android:ellipsize="end"
android:singleLine="true"
for the width of textview, wrap_content or match_parent should both be good.
You may want to take a look at XCopy or RoboCopy which are pretty comprehensive solutions for nearly all file copy operations on Windows.
Solution in R (RSelenium): I had a popup dialog (which is dynamically generated) and hence undetectable in the original page source code Here are methods which worked for me:
Method 1: Simulating Pressing keys for Tabs and switching to that modal dialog My current key is focussed on a dropdown button behind the modal dialog boxremDr$sendKeysToActiveElement(list(key = "tab"))
Sys.sleep(5)
remDr$sendKeysToActiveElement(list(key = "enter"))
Sys.sleep(15)
Method 2: Bring focus to the frame(or iframe) if you can locate it
date_filter_frame <- remDr$findElement(using = "tag name", 'iframe')
date_filter_frame$highlightElement()
Sys.sleep(5)
remDr$switchToFrame(date_filter_frame)
Sys.sleep(2)
Now you can search for elements in the frame. Remember to put adequate Sys.sleep in between commands for elements to load properly (just in case)
date_filter_element <- remDr$findElement(using = "xpath", paste0("//*[contains(text(), 'Week to Date')]"))
date_filter_element$highlightElement()
Sometimes I like to do this using column ids instead.
df <- data.frame(a=rnorm(100),
b=rnorm(100),
c=rnorm(100),
d=rnorm(100),
e=rnorm(100),
f=rnorm(100),
g=rnorm(100))
as.data.frame(names(df))
names(df)
1 a
2 b
3 c
4 d
5 e
6 f
7 g
Removing columns "c" and "g"
df[,-c(3,7)]
This is especially useful if you have data.frames that are large or have long column names that you don't want to type. Or column names that follow a pattern, because then you can use seq() to remove.
RE: Your edit
You don't necessarily have to put "" around a string, nor "," to create a character vector. I find this little trick handy:
x <- unlist(strsplit(
'A
B
C
D
E',"\n"))
You have two ways to do that, both use the Arrays utility class
Example
class Book implements Comparable<Book> {
public String name, id, author, publisher;
public Book(String name, String id, String author, String publisher) {
this.name = name;
this.id = id;
this.author = author;
this.publisher = publisher;
}
public String toString() {
return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
}
@Override
public int compareTo(Book o) {
// usually toString should not be used,
// instead one of the attributes or more in a comparator chain
return toString().compareTo(o.toString());
}
}
@Test
public void sortBooks() {
Book[] books = {
new Book("foo", "1", "author1", "pub1"),
new Book("bar", "2", "author2", "pub2")
};
// 1. sort using Comparable
Arrays.sort(books);
System.out.println(Arrays.asList(books));
// 2. sort using comparator: sort by id
Arrays.sort(books, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.id.compareTo(o2.id);
}
});
System.out.println(Arrays.asList(books));
}
Output
[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]
Controller
public ActionResult Index()
{
//you don't need to include the category bc it does it by itself
//var model = db.Product.Include(c => c.Category).ToList()
ViewBag.Categories = db.Category.OrderBy(c => c.Name).ToList();
var model = db.Product.ToList()
return View(model);
}
View
you need to filter the model with the given category
like :=> Model.where(p=>p.CategoryID == category.CategoryID)
try this...
@foreach (var category in ViewBag.Categories)
{
<h3><u>@category.Name</u></h3>
<div>
@foreach (var product in Model.where(p=>p.CategoryID == category.CategoryID))
{
<table cellpadding="5" cellspacing"5" style="border:1px solid black; width:100%;background-color:White;">
<thead>
<tr>
<th style="background-color:black; color:white;">
@product.Title
@if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
{
@Html.Raw(" - ")
@Html.ActionLink("Edit", "Edit", new { id = product.ID }, new { style = "background-color:black; color:white !important;" })
}
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="background-color:White;">
@product.Description
</td>
</tr>
</tbody>
</table>
}
</div>
}
public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";
public static DataSet LoaderDataSet(string StrSql)
{
SqlConnection cnn;
SqlDataAdapter dad;
DataSet dts = new DataSet();
cnn = new SqlConnection(textDataSource);
dad = new SqlDataAdapter(StrSql, cnn);
try
{
cnn.Open();
dad.Fill(dts);
cnn.Close();
return dts;
}
catch (Exception)
{
return dts;
}
finally
{
dad.Dispose();
dts = null;
cnn = null;
}
}
Use the span
tag
<style>
.redText
{
color:red;
}
.blackText
{
color:black;
font-weight:bold;
}
</style>
<span class="redText">My Name is:</span> <span class="blackText">Tintincute</span>
It's also a good idea to avoid inline styling. Use a custom CSS class instead.
After installation, you need the following configuration to properly send mail from wampserver:
1) When you first open hMailServer Administrator, you need to add a new domain.
2) Click on the "Add Domain ..." button at the Welcome page.
3) Under the domain text field, enter your computer's IP, in this case it should be 127.0.0.1.
4) Click on the Save button.
5) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
6) Enter "localhost" in the localhost name field.
7) Click on the Save button.
If you need to send mail using a FROM addressee of another computer, you need to allow deliveries from External to External accounts. To do that, follow these steps:
1) Go to Settings>Advanced>IP Ranges and double click on "My Computer" which should have IP address of 127.0.0.1
2) Check the Allow Deliveries from External to External accounts checkbox.
3) Save settings using Save button.
(However, Windows Live/Hotmail has denied all emails coming from dynamic IPs, which most residential computers are using. The workaround is to use Gmail account )
1) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
2) Enter "smtp.gmail.com" in the Remote Host name field.
3) Enter "465" as the port number
4) Check "Server requires authentication"
5) Enter gmail address in the Username
6) Enter gmail password in the password
7) Check "Use SSL"
(Note, From field doesnt function with gmail)
*p.s. For some people it might also be needed to untick everything under require SMTP authentication
in :
You can use SendMail installation.
Use any of these methods.
As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.
Below is the code snippet for it :
//WorkAround
for (String color : colors ){
String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));
Jmi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
IconA icon = (IconA) item.getIcon();
// HERE YOU USE THE String color variable and no errors!!!
Color kolorIkony = getColour(color);
textArea.setForeground(kolorIkony);
}
});
mnForeground.add(Jmi);
}
}
$config['cricket'] = 'bat';
in config.php file
$this->config->item('cricket')
use this in view
Remove servlet.jar
from source web-inf/lib
folder as it is available in tomcat lib
folder then it works fine
This may be a easy solution.
var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");
FirstView
{
NSMutableArray *array; }
- (void)viewDidLoad {
[super viewDidLoad];
array = [[NSMutableArray alloc]init];
array = [[NSUserDefaults standardUserDefaults]objectForKey:@"userlist"];
NSLog(@"%lu",(unsigned long)array.count);
if (array>0)
{
for (int i=0; i<array.count; i++)
{
NSDictionary *dict1 = @{@"Username":[[array valueForKey:@"Username"] objectAtIndex:i],@"Mobilenumber":[[array valueForKey:@"Mobilenumber"] objectAtIndex:i],@"Firstname":[[array valueForKey:@"Firstname"] objectAtIndex:i],@"Lastname":[[array valueForKey:@"Lastname"] objectAtIndex:i],@"dob":[[array valueForKey:@"dob"] objectAtIndex:i],@"image":[[array valueForKey:@"image"] objectAtIndex:i]};
NSLog(@"%@",dict1);
NSArray *array1 = [[NSArray alloc]initWithObjects:dict1, nil];
[[NSUserDefaults standardUserDefaults] setObject:array1 forKey:@"UserList"];
}
}
}
ImagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imaGe.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
(IBAction)submitBton:(id)sender {
NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray:
[[NSUserDefaults standardUserDefaults]objectForKey:
@"userlist"]];
UIImage *ima = _imaGe.image;
NSData *imagedata = UIImageJPEGRepresentation(ima,100);
NSDictionary *dict = @{@"Username":_userTxt.text,@"Lastname":_lastTxt.text,@"Firstname":_firstTxt.text,@"Mobilenumber":_mobTxt.text,@"dob":_dobTxt.text,@"image":imagedata};
[array2 addObject:dict];
[[NSUserDefaults standardUserDefaults]setObject:array2
forKey:@"userlist"];
NSLog(@"%@",array2);
[self performSegueWithIdentifier:@"second" sender:self];
}
(IBAction)chooseImg:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController
alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
second View { NSMutableArray *arr; }
- (void)viewDidLoad {
[super viewDidLoad];
arr =[[NSMutableArray alloc]init];
arr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userlist"]; }
#pragma mark- TableView DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1; }
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return arr.count; }
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellId = @"tablecell";
TableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
cell.userLbl.text =[[arr valueForKey:@"username"] objectAtIndex:indexPath.row];
cell.ageLbl.text =[[arr valueForKey:@"dob"] objectAtIndex:indexPath.row];
cell.profileImg.image =[UIImage imageNamed:[[arr valueForKey:@"image"] objectAtIndex:indexPath.row]];
return cell; }
The answer of crdunst is pretty neat and the best looking answer I've found but there's no explanation on how to use and the code is bigger than needed.
The only code you need:
#element {
background-color: #cacbcf;
text-shadow: 2px 2px 4px rgba(0,0,0, 0.5);
filter: chroma(color=#cacbcf) progid:DXImageTransform.Microsoft.dropshadow(color=#60000000, offX=2, offY=2);
}
First you MUST specify a background-color
- if your element should be transparent just copy the background-color of the parent or let it inherit. The color at the chroma-filter must match the background-color to fix those artifacts around the text (but here you must copy the color, you can't write inherit
). Note that I haven't shortened the dropshadow-filter - it works but the shadows are then cut to the element dimensions (noticeable with big shadows; try to set the offsets to atleast 4).
TIP: If you want to use colors with transparency (alpha-channel) write in a #AARRGGBB notation, where AA stands for a hexadezimal value of the opacity - from 01 to FE, because FF and ironically also 00 means no transparency and is therefore useless.. ^^ Just go a little lower than in the rgba notation because the shadows aren't soft and the same alpha value would appear darker then. ;)
A nice snippet to convert the alpha value for IE (JavaScript, just paste into the console):
var number = 0.5; //alpha value from the rgba() notation
("0"+(Math.round(0.75 * number * 255).toString(16))).slice(-2);
ISSUES: The text/font behaves like an image after the shadow is applied; it gets pixelated and blurry after you zoom in... But that's IE's issue, not mine.
Live demo of the shadow here: http://jsfiddle.net/12khvfru/2/
The syntax you're after is possible with a little helper function that converts a Runnable
into Action<Void, Void>
(you can place it in Action
for example):
public static Action<Void, Void> action(Runnable runnable) {
return (v) -> {
runnable.run();
return null;
};
}
// Somewhere else in your code
Action<Void, Void> action = action(() -> System.out.println("foo"));
Note : a nice easy alternative to using the inbuilt "Visual Studio Development Server" or IIS Express (e.g. because you are developing against IIS and have particular settings you need for proper functioning of your app) is to simply stay running run in IIS (I use the Custom Web Server + hosts file entry + IIS binding to same domain)
Your breakpoint should be hit nicely, and you can continue to debug in your natural IIS habitat. Great !
What's a "block scheme"?
If I were drawing it, I might draw a box with "for each x in y" written in it.
If you're drawing a flowchart, there's always a loop with a decision box.
Nassi-Schneiderman diagrams have a loop construct you could use.
$('mainCheckBox').click(function(){
if($(this).prop('checked')){
$('Id or Class of checkbox').prop('checked', true);
}else{
$('Id or Class of checkbox').prop('checked', false);
}
});
The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.
Instead, use sos (second-order sections) output of filter design.
from scipy.signal import butter, sosfilt, sosfreqz
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype='band', output='sos')
return sos
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfilt(sos, data)
return y
Also, you can plot frequency response by changing
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
to
sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)
if (obj === undefined)
{
// Create obj
}
If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.
Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.
Try resetting your password since it seems it has changed you can reset your password by going to
C:\xampp\mysql
and clicking on the resetroot.bat file
Then change in the php config file the password back to blank and you should have access again
I've wanted to do this quite a lot. This hack is very similar to rlotun's suggestion, but it's a one-liner, which is important to me:
blah = 1
blah_name = [ k for k,v in locals().iteritems() if v is blah][0]
Python 3+
blah = 1
blah_name = [ k for k,v in locals().items() if v is blah][0]
There is a numpy built-in function to help with that.
import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])
Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of **kwargs
or remove them from *args
. Instead, you can define a Base
class which unlike object
, absorbs/ignores arguments:
class Base(object):
def __init__(self, *args, **kwargs): pass
class A(Base):
def __init__(self, *args, **kwargs):
print "A"
super(A, self).__init__(*args, **kwargs)
class B(Base):
def __init__(self, *args, **kwargs):
print "B"
super(B, self).__init__(*args, **kwargs)
class C(A):
def __init__(self, arg, *args, **kwargs):
print "C","arg=",arg
super(C, self).__init__(arg, *args, **kwargs)
class D(B):
def __init__(self, arg, *args, **kwargs):
print "D", "arg=",arg
super(D, self).__init__(arg, *args, **kwargs)
class E(C,D):
def __init__(self, arg, *args, **kwargs):
print "E", "arg=",arg
super(E, self).__init__(arg, *args, **kwargs)
print "MRO:", [x.__name__ for x in E.__mro__]
E(10)
yields
MRO: ['E', 'C', 'A', 'D', 'B', 'Base', 'object']
E arg= 10
C arg= 10
A
D arg= 10
B
Note that for this to work, Base
must be the penultimate class in the MRO.
If you don't want or you cannot modify the settings.xml
file, you can create a new one in your root project, and call maven passing it as a parameter with the -s
parameter:
$ mvn COMMAND ... -s settings.xml
GridView
is used for implementing material grid lists. If you know you have a fixed number of items and it's not very many (16 is fine), you can use GridView.count
. However, you should note that a GridView
is scrollable, and if that isn't what you want, you may be better off with just rows and columns.
import 'dart:collection';
import 'package:flutter/scheduler.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.orange,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget{
@override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(
title: new Text('Grid Demo'),
),
body: new GridView.count(
crossAxisCount: 4,
children: new List<Widget>.generate(16, (index) {
return new GridTile(
child: new Card(
color: Colors.blue.shade200,
child: new Center(
child: new Text('tile $index'),
)
),
);
}),
),
);
}
}
The problem here is very simple. If you want to display value in JSP, you have to use <%= %> tag instead of <% %>, here is the solved code:
<tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getString("SKILL") %></td>
</tr>
var ListByOwner = list.GroupBy(l => l.Owner)
.Select(lg =>
new {
Owner = lg.Key,
Boxes = lg.Count(),
TotalWeight = lg.Sum(w => w.Weight),
TotalVolume = lg.Sum(w => w.Volume)
});
This is the JsonParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Note: DefaultHttpClient is no longer supported by sdk 23, so it is advisable to use target sdk 21 with this code.
As has been mentioned cron is deprecated (but supported), and launchd is recommended for OS X.
This is taken from developer.apple.com
If the system is turned off or asleep, cron jobs do not execute; they will not run until the next designated time occurs.
If you schedule a launchd job by setting the StartCalendarInterval key and the computer is asleep when the job should have run, your job will run when the computer wakes up. However, if the machine is off when the job should have run, the job does not execute until the next designated time occurs.
All other launchd jobs are skipped when the computer is turned off or asleep; they will not run until the next designated time occurs.
Consequently, if the computer is always off at the job’s scheduled time, both cron jobs and launchd jobs never run. For example, if you always turn your computer off at night, a job scheduled to run at 1 A.M. will never be run.
You can use the following attributes for webkit, which reach into the shadow DOM:
::-webkit-scrollbar { /* 1 */ }
::-webkit-scrollbar-button { /* 2 */ }
::-webkit-scrollbar-track { /* 3 */ }
::-webkit-scrollbar-track-piece { /* 4 */ }
::-webkit-scrollbar-thumb { /* 5 */ }
::-webkit-scrollbar-corner { /* 6 */ }
::-webkit-resizer { /* 7 */ }
Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.
http://jsfiddle.net/hmartiro/Xck2A/1/
Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.
just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()
ddl2.DataSource=New List(Of String)() ddl2.DataSource = sql2 ddl2.DataBind() End Sub
and it worked just fine
you can also use jquery. This is the same what Alex proposed just using JQuery:
$('#currentElement').attr("src", $('#currentElement').attr("src"));
I think that your model #2 is fine, however you can take a look at the more complex model which stores questions and pre-made answers (offered answers) and allows them to be re-used in different surveys.
- One survey can have many questions; one question can be (re)used in many surveys.
- One (pre-made) answer can be offered for many questions. One question can have many answers offered. A question can have different answers offered in different surveys. An answer can be offered to different questions in different surveys. There is a default "Other" answer, if a person chooses other, her answer is recorded into Answer.OtherText.
- One person can participate in many surveys, one person can answer specific question in a survey only once.
You can do this without a JOIN
:
SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
FROM YourTable
)sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids
Demo: SQL Fiddle
I have been working on a solution to finding the parent object of the current object for my own pet project. Adding a reference to the parent object within the current object creates a cyclic relationship between the two objects.
Consider -
var obj = {
innerObj: {},
setParent: function(){
this.innerObj.parent = this;
}
};
obj.setParent();
The variable obj will now look like this -
obj.innerObj.parent.innerObj.parent.innerObj...
This is not good. The only solution that I have found so far is to create a function which iterates over all the properties of the outermost Object until a match is found for the current Object and then that Object is returned.
Example -
var obj = {
innerObj: {
innerInnerObj: {}
}
};
var o = obj.innerObj.innerInnerObj,
found = false;
var getParent = function (currObj, parObj) {
for(var x in parObj){
if(parObj.hasOwnProperty(x)){
if(parObj[x] === currObj){
found = parObj;
}else if(typeof parObj[x] === 'object'){
getParent(currObj, parObj[x]);
}
}
}
return found;
};
var res = getParent(o, obj); // res = obj.innerObj
Of course, without knowing or having a reference to the outermost object, there is no way to do this. This is not a practical nor is it an efficient solution. I am going to continue to work on this and hopefully find a good answer for this problem.
log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.
Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.
Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
<Properties>
<Property name="filename">log/CelsiusConverter.log</Property>
</Properties>
<Appenders>
<Appender type="Console" name="Console">
<Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
</Appender>
<Appender type="Console" name="FLOW">
<Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
</Appender>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="File" />
<AppenderRef ref="Console" />
<!-- Use FLOW to trace down exact method sending the msg -->
<!-- <AppenderRef ref="FLOW" /> -->
</Root>
</Loggers>
</Configuration>
It's due to you sending one object, and you're expecting two parameters.
Try this and you'll see:
public class UserDetails
{
public string username { get; set; }
public string password { get; set; }
}
public JsonResult Login(UserDetails data)
{
string error = "";
//the rest of your code
}
The execmgr.log
will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log
and some clients will have outdated appenforce
or no ppenforce.log
files.
execmgr.log
also shows required hidden uninstall actions as well.
You may want to save the blog link. I still reference it from time to time.
You can set the ReadOnly property to true.
Quoth the link:
When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.
In my case i had to install google repository from the SDK manager.
db.users.count()
db.users.remove({})
db.users.count()
The Facebook API limit isn't really documented, but apparently it's something like: 600 calls per 600 seconds, per token & per IP. As the site is restricted, quoting the relevant part:
After some testing and discussion with the Facebook platform team, there is no official limit I'm aware of or can find in the documentation. However, I've found 600 calls per 600 seconds, per token & per IP to be about where they stop you. I've also seen some application based rate limiting but don't have any numbers.
As a general rule, one call per second should not get rate limited. On the surface this seems very restrictive but remember you can batch certain calls and use the subscription API to get changes.
As you can access the Graph API on the client side via the Javascript SDK; I think if you travel your request for photos from the client, you won't hit any application limit
as it's the user (each one with unique id) who's fetching data, not your application server (unique ID).
This may mean a huge refactor if everything you do go through a server. But it seems like the best solution if you have so many request (as it'll give a breath to your server).
Else, you can try batch
request, but I guess you're already going this way if you have big traffic.
If nothing of this works, according to the Facebook Platform Policy you should contact them.
If you exceed, or plan to exceed, any of the following thresholds please contact us as you may be subject to additional terms: (>5M MAU) or (>100M API calls per day) or (>50M impressions per day).
If you want an alphanumeric strings with lowercase and uppercase characters ([a-zA-Z0-9]), you can use Convert.ToBase64String() for a fast and simple solution.
As for uniqueness, check out the birthday problem to calculate how likely a collission is given (A) the length of the strings generated and (B) the number of strings generated.
Random random = new Random();
int outputLength = 10;
int byteLength = (int)Math.Ceiling(3f / 4f * outputLength); // Base64 uses 4 characters for every 3 bytes of data; so in random bytes we need only 3/4 of the desired length
byte[] randomBytes = new byte[byteLength];
string output;
do
{
random.NextBytes(randomBytes); // Fill bytes with random data
output = Convert.ToBase64String(randomBytes); // Convert to base64
output = output.Substring(0, outputLength); // Truncate any superfluous characters and/or padding
} while (output.Contains('/') || output.Contains('+')); // Repeat if we contain non-alphanumeric characters (~25% chance if length=10; ~50% chance if length=20; ~35% chance if length=32)
Install the NuGet package called SevenZipSharp.Interop
Then:
SevenZipBase.SetLibraryPath(@".\x86\7z.dll");
var compressor = new SevenZip.SevenZipCompressor();
var filesToCompress = Directory.GetFiles(@"D:\data\");
compressor.CompressFiles(@"C:\archive\abc.7z", filesToCompress);
You can also done this by using group by clause
SELECT purchases.address_id, purchases.* FROM "purchases"
WHERE "purchases"."product_id" = 1 GROUP BY address_id,
purchases.purchased_at ORDER purchases.purchased_at DESC
$('select').val('')
I simply used this on the select itself and it did the trick.
I'm on jQuery 1.7.1.
My solution was to make all the parents 100% and set a specific percentage for each row:
html, body,div[class^="container"] ,.column {
height: 100%;
}
.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}
Based on @AmNaN suggestion (more details):
class ApplicationController < ActionController::Base
def current_controller?(names)
names.include?(params[:controller]) unless params[:controller].blank? || false
end
helper_method :current_controller?
end
Now you can call it e.g. in a navigation layout for marking list items as active:
<ul class="nav nav-tabs">
<li role="presentation" class="<%= current_controller?('items') ? 'active' : '' %>">
<%= link_to user_items_path(current_user) do %>
<i class="fa fa-cloud-upload"></i>
<% end %>
</li>
<li role="presentation" class="<%= current_controller?('users') ? 'active' : '' %>">
<%= link_to users_path do %>
<i class="fa fa-newspaper-o"></i>
<% end %>
</li>
<li role="presentation" class="<%= current_controller?('alerts') ? 'active' : '' %>">
<%= link_to alerts_path do %>
<i class="fa fa-bell-o"></i>
<% end %>
</li>
</ul>
For the users
and alerts
routes, current_page?
would be enough:
current_page?(users_path)
current_page?(alerts_path)
But with nested routes and request for all actions of a controller (comparable with items
), current_controller?
was the better method for me:
resources :users do
resources :items
end
The first menu entry is that way active for the following routes:
/users/x/items #index
/users/x/items/x #show
/users/x/items/new #new
/users/x/items/x/edit #edit
We can use pip freeze
to get any Python package version without opening the Python shell.
pip freeze | grep 'numpy'
For use with React Router v4 and a functional component anywhere in the dom-tree.
import React from 'react';
import { withRouter } from 'react-router-dom';
const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;
export default withRouter(GoBack);
Is the Postman Interceptor enabled? Toggling it will route all requests and responses through the Chrome browser.
Interceptor - https://www.getpostman.com/docs/capture Cookies documentation - http://blog.getpostman.com/index.php/2014/11/28/using-the-interceptor-to-read-and-write-cookies/
You could also use ld
option -Bdynamic
gcc <objectfiles> -static -lstatic1 -lstatic2 -Wl,-Bdynamic -ldynamic1 -ldynamic2
All libraries after it (including system ones linked by gcc automatically) will be linked dynamically.
You could make the text color the same as the background color:
#mybox:hover
{
background-color: red;
color: red;
}
This is Code for converting the image of any type(for example PNG, JPG, JPEG) to byte array
public static byte[] imageConversion(string imageName){
//Initialize a file stream to read the image file
FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
//Close a file stream
fs.Close();
return imageByteArr
}
Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.
You might also consider adding "
.
For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus"
is very good idea.
Here is an example of getting the bounds using svg.getBox()
:
https://gist.github.com/john-doherty/2ad94360771902b16f459f590b833d44
At the end you get numbers that you can plug into the svg to set the viewbox properly. Then use any css on the parent div and you're done.
// get all SVG objects in the DOM
var svgs = document.getElementsByTagName("svg");
var svg = svgs[0],
box = svg.getBBox(), // <- get the visual boundary required to view all children
viewBox = [box.x, box.y, box.width, box.height].join(" ");
// set viewable area based on value above
svg.setAttribute("viewBox", viewBox);
I had the same issue because I had 2 .git
folders in the working directory.
Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git
folders, and, if so, deleting one of them.
That allowed me to upload the project successfully.
Three options:
Option1:
public class TheRepresentativeType {
public ... SomeVariable {get;set;}
public ... AnotherVariable {get;set;}
}
public IEnumerable<TheRepresentativeType> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB;
}
}
Option 2:
public IEnumerable TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB;
}
}
you can iterate it as object
Option 3:
public IEnumerable<dynamic> TheMethod(SomeParameter)
{
using (MyDC TheDC = new MyDC())
{
var TheQueryFromDB = (....
select new TheRepresentativeType{ SomeVariable = ....,
AnotherVariable = ....}
).ToList();
return TheQueryFromDB; //You may need to call .Cast<dynamic>(), but I'm not sure
}
}
and you will be able to iterate it as a dynamic object and access their properties directly
You can make a simple program to ask for the user's name and print whatever the reply use inputs.
Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.
So there you need the Scanner class. You have to import java.util.Scanner;
, and in the code you need to use:
Scanner input = new Scanner(System.in);
input
is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value
System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer
System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double
See how this differs: input.next();
, i = input.nextInt();
, d = input.nextDouble();
According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.
session in rails is a hash object. Hence any function available for clearing hash will work with sessions.
session.clear
or if specific keys have to be destroyed:
session.delete(key)
Tested in rails 3.2
added
People have mentioned by session={}
is a bad idea. Regarding session.clear
, Lobati comments- It looks like you're probably better off using reset_session [than session.clear], as it does some other cleaning up beyond what session.clear does. Internally, reset_session calls session.destroy, which itself calls clear as well some other stuff.
just copy " _CRT_SECURE_NO_WARNINGS " paste it on projects->properties->c/c++->preprocessor->preprocessor definitions click ok.it will work
DateTime
class , OOP Style.<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m
You Must use
-(void)viewWillAppear:(BOOL)animated
and set your entries like you want...
As stated by others, your question is ambiguous at best. The problem is, you want to represent the object as a string, and then be able to construct the object again from that string.
However, note that while many object types in Java have string representations, this does not guarantee that an object can be constructed from its string representation.
To quote this source,
Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time.
So, you see, what you want might not be possible. But it is possible to save your object's state to a byte sequence, and then reconstruct it from that byte sequence.
You can try like:
$("#myformid").submit(function(){
//perform anythng
});
Or even you can try like
$(".nextbutton").click(function() {
$('#form1').submit();
});
A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:
var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));
Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:
var $a = $('#demoTable td'); var inner = ''; $a.children.html().each(function() { inner = inner + this.outerHTML; }); $a.html('New text' + inner);
Whenever I have a NuGet error such as these I usually take these steps:
Taking all of these steps almost always restores all the packages and dll's I need for my MVC program.
EDIT >>>
For Visual Studio 2013 and above, step 2) should read:
If a number n
is not a prime, it can be factored into two factors a
and b
:
n = a * b
Now a
and b
can't be both greater than the square root of n
, since then the product a * b
would be greater than sqrt(n) * sqrt(n) = n
. So in any factorization of n
, at least one of the factors must be smaller than the square root of n
, and if we can't find any factors less than or equal to the square root, n
must be a prime.
Microsoft provides us built-in functionality which we use in our application for security purposes, so no one can hack our site or invade some critical information.
From Purpose Of ValidateAntiForgeryToken In MVC Application by Harpreet Singh:
Use of ValidateAntiForgeryToken
Let’s try with a simple example to understand this concept. I do not want to make it too complicated, that’s why I am going to use a template of an MVC application, already available in Visual Studio. We will do this step by step. Let’s start.
Step 1 - Create two MVC applications with default internet template and give those names as CrossSite_RequestForgery and Attack_Application respectively.
Now, open CrossSite_RequestForgery application's Web Config and change the connection string with the one given below and then save.
`
<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF; Integrated Security=true;" providerName="System.Data.SqlClient" /> </connectionStrings>
Now, click on Tools >> NuGet Package Manager, then Package Manager Console
Now, run the below mentioned three commands in Package Manager Console to create the database.
Enable-Migrations add-migration first update-database
Important Notes - I have created database with code first approach because I want to make this example in the way developers work. You can create database manually also. It's your choice.
- Now, open Account Controller. Here, you will see a register method whose type is post. Above this method, there should be an attribute available as [ValidateAntiForgeryToken]. Comment this attribute. Now, right click on register and click go to View. There again, you will find an html helper as @Html.AntiForgeryToken() . Comment this one also. Run the application and click on register button. The URL will be open as:
http://localhost:52269/Account/Register
Notes- I know now the question being raised in all readers’ minds is why these two helpers need to be commented, as everyone knows these are used to validate request. Then, I just want to let you all know that this is just because I want to show the difference after and before applying these helpers.
Now, open the second application which is Attack_Application. Then, open Register method of Account Controller. Just change the POST method with the simple one, shown below.
Registration Form
- @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
- @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
- @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)
7.Now, suppose you are a hacker and you know the URL from where you can register user in CrossSite_RequestForgery application. Now, you created a Forgery site as Attacker_Application and just put the same URL in post method.
8.Run this application now and fill the register fields and click on register. You will see you are registered in CrossSite_RequestForgery application. If you check the database of CrossSite_RequestForgery application then you will see and entry you have entered.
- Important - Now, open CrossSite_RequestForgery application and comment out the token in Account Controller and register the View. Try to register again with the same process. Then, an error will occur as below.
Server Error in '/' Application. ________________________________________ The required anti-forgery cookie "__RequestVerificationToken" is not present.
This is what the concept says. What we add in View i.e. @Html.AntiForgeryToken() generates __RequestVerificationToken on load time and [ValidateAntiForgeryToken] available on Controller method. Match this token on post time. If token is the same, then it means this is a valid request.
The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.
I pulled most of this code from another post found here. I have modified it for my purposes. This works well for what I need. It may help with your situation.
$(window).load(function() {
function checkDate() {
var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var valDate = $(this).val();
if ( valDate.match( dateFormat )) {
$(this).css("border","1px solid #cccccc","color", "#555555", "font-weight", "normal");
var seperator1 = valDate.split('/');
var seperator2 = valDate.split('-');
if ( seperator1.length > 1 ) {
var splitdate = valDate.split('/');
} else if ( seperator2.length > 1 ) {
var splitdate = valDate.split('-');
}
var dd = parseInt(splitdate[0]);
var mm = parseInt(splitdate[1]);
var yy = parseInt(splitdate[2]);
var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];
if ( mm == 1 || mm > 2 ) {
if ( dd > ListofDays[mm - 1] ) {
$(this).val("");
$(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
alert('Invalid Date! You used a date which does not exist in the known calender.');
return false;
}
}
if ( mm == 2 ) {
var lyear = false;
if ( (!(yy % 4) && yy % 100) || !(yy % 400) ){
lyear = true;
}
if ( (lyear==false) && (dd>=29) ) {
$(this).val("");
$(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
alert('Invalid Date! You used Feb 29th for an invalid leap year');
return false;
}
if ( (lyear==true) && (dd>29) ) {
$(this).val("");
$(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
alert('Invalid Date! You used a date greater than Feb 29th in a valid leap year');
return false;
}
}
} else {
$(this).val("");
$(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
alert('Date format was invalid! Please use format mm/dd/yyyy');
return false;
}
};
$('#from_date').change( checkDate );
$('#to_date').change( checkDate );
});
Here is another possible workaround:
if exists (select * from master..sysservers where srvname = 'loopback')
exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver @server = N'loopback', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = @@servername
go
create function testit()
returns int
as
begin
declare @res int;
select @res=count(*) from openquery(loopback, 'exec sp_who');
return @res
end
go
select dbo.testit()
It's not so scary as xp_cmdshell
but also has too many implications for practical use.
All it takes is a bit of XAML...
<Window x:Class="WCSamples.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close"
Executed="CloseCommandHandler"/>
</Window.CommandBindings>
<StackPanel Name="MainStackPanel">
<Button Command="ApplicationCommands.Close"
Content="Close Window" />
</StackPanel>
</Window>
And a bit of C#...
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
(adapted from this MSDN article)
They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.
you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.
def find_pos(chaine,x):
for i in range(len(chaine)):
if chaine[i] ==x :
return 'yes',i
return 'no'
The virtual keyword forces the compiler to pick the method implementation defined in the object's class rather than in the pointer's class.
Shape *shape = new Triangle();
cout << shape->getName();
In the above example, Shape::getName will be called by default, unless the getName() is defined as virtual in the Base class Shape. This forces the compiler to look for the getName() implementation in the Triangle class rather than in the Shape class.
The virtual table is the mechanism in which the compiler keeps track of the various virtual-method implementations of the subclasses. This is also called dynamic dispatch, and there is some overhead associated with it.
Finally, why is virtual even needed in C++, why not make it the default behavior like in Java?
I know it's an old question and it has been solved already but for me the Tomcat conf/tomcat-users.xml file was created with a different encoding from the rest of the configuration files. The first line of that file looked like this:
<?xml version='1.0' encoding='cp65001'?>
All I had to do to solve the issue was change that line for:
<?xml version="1.0" encoding="UTF-8"?>
And voila.
I have no idea what 'cp65001'
means or why it was created like that.
Maybe this will help other users facing the same issue.
I would create separate images for each one:
LDPI should be 36 x 36.
MDPI should be 48 x 48.
TVDPI should be 64 x 64.
HDPI should be 72 x 72.
XHDPI should be 96 x 96.
XXHDPI should be 144 x 144.
XXXHDPI should be 192 x 192.
Then just put each of them in the separate stalks of the drawable folder.
You are also required to give a large version of your icon when uploading your app onto the Google Play Store and this should be WEB 512 x 512
. This is so large so that Google can rescale it to any size in order to advertise your app throughout the Google Play Store and not add pixelation to your logo.
Basically, all of the other icons should be in proportion to the 'baseline' icon, MDPI at 48 x 48
.
LDPI is MDPI x 0.75.
TVDPI is MDPI x 1.33.
HDPI is MDPI x 1.5.
XHDPI is MDPI x 2.
XXHDPI is MDPI x 3.
XXXHDPI is MDPI x 4.
This is all explained on the Iconography page of the Android Developers website: http://developer.android.com/design/style/iconography.html