How does your .NET Webservice look like?
I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)
And everytime I used
Integer result = (Integer)envelope.getResponse();
to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive
exception.
I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.
[SoapRpcMethod(), WebMethod]
public Object GetInteger1(int i)
{
// android device will throw exception
return 0;
}
[WebMethod]
public Object GetInteger2(int i)
{
// android device will get the value
return 0;
}
Then I changed my Android code to:
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString()
method, so I use Integer.parseInt(result.toString())
to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.
Here is the full source:
private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";
public int GetInteger2() throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("i");
pi.setValue(123);
request.addProperty(pi);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
return Integer.parseInt(result.toString());
}
Some people have pointed out that ‘ToUniversalTime’ is somewhat unsafe in that it can cause unintended incorrect time dispalys. Expanding on that I’m providing a more detailed example of a solution. The sample here creates an extension to the DateTime object that safely returns a UTC DateTime where you can use ToString as desired….
class Program
{
static void Main(string[] args)
{
DateTime dUtc = new DateTime(2016, 6, 1, 3, 17, 0, 0, DateTimeKind.Utc);
DateTime dUnspecified = new DateTime(2016, 6, 1, 3, 17, 0, 0, DateTimeKind.Unspecified);
//Sample of an unintended mangle:
//Prints "2016-06-01 10:17:00Z"
Console.WriteLine(dUnspecified.ToUniversalTime().ToString("u"));
//Prints "2016 - 06 - 01 03:17:00Z"
Console.WriteLine(dUtc.SafeUniversal().ToString("u"));
//Prints "2016 - 06 - 01 03:17:00Z"
Console.WriteLine(dUnspecified.SafeUniversal().ToString("u"));
}
}
public static class ConvertExtensions
{
public static DateTime SafeUniversal(this DateTime inTime)
{
return (DateTimeKind.Unspecified == inTime.Kind)
? new DateTime(inTime.Ticks, DateTimeKind.Utc)
: inTime.ToUniversalTime();
}
}
I Found the best way to increase Font Size in Eclipse:
Follow this path : Eclipse-Folder\plugins\org.eclipse.ui.themes_1.2.100.v20180514-1547\css
--There are a bunch of Files here and it depends on user system which file to change.
* {
font-size:13;
font-family: Helvetica, Arial, sans-serif;
font-weight: normal;
}
you can even change Font Family if you like.
For Windows Users add the following piece of css at BOTTOM of these files: File Names: e4_default_gtk.css & e4_default_win.css
For Mac Users: e4_default_mac.css
You can use JavaScript to do what you want:
if (document.addEventListener !== undefined) {
// Not IE
document.addEventListener('click', checkSelection, false);
} else {
// IE
document.attachEvent('onclick', checkSelection);
}
function checkSelection() {
var sel = {};
if (window.getSelection) {
// Mozilla
sel = window.getSelection();
} else if (document.selection) {
// IE
sel = document.selection.createRange();
}
// Mozilla
if (sel.rangeCount) {
sel.removeAllRanges();
return;
}
// IE
if (sel.text > '') {
document.selection.empty();
return;
}
}
Soap box: You really shouldn't be screwing with the client's user agent in this manner. If the client wants to select things on the document, then they should be able to select things on the document. It doesn't matter if you don't like the highlight color, because you aren't the one viewing the document.
You can use the find function:
if($('#popup').find('p.filled-text').length !== 0)
// Do Stuff
In IntelliJ Community Edition 2019.02, Changing the following settings worked for me
Update File->Project structure->Project Settings->Project->Project Language level to Java 11 (update to the java version that you wish to use in your project) using drop down.
Update File->Project structure->Project Settings->Modules->Language level
Update File->Settings->Build,Execution,Deployment -> Compiler -> Java Compiler-> Project ByteCode Version to java 11.
Update Target version for all the entries under File->Settings->Build,Execution,Deployment -> Compiler -> Java Compiler-> Per module Byte Code Version.
You can use simple trick which is import flask app variable from main inside another file, like:
test-routes.py
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
and in your main files, where you declared flask app, import test-routes, like:
app.py
from flask import Flask, request, abort
app = Flask(__name__)
# import declared routes
import test-routes
It works from my side.
try to simply git restore .
That's what git says & it's working
You will need to do two steps here for a complete solution
First click on the Solution that you have open and then go File-> Source Control -> Go Online Then uncheck all the files that are being shown as being modified while you were offline.
Don't do the Get Latest version from Source Control Explorer. That will result in a dialog potentially showing a bunch of files asking you to resolve conflicts. Instead do this
In source Control explorer right click on the folder you want to get latest of and then Advanced - Get Specific Version. In the dropdown for version type choose Latest and then choose the first check box that says Overwrite writable files that are not checked out. This will automatically bring your folder in sync with latest on the server
The following example highlights various advantages of using interpolated strings over string.Format()
as far as cleanliness and readability goes. It also shows that code within {}
gets evaluated like any other function argument, just as it would if string.Format()
we're being called.
using System;
public class Example
{
public static void Main()
{
var name = "Horace";
var age = 34;
// replaces {name} with the value of name, "Horace"
var s1 = $"He asked, \"Is your name {name}?\", but didn't wait for a reply.";
Console.WriteLine(s1);
// as age is an integer, we can use ":D3" to denote that
// it should have leading zeroes and be 3 characters long
// see https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
//
// (age == 1 ? "" : "s") uses the ternary operator to
// decide the value used in the placeholder, the same
// as if it had been placed as an argument of string.Format
//
// finally, it shows that you can actually have quoted strings within strings
// e.g. $"outer { "inner" } string"
var s2 = $"{name} is {age:D3} year{(age == 1 ? "" : "s")} old.";
Console.WriteLine(s2);
}
}
// The example displays the following output:
// He asked, "Is your name Horace?", but didn't wait for a reply.
// Horace is 034 years old.
All nice solutions, borrowing and improvising for special case -> If you want to add a label near the arrowhead:
arr = [2,3]
txt = “Vector X”
ax.annotate(txt, arr)
ax.arrow(0, 0, *arr, head_width=0.05, head_length=0.1)
You can close a figure by calling matplotlib.pyplot.close
, for example:
from numpy import *
import matplotlib.pyplot as plt
from scipy import *
t = linspace(0, 0.1,1000)
w = 60*2*pi
fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)
You can also close all open figures by calling matplotlib.pyplot.close("all")
In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte
data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:
module tb;
byte b [4];
initial begin
foreach (b[i]) b[i] = 1 << i;
foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
$finish;
end
endmodule
This prints out:
Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000
This is similar in concept to Marty's reg [7:0] a [0:3];
. However, byte
is a 2-state data type (0 and 1), but reg
is 4-state (01xz). Using byte
also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i])
loop syntax.
The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.
You can use date
to get time and date of a day:
[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013
Also hwclock
would do:
[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST -0.516080 seconds
For customized output, you can either redirect the output of date
to something like awk
, or write your own program to do that.
Remember to put your own executable scripts/binary into your PATH
(e.g. /usr/bin) to make it invokable anywhere.
RFC3966 defines the IETF standard URI for telephone numbers, that is the 'tel:' URI. That's the standard. There's no similar standard that specifies 'callto:', that's a particular convention for Skype on platforms where is allows registering a URI handler to support it.
I faced this problem when I tried to build and install my app to a Android 8.1.0 (API 26)phone.
The only reason is that I added android:hasCode="false"
to the application
tag in the manifest
file. However, it worked on API 24 with the same code when I tried several months ago (STRANGE?).
After removing that attribute, the problem disappears.
IF they Give Path Directory Error!
In MAC Then Go to Folder Get Info and Open Storage and Permission change to privileges Read To Write
You can try Wolfram Alpha as in this example based on your input:
Not necessary to execute as script
You can interrogate the thread instance with getState() which returns an instance of Thread.State enumeration with one of the following values:
* NEW
A thread that has not yet started is in this state.
* RUNNABLE
A thread executing in the Java virtual machine is in this state.
* BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
* WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
* TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
* TERMINATED
A thread that has exited is in this state.
However I think it would be a better design to have a master thread which waits for the 3 children to finish, the master would then continue execution when the other 3 have finished.
vitaminwater's answer is working for me.
If your textview's text is bouncing up and down during edit, after setting [textView setScrollEnabled:NO];
, set Size Inspector > Scroll View > Content Insets > Never
.
Hope it helps.
If you are using python elasticsearch5 module or curl:
from python you do
es = elasticsearch5.Elasticsearch('my_host:my_port')
es.search(
index='my_index',
size=1,
sort='my_timestamp:desc'
)
If your documents are not inserted with any field that is of type datetime, then I don't believe you can get the N "most recent".
This is the one I use:
set statusline=
set statusline+=%7*\[%n] "buffernr
set statusline+=%1*\ %<%F\ "File+path
set statusline+=%2*\ %y\ "FileType
set statusline+=%3*\ %{''.(&fenc!=''?&fenc:&enc).''} "Encoding
set statusline+=%3*\ %{(&bomb?\",BOM\":\"\")}\ "Encoding2
set statusline+=%4*\ %{&ff}\ "FileFormat (dos/unix..)
set statusline+=%5*\ %{&spelllang}\%{HighlightSearch()}\ "Spellanguage & Highlight on?
set statusline+=%8*\ %=\ row:%l/%L\ (%03p%%)\ "Rownumber/total (%)
set statusline+=%9*\ col:%03c\ "Colnr
set statusline+=%0*\ \ %m%r%w\ %P\ \ "Modified? Readonly? Top/bot.
Highlight on? function:
function! HighlightSearch()
if &hls
return 'H'
else
return ''
endif
endfunction
Colors (adapted from ligh2011.vim):
hi User1 guifg=#ffdad8 guibg=#880c0e
hi User2 guifg=#000000 guibg=#F4905C
hi User3 guifg=#292b00 guibg=#f4f597
hi User4 guifg=#112605 guibg=#aefe7B
hi User5 guifg=#051d00 guibg=#7dcc7d
hi User7 guifg=#ffffff guibg=#880c0e gui=bold
hi User8 guifg=#ffffff guibg=#5b7fbb
hi User9 guifg=#ffffff guibg=#810085
hi User0 guifg=#ffffff guibg=#094afe
selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.
User.find({ "username": { "$ne": 'admin' } })
$nin selects the documents where: the field value is not in the specified array or the field does not exist.
User.find({ "groups": { "$nin": ['admin', 'user'] } })
One caveat: in .NET the linefeed is "\r\n". So if you're loading your text from a file, you might have to use that instead of just "\n"
edit> as samuel pointed out in the comments, "\r\n" is not .NET specific, but is windows specific.
Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.
As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.
long unixTime = System.currentTimeMillis() / 1000L;
In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:
$.ajax(
'https://foo.bar.com,
{
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: successFunc
}
);
The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:
An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT
Very much agreed with @Patrik M, but the thing with Arrays.toString is that it includes "[" and "]" and "," in the output. So I'll simply use a regex to remove them from outout like this
String strOfInts = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", "");
and now you have a String which can be parsed back to java.lang.Number
, for example,
long veryLongNumber = Long.parseLong(intStr);
Or you can use the java 8 streams, if you hate regex,
String strOfInts = Arrays
.stream(intArray)
.mapToObj(String::valueOf)
.reduce((a, b) -> a.concat(",").concat(b))
.get();
This is possible using the mergeFunction
parameter of Collectors.toMap(keyMapper, valueMapper, mergeFunction)
:
Map<String, String> phoneBook =
people.stream()
.collect(Collectors.toMap(
Person::getName,
Person::getAddress,
(address1, address2) -> {
System.out.println("duplicate key found!");
return address1;
}
));
mergeFunction
is a function that operates on two values associated with the same key. adress1
corresponds to the first address that was encountered when collecting elements and adress2
corresponds to the second address encountered: this lambda just tells to keep the first address and ignores the second.
This will print out the query:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
print $query;
This will print out the results:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($dave)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
Edit:
Ok, I understand your confusion so let me elaborate:
Case 1:
if (myDict.Contains(someKey))
someVal = myDict[someKey];
In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it
Case 2:
myDict.TryGetValue(somekey, out someVal)
In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.
If tomorrow you decide you don't love Marry either she can be replaced as well:
today=$(</tmp/lovers.txt)
tomorrow="${today//Suzi/Sara}"
echo "${tomorrow//Marry/Jesica}" > /tmp/lovers.txt
There must be 50 ways to leave your lover.
Simply should be normalized chain and run a replacement codes:
var str = "Letras Á É Í Ó Ú Ñ - á é í ó ú ñ...";
console.log (str.normalize ("NFKD").replace (/[\u0300-\u036F]/g, ""));
// Letras A E I O U N - a e i o u n...
See normalize
Then you can use this function:
function noTilde (s) {
if (s.normalize != undefined) {
s = s.normalize ("NFKD");
}
return s.replace (/[\u0300-\u036F]/g, "");
}
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
I would do it in the Initialize event of the controller like this...
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
const string culture = "en-US";
CultureInfo ci = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
If you have an SMTP service running, you can outfile to the drop directory. If you have high volume, you may result with duplicate file names, but there are ways to avoid that.
Otherwise, you will need to create a UDF.
Here's a sample trigger solution:
CREATE TRIGGER test.autosendfromdrop BEFORE INSERT ON test.emaildrop
FOR EACH ROW BEGIN
/* START THE WRITING OF THE EMAIL FILE HERE*/
SELECT concat("To: ",NEW.To),
concat("From: ",NEW.From),
concat("Subject: ",NEW.Subject),
NEW.Body
INTO OUTFILE
"C:\\inetpub\\mailroot\\pickup\\mail.txt"
FIELDS TERMINATED by '\r\n' ESCAPED BY '';
END;
To markup the message body you will need something like this...
CREATE FUNCTION `HTMLBody`(Msg varchar(8192))
RETURNS varchar(17408) CHARSET latin1 DETERMINISTIC
BEGIN
declare tmpMsg varchar(17408);
set tmpMsg = cast(concat(
'Date: ',date_format(NOW(),'%e %b %Y %H:%i:%S -0600'),'\r\n',
'MIME-Version: 1.0','\r\n',
'Content-Type: multipart/alternative;','\r\n',
' boundary=\"----=_NextPart_000_0000_01CA4B3F.8C263EE0\"','\r\n',
'Content-Class: urn:content-classes:message','\r\n',
'Importance: normal','\r\n',
'Priority: normal','\r\n','','\r\n','','\r\n',
'This is a multi-part message in MIME format.','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/plain;','\r\n',
' charset=\"iso-8859-1\"','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n','','\r\n',
Msg,
'\r\n','','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/html','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n',
Msg,
'\r\n','------=_NextPart_000_0000_01CA4B3F.8C263EE0--'
) as char);
RETURN tmpMsg;
END ;
You should not be updating 10k rows in a set unless you are certain that the operation is getting Page Locks (due to multiple rows per page being part of the UPDATE
operation). The issue is that Lock Escalation (from either Row or Page to Table locks) occurs at 5000 locks. So it is safest to keep it just below 5000, just in case the operation is using Row Locks.
You should not be using SET ROWCOUNT to limit the number of rows that will be modified. There are two issues here:
It has that been deprecated since SQL Server 2005 was released (11 years ago):
Using SET ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements in a future release of SQL Server. Avoid using SET ROWCOUNT with DELETE, INSERT, and UPDATE statements in new development work, and plan to modify applications that currently use it. For a similar behavior, use the TOP syntax
It can affect more than just the statement you are dealing with:
Setting the SET ROWCOUNT option causes most Transact-SQL statements to stop processing when they have been affected by the specified number of rows. This includes triggers. The ROWCOUNT option does not affect dynamic cursors, but it does limit the rowset of keyset and insensitive cursors. This option should be used with caution.
Instead, use the TOP () clause.
There is no purpose in having an explicit transaction here. It complicates the code and you have no handling for a ROLLBACK, which isn't even needed since each statement is its own transaction (i.e. auto-commit).
Assuming you find a reason to keep the explicit transaction, then you do not have a TRY / CATCH structure. Please see my answer on DBA.StackExchange for a TRY / CATCH template that handles transactions:
Are we required to handle Transaction in C# Code as well as in Store procedure
I suspect that the real WHERE clause is not being shown in the example code in the Question, so simply relying upon what has been shown, a better model would be:
DECLARE @Rows INT,
@BatchSize INT; -- keep below 5000 to be safe
SET @BatchSize = 2000;
SET @Rows = @BatchSize; -- initialize just to enter the loop
BEGIN TRY
WHILE (@Rows = @BatchSize)
BEGIN
UPDATE TOP (@BatchSize) tab
SET tab.Value = 'abc1'
FROM TableName tab
WHERE tab.Parameter1 = 'abc'
AND tab.Parameter2 = 123
AND tab.Value <> 'abc1' COLLATE Latin1_General_100_BIN2;
-- Use a binary Collation (ending in _BIN2, not _BIN) to make sure
-- that you don't skip differences that compare the same due to
-- insensitivity of case, accent, etc, or linguistic equivalence.
SET @Rows = @@ROWCOUNT;
END;
END TRY
BEGIN CATCH
RAISERROR(stuff);
RETURN;
END CATCH;
By testing @Rows
against @BatchSize
, you can avoid that final UPDATE query (in most cases) because the final set is typically some number of rows less than @BatchSize
, in which case we know that there are no more to process (which is what you see in the output shown in your answer). Only in those cases where the final set of rows is equal to @BatchSize
will this code run a final UPDATE affecting 0 rows.
I also added a condition to the WHERE
clause to prevent rows that have already been updated from being updated again.
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html
Specifically:
Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.
I was the person who originated this convention back in 2006 and promoted it on the early jQuery mailing list, so let me share some of the history and motivation around it.
The accepted answer gives this example:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
But that doesn't really illustrate it well. Even without the $
, we would still have two different variable names here, email
and email_field
. That's plenty good right there. Why would we need to throw a $
into one of the names when we already have two different names?
Actually, I wouldn't have used email_field
here for two reasons: names_with_underscores
are not idiomatic JavaScript, and field
doesn't really make sense for a DOM element. But I did follow the same idea.
I tried a few different things, among them something very similar to the example:
var email = $("#email"), emailElement = $("#email")[0];
// Now email is a jQuery object and emailElement is the first/only DOM element in it
(Of course a jQuery object can have more than one DOM element, but the code I was working on had a lot of id
selectors, so in those cases there was a 1:1 correspondence.)
I had another case where a function received a DOM element as a parameter and also needed a jQuery object for it:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var emailJQ = $(email);
// Now email is the DOM element and emailJQ is a jQuery object for it
}
Well that's a little confusing! In one of my bits of code, email
is the jQuery object and emailElement
is the DOM element, but in the other, email
is the DOM element and emailJQ
is the jQuery object.
There was no consistency and I kept mixing them up. Plus it was a bit of a nuisance to keep having to make up two different names for the same thing: one for the jQuery object and another for the matching DOM element. Besides email
, emailElement
, and emailJQ
, I kept trying other variations too.
Then I noticed a common pattern:
var email = $("#email");
var emailJQ = $(email);
Since JavaScript treats $
as simply another letter for names, and since I always got a jQuery object back from a $(whatever)
call, the pattern finally dawned on me. I could take a $(...)
call and just remove some characters, and it would come up with a pretty nice name:
$
("#email")$
(email)
Strikeout isn't perfect, but you may get the idea: with some characters deleted, both of those lines end up looking like:
$email
That's when I realized I didn't need to make up a convention like emailElement
or emailJQ
. There was already a nice convention staring at me: take some characters out of a $(whatever)
call and it turns into $whatever
.
var $email = $("#email"), email = $email[0];
// $email is the jQuery object and email is the DOM object
and:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var $email = $(email);
// $email is the jQuery object and email is the DOM object
// Same names as in the code above. Yay!
}
So I didn't have to make up two different names all the time but could just use the same name with or without a $
prefix. And the $
prefix was a nice reminder that I was dealing with a jQuery object:
$('#email').click( ... );
or:
var $email = $('#email');
// Maybe do some other stuff with $email here
$email.click( ... );
You can add a reference to System.Configuration
in your project and then:
using System.Configuration;
then
string sValue = ConfigurationManager.AppSettings["BatchFile"];
with an app.config
file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="BatchFile" value="blah.bat" />
</appSettings>
</configuration>
This did the trick for me (I still was on the master branch):
git reset --hard origin/master
While JS is probably the way to go, it could be done with HTML and CSS only.
Here you have a fake radio button which is really a label for a real hidden radio button. By doing that, you get exactly the effect you need.
<style>
#uncheck>input { display: none }
input:checked + label { display: none }
input:not(:checked) + label + label{ display: none }
</style>
<div id='uncheck'>
<input type="radio" name='food' id="box1" />
Pizza
<label for='box1'>◎</label>
<label for='box0'>◉</label>
<input type="radio" name='food' id="box2" />
Ice cream
<label for='box2'>◎</label>
<label for='box0'>◉</label>
<input type="radio" name='food' id="box0" checked />
</div>
See it here: https://jsfiddle.net/tn70yxL8/2/
Now, that assumes you need non-selectable labels.
If you were willing to include the labels, you can technically avoid repeating the "uncheck" label by changing its text in CSS, see here: https://jsfiddle.net/7tdb6quy/2/
You can use this to solve your problem:
private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
HttpClient webClient = new HttpClient();
Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
HttpResponseMessage response = await webClient.GetAsync(uri);
var jsonString = await response.Content.ReadAsStringAsync();
var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
foreach (Student Student in _Data)
{
tb1.Text = Student.student_name;
}
}
To refresh the whole page, but it works normally:
Response.Redirect(url,bool)
This depends not only on the operating system in question, but also on configuration, potentially real-time configuration.
For Linux:
cat /proc/sys/fs/file-max
will show the current maximum number of file descriptors total allowed to be opened simultaneously. Check out http://www.cs.uwaterloo.ca/~brecht/servers/openfiles.html
You can try doing:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
Should be
~/([^/]*)$~
Means: Match a /
and then everything, that is not a /
([^/]*
) until the end ($
, "end"-anchor).
I use the ~
as delimiter, because now I don't need to escape the forward-slash /
.
What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).
This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow Id
on a OneToOne
or ManyToOne
. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn
and also define a Basic
Id
mapping for the foreign key column.
Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?
You can obtain a similar result but using an Id
on OneToOne
or ManyToOne
is much simpler and is the preferred way to map derived identifiers with JPA 2.0. PrimaryKeyJoinColumn
might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:
11.1.40 PrimaryKeyJoinColumn Annotation
The
PrimaryKeyJoinColumn
annotation specifies a primary key column that is used as a foreign key to join to another table.The
PrimaryKeyJoinColumn
annotation is used to join the primary table of an entity subclass in theJOINED
mapping strategy to the primary table of its superclass; it is used within aSecondaryTable
annotation to join a secondary table to a primary table; and it may be used in aOneToOne
mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108]....
If no
PrimaryKeyJoinColumn
annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass....
Example: Customer and ValuedCustomer subclass
@Entity @Table(name="CUST") @Inheritance(strategy=JOINED) @DiscriminatorValue("CUST") public class Customer { ... } @Entity @Table(name="VCUST") @DiscriminatorValue("VCUST") @PrimaryKeyJoinColumn(name="CUST_ID") public class ValuedCustomer extends Customer { ... }
[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over
PrimaryKeyJoinColumn
for the OneToOne mapping case.
This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?
The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.
For the record, support of Id
on OneToOne
and ManyToOne
has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.
Java interning() method basically makes sure that if String object is present in SCP, If yes then it returns that object and if not then creates that objects in SCP and return its references
for eg: String s1=new String("abc");
String s2="abc";
String s3="abc";
s1==s2// false, because 1 object of s1 is stored in heap and other in scp(but this objects doesn't have explicit reference) and s2 in scp
s2==s3// true
now if we do intern on s1
s1=s1.intern()
//JVM checks if there is any string in the pool with value “abc” is present? Since there is a string object in the pool with value “abc”, its reference is returned.
Notice that we are calling s1 = s1.intern(), so the s1 is now referring to the string pool object having value “abc”.
At this point, all the three string objects are referring to the same object in the string pool. Hence s1==s2 is returning true now.
I wasn't satisfied with the rounded top and bottom to the shadow present in Deefour's solution so created my own.
inset
box-shadow
creates a nice uniform shadow with the top and bottom cut off.
To use this effect on the sides of your element, create two pseudo elements :before
and :after
positioned absolutely on the sides of the original element.
div:before, div:after {
content: " ";
height: 100%;
position: absolute;
top: 0;
width: 15px;
}
div:before {
box-shadow: -15px 0 15px -15px inset;
left: -15px;
}
div:after {
box-shadow: 15px 0 15px -15px inset;
right: -15px;
}
div {
background: #EEEEEE;
height: 100px;
margin: 0 50px;
width: 100px;
position: relative;
}
_x000D_
<div></div>
_x000D_
Edit
Depending on your design, you may be able to use clip-path
, as shown in @Luke's answer. However, note that in many cases this still results in the shadow tapering off at the top and bottom as you can see in this example:
div {
width: 100px;
height: 100px;
background: #EEE;
box-shadow: 0 0 15px 0px #000;
clip-path: inset(0px -15px 0px -15px);
position: relative;
margin: 0 50px;
}
_x000D_
<div></div>
_x000D_
With SQL Developer 4.x, the language option is to be added to ..\sqldeveloper\bin\sqldeveloper.conf
, rather than ..\sqldeveloper\bin\ide.conf
:
# ----- MODIFICATION BEGIN -----
AddVMOption -Duser.language=en
# ----- MODIFICATION END -----
Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry. Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies! Okay, let me try:
1) They are all event-driven things. (I hear the laugh, but read on)
If you don't know what event-driven is Then think you place a button on the page, hook it up w/ a function using "on-click", waiting for users to click on it to trigger the actions you plant inside the function. Or think of "trigger" of SQL Server / Oracle.
2) $watch is "on-click".
What's special about is it takes 2 functions as parameters, first one gives the value from the event, second one takes the value into consideration...
3) $digest is the boss who checks around tirelessly, bla-bla-bla but a good boss.
4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)
Now, let's make it visual. Picture this to make it even more easy to grab the idea:
In a restaurant,
- WAITERS
are supposed to take orders from customers, this is
$watch(
function(){return orders;},
function(){Kitchen make it;}
);
- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()
- OWNER has the ultimate power to drive everyone upon request, this is $apply()
git clone <remote-url>
<=>
git init
// init new repositorygit remote add origin <remote-url>
// add remotegit fetch
// fetch all remote branchsgit switch <default_branch>
// switch to the default branchgit pull
<=>
git pull <remote> <branch>
<=>
I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.
scanf("%d %d %d", &var1, &var2, &var3);
Similarly if you want to read comma separated values use :
scanf("%d,%d,%d", &var1, &var2, &var3);
While the w32tm /resync
in theory does the job, it only does so under certain conditions. When "down to the millisecond" matters, however, I found that Windows wouldn't actually make the adjustment; as if "oh, I'm off by 2.5 seconds, close enough bro, nothing to see or do here".
In order to truly force the resync (Windows 7):
w32tm /resync
watch -n 0.1 date
on a Linux machine on the network that I had SSH'd over into)--- Rapid Method ---
net start w32time
(Time Service must be running)time 8
(where 8 may be replaced by any 'hour' value, presumably 0-23)w32tm /resync
SELECT [ReportId],
SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
(
SELECT DISTINCT [ReportId]
FROM Table1
) a
CROSS APPLY
(
SELECT [Email] + ', '
FROM Table1 AS B
WHERE A.[ReportId] = B.[ReportId]
FOR XML PATH('')
) D (EmailList)
print("<pre>".print_r($data,true)."</pre>");
I will give you a simple solution for this one. In my case I don't have access to a server. In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple:
Simple paste in "C:\Program Files\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security
.
The location may differ. Now open Chrome by clicking on that shortcut.
The discussion I had with Asaph may be unclear to follow as we went back and forth quite a bit.
I thought that I might clarify the upshot of our discourse for others who might face similar situations in the future to benefit from:
ENUM
-type columns are very difficult beasts to manipulate. I wanted to add two countries (Malaysia & Sweden) to the existing set of countries in my ENUM.
It seems that MySQL 5.1 (which is what I am running) can only update the ENUM by redefining the existing set in addition to what I want:
This did not work:
ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia') DEFAULT NULL;
The reason was that the MySQL statement was replacing the existing ENUM with another containing the entries 'Malaysia'
and 'Sweden'
only. MySQL threw up an error because the carmake
table already had values like 'England'
and 'USA'
which were not part of the new ENUM
's definition.
Surprisingly, the following did not work either:
ALTER TABLE carmake CHANGE country country ENUM('Australia','England','USA'...'Sweden','Malaysia') DEFAULT NULL;
It turns out that even the order of elements of the existing ENUM
needs to be preserved while adding new members to it. So if my existing ENUM
looks something like ENUM('England','USA')
, then my new ENUM
has to be defined as ENUM('England','USA','Sweden','Malaysia')
and not ENUM('USA','England','Sweden','Malaysia')
. This problem only becomes manifest when there are records in the existing table that use 'USA'
or 'England'
values.
BOTTOM LINE:
Only use ENUM
s when you do not expect your set of members to change once defined. Otherwise, lookup tables are much easier to update and modify.
You can use this javascript code to redirect after a specific time. Hope it will work.
setRedirectTime(function ()
{
window.location.href= 'https://www.google.com'; // the redirect URL will be here
},10000); // 10 seconds
The full command would be something like below, notice the quotes
icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"
$ ionic info Ionic:
Ionic CLI : 5.4.16
Utility:
cordova-res : not installed native-run : 0.3.0
System:
NodeJS : v12.16.1 npm : 6.13.4 OS : Linux 5.3
------------------------------------------------------------
Ionic CLI update available: 5.4.16 ? 6.2.2
The package name has changed from ionic to @ionic/cli!
To update, run: npm uninstall -g ionic
Then run: npm i -g @ionic/cli
------------------------------------------------------------
This can also occur if your stored procedure encounters a compile failure after opening a transaction (e.g. table not found, invalid column name).
I found i had to use 2 stored procedures a "worker" one and a wrapper one with try/catch both with logic similar to that outlined by Remus Rusanu. The worker catch is used to handle the "normal" failures and the wrapper catch to handle compile failure errors.
https://msdn.microsoft.com/en-us/library/ms175976.aspx
Errors Unaffected by a TRY…CATCH Construct
The following types of errors are not handled by a CATCH block when they occur at the same level of execution as the TRY…CATCH construct:
- Compile errors, such as syntax errors, that prevent a batch from running.
- Errors that occur during statement-level recompilation, such as object name resolution errors that occur after compilation because of deferred name resolution.
Hopefully this helps someone else save a few hours of debugging...
We can check by isInteger
function.
ie number will return true and float return false
console.log(Number.isInteger(2)),<BR>
Will return true
console.log(Number.isInteger(2.5))
Will return false
For me, I had things unnecessarily split into separate folders. I'm running plotly dash and I had my Procfile
, and Pipfile
(and lock) together, but separate from the other features of my app (run.py
and app.py
, the actual content of the pages being used was in a subfolder). So joining much of that together repaired my H10 error
Add Tooltip to a div
<style>
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">Hover over me
<span class="tooltiptext">Information</span>
</div>
If the browser people see this as a security and/or usability problem, then the answer to your question is to simply not close the window, since by definition they will come up with solutions for your workaround anyway. There is a nice summation about the reasoning why the choice have been in the firefox bug database https://bugzilla.mozilla.org/show_bug.cgi?id=190515#c70
So what can you do?
Change the specification of your website, so that you have a solution for these people. You could for instance take it as an opportunity to direct them to a partner.
That is, see it as a handoff to someone else that (potentially) needs it. As an example, Hanselman had a recent article about what to do in the other similar situation, namely 404 errors: http://www.hanselman.com/blog/PutMissingKidsOnYour404PageEntirelyClientSideSolutionWithYQLJQueryAndMSAjax.aspx
Just define your variables in global.js outside a function scope:
// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";
// other js-file
function testGlobal () {
alert(global1);
}
To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:
<html>
<head>
<!-- Include global.js first -->
<script src="/YOUR_PATH/global.js" type="text/javascript"></script>
<!-- Now we can reference variables, objects, functions etc.
defined in global.js -->
<script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
</head>
[...]
</html>
You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.
If you just need to await
to avoid nesting code:
let json;
await new Promise(done => $.getJSON('https://***', async function (data) {
json = data;
done();
}));
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
I see there is a VBA solution and a non-VBA solution, which both are really good. I wanted to propose my Javascript solution.
There is an Excel add-in called Funfun that allows you to use javascript, HTML and css in Excel. It has an online editor with an embedded spreadsheet where you can build your chart.
I have written this code for you with Chart.js:
https://www.funfun.io/1/#/edit/5a61ed15404f66229bda3f44
To create this chart, I entered my data on the spreadsheet and read it with a json file, it is the short
file.
I make sure to put it in the right format, in script.js
, so I can add it to my chart:
var data = [];
var color = [];
var label = [];
for (var i = 1; i < $internal.data.length; i++)
{
label.push($internal.data[i][0]);
data.push([$internal.data[i][1], $internal.data[i][2]]);
color.push($internal.data[i][3]);
}
I then create the scatter chart with each dot having his designated color and position:
var dataset = [];
for (var i = 0; i < data.length; i++) {
dataset.push({
data: [{
x: data[i][0],
y: data[i][1]
}],
pointBackgroundColor: color[i],
pointStyle: "cercle",
radius: 6
});
}
After I've created my scatter chart I can upload it in Excel by pasting the URL in the funfun Excel add-in. Here is how it looks like with my example:
Once this is done You can change the color or the position of a dot instantly, in Excel, by changing the values in the spreadsheet.
If you want to add extra dots in the charts you just need to modify the radius of data
in the short
json file.
Hope this Javascript solution helps !
Disclosure : I’m a developer of funfun
this worked perfectly for me:
for(a in array)console.log(array[a])
you can extract any array created in console for find/replace cleanup and posterior usage of this data extracted
Just want to sum up, there might be 4 ways.
or open a new table view control with a check mark:
Hope this helps.
Does the job a lot cleaner than parseInt in my opinion, Use the +operator
var s = '';
console.log(+s);
var s = '1024'
+s
1024
s = 0
+s
0
s = -1
+s
-1
s = 2.456
+s
2.456
s = ''
+s
0
s = 'wtf'
+s
NaN
It sounds like this has been a known issue (Bug 67414)that was resolved in 3.0 ... someone has commented that it's occurring for them in 3.4 as well.
In the mean time, the work around is to remove the JRE System Library from the project and then add it back again.
Here are the steps:
Go to properties of project with the build error (right click > Properties)
View the "Libraries" tab in the "Build Path" section
Find the "JRE System Library" in the list (if this is missing then this error message is not an eclipse bug but a mis-configured project)
Remove the "JRE System Library"
Hit "Add Library ...", Select "JRE System Library" and add the appropriate JRE for the project (eg. 'Workspace default JRE')
Hit "Finish" in the library selection and "OK" in the project properties and then wait for the re-build of the project
Hopefully the error will be resolved ...
Here's one without delegation:
tf1.addTarget(tf2, action: #selector(becomeFirstResponder), for: .editingDidEndOnExit)
tf2.addTarget(tf3, action: #selector(becomeFirstResponder), for: .editingDidEndOnExit)
ObjC:
[tf1 addTarget:tf2 action:@selector(becomeFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];
[tf2 addTarget:tf3 action:@selector(becomeFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];
Works using the (mostly unknown) UIControlEventEditingDidEndOnExit
UITextField
action.
You can also easily hook this up in the storyboard, so no delegation or code is required.
Edit: actually I cannot figure out how to hook this up in storyboard. becomeFirstResponder
does not seem to be a offered action for this control-event, which is a pity. Still, you can hook all your textfields up to a single action in your ViewController which then determines which textField to becomeFirstResponder
based on the sender (though then it is not as elegant as the above programmatic solution so IMO do it with the above code in viewDidLoad
).
In Visual Studio, you can't just open a .cpp
file and expect it to run. You must create a project first, or open the .cpp in some existing project.
In your case, there is no project, so there is no project to build.
Go to File --> New --> Project --> Visual C++ --> Win32 Console Application
. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".
Then, You can add .cpp
files you created outside the Visual Studio by right clicking in the Solution explorer
on folder icon "Source" and Add->Existing Item.
Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.
Then you can press ctrl+F5 to compile without debugging and can see output on console window.
give this style to td: width: 1%;
How about HKEY_CLASSES_ROOT\Word.Application\CurVer?
You can easily call any controller's action using jQuery AJAX method like this:
Note in this example my controller name is Student
Controller Action
public ActionResult Test()
{
return View();
}
In Any View of this above controller you can call the Test() action like this:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "@Url.Action("Test", "Student")",
success: function (result, status, xhr) {
alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
},
error: function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
});
</script>
If you have the product's ID you can use that to create a product object:
$_product = wc_get_product( $product_id );
Then from the object you can run any of WooCommerce's product methods.
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Update
Please review the Codex article on how to write your own shortcode.
Integrating the WooCommerce product data might look something like this:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Your shortcode would then look like [woocommerce_price id="99"]
Since you add ..
after cmake, it will jump up and up (just like cd ..
) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use .
instead of ..
.
I believe there are a lot of good articles about this around the Web, but here is a short summary.
Both UTF-8 and UTF-16 are variable length encodings. However, in UTF-8 a character may occupy a minimum of 8 bits, while in UTF-16 character length starts with 16 bits.
Main UTF-8 pros:
Main UTF-8 cons:
Main UTF-16 pros:
char
as the primitive component of the string.Main UTF-16 cons:
In general, UTF-16 is usually better for in-memory representation because BE/LE is irrelevant there (just use native order) and indexing is faster (just don't forget to handle surrogate pairs properly). UTF-8, on the other hand, is extremely good for text files and network protocols because there is no BE/LE issue and null-termination often comes in handy, as well as ASCII-compatibility.
Adapted from this answer to a very similar question:
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
You should run this command from within your d:\study
folder. It will delete all subfolders which are older than 10 days.
The /S /Q
after the rd
makes it delete folders even if they are not empty, without prompting.
I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat
.
Quote from this post (it's written by the author of doxygen himself) :
run doxygen -g and change the following options of the generated Doxyfile:
EXTRACT_ALL = YES
HAVE_DOT = YES
UML_LOOK = YES
run doxygen again
If you are using ajax as a function remember it expects JSON data to be returned to it, with the parameters set.
$('#example').dataTable({
"ajax" : function (data, callback, settings) {
callback({
data: [...],
recordsTotal: 40,
recordsFiltered: 40}
));
}
})
Xampp has the php application under: C:\xampp\php file directory ... if you input C:\xampp\php\php in CMD it should enter the php application.
If you want to center one view, use this one. In this case TextView must be the lowermost view in your XML because it's layout_height is match_parent.
<TextView
android:id="@+id/tv_to_be_centered"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:gravity="center"
android:text="Some text"
/>
X milliseconds = X / 1000 seconds = (X / 1000) / 60 minutes
If you have 100,000 milliseconds, divide this value by 1,000 and you're left with 100 seconds. Now 100 / 60 = 1.666~ minutes, but fractional minutes have no value, so: do 100 % 60 = 40 seconds to find the remainder, then integer division 100 / 60 = 1 minute, with 40 seconds remainder. Answer: 1 minute, 40 seconds.
Find in /usr/lib/jvm/java-8-oracle/bin/jarsigner -verbose -sigalg SHA1withRSA
The default IsSelected trigger changes 3 properties, Background, Foreground & BorderBrush. If you want to change the border as well as the background, just include this in your style trigger.
<Style TargetType="{x:Type dg:DataGridCell}">
<Style.Triggers>
<Trigger Property="dg:DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="#CCDAFF" />
<Setter Property="BorderBrush" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
simply use..
location.reload(true/false);
If false, the page will be reloaded from cache, else from the server.
Example:
How to transfer putty configuration and session configuration from one user account to another e.g. when created a new account and want to use the putty sessions/configurations from the old account
Process:
- Export registry key from old account into a file
- Import registry key from file into new account
Export reg key: (from OLD account)
Import reg key: (into NEW account)
Login into NEW account e.g. tom
Open normal 'command prompt' (NOT admin !)
Type 'regedit'
Select 'Import' from the menu
Select the registry file to import e.g. 'puttyconfig.reg'
Done
Note:
Do not use an 'admin command prompt' as settings are located under '[HKEY_CURRENT_USER...] 'and regedit would run as admin and show that section for the admin-user rather then for the user to transfer from and/or to.
function exec(cmd, handler = function(error, stdout, stderr){console.log(stdout);if(error !== null){console.log(stderr)}})
{
const childfork = require('child_process');
return childfork.exec(cmd, handler);
}
This function can be easily used like:
exec('echo test');
//output:
//test
exec('echo test', function(err, stdout){console.log(stdout+stdout+stdout)});
//output:
//testtesttest
You can have a simple class which can be used for this kind of measurements.
class duration_printer {
public:
duration_printer() : __start(std::chrono::high_resolution_clock::now()) {}
~duration_printer() {
using namespace std::chrono;
high_resolution_clock::time_point end = high_resolution_clock::now();
duration<double> dur = duration_cast<duration<double>>(end - __start);
std::cout << dur.count() << " seconds" << std::endl;
}
private:
std::chrono::high_resolution_clock::time_point __start;
};
The only thing is needed to do is to create an object in your function at the beginning of that function
void veryLongExecutingFunction() {
duration_calculator dc;
for(int i = 0; i < 100000; ++i) std::cout << "Hello world" << std::endl;
}
int main() {
veryLongExecutingFunction();
return 0;
}
and that's it. The class can be modified to fit your requirements.
npm install
,if the issue is not yet fixed try the following one after the other.npm cache clean
,thennpm install -g npm
,then
npm install
,Finallyng serve --o
to run the project.
Hope this will help....Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to
F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3\lib;F:\oracle\product\10.2.0\db_2\sysman\admin\scripts;
change your drive and folder depending on your requirement...
To dismiss the Viewcontroller called with the previous answers code by CmdSft
ViewController *viewController = [[ViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
you can use
[self dismissViewControllerAnimated:YES completion: nil];
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
Try
string fileName = "test.txt";
FileInfo f = new FileInfo(fileName);
string fullname = f.FullName;
if youre main file is located at /Users/feelexit/WebstormProjects/learnnode/node_modules/index.js
then express needs to be located
at /Users/feelexit/WebstormProjects/learnnode/node_modules/node_modules
as node always looks for modules in ./node_modules
(and its internal folder)
when the path dont start with ./
or /
(more info here)
i think you miss placed youre main file in the module folder
Here's a nice fun LINQ example.
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static void WriteLog(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(strLog);
log.Close();
}
Refer Link: blogspot.in
For me, the following steps worked:
eclipse.ini
fileChange
-Xms40m
-Xmx512m
to
-Xms512m
-Xmx1024m
Restart Eclipse
If you want your JSON to have a validated Typescript type, you will need to do that validation work yourself. This is nothing new. In plain Javascript, you would need to do the same.
I like to express my validation logic as a set of "transforms". I define a Descriptor
as a map of transforms:
type Descriptor<T> = {
[P in keyof T]: (v: any) => T[P];
};
Then I can make a function that will apply these transforms to arbitrary input:
function pick<T>(v: any, d: Descriptor<T>): T {
const ret: any = {};
for (let key in d) {
try {
const val = d[key](v[key]);
if (typeof val !== "undefined") {
ret[key] = val;
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(`could not pick ${key}: ${msg}`);
}
}
return ret;
}
Now, not only am I validating my JSON input, but I am building up a Typescript type as I go. The above generic types ensure that the result infers the types from your "transforms".
In case the transform throws an error (which is how you would implement validation), I like to wrap it with another error showing which key caused the error.
In your example, I would use this as follows:
const value = pick(JSON.parse('{"name": "Bob", "error": false}'), {
name: String,
error: Boolean,
});
Now value
will be typed, since String
and Boolean
are both "transformers" in the sense they take input and return a typed output.
Furthermore, the value
will actually be that type. In other words, if name
were actually 123
, it will be transformed to "123"
so that you have a valid string. This is because we used String
at runtime, a built-in function that accepts arbitrary input and returns a string
.
You can see this working here. Try the following things to convince yourself:
const value
definition to see that the pop-over shows the correct type."Bob"
to 123
and re-run the sample. In your console, you will see that the name has been properly converted to the string "123"
.If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:
df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]
According to the properties of DFS and BFS. For example,when we want to find the shortest path. we usually use bfs,it can guarantee the 'shortest'. but dfs only can guarantee that we can come from this point can achieve that point ,can not guarantee the 'shortest'.
Something like this:
$(myObj).attr({"data-test-1": num1, "data-test-2": num2});
My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.
You could do this easily by creating a CreateRoles
method in your startup
class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Manager", "Member" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
//Here you could create a super user who will maintain the web app
var poweruser = new ApplicationUser
{
UserName = Configuration["AppSettings:UserName"],
Email = Configuration["AppSettings:UserEmail"],
};
//Ensure you have these values in your appsettings.json file
string userPWD = Configuration["AppSettings:UserPassword"];
var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);
if(_user == null)
{
var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
and then you could call the CreateRoles(serviceProvider).Wait();
method from the Configure
method in the Startup class.
ensure you have IServiceProvider
as a parameter in the Configure
class.
Using role-based authorization in a controller to filter user access: Question 2
You can do this easily, like so.
[Authorize(Roles="Manager")]
public class ManageController : Controller
{
//....
}
You can also use role-based authorization in the action method like so. Assign multiple roles, if you will
[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
.....
*/
}
While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here
The other answers address the question asked. I will address the underlying cause: poor schema design.
Do not splay an array across columns. Here you have 3*10 columns that should be turned into 10 rows of 3 columns in a new table (plus id
, etc)
Your Main
table would have only
id int(11) No
name text No
date date No
time time No
schedule int(11) No
category int(11) No
status int(11) No
admin_id int(11) No
Your extra table (Top
) would have
id int(11) No -- for joining to Main
seq TINYINT UNSIGNED -- containing 1..10
img varchar(255) No
title varchar(255) No
desc text No
PRIMARY KEY(id, seq) -- so you can easily find the 10 top_titles
There would be 10 (or fewer? or more?) rows in Top
for each id
.
This eliminates your original problem, and cleans up the schema. (This is not "normalization", as debated in some of the Comments.)
Do not switch to MyISAM; it is going away.
Don't worry about ROW_FORMAT
.
You will need to change your code to do the JOIN
and to handle multiple rows instead of multiple columns.
TOP and square brackets are specific to Transact-SQL. In ANSI SQL one uses LIMIT and backticks (`).
select * from `Table_Name` LIMIT 5;
FDView combines PDF2SWF (which itself is based on xpdf) with an SWF viewer so you can convert and embed PDF documents on the fly on your server.
xpdf is not a perfect PDF converter. If you need better results then Ghostview has some ability to convert PDF documents into other formats which you may be able to more easily build a Flash viewer for.
But for simple PDF documents, FDView should work reasonably well.
It's better to have a proper JSON format instead of directly using the one converted from XML.
[
{
"number": "2013-W45",
"days": [
{
"dow": "1",
"templateDay": "Monday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
},
{
"name": "work 9-5",
}
]
},
{
"dow": "2",
"templateDay": "Tuesday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
}
]
}
]
}
]
This will make things much easier and easy to loop through.
Now you can write the loop as -
<div ng-repeat="week in myData">
<div ng-repeat="day in week.days">
{{day.dow}} - {{day.templateDay}}
<b>Jobs:</b><br/>
<ul>
<li ng-repeat="job in day.jobs">
{{job.name}}
</li>
</ul>
</div>
</div>
Below is the program to execute the rest api in python-
import requests
url = 'https://url'
data = '{ "platform": { "login": { "userName": "name", "password": "pwd" } } }'
response = requests.post(url, data=data,headers={"Content-Type": "application/json"})
print(response)
sid=response.json()['platform']['login']['sessionId'] //to extract the detail from response
print(response.text)
print(sid)
I ran through similar problem and found that I was trying to get the offset of footer but I was loading my script inside a div before the footer. It was something like this:
<div> I have some contents </div>
<script>
$('footer').offset().top;
</script>
<footer>This is footer</footer>
So, the problem was, I was calling the footer element before the footer was loaded.
I pushed down my script below footer and it worked fine!
A slightly modified version of @sidanmor 's code. The main point is, not every webpage is purely ASCII, user should be able to handle the decoding manually (even encode into base64)
function httpGet(url) {
return new Promise((resolve, reject) => {
const http = require('http'),
https = require('https');
let client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client.get(url, (resp) => {
let chunks = [];
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
chunks.push(chunk);
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(Buffer.concat(chunks));
});
}).on("error", (err) => {
reject(err);
});
});
}
(async(url) => {
var buf = await httpGet(url);
console.log(buf.toString('utf-8'));
})('https://httpbin.org/headers');
if you want to pick file from Bin folder of the application then you can try following and don't forget to do exception handling.
string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));
How are you generating your data?
See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.
In [31]: data
Out[31]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)
look ?
Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float)
.
You can also call frame.astype(float)
Now Apple Inc. added a new device screen shots also over iTunesconnect that is iPad Pro. Here are all sizes of screen shots which iTunesconnects requires.
Unfortunately, there are no great options here. Remember, the goal of all of this is to preserve type safety. "Java Generics" offers a solution for dealing with non-genericized legacy libraries, and there is one in particular called the "empty loop technique" in section 8.2. Basically, make the unsafe cast, and suppress the warning. Then loop through the map like this:
@SuppressWarnings("unchecked")
Map<String, Number> map = getMap();
for (String s : map.keySet());
for (Number n : map.values());
If an unexpected type is encountered, you will get a runtime ClassCastException
, but at least it will happen close to the source of the problem.
So it turns out you can get around this by matching your module name to the file name. If you have the module name BankSpecialtyModule then the file name should be. bank-specialty.module.ts
You can't get a count of rows directly from a data reader because it's what is known as a firehose cursor - which means that the data is read on a row by row basis based on the read being performed. I'd advise against doing 2 reads on the data because there's the potential that the data has changed between doing the 2 reads, and thus you'd get different results.
What you could do is read the data into a temporary structure, and use that in place of the second read. Alternatively, you'll need to change the mechanism by which you retrieve the data and use something like a DataTable instead.
HAVING is like WHERE with aggregate functions, or you could use a subquery.
select EmployeeId, sum(amount)
from Sales
group by Employee
having sum(amount) > 20000
Or
select EmployeeId, sum(amount)
from Sales
group by Employee
where EmployeeId in (
select max(EmployeeId) from Employees)
In some cases you might end up having chain of observables, wherein your observable would return another observable. 'flatmap' kind of unwraps the second observable which is buried in the first one and let you directly access the data second observable is spitting out while subscribing.
.center {
display: table;
margin: auto;
}
The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
Use Windows Service Template C# project to create a new service app https://github.com/HarpyWar/windows-service-template
There are console/service mode automatically detected, auto installer/deinstaller of your service and several most used features are included.
I think you can't do it because Id is unique you have to use it for one element . You can use class for the purpose
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
Can try to adopt approach from C++ Boost libraries. Something like this:
class HashUtil
{
public static int HashCombine(int seed, int other)
{
unchecked
{
return other + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
}
}
and then:
class MyClass
{
private string _field1;
private int _field2;
private AnotherClass _field3;
private YetAnotherClass _field4;
public override int GetHashCode()
{
int result = HashUtil.HashCombine(_field1.GetHashCode(), _field2);
result = HashUtil.HashCombine(result, _field3.GetHashCode());
return HashUtil.HashCombine(result, _field4.GetHashCode());
}
}
Just add both these files after opening of body tag. Keep in mind 'Only after Body tag' any where after body tag. If you add below mentioned files inside body tag then your problems would still be unresolved.
So paste them after or before close of body tag... This works 100%. I've tested and got it working!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
To call the function you have to add ()
{this.renderIcon()}
What even is ‘children’?
The React docs say that you can use
props.children
on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.My simple explanation of what
this.props.children
does is that it is used to display whatever you include between the opening and closing tags when invoking a component.A simple example:
Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no
this
keyword so just useprops.children
const Picture = (props) => {
return (
<div>
<img src={props.src}/>
{props.children}
</div>
)
}
This component contains an
<img>
that is receiving someprops
and then it is displaying{props.children}
.Whenever this component is invoked
{props.children}
will also be displayed and this is just a reference to what is between the opening and closing tags of the component.
//App.js
render () {
return (
<div className='container'>
<Picture key={picture.id} src={picture.src}>
//what is placed here is passed as props.children
</Picture>
</div>
)
}
Instead of invoking the component with a self-closing tag
<Picture />
if you invoke it will full opening and closing tags<Picture> </Picture>
you can then place more code between it.This de-couples the
<Picture>
component from its content and makes it more reusable.
Reference: A quick intro to React’s props.children
If you are using C++11, and you need the value as a C++ compile-time constant, a very elegant solution is this:
#include <tuple>
#define MACRO(...) \
std::cout << "num args: " \
<< std::tuple_size<decltype(std::make_tuple(__VA_ARGS__))>::value \
<< std::endl;
Please note: the counting happens entirely at compile time, and the value can be used whenever compile-time integer is required, for instance as a template parameter to std::array.
Put the classname into a variable first:
$classname=$var.'Class';
$bar=new $classname("xyz");
This is often the sort of thing you'll see wrapped up in a Factory pattern.
See Namespaces and dynamic language features for further details.
I am using React-Bootstrap. The onSelect trigger for dropdowns were not allowing me to pass data. Just the event. So remember you can just set any values as attributes and pick them up from the function using javascript. Picking up those attributes you set in that event target.
let currentTarget = event.target;
let currentId = currentTarget.getAttribute('data-id');
let currentValue = currentTarget.getAttribute('data-value');
Just to add some use cases for @anon's & @Oktalist's answer, here's a great reading material about pointer-to-member-function and pointer-to-member-data.
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
I was using function as below:
function doSomething() {
require_once(xyz.php);
....
}
There were constant values declared in xyz.php.
I have to call this doSomething() function from another PHP script file.
But I observed behavior while calling this function in a loop, for first iteration doSomething() was getting constant values within xyz.php
, but later every iteration doSomething()
was not able to get the constant values declared in xyz.php
.
I solved my problem by switching from require_once()
to include()
, updated doSomething()
code is as below:
function doSomething() {
include(xyz.php);
....
}
Now every iteration call to doSomething()
gets the constant values defined in xyz.php
.
Pure JavaScript:
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
jQuery:
$("#button").click(function() {
// assumes element with id='button'
$("#newpost").toggle();
});
A class must have the @Component
annotation or a derivation of that (like @Service
, @Repository
etc.) to be recognized as a Spring bean by the component scanning. So if you add @Component
to the class, it should solve your problem.
check your value which you want to store in integer column. I think this is greater then range of integer. if you want to store value greater then integer range. you should use bigint datatype
SELECT name,COUNT(*) as count
FROM tablename
GROUP BY name
ORDER BY count DESC;
My version. Hope it helps.
import pandas.io.sql
import pyodbc
import sys
server = 'example'
db = 'NORTHWND'
db2 = 'example'
#Crear la conexión
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server +
';DATABASE=' + db +
';DATABASE=' + db2 +
';Trusted_Connection=yes')
#Query db
sql = """SELECT [EmployeeID]
,[LastName]
,[FirstName]
,[Title]
,[TitleOfCourtesy]
,[BirthDate]
,[HireDate]
,[Address]
,[City]
,[Region]
,[PostalCode]
,[Country]
,[HomePhone]
,[Extension]
,[Photo]
,[Notes]
,[ReportsTo]
,[PhotoPath]
FROM [NORTHWND].[dbo].[Employees] """
data_frame = pd.read_sql(sql, conn)
data_frame
Another option for you is a linked list. You'll need to analyze how your program will use the data structure, if you don't need random access it could be faster than reallocating.
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
I do a lot of Novell Identity Manager stuff, and XPATH in that context looks a little different.
Assume the value you are looking for is in a string variable, called TARGET, then the XPATH would be:
count(attr/value[.='$TARGET']/preceding-sibling::*)+1
Additionally it was pointed out that to save a few characters of space, the following would work as well:
count(attr/value[.='$TARGET']/preceding::*) + 1
I also posted a prettier version of this at Novell's Cool Solutions: Using XPATH to get the position node
The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with
RewriteBase /
Which doesn't seem to work in MAMP...at least for me.
I personally dislike the "pass by reference" functionality offered by various programming languages. Perhaps that's because I am just discovering the concepts of functional programming, but I always get goosebumps when I see functions that cause side effects (like manipulating parameters passed by reference). I personally strongly embrace the "single responsibility" principle.
IMHO, a function should return just one result/value using the return keyword. Instead of modifying a parameter/argument, I would just return the modified parameter/argument value and leave any desired reassignments up to the calling code.
But sometimes (hopefully very rarely), it is necessary to return two or more result values from the same function. In that case, I would opt to include all those resulting values in a single structure or object. Again, processing any reassignments should be up to the calling code.
Example:
Suppose passing parameters would be supported by using a special keyword like 'ref' in the argument list. My code might look something like this:
//The Function
function doSomething(ref value) {
value = "Bar";
}
//The Calling Code
var value = "Foo";
doSomething(value);
console.log(value); //Bar
Instead, I would actually prefer to do something like this:
//The Function
function doSomething(value) {
value = "Bar";
return value;
}
//The Calling Code:
var value = "Foo";
value = doSomething(value); //Reassignment
console.log(value); //Bar
When I would need to write a function that returns multiple values, I would not use parameters passed by reference either. So I would avoid code like this:
//The Function
function doSomething(ref value) {
value = "Bar";
//Do other work
var otherValue = "Something else";
return otherValue;
}
//The Calling Code
var value = "Foo";
var otherValue = doSomething(value);
console.log(value); //Bar
console.log(otherValue); //Something else
Instead, I would actually prefer to return both new values inside an object, like this:
//The Function
function doSomething(value) {
value = "Bar";
//Do more work
var otherValue = "Something else";
return {
value: value,
otherValue: otherValue
};
}
//The Calling Code:
var value = "Foo";
var result = doSomething(value);
value = result.value; //Reassignment
console.log(value); //Bar
console.log(result.otherValue);
These code examples are quite simplified, but it roughly demonstrates how I personally would handle such stuff. It helps me to keep various responsibilities in the correct place.
Happy coding. :)
Use $(this).find()
, or pass this in context, using jQuery context with selector.
Using $(this).find()
$(".class").click(function(){
$(this).find(".subclass").css("visibility","visible");
});
Using this
in context, $( selector, context )
, it will internally call find function, so better to use find on first place.
$(".class").click(function(){
$(".subclass", this).css("visibility","visible");
});
The most common way would be to put a simple text file (XML/JSON would be better) on your webserver with the last build version. The application will then download this file, check the version and start the updater. A typical file would look like this:
Application Update File (A unique string that will let your application recognize the file type)
version: 1.0.0 (Latest Assembly Version)
download: http://yourserver.com/... (A link to the download version)
redirect: http://yournewserver.com/... (I used this field in case of a change in the server address.)
This would let the client know that they need to be looking at a new address.
You can also add other important details.
If you need access to the resources of a library project (as you do with ABS) ensure that you add the library project/module as a "Module Dependency" instead of a "Library".
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
You can (should) use CROSS JOIN
. Following query will be equivalent to yours:
SELECT
table1.columnA
, table2.columnA
FROM table1
CROSS JOIN table2
WHERE table1.columnA = 'Some value'
or you can even use INNER JOIN with some always true conditon:
FROM table1
INNER JOIN table2 ON 1=1
function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}
This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.
Try this one :
var time = new Date().toJSON();
1) "Unnecessarily complicated" is IMHO to create first an unmodifiable List before adding its elements to the ArrayList.
2) The solution matches exact the question: "Is there a way to define an ArrayList with the double type?"
double type:
double[] arr = new double[] {1.38, 2.56, 4.3};
ArrayList:
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( new Supplier<ArrayList<Double>>() {
public ArrayList<Double> get() {
return( new ArrayList<Double>() );
}
} ) );
…and this creates the same compact and fast compilation as its Java 1.8 short-form:
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( ArrayList::new ) );
The Throwable class provides two methods named printStackTrace
, one that accepts a PrintWriter
and one that takes in a PrintStream
, that outputs the stack trace to the given stream. Consider using one of these.
I had the same problem, on Windows7.
I was getting error 2147942667 and a report of being unable to run c:\windows\system32\CMD.EXE. I tried with and without double quotes in the Script and Start-in and it made no difference. Then I tried replacing all path references to mapped network drives and with UNC references (\Server1\Sharexx\my_scripts\run_this.cmd) and that fixed it for me. Pat.
you can also user @RequestBody Map<String, String> params
,then use params.get("key")
to get the value of parameter
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.
This works for me.
dataset <- read.csv(file = "data.csv",header=TRUE,fill = T,na.strings = "")
Here's my effort to give a more complete answer (building on @john's answer).
The initial issue I encountered was changing the width and height of a canvas node (using styles), resulted in the contents just being "zoomed" or "shrunk." This was not the desired effect.
So, say you want to draw two rectangles of arbitrary size in a canvas that is 100px by 100px.
<canvas width="100" height="100"></canvas>
To ensure that the rectangles will not exceed the size of the canvas and therefore not be visible, you need to ensure that the canvas is big enough.
var $canvas = $('canvas'),
oldCanvas,
context = $canvas[0].getContext('2d');
function drawRects(x, y, width, height)
{
if (($canvas.width() < x+width) || $canvas.height() < y+height)
{
oldCanvas = $canvas[0].toDataURL("image/png")
$canvas[0].width = x+width;
$canvas[0].height = y+height;
var img = new Image();
img.src = oldCanvas;
img.onload = function (){
context.drawImage(img, 0, 0);
};
}
context.strokeRect(x, y, width, height);
}
drawRects(5,5, 10, 10);
drawRects(15,15, 20, 20);
drawRects(35,35, 40, 40);
drawRects(75, 75, 80, 80);
Finally, here's the jsfiddle for this: http://jsfiddle.net/Rka6D/4/ .
Two ways:
Example of #2:
int[,] arr = { { 1, 2 }, { 3, 4 } }; foreach(int a in arr) Console.Write(a);
Output will be 1234. ie. exactly the same as doing i from 0 to n, and j from 0 to n.
The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.
I decided to update the entire URL using window.history.replaceState
rather than using the window.location.hash
method. Thus circumventing the hashChange event fired by the browser.
// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {
// Prevent default anchor handling (which causes the page-jumping)
event.preventDefault();
if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if ( target.length ) {
// Smooth scrolling to anchor
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
// Update URL
window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
}
}
});
You can modify the whole InfoWindow using jquery alone...
var popup = new google.maps.InfoWindow({
content:'<p id="hook">Hello World!</p>'
});
Here the <p> element will act as a hook into the actual InfoWindow. Once the domready fires, the element will become active and accessible using javascript/jquery, like $('#hook').parent().parent().parent().parent()
.
The below code just sets a 2 pixel border around the InfoWindow.
google.maps.event.addListener(popup, 'domready', function() {
var l = $('#hook').parent().parent().parent().siblings();
for (var i = 0; i < l.length; i++) {
if($(l[i]).css('z-index') == 'auto') {
$(l[i]).css('border-radius', '16px 16px 16px 16px');
$(l[i]).css('border', '2px solid red');
}
}
});
You can do anything like setting a new CSS class or just adding a new element.
Play around with the elements to get what you need...
"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted
This depends on a lot of things, such as what is the size of the file, what is its type (text/binary) etc. Some time ago I benchmarked the following function against versions using streambuf iterators - it was about twice as fast:
unsigned int FileRead( std::istream & is, std::vector <char> & buff ) {
is.read( &buff[0], buff.size() );
return is.gcount();
}
void FileRead( std::ifstream & ifs, string & s ) {
const unsigned int BUFSIZE = 64 * 1024; // reasoable sized buffer
std::vector <char> buffer( BUFSIZE );
while( unsigned int n = FileRead( ifs, buffer ) ) {
s.append( &buffer[0], n );
}
}
Another way to achieve this is using old printf()
function of C language
You can use this like
int dd = 1, mm = 9, yy = 1;
printf("%02d - %02d - %04d", mm, dd, yy);
This will print 09 - 01 - 0001
on the console.
You can also use another function sprintf()
to write formatted output to a string like below:
int dd = 1, mm = 9, yy = 1;
char s[25];
sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
cout << s;
Don't forget to include stdio.h
header file in your program for both of these functions
You can fill blank space either by 0 or by another char (not number).
If you do write something like %24d
format specifier than this will not fill 2
in blank spaces. This will set pad to 24
and will fill blank spaces.
The minimal-ui viewport property is no longer supported in iOS 8. However, the minimal-ui itself is not gone. User can enter the minimal-ui with a "touch-drag down" gesture.
There are several pre-conditions and obstacles to manage the view state, e.g. for minimal-ui to work, there has to be enough content to enable user to scroll; for minimal-ui to persist, window scroll must be offset on page load and after orientation change. However, there is no way of calculating the dimensions of the minimal-ui using the screen
variable, and thus no way of telling when user is in the minimal-ui in advance.
These observations is a result of research as part of developing Brim – view manager for iOS 8. The end implementation works in the following way:
When page is loaded, Brim will create a treadmill element. Treadmill element is used to give user space to scroll. Presence of the treadmill element ensures that user can enter the minimal-ui view and that it continues to persist if user reloads the page or changes device orientation. It is invisible to the user the entire time. This element has ID
brim-treadmill
.Upon loading the page or after changing the orientation, Brim is using Scream to detect if page is in the minimal-ui view (page that has been previously in minimal-ui and has been reloaded will remain in the minimal-ui if content height is greater than the viewport height).
When page is in the minimal-ui, Brim will disable scrolling of the document (it does this in a safe way that does not affect the contents of the main element). Disabling document scrolling prevents accidentally leaving the minimal-ui when scrolling upwards. As per the original iOS 7.1 spec, tapping the top bar brings back the rest of the chrome.
The end result looks like this:
For the sake of documentation, and in case you prefer to write your own implementation, it is worth noting that you cannot use Scream to detect if device is in minimal-ui straight after the orientationchange event because window
dimensions do not reflect the new orientation until the rotation animation has ended. You have to attach a listener to the orientationchangeend event.
Scream and orientationchangeend have been developed as part of this project.
All of
std::string s(1, c); std::cout << s << std::endl;
and
std::cout << std::string(1, c) << std::endl;
and
std::string s; s.push_back(c); std::cout << s << std::endl;
worked for me.
when you want to check your all table structure with some filed then use this code. In this query i select column_name,column_type and table_name for more details . I use order by column_type so i can see it easily.
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' order by DATA_TYPE;
If you want to check only double type filed then you can do it easily
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME,DATA_TYPE
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' AND DATA_TYPE like '%bigint%' order by DATA_TYPE;
if you want to check which field allow null type etc then you can use this
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME,IS_NULLABLE,DATA_TYPE
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' and DATA_TYPE like '%bigint%' and IS_NULLABLE ='NO' order by COLUMN_TYPE;
you want to check more then thik link also help you.
I think you want $data[$category] = $question;
Or in case you want an array that maps categories to array of questions:
$data = array();
foreach($file_data as $value) {
list($category, $question) = explode('|', $value, 2);
if(!isset($data[$category])) {
$data[$category] = array();
}
$data[$category][] = $question;
}
print_r($data);
You have to create a symlink to your mysql installation if it is not the most recent version of mysql.
$ brew link --force [email protected]
try using the cloning technique.
{
DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
// then for each of the values use a loop like below.
int cc = yourdatagrid.Columns.Count;
for (int i2 = 0; i < cc; i2++)
{
row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
}
yourdatagrid.Rows.Add(row);
i++;
}
}
This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.
This is no longer up-to-date!
Push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.
Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.
Map can also be used, but sometimes hard to read when you have lots of things going on.
map{ print "element $_\n" } @array;
To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList?
Yes to the loop (either using indexes or an Iterator
). On the return value, either return its index, or the item iteself, depending on your needs. ArrayList
doesn't have an indexOf
(Object target, Comparator compare)` or similar. Now that Java is getting lambda expressions (in Java 8, ~March 2014), I expect we'll see APIs get methods that accept lambdas for things like this.
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
It's much easier with Swift 4
or Swift 4.2
inside your ViewDidLoad
method, define your button and add it to the navigation bar.
override func viewDidLoad() {
super.viewDidLoad()
let logoutBarButtonItem = UIBarButtonItem(title: "Logout", style: .done, target: self, action: #selector(logoutUser))
self.navigationItem.rightBarButtonItem = logoutBarButtonItem
}
then you need to define the function that you mentioned inside action parameter as below
@objc func logoutUser(){
print("clicked")
}
You need to add the @objc
prefix as it's still making use of the legacy stuff (Objective C).
You can use this helper class;
using System;
using System.Runtime.InteropServices;
/// <summary>
/// Provides detailed information about the host operating system.
/// </summary>
public static class OSInfo
{
#region BITS
/// <summary>
/// Determines if the current application is 32 or 64-bit.
/// </summary>
public static int Bits
{
get
{
return IntPtr.Size * 8;
}
}
#endregion BITS
#region EDITION
private static string s_Edition;
/// <summary>
/// Gets the edition of the operating system running on this computer.
/// </summary>
public static string Edition
{
get
{
if (s_Edition != null)
return s_Edition; //***** RETURN *****//
string edition = String.Empty;
OperatingSystem osVersion = Environment.OSVersion;
OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );
if (GetVersionEx( ref osVersionInfo ))
{
int majorVersion = osVersion.Version.Major;
int minorVersion = osVersion.Version.Minor;
byte productType = osVersionInfo.wProductType;
short suiteMask = osVersionInfo.wSuiteMask;
#region VERSION 4
if (majorVersion == 4)
{
if (productType == VER_NT_WORKSTATION)
{
// Windows NT 4.0 Workstation
edition = "Workstation";
}
else if (productType == VER_NT_SERVER)
{
if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
{
// Windows NT 4.0 Server Enterprise
edition = "Enterprise Server";
}
else
{
// Windows NT 4.0 Server
edition = "Standard Server";
}
}
}
#endregion VERSION 4
#region VERSION 5
else if (majorVersion == 5)
{
if (productType == VER_NT_WORKSTATION)
{
if ((suiteMask & VER_SUITE_PERSONAL) != 0)
{
// Windows XP Home Edition
edition = "Home";
}
else
{
// Windows XP / Windows 2000 Professional
edition = "Professional";
}
}
else if (productType == VER_NT_SERVER)
{
if (minorVersion == 0)
{
if ((suiteMask & VER_SUITE_DATACENTER) != 0)
{
// Windows 2000 Datacenter Server
edition = "Datacenter Server";
}
else if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
{
// Windows 2000 Advanced Server
edition = "Advanced Server";
}
else
{
// Windows 2000 Server
edition = "Server";
}
}
else
{
if ((suiteMask & VER_SUITE_DATACENTER) != 0)
{
// Windows Server 2003 Datacenter Edition
edition = "Datacenter";
}
else if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
{
// Windows Server 2003 Enterprise Edition
edition = "Enterprise";
}
else if ((suiteMask & VER_SUITE_BLADE) != 0)
{
// Windows Server 2003 Web Edition
edition = "Web Edition";
}
else
{
// Windows Server 2003 Standard Edition
edition = "Standard";
}
}
}
}
#endregion VERSION 5
#region VERSION 6
else if (majorVersion == 6)
{
int ed;
if (GetProductInfo( majorVersion, minorVersion,
osVersionInfo.wServicePackMajor, osVersionInfo.wServicePackMinor,
out ed ))
{
switch (ed)
{
case PRODUCT_BUSINESS:
edition = "Business";
break;
case PRODUCT_BUSINESS_N:
edition = "Business N";
break;
case PRODUCT_CLUSTER_SERVER:
edition = "HPC Edition";
break;
case PRODUCT_DATACENTER_SERVER:
edition = "Datacenter Server";
break;
case PRODUCT_DATACENTER_SERVER_CORE:
edition = "Datacenter Server (core installation)";
break;
case PRODUCT_ENTERPRISE:
edition = "Enterprise";
break;
case PRODUCT_ENTERPRISE_N:
edition = "Enterprise N";
break;
case PRODUCT_ENTERPRISE_SERVER:
edition = "Enterprise Server";
break;
case PRODUCT_ENTERPRISE_SERVER_CORE:
edition = "Enterprise Server (core installation)";
break;
case PRODUCT_ENTERPRISE_SERVER_CORE_V:
edition = "Enterprise Server without Hyper-V (core installation)";
break;
case PRODUCT_ENTERPRISE_SERVER_IA64:
edition = "Enterprise Server for Itanium-based Systems";
break;
case PRODUCT_ENTERPRISE_SERVER_V:
edition = "Enterprise Server without Hyper-V";
break;
case PRODUCT_HOME_BASIC:
edition = "Home Basic";
break;
case PRODUCT_HOME_BASIC_N:
edition = "Home Basic N";
break;
case PRODUCT_HOME_PREMIUM:
edition = "Home Premium";
break;
case PRODUCT_HOME_PREMIUM_N:
edition = "Home Premium N";
break;
case PRODUCT_HYPERV:
edition = "Microsoft Hyper-V Server";
break;
case PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT:
edition = "Windows Essential Business Management Server";
break;
case PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING:
edition = "Windows Essential Business Messaging Server";
break;
case PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY:
edition = "Windows Essential Business Security Server";
break;
case PRODUCT_SERVER_FOR_SMALLBUSINESS:
edition = "Windows Essential Server Solutions";
break;
case PRODUCT_SERVER_FOR_SMALLBUSINESS_V:
edition = "Windows Essential Server Solutions without Hyper-V";
break;
case PRODUCT_SMALLBUSINESS_SERVER:
edition = "Windows Small Business Server";
break;
case PRODUCT_STANDARD_SERVER:
edition = "Standard Server";
break;
case PRODUCT_STANDARD_SERVER_CORE:
edition = "Standard Server (core installation)";
break;
case PRODUCT_STANDARD_SERVER_CORE_V:
edition = "Standard Server without Hyper-V (core installation)";
break;
case PRODUCT_STANDARD_SERVER_V:
edition = "Standard Server without Hyper-V";
break;
case PRODUCT_STARTER:
edition = "Starter";
break;
case PRODUCT_STORAGE_ENTERPRISE_SERVER:
edition = "Enterprise Storage Server";
break;
case PRODUCT_STORAGE_EXPRESS_SERVER:
edition = "Express Storage Server";
break;
case PRODUCT_STORAGE_STANDARD_SERVER:
edition = "Standard Storage Server";
break;
case PRODUCT_STORAGE_WORKGROUP_SERVER:
edition = "Workgroup Storage Server";
break;
case PRODUCT_UNDEFINED:
edition = "Unknown product";
break;
case PRODUCT_ULTIMATE:
edition = "Ultimate";
break;
case PRODUCT_ULTIMATE_N:
edition = "Ultimate N";
break;
case PRODUCT_WEB_SERVER:
edition = "Web Server";
break;
case PRODUCT_WEB_SERVER_CORE:
edition = "Web Server (core installation)";
break;
}
}
}
#endregion VERSION 6
}
s_Edition = edition;
return edition;
}
}
#endregion EDITION
#region NAME
private static string s_Name;
/// <summary>
/// Gets the name of the operating system running on this computer.
/// </summary>
public static string Name
{
get
{
if (s_Name != null)
return s_Name; //***** RETURN *****//
string name = "unknown";
OperatingSystem osVersion = Environment.OSVersion;
OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );
if (GetVersionEx( ref osVersionInfo ))
{
int majorVersion = osVersion.Version.Major;
int minorVersion = osVersion.Version.Minor;
switch (osVersion.Platform)
{
case PlatformID.Win32Windows:
{
if (majorVersion == 4)
{
string csdVersion = osVersionInfo.szCSDVersion;
switch (minorVersion)
{
case 0:
if (csdVersion == "B" || csdVersion == "C")
name = "Windows 95 OSR2";
else
name = "Windows 95";
break;
case 10:
if (csdVersion == "A")
name = "Windows 98 Second Edition";
else
name = "Windows 98";
break;
case 90:
name = "Windows Me";
break;
}
}
break;
}
case PlatformID.Win32NT:
{
byte productType = osVersionInfo.wProductType;
switch (majorVersion)
{
case 3:
name = "Windows NT 3.51";
break;
case 4:
switch (productType)
{
case 1:
name = "Windows NT 4.0";
break;
case 3:
name = "Windows NT 4.0 Server";
break;
}
break;
case 5:
switch (minorVersion)
{
case 0:
name = "Windows 2000";
break;
case 1:
name = "Windows XP";
break;
case 2:
name = "Windows Server 2003";
break;
}
break;
case 6:
switch (productType)
{
case 1:
name = "Windows Vista";
break;
case 3:
name = "Windows Server 2008";
break;
}
break;
}
break;
}
}
}
s_Name = name;
return name;
}
}
#endregion NAME
#region PINVOKE
#region GET
#region PRODUCT INFO
[DllImport( "Kernel32.dll" )]
internal static extern bool GetProductInfo(
int osMajorVersion,
int osMinorVersion,
int spMajorVersion,
int spMinorVersion,
out int edition );
#endregion PRODUCT INFO
#region VERSION
[DllImport( "kernel32.dll" )]
private static extern bool GetVersionEx( ref OSVERSIONINFOEX osVersionInfo );
#endregion VERSION
#endregion GET
#region OSVERSIONINFOEX
[StructLayout( LayoutKind.Sequential )]
private struct OSVERSIONINFOEX
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
[MarshalAs( UnmanagedType.ByValTStr, SizeConst = 128 )]
public string szCSDVersion;
public short wServicePackMajor;
public short wServicePackMinor;
public short wSuiteMask;
public byte wProductType;
public byte wReserved;
}
#endregion OSVERSIONINFOEX
#region PRODUCT
private const int PRODUCT_UNDEFINED = 0x00000000;
private const int PRODUCT_ULTIMATE = 0x00000001;
private const int PRODUCT_HOME_BASIC = 0x00000002;
private const int PRODUCT_HOME_PREMIUM = 0x00000003;
private const int PRODUCT_ENTERPRISE = 0x00000004;
private const int PRODUCT_HOME_BASIC_N = 0x00000005;
private const int PRODUCT_BUSINESS = 0x00000006;
private const int PRODUCT_STANDARD_SERVER = 0x00000007;
private const int PRODUCT_DATACENTER_SERVER = 0x00000008;
private const int PRODUCT_SMALLBUSINESS_SERVER = 0x00000009;
private const int PRODUCT_ENTERPRISE_SERVER = 0x0000000A;
private const int PRODUCT_STARTER = 0x0000000B;
private const int PRODUCT_DATACENTER_SERVER_CORE = 0x0000000C;
private const int PRODUCT_STANDARD_SERVER_CORE = 0x0000000D;
private const int PRODUCT_ENTERPRISE_SERVER_CORE = 0x0000000E;
private const int PRODUCT_ENTERPRISE_SERVER_IA64 = 0x0000000F;
private const int PRODUCT_BUSINESS_N = 0x00000010;
private const int PRODUCT_WEB_SERVER = 0x00000011;
private const int PRODUCT_CLUSTER_SERVER = 0x00000012;
private const int PRODUCT_HOME_SERVER = 0x00000013;
private const int PRODUCT_STORAGE_EXPRESS_SERVER = 0x00000014;
private const int PRODUCT_STORAGE_STANDARD_SERVER = 0x00000015;
private const int PRODUCT_STORAGE_WORKGROUP_SERVER = 0x00000016;
private const int PRODUCT_STORAGE_ENTERPRISE_SERVER = 0x00000017;
private const int PRODUCT_SERVER_FOR_SMALLBUSINESS = 0x00000018;
private const int PRODUCT_SMALLBUSINESS_SERVER_PREMIUM = 0x00000019;
private const int PRODUCT_HOME_PREMIUM_N = 0x0000001A;
private const int PRODUCT_ENTERPRISE_N = 0x0000001B;
private const int PRODUCT_ULTIMATE_N = 0x0000001C;
private const int PRODUCT_WEB_SERVER_CORE = 0x0000001D;
private const int PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT = 0x0000001E;
private const int PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY = 0x0000001F;
private const int PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING = 0x00000020;
private const int PRODUCT_SERVER_FOR_SMALLBUSINESS_V = 0x00000023;
private const int PRODUCT_STANDARD_SERVER_V = 0x00000024;
private const int PRODUCT_ENTERPRISE_SERVER_V = 0x00000026;
private const int PRODUCT_STANDARD_SERVER_CORE_V = 0x00000028;
private const int PRODUCT_ENTERPRISE_SERVER_CORE_V = 0x00000029;
private const int PRODUCT_HYPERV = 0x0000002A;
#endregion PRODUCT
#region VERSIONS
private const int VER_NT_WORKSTATION = 1;
private const int VER_NT_DOMAIN_CONTROLLER = 2;
private const int VER_NT_SERVER = 3;
private const int VER_SUITE_SMALLBUSINESS = 1;
private const int VER_SUITE_ENTERPRISE = 2;
private const int VER_SUITE_TERMINAL = 16;
private const int VER_SUITE_DATACENTER = 128;
private const int VER_SUITE_SINGLEUSERTS = 256;
private const int VER_SUITE_PERSONAL = 512;
private const int VER_SUITE_BLADE = 1024;
#endregion VERSIONS
#endregion PINVOKE
#region SERVICE PACK
/// <summary>
/// Gets the service pack information of the operating system running on this computer.
/// </summary>
public static string ServicePack
{
get
{
string servicePack = String.Empty;
OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );
if (GetVersionEx( ref osVersionInfo ))
{
servicePack = osVersionInfo.szCSDVersion;
}
return servicePack;
}
}
#endregion SERVICE PACK
#region VERSION
#region BUILD
/// <summary>
/// Gets the build version number of the operating system running on this computer.
/// </summary>
public static int BuildVersion
{
get
{
return Environment.OSVersion.Version.Build;
}
}
#endregion BUILD
#region FULL
#region STRING
/// <summary>
/// Gets the full version string of the operating system running on this computer.
/// </summary>
public static string VersionString
{
get
{
return Environment.OSVersion.Version.ToString();
}
}
#endregion STRING
#region VERSION
/// <summary>
/// Gets the full version of the operating system running on this computer.
/// </summary>
public static Version Version
{
get
{
return Environment.OSVersion.Version;
}
}
#endregion VERSION
#endregion FULL
#region MAJOR
/// <summary>
/// Gets the major version number of the operating system running on this computer.
/// </summary>
public static int MajorVersion
{
get
{
return Environment.OSVersion.Version.Major;
}
}
#endregion MAJOR
#region MINOR
/// <summary>
/// Gets the minor version number of the operating system running on this computer.
/// </summary>
public static int MinorVersion
{
get
{
return Environment.OSVersion.Version.Minor;
}
}
#endregion MINOR
#region REVISION
/// <summary>
/// Gets the revision version number of the operating system running on this computer.
/// </summary>
public static int RevisionVersion
{
get
{
return Environment.OSVersion.Version.Revision;
}
}
#endregion REVISION
#endregion VERSION
}
Sample code is here:
Console.WriteLine( "Operation System Information" );
Console.WriteLine( "----------------------------" );
Console.WriteLine( "Name = {0}", OSInfo.Name );
Console.WriteLine( "Edition = {0}", OSInfo.Edition );
Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
Console.WriteLine( "Version = {0}", OSInfo.VersionString );
Console.WriteLine( "Bits = {0}", OSInfo.Bits );
I was found at this address : http://www.csharp411.com/wp-content/uploads/2009/01/OSInfo.cs
It is actually a 3 step process to connect to a PostgreSQL server remotely through pgAdmin3.
Note: I use Ubuntu 11.04 and PostgreSQL 8.4.
You have to make PostgreSQL listening for remote incoming TCP connections because the default settings allow to listen only for connections on the loopback interface. To be able to reach the server remotely you have to add the following line into the file /etc/postgresql/8.4/main/postgresql.conf:
listen_addresses = '*'
PostgreSQL by default refuses all connections it receives from any remote address, you have to relax these rules by adding this line to /etc/postgresql/8.4/main/pg_hba.conf:
host all all 0.0.0.0/0 md5
This is an access control rule that let anybody login in from any address if he can provide a valid password (the md5 keyword). You can use needed network/mask instead of 0.0.0.0/0 .
When you have applied these modifications to your configuration files you need to restart PostgreSQL server. Now it is possible to login to your server remotely, using the username and password.
For global use, you may use:
$val = $_REQUEST['subject'];
and to add yo your session, simply
session_start();
$_SESSION['subject'] = $val;
And you dont need jQuery in this case.
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
content
</body>
<script type="text/javascript">
$("body").load(url);
</script>
</html>
The SHGetFileInfo
(Check pinvoke.net for the signature) lets you retrieve a small or large icon, just as if you were dealing with a file/folder/Shell item.
I created this as an answer to your question and my own confusion. I hope it helps. Pay attention to PYTHONPATH in both the py.test command line and in the tox.ini.
https://github.com/jeffmacdonald/pytest_test
Specifically: You have to tell py.test and tox where to find the modules you are including.
With py.test you can do this:
PYTHONPATH=. py.test
And with tox, add this to your tox.ini:
[testenv]
deps= -r{toxinidir}/requirements.txt
commands=py.test
setenv =
PYTHONPATH = {toxinidir}
Add this import <%@page import="java.util.Map" %>
This worked for me, but I also needed to add <%@ page import="java.util.HashMap" %>.
It seems that the above answer is true, that if you have the newer tomcat you might not need to add these lines, but as I could not change my whole system, this worked.
Thank you
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
// Merge object2 into object1
$.extend( object1, object2 );
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8001,suspend=y -jar target/cxf-boot-simple-0.0.1-SNAPSHOT.jar
address
specifies the port at which it will allow to debug
**Debug Spring Boot app with Maven:
mvn spring-boot:run -Drun.jvmArguments=**"-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8001"
//this should allow you to replica an animation effect for any css property, even //properties //that transform animation jQuery plugins do not allow
function twistMyElem(){
var ball = $('#form');
document.getElementById('form').style.zIndex = 1;
ball.animate({ zIndex : 360},{
step: function(now,fx){
ball.css("transform","rotateY(" + now + "deg)");
},duration:3000
}, 'linear');
}
# The following would be a very simple solution.
print("")
string = input("Enter your string :")
noofspacesinstring = 0
for counter in string:
if counter == " ":
noofspacesinstring += 1
if noofspacesinstring == 0:
message = "Your string is a single word"
else:
message = "Your string is not a single word"
print("")
print(message)
print("")
Broadcast Receivers timeout after 10 seconds. Possibly your doing an asynchronous call (wrong) from a broadcast receiver and 4.3 actually detects it.
The best way to achieve is by defining __slots__
. That way your instances can't have new attributes.
ks = ['ab', 'cd']
vs = [12, 34]
class C(dict):
__slots__ = []
def __init__(self, ks, vs): self.update(zip(ks, vs))
def __getattr__(self, key): return self[key]
if __name__ == "__main__":
c = C(ks, vs)
print c.ab
That prints 12
c.ab = 33
That gives: AttributeError: 'C' object has no attribute 'ab'
Try array_merge.
$array1 = array('Item 1');
$array2 = array('Item 2');
$array3 = array_merge($array1, $array2);
I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.