Here's my step in Ubuntu 16.04 and Tomcat 8.
Copy folder /var/lib/tomcat8/webapps/ROOT to your folder.
cp -r /var/lib/tomcat8/webapps/ROOT /var/lib/tomcat8/webapps/{yourfolder}
Add your html, css, js, to your folder.
Open "http://localhost:8080/{yourfolder}" in browser
Notes:
If you using chrome web browser and did wrong folder before, then clean web browser's cache(or change another name) otherwise (sometimes) it always 404.
The folder META-INF with context.xml is needed.
For iOS 8, try this:
<a href="sms:/* phone number here */&body=/* body text here */">Link</a>
Switching the ";" with a "&" worked for me.
The best solution is to override the click functionality:
public void _click(WebElement element){
boolean flag = false;
while(true) {
try{
element.click();
flag=true;
}
catch (Exception e){
flag = false;
}
if(flag)
{
try{
element.click();
}
catch (Exception e){
System.out.printf("Element: " +element+ " has beed clicked, Selenium exception triggered: " + e.getMessage());
}
break;
}
}
}
Try to use deep Equal. It will compare nested arrays as well as nested Json.
expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
Please refer to main documentation site.
The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.
Also, I didn't understand when the accepted answer said "it defaults to node server.js
". I think the documentation clarifies the default behavior:
npm-start
Start a package
Synopsis
npm start [-- <args>]
Description
This runs an arbitrary command specified in the package's "
start
" property of its "scripts
" object. If no "start
" property is specified on the "scripts
" object, it will runnode server.js
.
In summary, running npm start
could do one of two things:
npm start {command_name}
: Run an arbitrary command (i.e. if such command is specified in the start
property of package.json's scripts
object)npm start
: Else if no start
property exists (or no command_name
is passed): Run node server.js
, (which may not be appropriate, for example the OP doesn't have server.js
; the OP runs node
app.js
)package.json
in the directory where you run npm start
, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'
Best use rm -rf .git/hooks
and then try git push
Error : the hierarchy of the type "class name" is inconsistent error.
solution : class OtherDepJar {} --> is inside "other.dep.jar" .
class DepJar extends OtherDepJar {} --> is inside "dep.jar".
class ProblematicClass extends DepJar {} --> is inside current project .
If dep.jar is in the project's classpath, but other.dep.jar isn't in the project's classpath, Eclipse will show the" The hierarchy of the type ... is inconsistent error"
I am assuming you know the length of the part before the _
and after the underscore, as well as the extension. If you don't it might be more complex than a simple substring.
cd C:\path\to\the\files
for /f %%a IN ('dir /b *.jpg') do (
set p=%a:~0,3%
set q=%a:~4,4%
set b=%p_%q.jpg
ren %a %b
)
I just came up with this script, and I did not test it. Check out this and that for more info.
IF you want to assume you don't know the positions of the _
and the lengths and the extension, I think you could do something with for loops to check the index of the _
, then the last index of the .
, wrap it in a goto
thing and make it work. If you're willing to go through that trouble, I'd suggest you use WindowsPowerShell (or Cygwin) at least (for your own sake) or install a more advanced scripting language (think Python/Perl) you'll get more support either way.
I ran into the same issue and found that I could solve it with a Common Table Expression (available in SQL 2005 or later):
;with cte as (
SELECT PitchID, SUM(Price) somePrice
FROM BookingPitchExtras
WHERE [required] = 1
GROUP BY PitchID)
UPDATE p SET p.extrasPrice=cte.SomePrice
FROM BookingPitches p INNER JOIN cte ON p.ID=cte.PitchID
WHERE p.BookingID=1
In addition to the answers above:
$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop
$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop
like say a class .c1 has height:40px; how do I get rid of this height property?
Sadly, you can't. CSS doesn't have a "default" placeholder.
In that case, you would reset the property using
height: auto;
as @Ben correctly points out, in some cases, inherit
is the correct way to go, for example when resetting the text colour of an a
element (that property is inherited from the parent element):
a { color: inherit }
Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.
The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.
public void showInput() {
OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, boolean hasFocus) {
if (hasFocus) {
// Must use message queue to show keyboard
v.post(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(v, 0);
}
});
}
}
};
final EditText editTextName = new EditText(this);
editTextName.setHint("Name");
editTextName.setFocusable(true);
editTextName.setClickable(true);
editTextName.setFocusableInTouchMode(true);
editTextName.setSelectAllOnFocus(true);
editTextName.setSingleLine(true);
editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
editTextName.setOnFocusChangeListener(onFocusChangeListener);
final EditText editTextPassword = new EditText(this);
editTextPassword.setHint("Password");
editTextPassword.setFocusable(true);
editTextPassword.setClickable(true);
editTextPassword.setFocusableInTouchMode(true);
editTextPassword.setSelectAllOnFocus(true);
editTextPassword.setSingleLine(true);
editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
editTextPassword.setOnFocusChangeListener(onFocusChangeListener);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(editTextName);
linearLayout.addView(editTextPassword);
DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
// Done button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
// Cancel button clicked
break;
}
}
};
final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
.setView(linearLayout)
.setPositiveButton("Done", alertDialogClickListener)
.setNegativeButton("Cancel", alertDialogClickListener)
.create();
editTextName.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
editTextPassword.requestFocus(); // Press Return to focus next one
return false;
}
});
editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Press Return to invoke positive button on alertDialog.
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
return false;
}
});
// Must set password mode after creating alert dialog.
editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
alertDialog.show();
}
You cant simply (directly) convert the datareader to list.
You have to loop through all the elements in datareader and insert into list
below the sample code
using (drOutput)
{
System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();
int customerId = drOutput.GetOrdinal("customerId ");
int CustomerName = drOutput.GetOrdinal("CustomerName ");
while (drOutput.Read())
{
CustomerEntity obj=new CustomerEntity ();
obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
arrObjects .Add(obj);
}
}
The Github application for Windows shows all remote branches of a repository. If you have deleted the branch locally with $ git branch -d [branch_name]
, the remote branch still exists in your Github repository and will appear regardless in the Windows Github application.
If you want to delete the branch completely (remotely as well), use the above command in combination with $ git push origin :[name_of_your_new_branch]
. Warning: this command erases all existing branches and may cause loss of code. Be careful, I do not think this is what you are trying to do.
However every time you delete the local branch changes, the remote branch will still appear in the application. If you do not want to keep making changes, just ignore it and do not click, otherwise you may clone the repository. If you had any more questions, please let me know.
int max = 50;
int min = 1;
double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);
This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double
Why?
random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.
Random rand = new Random();
int value = rand.nextInt(50);
This will give value from 0 to 49.
For 1 to 50: rand.nextInt((max - min) + 1) + min;
Source of some Java Random awesomeness.
XSD : XML Schema Definition.
XML : eXtensible Markup Language.
WSDL : Web Service Definition Language.
I am not going to answer in technical terms. I am aiming this explanation at beginners.
It is not easy to communicate between two different applications that are developed using two different technologies. For example, a company in Chicago might develop a web application using Java and another company in New York might develop an application in C# and when these two companies decided to share information then XML comes into picture. It helps to store and transport data between two different applications that are developed using different technologies. Note: It is not limited to a programming language, please do research on the information transportation between two different apps.
XSD is a schema definition. By that what I mean is, it is telling users to develop their XML in such a schema. Please see below images, and please watch closely with "load-on-startup" element and its type which is integer. In the XSD image you can see it is meant to be integer value for the "load-on-startup" and hence when user created his/her XML they passed an int value to that particular element. As a reminder, XSD is a schema and style whereas XML is a form to communicate with another application or system. One has to see XSD and create XML in such a way or else it won't communicate with another application or system which has been developed with a different technology. A company in Chicago provides a XSD template for a company in Texas to write or generate their XML in the given XSD format. If the company in Texas failed to adhere with those rules or schema mentioned in XSD then it is impossible to expect correct information from the company in Chicago. There is so much to do after the above said story, which an amateur or newbie have to know while coding for some thing like I said above. If you really want to know what happens later then it is better to sit with senior software engineers who actually developed web services. Next comes WSDL, please follow the images and try to figure out where the WSDL will fit in.
***************========Below is partial XML image ==========***************
***************========Below is partial XSD image ==========***************
***************========Below is the partial WSDL image =======*************
I had to create a sample WSDL for a web service called Book. Note, it is an XSD but you have to call it WSDL (Web Service Definition Language) because it is very specific for Web Services. The above WSDL (or in other words XSD) is created for a class called Book.java and it has created a SOAP service. How the SOAP web service created it is a different topic. One has to write a Java class and before executing it create as a web service the user has to make sure Axis2 API is installed and Tomcat to host web service is in place.
As a servicer (the one who allows others (clients) to access information or data from their systems ) actually gives the client (the one who needs to use servicer information or data) complete access to data through a Web Service, because no company on the earth willing to expose their Database for outsiders. Like my company, decided to give some information about products via Web Services, hence we had to create XSD template and pass-on to few of our clients who wants to work with us. They have to write some code to make complete use of the given XSD and make Web Service calls to fetch data from servicer and convert data returned into their suitable requirement and then display or publish data or information about the product on their website. A simple example would be FLIGHT Ticket booking. An airline will let third parties to use flight data on their site for ticket sales. But again there is much more to it, it is just not letting third party flight ticket agent to sell tickets, there will be synchronize and security in place. If there is no sync then there is 100 % chances more than 1 customer might buy same flight ticket from various sources.
I am hoping experts will contribute to my answer. It is really hard for newbie or novice to understand XML, XSD and then to work on Web Services.
I didn't dig up the BNF for this, but the Arduino documentation had a great example of the function and it's breakdown. I was able to use this in Python by simply adding a def renaming to remap (cause map is a built-in) and removing the type casts and curly braces (ie just remove all the 'long's).
Original
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
Python
def remap(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
Besides the box-shadow, transform and border options mentioned in other answers, WebKit browsers currently also obey -webkit-text-fill-color to set the colour of the "time elapsed" numbers, but since there is no way to set their background (which might vary with platform, e.g. inverted high-contrast modes on some operating systems), you would be advised to set -webkit-text-fill-color to the value "initial" if you've used it elsewhere and the audio element is inheriting this, otherwise some users might find those numbers unreadable.
If you are using LESS
or Sass
, You can try this:
.btn {
&[disabled] {
opacity: 0.6;
}
&:hover, &:active {
&:not([disabled]) {
background-color: darken($orange, 15);
}
}
}
Context java 8
I give my answer here in the context of Oracle java 8 implementation, since after reading all the answers, I found that an answer in the context of java 6 has given by gmgmiller, and another answer has been given in the context of java 7. But how java 8 implementes the size increasement has not been given.
In java 8, the size increasement behavior is the same as java 6, see the grow
method of ArrayList:
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
the key code is this line:
int newCapacity = oldCapacity + (oldCapacity >> 1);
So clearly, the growth factor is also 1.5, the same as java 6.
This should also work:
w.female[w.female == 'female'] = 1
w.female[w.female == 'male'] = 0
As Marc says, this is not possible (although Visual Studio allows you to add an application configuration file in a class library project).
You might want to check out the AssemblySettings class which seems to make assembly config files possible.
Use git revert like so:
git revert <insert bad commit hash here>
git revert
creates a new commit with the changes that are rolled back. git reset
erases your git history instead of making a new commit.
The steps after are the same as any other commit.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/logout"
android:icon="@drawable/logout"
android:title="Log Out"
app:showAsAction="always"
/>
</menu>
This did the trick for me!
When you try to handle multi languages like Japanese and Korean you might get in trouble. mb_convert_encoding with 'auto' parameter doesn't work well. Setting mb_detect_order('ASCII,UTF-8,JIS,EUC-JP,SJIS,EUC-KR,UHC') doesn't help since it will detect EUC-* wrongly.
I concluded that as long as input strings comes from HTML, it should use 'charset' in a meta element. I use Simple HTML DOM Parser because it supports invalid HTML.
The below snippet extracts title element from a web page. If you would like to convert entire page, then you may want to remove some lines.
<?php
require_once 'simple_html_dom.php';
echo convert_title_to_utf8(file_get_contents($argv[1])), PHP_EOL;
function convert_title_to_utf8($contents)
{
$dom = str_get_html($contents);
$title = $dom->find('title', 0);
if (empty($title)) {
return null;
}
$title = $title->plaintext;
$metas = $dom->find('meta');
$charset = 'auto';
foreach ($metas as $meta) {
if (!empty($meta->charset)) { // html5
$charset = $meta->charset;
} else if (preg_match('@charset=(.+)@', $meta->content, $match)) {
$charset = $match[1];
}
}
if (!in_array(strtolower($charset), array_map('strtolower', mb_list_encodings()))) {
$charset = 'auto';
}
return mb_convert_encoding($title, 'UTF-8', $charset);
}
I found this variant hanging out in the "deleted by author" answers on a duplicate of this question. Unlike some of the other answers that have many upvotes already, this is:
shuffled
name rather than shuffle
)Here's a jsfiddle showing it in use.
Array.prototype.shuffled = function() {
return this.map(function(n){ return [Math.random(), n] })
.sort().map(function(n){ return n[1] });
}
From W3 web site Common HTML entities used for typography
For the sake of portability, Unicode entity references should be reserved for use in documents certain to be written in the UTF-8 or UTF-16 character sets. In all other cases, the alphanumeric references should be used.
Translation: If you are looking for widest support, go with —
[^\s-]
should work and so will
[^-\s]
[]
: The char class^
: Inside the char class ^
is the
negator when it appears in the beginning.\s
: short for a white space-
: a literal hyphen. A hyphen is a
meta char inside a char class but not
when it appears in the beginning or
at the end.For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
Did the following for a spring application running static, rest and websocket content.
The Apache is used as Proxy and SSL Endpoint for the following URIs:
<VirtualHost *:80>
ServerName xxx.xxx.xxx
ProxyRequests Off
ProxyVia Off
ProxyPreserveHost On
<Proxy *>
Require all granted
</Proxy>
RewriteEngine On
# websocket
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule ^/api/ws/(.*) ws://localhost:8080/api/ws/$1 [P,L]
# rest
ProxyPass /api http://localhost:8080/api
ProxyPassReverse /api http://localhost:8080/api
# static content
ProxyPass /app http://localhost:8080/app
ProxyPassReverse /app http://localhost:8080/app
</VirtualHost>
I use the same vHost config for the SSL configuration, no need to change anything proxy related.
server.use-forward-headers: true
None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:
$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.
The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.
As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.
Public Function _
CreateTextArrayFromSourceTexts(ParamArray SourceTexts() As Variant) As String()
ReDim TargetTextArray(0 To UBound(SourceTexts)) As String
For SourceTextsCellNumber = 0 To UBound(SourceTexts)
TargetTextArray(SourceTextsCellNumber) = SourceTexts(SourceTextsCellNumber)
Next SourceTextsCellNumber
CreateTextArrayFromSourceTexts = TargetTextArray
End Function
Example:
Dim TT() As String
TT = CreateTextArrayFromSourceTexts("hi", "bye", "hi", "bcd", "bYe")
Result:
TT(0)="hi"
TT(1)="bye"
TT(2)="hi"
TT(3)="bcd"
TT(4)="bYe"
Enjoy!
Edit: I removed the duplicatedtexts deleting feature and made the code smaller and easier to use.
var span = TimeSpan.FromMinutes(2);
var t = Task.Factory.StartNew(async delegate / () =>
{
this.SomeAsync();
await Task.Delay(span, source.Token);
}, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
source.Cancel(true/or not);
// or use ThreadPool(whit defaul options thread) like this
Task.Start(()=>{...}), source.Token)
if u like use some loop thread inside ...
public async void RunForestRun(CancellationToken token)
{
var t = await Task.Factory.StartNew(async delegate
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(1), token)
.ContinueWith(task => { Console.WriteLine("End delay"); });
this.PrintConsole(1);
}
}, token) // drop thread options to default values;
}
// And somewhere there
source.Cancel();
//or
token.ThrowIfCancellationRequested(); // try/ catch block requred.
try this: (you missed the single quotes)
var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';
If you want to view the information in a slice in the same format that you'd use to type it in (something like ["one", "two", "three"]
), here's a code example showing how to do that:
package main
import (
"fmt"
"strings"
)
func main() {
test := []string{"one", "two", "three"} // The slice of data
semiformat := fmt.Sprintf("%q\n", test) // Turn the slice into a string that looks like ["one" "two" "three"]
tokens := strings.Split(semiformat, " ") // Split this string by spaces
fmt.Printf(strings.Join(tokens, ", ")) // Join the Slice together (that was split by spaces) with commas
}
As einpoklum mentioned in their answer, since C++17 you can also use structured binding declarations. I want to extend on that by providing a full solution for iterating over a map of maps in a comfortable way:
int main() {
std::map<std::string, std::map<std::string, std::string>> m {
{"name1", {{"value1", "data1"}, {"value2", "data2"}}},
{"name2", {{"value1", "data1"}, {"value2", "data2"}}},
{"name3", {{"value1", "data1"}, {"value2", "data2"}}}
};
for (const auto& [k1, v1] : m)
for (const auto& [k2, v2] : v1)
std::cout << "m[" << k1 << "][" << k2 << "]=" << v2 << std::endl;
return 0;
}
Note 1: For filling the map, I used an initializer list (which is a C++11 feature). This can sometimes be handy to keep fixed initializations compact.
Note 2: If you want to modify the map m
within the loops, you have to remove the const
keywords.
With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.
# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12
# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert
To verify the contents of the JKS, you can use this command:
keytool -list -v -keystore mykeystore.jks
If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
For those wanting to update their existing data here is the query:
update SomeEventTable set eventTime=RIGHT('00000'+ISNULL(eventTime, ''),5)
Swift 3/4
You can use the below extension for your convenience.
Usage inside a ViewController
:
showInputDialog(title: "Add number",
subtitle: "Please enter the new number below.",
actionTitle: "Add",
cancelTitle: "Cancel",
inputPlaceholder: "New number",
inputKeyboardType: .numberPad)
{ (input:String?) in
print("The new number is \(input ?? "")")
}
The extension code:
extension UIViewController {
func showInputDialog(title:String? = nil,
subtitle:String? = nil,
actionTitle:String? = "Add",
cancelTitle:String? = "Cancel",
inputPlaceholder:String? = nil,
inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
actionHandler: ((_ text: String?) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
alert.addTextField { (textField:UITextField) in
textField.placeholder = inputPlaceholder
textField.keyboardType = inputKeyboardType
}
alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
guard let textField = alert.textFields?.first else {
actionHandler?(nil)
return
}
actionHandler?(textField.text)
}))
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))
self.present(alert, animated: true, completion: nil)
}
}
You can do something like
SELECT news.id as news_id, user.id as user_id ....
And then $row['news_id']
will be the news id and $row['user_id']
will be the user id
I would fire up Visual Studio, create a web project (or console app - doesn't matter).
For .Net Standard:
If there is no error, you should simply set the NameSpace you want to use to access the service and it'll be generated for you.
For .Net Core
Any of the methods above will generate a simple, very basic WCF client for you to use. You should find a "YourservicenameClient" class in the generated code.
For reference purpose, the generated cs file can be found in your Obj/debug(or release)/XsdGeneratedCode and you can still find the dlls in the TempPE folder.
The created Service(s) should have methods for each of the defined methods on the WSDL contract.
Instantiate the client and call the methods you want to call - that's all there is!
YourServiceClient client = new YourServiceClient();
client.SayHello("World!");
If you need to specify the remote URL (not using the one created by default), you can easily do this in the constructor of the proxy client:
YourServiceClient client = new YourServiceClient("configName", "remoteURL");
where configName
is the name of the endpoint to use (you will use all the settings except the URL), and the remoteURL
is a string representing the URL to connect to (instead of the one contained in the config).
if you are using any mobile suit like mobogenie or something that might also will make this issue. try killing that too from the task manager.
Note : i faced the same issue, tried the above solution. That didn't work, finally found out this solution.May useful for someone else!..
If you use jupyter notebook, my solution is as simple as:
%pylab
import matplotlib.pyplot as plt
import mplcursors
plt.plot(...)
mplcursors.cursor(hover=True)
plt.show()
One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.
For example:
HTML:
<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>
<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>
JS:
$( ".selected" ).each(function(index) {
$(this).on("click", function(){
// For the boolean value
var boolKey = $(this).data('selected');
// For the mammal value
var mammalKey = $(this).attr('id');
});
});
Those do both mean non-breaking space, yes.  
is another synonym, in hex.
This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/
It is nicely designed Fluent API.
//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
.Configure()
.CreateTask("TaskName", "C:\\Test.bat")
.RunDaily()
.RunEveryXMinutes(10)
.RunDurationFor(new TimeSpan(18, 0, 0))
.SetStartDate(new DateTime(2015, 8, 8))
.SetStartTime(new TimeSpan(8, 0, 0))
.Execute();
This is the best way
LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them
lp.removeViewAt(0); // and so on
If you have xml layout then no need to add dynamically.just call
lp.removeViewAt(0);
Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)
ES6 modules support in Node.js is fairly recent; even in the bleeding-edge versions, it is still experimental. With Node.js 10, you can start Node.js with the --experimental-modules
flag, and it will likely work.
To import on older Node.js versions - or standard Node.js 10 - use CommonJS syntax:
const fs = require('fs');
I think the answers are below
List<string> aa = (from char c in source
select c.ToString() ).ToList();
List<string> aa2 = (from char c1 in source
from char c2 in source
select string.Concat(c1, ".", c2)).ToList();
Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException
) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
Use mkdir's -p
option, but note that it has another effect as well.
-p Create intermediate directories as required. If this option is not specified, the full path prefix of each oper-
and must already exist. On the other hand, with this option specified, no error will be reported if a directory
given as an operand already exists. Intermediate directories are created with permission bits of rwxrwxrwx
(0777) as modified by the current umask, plus write and search permission for the owner.
string = "firstName:name1, lastName:last1";
This will work:
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split(':');
fieldObject[c[0]] = c[1];
});
}
However it's not efficient. What happens when you have something like this:
string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";
split()
will split 'http'. So i suggest you use a special delimiter like pipe
string = "firstName|name1, lastName|last1";
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split('|');
fieldObject[c[0]] = c[1];
});
}
cast it to a char pointer an increment your pointer forward x bytes ahead.
Use the OutputDebugString
function or the TRACE
macro (MFC) which lets you do printf
-style formatting:
int x = 1;
int y = 16;
float z = 32.0;
TRACE( "This is a TRACE statement\n" );
TRACE( "The value of x is %d\n", x );
TRACE( "x = %d and y = %d\n", x, y );
TRACE( "x = %d and y = %x and z = %f\n", x, y, z );
I know that this may not be a popular answer but I do agree with @Randy Minder on using third party tool when more complex comparison is needed.
This specific case here is easy and for this case such tools are not needed but this can get complex easily if you introduce more columns, databases on two servers, more complex comparison criteria and such.
There are a lot of these tools such as ApexSQL Data Diff or Quest Toad and you can always use them in trial mode to get the job done.
The answer from @edutesoy points to the documentation of PowerMockito
and mentions constructor mocking as a hint but doesn't mention how to apply that to the current problem in the question.
Here is a solution based on that. Taking the code from the question:
public class MyClass {
void method1 {
MyObject obj1 = new MyObject();
obj1.method1();
}
}
The following test will create a mock of the MyObject
instance class via preparing the class that instantiates it (in this example I am calling it MyClass
) with PowerMock
and letting PowerMockito
to stub the constructor of MyObject
class, then letting you stub the MyObject
instance method1()
call:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
@Test
public void testMethod1() {
MyObject myObjectMock = mock(MyObject.class);
when(myObjectMock.method1()).thenReturn(<whatever you want to return>);
PowerMockito.whenNew(MyObject.class).withNoArguments().thenReturn(myObjectMock);
MyClass objectTested = new MyClass();
objectTested.method1();
... // your assertions or verification here
}
}
With that your internal method1()
call will return what you want.
If you like the one-liners you can make the code shorter by creating the mock and the stub inline:
MyObject myObjectMock = when(mock(MyObject.class).method1()).thenReturn(<whatever you want>).getMock();
You are dividing integers then converting to float. Divide by floats instead.
As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language
To specify a percent conversion and precision.
>>> float(1) / float(3)
[Out] 0.33333333333333331
>>> 1.0/3.0
[Out] 0.33333333333333331
>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'
>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'
A great gem!
use Arrays.equals(ary1,ary2);
// returns boolean value
EDIT
you can use Arrays.deepEquals(ary1,ary2)
to compare 2D arrays as well
also check this link for comparision comparision between Arrays.equls(ar1,ar2)
and Arrays.deepEquals(ar1,ar2)
Java Arrays.equals() returns false for two dimensional arrays
EDIT 2
if you dont want to use these library methods then you can easily implement your method like this:
public static boolean ArrayCompare(int[] a, int[] a2) {
if (a==a2) // checks for same array reference
return true;
if (a==null || a2==null) // checks for null arrays
return false;
int length = a.length;
if (a2.length != length) // arrays should be of equal length
return false;
for (int i=0; i<length; i++) // compare array values
if (a[i] != a2[i])
return false;
return true;
}
You can use canvas’ context.translate & context.rotate to do rotate your image
Here’s a function to draw an image that is rotated by the specified degrees:
function drawRotated(degrees){
context.clearRect(0,0,canvas.width,canvas.height);
// save the unrotated context of the canvas so we can restore it later
// the alternative is to untranslate & unrotate after drawing
context.save();
// move to the center of the canvas
context.translate(canvas.width/2,canvas.height/2);
// rotate the canvas to the specified degrees
context.rotate(degrees*Math.PI/180);
// draw the image
// since the context is rotated, the image will be rotated also
context.drawImage(image,-image.width/2,-image.width/2);
// we’re done with the rotating so restore the unrotated context
context.restore();
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/6ZsCz/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var angleInDegrees=0;
var image=document.createElement("img");
image.onload=function(){
ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
}
image.src="houseicon.png";
$("#clockwise").click(function(){
angleInDegrees+=30;
drawRotated(angleInDegrees);
});
$("#counterclockwise").click(function(){
angleInDegrees-=30;
drawRotated(angleInDegrees);
});
function drawRotated(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(image,-image.width/2,-image.width/2);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas><br>
<button id="clockwise">Rotate right</button>
<button id="counterclockwise">Rotate left</button>
</body>
</html>
No. You have 2 options:
DateTime date = DateTime.MinValue;
This works when you need to do something every X amount of time (since you will always be over MinValue
) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue
) if you are not careful.
And you can use Nullable
:
DateTime? date = null;
Which is nice and avoids most issues while introducing only 1 or 2.
It really depends on what you are trying to achieve.
Use the oncontextmenu
event.
Here's an example:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners (credit to rampion from a comment in 2011):
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
I guess the answer you need is referenced here Python sets are not json serializable
Not all datatypes can be json serialized . I guess pickle module will serve your purpose.
There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle.
Please go through the below points.
1 Query String.
FirstForm.aspx.cs
Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);
SecondForm.aspx.cs
TextBox1.Text = Request.QueryString["Parameter"].ToString();
This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:
FirstForm.aspx.cs
Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));
SecondForm.aspx.cs
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());
URL Encoding
2. Passing value through context object
Passing value through context object is another widely used method.
FirstForm.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
SecondForm.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);
Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.
3. Posting form to another page instead of PostBack
Third method of passing value by posting page to another form. Here is the example of that:
FirstForm.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add("onclick", "return PostPage();");
}
And we create a javascript function to post the form.
SecondForm.aspx.cs
function PostPage()
{
document.Form1.action = "SecondForm.aspx";
document.Form1.method = "POST";
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();
Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false
4. Another method is by adding PostBackURL property of control for cross page post back
In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.
FirstForm.aspx.cs
<asp:Button id=buttonPassValue style=”Z-INDEX: 102" runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”></asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.
You can also use PreviousPage class to access controls of previous page instead of using classic Request object.
SecondForm.aspx
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1");
TextBox1.Text = textBoxTemp.Text;
As you have noticed, this is also a simple and clean implementation of passing value between pages.
Reference: MICROSOFT MSDN WEBSITE
HAPPY CODING!
$('a[data-category="music"]')
It works. See Attribute Equals Selector [name=”value”].
Structs "really" pure aren't supported in Java. E.g., C# supports struct
definitions that represent values and can be allocated anytime.
In Java, the unique way to get an approximation of C++ structs
struct Token
{
TokenType type;
Stringp stringValue;
double mathValue;
}
// Instantiation
{
Token t = new Token;
}
without using a (static buffer or list) is doing something like
var type = /* TokenType */ ;
var stringValue = /* String */ ;
var mathValue = /* double */ ;
So, simply allocate variables or statically define them into a class.
With 1.1.1, I used the following to fix the scale between 0.0 and 1.0:
var options = {
scaleOverride: true,
scaleStartValue: 0,
scaleSteps: 10,
scaleStepWidth: 0.1
}
Make server output on First of all
SET SERVEROUTPUT on
then
Go to the DBMS Output window (View->DBMS Output)
then Press Ctrl+N for connecting server
Trigger DataTable search function after initializing DataTable with a blank string in it. It will automatically adjust misalignment of thead
with tbody
.
$( document ).ready(function()
{
$('#monitor_data_voyage').DataTable( {
scrollY:150,
bSort:false,
bPaginate:false,
sScrollX: "100%",
scrollX: true,
} );
setTimeout( function(){
$('#monitor_data_voyage').DataTable().search( '' ).draw();
}, 10 );
});
All tables within bootstrap stretch according to the container they're in. You can put your tables inside a .span
element to control the size. This SO Question may help you out
This was happening for me when I had Skype running on my local machine. As soon as I closed that the exception went away.
I have got same issue on my server. Follow below steps -
It works and solved my problem.
$id = "1";
$title = "phpmyadmin";
$sql= mysql_query("UPDATE table_name SET id ='".$id."', title = '".$title."',now() WHERE id = '".$id."' ");
now() function update current date and time.
note: For update query we have define the particular id otherwise it update whole table defaulty
don't uninstall anything. a system with multiple versions of java works just fine. and you don't need to update your environment varables (e.g. java_home, path, etc..).
yes, ireports 3.6.1 needs java 7 (doesn't work with java 8).
all you have to do is edit C:\Program Files\Jaspersoft\iReport-nb-3.6.1\etc\ireport.conf:
# default location of JDK/JRE, can be overridden by using --jdkhome <dir> switch
jdkhome="C:/Program Files/Java/jdk1.7.0_45"
on linux (no spaces and standard file paths) its that much easier. keep your java 8 for other interesting projects...
You could add google()
to repositories block
allprojects {
repositories {
jcenter()
maven {
url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'
}
maven {
url "https://jitpack.io"
}
google()
}
}
sed
expression needs to be quoted
sed -i "s/$oldstring/$newstring/g"
Another thing to be careful of (I did this so I know, duh). Be sure not to enable Proguard for debug!
In Kotlin,you can use using alpha like this,
//Click on On.//
view.rel_on.setOnClickListener{
view.rel_off.alpha= 0.2F
view.rel_on.alpha= 1F
}
//Click on Off.//
view.rel_off.setOnClickListener {
view.rel_on.alpha= 0.2F
view.rel_off.alpha= 1F
}
Result is like in this screen shots.
Hope this will help you.Thanks
If you don't care about loading the file into memory, as of Go 1.16, you can use the os.ReadFile
and bytes.Count
functions.
package main
import (
"log"
"os"
"bytes"
)
func main() {
data, err := os.ReadFile("input.txt")
if err != nil {
log.Fatal(err)
}
n := bytes.Count(data, []byte{'\n'})
fmt.Printf("input.txt has %d lines\n", n)
}
Try this
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"Login"];
[[UIApplication sharedApplication].keyWindow setRootViewController:vc];
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;
Alternatively:
var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);
Use collectl
which has extensive process I/O monitoring including monitoring threads.
Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl
reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html
Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?
this worked for me
sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
domain.com -d www.domain.com
We can do this using JavaScript, no need of jQuery. Just pass the changed element and let JavaScript handle it.
HTML
<form id="myform">
syn<input type="checkbox" name="checkfield" id="g01-01" onchange="doalert(this)"/>
</form>
JS
function doalert(checkboxElem) {
if (checkboxElem.checked) {
alert ("hi");
} else {
alert ("bye");
}
}
This is a short and simple example I just used:
If:
fp = open("file.txt", "w")
Then:
fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"
Not:
line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing
The recommended way to install setuptools on Windows is to download ez_setup.py and run it. The script will download the appropriate .egg file and install it for you.
For best results, uninstall previous versions FIRST (see Uninstalling).
Once installation is complete, you will find an easy_install.exe program in your Python Scripts subdirectory. For simple invocation and best results, add this directory to your PATH environment variable, if it is not already present.
more details : https://pypi.python.org/pypi/setuptools
import os
print os.path.abspath(__file__)
This is what the code would look like in a batch file(tested, works):
powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"
Based on the information from:
http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/
\r
is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line.
The cursor is the position where the next characters will be rendered.
So, printing a \r
allows to override the current line of the terminal emulator.
Tom Zych figured why the output of your program is o world
while the \r
is at the end of the line and you don't print anything after that:
When your program exits, the shell prints the command prompt. The terminal renders it where you left the cursor. Your program leaves the cursor at the start of the line, so the command prompt partly overrides the line you printed. This explains why you seen your command prompt followed by o world
.
The online compiler you mention just prints the raw output to the browser. The browser ignores control characters, so the \r
has no effect.
See https://en.wikipedia.org/wiki/Carriage_return
Here is a usage example of \r
:
#include <stdio.h>
#include <unistd.h>
int main()
{
char chars[] = {'-', '\\', '|', '/'};
unsigned int i;
for (i = 0; ; ++i) {
printf("%c\r", chars[i % sizeof(chars)]);
fflush(stdout);
usleep(200000);
}
return 0;
}
It repeatedly prints the characters -
\
|
/
at the same position to give the illusion of a rotating |
in the terminal.
Try:
SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamp_A))
FROM TableA
Details here: EXTRACT.
If you are using Spyder in the Anaconda package...
In the IPython Console, use
!conda install packageName
This works locally too.
!conda install /path/to/package.tar
Note: the ! is required when using IPython console from within Spyder.
According to the latest version (1.5.3) there is no fromHTML()
method anymore.
Instead you should utilize jsPDF HTML plugin, see: https://rawgit.com/MrRio/jsPDF/master/docs/module-html.html#~html
You also need to add html2canvas library in order for it to work properly: https://github.com/niklasvh/html2canvas
JS (from API docs):
var doc = new jsPDF();
doc.html(document.body, {
callback: function (doc) {
doc.save();
}
});
You can provide HTML string instead of reference to the DOM element as well.
A DLL is a library of functions that are shared among other executable programs. Just look in your windows/system32 directory and you will find dozens of them. When your program creates a DLL it also normally creates a lib file so that the application *.exe program can resolve symbols that are declared in the DLL.
A .lib is a library of functions that are statically linked to a program -- they are NOT shared by other programs. Each program that links with a *.lib file has all the code in that file. If you have two programs A.exe and B.exe that link with C.lib then each A and B will both contain the code in C.lib.
How you create DLLs and libs depend on the compiler you use. Each compiler does it differently.
I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.
I just made two changes and I don't which help.
Go to IIS 6 Manager
Select properties of SMTP server
On tab Access, select Relays
Add your public IP address
Close the dialog and on the same tab click to Authentication button.
Add Integrated Windows Authentication
Maybe some step is not needed, but it works.
A float has 23 bits of precision, and a double has 52.
The application Pools element contains configuration settings for all application pools running on your IIS. An application pool defines a group of one or more worker processes, configured with common settings that serve requests to one or more applications that are assigned to that application pool.
Because application pools allow a set of Web applications to share one or more similarly configured worker processes, they provide a convenient way to isolate a set of Web applications from other Web applications on the server computer.
Process boundaries separate each worker process; therefore, application problems in one application pool do not affect Web sites or applications in other application pools. Application pools significantly increase both the reliability and manageability of your Web infrastructure.
npm install -g npm@version
in which you want to downgrade
npm install -g [email protected]
Did they add a runtime List<> and/or Map<> type class to typepad 1.0
No, providing a runtime is not the focus of the TypeScript team.
is there a solid library out there someone wrote that provides this functionality?
I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections
JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts
: https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want
import re
url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)
>>> print urls
['http://example.com', 'http://example2.com']
Using the {# #}
notation, like so:
{# Everything you see here is a comment. It won't show up in the HTML output. #}
Except first answer form Bathsheba, except MSDN information for:
you could analyse these tables for better understanding of differences between analysed properties.
My solution is similar to user1587439's answer, but works directly on the controller's instance (instead of accessing HttpContext.Current).
In the 'Watch' window, I saw that this.RequestContext.WebRequest contains the 'UserHostAddress' property, but since it relies on the WebHostHttpRequestContext type (which is internal to the 'System.Web.Http' assembly) - I wasn't able to access it directly, so I used reflection to directly access it:
string hostAddress = ((System.Web.HttpRequestWrapper)this.RequestContext.GetType().Assembly.GetType("System.Web.Http.WebHost.WebHostHttpRequestContext").GetProperty("WebRequest").GetMethod.Invoke(this.RequestContext, null)).UserHostAddress;
I'm not saying it's the best solution. using reflection may cause issues in the future in case of framework upgrade (due to name changes), but for my needs it's perfect
May I suggest a little simplification of @ashishduh's answer:
public class AlertDialogFragment extends DialogFragment {
public static final String ARG_TITLE = "AlertDialog.Title";
public static final String ARG_MESSAGE = "AlertDialog.Message";
public static void showAlert(String title, String message, Fragment targetFragment) {
DialogFragment dialog = new AlertDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
args.putString(ARG_MESSAGE, message);
dialog.setArguments(args);
dialog.setTargetFragment(targetFragment, 0);
dialog.show(targetFragment.getFragmentManager(), "tag");
}
public AlertDialogFragment() {}
@NonNull
@Override
public AlertDialog onCreateDialog(Bundle savedInstanceState)
{
Bundle args = getArguments();
String title = args.getString(ARG_TITLE, "");
String message = args.getString(ARG_MESSAGE, "");
return new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
}
})
.create();
}
It removes the need for the user (of the class) to be familiar with the internals of the component and makes usage really simple:
AlertDialogFragment.showAlert(title, message, this);
P.S. In my case I needed a simple alert dialog so that's what I created. You can apply the approach to a Yes/No or any other type you need.
use this code below as progress.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#ff9d9e9d"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:angle="270"
/>
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
</layer-list>
where:
after that use it in the layout containing the xml:
<SeekBar
android:id="@+id/myseekbar"
...
android:progressDrawable="@drawable/progress"
/>
you can also customize the thumb by using a custom icon seek_thumb.png:
android:thumb="@drawable/seek_thumb"
Comparision:
if (userProfile.AccountType == AccountType.Retailer)
{
//your code
}
In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:
if(userProfile != null)
{
if (userProfile.AccountType == AccountType.Retailer)
{
//your code
}
}
or shorter version:
if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
//your code
}
Object object = new Object();
// First way
List objects1 = new ArrayList<Object>();
objects1.add(object);
// second way
List<Object> objects2 = Arrays.asList(object);
// Third way
List<Object> objects3 = Collections.singletonList(object);
I use the following in a console app, running as a service, to get directory info from the App.Settings file. Number of days to keep the files is also configurable, multiplied by -1 for use in the AddDays() method of DateTime.Now.
static void CleanBackupFiles()
{
string gstrUncFolder = ConfigurationManager.AppSettings["DropFolderUNC"] + "";
int iDelAge = Convert.ToInt32(ConfigurationManager.AppSettings["NumDaysToKeepFiles"]) * -1;
string backupdir = string.Concat(@"\", "Backup", @"\");
string[] files = Directory.GetFiles(string.Concat(gstrUncFolder, backupdir));
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < DateTime.Now.AddDays(iDelAge))
{
fi.Delete();
}
}
}
Brent - the reason the association is one way has to do with the fact that any class on any component of your CLASSPATH can declare itself in any package (except for java/javax). Thus there just is no mapping of ALL the classes in a given "package" because nobody knows nor can know. You could update a jar file tomorrow and remove or add classes. It's like trying to get a list of all people named John/Jon/Johan in all the countries of the world - none of us is omniscient therefore none of us will ever have the correct answer.
This is impossible as you cannot return from an asynchronous call inside a synchronous method.
In this case you need to pass a callback to foo that will receive the return value
function foo(address, fn){
geocoder.geocode( { 'address': address}, function(results, status) {
fn(results[0].geometry.location);
});
}
foo("address", function(location){
alert(location); // this is where you get the return value
});
The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.
If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.
Just simply provide the link to actual font like this and you will be good to go
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet'>
<style>
body {
font-family: 'Montserrat';font-size: 22px;
}
</style>
</head>
<body>
<h1>Montserrat</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
</body>
</html>
Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.
You can't POST using JSONP...it simply doesn't work that way, it creates a <script>
element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.
Short answer: I guess these annotations are only useful for your IDE to warn you of potentially null pointer errors.
As said in the "Clean Code" book, you should check your public method's parameters and also avoid checking invariants.
Another good tip is never returning null values, but using Null Object Pattern instead.
Works perfect in Swift 2.0
@IBOutlet var theImage: UIImageView! //you can replace this with any UIObject eg: label etc
override func viewDidLoad() {
super.viewDidLoad()
//Make sure the width and height are same
self.theImage.layer.cornerRadius = self.theImage.frame.size.width / 2
self.theImage.layer.borderWidth = 2.0
self.theImage.layer.borderColor = UIColor.whiteColor().CGColor
self.theImage.clipsToBounds = true
}
The problem is WHEN the event is added and EXECUTED via triggering
(the document
onload
property modification can be verified by examining the properties list).
When does this execute and modify onload
relative to the onload
event trigger:
document.addEventListener('load', ... );
before, during or after the load and/or render of the page's HTML?
This simple scURIple (cut & paste to URL) "works" w/o alert
ing as naively expected:
data:text/html;charset=utf-8,
<html content editable><head>
<script>
document.addEventListener('load', function(){ alert(42) } );
</script>
</head><body>goodbye universe - hello muiltiverse</body>
</html>
Does loading imply script contents have been executed?
A little out of this world expansion ...
Consider a slight modification:
data:text/html;charset=utf-8,
<html content editable><head>
<script>
if(confirm("expand mind?"))document.addEventListener('load', function(){ alert(42) } );
</script>
</head><body>goodbye universe - hello muiltiverse</body>
</html>
and whether the HTML has been loaded or not.
Rendering is certainly pending since goodbye universe - hello muiltiverse
is not seen on screen but, does not the confirm( ... )
have to be already loaded to be executed? ... and so document.addEventListener('load', ... )
... ?
In other words, can you execute code to check for self-loading when the code itself is not yet loaded?
Or, another way of looking at the situation, if the code is executable and executed then it has ALREADY been loaded as a done deal and to retroactively check when the transition occurred between not yet loaded and loaded is a priori fait accompli.
So which comes first: loading and executing the code or using the code's functionality though not loaded?
onload
as a window
property works because it is subordinate to the object and not self-referential as in the document
case, ie. it's the window
's contents, via document
, that determine the loaded question err situation.
PS.: When do the following fail to alert(...)
? (personally experienced gotcha's):
caveat: unless loading to the same window is really fast ... clobbering is the order of the day
so what is really needed below when using the same named window:
window.open(URIstr1,"w") .
addEventListener('load',
function(){ alert(42);
window.open(URIstr2,"w") .
addEventListener('load',
function(){ alert(43);
window.open(URIstr3,"w") .
addEventListener('load',
function(){ alert(44);
/* ... */
} )
} )
} )
alternatively, proceed each successive window.open
with:
alert("press Ok either after # alert shows pending load is done or inspired via divine intervention" );
data:text/html;charset=utf-8,
<html content editable><head><!-- tagging fluff --><script>
window.open(
"data:text/plain, has no DOM or" ,"Window"
) . addEventListener('load', function(){ alert(42) } )
window.open(
"data:text/plain, has no DOM but" ,"Window"
) . addEventListener('load', function(){ alert(4) } )
window.open(
"data:text/html,<html><body>has DOM and", "Window"
) . addEventListener('load', function(){ alert(2) } )
window.open(
"data:text/html,<html><body>has DOM and", "noWindow"
) . addEventListener('load', function(){ alert(1) } )
/* etc. including where body has onload=... in each appropriate open */
</script><!-- terminating fluff --></head></html>
which emphasize onload
differences as a document
or window
property.
Another caveat concerns preserving XSS, Cross Site Scripting, and SOP, Same Origin Policy rules which may allow loading an HTML URI but not modifying it's content to check for same. If a scURIple is run as a bookmarklet/scriplet from the same origin/site then there maybe success.
ie. From an arbitrary page, this link will do the load but not likely do alert('done')
:
<a href="javascript:window.open('view-source:http://google.ca') .
addEventListener( 'load', function(){ alert('done') } )"> src. vu </a>
but if the link is bookmarked and then clicked when viewing a google.ca
page, it does both.
test environment:
window.navigator.userAgent =
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 (Splashtop-v1.2.17.0)
Functional programming is "programming with functions," where a function has some expected mathematical properties, including referential transparency. From these properties, further properties flow, in particular familiar reasoning steps enabled by substitutability that lead to mathematical proofs (i.e. justifying confidence in a result).
It follows that a functional program is merely an expression.
You can easily see the contrast between the two styles by noting the places in an imperative program where an expression is no longer referentially transparent (and therefore is not built with functions and values, and cannot itself be part of a function). The two most obvious places are: mutation (e.g. variables) other side-effects non-local control flow (e.g. exceptions)
On this framework of programs-as-expressions which are composed of functions and values, is built an entire practical paradigm of languages, concepts, "functional patterns", combinators, and various type systems and evaluation algorithms.
By the most extreme definition, almost any language—even C or Java—can be called functional, but usually people reserve the term for languages with specifically relevant abstractions (such as closures, immutable values, and syntactic aids like pattern matching). As far as use of functional programming is concerned it involves use of functins and builds code without any side effects . used to write proofs
You can solve any equation including adding with this code:
@echo off
title Richie's Calculator 3.0
:main
echo Welcome to Richie's Calculator 3.0
echo Press any key to begin calculating...
pause>nul
echo Enter An Equation
echo Example: 1+1
set /p
set /a sum=%equation%
echo.
echo The Answer Is:
echo %sum%
echo.
echo Press any key to return to the main menu
pause>nul
cls
goto main
I show you my example with modal windows...you create your modal and give it an id then In your table you have tr section, just ad the first line you see below (don't forget to set the on the first row like this
<tr onclick="input" data-toggle="modal" href="#the name for my modal windows" >
<td><label>Some value here</label></td>
</tr>
The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.
If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.
Something like below should suffice :-
String decimalPattern = "([0-9]*)\\.([0-9]*)";
String number="20.00";
boolean match = Pattern.matches(decimalPattern, number);
System.out.println(match); //if true then decimal else not
This will solve all gulp problem
sudo npm install gulp && sudo npm install --save del && sudo gulp build
If you've got VS2010
installed, you ought to find a .NET 4.0 gacutil at
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools
The 7.0A Windows SDK
should have been installed alongside VS2010 - 6.0A
will have been installed with VS2008
, and hence won't have .NET 4.0 support.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
_x000D_
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
_x000D_
Sorry writing late to the post but I see no accepted answer.
df.write().saveAsTable
will throw AnalysisException
and is not HIVE table compatible.
Storing DF as df.write().format("hive")
should do the trick!
However, if that doesn't work, then going by the previous comments and answers, this is what is the best solution in my opinion (Open to suggestions though).
Best approach is to explicitly create HIVE table (including PARTITIONED table),
def createHiveTable: Unit ={
spark.sql("CREATE TABLE $hive_table_name($fields) " +
"PARTITIONED BY ($partition_column String) STORED AS $StorageType")
}
save DF as temp table,
df.createOrReplaceTempView("$tempTableName")
and insert into PARTITIONED HIVE table:
spark.sql("insert into table default.$hive_table_name PARTITION($partition_column) select * from $tempTableName")
spark.sql("select * from default.$hive_table_name").show(1000,false)
Offcourse the LAST COLUMN in DF will be the PARTITION COLUMN so create HIVE table accordingly!
Please comment if it works! or not.
--UPDATE--
df.write()
.partitionBy("$partition_column")
.format("hive")
.mode(SaveMode.append)
.saveAsTable($new_table_name_to_be_created_in_hive) //Table should not exist OR should be a PARTITIONED table in HIVE
I'd just wrap the header with another div and play with borders.
<div class="header-border"><div class="header-real">
<p>Foo</p>
</div></div>
CSS:
.header-border { border: 2px solid #000000; }
.header-real { border: 10px solid #003399; background: #cccccc; padding: 10px; }
So, I'm used to use
var nameOfList = new List("objectName", "objectName", "objectName")
This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.
When you open a file with the name address.csv
, you are telling the open()
function that your file is in the current working directory. This is called a relative path.
To give you an idea of what that means, add this to your code:
import os
cwd = os.getcwd() # Get the current working directory (cwd)
files = os.listdir(cwd) # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))
That will print the current working directory along with all the files in it.
Another way to tell the open()
function where your file is located is by using an absolute path, e.g.:
f = open("/Users/foo/address.csv")
There's no readily available syntax to do this in the original Markdown syntax, but Markdown Extra provides a means to at least assign IDs to headers — which you can then link to easily. Note also that you can use regular HTML in both Markdown and Markdown Extra, and that the name
attribute has been superseded by the id
attribute in more recent versions of HTML.
I have also got stuck into this and believe me disabling SELinux is not a good idea.
Please just use below and you are good,
sudo restorecon -R /var/www/mysite
Enjoy..
To add the contents of mydirectory
to a new zip file, including all files and subdirectories:
import os
import zipfile
zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("mydirectory"):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
[100 %]Solved. I had the same problem today. I checked my server space
df-h
I saw that server is out of space so i check which directory has most size by
sudo du -ch / | sort -h
I saw 12.2G /var/lib/jenkins so i entered this folder and cleared all the logs by
cd /var/libs/jenkins
rm *
and restart the jenkins it will work normal
sudo systemctl restart jenkins.service
On Mac OSX, sleep does not take minutes/etc, only seconds. So for two minutes,
sleep 120
If you want to filter out only your app's activities currently running/paused, you can use this command:
adb shell dumpsys activity activities | grep 'Hist #' | grep 'YOUR_PACKAGE_NAME'
For example:
adb shell dumpsys activity activities | grep 'Hist #' | grep 'com.supercell.clashroyale'
The output will be something like:
* Hist #2: ActivityRecord{26ba44b u10 com.supercell.clashroyale/StartActivity t27770}
* Hist #1: ActivityRecord{2f3a0236 u10 com.supercell.clashroyale/SomeActivity t27770}
* Hist #0: ActivityRecord{20bbb4ae u10 com.supercell.clashroyale/OtherActivity t27770}
Do notice that the output shows the actual stack of activities i.e. the topmost activity is the one that is currently being displayed.
CSS font-stretch is now supported in all major browsers (except iOS Safari and Opera Mini). It is not easy to find a common font-family that supports expanding fonts, but it is easy to find fonts that support condensing, for example:
font-stretch: condense;
font-family: sans-serif, "Helvetica Neue", "Lucida Grande", Arial;
Without using itertools:
def combine(inp):
return combine_helper(inp, [], [])
def combine_helper(inp, temp, ans):
for i in range(len(inp)):
current = inp[i]
remaining = inp[i + 1:]
temp.append(current)
ans.append(tuple(temp))
combine_helper(remaining, temp, ans)
temp.pop()
return ans
print(combine(['a', 'b', 'c', 'd']))
One time, after a power outage, I had to face the same slowness problem each time a breakpoint was hit or a Exception was thrown.
I had the vague remembering that the "suo" file (in the same directory as the "sln" solution file) can be corrupted and make everything slow down.
I deleted my "suo" files and everything was ok. The .suo files deletion is harmless and only implies to recreate my windows layout plus the starting project and a few other non critical customizations.
Groupby A:
In [0]: grp = df.groupby('A')
Within each group, sum over B and broadcast the values using transform. Then sort by B:
In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
B
2 -2.829710
5 -2.829710
1 0.253651
4 0.253651
0 0.551377
3 0.551377
Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:
In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]
In [3]: sort1
Out[3]:
A B C
2 baz -0.528172 False
5 baz -2.301539 True
1 bar -0.611756 True
4 bar 0.865408 False
0 foo 1.624345 False
3 foo -1.072969 True
Finally, sort the 'C' values within groups of 'A' using the sort=False
option to preserve the A sort order from step 1:
In [4]: f = lambda x: x.sort('C', ascending=False)
In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)
In [6]: sort2
Out[6]:
A B C
A
baz 5 baz -2.301539 True
2 baz -0.528172 False
bar 1 bar -0.611756 True
4 bar 0.865408 False
foo 3 foo -1.072969 True
0 foo 1.624345 False
Clean up the df index by using reset_index
with drop=True
:
In [7]: sort2.reset_index(0, drop=True)
Out[7]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
If you use instanceof
, making your equals
implementation final
will preserve the symmetry contract of the method: x.equals(y) == y.equals(x)
. If final
seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the Object
class.
Set ${COMMAND}
to g++
on Linux
Under "Preprocessor Include Paths, Macros, etc." and "CDT GCC Built-in Compiler Settings" there is an undefined ${COMMAND}
variable if you imported the sources from an existing Makefile project.
Eclipse tries to run that command to parse its stdout to find headers, but ${COMMAND}
is not set by default, and so it is not able to do so.
I have explained this in more detail at: How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?
Sadly, @jason-robinson answer above didn't work for me.
Although the rotate function works perfectly:
public static Bitmap rotateImage(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix,
true);
}
I had to do the following to get the orientation as the Exif orientation was always 0
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Cursor cur = managedQuery(imageUri, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
InputStream imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
switch(orientation) {
case 90:
bitmap = rotateImage(chosen_image_bitmap, 90);
break;
case 180:
bitmap = rotateImage(chosen_image_bitmap, 180);
break;
case 270:
bitmap = rotateImage(chosen_image_bitmap, 270);
break;
default:
break;
}
imageView.setImageBitmap(bitmap );
For version 3 of the API, this is simple and working:
var latlngList = [];
latlngList.push(new google.maps.LatLng(lat, lng));
var bounds = new google.maps.LatLngBounds();
latlngList.each(function(n) {
bounds.extend(n);
});
map.setCenter(bounds.getCenter()); //or use custom center
map.fitBounds(bounds);
and some optional tricks:
//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom() - 1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom() > 15){
map.setZoom(15);
}
If you really want to get the type by name you may use the following:
System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");
Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.
Tomcat is not running. Your search is showing you the grep process, which is searching for tomcat. Of course, by the time you see that output, grep is no longer running, so the pid is no longer valid.
I wonder why the best answer that I've found is only in the comments! (by Daenyth with 86 up votes)
git reset --hard origin
This command will sync the local repository with the remote repository getting rid of every change you have made on your local. You can also do the following to fetch the exact branch that you have in the origin.
git reset --hard origin/<branch>
Every response has missed one detail. What if the group only has 1 user.
$count = @(get-adgroupmember $group).count
Put the command in the @() wrapper so that the result is an array no matter what, so even if it is 1 item, you get a count.
I got same error message. I was giving
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe "C:\MyService\MyService.exe"
Instead of
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "C:\MyService\MyService.exe"
Wrap the xml in another element
<wrapper>
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</wrapper>
why don't you use popen?
for ($i=0; $i<10; $i++) {
// open ten processes
for ($j=0; $j<10; $j++) {
$pipe[$j] = popen('script2.php', 'w');
}
// wait for them to finish
for ($j=0; $j<10; ++$j) {
pclose($pipe[$j]);
}
}
U can use mysql dump or query to export data to csv file
SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products
You can set the height
and width
of your divs
with css
.
<style type="text/css">
.box {
height: 150px;
width: 150px;
}
</style>
Is this what you're looking for?
I used this config:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v2.0"/>
<supportedRuntime version="v4.0"/>
</startup>
Worked for me
The most elegant way to do this is with a ByteArrayOutputStream
.
byte a[];
byte b[];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write( a );
outputStream.write( b );
byte c[] = outputStream.toByteArray( );
To open a URL with the default browser, you can execute:
rundll32 url.dll,FileProtocolHandler https://www.google.com
I had issues with URL parameters with the other solutions. However, this one seemed to work correctly.
One thing you should know is $ prefix refers to an Angular Method, $$ prefixes refers to angular methods that you should avoid using.
below is an example template and its controllers, we'll explore how $broadcast/$on can help us achieve what we want.
<div ng-controller="FirstCtrl">
<input ng-model="name"/>
<button ng-click="register()">Register </button>
</div>
<div ng-controller="SecondCtrl">
Registered Name: <input ng-model="name"/>
</div>
The controllers are
app.controller('FirstCtrl', function($scope){
$scope.register = function(){
}
});
app.controller('SecondCtrl', function($scope){
});
My question to you is how do you pass the name to the second controller when a user clicks register? You may come up with multiple solutions but the one we're going to use is using $broadcast and $on.
$broadcast vs $emit
Which should we use? $broadcast will channel down to all the children dom elements and $emit will channel the opposite direction to all the ancestor dom elements.
The best way to avoid deciding between $emit or $broadcast is to channel from the $rootScope and use $broadcast to all its children. Which makes our case much easier since our dom elements are siblings.
Adding $rootScope and lets $broadcast
app.controller('FirstCtrl', function($rootScope, $scope){
$scope.register = function(){
$rootScope.$broadcast('BOOM!', $scope.name)
}
});
Note we added $rootScope and now we're using $broadcast(broadcastName, arguments). For broadcastName, we want to give it a unique name so we can catch that name in our secondCtrl. I've chosen BOOM! just for fun. The second arguments 'arguments' allows us to pass values to the listeners.
Receiving our broadcast
In our second controller, we need to set up code to listen to our broadcast
app.controller('SecondCtrl', function($scope){
$scope.$on('BOOM!', function(events, args){
console.log(args);
$scope.name = args; //now we've registered!
})
});
It's really that simple. Live Example
Other ways to achieve similar results
Try to avoid using this suite of methods as it is neither efficient nor easy to maintain but it's a simple way to fix issues you might have.
You can usually do the same thing by using a service or by simplifying your controllers. We won't discuss this in detail but I thought I'd just mention it for completeness.
Lastly, keep in mind a really useful broadcast to listen to is '$destroy' again you can see the $ means it's a method or object created by the vendor codes. Anyways $destroy is broadcasted when a controller gets destroyed, you may want to listen to this to know when your controller is removed.
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = 0;
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX);
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(message)
.setColor(getResources().getColor(R.color.colorPrimaryDark))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()))
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noBuilder.build());
three different approaches:
Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.
replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.
offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.
There is a Console tab at the bottom of the SQL (query) screen. By default it is not expanded, but once clicked on it should expose tabs for Options, History and Clear. Click on history.
The Query history length is set from within Page Related Settings which found by clicking on the gear wheel at the top right of screen.
This is correct for PHP version 4.5.1-1
do this
while read -r line
do
set -- $line
echo "$1 $2"
done <"file"
$1, $2 etc will be your 1st and 2nd splitted "fields". use $@ to get all values..use $# to get length of the "fields".
This is basically Marco Antônio's answer for a React custom hook, but modified to set the dimensions initially and not only after a resize.
export const useContainerDimensions = myRef => {
const getDimensions = () => ({
width: myRef.current.offsetWidth,
height: myRef.current.offsetHeight
})
const [dimensions, setDimensions] = useState({ width: 0, height: 0 })
useEffect(() => {
const handleResize = () => {
setDimensions(getDimensions())
}
if (myRef.current) {
setDimensions(getDimensions())
}
window.addEventListener("resize", handleResize)
return () => {
window.removeEventListener("resize", handleResize)
}
}, [myRef])
return dimensions;
};
Used in the same way:
const MyComponent = () => {
const componentRef = useRef()
const { width, height } = useContainerDimensions(componentRef)
return (
<div ref={componentRef}>
<p>width: {width}px</p>
<p>height: {height}px</p>
<div/>
)
}
For one-liners, userandom.sample(list_to_be_shuffled, length_of_the_list)
with an example:
import random
random.sample(list(range(10)), 10)
outputs: [2, 9, 7, 8, 3, 0, 4, 1, 6, 5]
There are two ways. One is to aggregate:
SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'
The other is to use an array constructor:
SELECT ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name = 'aean')
I'm presuming this is for plpgsql. In that case you can assign it like this:
colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);
A clean dplyr
solution, taken from here
library(dplyr)
df <- tibble(x = 1:2, y = c("a", "b"))
df %>% slice(rep(1:n(), each = 2))
Of course the best approach is to use the ever-more-supported <input type="search" />
.
Anyway for a bit of coding fun I thought that it could be achieved also using the form's reset button, and this is the working result (it is worth noting that you cannot have other inputs in the form but the search field with this approach, or the reset button will erase them too), no javascript needed:
form{
position: relative;
width: 200px;
}
form input {
width: 100%;
padding-right: 20px;
box-sizing: border-box;
}
form input:placeholder-shown + button{
opacity: 0;
pointer-events: none;
}
form button {
position: absolute;
border: none;
display: block;
width: 15px;
height: 15px;
line-height: 16px;
font-size: 12px;
border-radius: 50%;
top: 0;
bottom: 0;
right: 5px;
margin: auto;
background: #ddd;
padding: 0;
outline: none;
cursor: pointer;
transition: .1s;
}
_x000D_
<form>
<input type="text" placeholder=" " />
<button type="reset">×</button>
</form>
_x000D_
Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.
fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"
If you want to know if any activity of your app is visible on the screen, you can do something like this:
public class MyAppActivityCallbacks implements Application.ActivityLifecycleCallbacks {
private Set<Class<Activity>> visibleActivities = new HashSet<>();
@Override
public void onActivityResumed(Activity activity) {
visibleActivities.add((Class<Activity>) activity.getClass());
}
@Override
public void onActivityStopped(Activity activity) {
visibleActivities.remove(activity.getClass());
}
public boolean isAnyActivityVisible() {
return !visibleActivities.isEmpty();
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivityDestroyed(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}}
Just create a singleton of this class and set it in your Application instance like below:
class App extends Application{
@Override
public void onCreate() {
registerActivityLifecycleCallbacks(myAppActivityCallbacks);
}
}
Then you can use isAnyActivityVisible() method of your MyAppActivityCallbacks instance everywhere!
If you spell the class name wrong or the class isn't on the classpath, the JSP processor will say it "resolves to a package" rather than that it doesn't exist. This was driving me crazy today as I kept not seeing a typo I'd made.
EXAMPLE:- Although it is not very common that we find ourselves in need of a 302 redirect, this option can be very useful in some cases. These are the most frequent cases:
A redirect 302 is a code that tells visitors of a specific URL that the page has been moved temporarily, directing them directly to the new location.
In other words, redirect 302 is activated when Google robots or other search engines request to load a specific page. At that moment, thanks to this redirection, the server returns an automatic response indicating a new URL.
In this way errors and annoyances are avoided both to search engines and users, guaranteeing smooth navigation.
For More details Refer this Article.
you could deserialize your json string into a dictionary and then add new properties then serialize it.
var jsonString = @"{}";
var jsonDoc = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);
jsonDoc.Add("Name", "Khurshid Ali");
Console.WriteLine(JsonSerializer.Serialize(jsonDoc));
A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =
:
HOME=c
An environment variable is a regular variable that has been marked for export to the environment.
export HOME
HOME=c
You can combine the assignment with the export
statement.
export HOME=c
Dataframes have a sort_index
method which returns a copy by default. Pass inplace=True
to operate in place.
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())
Gives me:
A
1 4
29 2
100 1
150 5
234 3
Don't loop through a file this way. Instead use a for
loop.
for line in f:
vowel += sum(ch.isvowel() for ch in line)
In fact your whole program is just:
VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
vowel = sum(ch in VOWELS for line in f for ch in line.strip())
That said, if you really want to keep using a while
loop for some misguided reason:
while True:
line = f.readline().strip()
if line == '':
# either end of file or just a blank line.....
# we'll assume EOF, because we don't have a choice with the while loop!
break
When [dropping] the encoding settings mentioned above all characters [are rendered] correctly but the encoding that is detected shows either windows-1252 or ISO-8859-1 depending on the browser.
Then that's what you're really sending. None of the encoding settings in your bullet list will actually modify your output in any way; all they do is tell the browser what encoding to assume when interpreting what you send. That's why you're getting those ?s - you're telling the browser that what you're sending is UTF-8, but it's really ISO-8859-1.
<c:if test="${companies.size() > 0}">
</c:if>
This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt
instead of >
.
<c:if test="${companies.size() gt 0}">
</c:if>
If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length()
function then. From the documentation:
length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.
Put this at the top of JSP page to allow the fn
namespace:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Or if you're using JSPX or Facelets:
<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">
And use like this in your page:
<p>The length of the companies collection is: ${fn:length(companies)}</p>
So to test with length of a collection:
<c:if test="${fn:length(companies) gt 0}">
</c:if>
Alternatively, for this specific case you can also simply use the EL empty
operator:
<c:if test="${not empty companies}">
</c:if>
this error appeared to me because my php-fpm
image enabled cron
, and I have no idea why
Try this instead:
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumall = str(sumall) # add this line
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln
sumall
is a number, and you can't access its digits using the subscript notation (sumall[0]
, sumall[1]
). For that to work, you'll need to transform it back to a string.
Example/Scenario for Abstract Factory
I live in a place where it rains in the rainy season, snows in winter and hot and sunny in summers. I need different kind of clothes to protect myself from the elements. To do so I go to the store near my house and ask for clothing/items to protect myself. The store keeper gives me the appropriate item as per the environment and depth of my pocket. The items he gives me are of same level of quality and price range. Since he is aware of my standards its easy for him to do so. But when a rich guy from across the street comes up with the same requirements he gets an expensive, branded item. One noticeable thing is all the items he gives to me complement each other in term quality, standard and cost. One can say they go with each other. Same is the case with the items this rich guy gets.
So by looking at above scenario, I now appreciate the efficiency of the shop keeper. I can replace this shopkeeper with an Abstract Shop. The items we get with abstract items and me and the rich as perspective clients. All we need is the product/item which suits our needs.
Now I can easily see myself considering an online store which provides a set of services to its numerous clients. Each client belongs to one of the three groups. When a premium group user opens up the site he gets great UI, highly customised advertisement pane, more options in the menus etc. These same set of features are presented to gold user but the functionality in the menu is less, advertisements are mostly relevent, and slightly less egronomic UI. Last is my kind of user, a ‘free group’ user. I am just served enough so that I do not get offended. The UI is a bare minimum, advertisements are way off track so much so that I do not know what comes in it, lastly the menu has only log out.
If I get a chance to build something like this website I would definitely consider Abstract Factory Pattern.
Abstract Products : Advertisement Pane, Menu, UI painter.
Abstract Factory : Web Store User Experience
Concreate Factory: Premium User Experience, Gold User Experience, General User Experience.
I faced the same 415
http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON.
In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.
As mentioned in the other responses I have correctly set the Accept
and Content-Type
headers to application/json
, but it doesn't suffice.
Solution
I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.
Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:
Wrong
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
Right
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO() {
}
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
I lost hours, I hope this'll save yours ;-)
The current "pipable" variant of this operator is called finalize()
(since RxJS 6). The older and now deprecated "patch" operator was called finally()
(until RxJS 5.5).
I think finalize()
operator is actually correct. You say:
do that logic only when I subscribe, and after the stream has ended
which is not a problem I think. You can have a single source
and use finalize()
before subscribing to it if you want. This way you're not required to always use finalize()
:
let source = new Observable(observer => {
observer.next(1);
observer.error('error message');
observer.next(3);
observer.complete();
}).pipe(
publish(),
);
source.pipe(
finalize(() => console.log('Finally callback')),
).subscribe(
value => console.log('#1 Next:', value),
error => console.log('#1 Error:', error),
() => console.log('#1 Complete')
);
source.subscribe(
value => console.log('#2 Next:', value),
error => console.log('#2 Error:', error),
() => console.log('#2 Complete')
);
source.connect();
This prints to console:
#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message
Jan 2019: Updated for RxJS 6
I am using Tortoise SVN client. You can alternativley check out the required project from SVN in some folder. You can see a .SVN folder inside the project. Copy the .SVN folder into the workspace folder. Now remove the project from eclipse and import the same again into eclipse. You can see now the project is now associated with svn
Change the directory and point to your current project folder and then "npm install". .
This will install all dependencies and modules into your project folder.
Its an auto-implemented property for C#.
You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page
Also you can use Flash to embed the document into any HTML page like that:
<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
<p>
It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
</p>
</object>
If you put
window.location.reload(true);
at the beginning of your page with no other condition qualifying why that code runs, the page will load and then continue to reload itself until you close your browser.
You're looking for the function strcmp
, or strncmp
from string.h
.
Since strings are just arrays, you need to compare each character, so this function will do that for you:
if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
Further reading: strcmp at cplusplus.com
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Normally you would select IDs using the ID selector #
, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):
div[id^="player_"]
If you are able to modify that HTML, however, you should add a class to your player div
s then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.
[[ $list =~ (^|[[:space:]])$x($|[[:space:]]) ]] && echo 'yes' || echo 'no'
or create a function:
contains() {
[[ $1 =~ (^|[[:space:]])$2($|[[:space:]]) ]] && exit(0) || exit(1)
}
to use it:
contains aList anItem
echo $? # 0: match, 1: failed
In C++11, the using
keyword when used for type alias
is identical to typedef
.
7.1.3.2
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.
Bjarne Stroustrup provides a practical example:
typedef void (*PFD)(double); // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double); // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP
Pre-C++11, the using
keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):
class Derived : public Base {
public:
using Base::f; // lift Base's f into Derived's scope -- works in C++98
void f(char); // provide a new f
void f(int); // prefer this f to Base::f(int)
using Base::Base; // lift Base constructors Derived's scope -- C++11 only
Derived(char); // provide a new constructor
Derived(int); // prefer this constructor to Base::Base(int)
// ...
};
Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard
, Design decisions
, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.
Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.
First let’s consider a toy example:
template <typename T> class MyAlloc {/*...*/}; template <typename T, class A> class MyVector {/*...*/}; template <typename T> struct Vec { typedef MyVector<T, MyAlloc<T> > type; }; Vec<int>::type p; // sample usage
The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.
template <typename T> void foo (Vec<T>::type&);
So, the syntax is somewhat ugly. We would rather avoid the nested
::type
We’d prefer something like the following:template <typename T> using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below Vec<int> p; // sample usage
Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on
Vec<T>
in deducible context, and the syntax is improved as well. For example we could rewrite foo as:template <typename T> void foo (Vec<T>&);
We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to
foo(p)
will succeed.
The follow-up paper n1489 explains why using
instead of using typedef
:
It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:
template<class T> typedef std::vector<T, MyAllocator<T> > Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector< [bullet] , MyAllocator< [bullet] > >
– where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentencetemplate<class T> using Vec = std::vector<T, MyAllocator<T> >;
can be read/interpreted as: from now on, I’ll be using
Vec<T>
as a synonym forstd::vector<T, MyAllocator<T> >
. With that reading, the new syntax for aliasing seems reasonably logical.
I think the important distinction is made here, aliases instead of types. Another quote from the same document:
An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.
Summary, for the role of using
:
namespace PO = boost::program_options
and using PO = ...
equivalent)A typedef declaration can be viewed as a special case of non-template alias-declaration
. It's an aesthetic change, and is considered identical in this case.namespace std
into the global scope), member functions, inheriting constructorsIt cannot be used for:
int i;
using r = i; // compile-error
Instead do:
using r = decltype(i);
Naming a set of overloads.
// bring cos into scope
using std::cos;
// invalid syntax
using std::cos(double);
// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);
Often i reach for the abbreviation html tag in this situation.
<abbr title="Hover">Text</abbr>
Seems there is missing MongoDB driver. Include the following dependency to pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Try this:
CONCATENATE(""""; B2 ;"""")
@widor provided a nice solution alternative too - integrated with mine:
CONCATENATE(char(34); B2 ;char(34))
In your example you use the href
attribute to tell where the JavaScript file can be found. This should be the src
attribute:
?> <script type="text/javascript" src="file.js"></script> <?php
For more information see w3schools.
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
I have this:
def has_extension(filename, extension):
ext = "." + extension
if filename.endswith(ext):
return True
else:
return False