I faced difficulties using "window.URL" with Opera Browser as it would result to "undefined". Also, with window.URL, the PDF document never opened in Internet Explorer and Microsoft Edge (it would remain waiting forever). I came up with the following solution that works in IE, Edge, Firefox, Chrome and Opera (have not tested with Safari):
$http.post(postUrl, data, {responseType: 'arraybuffer'})
.success(success).error(failed);
function success(data) {
openPDF(data.data, "myPDFdoc.pdf");
};
function failed(error) {...};
function openPDF(resData, fileName) {
var ieEDGE = navigator.userAgent.match(/Edge/g);
var ie = navigator.userAgent.match(/.NET/g); // IE 11+
var oldIE = navigator.userAgent.match(/MSIE/g);
var blob = new window.Blob([resData], { type: 'application/pdf' });
if (ie || oldIE || ieEDGE) {
window.navigator.msSaveBlob(blob, fileName);
}
else {
var reader = new window.FileReader();
reader.onloadend = function () {
window.location.href = reader.result;
};
reader.readAsDataURL(blob);
}
}
Let me know if it helped! :)
BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;
So 2 basic things to get string visible in the different class:
//make sure you are importing the right R class
import your.namespace.R;
//don't forget about the context
public void some_method(Context context) {
context.getString(R.string.YOUR_STRING);
}
"hard coding" means putting something into your source code. If you are not hard coding, then you do something like prompting the user for the data, or allow the user to put the data on the command line, or something like that.
So, to hard code the location of the file as being on the C: drive, you would just put the pathname of the file all together in your source code.
Here is an example.
int main()
{
const char *filename = "C:\\myfile.txt";
printf("Filename is: %s\n", filename);
}
The file name is "hard coded" as: C:\myfile.txt
The reason the backslash is doubled is because backslashes are special in C strings.
x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)
this is very basic method to send plain text email using mail function.
<?php
$to = '[email protected]';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <[email protected]>";
mail($to,$subject,$message,$from);
// works also after bind operation for WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
The task can be solved using the following piece of code, [0:28] being interval where the name is being held, while [29:34] contains the actual pid.
import os
program_pid = 0
program_name = "notepad.exe"
task_manager_lines = os.popen("tasklist").readlines()
for line in task_manager_lines:
try:
if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces
program_pid = int(line[29:34])
break
except:
pass
print(program_pid)
Here's a solution I came up with to generate aesthetically pleasing pastel colours based on an input string. It uses the first two chars of the string as a random seed, then generates R/G/B based on that seed.
It could be easily extended so that the seed is the XOR of all chars in the string, rather than just the first two.
Inspired by David Crow's answer here: Algorithm to randomly generate an aesthetically-pleasing color palette
//magic to convert strings to a nice pastel colour based on first two chars
//
// every string with the same first two chars will generate the same pastel colour
function pastel_colour(input_str) {
//TODO: adjust base colour values below based on theme
var baseRed = 128;
var baseGreen = 128;
var baseBlue = 128;
//lazy seeded random hack to get values from 0 - 256
//for seed just take bitwise XOR of first two chars
var seed = input_str.charCodeAt(0) ^ input_str.charCodeAt(1);
var rand_1 = Math.abs((Math.sin(seed++) * 10000)) % 256;
var rand_2 = Math.abs((Math.sin(seed++) * 10000)) % 256;
var rand_3 = Math.abs((Math.sin(seed++) * 10000)) % 256;
//build colour
var red = Math.round((rand_1 + baseRed) / 2);
var green = Math.round((rand_2 + baseGreen) / 2);
var blue = Math.round((rand_3 + baseBlue) / 2);
return { red: red, green: green, blue: blue };
}
GIST is here: https://gist.github.com/ro-sharp/49fd46a071a267d9e5dd
You need to CAST
the ParentId
as an nvarchar
, so that the output is always the same data type.
SELECT Id 'PatientId',
ISNULL(CAST(ParentId as nvarchar(100)),'') 'ParentId'
FROM Patients
select propety
Row Source Type => Value List
Code :
ListbName.ColumnCount=2
ListbName.AddItem "value column1;value column2"
The script from @larsmans, a bit improved:
#!/bin/sh
set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
if ["$branch" -ne "$CURRENT"]; then
git checkout "$branch" || exit 1
git rebase "origin/$branch" || exit 1
fi
done
git checkout "$CURRENT" || exit 1
git rebase "origin/$CURRENT" || exit 1
This, after it finishes, leaves working copy checked out from the same branch as it was before the script was called.
The git pull
version:
#!/bin/sh
set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
if ["$branch" -ne "$CURRENT"]; then
git checkout "$branch" || exit 1
git pull || exit 1
fi
done
git checkout "$CURRENT" || exit 1
git pull || exit 1
You don't mention if this is an anonymous PL/SQL block or a declarative one ie. Package, Procedure or Function. However, in PL/SQL a COMMIT must be explicitly made to save your transaction(s) to the database. The COMMIT actually saves all unsaved transactions to the database from your current user's session.
If an error occurs the transaction implicitly does a ROLLBACK.
This is the default behaviour for PL/SQL.
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?
) as the request body.
This requires Content-Type
and Content-Length
headers, so the receiving server knows how to interpret the incoming data. (*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded
for the traditional format that a standard HTML form would use.
It's easy to send JSON (application/json
) in exactly the same manner; just JSON.stringify()
the data beforehand.
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
The bottom line is: The server must be able to interpret the content type in question. It could be text/plain
or anything else; there is no need to convert data if the receiving server understands it as it is.
Add a charset parameter (e.g. application/json; charset=Windows-1252
) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
I had the same issue. In my home folder I've got a script named sqlplus.sh that takes care of this for me, containing:
ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export ORACLE_HOME
ORACLE_SID=XE
export ORACLE_SID
NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export NLS_LANG
PATH=$ORACLE_HOME/bin:$PATH
export PATH
sqlplus /nolog
You can using the EventLog class, as explained on How to: Write to the Application Event Log (Visual C#):
var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");
However, you'll need to configure this source "MySource" using administrative privileges:
Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.
Use the following code in your controller:
return Json(new { success = string }, JsonRequestBehavior.AllowGet);
and in JavaScript:
success: function (data) {
var response = data.success;
....
}
As nobody answer, I try something :
I think I understand why Attent one does not work. It's because joining a computer to a domain is somehow also renaming the computer (the domain name part, enter in the name of the machine).
So do you try to do it in full WMI way, you've got a method in Win32_ComputerSystem
class called JoinDomainOrWorkgroup
. Doing it on the same level perhaps gives you more chance to make it work.
The message usually comes when you put the wrong image name. Please check your image if it exists on the Docker repository with the correct tag. It helped me.
docker run -d -p 80:80 --name ngnix ngnix:latest
Unable to find image 'ngnix:latest' locally
docker: Error response from daemon: pull access denied for ngnix, repository does not exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
$ docker run -d -p 80:80 --name nginx nginx:latest
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
Komodo IDE works well with xdebug, even for the remore debugging. It needs minimum amount of configuration. All you need is a version of php that Komodo can use locally to step through the code on a breakpoint. If you have the script imported into komodo project, then you can set breakpoints with a mouse-click just how you would set it inside eclipse for debugging a java program. Remote debugging is obviously more tricky to get it to work correctly ( you might have to map the remote url with a php script in your workspace ) than a local debugging setup which is pretty easy to configure if you are on a MAC or a linux desktop.
Better use PHP_EOL ("End Of Line") instead. It's cross-platform.
E.g.:
$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';
To update the local list of remote branches:
git remote update origin --prune
To show all local and remote branches that (local) Git knows about
git branch -a
This stuff here is actively maintained and so far is my favorite: xml2json in python
Bit late response to this question, however I do have something to add that might be useful for others.
If you make use of an iFrame and set the pdf file path to the src, it will load zoomed out to 100%, which the equivalence of FitH
Per google official documentation, use %1$s and %2$s http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
Hello, %1$s! You have %2$d new messages.
Logical Processing Order of the SELECT statement
The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE or WITH ROLLUP
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- TOP
Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx
Deleting Elements in an Array if Element is a Certain value VBA
to delete elements in an Array wih certain condition, you can code like this
For i = LBound(ArrValue, 2) To UBound(ArrValue, 2)
If [Certain condition] Then
ArrValue(1, i) = "-----------------------"
End If
Next i
StrTransfer = Replace(Replace(Replace(join(Application.Index(ArrValue(), 1, 0), ","), ",-----------------------,", ",", , , vbBinaryCompare), "-----------------------,", "", , , vbBinaryCompare), ",-----------------------", "", , , vbBinaryCompare)
ResultArray = join( Strtransfer, ",")
I often manipulate 1D-Array with Join/Split but if you have to delete certain value in Multi Dimension I suggest you to change those Array into 1D-Array like this
strTransfer = Replace(Replace(Replace(Replace(Names.Add("A", MultiDimensionArray), Chr(34), ""), "={", ""), "}", ""), ";", ",")
'somecode to edit Array like 1st code on top of this comment
'then loop through this strTransfer to get right value in right dimension
'with split function.
WordPress include tags, categories and taxonomies in search results
This code is taken from http://atiblog.com/custom-search-results/
Some functions here are taken from twentynineteen theme.Because it is made on this theme.
This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.
You need to modify your search.php of your theme to do so.
<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) );
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );
$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();
foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}
foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}
foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}
$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));
$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {
}
?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {
}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {
}
?>
You don't mention the API version, but since API 11 there's the method WebViewClient.shouldInterceptRequest
Maybe this could help?
The entity type 'DisplayFormatAttribute' requires a primary key to be defined.
In my case I figured out the problem was that I used properties like this:
public string LastName { get; set; } //OK
public string Address { get; set; } //OK
public string State { get; set; } //OK
public int? Zip { get; set; } //OK
public EmailAddressAttribute Email { get; set; } // NOT OK
public PhoneAttribute PhoneNumber { get; set; } // NOT OK
Not sure if there is a better way to solve it but I changed the Email and PhoneNumber attribute to a string. Problem solved.
While the answers with List<T>.ForEach
are very good.
I found String.Join<T>(string separator, IEnumerable<T> values)
method more useful.
Example :
List<string> numbersStrLst = new List<string>
{ "One", "Two", "Three","Four","Five"};
Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"
int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"
Remarks :
If separator is null, an empty string (String.Empty
) is used instead. If any member of values is null, an empty string is used instead.
Join(String, IEnumerable<String>)
is a convenience method that lets you concatenate each element in an IEnumerable(Of String) collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.
This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String, Object[])
Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx
You might output your DataFrame
as a csv file and then use mysqlimport
to import your csv into your mysql
.
Seems pandas's build-in sql util provide a write_frame
function but only works in sqlite.
I found something useful, you might try this
another way to find last highest data based on date
SELECT A.JID,A.EntryDate,RefundDate,Comments,Refund, ActionBy FROM (
(select JID, Max(EntryDate) AS EntryDate from refundrequested GROUP BY JID) A
Inner JOIN (SELECT JID,ENTRYDATE,refundDate,Comments,refund,ActionBy from refundrequested) B
ON A.JID=B.JID AND A.EntryDate = B.EntryDate)
db.find({ pictures: { $elemMatch: { $exists: true } } })
$elemMatch
matches documents that contain an array field with at least one element that matches the specified query.
So you're matching all arrays with at least an element.
To unlock a file in your working copy from command prompt that is currently locked by another user, use --force
option.
$ svn unlock --force tree.jpg
There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.
While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
I've found this the easy fix, simply add this to the css:
cursor: pointer;
The following will return you the "a" letter:
$a = array_shift(explode('.', 'a.b'));
Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
(which references 32-bit programs) for part of the name of the program, or
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
(if it actually was a 64-bit program).
If you find something that matches your program in one of those, the contents of UninstallString
in that key usually give you the exact command you are looking for (that you can run in a script).
If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.
Then in a .bat script you can do
if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
I'd say use <em>
to emphasize inline elements. Use a class for block elements like blocks of text. CSS or not, the text still has to be tagged. Whether its for semantics or for visual aid, I'm assuming you'd be using it for something meaningful...
If you're emphasizing text for ANY reason, you could use <em>
, or a class that italicizes your text.
It's OK to break the rules sometimes!
<script type = "text/javascript">
function DisableButtons() {
var inputs = document.getElementsByTagName("INPUT");
for (var i in inputs) {
if (inputs[i].type == "button" || inputs[i].type == "submit") {
inputs[i].disabled = true;
}
}
}
window.onbeforeunload = DisableButtons;
</script>
Installing modules usually requires you to run an sql script that is included with the database installation.
Assuming linux-like OS
find / -name dblink.sql
Verify the location and run it
For different values of k, the approach will be different so there won't be a generic answer in terms of k. For example, for k=1 one can take advantage of the sum of natural numbers, but for k = n/2, one has to use some kind of bitset. The same way for k=n-1, one can simply compare the only number in the bag with the rest.
To answer the first part of your question:
LPCSTR
is a pointer to a const string (LP means Long Pointer)
LPCTSTR
is a pointer to a const TCHAR
string, (TCHAR
being either a wide char or char depending on whether UNICODE is defined in your project)
LPTSTR
is a pointer to a (non-const) TCHAR
string
In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.
This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)
Instead of images i choose background option:
HTML:
<div class="class1">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
<div class="class2">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
<div class="class3">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
CSS:
.class1 {
background: url("Some.png") no-repeat top center;
text-align: center;
}
.class2 {
background: url("Some2.png") no-repeat top center;
text-align: center;
}
.class3 {
background: url("Some3.png") no-repeat top center;
text-align: center;
}
In your Safari menu bar click Safari > Preferences & then select the Advanced tab.
Select: "Show Develop menu in menu bar"
Now you can click Develop in your menu bar and choose Show Web Inspector
You can also right-click and press "Inspect element".
These examples are fine, I wanted to point out that you can achieve the same result using an Intent. The intent opens the Contacts app with the fields you provide already filled in.
It's up to the user to save the newly created contact.
You can read about it here: https://developer.android.com/training/contacts-provider/modify-data.html
Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
contactIntent
.putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
.putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");
startActivityForResult(contactIntent, 1);
startActivityForResult() gives you the opportunity to see the result.
I've noticed the resultCode works on >5.0 devices,
but I have an older Samsung (<5) that always returns RESULT_CANCELLED (0).
Which I understand is the default return if an activity doesn't expect to return anything.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == 1)
{
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
}
}
}
Set a cookie:
res.cookie('cookie', 'monster')
https://expressjs.com/en/4x/api.html#res.cookie
Read a cookie:
(using cookie-parser middleware)
req.cookies['cookie']
You should use urllib2, like this:
import urllib2
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
try:
connection = urllib2.urlopen(url)
print connection.getcode()
connection.close()
except urllib2.HTTPError, e:
print e.getcode()
# Prints:
# 200 [from the try block]
# 404 [from the except block]
From Wikipedia:
Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).
So as others mentioned, it's a convention.
This is quite an old conversation by now and apache commons are now using a StringBuilder internally: http://commons.apache.org/lang/api/src-html/org/apache/commons/lang/StringUtils.html#line.3045
This will as we know improve performance, but if performance is critical then the method used might be somewhat inefficient. Whereas the interface is flexible and will allow for consistent behaviour across different Collection types it is somewhat inefficient for Lists, which is the type of Collection in the original question.
I base this in that we are incurring some overhead which we would avoid by simply iterating through the elements in a traditional for loop. Instead there are some additional things happening behind the scenes checking for concurrent modifications, method calls etc. The enhanced for loop will on the other hand result in the same overhead since the iterator is used on the Iterable object (the List).
Put in other words, this error is telling you that SQL Server does not know which B
to select from the group.
Either you want to select one specific value (e.g. the MIN
, SUM
, or AVG
) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B
in the GROUP BY
field list).
Consider the following data:
ID A B 1 1 13 1 1 79 1 2 13 1 2 13 1 2 42
The query
SELECT A, COUNT(B) AS T1
FROM T2
GROUP BY A
would return:
A T1 1 2 2 3
which is all well and good.
However consider the following (illegal) query, which would produce this error:
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A
And its returned data set illustrating the problem:
A T1 B 1 2 13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...? 2 3 13? 42? ...?
However, the following two queries make this clear, and will not cause the error:
Using an aggregate
SELECT A, COUNT(B) AS T1, SUM(B) AS B
FROM T2
GROUP BY A
would return:
A T1 B 1 2 92 2 3 68
Adding the column to the GROUP BY
list
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A, B
would return:
A T1 B 1 1 13 1 1 79 2 2 13 2 1 42
pathinfo is cool but your code can be improved:
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = array('jpg','png','gif');
if( ! in_array( $ext, $allowed ) ) {echo 'error';}
Of course simply checking the extension of the filename would not guarantee the file type as a valid image. You may consider using a function like getimagesize
to validate uploaded image files.
No, he must have been confused about the MD5 dictionaries.
Cryptographic hashes (MD5, etc...) are one way and you can't get back to the original message with only the digest unless you have some other information about the original message, etc. that you shouldn't.
In Route.config
namespaces: new[] { "Appname.Controllers" }
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
suport all iphones, all ipads, all androids.
#/bin/bash
#pgm to monitor
tail -f /var/log/messages >> /tmp/log&
# background cmd pid
pid=$!
# loop to monitor running background cmd
while :
do
ps ax | grep $pid | grep -v grep
ret=$?
if test "$ret" != "0"
then
echo "Monitored pid ended"
break
fi
sleep 5
done
wait $pid
echo $?
This problem is due to the https protocol, which is why the other solution works (by switching to the non-secure protocol).
For me, the best solution was to compile the latest version of node, which includes npm
apt-get purge nodejs npm
git clone https://github.com/nodejs/node ~/local/node
cd ~/local/node
./configure
make
make install
The point is semantics. In assertTrue, you are asserting that the expression is true. If it is not, then it will display the message and the assertion will fail. In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails.
assertTrue (message, value == false) == assertFalse (message, value);
These are functionally the same, but if you are expecting a value to be false then use assertFalse
. If you are expecting a value to be true, then use assertTrue
.
Use the ngOnChanges()
lifecycle method in your component.
ngOnChanges is called right after the data-bound properties have been checked and before view and content children are checked if at least one of them has changed.
Here are the Docs.
depending on who is going to be using your database, for example African names will do with varchar(20) for last name and first name separated. however it is different from nation to nation but for the sake saving your database resources and memory, separate last name and first name fields and use varchar(30) think that will work.
I notice you are using windows, which is particularly bad about using low port numbers for outgoing sockets. See here for how to reserve the port number that you want to rely on using for glassfish.
UPDATE
The bookmarklet hack below is broken due to XHR issues and API changes.
Thankfully Github now has "A Whole New Code Search" which does the job superbly.
Checkout this voodoo: Github code search userscript.
Follow the directions there, or if you hate bloating your browser with scripts and extensions, use my bookmarkified bundle of the userscript:
javascript:(function(){var s='https://raw.githubusercontent.com/skratchdot/github-enhancement-suite/master/build/github-enhancement-suite.user.js',t='text/javascript',d=document,n=navigator,e;(e=d.createElement('script')).src=s;e.type=t;d.getElementsByTagName('head')[0].appendChild(e)})();doIt('');void('');
Save the source above as the URL of a new bookmark. Browse to any Github repo, click the bookmark, and bam: in-page, ajaxified code search.
CAVEAT Github must index a repo before you can search it.
Abracadabra...
Here's a sample search from the annotated ECMAScript 5.1 specification repository:
I will use CXF also you can think of AXIS 2 .
The best way to do it may be using JAX RS Refer this example
Example:
wsimport -p stockquote http://stockquote.xyz/quote?wsdl
This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.
I
You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap
A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.
import extname in order to return the extension the file:
import { extname } from 'path';
extname(file.originalname);
where file is the file 'name' of form
You can get the element in JQuery by using its ID attribute like this:
$("#tcol1").hide();
<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a>
</span>
</span>
</div>
I just put them in their own file and export it for node and webpack:
// lodash-cherries.js
module.exports = {
defaults: require('lodash/defaults'),
isNil: require('lodash/isNil'),
isObject: require('lodash/isObject'),
isArray: require('lodash/isArray'),
isFunction: require('lodash/isFunction'),
isInteger: require('lodash/isInteger'),
isBoolean: require('lodash/isBoolean'),
keys: require('lodash/keys'),
set: require('lodash/set'),
get: require('lodash/get'),
}
I was also getting same error when I start first time on laravel + Ubuntu 14.04 I just right click on bootstrap and storage folder >>> properties >>>permission>> Others Access >>> change it to "Create and delete files" Change permission for enclosed files
Thank you
The tutorial Android Custom Navigation Drawer (via archive.org) contains a basic and a custom project. The latter shows how to setup a Navigation Drawer as shown in the screenshot:
The source code of the projects (via archive.org) is available for download.
The is also the Navigation Drawer - Live-O project ...
The source code of the project is available on GitHub.
The MaterialDrawer library aims to provide the easiest possible implementation of a navigation drawer for your application. It provides a great amount of out of the box customizations and also includes an easy to use header which can be used as AccountSwitcher.
Please note that Android Studio meanwhile has a template project to create a Navigation Drawer Activity as shown in the screenshot.
This repository keeps track of changes being made to the template.
Try the SetField method:
table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);
This should get the job done and is a bit "cleaner" than using Rows[i][j].
Well I needed something that would reduce seconds into hours minutes and seconds, but would exceed 24 hours, and not reduce further down into days.
Here is a simple function that works. You can probably improve it... But here it is:
function formatSeconds($seconds)
{
$hours = 0;$minutes = 0;
while($seconds >= 60){$seconds -= 60;$minutes++;}
while($minutes >= 60){$minutes -=60;$hours++;}
$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $hours.":".$minutes.":".$seconds;
}
try this ,hope it helps
select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
CASE
WHEN invitee_status=1 THEN "attending"
WHEN invitee_status=2 THEN "unsure"
WHEN invitee_status=3 THEN "declined"
WHEN invitee_status=0 THEN "notreviwed" END
) AS invitee_status
FROM your_tbl
Ctrl+K, Ctrl+D - Format the current document.
Helped me fix indentation and remove unneeded spaces quickly
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "
Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
To be clear, you want to made your decision based on how much of the parameters are logical TRUE (in case of string arguments - not empty)?
argsne = (1 if a else 0) + (1 if b else 0) + (1 if c else 0)
Then you made a decision:
if ( 0 < argsne < 3 ):
doSth()
Now the logic is more clear.
.live was removed in 1.9, please see the upgrade guide: http://jquery.com/upgrade-guide/1.9/#live-removed
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
// read item
}
}
}
Or, if you need the column info:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
object item = row[column];
// read column and item
}
}
}
I thought Sequel Pro for MySQL looked pretty interesting. It's hard to find one tool that works with all those databases (especially SQL Server 2005 . . . most people use SQL Server Management Studio and that's Windows only of course).
@Someone Somewhere I used this to clear focus:
editText.clearFocus();
and it helps
SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.
As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.
Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.
As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).
Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.
The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.
Some of the anwsers above, don't work well when rotating device.
Try:
CGRect imageContent = self.myUIImage.bounds;
CGFloat imageWidth = imageContent.size.width;
CGFloat imageHeight = imageContent.size.height;
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
stopPropagation
prevents further propagation of the current event in the capturing and bubbling phases.
preventDefault
prevents the default action the browser makes on that event.
preventDefault
$("#but").click(function (event) {
event.preventDefault()
})
$("#foo").click(function () {
alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
_x000D_
stopPropagation
$("#but").click(function (event) {
event.stopPropagation()
})
$("#foo").click(function () {
alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
_x000D_
With stopPropagation
, only the button
's click handler is called while the div
's click handler never fires.
Where as if you use preventDefault
, only the browser's default action is stopped but the div's click handler still fires.
Below are some docs on the DOM event properties and methods from MDN:
For IE9 and FF you can just use preventDefault & stopPropagation.
To support IE8 and lower replace stopPropagation
with cancelBubble
and replace preventDefault
with returnValue
You can do it in in-place by doing only one pass:
function transpose(arr,arrLen) {
for (var i = 0; i < arrLen; i++) {
for (var j = 0; j <i; j++) {
//swap element[i,j] and element[j,i]
var temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
You use new
to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.
You have no reason to use new
, since A
is an automatic variable. You can simply initialise A
using its constructor:
vector<vector<int> > A(dimension, vector<int>(dimension));
I'm a beginner but...Up to my knowledge,the best way is
strncpy(dest_string,"",strlen(dest_string));
You can also do this by passing function with onclick event
<a onclick="getColor(this);" color="red">
<script type="text/javascript">
function getColor(el)
{
color = $(el).attr('color');
alert(color);
}
</script>
Try something like this:
SELECT
*
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks
Specify the paths explicitly:
git diff HEAD:full/path/to/foo full/path/to/bar
Check out the --find-renames
option in the git-diff
docs.
Credit: twaggs.
Another way could be through adding .LNK
to your $PATHEX.
Then just create a shortcut to your executable (ie: yourshortcut.lnk) and put it into any of the directories listed within $PATH.
WARNING NOTE: Know that any .lnk files located in any directories listed in your $PATH are now "PATH'ed" as well. For this reason, I would favor the batch file method mentionned earlier to this method.
Try dir /b
, for bare format.
dir /?
will show you documentation of what you can do with the dir
command. Here is the output from my Windows 7 machine:
C:\>dir /?
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename]
Specifies drive, directory, and/or files to list.
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
default. Use /-C to disable display of separator.
/D Same as wide but files are list sorted by column.
/L Uses lowercase.
/N New long list format where filenames are on the far right.
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
/P Pauses after each screenful of information.
/Q Display the owner of the file.
/R Display alternate data streams of the file.
/S Displays files in specified directory and all subdirectories.
/T Controls which time field displayed or used for sorting
timefield C Creation
A Last Access
W Last Written
/W Uses wide list format.
/X This displays the short names generated for non-8dot3 file
names. The format is that of /N with the short name inserted
before the long name. If no short name is present, blanks are
displayed in its place.
/4 Displays four-digit years
Switches may be preset in the DIRCMD environment variable. Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.
I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.
my_data
is a struct with name
as a field and data[]
is arry of structs, you are initializing each index. read following:
5.20 Designated Initializers:
In a structure initializer, specify the name of a field to initialize with
.fieldname ='
before the element value. For example, given the following structure,struct point { int x, y; };
the following initialization
struct point p = { .y = yvalue, .x = xvalue };
is equivalent to
struct point p = { xvalue, yvalue };
Another syntax which has the same meaning, obsolete since GCC 2.5, is
fieldname:'
, as shown here:struct point p = { y: yvalue, x: xvalue };
You can also write:
my_data data[] = {
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
as:
my_data data[] = {
[0] = { .name = "Peter" },
[1] = { .name = "James" },
[2] = { .name = "John" },
[3] = { .name = "Mike" }
};
or:
my_data data[] = {
[0].name = "Peter",
[1].name = "James",
[2].name = "John",
[3].name = "Mike"
};
Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:
my_data data[] = {
[3].name = "Mike",
[1].name = "James",
[0].name = "Peter",
[2].name = "John"
};
If you have multiple fields in your struct (for example, an int age
), you can initialize all of them at once using the following:
my_data data[] = {
[3].name = "Mike",
[2].age = 40,
[1].name = "James",
[3].age = 23,
[0].name = "Peter",
[2].name = "John"
};
To understand array initialization read Strange initializer expression?
Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code
You could try the following:
select customer1.Id,customer1.Name,customer1.city,CustAdd.phone,CustAdd.Country
from customer1
inner join [EBST08].[Test].[dbo].[customerAddress] CustAdd
on customer1.Id=CustAdd.CustId
A "quick and dirty" way is to use the find function and activate regular expressions.
Then just search for : \s for highlighting spaces \t for tabs \n for new-lines etc.
let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.backgroundColor = .black
blurEffectView.alpha = 0.5
blurEffectView.frame = topView.bounds
if !self.presenting {
blurEffectView.frame.origin.x = 0
} else {
blurEffectView.frame.origin.x = -topView.frame.width
}
blurEffectView.frame.origin.x = -topView.frame.width
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveEaseIn]) {
if !self.presenting {
blurEffectView.frame.origin.x = -topView.frame.width
} else {
blurEffectView.frame.origin.x = 0
}
view.addSubview(blurEffectView)
} completion: { (status) in
}
For siblings package imports, you can use either the insert or the append method of the [sys.path][2] module:
if __name__ == '__main__' and if __package__ is None:
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
import api
This will work if you are launching your scripts as follows:
python examples/example_one.py
python tests/test_one.py
On the other hand, you can also use the relative import:
if __name__ == '__main__' and if __package__ is not None:
import ..api.api
In this case you will have to launch your script with the '-m' argument (note that, in this case, you must not give the '.py' extension):
python -m packageName.examples.example_one
python -m packageName.tests.test_one
Of course, you can mix the two approaches, so that your script will work no matter how it is called:
if __name__ == '__main__':
if __package__ is None:
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
import api
else:
import ..api.api
From the error, I infer that referenceElement
is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).
>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
You probably meant either for element in referenceElement.keys()
or for element in json['referenceElement'].keys()
. With more context on what types json
and referenceElement
are and what they contain, we will be able to better help you if neither solution works.
First convert the numeric value then add the 'S'
:
select convert(varchar(10),StandardCost) +'S'
from DimProduct where ProductKey = 212
Press F2 and then rename it (or right click on the project and select Rename
). It changes wherever that package is declared in your project. It's automatically renamed all over.
Use min-height: 1px;
Everything has at least min-height of 1px so no extra space is taken up with nbsp or padding, or being forced to know the height first.
Unique at any time:
int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
Given a string, with a complete python path to a function, this is how I went about getting the result of said function:
import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()
To bind a control to your state you need to call a function on the component that updates the state from the control's event handler.
Rather than have an update function for all your form fields, you could create a generic update function using ES6 computed name feature and pass it the values it needs inline from the control like this:
class LovelyForm extends React.Component {_x000D_
constructor(props) {_x000D_
alert("Construct");_x000D_
super(props);_x000D_
this.state = {_x000D_
field1: "Default 1",_x000D_
field2: "Default 2"_x000D_
};_x000D_
}_x000D_
_x000D_
update = (name, e) => {_x000D_
this.setState({ [name]: e.target.value });_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<form>_x000D_
<p><input type="text" value={this.state.field1} onChange={(e) => this.update("field1", e)} />_x000D_
{this.state.field1}</p>_x000D_
<p><input type="text" value={this.state.field2} onChange={(e) => this.update("field2", e)} />_x000D_
{this.state.field2}</p>_x000D_
</form>_x000D_
);_x000D_
}_x000D_
}_x000D_
ReactDOM.render(<LovelyForm/>, document.getElementById('example'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="example"></div>
_x000D_
This is a good thing to handle with a revision control system. That way when you get a bug report from a user, you can check out that revision of code and (hopefully) reproduce the bug running the exact same code as the user.
The idea is that every time you do a build, you will run a script that gets the current revision number of your code and updates a file within your project (usually with some form of token replacement). You can then write an error handling routine that always includes the revision number in the error output, or you can display it on an "About" page.
Using explode and implode function we can improvise a solution :
$array = array('lastname', 'email', 'phone');
define('DEFAULT_ROLES', implode (',' , $array));
echo explode(',' ,DEFAULT_ROLES ) [1];
This will echo email
.
If you want it to optimize it more you can define 2 functions to do the repetitive things for you like this :
//function to define constant
function custom_define ($const , $array) {
define($const, implode (',' , $array));
}
//function to access constant
function return_by_index ($index,$const = DEFAULT_ROLES) {
$explodedResult = explode(',' ,$const ) [$index];
if (isset ($explodedResult))
return explode(',' ,$const ) [$index] ;
}
Hope that helps . Happy coding .
I used the timezone-js package.
var timezoneJS = require('timezone-js');
var tzdata = require('tzdata');
createDate(dateObj) {
if ( dateObj == null ) {
return null;
}
var nativeTimezoneOffset = new Date().getTimezoneOffset();
var offset = this.getTimeZoneOffset();
// use the native Date object if the timezone matches
if ( offset == -1 * nativeTimezoneOffset ) {
return dateObj;
}
this.loadTimeZones();
// FIXME: it would be better if timezoneJS.Date was an instanceof of Date
// tried jquery $.extend
// added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},
start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar
start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar --stop
Click on Start
button in Windows.
Go to All Programs -> Microsoft SQL Server 2008 -> Configuration Tools -> SQL Server Configuration Manager
Click on SQL Native Client 10.0 Configuration -> Client Protocols -> TCP/IP
double click ( Right click select Properties
) on TCP/IP
.
You will find Default Port 1433
.
Depending on connection, the port number may vary.
Which Oracle client are you using?
Oracle 64bit 11g client isn't support in PLSQL Developer. Try to install 32bits client.
There's a jQuery plugin called "imagesLoaded" that provides a cross-browser compatible method to check if an element's image(s) have been loaded.
Site: https://github.com/desandro/imagesloaded/
Usage for a container that has many images inside:
$('container').imagesLoaded(function(){
console.log("I loaded!");
})
The plugin is great:
Using React.createRef()
class MessageBox extends Component {
constructor(props) {
super(props)
this.boxRef = React.createRef()
}
scrollToBottom = () => {
this.boxRef.current.scrollTop = this.boxRef.current.scrollHeight
}
componentDidUpdate = () => {
this.scrollToBottom()
}
render() {
return (
<div ref={this.boxRef}></div>
)
}
}
https://www.microsoft.com/en-us/download/details.aspx?id=20098 - when you run this software . it will extract dll file. and paste two dll file(php_pdo_sqlsrv_55_ts.dll,extension=php_sqlsrv_55_ts.dll) this location C:\wamp\bin\php\php5.6.40\ext\ (pls make sure your current version)
2)edit php.ini file add below line extension=php_pdo_sqlsrv_55_ts.dll extension=php_sqlsrv_55_ts.dll
Please refer screenshort add dll in your php.ini file
The simpler way:
h = ''
i = None
j = 0
k = 1
print h or i or j or k
Will print 1
print k or j or i or h
Will print 1
I had a similar problem but all answers here didn't help me.
For me the problem was a failing test. If you are doing test driven development than a failing / not implemented test shouldn't break the build. I still want my project to build.
To solve this I added a configuration to surefire so that it ignores a failing test.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
The only thing that might make a checksum comparison slightly faster than a byte-by-byte comparison is the fact that you are reading one file at a time, somewhat reducing the seek time for the disk head. That slight gain may however very well be eaten up by the added time of calculating the hash.
Also, a checksum comparison of course only has any chance of being faster if the files are identical. If they are not, a byte-by-byte comparison would end at the first difference, making it a lot faster.
You should also consider that a hash code comparison only tells you that it's very likely that the files are identical. To be 100% certain you need to do a byte-by-byte comparison.
If the hash code for example is 32 bits, you are about 99.99999998% certain that the files are identical if the hash codes match. That is close to 100%, but if you truly need 100% certainty, that's not it.
I was scratching my head with this compiler error. My class was not an extension method, was working perfectly since months and needed to stay non-static. I had included a new method inside the class:
private static string TrimNL(this string Value)
{...}
I had copied the method from a sample and didn't notice the "this" modifier in the method signature, which is used in extension methods. Removing it solved the issue.
That's 32 hex characters - 1 hex character is 4 bits.
I also had this issue where some parameterized queries or sp's would give me a SqlException (mostly the string or binary data would be truncated), and the statements where hard to debug (As far as i know there currently is no sql-profiler support for SQL Azure)
I see a lot of simular code in reactions here. I ended up putting my solution in a Sql-Library project for future use.
The generator is available here: https://github.com/jeroenpot/SqlHelper/blob/master/Source/Mirabeau.MsSql.Library/SqlGenerator.cs
It supports both CommandType.Text and CommandType.StoredProcedure
And if you install the nuget-package you can generate it with this statement:
SqlDebugHelper.CreateExecutableSqlStatement(sql, parameters);
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type. You also do not need to include jQuery path.
React Hooks (16.8+):
const Dropdown = ({
options
}) => {
const [selectedOption, setSelectedOption] = useState(options[0].value);
return (
<select
value={selectedOption}
onChange={e => setSelectedOption(e.target.value)}>
{options.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
);
};
public Form1()
{
InitializeComponent();
string myHost = System.Net.Dns.GetHostName();
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
}
Declare myIP and myHost in public Variable and use in any function of the form.
The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.
Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.
<input type="hidden" name="TrackingID"
<input type="text" name="FirstName" id="firstnametext" />
<input type="checkbox" name="IsLegal" value="Do you accept terms and conditions?" />
Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string
is nullable)) otherwise the AJAX or POST back will fail.
[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}
You can also post back a model without using any razor helpers. I have come across that this is needed some times.
public Class HomeModel
{
public int HouseNumber { get; set; }
public string StreetAddress { get; set; }
}
The HTML markup will simply be ...
<input type="text" name="variableName.HouseNumber" id="whateverid" >
and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.
[HttpPost]
public ActionResult PostBack(HomeModel variableName){
postBack.HouseNumber; //The value user entered
postBack.StreetAddress; //the default value of NULL.
}
When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.
TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !
Using List<>
is bit more complex in its mark-up.
<input type="text" name="variableNameHere[0].HouseNumber" id="id" value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber" value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">
Index on List<> MUST always be zero based and sequential. 0,1,2,3.
[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
int counter = MyHomes.Count()
foreach(var home in MyHomes)
{ ... }
}
Using IEnumerable<>
for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.
<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id" value="3">
<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3" value="4">
<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23" value="5">
And the code just needs to use IEnumerable and call ToList()
[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
int counter = variableNameHere.ToList().Count()
foreach(var home in variableNameHere)
{ ... }
}
It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.
So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.
check the Eclipse log (the intelligently named ".log" file in your workspace .metadata folder) and check for the complete stacktrace. In my case it was caused at method "org.eclipse.m2e.jdt.internal.MavenClasspathVariableInitializer.initialize(MavenClasspathVariableInitializer.java:30)" which lead to a never fixed "race condition during startup" bug. I would really recommend dumping Eclipse in favor of a more serious IDE; like IntelliJ or Netbeans. Using Eclipse means that you will invest 40-50% of your time trying to work around this kind of bugs, instead of being productive.
Several of the answers above will work around the lack of a direct reference to a specific row, but will not work if changes occur to the other rows in a table. That is my criteria for which answers fall technically short.
A common use of Oracle's ROWID is to provide a (somewhat) stable method of selecting rows and later returning to the row to process it (e.g., to UPDATE it). The method of finding a row (complex joins, full-text searching, or browsing row-by-row and applying procedural tests against the data) may not be easily or safely re-used to qualify the UPDATE statement.
The SQL Server RID seems to provide the same functionality, but does not provide the same performance. That is the only issue I see, and unfortunately the purpose of retaining a ROWID is to avoid repeating an expensive operation to find the row in, say, a very large table. Nonetheless, performance for many cases is acceptable. If Microsoft adjusts the optimizer in a future release, the performance issue could be addressed.
It is also possible to simply use FOR UPDATE and keep the CURSOR open in a procedural program. However, this could prove expensive in large or complex batch processing.
Caveat: Even Oracle's ROWID would not be stable if the DBA, between the SELECT and the UPDATE, for example, were to rebuild the database, because it is the physical row identifier. So the ROWID device should only be used within a well-scoped task.
Yes
document.location is the normal way.
However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.
Check out this thread on SO for more info:
What's the difference between window.location and document.location in JavaScript?
In my case I used below configuration at VM options in IntelliJ
, it was not picking the local configurations but after a restart of IntelliJ
it picked configuration details from IntelliJ
and service started running.
-Dspring.profiles.active=local
Using Visual Studio's Productivity Power Tools (free) extension helps a bit. Specifically, the Solution Error Visualizer
feature. With it, compilation errors marked visually in the solution explorer (in the source file where the error was found). For some reason, however, this feature does not work as with other errors anywhere else in the code.
With MVC views, any compile-time errors will still be underlined in red in their respective .cs files, but signaling these errors is not propagated upwards in the Solution Explorer (in no way, even not in the containing source file).
Thanks for BlueClouds
for correcting my previous statement.
I have just reported this as an issue on the extension's github project.
None of the answers here solved this error for me. Code would run, but I could not jump directly to function definitions. It was only for certain local packages. For one thing, python.jediEnabled
is no longer a valid option. I did two things, but I am not sure the first was necessary:
python.languageServer
to "Pylance""python.analysis.extraPaths": [ "path_to/src_file" ]
Apparently the root and src
will be checked for local packages, but others must be added here.
I will add my answer since I don't use any of the other answers provided.
With the Support Library v7, all the styles are actually already defined and ready to use, for the standard buttons, all of these styles are available:
style="@style/Widget.AppCompat.Button"
style="@style/Widget.AppCompat.Button.Colored"
style="@style/Widget.AppCompat.Button.Borderless"
style="@style/Widget.AppCompat.Button.Borderless.Colored"
Widget.AppCompat.Button.Colored
:
Widget.AppCompat.Button.Borderless
Widget.AppCompat.Button.Borderless.Colored
:
To answer the question, the style to use is therefore
<Button style="@style/Widget.AppCompat.Button.Colored"
.......
.......
.......
android:text="Button"/>
For the whole app:
The color of all the UI controls (not only buttons, but also floating action buttons, checkboxes etc.) is managed by the attribute colorAccent
as explained here.
You can modify this style and apply your own color in your theme definition:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
<item name="colorAccent">@color/Orange</item>
</style>
For a specific button:
If you need to change the style of a specific button, you can define a new style, inheriting one of the parent styles described above. In the example below I just changed the background and font colors:
<style name="AppTheme.Button" parent="Widget.AppCompat.Button.Colored">
<item name="colorButtonNormal">@color/Red</item>
<item name="android:textColor">@color/White</item>
</style>
Then you just need to apply this new style on the button with:
android:theme="@style/AppTheme.Button"
To set a default button design in a layout, add this line to the styles.xml theme:
<item name="buttonStyle">@style/btn</item>
where @style/btn
is your button theme. This sets the button style for all the buttons in a layout with a specific theme
We have the following benefits of using IHttpActionResult
over HttpResponseMessage
:
IHttpActionResult
we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.async
and await
by default.ACE.oledb.16.0 dosen't work in the 64-bit os
download patch from https://www.microsoft.com/en-us/download/details.aspx?id=13255
So at the most basic level a HANDLE of any sort is a pointer to a pointer or
#define HANDLE void **
Now as to why you would want to use it
Lets take a setup:
class Object{
int Value;
}
class LargeObj{
char * val;
LargeObj()
{
val = malloc(2048 * 1000);
}
}
void foo(Object bar){
LargeObj lo = new LargeObj();
bar.Value++;
}
void main()
{
Object obj = new Object();
obj.val = 1;
foo(obj);
printf("%d", obj.val);
}
So because obj was passed by value (make a copy and give that to the function) to foo, the printf will print the original value of 1.
Now if we update foo to:
void foo(Object * bar)
{
LargeObj lo = new LargeObj();
bar->val++;
}
There is a chance that the printf will print the updated value of 2. But there is also the possibility that foo will cause some form of memory corruption or exception.
The reason is this while you are now using a pointer to pass obj to the function you are also allocating 2 Megs of memory, this could cause the OS to move the memory around updating the location of obj. Since you have passed the pointer by value, if obj gets moved then the OS updates the pointer but not the copy in the function and potentially causing problems.
A final update to foo of:
void foo(Object **bar){
LargeObj lo = LargeObj();
Object * b = &bar;
b->val++;
}
This will always print the updated value.
See, when the compiler allocates memory for pointers it marks them as immovable, so any re-shuffling of memory caused by the large object being allocated the value passed to the function will point to the correct address to find out the final location in memory to update.
Any particular types of HANDLEs (hWnd, FILE, etc) are domain specific and point to a certain type of structure to protect against memory corruption.
in IIS, highlight the machine, double-click "Request Filtering", open the "Hidden Segments" tab. "App_Data" is listed there as a restricted folder. Yes i know this thread is really old, but this is still applicable.
when using the categorical_crossentropy
loss, your targets should be in categorical format (e.g. if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros except for a 1 at the index corresponding to the class of the sample).
A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:
from tkinter import Frame, Tk
class MyApp():
def __init__(self):
self.root = Tk()
self.my_frame_red = Frame(self.root, bg='red')
self.my_frame_red.grid(row=0, column=0, sticky='nsew')
self.my_frame_blue = Frame(self.root, bg='blue')
self.my_frame_blue.grid(row=0, column=1, sticky='nsew')
self.root.grid_rowconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.root.mainloop()
if __name__ == '__main__':
app = MyApp()
But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.
This is what works for me:
if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else
Two possibilities I can think of, although they are both mentioned in the link you referenced:
You're not specifying the correct SSH keypair file or user name in the ssh command you're using to log into the server:
ssh -i [full path to keypair file] root@[EC2 instance hostname or IP address]
You don't have the correct permissions on the keypair file; you should use
chmod 600 [keypair file]
to ensure that only you can read or write the file.
Try using the -v option with ssh to get more info on where exactly it's failing, and post back here if you''d like more help.
[Update]: OK, so this is what you should have seen if everything was set up properly:
debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: Next authentication method: publickey
debug1: Trying private key: ec2-keypair
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
Are you running the ssh command from the directory containing the ec2-keypair file ? If so, try specifying -i ./ec2-keypair just to eliminate path problems. Also check "ls -l [full path to ec2-keypair]" file and make sure the permissions are 600 (displayed as rw-------). If none of that works, I'd suspect the contents of the keypair file, so try recreating it using the steps in your link.
It is easy to create a self-signed certificate, import it, and bind it to your website.
1.) Create a self-signed certificate:
Run the following 4 commands, one at a time, from an elevated Command Prompt:
cd C:\Program Files (x86)\Windows Kits\8.1\bin\x64
makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.3 -sv localhost.pvk localhost.cer
cert2spc localhost.cer localhost.spc
pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx
2.) Import certificate to Trusted Root Certification Authorities store:
start --> run --> mmc.exe --> Certificates plugin --> "Trusted Root Certification Authorities" --> Certificates
Right-click Certificates --> All Tasks --> Import Find your "localhost" Certificate at C:\Program Files (x86)\Windows Kits\8.1\bin\x64\
3.) Bind certificate to website:
start --> (IIS) Manager --> Click on your Server --> Click on Sites --> Click on your top level site --> Bindings
Add or edit a binding for https and select the SSL certificate called "localhost".
4.) Import Certificate to Chrome:
Chrome Settings --> Manage Certificates --> Import .pfx certificate from C:\certificates\ folder
Test Certificate by opening Chrome and navigating to https://localhost/
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
Use the name attribute selector:
$("input[name='nameGoesHere']").val();
It is a mandatory requirement to include quotes around the value, see: http://api.jquery.com/attribute-equals-selector/
After you get the error, run
EXEC sp_who2
Look for the database in the list. It's possible that a connection was not terminated. If you find any connections to the database, run
KILL <SPID>
where <SPID>
is the SPID for the sessions that are connected to the database.
Try your script after all connections to the database are removed.
Unfortunately, I don't have a reason why you're seeing the problem, but here is a link that shows that the problem has occurred elsewhere.
Alternatively to the answer marked as correct, if you have to replace words instead of chars you can do it with this piece of code :
$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count($values), '?') as $key => $wildcard) {
$query = substr_replace($query, '"'.$values[$key].'"', strpos($query, $wildcard), strlen($wildcard));
}
echo $query;
Demo here : http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7
If its a 32 bit COM/Active X, use version 32 bit of cscript.exe/wscript.exe located in C:\Windows\SysWOW64\
Maybe good ol' cfront will do?
consider
data={'fld':'hello'}
now
jsonify(data)
will yield {'fld':'hello'} and
json.dumps(data)
gives
"<html><body><p>{'fld':'hello'}</p></body></html>"
The following works for me:
form_for @user, :url => {:action => "YourActionName"}
I was having problem that control was not going in to didselect row after applying break point. problem was in view. I removed tab gesture from view. then its worked fine
abc "$@"
$@
represents all the parameters given to your bash script.
If your text will be consumed by non-browsers then it's safer to type the character with the keyboard-combo option shift right bracket
because ’
will not be transformed into an apostrophe by a regular XML or JSON parser. (e.g. if you are serving this content to native Android/iOS apps).
Im my browser, this doesn't work at all. The tooltip field doesn't show a link, but <a href='#' onClick='alert('Hello World!')>The Link</a>
.
I'm using FF 3.6.12.
You'll have to do this by hand with JS and CSS. Begin here
for those who still face the same problem which i faced before when i have a ViewPager
with 7 fragments. the default for these fragments to load the English content from API
service but the problem here that i want to change the language from settings activity and after finish
settings activity i want ViewPager
in main activity to refresh the fragments to match the language selection from the user and load the Arabic content if user chooses Arabic here what i did to work from the first time
1- You must use FragmentStatePagerAdapter as mentioned above.
2- on mainActivity i override the onResume and did the following
if (!(mPagerAdapter == null)) {
mPagerAdapter.notifyDataSetChanged();
}
3-i overrided the getItemPosition()
in mPagerAdapter and make it return POSITION_NONE
.
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
works like charm
Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.
yes | execute_command
This will use yes as the answer to all yes/no prompts.
Try out cat
and sprintf
in your for loop.
eg.
cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))
See here
Thou shalt always encode URLs.
Here is how Ruby encodes your URL:
irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"
You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration
<endpointBehaviors>
<behavior name="jsonBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
An example of endpoint configuration in your scenario is
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="ITestService"/>
</service>
</services>
so, the service will be available at
Apply [WebGet] to the operation contract to make it RESTful. e.g.
public interface ITestService
{
[OperationContract]
[WebGet]
string HelloWorld(string text)
}
Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.
For plain old XML as return format, this is an example that would work both for SOAP and XML.
[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
[OperationContract]
[WebGet(UriTemplate = "accounts/{id}")]
Account[] GetAccount(string id);
}
POX behavior for REST Plain Old XML
<behavior name="poxBehavior">
<webHttp/>
</behavior>
Endpoints
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="xml" binding="webHttpBinding" behaviorConfiguration="poxBehavior" contract="ITestService"/>
</service>
</services>
Service will be available at
REST request try it in browser,
SOAP request client endpoint configuration for SOAP service after adding the service reference,
<client>
<endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
contract="ITestService" name="BasicHttpBinding_ITestService" />
</client>
in C#
TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");
Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.
Be careful using SelectedItem.Text... If there is no item selected, then SelectedItem will be null and SelectedItem.Text will generate a null-value exception.
.NET should have provided a SelectedText property like the SelectedValue property that returns String.Empty when there is no selected item.
It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)
or you can simply try this in inline css
<textarea style="::placeholder{color:white}"/>
while(listbox.Items.Remove(s)) ;
should work, as well. However, I think the backwards solution is the fastest.
System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
I gave up and inserted a simple jQuery code as below. This will add a tr after every tr, if you have so many trs like me. Demo: https://jsfiddle.net/acf9sph6/
<table>
<tbody>
<tr class="my-tr">
<td>one line</td>
</tr>
<tr class="my-tr">
<td>one line</td>
</tr>
<tr class="my-tr">
<td>one line</td>
</tr>
</tbody>
</table>
<script>
$(function () {
$("tr.my-tr").after('<tr class="tr-spacer"/>');
});
</script>
<style>
.tr-spacer
{
height: 20px;
}
</style>
Old post, but this zombie is hitting VS 2017 (I haven't dug into why it's just "some" projects). In this case, it's not user permissions, rather IIS Express process is still using the files.
You'll see the icon in your task tray
rebuild
without this annoying "permission denied" message.This is also why "restarting Visual Studio" will "fix" the issue. Doing so, stops IIS Express.
Hth...
Extending @oopbase's answer with return;
statement.
Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,
/* Some Import Statements here. */
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
}
// ....
session.getAttribute("user_id");
// ....
/* Some More JSP+Java+HTML code here */
It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch
block or handled if(null != session.getAttribute("attr_name"))
everytime.
So by putting a return;
statement I stopped further execution and forced to redirect page to certain location.
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
return;
}
Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).
One problem with StringWriter
is that by default it doesn't let you set the encoding which it advertises - so you can end up with an XML document advertising its encoding as UTF-16, which means you need to encode it as UTF-16 if you write it to a file. I have a small class to help with that though:
public sealed class StringWriterWithEncoding : StringWriter
{
public override Encoding Encoding { get; }
public StringWriterWithEncoding (Encoding encoding)
{
Encoding = encoding;
}
}
Or if you only need UTF-8 (which is all I often need):
public sealed class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
As for why you couldn't save your XML to the database - you'll have to give us more details about what happened when you tried, if you want us to be able to diagnose/fix it.
An exe is an executible program whereas A DLL is a file that can be loaded and executed by programs dynamically.
('' + 123456789).split('').map( x => +x ).reduce( (a,b) => a+b ) === 45
true
or without map
('' + 123456789).split('').reduce( (a,b) => (+a)+(+b) ) === 45
true
From jQuery Docs:
const height = $(window).height();
const scrollTop = $(window).scrollTop();
http://api.jquery.com/scrollTop/
http://api.jquery.com/height/
try:
$(window).scrollTop( $('body').height() );
If you want multiplicities, you can put it in map that maps pair to ammount. This way there will only be one pair of given values, but it can represent multiple occurances.
Then if you have lot of repeatet values and want to perform some operation on all values, you can save lot of computations.
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
Use the system stored procedure sp_who2
.
Create the following function
CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
"is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'
And it'll work.
You may to create different versions with different parameter types.
Definitely the second method is preferred because you don't have the overhead of another function invocation:
window.location.href = "webpage.htm";
Had a problem on IIS 8 when retrieving Content via Ajax. The issue was that MaximumWorkerProcesses
was set to 2
and Javascript opened 17 concurrent requests. That was more than the AppPool could handle and a new pool (without auth-data) was opened.
Solution was to Change MaximumWorkerProcesses
to 0
in IIS -> Server -> Application Pools -> [myPool] -> Advanced Settings -> Process Model -> MaximumWorkerProcesses
.
This exact question is answered on mySql workbench-faq:
Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.
That means hover over an acronym in the mySql Workbench table editor.
$location / switching between html5 and hashbang mode / link rewriting
<?php
function is_valid_domain_name($domain_name)
{
return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name) //valid chars check
&& preg_match("/^.{1,253}$/", $domain_name) //overall length check
&& preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name) ); //length of each label
}
?>
Test cases:
is_valid_domain_name? [a] Y
is_valid_domain_name? [0] Y
is_valid_domain_name? [a.b] Y
is_valid_domain_name? [localhost] Y
is_valid_domain_name? [google.com] Y
is_valid_domain_name? [news.google.co.uk] Y
is_valid_domain_name? [xn--fsqu00a.xn--0zwm56d] Y
is_valid_domain_name? [goo gle.com] N
is_valid_domain_name? [google..com] N
is_valid_domain_name? [google.com ] N
is_valid_domain_name? [google-.com] N
is_valid_domain_name? [.google.com] N
is_valid_domain_name? [<script] N
is_valid_domain_name? [alert(] N
is_valid_domain_name? [.] N
is_valid_domain_name? [..] N
is_valid_domain_name? [ ] N
is_valid_domain_name? [-] N
is_valid_domain_name? [] N
.switch {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 90px;_x000D_
height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #ca2222;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
position: absolute;_x000D_
content: "";_x000D_
height: 26px;_x000D_
width: 26px;_x000D_
left: 4px;_x000D_
bottom: 4px;_x000D_
background-color: white;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
-webkit-transform: translateX(55px);_x000D_
-ms-transform: translateX(55px);_x000D_
transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
color: white;_x000D_
position: absolute;_x000D_
transform: translate(-50%,-50%);_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 10px;_x000D_
font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
Easier solution;
#/bin/bash
if (( ${1:-2} >= 2 )); then
echo "First parameter must be 0 or 1"
fi
# rest of script...
Output
$ ./test
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1
Explanation
(( ))
- Evaluates the expression using integers.${1:-2}
- Uses parameter expansion to set a value of 2
if undefined.>= 2
- True if the integer is greater than or equal to two 2
.From here:
Windows
For Example, C:\Program Files\MySQL\MySQL Server 5.1\my.ini
#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"
Find the “datadir”
, this is the where does MySQL stored the data in Windows.
Linux
yongmo@myserver:~$ find / -name my.cnf
find: /home/lost+found: Permission denied
find: /lost+found: Permission denied
/etc/mysql/my.cnf
my.cnf
file like this: cat /etc/mysql/my.cnf
yongmo@myserver:~$ cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/english
skip-external-locking
“datadir”
, this is where does MySQL stored the data in Linux system.There are cases when they are necessary:
In code I work on I use explicit destructor call in allocators, I have implementation of simple allocator that uses placement new to return memory blocks to stl containers. In destroy I have:
void destroy (pointer p) {
// destroy objects by calling their destructor
p->~T();
}
while in construct:
void construct (pointer p, const T& value) {
// initialize memory with placement new
#undef new
::new((PVOID)p) T(value);
}
there is also allocation being done in allocate() and memory deallocation in deallocate(), using platform specific alloc and dealloc mechanisms. This allocator was used to bypass doug lea malloc and use directly for example LocalAlloc on windows.
The recommended version by Günter Zöchbauer works fine, but I have an addition to make. In my case I had an unstyled html-element and I did not know how to style it. Therefore I designed a pipe to add styling to it.
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'StyleClass'
})
export class StyleClassPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(html: any, styleSelector: any, styleValue: any): SafeHtml {
const style = ` style = "${styleSelector}: ${styleValue};"`;
const indexPosition = html.indexOf('>');
const newHtml = [html.slice(0, indexPosition), style, html.slice(indexPosition)].join('');
return this.sanitizer.bypassSecurityTrustHtml(newHtml);
}
}
Then you can add style to any html-element like this:
<span [innerhtml]="Variable | StyleClass: 'margin': '0'"> </span>
With:
Variable = '<p> Test </p>'
Just to provide an another way, you can also simply use the following command
$ cat to_remove
/tmp/file1
/tmp/file2
/tmp/file3
$ rm $( cat to_remove )
<div>
with some proportions
div {
position: relative;
width: 100%;
height: 100%;
}
<img>
's with their own proportions
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: auto; /* to keep proportions */
height: auto; /* to keep proportions */
max-width: 100%; /* not to stand out from div */
max-height: 100%; /* not to stand out from div */
margin: auto auto 0; /* position to bottom and center */
}
If you get this issue, then either
I've resorted to
df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index
lately. That gets both null and empty-string cells in one go.
$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr '$!N;/^(.*)\n\1$/!P;D'
1
2
3
4
5
the core idea is:
print ONLY once of each duplicate consecutive lines at its LAST appearance and use D command to implement LOOP.
Explains:
$!N;
: if current line is NOT the last line, use N
command to read the next line into pattern space
./^(.*)\n\1$/!P
: if the contents of current pattern space
is two duplicate string
separated by \n
, which means the next line is the same
with current line, we can NOT print it according to our core idea; otherwise, which means current line is the LAST appearance of all of its duplicate consecutive lines, we can now use P
command to print the chars in current pattern space
util \n
(\n
also printed).D
: we use D
command to delete the chars in current pattern space
util \n
(\n
also deleted), then the content of pattern space
is the next line.D
command will force sed
to jump to its FIRST
command $!N
, but NOT read the next line from file or standard input stream.$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr 'p;:loop;$!N;s/^(.*)\n\1$/\1/;tloop;D'
1
2
3
4
5
the core idea is:
print ONLY once of each duplicate consecutive lines at its FIRST appearance and use : command & t command to implement LOOP.
Explains:
:loop
command set a label
named loop
.N
to read next line into the pattern space
.s/^(.*)\n\1$/\1/
to delete current line if the next line is same with current line, we use s
command to do the delete
action.s
command is executed successfully, then use tloop
command force sed
to jump to the label
named loop
, which will do the same loop to the next lines util there are no duplicate consecutive lines of the line which is latest printed
; otherwise, use D
command to delete
the line which is the same with thelatest-printed line
, and force sed
to jump to first command, which is the p
command, the content of current pattern space
is the next new line.Some of this may be due to the OS your server is running. I recently did a migration to a new hosting environment running Ubuntu. Adding this alias alias composer="/path/to/your/composer"
to .bashrc or .bash_aliases didn't work at first because of two reasons:
The server was running csh, not bash, by default. To check if this is an issue in your case, run echo $0
. If the what is returned is -csh
you will want to change it to bash, since some processes run by Composer will fail using csh/tcsh.
To change it, first check if bash is available on your server by running cat /etc/shells
. If, in the list returned, you see bin/bash
, you can change the default to bash by running chsh -s /bin/csh
.
Now, at this point, you should be able to run Composer, but normally, on Ubuntu, you will have to load the script at every session by sourcing your Bash scripts by running source ~/.bashrc
or source ~/.bash_profile
. This is because, in most cases, Ubuntu won't load your Bash script, since it loads .profile
as the default script.
To load your Bash scripts when you open a session, try adding this to your .profile (this is if your Bash script is .bashrc—modify accordingly if .bash_profile or other):
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
To test, close your session and reload. If it's working properly, running composer -v
or which composer
should behave as expected.
The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain UNIQUE values and column cannot contain NULL Values.
-- DROP current primary key
ALTER TABLE tblPersons DROP CONSTRAINT <constraint_name>
Example:
ALTER TABLE tblPersons
DROP CONSTRAINT P_Id;
-- ALTER TABLE tblpersion
ALTER TABLE tblpersion add primary key (P_Id,LastName)
A hash_map
is an older, unstandardized version of what for standardization purposes is called an unordered_map
(originally in TR1, and included in the standard since C++11). As the name implies, it's different from std::map
primarily in being unordered -- if, for example, you iterate through a map from begin()
to end()
, you get items in order by key1, but if you iterate through an unordered_map
from begin()
to end()
, you get items in a more or less arbitrary order.
An unordered_map
is normally expected to have constant complexity. That is, an insertion, lookup, etc., typically takes essentially a fixed amount of time, regardless of how many items are in the table. An std::map
has complexity that's logarithmic on the number of items being stored -- which means the time to insert or retrieve an item grows, but quite slowly, as the map grows larger. For example, if it takes 1 microsecond to lookup one of 1 million items, then you can expect it to take around 2 microseconds to lookup one of 2 million items, 3 microseconds for one of 4 million items, 4 microseconds for one of 8 million items, etc.
From a practical viewpoint, that's not really the whole story though. By nature, a simple hash table has a fixed size. Adapting it to the variable-size requirements for a general purpose container is somewhat non-trivial. As a result, operations that (potentially) grow the table (e.g., insertion) are potentially relatively slow (that is, most are fairly fast, but periodically one will be much slower). Lookups, which cannot change the size of the table, are generally much faster. As a result, most hash-based tables tend to be at their best when you do a lot of lookups compared to the number of insertions. For situations where you insert a lot of data, then iterate through the table once to retrieve results (e.g., counting the number of unique words in a file) chances are that an std::map
will be just as fast, and quite possibly even faster (but, again, the computational complexity is different, so that can also depend on the number of unique words in the file).
1 Where the order is defined by the third template parameter when you create the map, std::less<T>
by default.
In my humble opinion, this is just a matter of deciding if the arguments are optional or not. If an Person object shouldn't (logically) exist without Name and Age, they should be mandatory in the constructor. If they are optional, (i.e. their absence is not a threat to the good functioning of the object), use the setters.
Here's a quote from Symfony's docs on constructor injection:
There are several advantages to using constructor injection:
- If the dependency is a requirement and the class cannot work without it then injecting it via the constructor ensures it is present when the class is used as the class cannot be constructed without it.
- The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime.
These advantages do mean that constructor injection is not suitable for working with optional dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses constructor injection then extending it and overriding the constructor becomes problematic.
(Symfony is one of the most popular and respected php frameworks)
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
Just entering a single space for the Back button navigation item works!!
I had two repositories, pushing to one of which worked fine. So, I compared their .git/config
. The non-working one had at the end:
[http]
sslVerify = false
The working one had instead:
[credential]
helper = store
Changing .git/config
solved the problem.
It was changing the line endings (from Windows CRLF to Unix LF) in the .htaccess
file that fixed it for me.