For general purposes of copying any text to the clipboard, I wrote the following function:
function textToClipboard (text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
The value of the parameter is inserted into value of a newly created <textarea>
, which is then selected, its value is copied to the clipboard and then it gets removed from the document.
Just in case someone still needs it. The successful, not official, way to rename indexes are:
If you happen to get this error "dangled index directory name is", remove index folder in all master nodes (not data nodes), and restart one of the data nodes.
If you happen to reach here, and you are working with C#, here is the code:
var cancellationToken = new CancellationToken();
var request = new ScanRequest("TableName") {Select = Select.COUNT};
var result = context.Client.ScanAsync(request, cancellationToken).Result;
totalCount = result.Count;
You can delete one or more indices, which really deletes their files from disk. For example:
curl -XDELETE localhost:9200/$INDEXNAME
Where $INDEXNAME
can be an index name (e.g. users_v2
), N indices separated by comma (e.g. users_v2,users_v3
). An index pattern (e.g. users_*
) or _all
, also works, unless it's blocked in the config via action.destructive_requires_name: true
.
Deleting individual documents is possible, but this won't immediately purge them. A delete is only a soft delete, and documents are really removed during segment merges. You'll find lots of details about segments and merges in this presentation. It's about Solr, but merges are from Lucene, so you have the same options in Elasticsearch.
Back to the API, you can either delete individual documents by ID (provide a routing value if you index with routing):
curl -XDELETE localhost:9200/users_v2/_doc/user1
Or by query:
curl -XPOST -H 'Content-Type: application/json' localhost:9200/users_v2/_delete_by_query -d '{
"query": {
"match": {
"description_field": "bad user"
}
}
}'
To avoid using curl or Chrome plugins you can just use the the built in windows Powershell. From the Powershell command window run
Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:9200/sampleindex/sampleType/" -
Method POST -ContentType "application/json" -Body '{
"user" : "Test",
"post_date" : "2017/11/13 11:07:00",
"message" : "trying out Elasticsearch"
}'
Note the Index name MUST be in lowercase.
This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.
The solution for me, partly from here was:
And all was well.
I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
This might not be relevant to your specific problem, but the error message you mentioned has many causes, one of them is using a return type for an [OperationContract] that is either abstract, interface, or not known to the WCF client code.
Check the post (and solution) below
You can use array to handle several button click listener in android like this: here i am setting button click listener for n buttons by using array as:
Button btn[] = new Button[n];
NOTE: n is a constant positive integer
Code example:
//class androidMultipleButtonActions
package a.b.c.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class androidMultipleButtonActions extends Activity implements OnClickListener{
Button btn[] = new Button[3];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn[0] = (Button) findViewById(R.id.Button1);
btn[1] = (Button) findViewById(R.id.Button2);
btn[2] = (Button) findViewById(R.id.Button3);
for(int i=0; i<3; i++){
btn[i].setOnClickListener(this);
}
}
public void onClick(View v) {
if(v == findViewById(R.id.Button1)){
//do here what u wanna do.
}
else if(v == findViewById(R.id.Button2)){
//do here what u wanna do.
}
else if(v == findViewById(R.id.Button3)){
//do here what u wanna do.
}
}
}
Note: First write an main.xml file if u dont know how to write please mail to: [email protected]
This worked for me:
Dim binding As New WebHttpBinding(WebHttpSecurityMode.Transport)
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None
binding.MaxBufferSize = Integer.MaxValue
binding.MaxReceivedMessageSize = Integer.MaxValue
binding.MaxBufferPoolSize = Integer.MaxValue
My solution was rather simple: backup everything from the application, uninstall it, delete everything from the remaining folders (but not the folders so I won't have to grant the same permissions again) then copy back the files from the backup.
app.config
<client>
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="LisansSoap"
contract="Lisans.LisansSoap"
name="LisansSoap" />
</client>
program
Lisans.LisansSoapClient test = new LisansSoapClient("LisansSoap",
"http://webservis.uzmanevi.com/Lisans/Lisans.asmx");
MessageBox.Show(test.LisansKontrol("","",""));
I have had this issue before.
client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
do this against your wcf proxy before making the call.
In your binding configuration, there are four timeout values you can tweak:
<bindings>
<basicHttpBinding>
<binding name="IncreasedTimeout"
sendTimeout="00:25:00">
</binding>
</basicHttpBinding>
The most important is the sendTimeout
, which says how long the client will wait for a response from your WCF service. You can specify hours:minutes:seconds
in your settings - in my sample, I set the timeout to 25 minutes.
The openTimeout
as the name implies is the amount of time you're willing to wait when you open the connection to your WCF service. Similarly, the closeTimeout
is the amount of time when you close the connection (dispose the client proxy) that you'll wait before an exception is thrown.
The receiveTimeout
is a bit like a mirror for the sendTimeout
- while the send timeout is the amount of time you'll wait for a response from the server, the receiveTimeout
is the amount of time you'll give you client to receive and process the response from the server.
In case you're send back and forth "normal" messages, both can be pretty short - especially the receiveTimeout
, since receiving a SOAP message, decrypting, checking and deserializing it should take almost no time. The story is different with streaming - in that case, you might need more time on the client to actually complete the "download" of the stream you get back from the server.
There's also openTimeout, receiveTimeout, and closeTimeout. The MSDN docs on binding gives you more information on what these are for.
To get a serious grip on all the intricasies of WCF, I would strongly recommend you purchase the "Learning WCF" book by Michele Leroux Bustamante:
and you also spend some time watching her 15-part "WCF Top to Bottom" screencast series - highly recommended!
For more advanced topics I recommend that you check out Juwal Lowy's Programming WCF Services book.
Try changing your security mode to "transport".
You have a mismatch between the security tag and the transport tag.
Another possible solution to this error that I found. Might not have answered OP's exact question but may help others who stumble across this error message.
I was creating my Client in code using WebHttpBinding, in order to replicate the following line:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" proxyCredentialType="Windows" />
</security>
I had to do:
var binding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Windows;
as well as setting proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
Try setting maxReceivedMessageSize on the server too, e.g. to 4MB:
<binding name="MyService.MyServiceBinding"
maxReceivedMessageSize="4194304">
The main reason the default (65535 I believe) is so low is to reduce the risk of Denial of Service (DoS) attacks. You need to set it bigger than the maximum request size on the server, and the maximum response size on the client. If you're in an Intranet environment, the risk of DoS attacks is probably low, so it's probably safe to use a value much higher than you expect to need.
By the way a couple of tips for troubleshooting problems connecting to WCF services:
Enable tracing on the server as described in this MSDN article.
Use an HTTP debugging tool such as Fiddler on the client to inspect the HTTP traffic.
I think you are trying to configure your service in a similar way to the following config. There is more information here: Specify a Service with Two Endpoints Using Different Binding Values. Also, other than for development, it's probably not a good idea to have both HTTP & HTTPS endpoints to the same service. It kinda defeats the purpose of HTTPS. Hope this helps!
<service type="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null">
<endpoint
address="http://computer:8080/Hello"
contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
binding="basicHttpBinding"
bindingConfiguration="shortTimeout"
</endpoint>
<endpoint
address="http://computer:8080/Hello"
contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
binding="basicHttpBinding"
bindingConfiguration="Secure"
</endpoint>
</service>
<bindings>
<basicHttpBinding
name="shortTimeout"
timeout="00:00:00:01"
/>
<basicHttpBinding
name="Secure">
<Security mode="Transport" />
</basicHttpBinding>
</bindings>
Yes. I recommend you check out Kimberly Tripp's articles on indexing.
If an index is "covering", then there is no need to use anything but the index. In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.
Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.
You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.
If you have date in DateTime
variable then its a DateTime
object and doesn't contain any format. Formatted date are expressed as string
when you call DateTime.ToString
method and provide format in it.
Lets say you have two DateTime
variable, you can use the compare method for comparision,
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Code snippet taken from msdn.
If script execution order is not the issue, another possible cause of the problem is that the element is not being selected properly:
getElementById
requires the passed string to be the ID verbatim, and nothing else. If you prefix the passed string with a #
, and the ID does not start with a #
, nothing will be selected:
<div id="foo"></div>
// Error, selected element will be null:
document.getElementById('#foo')
// Fix:
document.getElementById('foo')
Similarly, for getElementsByClassName
, don't prefix the passed string with a .
:
<div class="bar"></div>
// Error, selected element will be undefined:
document.getElementsByClassName('.bar')[0]
// Fix:
document.getElementsByClassName('bar')[0]
With querySelector, querySelectorAll, and jQuery, to match an element with a particular class name, put a .
directly before the class. Similarly, to match an element with a particular ID, put a #
directly before the ID:
<div class="baz"></div>
// Error, selected element will be null:
document.querySelector('baz')
$('baz')
// Fix:
document.querySelector('.baz')
$('.baz')
The rules here are, in most cases, identical to those for CSS selectors, and can be seen in detail here.
To match an element which has two or more attributes (like two class names, or a class name and a data-
attribute), put the selectors for each attribute next to each other in the selector string, without a space separating them (because a space indicates the descendant selector). For example, to select:
<div class="foo bar"></div>
use the query string .foo.bar
. To select
<div class="foo" data-bar="someData"></div>
use the query string .foo[data-bar="someData"]
. To select the <span>
below:
<div class="parent">
<span data-username="bob"></span>
</div>
use div.parent > span[data-username="bob"]
.
Capitalization and spelling does matter for all of the above. If the capitalization is different, or the spelling is different, the element will not be selected:
<div class="result"></div>
// Error, selected element will be null:
document.querySelector('.results')
$('.Result')
// Fix:
document.querySelector('.result')
$('.result')
You also need to make sure the methods have the proper capitalization and spelling. Use one of:
$(selector)
document.querySelector
document.querySelectorAll
document.getElementsByClassName
document.getElementsByTagName
document.getElementById
Any other spelling or capitalization will not work. For example, document.getElementByClassName
will throw an error.
Make sure you pass a string to these selector methods. If you pass something that isn't a string to querySelector
, getElementById
, etc, it almost certainly won't work.
If the HTML attributes on elements you want to select are surrounded by quotes, they must be plain straight quotes (either single or double); curly quotes like ‘
or ”
will not work if you're trying to select by ID, class, or attribute.
When Bootstrap Select initializes, it'll build a set of custom divs that run alongside the original <select>
element and will typically synchronize state between the two input mechanisms.
Which is to say that one way to handle events on bootstrap select is to listen for events on the original select that it modifies, regardless of who updated it.
Just listen for a change
event and get the selected value using javascript or jQuery like this:
$('select').on('change', function(e){
console.log(this.value,
this.options[this.selectedIndex].value,
$(this).find("option:selected").val(),);
});
*NOTE: As with any script reliant on the DOM, make sure you wait for the DOM ready event before executing
$(function() {_x000D_
_x000D_
$('select').on('change', function(e){_x000D_
console.log(this.value,_x000D_
this.options[this.selectedIndex].value,_x000D_
$(this).find("option:selected").val(),);_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option val="Must"> Mustard </option>_x000D_
<option val="Cat" > Ketchup </option>_x000D_
<option val="Rel" > Relish </option>_x000D_
</select>
_x000D_
As this answer alludes, Bootstrap Select has their own set of custom events, including changed.bs.select
which:
fires after the select's value has been changed. It passes through event, clickedIndex, newValue, oldValue.
And you can use that like this:
$("select").on("changed.bs.select",
function(e, clickedIndex, newValue, oldValue) {
console.log(this.value, clickedIndex, newValue, oldValue)
});
$(function() {_x000D_
_x000D_
$("select").on("changed.bs.select", _x000D_
function(e, clickedIndex, newValue, oldValue) {_x000D_
console.log(this.value, clickedIndex, newValue, oldValue)_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option val="Must"> Mustard </option>_x000D_
<option val="Cat" > Ketchup </option>_x000D_
<option val="Rel" > Relish </option>_x000D_
</select>
_x000D_
If you set width: auto
to a block element, then the width would be 100%. So it really doesn't make much sense to have the auto
value here. It is really the same for height, because by default any element is set to an automatic height.
So finally your div#container
is actually centered, but it just occupies the whole width of its parent element. You do the centering right, and you need just to change the width (if needed) to see that it is really centered. If you want to center your #main_content then just apply margin: 0 auto;
on it.
try this..
<tr ng-repeat='item in items'>
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>
as another option:
$ curl -i http://google.com
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Sat, 19 Jun 2010 04:15:10 GMT
Expires: Mon, 19 Jul 2010 04:15:10 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
But it doesn't go past the first one.
$('img.conversation_img[alt="example"]')
.each(function(){
alert($(this).attr('src'))
});
This will display src attributes of all images of class 'conversation_img' with alt='example'
I was able to go around the whole thing by replacing the context reference from this
or Context.this
to getapplicationcontext
.
Selector name{
font-weight:bold;
}
Suppose you want to make bold for p element
p{
font-weight:bold;
}
You can use other alternative value instead of bold like
p{
font-weight:bolder;
font-weight:600;
}
The param ?v=1.123
indicates a query string, and the browser will therefore think it is a new path from, say, ?v=1.0
. Thus causing it to load from file, not from cache. As you want.
And, the browser will assume that the source will stay the same next time you call ?v=1.123
and should cache it with that string. So it will remain cached, however your server is set up, until you move to ?v=1.124
or so on.
This worked for me:
refreshTableSorce() {
this.dataSource = new MatTableDataSource<Element>(this.newSource);
}
I combined some beautiful answers here to make it possible to easily support more Expression operators.
This is based on the answer of @Dejan but now it's quite easy to add the OR as well. I chose not to make the Combine
function public, but you could do that to be even more flexible.
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.AndAlso);
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.Or);
public static Expression<Func<T, bool>> Combine<T>(Expression<Func<T, bool>> leftExpression, Expression<Func<T, bool>> rightExpression, Func<Expression, Expression, BinaryExpression> combineOperator)
{
var leftParameter = leftExpression.Parameters[0];
var rightParameter = rightExpression.Parameters[0];
var visitor = new ReplaceParameterVisitor(rightParameter, leftParameter);
var leftBody = leftExpression.Body;
var rightBody = visitor.Visit(rightExpression.Body);
return Expression.Lambda<Func<T, bool>>(combineOperator(leftBody, rightBody), leftParameter);
}
private class ReplaceParameterVisitor : ExpressionVisitor
{
private readonly ParameterExpression _oldParameter;
private readonly ParameterExpression _newParameter;
public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return ReferenceEquals(node, _oldParameter) ? _newParameter : base.VisitParameter(node);
}
}
}
Usage is not changed and still like this:
Expression<Func<Result, bool>> noFilterExpression = item => filters == null;
Expression<Func<Result, bool>> laptopFilterExpression = item => item.x == ...
Expression<Func<Result, bool>> dateFilterExpression = item => item.y == ...
var combinedFilterExpression = noFilterExpression.Or(laptopFilterExpression.AndAlso(dateFilterExpression));
efQuery.Where(combinedFilterExpression);
(This is an example based on my actual code, but read is as pseudo-code)
your answer is:
round((strtotime($day2) - strtotime($day1))/(60*60))
Try to set processData: false in ajax settings like this
$.ajax({
url : base_url+'index.php',
type: 'POST',
dataType: 'json',
data: data,
cache : false,
processData: false
}).done(function(response) {
alert(response);
});
Make sure you have Desktop Development with C++ installed. I was experiencing the same problem because I only had Universal Windows Platform Development installed.
As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:
array_push($md_array['recipe_type'], $newdata);
You can write that for example:
private Date TruncarFecha(Date fechaParametro) throws ParseException {
String fecha="";
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
fecha =outputFormatter.format(fechaParametro);
return outputFormatter.parse(fecha);
}
... Or just replace body
by documentElement
:
document.documentElement.scrollTop = 0;
let arr=[1,2,3,3,4,5,5,6,7,7]
let obj={}
for(var i=0;i<arr.length;i++){
obj[arr[i]]=obj[arr[i]]!=null ?obj[arr[i]]+1:1 //stores duplicate in an obj
}
console.log(obj)
//returns object {1:1,:1,3:2,.....}
If you have no choice other than using double values, can use the below code.
public static double sumDouble(double value1, double value2) {
double sum = 0.0;
String value1Str = Double.toString(value1);
int decimalIndex = value1Str.indexOf(".");
int value1Precision = 0;
if (decimalIndex != -1) {
value1Precision = (value1Str.length() - 1) - decimalIndex;
}
String value2Str = Double.toString(value2);
decimalIndex = value2Str.indexOf(".");
int value2Precision = 0;
if (decimalIndex != -1) {
value2Precision = (value2Str.length() - 1) - decimalIndex;
}
int maxPrecision = value1Precision > value2Precision ? value1Precision : value2Precision;
sum = value1 + value2;
String s = String.format("%." + maxPrecision + "f", sum);
sum = Double.parseDouble(s);
return sum;
}
For me, I tried to check out a SVN-project with TortoiseGit. It worked fine if I used TortoiseSVN though. (May seem obvious, but newcomers may stumble on this one)
The boolean needs to depend on the template parameter being deduced. So an easy way to fix is to use a default boolean parameter:
template< class T >
class Y {
public:
template < bool EnableBool = true, typename = typename std::enable_if<( std::is_same<T, double>::value && EnableBool )>::type >
T foo() {
return 10;
}
};
However, this won't work if you want to overload the member function. Instead, its best to use TICK_MEMBER_REQUIRES
from the Tick library:
template< class T >
class Y {
public:
TICK_MEMBER_REQUIRES(std::is_same<T, double>::value)
T foo() {
return 10;
}
TICK_MEMBER_REQUIRES(!std::is_same<T, double>::value)
T foo() {
return 10;
}
};
You can also implement your own member requires macro like this(just in case you don't want to use another library):
template<long N>
struct requires_enum
{
enum class type
{
none,
all
};
};
#define MEMBER_REQUIRES(...) \
typename requires_enum<__LINE__>::type PrivateRequiresEnum ## __LINE__ = requires_enum<__LINE__>::type::none, \
class=typename std::enable_if<((PrivateRequiresEnum ## __LINE__ == requires_enum<__LINE__>::type::none) && (__VA_ARGS__))>::type
Here is a polyglot program for BASH and Windows CMD that runs a series of commands and quits out if any of them fail:
#!/bin/bash 2> nul
:; set -o errexit
:; function goto() { return $?; }
command 1 || goto :error
command 2 || goto :error
command 3 || goto :error
:; exit 0
exit /b 0
:error
exit /b %errorlevel%
I have used this type of thing in the past for a multiple platform continuous integration script.
XML Element is a XML Node but with additional elements like attributes.
<a>Lorem Ipsum</a> //This is a node
<a id="sample">Lorem Ipsum</a> //This is an element
First of all, make 'E' in enum, 'e' as a lower case.
Second, drop type name 'Days' in 'Days.Saturday'.
Third ...buy yourself a good C++ book.
There are some good answers already. I'll focus mainly on what I think they lack - an explanation of the "cons" with the copy-and-swap idiom....
What is the copy-and-swap idiom?
A way of implementing the assignment operator in terms of a swap function:
X& operator=(X rhs)
{
swap(rhs);
return *this;
}
The fundamental idea is that:
the most error-prone part of assigning to an object is ensuring any resources the new state needs are acquired (e.g. memory, descriptors)
that acquisition can be attempted before modifying the current state of the object (i.e. *this
) if a copy of the new value is made, which is why rhs
is accepted by value (i.e. copied) rather than by reference
swapping the state of the local copy rhs
and *this
is usually relatively easy to do without potential failure/exceptions, given the local copy doesn't need any particular state afterwards (just needs state fit for the destructor to run, much as for an object being moved from in >= C++11)
When should it be used? (Which problems does it solve [/create]?)
When you want the assigned-to objected unaffected by an assignment that throws an exception, assuming you have or can write a swap
with strong exception guarantee, and ideally one that can't fail/throw
..†
When you want a clean, easy to understand, robust way to define the assignment operator in terms of (simpler) copy constructor, swap
and destructor functions.
† swap
throwing: it's generally possible to reliably swap data members that the objects track by pointer, but non-pointer data members that don't have a throw-free swap, or for which swapping has to be implemented as X tmp = lhs; lhs = rhs; rhs = tmp;
and copy-construction or assignment may throw, still have the potential to fail leaving some data members swapped and others not. This potential applies even to C++03 std::string
's as James comments on another answer:
@wilhelmtell: In C++03, there is no mention of exceptions potentially thrown by std::string::swap (which is called by std::swap). In C++0x, std::string::swap is noexcept and must not throw exceptions. – James McNellis Dec 22 '10 at 15:24
‡ assignment operator implementation that seems sane when assigning from a distinct object can easily fail for self-assignment. While it might seem unimaginable that client code would even attempt self-assignment, it can happen relatively easily during algo operations on containers, with x = f(x);
code where f
is (perhaps only for some #ifdef
branches) a macro ala #define f(x) x
or a function returning a reference to x
, or even (likely inefficient but concise) code like x = c1 ? x * 2 : c2 ? x / 2 : x;
). For example:
struct X
{
T* p_;
size_t size_;
X& operator=(const X& rhs)
{
delete[] p_; // OUCH!
p_ = new T[size_ = rhs.size_];
std::copy(p_, rhs.p_, rhs.p_ + rhs.size_);
}
...
};
On self-assignment, the above code delete's x.p_;
, points p_
at a newly allocated heap region, then attempts to read the uninitialised data therein (Undefined Behaviour), if that doesn't do anything too weird, copy
attempts a self-assignment to every just-destructed 'T'!
? The copy-and-swap idiom can introduce inefficiencies or limitations due to the use of an extra temporary (when the operator's parameter is copy-constructed):
struct Client
{
IP_Address ip_address_;
int socket_;
X(const X& rhs)
: ip_address_(rhs.ip_address_), socket_(connect(rhs.ip_address_))
{ }
};
Here, a hand-written Client::operator=
might check if *this
is already connected to the same server as rhs
(perhaps sending a "reset" code if useful), whereas the copy-and-swap approach would invoke the copy-constructor which would likely be written to open a distinct socket connection then close the original one. Not only could that mean a remote network interaction instead of a simple in-process variable copy, it could run afoul of client or server limits on socket resources or connections. (Of course this class has a pretty horrid interface, but that's another matter ;-P).
To make a sticky nav you need to add the class navbar-fixed-top to your nav
Official documentation:
http://getbootstrap.com/components/#navbar-fixed-top
Official example:
http://getbootstrap.com/examples/navbar-fixed-top/
A simple example code:
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
...
</div>
</nav>
with related jsfiddle: http://jsfiddle.net/ur7t8/
If you want the nav bar to resize while you scroll the page you can give a look to this example: http://www.bootply.com/109943
JS
$(window).scroll(function() {
if ($(document).scrollTop() > 50) {
$('nav').addClass('shrink');
} else {
$('nav').removeClass('shrink');
}
});
CSS
nav.navbar.shrink {
min-height: 35px;
}
To add an animation while you scroll, all you need to do is set a transition on the nav
CSS
nav.navbar{
background-color:#ccc;
// Animation
-webkit-transition: all 0.4s ease;
transition: all 0.4s ease;
}
I made a jsfiddle with the full example code: http://jsfiddle.net/Filo/m7yww8oa/
Try like this.
You must give a function as value to onClick()
You button:
<button type="button" onClick={ refreshPage }> <span>Reload</span> </button>
refreshPage function:
function refreshPage(){
window.location.reload();
}
I'd remove the autoplay
attribute, since if the browser encounters it, it autoplays!
autoplay
is a HTML boolean attribute, but be aware that the values true
and false
are not allowed. To represent a false
value, you must omit the attribute.
The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
Also, the type goes inside the source, like this:
<video width="640" height="480" controls preload="none">
<source src="http://example.com/mytestfile.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
References:
Use the string concatenation operator:
Dim str As String = New String("") & "some other string"
Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.
This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.
See "How to: Concatenate Multiple Strings" for more information on both methods.
Code:
str = "http://localhost/with spaces and spaces"
encoded = URI::encode(str)
puts encoded
Result:
http://localhost/with%20spaces%20and%20spaces
If you are looking for a popup in the page, that is not a new browser window, then I would take a look at the various "LightBox" implementations in Javascript.
This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.
Follow below steps (assuming you are building it using CMake GUI)
Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it
Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.
Unzip the folder.
Open CMake
Click Browse Source and navigate to your openCV folder.
Click Browse Build and navigate to your build Folder.
Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.
Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)
Click Configure again, then Click Generate.
Go to build folder
# cd build
# make
# sudo make install
I had the same problem quite a few times. It happened especially when i tried to paste a few lines of code from an editor online, the spaces are not registered properly as 'tabs' or 'spaces'.
However the fix was quite simple. I just had to remove the spacing across all the lines of code in that specific set and space it again with the tabs correctly. This fixed my problem.
You are assigning reloaded items to global variable items in onResume()
, but this will not reflect in ItemAdapter
class, because it has its own instance variable called 'items'.
For refreshing ListView
, add a refresh() in ItemAdapter
class which accepts list data i.e items
class ItemAdapter
{
.....
public void refresh(List<Item> items)
{
this.items = items;
notifyDataSetChanged();
}
}
update onResume()
with following code
@Override
public void onResume()
{
super.onResume();
items.clear();
items = dbHelper.getItems(); //reload the items from database
**adapter.refresh(items);**
}
Mp4 files can be playable with transparent background using seeThrou Js library. All you need to combine actual video and alpha channel in the single video. Also make sure to keep video height dimension below 1400 px as some of the old iphone devices wont play videos with dimension more than 2000. This is pretty useful in safari desktop and mobile devices which doesnt support webm at this time.
more details can be found in the below link https://github.com/m90/seeThru
If you are using angular and trying to create a directive that has a custom modal in it, the modal backdrop will show but the modal itself will not unless you set replace: true on your directive.
Typescript Directive:
export class myModalDirective implements ng.IDirective {
static Register = () => {
angular.module('app').directive('myModal', () => { return new myModalDirective () });
}
templateUrl = 'mymodal.html'
restrict = 'E';
replace = true;
scope = {
show: '='
}
link = (scope: any, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any) => {
var vm = this;
scope.$watch(function () { return scope.show; }, function (vis) {
if (vis) {
$(element).modal('show');
} else {
$(element).modal('hide');
}
});
}
constructor () {
}
}
Modal HTML
<div class="modal fade" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal Title</h4>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.
Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.
As a guess, I would try using this:
Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate
Let said our backend looks like this:
public async Task<IActionResult> Post([FromBody] IList<UserRol> roles, string notes) {
}
We have a HttpService like this:
post<T>(url: string, body: any, headers?: HttpHeaders, params?: HttpParams): Observable<T> {
return this.http.post<T>(url, body, { headers: headers, params});
}
Following is how we can pass the body and the notes as parameter: // how to call it
const headers: HttpHeaders = new HttpHeaders({
'Authorization': `Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXX`
});
const bodyData = this.getBodyData(); // get whatever we want to send as body
let params: HttpParams = new HttpParams();
params = params.set('notes', 'Some notes to send');
this.httpService.post<any>(url, bodyData, headers, params);
It worked for me (using angular 7^), I hope is useful for somebody.
To get latitude and longitude too, you can use this simple code:
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />
</body>
</html>
By default is private
. Unless they're nested, classes are internal
.
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
The following kills all the processes created by this user:
kill -9 -1
if you want to connect to container and install something
using apt-get
first as above answer from our brother "Tomáš Záluský"
docker exec -u root -t -i container_id /bin/bash
then try to
RUN apt-get update or apt-get 'anything you want'
it worked with me hope it's useful for all
1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>
loadXMLDoc JS function should return false, otherwise it will result in postback.
Here is my working env path variables after much troubleshooting
CLASSPATH
.;C:\Program Files (x86)\Java\jre7\lib\ext\QTJava.zip;C:\Program Files (x86)\Java\jdk1.6.0_27\bin
PATH <---sometimes this PATH fills up with too many paths and you can't add a path(which was my case!)
bunchofpaths;C:\Program Files (x86)\Java\jdk1.6.0_27\bin
Additionally, when you try to use the cmd to execute the file...make sure your in the local directory as the file your trying to execute (which you did.)
Just a little checklist for people that have this problem still.
in visualstudio 2008 you could use this code :
var _assembly = System.Reflection.Assembly
.GetExecutingAssembly().GetName().CodeBase;
var _path = System.IO.Path.GetDirectoryName(_assembly) ;
Use ModHeader Chrome extension.
Or you can try more complex value like Accept-Language: en-US,en;q=0.9,ru;q=0.8,th;q=0.7
That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.
To change your Platform Toolset:
It marks the string as a verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.
So "C:\\Users\\Rich"
is the same as @"C:\Users\Rich"
There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, @""""
evaluates to "
.
You can use below code if object has attibutes under it.
String getCommonSeperatedString(List<ActionObject> actionObjects) {
StringBuffer sb = new StringBuffer();
for (ActionObject actionObject : actionObjects){
sb.append(actionObject.Id).append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
return sb.toString();
}
You can use:
\\
That's ok, for example:
if (invName.substring(j,k).equals("\\")) {
copyf=invName.substring(0,j);
}
Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference
under the info tar
command.
x
means --extract
. v
means --verbose
. f
means --file
. z
means --gzip
. You can combine one-letter arguments together, and f
takes an argument, the filename. There is something you have to watch out for:
Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).
This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:tar cfz archive.tar.gz file tar -cfz archive.tar.gz file
are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.
Alternatively, if you have Node.js installed, you can use the following command:
npx degit GIT_REPO
npx
comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit
globally using npm i -g degit
).
Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
Added a for
loop and changed .serialize()
to .serializeArray()
for object reference in a .each()
to append to the FormData
.
I keep all my own certificates and keys in one directory, and this works for tools like PuTTY, but I got this "too open" error message from the scp command. I discovered that Windows already maintains a C:\users\ACCOUNTNAME\.ssh folder having the proper access rights for storing SSH keys. So long as you keep the contents backed up (Windows sometimes deletes it during updates), or create your own folder for ssh keys in your user folder, this will work fine, as only you and the administrators have access to that parent folder.
Be very careful about changing access rights on Windows folders. I did this, and once a day Windows is scanning, reading, and writing all the files on my C: drive, a process that slows the computer for many minutes.
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
public static function countDays($date1,$date2)
{
$date1 = strtotime($date1); // or your date as well
$date2 = strtotime($date2);
$datediff = $date1 - $date2;
return floor($datediff/(60*60*24));
}
public static function dateRange($date1,$date2)
{
$count = static::countDays($date1,$date2) + 1;
$dates = array();
for($i=0;$i<$count;$i++)
{
$dates[] = date("Y-m-d",strtotime($date2.'+'.$i.' days'));
}
return $dates;
}
You can mark it as @JsonIgnore
.
With 1.9, you can add @JsonIgnore
for getter, @JsonProperty
for setter, to make it deserialize but not serialize.
Here is the batch file which should work for you:
@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder
:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"
if not exist "%Package%" (
echo.
echo The entered folder/MSI file does not exist ^(typing mistake^).
echo.
setlocal EnableDelayedExpansion
set /P "Retry=Try again [Y/N]: "
if /I "!Retry!"=="Y" endlocal & goto select
endlocal
goto :EOF
)
echo.
echo Selected installation: %MSI%
echo.
echo.
:verify
echo Is This Correct?
echo.
echo.
echo 0: ABORT INSTALL
echo 1: YES
echo 2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select
:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"
The characters listed on last page output on entering in a command prompt window either help cmd
or cmd /?
have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^
as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.
And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec
with the command line option /i
to install the application inside MSI package.
Run msiexec.exe /?
to get in a GUI window the available options or look at Msiexec (command-line options).
I have added already /quiet
additionally to required option /i
for a silent installation.
In batch code above command start
is used with option /wait
to start Windows application msiexec.exe
and hold execution of batch file until installation finished (or aborted).
CASE course_enrollment_settings.base_price
is wrong here, it should be just CASE
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
WHEN course_enrollment_settings.base_price<101 THEN 2
WHEN course_enrollment_settings.base_price>100 AND
course_enrollment_settings.base_price<201 THEN 3
ELSE 6
END AS 'calc_base_price',
course_enrollment_settings.base_price
FROM
course_enrollment_settings
WHERE course_enrollment_settings.base_price = 0
Some explanations. Your original query will be executed as :
SELECT
CASE 0
WHEN 0=0 THEN 1 -- condition evaluates to 1, then 0 (from CASE 0)compares to 1 - false
WHEN 0<1 THEN 2 -- condition evaluates to 1,then 0 (from CASE 0)compares to 1 - false
WHEN 0>100 and 0<201 THEN 3 -- evaluates to 0 ,then 0 (from CASE 0)compares to 0 - true
ELSE 6, ...
it's why you always get 3
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);
When I face this problem I just edit the file and save it... works like charm
SELECT DATEPART(QUARTER, @date)
This returns the quarter of the @date
, assuming @date
is a DATETIME
.
Hope this helps someone in the future. My problem was that I was following the same tutorial as the OP to enable global CORS. However, I also set an Action specific CORS rule in my AccountController.cs file:
[EnableCors(origins: "", headers: "*", methods: "*")]
and was getting errors about the origin cannot be null or empty string. BUT the error was happening in the Global.asax.cs file of all places. Solution is to change it to:
[EnableCors(origins: "*", headers: "*", methods: "*")]
notice the * in the origins? Missing that was what was causing the error in the Global.asax.cs file.
Hope this helps someone.
Simplification from the above Andrew's answer leads to this key theme to generate the half border.
theme (panel.border = element_blank(),
axis.line = element_line(color='black'))
^[^<>]+$
The caret in the character class ([^
) means match anything but, so this means, beginning of string, then one or more of anything except <
and >
, then the end of the string.
Don't know if this is too late but you can use np.where to find the indices of non values as such:
indices = list(np.where(df['b'].isna()[0]))
Check out the Magick++ API to ImageMagick.
To complete the picture, since -Werror
might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:
-Werror=implicit-function-declaration
See Make one gcc warning an error?
Regarding general use of -Werror
: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.
Chaos is spot on, though for these sorts of questions you should check out the Jquery Documentation online - it really is quite comprehensive. The feature you are after is called 'jquery selectors'
Generally you do $('#ID').val()
- the .afterwards can do a number of things on the element that is returned from the selector. You can also select all of the elements on a certain class and do something to each of them. Check out the documentation for some good examples.
If you use auto-layout.
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2
While you do the following, technically speaking:
<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
//reference to the button that triggered the function:
$event.target
};
This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.
You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796
What you want to do is set the selectedIndex attribute of the select box.
country.options.selectedIndex = index_of_indonesia;
Changing the 'selected' attribute will generally not work in IE. If you really want the behavior you're describing, I suggest you write a custom javascript reset function to reset all the other values in the form to their default.
From your code, it looks like provider
is a variant or some other variable, and not an object.
Is Nothing
is for objects only, yet later you say it's a value that should either be NULL or NOT NULL, which would be handled by IsNull
.
Try using:
If Not IsNull(provider) Then
url = url & "&provider=" & provider
End if
Alternately, if that doesn't work, try:
If provider <> "" Then
url = url & "&provider=" & provider
End if
Works for any number from 0 to 999999999.
This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.
#include <iostream>
using namespace std;
int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
long input, nFake = 0;
const char ones[][20] = {"", "one", "two", "three",
"four", "five", "six", "seven",
"eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"};
const char tens[][20] = {"", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"};
void convert(int funcVar);
int main() {
cout << "Enter the number:";
cin >> input;
nFake = input;
buffer = 0;
while (nFake) {
part[buffer] = nFake % 1000;
nFake /= 1000;
buffer++;
}
if (buffer == 0) {
cout << "Zero.";
} else if (buffer == 1) {
convert(part[0]);
} else if (buffer == 2) {
convert(part[1]);
cout << " thousand,";
convert(part[0]);
} else {
convert(part[2]);
cout << " million,";
if (part[1]) {
convert(part[1]);
cout << " thousand,";
} else {
cout << "";
}
convert(part[0]);
}
system("pause");
return (0);
}
void convert(int funcVar) {
buffer = 0;
if (funcVar >= 100) {
a = funcVar / 100;
b = funcVar % 100;
if (b)
cout << " " << ones[a] << " hundred and";
else
cout << " " << ones[a] << " hundred ";
if (b < 20)
cout << " " << ones[b];
else {
c = b / 10;
cout << " " << tens[c];
d = b % 10;
cout << " " << ones[d];
}
} else {
b = funcVar;
if (b < 20)
cout << ones[b];
else {
c = b / 10;
cout << tens[c];
d = b % 10;
cout << " " << ones[d];
}
}
}
{
int main(void);
should be
int main(void)
{
Then I let you fix the next compilation errors of your program...
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
this
is a reference to the object typed as the current class, and super
is a reference to the object typed as its parent class.
In the constructor, this()
calls a constructor defined in the current class. super()
calls a constructor defined in the parent class. The constructor may be defined in any parent class, but it will refer to the one overridden closest to the current class. Calls to other constructors in this way may only be done as the first line in a constructor.
Calling methods works the same way. Calling this.method()
calls a method defined in the current class where super.method()
will call the same method as defined in the parent class.
These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.
jQuery.scrollTableBody (GitHub)
As long as you have a table with proper <thead>
, <tbody>
, and (optional) <tfoot>
, all you need to do is this:
$('table').scrollTableBody();
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
i spent two days trying to solve this issue after updating ADT. finally i was lucky to get this post here:
https://code.google.com/p/android/issues/detail?id=55304
which led me in the right direction. when you follow the solution - remember to replace the android support library of all your projects to the same version (remove it and re-install it to the projects). i hope this helps - good luck
by creating an absolute-positioned link inside relative-positioned div.. You need set the link width & height as button dimensions, and left&top coordinates for the left-top corner of button within the wrapping div.
<div style="position:relative">
<img src="" width="??" height="??" />
<a href="#" style="display:block; width:247px; height:66px; position:absolute; left: 48px; top: 275px;"></a>
</div>
You can use placement-new like this:
class Car
{
int _no;
public:
Car(int no) : _no(no)
{
}
};
int main()
{
void *raw_memory = operator new[](NUM_CARS * sizeof(Car));
Car *ptr = static_cast<Car *>(raw_memory);
for (int i = 0; i < NUM_CARS; ++i) {
new(&ptr[i]) Car(i);
}
// destruct in inverse order
for (int i = NUM_CARS - 1; i >= 0; --i) {
ptr[i].~Car();
}
operator delete[](raw_memory);
return 0;
}
Reference from More Effective C++ - Scott Meyers:
Item 4 - Avoid gratuitous default constructors
Negative numbers mean that you count from the right instead of the left. So, list[-1]
refers to the last element, list[-2]
is the second-last, and so on.
What I did, is having a TextView
and a CheckBox
inside a (Relative)Layout
. The TextView
displays the text that I want the user to see, and the CheckBox
doesn't have any text. That way, I can set the position / padding of the CheckBox
wherever I want.
You can use the recode
function from dplyr
.
df <- iris %>%
mutate(Species = recode(Species, setosa = "SETOSA",
versicolor = "VERSICOLOR",
virginica = "VIRGINICA"
)
)
Often you want to pass a viewmodel also, and not the only one file. In the code below you'll find some other useful features:
It could be done via the following code:
[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
// if file's content length is zero or no files submitted
if (Request.Files.Count != 1 || Request.Files[0].ContentLength == 0)
{
ModelState.AddModelError("uploadError", "File's length is zero, or no files found");
return View(viewModel);
}
// check the file size (max 4 Mb)
if (Request.Files[0].ContentLength > 1024 * 1024 * 4)
{
ModelState.AddModelError("uploadError", "File size can't exceed 4 MB");
return View(viewModel);
}
// check the file size (min 100 bytes)
if (Request.Files[0].ContentLength < 100)
{
ModelState.AddModelError("uploadError", "File size is too small");
return View(viewModel);
}
// check file extension
string extension = Path.GetExtension(Request.Files[0].FileName).ToLower();
if (extension != ".pdf" && extension != ".doc" && extension != ".docx" && extension != ".rtf" && extension != ".txt")
{
ModelState.AddModelError("uploadError", "Supported file extensions: pdf, doc, docx, rtf, txt");
return View(viewModel);
}
// extract only the filename
var fileName = Path.GetFileName(Request.Files[0].FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
try
{
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
Request.Files[0].SaveAs(path);
}
catch (Exception)
{
ModelState.AddModelError("uploadError", "Can't save file to disk");
}
if(ModelState.IsValid)
{
// put your logic here
return View("Success");
}
return View(viewModel);
}
Make sure you have
@Html.ValidationMessage("uploadError")
in your view for validation errors.
Also keep in mind that default maximum request length is 4MB (maxRequestLength = 4096), to upload larger files you have to change this parameter in web.config:
<system.web>
<httpRuntime maxRequestLength="40960" executionTimeout="1100" />
(40960 = 40 MB here).
Execution timeout is the whole number of seconds. You may want to change it to allow huge files uploads.
Use the Apache XMLSerializer
here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1
you can check this as well
The issue resolved after I updated the 'appID' and 'secret' and then pushed the change back to heroku (i.e. - 'git push heroku master')
The key is not to forget to push the changes back to heroku master. Very easy to overlook if you're use to testing on localhost.
Hope this helps.
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...
First, add a pom.xml and make it a maven project and then build it. It will create a War file for you in the target folder after that you can deploy it wherever you want.
pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 it.megadix create-react-app-servlet 0.0.1-SNAPSHOT war
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<npm.output.directory>build</npm.output.directory>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Standard plugin to generate WAR -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<webResources>
<resource>
<directory>${npm.output.directory}</directory>
</resource>
</webResources>
<webXml>${basedir}/web.xml</webXml>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<!-- Required: The following will ensure `npm install` is called
before anything else during the 'Default Lifecycle' -->
<execution>
<id>npm install (initialize)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>initialize</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<!-- Required: The following will ensure `npm install` is called
before anything else during the 'Clean Lifecycle' -->
<execution>
<id>npm install (clean)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>pre-clean</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<!-- Required: This following calls `npm run build` where 'build' is
the script name I used in my project, change this if yours is
different -->
<execution>
<id>npm run build (compile)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>compile</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
</executions>
<configuration>
<environmentVariables>
<CI>true</CI>
<!-- The following parameters create an NPM sandbox for CI -->
<NPM_CONFIG_PREFIX>${basedir}/npm</NPM_CONFIG_PREFIX>
<NPM_CONFIG_CACHE>${NPM_CONFIG_PREFIX}/cache</NPM_CONFIG_CACHE>
<NPM_CONFIG_TMP>${project.build.directory}/npmtmp</NPM_CONFIG_TMP>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<environmentVariables>
<PUBLIC_URL>http://localhost:8080/${project.artifactId}</PUBLIC_URL>
<REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>prod</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<environmentVariables>
<PUBLIC_URL>http://my-awesome-production-host/${project.artifactId}</PUBLIC_URL>
<REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
Note:- If you find a blank page after running your project then clear your cache or restart your IDE.
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
I created a DefaultableDictionary to do exactly what you are asking for!
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace DefaultableDictionary {
public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
private readonly IDictionary<TKey, TValue> dictionary;
private readonly TValue defaultValue;
public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
this.dictionary = dictionary;
this.defaultValue = defaultValue;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
return dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item) {
dictionary.Add(item);
}
public void Clear() {
dictionary.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item) {
return dictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
dictionary.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item) {
return dictionary.Remove(item);
}
public int Count {
get { return dictionary.Count; }
}
public bool IsReadOnly {
get { return dictionary.IsReadOnly; }
}
public bool ContainsKey(TKey key) {
return dictionary.ContainsKey(key);
}
public void Add(TKey key, TValue value) {
dictionary.Add(key, value);
}
public bool Remove(TKey key) {
return dictionary.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value) {
if (!dictionary.TryGetValue(key, out value)) {
value = defaultValue;
}
return true;
}
public TValue this[TKey key] {
get
{
try
{
return dictionary[key];
} catch (KeyNotFoundException) {
return defaultValue;
}
}
set { dictionary[key] = value; }
}
public ICollection<TKey> Keys {
get { return dictionary.Keys; }
}
public ICollection<TValue> Values {
get
{
var values = new List<TValue>(dictionary.Values) {
defaultValue
};
return values;
}
}
}
public static class DefaultableDictionaryExtensions {
public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
}
}
}
This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.
The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.
Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);
Blog post on the usage as well.
Statically typed languages: each variable and expression is already known at compile time.
(int a;
a can take only integer type values at runtime)
Examples: C, C++, Java
Dynamically typed languages: variables can receive different values at runtime and their type is defined at run time.
(var a;
a can take any kind of values at runtime)
Examples: Ruby, Python.
The Python Book © 2015 Imagine Publishing Ltd, simply distunguishes the difference by the following hint mentioned in page 10 as:
An interpreted language such as Python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a compiled language such as C, where the source code is only converted to machine code once – the resulting machine code is then executed each time the program runs.
Enums cannot be derrived from other enums, but only from int, uint, short, ushort, long, ulong, byte and sbyte.
Like Pascal said, you can use other enum's values or constants to initialize an enum value, but that's about it.
This is just torazaburo's answer, updated to use a MouseEvent object.
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
el.dispatchEvent(ev);
}
Spend some time to make it working for me.
Requirement:
single or comma separated list of e-mails with domains ending [email protected] or [email protected]
Controller:
$scope.email = {
EMAIL_FORMAT: /^\w+([\.-]?\w+)*@(list.)?gmail.com+((\s*)+,(\s*)+\w+([\.-]?\w+)*@(list.)?gmail.com)*$/,
EMAIL_FORMAT_HELP: "format as '[email protected]' or comma separated '[email protected], [email protected]'"
};
HTML:
<ng-form name="emailModal">
<div class="form-group row mb-3">
<label for="to" class="col-sm-2 text-right col-form-label">
<span class="form-required">*</span>
To
</label>
<div class="col-sm-9">
<input class="form-control" id="to"
name="To"
ng-required="true"
ng-pattern="email.EMAIL_FORMAT"
placeholder="{{email.EMAIL_FORMAT_HELP}}"
ng-model="mail.to"/>
<small class="text-muted" ng-show="emailModal.To.$error.pattern">wrong</small>
</div>
</div>
</ng-form>
I found good online regex testing tool. Covered my regex with tests:
(d means decimal, b means binary)
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
You can't load a file from your local filesystem, like this, you need to put it on a a web server and load it from there. On the same site as you have the JavaScript loaded from.
EDIT: Looking at this thread, you can start chrome using option --allow-file-access-from-files
, which would allow access to local files.
For implementing the rounded border button with a border color use this
OutlineButton(
child: new Text("Button Text"),borderSide: BorderSide(color: Colors.blue),
onPressed: null,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(20.0))
),
You can use dangerouslySetInnerHTML, e.g.
render: function() {
return (
<div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
);
}
Is it acceptable & safe to run
pip install
undersudo
?
It's not safe and it's being frowned upon – see What are the risks of running 'sudo pip'?
To install Python package in your home directory you don't need root privileges. See description of --user
option to pip.
Do what the compiler tells you to do, i.e. recompile with -fPIC
. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.
In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.
Finally, you can read about it on Wikipedia too.
Assuming you are using VSTS run vsts-npm-auth -config .npmrc
to generate new .npmrc file with the auth token
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
Add this class to your project
import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;
import com.google.android.gms.ads.AdRequest;
import java.io.UnsupportedEncodingException;
public class AdsHelper {
public static AdRequest createRequest(Context context) {
AdRequest.Builder adRequest = new AdRequest.Builder();
adRequest.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
if (BuildConfig.DEBUG) {
String deviceId = MD5(getDeviceId(context));
if (!TextUtils.isEmpty(deviceId)) {
adRequest.addTestDevice(deviceId.toUpperCase());
}
}
return adRequest.build();
}
private static String MD5(String md5) {
if (TextUtils.isEmpty(md5)) return null;
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte anArray : array) {
sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException ignored) {
} catch(UnsupportedEncodingException ignored){
}
return null;
}
private static String getDeviceId(Context context) {
try {
return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
} catch (Exception e) {
return "";
}
}
}
Usage:
AdRequest adRequest = AdsHelper.createRequest(this);
Here you can find code with output like this: https://stackoverflow.com/a/56622847/6671330
V .
|-> V folder1
| |-> V folder2
| | |-> V folder3
| | | |-> file3.txt
| | |-> file2.txt
| |-> V folderX
| |-> file1.txt
|-> 02-hw1_wdwwfm.py
|-> 06-t1-home1.py
|-> 06-t1-home2.py
|-> hw1.py
If someone used this:
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
PreferenceManager is now depricated, refactor to this:
val sharedPreferences = context.getSharedPreferences(context.packageName + "_preferences", Context.MODE_PRIVATE)
There's an input stream decorator, java.security.DigestInputStream
, so that you can compute the digest while using the input stream as you normally would, instead of having to make an extra pass over the data.
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get("file.txt"));
DigestInputStream dis = new DigestInputStream(is, md))
{
/* Read decorated stream (dis) to EOF as normal... */
}
byte[] digest = md.digest();
Live example of Curl command to send OPTIONS requests: https://reqbin.com/req/c-d8nxa0fl
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { `
if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
you can use prepacked function
function unzip_file($file, $destination){
// create object
$zip = new ZipArchive() ;
// open archive
if ($zip->open($file) !== TRUE) {
return false;
}
// extract contents to destination directory
$zip->extractTo($destination);
// close archive
$zip->close();
return true;
}
How to use it.
if(unzip_file($file["name"],'uploads/')){
echo 'zip archive extracted successfully';
}else{
echo 'zip archive extraction failed';
}
You can use a zip
function with a list comprehension :
with open('ex.txt') as f:
print zip(*[line.split() for line in f])[1]
result :
('10', '20', '30', '40', '23', '13')
It's not necessary, it's optional, just as public
on interface methods.
See the JLS on this:
http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html
9.1.1.1 abstract Interfaces Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.
And
9.4 Abstract Method Declarations
[...]
For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.
Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.
To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.
I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!
By default Spring Boot gives json with error details.
curl -v localhost:8080/greet | json_pp
[...]
< HTTP/1.1 400 Bad Request
[...]
{
"timestamp" : 1413313361387,
"exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
"status" : 400,
"error" : "Bad Request",
"path" : "/greet",
"message" : "Required String parameter 'name' is not present"
}
It also works for all kind of request mapping errors. Check this article http://www.jayway.com/2014/10/19/spring-boot-error-responses/
If you want to create log it to NoSQL. You can create @ControllerAdvice where you would log it and then re-throw the exception. There is example in documentation https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
I just visited this site and it really bugged me,
apparently there are a couple ways to disable the mouse click:
1)
<script language="javascript">
document.onmousedown=disableclick;
status="Right Click Disabled";
function disableclick(event)
{
if(event.button==2)
{
alert(status);
return false;
}
}
</script>
and
<body oncontextmenu="return false">
...
in this case what you will have to do in the dev tools is :
document.removeEventListener("onmousedown",disableclick);
document.oncontextmenu = function(){}
2)
using flash as a content wrapper - no solution here except taking a screenshot
3)
some sites want to prevent downloading images via right click -> save image as
so what they do is put this:
<div style="background-image: url(YourImage.jpg);">
<img src="transparent.gif"/>
</div>
which is a transparent image spreding on the full width and height of the screen all you need to do is go to the elements inspector and find the div and delete it.
In my case #1 did the trick
You should write brackets only before path: "c:\program files\
i think this is a best mode to cast to int
public int ByteToint(Byte B){
String comb;
int out=0;
comb=B+"";
salida= Integer.parseInt(comb);
out=out+128;
return out;
}
first comvert byte to String
comb=B+"";
next step is comvert to a int
out= Integer.parseInt(comb);
but byte is in rage of -128 to 127 for this reasone, i think is better use rage 0 to 255 and you only need to do this:
out=out+256;
Simply use is_empty() or make function like:-
def is_empty(any_structure):
if any_structure:
print('Structure is not empty.')
return True
else:
print('Structure is empty.')
return False
It can be used for any data_structure like a list,tuples, dictionary and many more. By these, you can call it many times using just is_empty(any_structure)
.
SET @sql =
CONCAT( 'INSERT INTO <table_name> (',
(
SELECT GROUP_CONCAT( CONCAT('`',COLUMN_NAME,'`') )
FROM information_schema.columns
WHERE table_schema = <database_name>
AND table_name = <table_name>
AND column_name NOT IN ('id')
), ') SELECT ',
(
SELECT GROUP_CONCAT(CONCAT('`',COLUMN_NAME,'`'))
FROM information_schema.columns
WHERE table_schema = <database_name>
AND table_name = <table_source_name>
AND column_name NOT IN ('id')
),' from <table_source_name> WHERE <testcolumn> = <testvalue>' );
PREPARE stmt1 FROM @sql;
execute stmt1;
Of course replace <> values with real values, and watch your quotes.
Here you go. Just specify the chars you want to allow on the first line.
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead. Values produced byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.
use
$("#mySelectBox option:selected");
to test if its a particular option myoption
:
if($("#mySelectBox option:selected").text() == myoption){
//...
}
RedirectToAction
with parameter:
return RedirectToAction("Action","controller", new {@id=id});
If the previously mentioned higher z-indexing in parent nodes wont suit your needs, you can create alternative solution and target it to problematic browsers either by IE conditional comments or using the (more idealistic) feature detection provided by Modernizr.
Quick (and obviously working) test for Modernizr:
Modernizr.addTest('compliantzindex', function(){
var test = document.createElement('div'),
fake = false,
root = document.body || (function () {
fake = true;
return document.documentElement.appendChild(document.createElement('body'));
}());
root.appendChild(test);
test.style.position = 'relative';
var ret = (test.style.zIndex !== 0);
root.removeChild(test);
if (fake) {
document.documentElement.removeChild(root);
}
return ret;
});
This might be more useful when you want your index shuffled.
def shuffle(df):
index = list(df.index)
random.shuffle(index)
df = df.ix[index]
df.reset_index()
return df
It selects new df using new index, then reset them.
You can use wc function in library qdap:
> str1 <- "How many words are in this sentence"
> wc(str1)
[1] 7
You can use:
f.Controls[name];
Where f
is your form variable. That gives you the control with name name
.
SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
MAX([Value])
FOR [Period] IN ([2000], [2001], [2002])
) as pvt
Another way,
SELECT ACCOUNT,
MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account
An additional possible cause.
My HTML page had these starting tags:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
This was on a page that using the slick jquery slideshow.
I removed the tags and replaced with:
<html>
And everything is working again.
my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:
my solution (not the better way, but it works):
javascript:
function replaceAll( text, busca, reemplaza ){
while (text.toString().indexOf(busca) != -1)
text = text.toString().replace(busca,reemplaza);return text;
}
function cleanCode(cod){
code = replaceAll(cod , "|", "{1}" ); // error | palos de explode en java
code = replaceAll(code, "+", "{0}" ); // error con los signos mas
return code;
}
function to save:
function save(pid,code){
code = cleanCode(code); // fix sign + and |
code = escape(code); // fix accents
var url = 'editor.php';
var variables = 'op=save';
var myData = variables +'&code='+ code +'&pid='+ pid +'&newdate=' +(new Date()).getTime();
var result = null;
$.ajax({
datatype : "html",
data: myData,
url: url,
success : function(result) {
alert(result); // result ok
},
});
} // end function
function in php:
<?php
function save($pid,$code){
$code= preg_replace("[\{1\}]","|",$code);
$code= preg_replace("[\{0\}]","+",$code);
mysql_query("update table set code= '" . mysql_real_escape_string($code) . "' where pid='$pid'");
}
?>
you must write it in SQL not it C/PHP style
IF( action = 2 AND state = 0, 1, 0 ) AS state
for use in query
IF ( action = 2 AND state = 0 ) THEN SET state = 1
for use in stored procedures or functions
This command works like a charm for me:
for /r "$(SolutionDir)libraries" %%f in (*.dll, *.exe) do @xcopy "%%f" "$(TargetDir)"
It recursively copies every dll
and exe
file from MySolutionPath\libraries
into the bin\debug
or bin\release
.
You can find more info in here
What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.
In your component
[
{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
].map((anObjectMapped, index) => {
return (
<p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
{anObjectMapped.name} - {anObjectMapped.email}
</p>
);
})
And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.
Take a look at my answer at mapping an array to jsx
This is easier:
location.href = 'http://address.com';
Or
location.replace('http://address.com'); // <-- No history saved.
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
The value of __FILE__
is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.chdir
anywhere else in your application, this path will expand incorrectly.
puts __FILE__
Dir.chdir '../../'
puts __FILE__
One workaround to this problem is to store the expanded value of __FILE__
outside of any application code. As long as your require
statements are at the top of your definitions (or at least before any calls to Dir.chdir
), this value will continue to be useful after changing directories.
$MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))
# open class and do some stuff that changes directory
puts $MY_FILE_PATH
This is a late answer but still, guess setting the color to transparent is the best option.
#mybox:hover{
background-color:red;
}
This answer is similar to @PaulMcG's answer but doesn't require sorting the input.
For those into functional programming, groupBy
can be written in one line (not including imports!), and unlike itertools.groupby
it doesn't require the input to be sorted:
from functools import reduce # import needed for python3; builtin in python2
from collections import defaultdict
def groupBy(key, seq):
return reduce(lambda grp, val: grp[key(val)].append(val) or grp, seq, defaultdict(list))
(The reason for ... or grp
in the lambda
is that for this reduce()
to work, the lambda
needs to return its first argument; because list.append()
always returns None
the or
will always return grp
. I.e. it's a hack to get around python's restriction that a lambda can only evaluate a single expression.)
This returns a dict whose keys are found by evaluating the given function and whose values are a list of the original items in the original order. For the OP's example, calling this as groupBy(lambda pair: pair[1], input)
will return this dict:
{'KAT': [('11013331', 'KAT'), ('9843236', 'KAT')],
'NOT': [('9085267', 'NOT'), ('11788544', 'NOT')],
'ETH': [('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH')]}
And as per @PaulMcG's answer the OP's requested format can be found by wrapping that in a list comprehension. So this will do it:
result = {key: [pair[0] for pair in values],
for key, values in groupBy(lambda pair: pair[1], input).items()}
execute
show VARIABLES like "%char%”;
find character-set-server if is not utf8mb4.
set it in your my.cnf, like
vim /etc/my.cnf
add one line
character_set_server = utf8mb4
at last restart mysql
Had the same problem. For me it worked to call
viewPage.setAdapter( adapter );
again which caused reinstantiating the pages again.
Your method signature is:
- (void) myTest:(NSString *)
withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).
If you call the function in this manner:
[self performSelector:@selector(myTest:) withObject:myString];
It will work.
But, as the other posters have suggested, you may want to rename the method:
- (void)myTestWithAString:(NSString*)aString;
And call:
[self performSelector:@selector(myTestWithAString:) withObject:myString];
Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true);
Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true
) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring
). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.
You are correctly calling listen()
but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write()
or response.end()
. First, you need to include fs=require('fs')
to get access to the filesystem. Then, you need to actually serve the file.
XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string
will be undefined
(or perhaps null
), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.
Here is a simple implementation that incorporates all of the above:
server.js:
var http = require('http'),
fs = require('fs'),
url = require('url'),
choices = ["hello world", "goodbye world"];
http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
if(path=="/getstring"){
console.log("request recieved");
var string = choices[Math.floor(Math.random()*choices.length)];
console.log("string '" + string + "' chosen");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end(string);
console.log("string sent");
}else{
fs.readFile('./index.html', function(err, file) {
if(err) {
// write an error response or nothing here
return;
}
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(file, "utf-8");
});
}
}).listen(8001);
console.log("server initialized");
frontend (part of index.html):
function newGame()
{
guessCnt=0;
guess="";
server();
displayHash();
displayGuessStr();
displayGuessCnt();
}
function server()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8001/getstring", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
}
}
xmlhttp.send();
}
You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.
UPDATE: I have changed response.sendHeader()
to the new response.writeHead()
in the code above !!!
Make sure that the Python dev files come with your OS.
You should not hard code the library and include paths. Instead, use pkg-config, which will output the correct options for your specific system:
$ pkg-config --cflags --libs python2
-I/usr/include/python2.7 -lpython2.7
You may add it to your gcc line:
gcc -Wall utilsmodule.c -o Utilc $(pkg-config --cflags --libs python2)
As stated here https://bugs.python.org/issue28150 in previous versions of python Apple supplied the OpenSSL packages but does not anymore.
Running the command pip install certifi
and then pip install Scrapy
fixed it for me
Insted of
drawer.setDrawerListener(toggle);
You can use
drawer.addDrawerListener(toggle);
In Java, according to the JSSE Reference Guide, there is no default for the keystore
, the default for the truststore
is "jssecacerts, if it exists. Otherwise, cacerts".
A few applications use ~/.keystore
as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).
I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.
As someone mentioned in one of the many SO threads concerning this problem: Sometimes the process that has locked the table shows up as sleeping in the processlist! I was tearing my hair out until I killed all the sleeping threads that were open in the database in question (none were active at the time). That finally unlocked the table and let the update query run.
The commenter said something akin to "Sometimes a MySQL thread locks a table, then sleeps while it waits for something non-MySQL-related to happen."
After re-re-reviewing the show engine innodb status
log (once I'd tracked down the client responsible for the lock), I noticed the stuck thread in question was listed at the very bottom of the transaction list, beneath the active queries that were about to error out because of the frozen lock:
------------------
---TRANSACTION 2744943820, ACTIVE 1154 sec(!!)
2 lock struct(s), heap size 376, 2 row lock(s), undo log entries 1
MySQL thread id 276558, OS thread handle 0x7f93762e7710, query id 59264109 [ip] [database] cleaning up
Trx read view will not see trx with id >= 2744943821, sees < 2744943821
(unsure if the "Trx read view" message is related to the frozen lock, but unlike the other active transactions, this one does not show up with the query that was issued and instead claims the transaction is "cleaning up," yet has multiple row locks)
The moral of the story is that a transaction can be active even though the thread is sleeping.
We've released EAP to dotCover and will be releasing the beta version soon.
Maybe my response quite late, but it covers API below and above 21 level.
To add headers we should intercept every request and create new one with required headers.
So we need to override shouldInterceptRequest method called in both cases: 1. for API until level 21; 2. for API level 21+
webView.setWebViewClient(new WebViewClient() {
// Handle API until level 21
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return getNewResponse(url);
}
// Handle API 21+
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
return getNewResponse(url);
}
private WebResourceResponse getNewResponse(String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url.trim())
.addHeader("Authorization", "YOU_AUTH_KEY") // Example header
.addHeader("api-key", "YOUR_API_KEY") // Example header
.build();
Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
null,
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
} catch (Exception e) {
return null;
}
}
});
If response type should be processed you could change
return new WebResourceResponse(
null, // <- Change here
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
to
return new WebResourceResponse(
getMimeType(url), // <- Change here
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
and add method
private String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
switch (extension) {
case "js":
return "text/javascript";
case "woff":
return "application/font-woff";
case "woff2":
return "application/font-woff2";
case "ttf":
return "application/x-font-ttf";
case "eot":
return "application/vnd.ms-fontobject";
case "svg":
return "image/svg+xml";
}
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.
I find that the best way to do this is to use SUMPRODUCT
instead:
=SUMPRODUCT((A1:A10<>"")*1)
It's also pretty great if you want to throw in more criteria:
=SUMPRODUCT((A1:A10<>"")*(A1:A10>$B$1)*(A1:A10<=$B$2))
Expanding on Felix Turner s response, here is how I would use this approach with the fetch
API.
async function createFile(){
let response = await fetch('http://127.0.0.1:8080/test.jpg');
let data = await response.blob();
let metadata = {
type: 'image/jpeg'
};
let file = new File([data], "test.jpg", metadata);
// ... do something with the file or return it
}
createFile();
You should use profiles.
<profiles>
<profile>
<id>otherOutputDir</id>
<build>
<directory>yourDirectory</directory>
</build>
</profile>
</profiles>
And start maven with your profile
mvn compile -PotherOutputDir
If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :
<properties>
<buildDirectory>${project.basedir}/target</buildDirectory>
</properties>
<build>
<directory>${buildDirectory}</directory>
</build>
And compile like this :
mvn compile -DbuildDirectory=test
That's because you can't change the target directory by using -Dproject.build.directory
Here's the calling order:
app.config()
app.run()
app.controller()
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
From Angular's module docs:
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
One situation where run blocks are used is during authentications.
In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8
ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
and add Allow from all
after Allow from ::1 127.0.0.0/8 {line}
Restart xampp, and you are done.
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
This is a realy bad answer. For two reasons.
1. What happens with times like 23.59.59.700 etc. There are times larger than 23:59:59 and the next day.
2. The behaviour depends on the datatype. The query behaves differently for datetime/date/datetime2 types.
Testing with 23:59:59.999 makes it even worse because depending on the datetype you get different roundings.
select convert (varchar(40),convert(date , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime2 , '2014-03-19 23:59:59.999'))
-- For date the value is 'chopped'. -- For datetime the value is rounded up to the next date. (Nearest value). -- For datetime2 the value is precise.
You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.
Step 1, generate public and private key on build server as user jenkins
build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa):
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...]
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw------- 1 jenkins jenkins 1679 Feb 28 11:55 id_rsa
-rw-r--r-- 1 jenkins jenkins 411 Feb 28 11:55 id_rsa.pub
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]
Step 2, paste the pub file contents onto the target server.
target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)
Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644
Step 3, configure Jenkins
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"/Beans.xml"}) public class DemoTest{}
Are you running on Linux? Perhaps the management agent is binding to localhost:
http://java.sun.com/j2se/1.5.0/docs/guide/management/faq.html#linux1
<textarea name="hide" style="display:none;"></textarea>
This sets the css display
property to none
, which prevents the browser from rendering the textarea.
This might help - Just Download and install the Android SDK version(same as your mobile's android version), then run.
This worked for me on Vista. It's based on work-around at MS: http://connect.microsoft.com/VisualStudio/feedback/details/520110/invalid-license-data-reinstall-is-required
Download subinacl command line tool
http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=e8ba3e56-d8fe-4a91-93cf-ed6985e3927b&displaylang=en
Run these commands:
subinacl /subkeyreg HKEY_CLASSES_ROOT\Licenses /setowner=everyone
subinacl /subkeyreg HKEY_CLASSES_ROOT\Licenses /grant=everyone=f
Start VS 2010 Express again and this time it asks for a license key.
(On Windows 7 Home I had to run the above commands twice before they worked correctly)
foreach (DictionaryEntry entry in Hashtable)
{
datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}
Apologize for keep answering 9 years questions.
I have follow @Michael's answer and it works.
I do it as UserControl where I can drag and drop like a Controls elements. I use MaterialDesign Theme from Nuget to get the Chevron icon and button ripple effect.
The running NumericUpDown from Micheal with modification will be as below:-
The code for user control:-
TemplateNumericUpDown.xaml
<UserControl x:Class="UserControlTemplate.TemplateNumericUpDown"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:UserControlTemplate"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d" MinHeight="48">
<Grid Background="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="60"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtNum" x:FieldModifier="private" Text="{Binding Path=NumValue}" TextChanged="TxtNum_TextChanged" FontSize="36" BorderThickness="0" VerticalAlignment="Center" Padding="5,0"/>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="30*"/>
<RowDefinition Height="30*"/>
</Grid.RowDefinitions>
<Grid Background="#FF673AB7">
<Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto" Width="Auto">
<materialDesign:PackIcon Kind="ChevronUp" Foreground="White" Height="32.941" Width="32"/>
</Viewbox>
<Button x:Name="cmdUp" x:FieldModifier="private" Click="CmdUp_Click" Height="Auto" BorderBrush="{x:Null}" Background="{x:Null}"/>
</Grid>
<Grid Grid.Row="1" Background="#FF673AB7">
<Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto" Width="Auto">
<materialDesign:PackIcon Kind="ChevronDown" Foreground="White" Height="32.942" Width="32"/>
</Viewbox>
<Button x:Name="cmdDown" x:FieldModifier="private" Click="CmdDown_Click" Height="Auto" BorderBrush="{x:Null}" Background="{x:Null}"/>
</Grid>
</Grid>
</Grid>
</UserControl>
TemplateNumericUpDown.cs
using System.Windows;
using System.Windows.Controls;
namespace UserControlTemplate
{
/// <summary>
/// Interaction logic for TemplateNumericUpDown.xaml
/// </summary>
public partial class TemplateNumericUpDown : UserControl
{
private int _numValue = 0;
public TemplateNumericUpDown()
{
InitializeComponent();
txtNum.Text = _numValue.ToString();
}
public int NumValue
{
get { return _numValue; }
set
{
if (value >= 0)
{
_numValue = value;
txtNum.Text = value.ToString();
}
}
}
private void CmdUp_Click(object sender, RoutedEventArgs e)
{
NumValue++;
}
private void CmdDown_Click(object sender, RoutedEventArgs e)
{
NumValue--;
}
private void TxtNum_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtNum == null)
{
return;
}
if (!int.TryParse(txtNum.Text, out _numValue))
txtNum.Text = _numValue.ToString();
}
}
}
On MyPageDesign.xaml, drag and drop created usercontrol will having <UserControlTemplate:TemplateNumericUpDown HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100"/>
To get the value from the template, I use
string Value1 = JournalNumStart.NumValue;
string Value2 = JournalNumEnd.NumValue;
I'm not in good skill yet to binding the Height of the control based from FontSize element, so I set the from my page fontsize manually in usercontrol.
** Note:- I have change the "Archieve" name to Archive on my program =)
This is speed-optimized solution for converting int (signed 16-bit integer) into string.
This implementation avoids using division since 8-bit AVR used for Arduino has no hardware DIV instruction, the compiler translate division into time-consuming repetitive subtractions. Thus the fastest solution is using conditional branches to build the string.
A fixed 7 bytes buffer prepared from beginning in RAM to avoid dynamic allocation. Since it's only 7 bytes, the cost of fixed RAM usage is considered minimum. To assist compiler, we add register modifier into variable declaration to speed-up execution.
char _int2str[7];
char* int2str( register int i ) {
register unsigned char L = 1;
register char c;
register boolean m = false;
register char b; // lower-byte of i
// negative
if ( i < 0 ) {
_int2str[ 0 ] = '-';
i = -i;
}
else L = 0;
// ten-thousands
if( i > 9999 ) {
c = i < 20000 ? 1
: i < 30000 ? 2
: 3;
_int2str[ L++ ] = c + 48;
i -= c * 10000;
m = true;
}
// thousands
if( i > 999 ) {
c = i < 5000
? ( i < 3000
? ( i < 2000 ? 1 : 2 )
: i < 4000 ? 3 : 4
)
: i < 8000
? ( i < 6000
? 5
: i < 7000 ? 6 : 7
)
: i < 9000 ? 8 : 9;
_int2str[ L++ ] = c + 48;
i -= c * 1000;
m = true;
}
else if( m ) _int2str[ L++ ] = '0';
// hundreds
if( i > 99 ) {
c = i < 500
? ( i < 300
? ( i < 200 ? 1 : 2 )
: i < 400 ? 3 : 4
)
: i < 800
? ( i < 600
? 5
: i < 700 ? 6 : 7
)
: i < 900 ? 8 : 9;
_int2str[ L++ ] = c + 48;
i -= c * 100;
m = true;
}
else if( m ) _int2str[ L++ ] = '0';
// decades (check on lower byte to optimize code)
b = char( i );
if( b > 9 ) {
c = b < 50
? ( b < 30
? ( b < 20 ? 1 : 2 )
: b < 40 ? 3 : 4
)
: b < 80
? ( i < 60
? 5
: i < 70 ? 6 : 7
)
: i < 90 ? 8 : 9;
_int2str[ L++ ] = c + 48;
b -= c * 10;
m = true;
}
else if( m ) _int2str[ L++ ] = '0';
// last digit
_int2str[ L++ ] = b + 48;
// null terminator
_int2str[ L ] = 0;
return _int2str;
}
// Usage example:
int i = -12345;
char* s;
void setup() {
s = int2str( i );
}
void loop() {}
This sketch is compiled to 1,082 bytes of code using avr-gcc which bundled with Arduino v1.0.5 (size of int2str function itself is 594 bytes). Compared with solution using String object which compiled into 2,398 bytes, this implementation can reduce your code size by 1.2 Kb (assumed that you need no other String's object method, and your number is strict to signed int type).
This function can be optimized further by writing it in proper assembler code.
You could also try this :
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);
find
refers to the text to be found and replace
to the text to be replaced with
This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :
new RegExp(find[i], 'g')
This MSDN blog post describes three separate ways of extracting a DLL from the GAC. A useful summary of the methods so far given.
if you looking for a way how to download temporary file, do stuff and delete it try this gem https://github.com/equivalent/pull_tempfile
require 'pull_tempfile'
PullTempfile.transaction(url: 'https://mycompany.org/stupid-csv-report.csv', original_filename: 'dont-care.csv') do |tmp_file|
CSV.foreach(tmp_file.path) do |row|
# ....
end
end
Here is a component that incorporates much of this by lovasoa: https://github.com/lovasoa/react-contenteditable/blob/master/index.js
He shims the event in the emitChange
emitChange: function(evt){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
evt.target = { value: html };
this.props.onChange(evt);
}
this.lastHtml = html;
}
I'm using a similar approach successfully
I added -Dspring.profiles.active=test
to VM Options and then re-ran that configuration. It worked perfectly.
This can be set by
Run | Edit Configurations...
Configuration
tab Environment
section to reveal VM options
I would take those directions to mean:
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
var obj = { //note you don't use = in an object definition
"name": name,
"totalScore": totalScore,
"gamesPlayed": gamesPlayed
}
return obj;
}
Why not call the $('.input-group.date').datepicker("remove");
when the select statement is changed then set your datepicker view then call the $('.input-group.date').datepicker("update");
I think you will find more information in this link:
http://codeidol.com/community/dotnet/controlling-case-sensitivity-when-comparing-two-st/8873/
Use the Compare static method on the String class to compare the two strings. Whether the comparison is case-insensitive is determined by the third parameter of one of its overloads. For example:
string lowerCase = "abc";
string upperCase = "AbC";
int caseInsensitiveResult = string.Compare(lowerCase, upperCase,
StringComparison.CurrentCultureIgnoreCase);
int caseSensitiveResult = string.Compare(lowerCase,
StringComparison.CurrentCulture);
The caseSensitiveResult value is -1 (indicating that lowerCase is "less than" upperCase) and the caseInsensitiveResult is zero (indicating that lowerCase "equals" upperCase).
-XX:PermSize
specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize
.
Right click on Visual studio and click Run as Administrator
Burgos has the right answer. Just to clarify, the Character Set should be changed to "Not Set".
A refined version of Moob's post. Create a hash of the POST, save it as a session cookie, and compare hashes every session.
// Optionally Disable browser caching on "Back"
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Expires: Sun, 1 Jan 2000 12:00:00 GMT' );
header( 'Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT' );
$post_hash = md5( json_encode( $_POST ) );
if( session_start() )
{
$post_resubmitted = isset( $_SESSION[ 'post_hash' ] ) && $_SESSION[ 'post_hash' ] == $post_hash;
$_SESSION[ 'post_hash' ] = $post_hash;
session_write_close();
}
else
{
$post_resubmitted = false;
}
if ( $post_resubmitted ) {
// POST was resubmitted
}
else
{
// POST was submitted normally
}
For a single line of text (or a single character) you can use this technique:
It can be used when #box
has a non-fixed, relative height in %.
<div id="box"></div>
#box::before {
display: block;
content: "";
height: 50%;
}
#box::after {
vertical-align: top;
line-height: 0;
content: "TextContent";
}
See a live demo at JsBin (easier to edit CSS) or JsFiddle (easier to change height of result frame).
If you want to place inner text in HTML, not in CSS, then you need to wrap text content in additional inline element and edit #box::after
to match it. (And, of course, content:
property should be removed.)
For example,
<div id="box"><span>TextContent</span></div>
.
In this case, #box::after
should be replaced with #box span
.
For Internet Explorer 8 support you must replace ::
with :
.
Now you can use new html5 input validation attribute pattern=".+\.(xlsx|xls|csv)"
.
pip install PyYAML
If libyaml is not found or compiled PyYAML can do without it on Mavericks.
Based on the above stuff:
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)
fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)
plot = fig.add_subplot(1, 1, 1)
plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)
for label in (plot.get_xticklabels() + plot.get_yticklabels()):
label.set_fontproperties(font)
According to this link Set default date of jquery datepicker, the other solution is
var d = new Date();
var currDate = d.getDate();
var currMonth = d.getMonth();
var currYear = d.getFullYear();
var dateStr = currDate + "-" + currMonth + "-" + currYear;
$("#datepicker").datepicker(({dateFormat: "dd-mm-yy" autoclose: true, defaultDate: dateStr });
Or maybe even easier
grep -R put **/*bills*
The **
glob syntax means "any depth of directories". It will work in Zsh, and I think recent versions of Bash too.
The syntax for using an alias in an update statement on SQL Server is as follows:
UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;
The alias should not be necessary here though.
us the AS keyword
select a.Price as PriceOne, b.price as PriceTwo
from tablea a, tableb b
If you want to get the full width of the page, including overflow, use document.body.scrollWidth
.
Change @Controller to @RestController in your controller class and everything should go smoothly.
You could create a razor file in the App_Code folder and then access it from your view pages.
Project>Repository/IdentityRepository.cs
namespace Infrastructure.Repository
{
public class IdentityRepository : IIdentityRepository
{
private readonly ISystemSettings _systemSettings;
private readonly ISessionDataManager _sessionDataManager;
public IdentityRepository(
ISystemSettings systemSettings
)
{
_systemSettings = systemSettings;
}
public string GetCurrentUserName()
{
return HttpContext.Current.User.Identity.Name;
}
}
}
Project>App_Code/IdentityRepositoryViewFunctions.cshtml:
@using System.Web.Mvc
@using Infrastructure.Repository
@functions
{
public static IIdentityRepository IdentityRepositoryInstance
{
get { return DependencyResolver.Current.GetService<IIdentityRepository>(); }
}
public static string GetCurrentUserName
{
get
{
var identityRepo = IdentityRepositoryInstance;
if (identityRepo != null)
{
return identityRepo.GetCurrentUserName();
}
return null;
}
}
}
Project>Views/Shared/_Layout.cshtml (or any other .cshtml file)
<div>
@IdentityRepositoryViewFunctions.GetCurrentUserName
</div>
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.
int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();
Hope this answers the question.