This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)
char *words; // setting this to NULL would have prevented the issue
if (condition) {
words = malloc( 512 );
/* calling free sometime later works here */
free(words)
} else {
/* do not allocate words in this branch */
}
/* free(words); -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/
There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:
*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer
IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.
Parse the string into date, then compare using compareTo
, before
or after
Date d = new Date();
d.compareTo(anotherDate)
i.e
Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(date1string)
Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse(date2string)
date1.compareTo(date2);
Copying the comment provided below by @MuhammadSaqib to complete this answer.
Returns the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument, and a value greater than 0 if this Date is after the Date argument. and NullPointerException - if anotherDate is null.
javadoc for compareTo http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo(java.util.Date)
Could someone explain to me, how to call the move method with the variable RIGHT
>>> myMissile = MissileDevice(myBattery) # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)
If you have programmed in any other language with classes, besides python, this sort of thing
class Foo:
bar = "baz"
is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; and variables defined in its scope are attached to the class, not the instances returned by the class. to refer to bar
, above, you can just call it Foo.bar
; you can also access class attributes through instances of the class, like Foo().bar
.
Im utterly baffled about what 'self' refers too,
>>> class Foo:
... def quux(self):
... print self
... print self.bar
... bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>
When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. All this does is arrange for the instance to be passed as the first argument.
To run the .bat, and have access to the last exit code, run it as:
& .\my-app\my-fle.bat
First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?
I think there is a workaround to make constructor private.
Thanks Pablo, just what I was looking for! However, if I can take the liberty of improving your script slightly, I suggest replacing your ^V macro with the following:
; Use backslash instead of backtick (yes, I am a C++ programmer).
#EscapeChar \
; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
SendInput {Raw}%clipboard2%
return
The advantage of using SendInput is that
Note, it's important to include the "{Raw}" in the SendInput command, in case the clipboard happens to contain "!", "+", "^" or "#".
Note, it uses StringReplace to remove excess Windows carriage return characters. Thanks hugov for that suggestion!
If you have java8, and you can use the G1 Garbage Collector, then run your application with:
-XX:+UseG1GC -XX:+UseStringDeduplication
This tells the G1 to find similar Strings and keep only one of them in memory, and the others are only a pointer to that String in memory.
This is useful when you have a lot of repeated strings. This solution may or not work and depends on each application.
More info on:
https://blog.codecentric.de/en/2014/08/string-deduplication-new-feature-java-8-update-20-2/
http://java-performance.info/java-string-deduplication/
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
In C++11 you could also create an alias for convenience:
template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
And use it like this:
min_heap<int> my_heap;
String mQuery = "SELECT Name,Family From tblName";
Cursor mCur = db.rawQuery(mQuery, new String[]{});
mCur.moveToFirst();
while ( !mCur.isAfterLast()) {
String name= mCur.getString(mCur.getColumnIndex("Name"));
String family= mCur.getString(mCur.getColumnIndex("Family"));
mCur.moveToNext();
}
Name and family are your result
it doenst work for me but it prints the correct element to the console
this is the code:
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
console.log(el); //print element to console
el.dispatchEvent(ev);
}
click(400, 400);
Your current implementation is correct. The suggested is not possible but the pseudo code would be implemented with multiple equal()
calls and ||
.
You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.
WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.
Generally speaking, many configurations files also go into WEB-INF.
As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).
True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.
Given your number
x = Decimal('40800000000.00000000000000')
Starting from Python 3,
'{:.2e}'.format(x)
is the recommended way to do it.
e
means you want scientific notation, and .2
means you want 2 digits after the dot. So you will get x.xxE±n
The best way is probably to use:
:%s/phrase//gc
c
asks for confirmation before each deletion. g
allows multiple replacements to occur on the same line.
You can also just search using /phrase
, select the next match with gn
, and delete it with d
.
yes in Virtuemart its must be button CLOSe-continue shopping, not element, because after click you can redirect.. i found this redirect bug on my ajax website.
Ok the first issue with the div tag was easy enough:
I just added a style="display:none;"
to it and then before showing the dialog I added this in my dialog script:
$("#dialog").css("display", "inherit");
But for the post version I'm still out of luck.
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
Well that may inspire u Those steps show how to create bordered table dynamically
here is the table view
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/nested_scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:scrollingCache="true">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:stretchColumns="*"
>
</TableLayout>
</android.support.v4.widget.NestedScrollView>
and here the row to use "attrib_row.xml"
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/border"
>
<TextView
android:id="@+id/attrib_name"
android:textStyle="bold"
android:height="30dp"
android:background="@drawable/border"
android:gravity="center"
/>
<TextView
android:id="@+id/attrib_value"
android:gravity="center"
android:height="30dp"
android:textStyle="bold"
android:background="@drawable/border"
/>
</TableRow>
and we can add this xml file to drawable to add border to our table "border.xml"
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape= "rectangle">
<solid android:color="@color/colorAccent"/>
<stroke android:width="1dp" android:color="#000000"/>
</shape>
and finally here is the compact code written in Kotlin but it's easy to convert it to java if you need
well temps is an array list contain data: ArrayList<Double>()
fun CreateTable()
{
val temps=controller?.getTemps()
val rowHead = LayoutInflater.from(context).inflate(R.layout.attrib_row, null) as TableRow
(rowHead.findViewById<View>(R.id.attrib_name) as TextView).text=("time")
(rowHead.findViewById<View>(R.id.attrib_value) as TextView).text=("Value")
table!!.addView(rowHead)
for (i in 0 until temps!!.size) {
val row = LayoutInflater.from(context).inflate(R.layout.attrib_row, null) as TableRow
(row.findViewById<View>(R.id.attrib_name) as TextView).text=((i+1).toString())
(row.findViewById<View>(R.id.attrib_value) as TextView).text=(temps[i].toString())
table!!.addView(row)
}
table!!.requestLayout()
}
and you can use it in your fragment for example like this
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
table = view?.findViewById<View>(R.id.simpleTableLayout) as TableLayout
CreateTable()
}
I was facing a similar issue and found that a few fields like Date were not getting a concrete value, once given the values things worked fine. Please make sure you do not have date or any other field present on the form which needs a concrete value.
In my case helped type disk name in lower case
Wrong - C:\someFolder
Correct - c:\someFolder
You can also use:
@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")
To specify the format of your output in a scenario where you need to use Charset, Type, etc.
I know this is an old question, but I thought I'd present one more solution that could be used if you'd like to avoid using named function expressions. (Not saying you should or should not avoid them, just presenting another solution)
var fn = (function() {
var innerFn = function(counter) {
console.log(counter);
if(counter > 0) {
innerFn(counter-1);
}
};
return innerFn;
})();
console.log("running fn");
fn(3);
var copyFn = fn;
console.log("running copyFn");
copyFn(3);
fn = function() { console.log("done"); };
console.log("fn after reassignment");
fn(3);
console.log("copyFn after reassignment of fn");
copyFn(3);
For zsh, echo
setopt VERBOSE
And for debugging,
setopt XTRACE
Assuming someTestObj
is a class
and not a struct
, the object is passed by reference, which means that both obj
and someTestObj
refer to the same object. E.g. changing name
in one will change it in the other. However, unlike if you passed it using the ref
keyword, setting obj = somethingElse
will not change someTestObj
.
It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.
If you want to fade to black(ish), you'll need a black container around the image. Something like:
.ctr {
margin: 0;
padding: 0;
background-color: black;
display: inline-block;
}
and
<div class="ctr"><img ... /></div>
Something like this should work (it did for me). The reason for wanting to use -Filter
instead of -Include
is that include takes a huge performance hit compared to -Filter
.
Below just loops each file type and multiple servers/workstations specified in separate files.
##
## This script will pull from a list of workstations in a text file and search for the specified string
## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside
$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'
##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'
foreach ($server in $servers)
{
foreach ($filetype in $filetypes)
{
## below creates the search path. This could be further improved to exclude the windows directory
$serverString = "\\"+$server+"\c$\Program Files"
## Display the server being queried
write-host “Server:” $server "searching for " $filetype in $serverString
Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
#-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt
$os = gwmi win32_operatingsystem -computer $server
$sp = $os | % {$_.servicepackmajorversion}
$a = $os | % {$_.caption}
## Below will list again the server name as well as its OS and SP
## Because the script may not be monitored, this helps confirm the machine has been successfully scanned
write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp
}
}
#end script
Please refer SysInternal toolkit from Microsoft from below link, https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer
Goto the download folder, Open "Procexp64.exe" as admin privilege. Open Find Menu-> "Find Handle or DLL" option or Ctrl+F shortcut way.
ClickOnce Publishing Tools are not installed as part of the Typical Installation Options. So you have to install it in advanced mode.
This dialog can be found in Windows 7 by going to Control Panel > Uninstall a program, right-clicking on Microsoft Visual Studio Professional 2015 and selecting Change
. A Visual Studio dialog will open up. Select Modify
from the set of buttons at the bottom and the above dialog will appear.
If I'm reading your question right, you want to run a script in the post build actions part of the build.
I myself use PostBuildScript Plugin for running git clean -fxd
after the build has archived artifacts and published test results. My Jenkins slaves have SSD disks, so I do not have the room keep generated files in the workspace.
I had the same problem and this worked:
sudo modprobe ip_tables
sudo echo 'ip_tables' >> /etc/modules
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
The easiest way to solve is the to recognize that in javascript dates are just numbers. It starts 0
or 'Wed Dec 31 1969 18:00:00 GMT-0600 (CST)
. Every 1
represents a millisecond. You can add or subtract milliseconds by getting the value and instantiating a new date using that value. You can manage it pretty easy with that mind.
const minutesToAdjust = 10;
const millisecondsPerMinute = 60000;
const originalDate = new Date('11/20/2017 10:00 AM');
const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));
console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)
You can use jsoup
to parse any kind of web page. Here you can find the jsoup library and full source code.
Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html
To install in Eclipse:
You can parse according to tag/parent/child very comfortably
You need to wrap the table inside another element and set the height of that element. Example with inline css:
<div style="height: 500px; overflow: auto;">
<table>
</table>
</div>
To explain the two concepts by example, imagine you have an order entry system for a bookstore. The mapping of orders to items is many to many (n:m) because each order can have multiple items, and each item can be ordered by multiple orders. On the other hand, a lookup between customers and order is one to many (1:n) because a customer can place more than one order, but an order is never for more than one customer.
You can use reduce method as bellow; If you change the 0(zero) to 1 or other numbers, it will add it to total number. For example, this example gives the total number as 31 however if we change 0 to 1, total number will be 32.
const batteryBatches = [4, 5, 3, 4, 4, 6, 5];
let totalBatteries= batteryBatches.reduce((acc,val) => acc + val ,0)
in case if your table has tbody
let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)
I had the same problem when I submitted data using jQuery AJAX:
$.ajax({
url:...
success:function(data){
//server response's data is JSON
//I use jQuery's parseJSON method
$.parseJSON(data);//it's ERROR
}
});
If the response is JSON, and you use this method, the data you get is a JavaScript object, but if you use dataType:"text"
, data is a JSON string. Then the use of $.parseJSON
is okay.
In SQL Server 2012+, you can use datefromparts()
:
select datefromparts(@year, @month, @day)
In earlier versions, you can cast a string. Here is one method:
select cast(cast(@year*10000 + @month*100 + @day as varchar(255)) as date)
You can do it without having to create a real Hibernate mapping. Try this:
SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team
JQUERY INR v1.2
A simple jQuery plug-in for convert Rs. to standard Indian rupee symbol through out the web page. Simple to use and simple instillation
The Indian Rupee sign is the currency sign: ? for the Indian Rupee, the official currency of India. Designed by D. Udaya Kumar, it was presented to the public by the Government of India on 15 July 2010,[1] following its selection through an “open” competition among Indian residents. Before its adoption, the most commonly used symbols for the rupee were Rs, Re or, if the text was in an Indian language, an appropriate abbreviation in that language. The new sign relates solely to the Indian rupee; other countries that use a rupee, such as Sri Lanka, Pakistan and Nepal, still use the generic U+20A8 ? rupee sign character. The design resembles both the Devanagari letter "?" (ra) and the Latin capital letter "R", with a double horizontal line at the top.
Instillation:
Include jQuery min and jQuery Ui to your page first
eg: NB: use jQuery stable version only
include the “indianRupee_v1.2.js” and “indianRupee_ctrl.js” after the jQuery library eg:
Use Span tag to wrap Rs through out the web it will replace with the symbol eg: Rs 1280000/-
Source:
Pay Him Rs 1280000/-
Pay Him Rs 528500/-
Pay Him Rs 1250/-
Result:
http://romy.theqtl.com/rupeePlugin/
Plug-in Options:
$("body").indianRupee({ targets:"span",// use as default we can also use [p, div, h1 , li etc...] vector:"on"//[on/off] of [true/false] NB: {vector not support in Internet Explore } });
Biginteger
is an immutable class.
You need to explicitly assign value of your output to sum like this:
sum = sum.add(BigInteger.valueof(i));
It is very easy.
First create a connection , lets name it, con
.
Then run the following code.
get_column_names=con.execute("select * from table_name limit 1")
col_name=[i[0] for i in get_column_names.description]
print(col_name)
You will get column name as a list
under etc/apache2/apache2.conf
, you can find one or more blocks that describe the server directories and permissions
As an example, this is the default configuration
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
you can replicate this but change the directory path /var/www/
with the new directory.
Finally, you need to restart the apache server, you can do that from a terminal with the command: sudo service apache2 restart
UINavigationItem* item = [[UINavigationItem alloc] initWithTitle:@"title text"];
...
[bar pushNavigationItem:item animated:YES];
[item release];
This code worked.
Were I you I would do something like this:
Before doing anything please keep a copy (better safe than sorry)
git checkout master
git checkout -b temp
git reset --hard <sha-1 of your first commit>
git add .
git commit -m 'Squash all commits in single one'
git push origin temp
After doing that you can delete other branches.
Result: You are going to have a branch with only 2 commits.
Use
git log --oneline
to see your commits in a minimalistic way and to find SHA-1 for commits!
Yes. The VBA equivalent of AltEnter is to use a linebreak character:
ActiveCell.Value = "I am a " & Chr(10) & "test"
Note that this automatically sets WrapText
to True.
Proof:
Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub
Also the $wshell = New-Object -ComObject wscript.shell;
helped a script that was running in the background, it worked fine with just but adding $wshell
. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")
The solution, if your list items can be display: inline
is quite easy:
#footer { text-align: center; }
#footer ul { list-style: none; }
#footer ul li { display: inline; }
However, many times you must use display:block
on your <li>
s. The following CSS will work, in this case:
#footer { width: 100%; overflow: hidden; }
#footer ul { list-style: none; position: relative; float: left; display: block; left: 50%; }
#footer ul li { position: relative; float: left; display: block; right: 50%; }
Less code is better code.
[NSThread sleepForTimeInterval:0.06];
Swift:
Thread.sleep(forTimeInterval: 0.06)
If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name
That will show you STDOUT and STDERR.
I also suggest using contourf(Z)
. For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.
So in my case, I prefer to use jucestain's answer. The default shading faceted
of pcolor()
is more suitable.
However, pcolor()
does not use the last row and column of the plotted matrix. For this, I used the padarray()
function:
pcolor(padarray(Z,[1 1],0,'post'))
Sorry if that is not really related to the original post
If you are interested to detect simple IR light blob through haar cascade, it will be very odd to do. Because simple IR blob does not have enough features to be trained through opencv like other objects (face, eyes,nose etc). Because IR is just a simple light having only one feature of brightness in my point of view. But if you want to learn how to train a classifier following link will help you alot.
http://note.sonots.com/SciSoftware/haartraining.html
And if you just want to detect IR blob, then you have two more possibilities, one is you go for DIP algorithms to detect bright region and the other one which I recommend you is you can use an IR cam which just pass the IR blob and you can detect easily the IR blob by using opencv blob functiuons. If you think an IR cam is expansive, you can make simple webcam to an IR cam by removing IR blocker (if any) and add visible light blocker i.e negative film, floppy material or any other. You can check the following link to convert simple webcam to IR cam.
http://www.metacafe.com/watch/385098/transform_your_webcam_into_an_infrared_cam/
You have already got sufficient answer for your question. But may be my answer help you more about |=
kind of binary operators.
I am writing table for bitwise operators:
Following are valid:
----------------------------------------------------------------------------------------
Operator Description Example
----------------------------------------------------------------------------------------
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
----------------------------------------------------------------------------------------
note all operators are binary operators.
Also Note: (for below points I wanted to add my answer)
>>>
is bitwise operator in Java that is called Unsigned shift
but >>>= operator >>>=
not an operator in Java.
~
is bitwise complement bits, 0 to 1 and 1 to 0
(Unary operator) but ~=
not an operator.
Additionally, !
Called Logical NOT Operator, but !=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. e.g. (A != B) is true
. where as A=!B
means if B
is true
then A
become false
(and if B
is false
then A
become true
).
side note: |
is not called pipe, instead its called OR, pipe is shell terminology transfer one process out to next..
From CLI:
$ su - postgres
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q
PHP (as tested on localhost, it works as expected):
$connString = 'port=5432 dbname=test_database user=tester password=test_password';
$connHandler = pg_connect($connString);
echo 'Connected to '.pg_dbname($connHandler);
If you use Tomcat server I suggest you to put JSTL .jar file to the Tomcat lib folder. By doing this you will have an access to JSTL in all your web projects automatically (with taglib declaration in .jsp files of course).
With LINQ:
List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();
If you need foreach, then no need for ToList:
foreach (string s in l.Skip(1).Take(2)){}
Advantage of LINQ is that if you want to just skip some leading element,you can :
List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}
i.e. no need to take care of count/length, etc.
Make sure the php.ini that you're modifying is on the /etc/php5/apache2 folder, or else it won't have any efect...
people.OrderBy(person => person.lastname).ToList();
I suppose that have you noticed that your link is actually an HTTPS link.... It seems that CURL parameters do not include any kind of SSH handling... maybe this could be your problem. Why don't you try with a non-HTTPS link to see what happens (i.e Google Custom Search Engine)...?
echo $a | grep -bo cat | sed 's/:.*$//'
From the UIDevice
class:
As an example: [[UIDevice currentDevice] name];
The UIDevice is a class that provides information about the iPhone or iPod Touch device.
Some of the information provided by UIDevice is static, such as device name or system version.
source: http://servin.com/iphone/uidevice/iPhone-UIDevice.html
Offical Documentation: Apple Developer Documentation > UIDevice
Class Reference
For your particular case you could also use Array#join
when constructing file path type of string:
string = [ROOT_DIR, project, 'App.config'].join('/')]
This has a pleasant side effect of automatically converting different types to string:
['foo', :bar, 1].join('/')
=>"foo/bar/1"
By the way, in Notepad++ there's built-in plugin that can handle this:
TextFX -> TextFX Edit -> Delete Blank Lines
(first press CTRL+A to select all).
This works for me:
class MyClass {
static MyEnum: { Value1; Value2; Value3; }
= {
Value1: "Value1",
Value2: "Value2",
Value3: "Value3"
};
}
or
module MyModule {
export var MyEnum: { Value1; Value2; Value3; }
= {
Value1: "Value1",
Value2: "Value2",
Value3: "Value3"
};
}
8)
Update: Shortly after posting this I discovered another way, but forgot to post an update (however, someone already did mentioned it above):
enum MyEnum {
value1 = <any>"value1 ",
value2 = <any>"value2 ",
value3 = <any>"value3 "
}
Use assets like a filesystem to dump any kind of files. And use res to store what it is made for, layouts, images, values.
If you need to convert the instance of System.Xml.Linq.XDocument into the instance of the System.Xml.XmlDocument this extension method will help you to do not lose the XML declaration in the resulting XmlDocument instance:
using System.Xml;
using System.Xml.Linq;
namespace www.dimaka.com
{
internal static class LinqHelper
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var reader = xDocument.CreateReader())
{
xmlDocument.Load(reader);
}
var xDeclaration = xDocument.Declaration;
if (xDeclaration != null)
{
var xmlDeclaration = xmlDocument.CreateXmlDeclaration(
xDeclaration.Version,
xDeclaration.Encoding,
xDeclaration.Standalone);
xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild);
}
return xmlDocument;
}
}
}
Hope that helps!
Center x = x + 1/2 of width
Center y = y + 1/2 of height
If you know the width and height already then you only need one set of coordinates.
The CSS solutions don't appear to be widely available as of mid-2013. Instead...
Nicholas Zakas explains that Modernizr applies a no-touch
CSS class when the browser doesn’t support touch.
Or detect in JavaScript with a simple piece of code, allowing you to implement your own Modernizr-like solution:
<script>
document.documentElement.className +=
(("ontouchstart" in document.documentElement) ? ' touch' : ' no-touch');
</script>
Then you can write your CSS as:
.no-touch .myClass {
...
}
.touch .myClass {
...
}
Try Like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
function index(){
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
}
}
?>
I normally use this statement:
ALTER TABLE `table_name`
CHANGE COLUMN `col_name` `col_name` VARCHAR(10000);
But, I think SET will work too, never have tried it. :)
There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.
I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).
When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.
I got this after upgrading to 0.2.7 from 0.2.5. Deleted all *.iml, .idea folders and restart IDE then re-import settings.gradle worked for me
IIS 6.0 and previous versions :
ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.
This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.
Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.
The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests
What's a SCRIPT MAP ?
Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed
A good example can be seen here
IIS 7 and above
IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.
IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )
What this means is that IIS 7 processes requests that arrive for any content type, with both NON ASP.NET Modules / native IIS modules
and ASP.NET modules
providing request processing in all stages This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.
IHttpModule
) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.IHttpHandler
)I thought this answer might be helpful to others having multiple versions of python and wants to use pipenv to create virtual environment.
py -[python version] pip install pipenv
, example: py -3.6 pip install pipenv
pipenv --python [version]
to create the virtual environment in the version of the python you desire. example: pipenv --python 3.6
pipenv shell
to activate your virtual environment.When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent
example:
22 = 1 << 2
= (int) Math.pow(2, 2)
210 = 1 << 10
= (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead
232 = 1L << 32
= (long) Math.pow(2, 32)
btw. in Kotlin you have shl
instead of <<
so
(java) 1L << 32
= 1L shl 32
(kotlin)
Thats work for me:
var jsScripts = [];
jsScripts.push("/js/script1.js" );
jsScripts.push("/js/script2.js" );
jsScripts.push("/js/script3.js" );
$(jsScripts).each(function( index, value ) {
$.holdReady( true );
$.getScript( value ).done(function(script, status) {
console.log('Loaded ' + index + ' : ' + value + ' (' + status + ')');
$.holdReady( false );
});
});
These files are from Maven wrapper. It works similarly to the Gradle wrapper.
This allows you to run the Maven project without having Maven installed and present on the path. It downloads the correct Maven version if it's not found (as far as I know by default in your user home directory).
The mvnw
file is for Linux (bash) and the mvnw.cmd
is for the Windows environment.
To create or update all necessary Maven Wrapper files execute the following command:
mvn -N io.takari:maven:wrapper
To use a different version of maven you can specify the version as follows:
mvn -N io.takari:maven:wrapper -Dmaven=3.3.3
Both commands require maven on PATH
(add the path to maven bin
to Path
on System Variables) if you already have mvnw in your project you can use ./mvnw
instead of mvn
in the commands.
You might want to try this example for version 2.6 of Python.
def my_print(text, begin, end):
"Print text in UPPER between 'begin' and 'end' in lower."
for obj in (text, begin, end):
assert isinstance(obj, str), 'Argument of wrong type!'
print begin.lower() + text.upper() + end.lower()
However, have you considered letting the function fail naturally instead?
Easy. Use .shape
.
>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.
In my case it was my ADBLOCKER! For some reason it was enabled on my localhost and causing this error in Firefox.
Disabling it or uninstalling the plugin should fix this.
In your case, it may not be an adblocker but another Firefox plugin. Test it out in incognito first with no plugins to determine if that is the issue and then systematically disable the plugins until you find the culprit.
To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):
import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"
evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)
in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script
. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.
Map
does not supports duplicate keys. you can use collection as value against same key.
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.
you can use any kind of List
or Set
implementation according to your requirement.
If your values might be also duplicate you can go with ArrayList
or LinkedList
, in case values are unique you can use HashSet
or TreeSet
etc.
Also In google guava collection library Multimap
is available, it is a collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:
a ? 1, 2
b ? 3
Example -
ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a", "1");
multimap.put("a", "2");
multimap.put("c", "3");
Handling key events consistently is not at all easy.
Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress
event. Do not try to get character codes for keyup
and keydown
events.
Secondly, you get different sets of values in a keypress
event to what you get in a keyup
or keydown
event.
I recommend this page as a useful resource. As a summary:
If you're interested in detecting a user typing a character, use the keypress
event. IE bizarrely only stores the character code in keyCode
while all other browsers store it in which
. Some (but not all) browsers also store it in charCode
and/or keyCode
. An example keypress handler:
function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
}
If you're interested in detecting a non-printable key (such as a cursor key), use the keydown
event. Here keyCode
is always the property to use. Note that keyup
events have the same properties.
function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
// Check for left arrow key
if (keyCode == 37) {
alert("Left arrow");
}
}
Try putting single quotes around the data source:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb';
The problem tends to be white space which does have meaning to the parser.
If you had other attributes (e.g., Extended Properties), their values may also have to be enclosed in single quotes:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb'; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';
You could equally well use double quotes; however, you'll probably have to escape them, and I find that more of a Pain In The Algorithm than using singles.
To be able to use std::unordered_map
(or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
A hash function; this must be a class that overrides operator()
and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash
template for your key-type.
A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator()
, or as a specialization of std::equal
, or – easiest of all – by overloading operator==()
for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
With this in place, you can instantiate a std::unordered_map
for the key-type:
int main()
{
std::unordered_map<Key,std::string> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
It will automatically use std::hash<Key>
as defined above for the hash value calculations, and the operator==
defined as member function of Key
for equality checks.
If you don't want to specialize template inside the std
namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
int main()
{
std::unordered_map<Key,std::string,KeyHasher> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value
and hash_combine
function template from the Boost library. The former acts in a similar way as std::hash
for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include <boost/functional/hash.hpp>
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(k.first));
hash_combine(seed,hash_value(k.second));
hash_combine(seed,hash_value(k.third));
// Return the result.
return seed;
}
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
template <>
struct hash<Key>
{
size_t operator()( const Key& k ) const
{
// Compute individual hash values for first, second and third
// http://stackoverflow.com/a/1646913/126995
size_t res = 17;
res = res * 31 + hash<string>()( k.first );
res = res * 31 + hash<string>()( k.second );
res = res * 31 + hash<int>()( k.third );
return res;
}
};
}
Here is a quick start to get the gears turning...
ParkingLot is a class.
ParkingSpace is a class.
ParkingSpace has an Entrance.
Entrance has a location or more specifically, distance from Entrance.
ParkingLotSign is a class.
ParkingLot has a ParkingLotSign.
ParkingLot has a finite number of ParkingSpaces.
HandicappedParkingSpace is a subclass of ParkingSpace.
RegularParkingSpace is a subclass of ParkingSpace.
CompactParkingSpace is a subclass of ParkingSpace.
ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.
ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()
Parker is a class.
Parker can Park().
Parker can Unpark().
Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.
Parker has a ParkingSpace.
Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().
Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().
HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)
In this solution, it is possible that Parker should be renamed to be Car.
I had this problem when running MSTest. I could not get it to work without the "noisolation" flag.
Hopefully this helps someone. Cost me a lot of time to figure that out. Everything ran fine from the IDE. Something weird about the Entity Framework in this context.
Using pure Javascript:
Don't need to pass this
to the SomeDeleteRowFunction()
:
<td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction()"></td>
The onclick function:
function SomeDeleteRowFunction() {
// event.target will be the input element.
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
}
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedUse the following code:
import numpy as np
myArray=np.array([1,2,4]) #func used to convert [1,2,3] list into an array
print(myArray)
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
(1) UPDATE 2019: ES7 Version
class Singleton {
static instance;
constructor() {
if (instance) {
return instance;
}
this.instance = this;
}
foo() {
// ...
}
}
console.log(new Singleton() === new Singleton());
(2) ES6 Version
class Singleton {
constructor() {
const instance = this.constructor.instance;
if (instance) {
return instance;
}
this.constructor.instance = this;
}
foo() {
// ...
}
}
console.log(new Singleton() === new Singleton());
Best solution found: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern
function MySingletonClass () {
if (arguments.callee._singletonInstance) {
return arguments.callee._singletonInstance;
}
arguments.callee._singletonInstance = this;
this.Foo = function () {
// ...
};
}
var a = new MySingletonClass();
var b = MySingletonClass();
console.log( a === b ); // prints: true
For those who want the strict version:
(function (global) {
"use strict";
var MySingletonClass = function () {
if (MySingletonClass.prototype._singletonInstance) {
return MySingletonClass.prototype._singletonInstance;
}
MySingletonClass.prototype._singletonInstance = this;
this.Foo = function() {
// ...
};
};
var a = new MySingletonClass();
var b = MySingletonClass();
global.result = a === b;
} (window));
console.log(result);
You can't use a filename like iexplore
by itself because the path to internet explorer isn't listed in the PATH
environment variable for the system or user.
However any path entered into the PATH
environment variable allows you to use just the file name to execute it.
System32
isn't special in this regard as any directory can be added to the PATH
variable. Each path is simply delimited by a semi-colon.
For example I have c:\ffmpeg\bin\
and c:\nmap\bin\
in my path environment variable, so I can do things like new ProcessStartInfo("nmap", "-foo")
or new ProcessStartInfo("ffplay", "-bar")
The actual PATH
variable looks like this on my machine.
%SystemRoot%\system32;C:\FFPlay\bin;C:\nmap\bin;
As you can see you can use other system variables
, such as %SystemRoot%
to build and construct paths in the environment variable.
So - if you add a path like "%PROGRAMFILES%\Internet Explorer;" to your PATH
variable you will be able to use ProcessStartInfo("iexplore");
If you don't want to alter your PATH
then simply use a system variable such as %PROGRAMFILES%
or %SystemRoot%
and then expand it when needed in code. i.e.
string path = Environment.ExpandEnvironmentVariables(
@"%PROGRAMFILES%\Internet Explorer\iexplore.exe");
var info = new ProcessStartInfo(path);
The listed return type of the method is Task<string>
. You're trying to return a string
. They are not the same, nor is there an implicit conversion from string to Task<string>
, hence the error.
You're likely confusing this with an async
method in which the return value is automatically wrapped in a Task
by the compiler. Currently that method is not an async method. You almost certainly meant to do this:
private async Task<string> methodAsync()
{
await Task.Delay(10000);
return "Hello";
}
There are two key changes. First, the method is marked as async
, which means the return type is wrapped in a Task
, making the method compile. Next, we don't want to do a blocking wait. As a general rule, when using the await
model always avoid blocking waits when you can. Task.Delay
is a task that will be completed after the specified number of milliseconds. By await
-ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).
If you prefer a 4.0 way of doing it, without using await
, you can do this:
private Task<string> methodAsync()
{
return Task.Delay(10000)
.ContinueWith(t => "Hello");
}
The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await
we aren't leveraging here.
If your Thread.Sleep(10000)
is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context. The easiest way of doing that is through Task.Run
:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
SomeLongRunningMethod();
return "Hello";
});
}
Or more likely:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
return SomeLongRunningMethodThatReturnsAString();
});
}
just posting in case anyone else has the same error...
I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.
The solution was to make the function asynchronous
function functionName(args) {}
becomes
async function functionName(args) {}
Try the format as dd-mon-yyyy, For example 02-08-2016 should be in the format '08-feb-2016'.
Connection object is for illustration only. The DataAdapter is the key bit:
Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
It is work for me without any errors:
this.dataGridView2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.dataGridView2.Click += new System.EventHandler(this.DeleteRow_Click);
And this
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var hti = dataGridView2.HitTest(e.X, e.Y);
dataGridView2.ClearSelection();
dataGridView2.Rows[hti.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
Int32 rowToDelete = dataGridView2.Rows.GetFirstRow(DataGridViewElementStates.Selected);
if (rowToDelete == -1) { }
else
{
dataGridView2.Rows.RemoveAt(rowToDelete);
dataGridView2.ClearSelection();
}
}
@Arnon Rotem-Gal-Oz answer is right for the most part. But I would like to point out the difference between df['year']=df['year'].astype(int)
and df.year.astype(int)
. df.year.astype(int)
returns a view of the dataframe and doesn't not explicitly change the type, atleast in pandas 0.24.2. df['year']=df['year'].astype(int)
explicitly change the type because it's an assignment. I would argue that this is the safest way to permanently change the dtype of a column.
Example:
df = pd.DataFrame({'Weed': ['green crack', 'northern lights', 'girl scout
cookies'], 'Qty':[10,15,3]})
df.dtypes
Weed object, Qty int64
df['Qty'].astype(str)
df.dtypes
Weed object, Qty int64
Even setting the inplace arg to True doesn't help at times. I don't know why this happens though. In most cases inplace=True equals an explicit assignment.
df['Qty'].astype(str, inplace = True)
df.dtypes
Weed object, Qty int64
Now the assignment,
df['Qty'] = df['Qty'].astype(str)
df.dtypes
Weed object, Qty object
It's not immediately obvious from the documentation why the following does not work:
<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>
But when doing it entirely inline:
"em"
class
is className
The correct way looks like this:
<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>
In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server
Thirding TagLib Sharp.
TagLib.File f = TagLib.File.Create(path);
f.Tag.Album = "New Album Title";
f.Save();
This produces them one-at-time without making a list - the same end result as Marios Choudary's answer (or simply calling C++'s nextPermute, as Anders answer notes). But this is Heap's algorithm (the non-recursive version) re-arranged and a class to save context. Used as:
P5=new genPermutes_t(5); // P5.P is now [0,1,2,3,4]
while(!P5.isDone()) {
// use P5.P here
P5.next();
}
Code is in C# without being an endorsement. Variables are as-is from Heap's pseudocode, to which the comments also refer:
public class genPermutes_t {
public int[] P; // the current permuation
private int n, i; // vars from the original algorithm
private int[] c; // ditto
public genPermutes_t(int count) {
// init algorithm:
n=count;
i=0;
c=new int[n];
for(int j=0;j<n;j++) c[j]=0;
// start current permutation as 0,1 ... n-1:
P=new int[n];
for(int j=0;j<n;j++) P[j]=j;
}
public bool isDone() {
return i>=n; // condition on the original while loop
}
public void next() {
// the part of the loop that spins until done or ready for next permute:
while(i<n && c[i]>=i) {
c[i]=0;
i++;
}
// pulled from inside loop -- the part that makes next permute:
if(i<n) { // if not done
if(i%2==0) swap(0,i);
else swap(c[i], i);
// "print P" removed. User will simply examine it
c[i]+=1;
i=0;
}
}
private void swap(int i1, int i2) {int tmp=P[i1]; P[i1]=P[i2]; P[i2]=tmp;}
}
Kotlin Native:
memScoped {
val q = alloc<utsname>()
uname(q.ptr)
val identifier = NSString.stringWithCString(q.machine, encoding = NSUTF8StringEncoding)
}
I have written a piece of code that transforms a XML content into a multi-layer structure of maps:
public static Object convertNodesFromXml(String xml) throws Exception {
InputStream is = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(is);
return createMap(document.getDocumentElement());
}
public static Object createMap(Node node) {
Map<String, Object> map = new HashMap<String, Object>();
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
String name = currentNode.getNodeName();
Object value = null;
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
value = createMap(currentNode);
}
else if (currentNode.getNodeType() == Node.TEXT_NODE) {
return currentNode.getTextContent();
}
if (map.containsKey(name)) {
Object os = map.get(name);
if (os instanceof List) {
((List<Object>)os).add(value);
}
else {
List<Object> objs = new LinkedList<Object>();
objs.add(os);
objs.add(value);
map.put(name, objs);
}
}
else {
map.put(name, value);
}
}
return map;
}
This code transforms this:
<house>
<door>blue</door>
<living-room>
<table>wood</table>
<chair>wood</chair>
</living-room>
</house>
into
{
"house": {
"door": "blue",
"living-room": {
"table": "wood",
"chair": "wood"
}
}
}
I don't have the inverse process, but that must not be very difficult to write.
You can only return one value in Java, so the neatest way is like this:
return new Pair<Integer>(number1, number2);
Here's an updated version of your code:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
private final T m_first;
private final T m_second;
public Pair(T first, T second) {
m_first = first;
m_second = second;
}
public T first() {
return m_first;
}
public T second() {
return m_second;
}
}
Using Glide library:
Glide.with(context)
.load(new File(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
ECMAScript 2021 brings Object.fromEntries
which does exactly the requirement:
const array = [ [ 'cardType', 'iDEBIT' ],
[ 'txnAmount', '17.64' ],
[ 'txnId', '20181' ],
[ 'txnType', 'Purchase' ],
[ 'txnDate', '2015/08/13 21:50:04' ],
[ 'respCode', '0' ],
[ 'isoCode', '0' ],
[ 'authCode', '' ],
[ 'acquirerInvoice', '0' ],
[ 'message', '' ],
[ 'isComplete', 'true' ],
[ 'isTimeout', 'false' ] ];
const obj = Object.fromEntries(array);
console.log(obj);
_x000D_
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
This will do it:
const array = [ [ 'cardType', 'iDEBIT' ],
[ 'txnAmount', '17.64' ],
[ 'txnId', '20181' ],
[ 'txnType', 'Purchase' ],
[ 'txnDate', '2015/08/13 21:50:04' ],
[ 'respCode', '0' ],
[ 'isoCode', '0' ],
[ 'authCode', '' ],
[ 'acquirerInvoice', '0' ],
[ 'message', '' ],
[ 'isComplete', 'true' ],
[ 'isTimeout', 'false' ] ];
var obj = {};
array.forEach(function(data){
obj[data[0]] = data[1]
});
console.log(obj);
_x000D_
(not enough reputation to comment)
This is BUGGY:
ls -1q some_pattern | wc -l
If shopt -s nullglob
happens to be set, it prints the number of ALL regular files, not just the ones with the pattern (tested on CentOS-8 and Cygwin). Who knows what other meaningless bugs does ls
have?
This is CORRECT and much faster:
shopt -s nullglob; files=(some_pattern); echo ${#files[@]};
It does the expected job.
0.006
on CentOS, and 0.083
on Cygwin (in case it is used with care).
0.000
on CentOS, and 0.003
on Cygwin.
I was searching for a similar functionality and I saw the data "http://download.geonames.org/export/dump/" shared on earlier reply (thank you for sharing, it is an excellent source), and implemented a service based on the cities1000.txt data.
You can see it running at
http://scatter-otl.rhcloud.com/location?lat=36&long=-78.9 (broken link)
Just change the latitude and longitude for your locations.
It is deployed on OpenShift (RedHat Platform). First call after a long idle period may take sometime, but usually performance is satisfactory. Feel free to use this service as you like...
Also, you can find the project source at https://github.com/turgos/Location.
As of Json.NET 4.0 Release 1, there is native dynamic support:
[Test]
public void DynamicDeserialization()
{
dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
jsonResponse.Works = true;
Console.WriteLine(jsonResponse.message); // Hi
Console.WriteLine(jsonResponse.Works); // True
Console.WriteLine(JsonConvert.SerializeObject(jsonResponse)); // {"message":"Hi","Works":true}
Assert.That(jsonResponse, Is.InstanceOf<dynamic>());
Assert.That(jsonResponse, Is.TypeOf<JObject>());
}
And, of course, the best way to get the current version is via NuGet.
Updated (11/12/2014) to address comments:
This works perfectly fine. If you inspect the type in the debugger you will see that the value is, in fact, dynamic. The underlying type is a JObject
. If you want to control the type (like specifying ExpandoObject
, then do so.
I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.
static final int COMPARE_EARLIEST = 0;
static final int COMPARE_MOST_RECENT = 1;
public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) {
LocalDate refDate = null;
switch(comparatorType)
{
case COMPARE_EARLIEST:
//returns the most earliest of the date entries
refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item ->
item.toDateTimeAtCurrentTime())).get();
break;
case COMPARE_MOST_RECENT:
//returns the most recent of the date entries
refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item ->
item.toDateTimeAtCurrentTime())).get();
break;
}
return refDate;
}
If you're dealing with a response from an AJAX (or XMLHttpRequest) call, what worked for me is to check the response content type and parse or not the content accordingly.
Dont get confusion : simply remember
Use git clone
with the --depth
option set to 1
to create a shallow clone with a history truncated to the latest commit.
For example:
git clone --depth 1 https://github.com/user/repo.git
To also initialize and update any nested submodules, also pass --recurse-submodules
and to clone them shallowly, also pass --shallow-submodules
.
For example:
git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git
Print the PDF header (using header() function) like:
header("Content-type: application/pdf");
and then just echo the content of the PDF file you created (instead of writing it to disk).
function listAllItems(){
for (i=0; i<localStorage.length; i++)
{
key = localStorage.key(i);
alert(localStorage.getItem(key));
}
}
You can tell EF which properties have to be updated in this way:
public void ChangePassword(int userId, string password)
{
var user = new User { Id = userId, Password = password };
using (var context = new ObjectContext(ConnectionString))
{
var users = context.CreateObjectSet<User>();
users.Attach(user);
context.ObjectStateManager.GetObjectStateEntry(user)
.SetModifiedProperty("Password");
context.SaveChanges();
}
}
You're on a 32-bit machine or a 64-bit Windows machine. On my 64-bit machine (running a Unix-derivative O/S, not Windows), sizeof(int) == 4
, but sizeof(long) == 8
.
They're different types — sometimes the same size as each other, sometimes not.
(In the really old days, sizeof(int) == 2
and sizeof(long) == 4
— though that might have been the days before C++ existed, come to think of it. Still, technically, it is a legitimate configuration, albeit unusual outside of the embedded space, and quite possibly unusual even in the embedded space.)
You can also use the special word like
:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
Recursively
const toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => {_x000D_
if (d instanceof Object) {_x000D_
Object.keys(d).forEach(k => {_x000D_
const v = d[k]_x000D_
if (pk) k = `${pk}[${k}]`_x000D_
if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) {_x000D_
return f(fd)(k)(v)_x000D_
} else {_x000D_
fd.append(k, v)_x000D_
}_x000D_
})_x000D_
}_x000D_
return fd_x000D_
})(new FormData())()_x000D_
_x000D_
let data = {_x000D_
name: 'John',_x000D_
age: 30,_x000D_
colors: ['red', 'green', 'blue'],_x000D_
children: [_x000D_
{ name: 'Max', age: 3 },_x000D_
{ name: 'Madonna', age: 10 }_x000D_
]_x000D_
}_x000D_
console.log('data', data)_x000D_
document.getElementById("data").insertAdjacentHTML('beforeend', JSON.stringify(data))_x000D_
_x000D_
let formData = toFormData(data)_x000D_
_x000D_
for (let key of formData.keys()) {_x000D_
console.log(key, formData.getAll(key).join(','))_x000D_
document.getElementById("item").insertAdjacentHTML('beforeend', `<li>${key} = ${formData.getAll(key).join(',')}</li>`)_x000D_
}
_x000D_
<p id="data"></p>_x000D_
<ul id="item"></ul>
_x000D_
You need both getText() - which returns an Editable and toString() - to convert that to a String for matching.
So instead of: passw1.toString().equalsIgnoreCase("1234")
you need passw1.getText().toString().equalsIgnoreCase("1234")
.
If you want the timestamp for yesterday try something like:
(CURRENT_TIMESTAMP - INTERVAL '1' DAY)
My StreamEx library extends the functionality of Stream API. In particular it offers methods like append and prepend which solve this issue (internally they use concat
). These methods can accept either another stream or collection or varargs array. Using my library your problem can be solved this way (note that x != 0
look strange for non-primitive stream):
Stream<Integer> stream = StreamEx.of(stream1)
.filter(x -> !x.equals(0))
.append(stream2)
.filter(x -> !x.equals(1))
.append(element)
.filter(x -> !x.equals(2));
By the way there's also a shortcut for your filter
operation:
Stream<Integer> stream = StreamEx.of(stream1).without(0)
.append(stream2).without(1)
.append(element).without(2);
Here is an example of one of our stored procedures that executes multiple stored procedures within it:
ALTER PROCEDURE [dbo].[AssetLibrary_AssetDelete]
(
@AssetID AS uniqueidentifier
)
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
EXEC AssetLibrary_AssetDeleteAttributes @AssetID
EXEC AssetLibrary_AssetDeleteComponents @AssetID
EXEC AssetLibrary_AssetDeleteAgreements @AssetID
EXEC AssetLibrary_AssetDeleteMaintenance @AssetID
DELETE FROM
AssetLibrary_Asset
WHERE
AssetLibrary_Asset.AssetID = @AssetID
RETURN (@@ERROR)
One thing json
cannot do is dict
indexed with numerals. The following snippet
import json
dictionary = dict({0:0, 1:5, 2:10})
serialized = json.dumps(dictionary)
unpacked = json.loads(serialized)
print(unpacked[0])
will throw
KeyError: 0
Because keys are converted to strings. cPickle
preserves the numeric type and the unpacked dict
can be used right away.
-- I like this as the data type and the format remains consistent with a date time data type
;with cte as(
select
cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
from dbo.mytable cd
where utcdate between '2014-01-14' and '2014-01-15'
group by
cast(utcdate as date), DATEPART(hour, utcdate)
)
select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
from cte
The stored procedure sp_columns returns detailed table information.
exec sp_columns MyTable
You can do this using jQuery:
This method gets a list of its children then counts the length of that list, as simple as that.
$("ul").find("*").length;
The find() method traverses DOM downwards along descendants, all the way down to the last descendant.
Note: children() method traverses a single level down the DOM tree.
Alternative syntax using the -Not
operator and depending on your preference for readability:
if( -Not (Test-Path -Path $TARGETDIR ) )
{
New-Item -ItemType directory -Path $TARGETDIR
}
If your collection type is a List<stuff>
, then the best approach is probably the following:
prods.RemoveAll(s => s.ID == 1)
This only does one pass (iteration) over the list, so should be more efficient than other methods.
If your type is more generically an ICollection<T>
, it might help to write a short extension method if you care about performance. If not, then you'd probably get away with using LINQ (calling Where
or Single
).
This seems to me to be what the question is after, no need for formatters:
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
A jsfiddle for custom tooltip pattern is Here
It is based on CSS Positioning and pseduo class selectors
Check MDN docs for cross-browser support of pseudo classes
<!-- HTML -->
<p>
<a href="http://www.google.com/" class="tooltip">
I am a
<span> (This website rocks) </span></a> a developer.
</p>
/*CSS*/
a.tooltip {
position: relative;
}
a.tooltip span {
display: none;
}
a.tooltip:hover span, a.tooltip:focus span {
display:block;
position:absolute;
top:1em;
left:1.5em;
padding: 0.2em 0.6em;
border:1px solid #996633;
background-color:#FFFF66;
color:#000;
}
You could also use wp_list_categories();
wp_list_categories( array('taxonomy' => 'product_cat', 'title_li' => '') );
When you ran
mysql -u bill -p
and got this error
ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)
mysqld is expecting you to connect as bill@localhost
Try creating bill@localhost
CREATE USER bill@localhost IDENTIFIED BY 'passpass';
grant all privileges on *.* to bill@localhost with grant option;
If you want to connect remotely, you must specify either the DNS name, the public IP, or 127.0.0.1 using TCP/IP:
mysql -u bill -p [email protected]
mysql -u bill -p -h10.1.2.30
mysql -u bill -p -h127.0.0.1 --protocol=TCP
Once you login, please run this
SELECT USER(),CURRENT_USER();
USER() reports how you attempted to authenticate in MySQL
CURRENT_USER() reports how you were allowed to authenticate in MySQL from the mysql.user table
This will give you a better view of how and why you were allowed to login to mysql. Why is this view important to know? It has to do with the user authentication ordering protocol.
Here is an example: I will create an anonymous user on my desktop MySQL
mysql> select user,host from mysql.user;
+---------+-----------+
| user | host |
+---------+-----------+
| lwdba | % |
| mywife | % |
| lwdba | 127.0.0.1 |
| root | 127.0.0.1 |
| lwdba | localhost |
| root | localhost |
| vanilla | localhost |
+---------+-----------+
7 rows in set (0.00 sec)
mysql> grant all on *.* to x@'%';
Query OK, 0 rows affected (0.02 sec)
mysql> select user,host from mysql.user;
+---------+-----------+
| user | host |
+---------+-----------+
| lwdba | % |
| mywife | % |
| x | % |
| lwdba | 127.0.0.1 |
| root | 127.0.0.1 |
| lwdba | localhost |
| root | localhost |
| vanilla | localhost |
+---------+-----------+
8 rows in set (0.00 sec)
mysql> update mysql.user set user='' where user='x';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
mysql> select user,host from mysql.user;
+---------+-----------+
| user | host |
+---------+-----------+
| | % |
| lwdba | % |
| mywife | % |
| lwdba | 127.0.0.1 |
| root | 127.0.0.1 |
| lwdba | localhost |
| root | localhost |
| vanilla | localhost |
+---------+-----------+
8 rows in set (0.00 sec)
mysql>
OK watch me login as anonymous user:
C:\MySQL_5.5.12>mysql -urol -Dtest -h127.0.0.1 --protocol=TCP
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.5.12-log MySQL Community Server (GPL)
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select user(),current_user();
+---------------+----------------+
| user() | current_user() |
+---------------+----------------+
| rol@localhost | @% |
+---------------+----------------+
1 row in set (0.00 sec)
mysql>
Authentication ordering is very strict. It checks from the most specific to the least. I wrote about this authentiation style in the DBA StackExchange.
Don't forget to explicitly call for TCP as the protocol for mysql client when necessary.
This works for me:
Console.OutputEncoding = System.Text.Encoding.Default;
To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:
Open Command Prompt;
Right click on the top bar of the Command Prompt;
Click Properties;
If the font is set to Raster Fonts, change it to Lucida Console.
This CsvEscape
function is XSLT 1.0 and escapes column values ,
, "
, and newlines like RFC 4180 or Excel. It makes use of the fact that you can recursively call XSLT templates:
EscapeQuotes
replaces all double quotes with 2 double quotes, recursively from the start of the string.CsvEscape
checks if the text contains a comma or double quote, and if so surrounds the whole string with a pair of double quotes and calls EscapeQuotes
for the string.Example usage: xsltproc xmltocsv.xslt file.xml > file.csv
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template name="EscapeQuotes">
<xsl:param name="value"/>
<xsl:choose>
<xsl:when test="contains($value,'"')">
<xsl:value-of select="substring-before($value,'"')"/>
<xsl:text>""</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="substring-after($value,'"')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="CsvEscape">
<xsl:param name="value"/>
<xsl:choose>
<xsl:when test="contains($value,',')">
<xsl:text>"</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:when>
<xsl:when test="contains($value,'
')">
<xsl:text>"</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:when>
<xsl:when test="contains($value,'"')">
<xsl:text>"</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="/">
<xsl:text>project,name,language,owner,state,startDate</xsl:text>
<xsl:text>
</xsl:text>
<xsl:for-each select="projects/project">
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(name)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(language)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(owner)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(state)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(startDate)"/></xsl:call-template>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Something like this (sounds like you just need to change your SMTP server):
String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
to_address[i] = new InternetAddress(to[i]);
i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {
message.addRecipient(Message.RecipientType.TO, to_address[i]);
i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
You have forgotten a *
between -3.7
and (prof[x])
.
Thus:
for x in range(len(prof)):
PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))
Also, there seems to be missing an (
as I count 6 times (
and 7 times )
, and I think (math.e, (0/2.25))
is missing a function call (probably math.pow
, but thats just a wild guess).
On Windows 10, I have docker installed. I am running Jnekins on a container and I encountered the same error message. Here is a step by step guide to resolve this issue:
Step 1: Open gitbash and run docker run -p 8080:8080 -p 50000:50000 jenkins.
Step 2: Open a new terminal.
Step 3: Do "docker ps" to get list of the running container. Copy the container id.
Step 4: Now if you do "docker exec -it {container id} sh" or "docker exec -it {container id} bash" you will get an error message similar to " the input device is not a TTY. If you are using mintty, try prefixing the command with 'winpty'"
Step 5: Run command " $winpty docker exec -it {container id} sh"
vola !! You are now inside the terminal.
I had trouble with the accepted answer (because I missed the HorizontalAlignment=Stretch portion and have adjusted the original answer).
This is another technique. It uses a Grid with a SharedSizeGroup.
Note: the Grid.IsSharedScope=true on the ListView.
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}" Grid.IsSharedSizeScope="True">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="40">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="IdColumn"/>
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Right" Text={Binding Path=Id}"/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
You can use strstream
. It's formally deprecated, but it's still a great tool if you need to work with C strings, i think.
char result[100]; // max size 100
std::ostrstream s(result, sizeof result - 1);
s << one << two << std::ends;
result[99] = '\0';
This will write one
and then two
into the stream, and append a terminating \0
using std::ends
. In case both strings could end up writing exactly 99
characters - so no space would be left writing \0
- we write one manually at the last position.
PreparedStatements are the way to go in most, but not all cases. Sometimes you will find yourself in a situation where a query, or a part of it, has to be built and stored as a string for later use. Check out the SQL Injection Prevention Cheat Sheet on the OWASP Site for more details and APIs in different programming languages.
Simple one-line answer to create a new dataframe with only numeric columns:
df.select_dtypes(include=np.number)
If you want the names of numeric columns:
df.select_dtypes(include=np.number).columns.tolist()
Complete code:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': range(7, 10),
'B': np.random.rand(3),
'C': ['foo','bar','baz'],
'D': ['who','what','when']})
df
# A B C D
# 0 7 0.704021 foo who
# 1 8 0.264025 bar what
# 2 9 0.230671 baz when
df_numerics_only = df.select_dtypes(include=np.number)
df_numerics_only
# A B
# 0 7 0.704021
# 1 8 0.264025
# 2 9 0.230671
colnames_numerics_only = df.select_dtypes(include=np.number).columns.tolist()
colnames_numerics_only
# ['A', 'B']
You can't delete on an array ! This should work better :
for (File f : files) f.delete();
But it won't work if the folders are not empty. For this cases, you will need to recursively descend into the folder hierarchy and delete everything. Yes it's a shame Java can't do that by default...
It is simple,for Example
-(void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(@"%s", __PRETTY_FUNCTION__);
}
Output: -[AppDelegate applicationWillEnterForeground:]
Use control
+option
+O
to auto-import the package or auto remove unused packages on MacOS
You can do the following:
String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList
<%= string_to_datetime("2011-05-19 10:30:14") %>
def string_to_datetime(string,format="%Y-%m-%d %H:%M:%S")
DateTime.strptime(string, format).to_time unless string.blank?
end
A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.
Please enter your username and password for
<realm name>
:
When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.
I assume that your style-sheet "style.css" is already located in the assets-folder
load the web-page with jsoup:
doc = Jsoup.connect("http://....").get();
remove links to external style-sheets:
// remove links to external style-sheets
doc.head().getElementsByTag("link").remove();
set link to local style-sheet:
// set link to local stylesheet
// <link rel="stylesheet" type="text/css" href="style.css" />
doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
make string from jsoup-doc/web-page:
String htmldata = doc.outerHtml();
display web-page in webview:
WebView webview = new WebView(this);
setContentView(webview);
webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
This will need new var ttfixed
Then this under the tt
value slot and replace all pointers down below that are tt
to ttfixed
ttfixed = (tt.replace(",", "."));
If you have a project created in Swift 4 and then added Objective-C files, do it like this:
@objcMembers
public class MyModel: NSObject {
var someFlag = false
func doSomething() {
print("doing something")
}
}
Reference: https://useyourloaf.com/blog/objc-warnings-upgrading-to-swift-4/
I love how this is explained in the article Cool performance features of EclipseLink 2.5
Indexing Foreign Keys
The first feature is auto indexing of foreign keys. Most people incorrectly assume that databases index foreign keys by default. Well, they don't. Primary keys are auto indexed, but foreign keys are not. This means any query based on the foreign key will be doing full table scans. This is any OneToMany, ManyToMany or ElementCollection relationship, as well as many OneToOne relationships, and most queries on any relationship involving joins or object comparisons. This can be a major perform issue, and you should always index your foreign keys fields.
Visit the site you want in Chrome. Click the Chrome menu in your browser toolbar.
Once you launch from that shortcut it will be a window without toolbar.
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
A quick fix would be something like this.
// Exploding the file based on the . operator
$file_ext = explode('.', $filename);
// Count taken (if more than one . exist; files like abc.fff.2013.pdf
$file_ext_count = count($file_ext);
// Minus 1 to make the offset correct
$cnt = $file_ext_count - 1;
// The variable will have a value pdf as per the sample file name mentioned above.
$file_extension = $file_ext[$cnt];
Swift 3, 4 & 5
Running code on the main thread
DispatchQueue.main.async {
// Your code here
}
I ran into a similar problem today (but with mod_wsgi
). It might be an Apache 2.2-to-2.4 problem. A comprehensive list of changes can be found here.
For me, it helped to add an additional <Directory>
-entry for every path the error-log was complaining about and filling the section with Require all granted
.
So in your case you could try
<Directory /usr/lib/cgi-bin/php5-fcgi>
Require all granted
Options FollowSymLinks
</Directory>
and I had to move my configuration file from folder conf.d
to folder sites-enabled
.
All in all, that did the trick for me, but I don't guarantee it works in your case as well.
Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html
For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432
Here is the example:
$url = 'https://www.example.com/api/list';
$cn_match = 'www.example.com';
$data = array (
'apikey' => '[example api key here]',
'limit' => intval($limit),
'offset' => intval($offset)
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
, 'ssl' => array(
'verify_peer' => true,
'cafile' => [path to file] . "cacert.pem",
'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
'CN_match' => $cn_match,
'disable_compression' => true,
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Hope that helps
http://jsfiddle.net/b9chris/zN39r/
HTML:
<div class="item row">
<div class="col-xs-12 col-sm-6"><h4>This is some text.</h4></div>
<div class="col-xs-12 col-sm-6"><h4>This is some more.</h4></div>
</div>
CSS:
div.item div h4 {
height: 60px;
vertical-align: middle;
display: table-cell;
}
Important notes:
vertical-align: middle; display: table-cell;
must be applied to a tag that has no Bootstrap classes applied; it cannot be a col-*
, a row
, etc.row
or col-*
tags.http://jsfiddle.net/b9chris/zN39r/1/
CSS:
div.item div {
background: #fdd;
table-layout: fixed;
display: table;
}
div.item div h4 {
height: 60px;
vertical-align: middle;
display: table-cell;
background: #eee;
}
Notice the added table-layout and display properties on the col-*
tags. This must be applied to the tag(s) that have col-*
applied; it won't help on other tags.
You can also use jQuery's delay()
method instead of setTimeout()
. It'll give you much more readable code. Here's an example from the docs:
$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );
The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout
thrusts upon you.
You should use @Override whenever possible. It prevents simple mistakes from being made. Example:
class C {
@Override
public boolean equals(SomeClass obj){
// code ...
}
}
This doesn't compile because it doesn't properly override public boolean equals(Object obj)
.
The same will go for methods that implement an interface (1.6 and above only) or override a Super class's method.
You could Node's util.inspect(object) to print out object's structure.
It is especially helpful when your object has circular dependencies e.g.
$ node
var obj = {
"name" : "John",
"surname" : "Doe"
}
obj.self_ref = obj;
util = require("util");
var obj_str = util.inspect(obj);
console.log(obj_str);
// prints { name: 'John', surname: 'Doe', self_ref: [Circular] }
It that case JSON.stringify throws exception: TypeError: Converting circular structure to JSON
Just check against null.
($myObject.MyProperty -ne $null)
If you have not set PowerShell to StrictMode, this works even if the property does not exist:
$obj = New-Object PSObject;
Add-Member -InputObject $obj -MemberType NoteProperty -Name Foo -Value "Bar";
$obj.Foo; # Bar
($obj.MyProperty -ne $null); # False, no exception
You can create branch with HEAD set to one commit before merge. Then, you can do:
git merge --squash testing
This will merge, but not commit. Then:
git diff
npm start
runs a script that the app maker built for easy starting of the app
npm install
installs all the packages in package.json
run npm install
first
then run npm start
I have overcome this problem by changing the device screen size.
I have found that if you are specifying 1024 mb ram then you have to specify the device screen size in hdpi only and if it is 512 mb ram then it should be mdpi or others.
So, We can clearly say that ram size should be specify according to the screen size . If you are specifying the 1024 ram size while keeping the device screen size in mdpi then it results in the above mentioned error i.e "Failed to allocate memory: 8 This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information."
or
make your options in AVD manager as follows:
[2013-01-11 14:44:01 - SDK Manager] hw.sensors.orientation=yes
[2013-01-11 14:44:01 - SDK Manager] hw.camera.front=none
[2013-01-11 14:44:01 - SDK Manager] hw.gps=yes
[2013-01-11 14:44:01 - SDK Manager] skin.dynamic=no
[2013-01-11 14:44:01 - SDK Manager] hw.keyboard=no
[2013-01-11 14:44:01 - SDK Manager] vm.heapSize=32
[2013-01-11 14:44:01 - SDK Manager] hw.ramSize=343
Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0
import tensorflow as tf
# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)
# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)
# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])
# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])
# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)
Result:
------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------
If you know the settings in advance you can define it in a single statement:
var defaultsettings = {
ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
};
If you don't know the values in advance you can just define the top level object and then add properties:
var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:
var defaultsettings = {
ajaxsettings : { },
uisettings : { }
};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";
You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:
var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";
Note that you can not use variables for key names in the { } literal syntax.
The dash is a special character in Bash as noted at http://tldp.org/LDP/abs/html/special-chars.html#DASHREF. So escaping this once just gets you past Bash, but Grep still has it's own meaning to dashes (by providing options).
So you really need to escape it twice (if you prefer not to use the other mentioned answers). The following will/should work
grep \\-X
grep '\-X'
grep "\-X"
One way to try out how Bash passes arguments to a script/program is to create a .sh script that just echos all the arguments. I use a script called echo-args.sh to play with from time to time, all it contains is:
echo $*
I invoke it as:
bash echo-args.sh \-X
bash echo-args.sh \\-X
bash echo-args.sh "\-X"
You get the idea.
The first link to sp_generate_inserts is pretty cool, here is a really simple version:
DECLARE @Fields VARCHAR(max); SET @Fields = '[QueueName], [iSort]' -- your fields, keep []
DECLARE @Table VARCHAR(max); SET @Table = 'Queues' -- your table
DECLARE @SQL VARCHAR(max)
SET @SQL = 'DECLARE @S VARCHAR(MAX)
SELECT @S = ISNULL(@S + '' UNION '', ''INSERT INTO ' + @Table + '(' + @Fields + ')'') + CHAR(13) + CHAR(10) +
''SELECT '' + ' + REPLACE(REPLACE(REPLACE(@Fields, ',', ' + '', '' + '), '[', ''''''''' + CAST('),']',' AS VARCHAR(max)) + ''''''''') +' FROM ' + @Table + '
PRINT @S'
EXEC (@SQL)
On my system, I get this result:
INSERT INTO Queues([QueueName], [iSort])
SELECT 'WD: Auto Capture', '10' UNION
SELECT 'Car/Lar', '11' UNION
SELECT 'Scan Line', '21' UNION
SELECT 'OCR', '22' UNION
SELECT 'Dynamic Template', '23' UNION
SELECT 'Fix MICR', '41' UNION
SELECT 'Fix MICR (Supervisor)', '42' UNION
SELECT 'Foreign MICR', '43' UNION
...
sleep(1.0/24.0)
As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.
You could try one of these solutions:
Try This
Input:
<!DOCTYPE html>
<html>
<body>
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
<p>Converting < and > into entities are often used to prevent browsers from using it as an HTML element. <br />This can be especially useful to prevent code from running when users have access to display input on your homepage.</p>
</body>
</html>
Output:
This is some <b>bold</b> text.
Converting < and > into entities are often used to prevent browsers from using it as an HTML element. This can be especially useful to prevent code from running when users have access to display input on your homepage.
If you haven't pushed your changes yet use git reset --soft [Hash for one commit]
to rollback to a specific commit. --soft
tells git to keep the changes being rolled back (i.e., mark the files as modified). --hard
tells git to delete the changes being rolled back.
You override $today
in the if statement.
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;
It is then not a Date() object anymore - hence the error.
the same problem occurs to me...
I check the file wrx permissions with:
$ls -l ./gradlew
-> -rw-rw-r-- (no execute permission)
so I use command $chmod +x ./gradlew
and this problem solved.
The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).
DateTime dateTime = ... anything ...
dateTime = new DateTime(
dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond),
dateTime.Kind
);
or the equivalent and shorter:
dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));
This could be generalized into an extension method:
public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}
which is used as follows:
dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...
The following code fragment should return the size in bytes of any object passed to it, so long as it can be serialized. I got this from a colleague at Quixant to resolve a problem of writing to SRAM on a gaming platform. Hope it helps out. Credit and thanks to Carlo Vittuci.
/// <summary>
/// Calculates the lenght in bytes of an object
/// and returns the size
/// </summary>
/// <param name="TestObject"></param>
/// <returns></returns>
private int GetObjectSize(object TestObject)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] Array;
bf.Serialize(ms, TestObject);
Array = ms.ToArray();
return Array.Length;
}
Java was uninstalled when I updated to OS X El Capitan.
See screenshot of terminal before and after I reinstalled Java.
To reinstall Java I followed this link that was provided in the Android Studio dialog box.
Android Studio ran again after the Java installation was reinstalled.
You can change build number by updating file ${JENKINS_HOME}/jobs/job_name/nextBuildNumber on Jenkins server.
You can also install plugin Next Build Number plugin to change build number using CLI or UI
If obj Is Nothing Then
' need to initialize obj: '
Set obj = ...
Else
' obj already set / initialized. '
End If
Or, if you prefer it the other way around:
If Not obj Is Nothing Then
' obj already set / initialized. '
Else
' need to initialize obj: '
Set obj = ...
End If
Use unlist
with use.names = FALSE
argument.
unlist(myList, use.names=FALSE)
I don't know about expanding the information bar.
But you can get the timings set as a default for all queries showing in the "Messages" tab.
When in a Query window, go to the Query Menu item, select "query options" then select "advanced" in the "Execution" group and check the "set statistics time" / "set statistics IO" check boxes. These values will then show up in the messages area for each query without having to remember to put in the set stats on and off.
You could also use Shift + Alt + S to enable client statistics at any time
/* Get sub domain or main domain url
* $url is $_SERVER['SERVER_NAME']
* $index int remove subdomain if acceess from sub domain my current url is https://support.abcd.com ("support" = 7 (char))
* $subDomain string
* $issecure string https or http
* return url
* call like echo getUrl($_SERVER['SERVER_NAME'],7,"payment",true,false);
* out put https://payment.abcd.com
* second call echo getUrl($_SERVER['SERVER_NAME'],7,null,true,true);
*/
function getUrl($url,$index,$subDomain=null,$issecure=false,$www=true) {
//$url=$_SERVER['SERVER_NAME']
$protocol=($issecure==true) ? "https://" : "http://";
$url= substr($url,$index);
$www =($www==true) ? "www": "";
$url= empty($subDomain) ? $protocol.$url :
$protocol.$www.$subDomain.$url;
return $url;
}
Here is a c++ stylish function your can use to read files char by char.
void readCharFile(string &filePath) {
ifstream in(filePath);
char c;
if(in.is_open()) {
while(in.good()) {
in.get(c);
// Play with the data
}
}
if(!in.eof() && in.fail())
cout << "error reading " << filePath << endl;
in.close();
}
sudo su - postgres
psql template1
creating role on pgsql with privilege as "superuser"
CREATE ROLE username superuser;
eg. CREATE ROLE demo superuser;
Then create user
CREATE USER username;
eg. CREATE USER demo;
Assign privilege to user
GRANT ROOT TO username;
And then enable login that user, so you can run e.g.: psql template1
, from normal $
terminal:
ALTER ROLE username WITH LOGIN;
With params
you can call your method like this:
addTwoEach(1, 2, 3, 4, 5);
Without params
, you can’t.
Additionally, you can call the method with an array as a parameter in both cases:
addTwoEach(new int[] { 1, 2, 3, 4, 5 });
That is, params
allows you to use a shortcut when calling the method.
Unrelated, you can drastically shorten your method:
public static int addTwoEach(params int[] args)
{
return args.Sum() + 2 * args.Length;
}
Please rewrite your query like
select /*+ MAX_EXECUTION_TIME(1000) */ * from table
this statement will kill your query after the specified time
Tools
> Options
> Query Results
> SQL Server
> Results to Text (or Grid if you want)
> Include columns headers in the result set
You might need to close and reopen SSMS after changing this option.
On the SQL Editor Toolbar you can select save to file without having to restart SSMS
In it's simplest form you would use it like:
var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>'
If you're going to be using a template a few times you'll want to compile it so it's faster:
var template = _.template('<li><%= name %></li>');
var html = [];
for (var key in names) {
html += template({ name: names[i] });
}
console.log(html.join('')); //Outputs a string of <li> items
I personally prefer the Mustache style syntax. You can adjust the template token markers to use double curly braces:
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
var template = _.template('<li>{{ name }}</li>');
Complete answer:
1. Is there a function available in SQL?
Yes, the SQL 92 spec, Oct 97, pg. 171, section 6.16 specifies this functions:
CURRENT_TIME Time of day at moment of evaluation
CURRENT_DATE Date at moment of evaluation
CURRENT_TIMESTAMP Date & Time at moment of evaluation
2. It is implementation depended so each database has its own function for this?
Each database has its own implementations, but they have to implement the three function above if they comply with the SQL 92 specification (but depends on the version of the spec)
3. What is the function available in MySQL?
NOW() returns 2009-08-05 15:13:00
CURDATE() returns 2009-08-05
CURTIME() returns 15:13:00
True jQuery way if you want to change directly the DOM without messing with inner HTML:
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
Prepend inserts inside the element, before() is the method we need here:
$('#text').find('br').before(document.createTextNode('\n')).remove();
Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.
This should be faster if you work with long texts since there are no string operations here.
To display the new lines:
$('#text').css('white-space', 'pre-line');
In Visual Studio, go to the Tools menu, select Options, expand Source Control, (In a TFS environment, click Visual Studio Team Foundation Server), and click on the Configure User Tools button.
Click the Add button.
Enter/select the following options for Compare:
.*
Compare
C:\Program Files\Beyond Compare 3\BComp.exe
(replace with the proper path for your machine, including version number)%1 %2 /title1=%6 /title2=%7
If using Beyond Compare Professional (3-way Merge):
.*
Merge
C:\Program Files\Beyond Compare 3\BComp.exe
(replace with the proper path for your machine, including version number)%1 %2 %3 %4 /title1=%6 /title2=%7 /title3=%8 /title4=%9
If using Beyond Compare v3/v4 Standard or Beyond Compare v2 (2-way Merge):
.*
Merge
C:\Program Files\Beyond Compare 3\BComp.exe
(replace with the proper path for your machine, including version number)%1 %2 /savetarget=%4 /title1=%6 /title2=%7
If you use tabs in Beyond Compare
If you run Beyond Compare in tabbed mode, it can get confused when you diff or merge more than one set of files at a time from Visual Studio. To fix this, you can add the argument /solo
to the end of the arguments; this ensures each comparison opens in a new window, working around the issue with tabs.
YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...
Do you mean include javascript variable values in the query string of the URL?
Yes:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;