There is a comparison of the features and performance of RabbitMQ ActiveMQ and QPID given at
http://bhavin.directi.com/rabbitmq-vs-apache-activemq-vs-apache-qpid/
Personally I have tried all the above three. RabbitMQ is the best performance wise according to me, but it does not have failover and recovery options. ActiveMQ has the most features, but is slower.
Update : HornetQ is also an option you can look into, it is JMS Complaint, a better option than ActiveMQ if you are looking for a JMS based solution.
Found it on another thread that solved my problem... was using an internet connection less network.
In that case copy the xsd files from the url and place it next to the beans.xml file and change the xsi:schemaLocation as under:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
spring-beans-3.1.xsd">
The short answer is "message acknowledgements". RabbitMQ can be configured to require message acknowledgements. If a receiver fails the message goes back on the queue and another receiver can try again. While you can accomplish this in Kafka with your own code, it works with RabbitMQ out of the box.
In my experience, if you have an application that has requirements to query a stream of information, Kafka and KSql are your best bet. If you want a queueing system you are better off with RabbitMQ.
Message queues are ideal for requests which may take a long time to process. Requests are queued and can be processed offline without blocking the client. If the client needs to be notified of completion, you can provide a way for the client to periodically check the status of the request.
Message queues also allow you to scale better across time. It improves your ability to handle bursts of heavy activity, because the actual processing can be distributed across time.
Note that message queues and web services are orthogonal concepts, i.e. they are not mutually exclusive. E.g. you can have a XML based web service which acts as an interface to a message queue. I think the distinction your looking for is Message Queues versus Request/Response, the latter is when the request is processed synchronously.
Shameless plug: I'm working on Bokeh: a simple, scalable and blazing-fast task queue built on ZeroMQ. It supports pluggable data stores for persisting tasks, currently in-memory, Redis and Riak are supported. Check it out.
We are using JMS for communication with systems in a huge number of remote sites over unreliable networks. The loose coupling in combination with reliable messaging produces a stable system landscape: Each message will be sent as soon it is technically possible, bigger problems in network will not have influence on the whole system landscape...
HTML5 number input doesn't have styles attributes like width or size, but you can style it easily with CSS.
input[type="number"] {
width:50px;
}
Another approach using Fetch API with Promise
<html>
<body>
<div class="root" data-content="partial.html">
<script>
const root = document.querySelector('.root')
const link = root.dataset.content;
fetch(link)
.then(function (response) {
return response.text();
})
.then(function (html) {
root.innerHTML = html;
});
</script>
</body>
</html>
This can be done quite easily if you:
Use str
to convert the number into a string so that you can iterate over it.
Use a list comprehension to split the string into individual digits.
Use int
to convert the digits back into integers.
Below is a demonstration:
>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>
select * from yourtable
where created < now()
and created > concat(curdate(),' 4:30:00 AM')
Also, you could use regex findall. It's a more general solution since it adds more control over the length of the number. It could be helpful in cases where you require a number with minimal length.
True if len(''.join(re.findall('\d+', '67389kjsdk'))) > 0 else False
Hope it helps some else.
You can use the accept attribute along with the . It doesn't work in IE and Safari.
Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.
For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes
Because it's more common to call range(0, 10)
which returns [0,1,2,3,4,5,6,7,8,9]
which contains 10 elements which equals len(range(0, 10))
. Remember that programmers prefer 0-based indexing.
Also, consider the following common code snippet:
for i in range(len(li)):
pass
Could you see that if range()
went up to exactly len(li)
that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++)
over for(int i = 0; i <= 9; i++)
.
If you are calling range with a start of 1 frequently, you might want to define your own function:
>>> def range1(start, end):
... return range(start, end+1)
...
>>> range1(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I repaired it using the Microsoft .NET Framework Repair Tool. After reloading my project a couple of times after that the problem went away.
I don't know R at all, but a bit of creative googling led me here: http://tolstoy.newcastle.edu.au/R/help/05/04/1919.html
The key quote from there:
I do not find explicit documentation for R on how to remove elements from lists, but trial and error tells me
myList[[5]] <- NULL
will remove the 5th element and then "close up" the hole caused by deletion of that element. That suffles the index values, So I have to be careful in dropping elements. I must work from the back of the list to the front.
A response to that post later in the thread states:
For deleting an element of a list, see R FAQ 7.1
And the relevant section of the R FAQ says:
... Do not set x[i] or x[[i]] to NULL, because this will remove the corresponding component from the list.
Which seems to tell you (in a somewhat backwards way) how to remove an element.
Hope that helps, or at least leads you in the right direction.
I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447
Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!
Not an answer per se, but a guideline. Most of the time there is not much sense in declaring local T&&
variable (as you did with std::vector<int>&& rval_ref
). You will still have to std::move()
them to use in foo(T&&)
type methods. There is also the problem that was already mentioned that when you try to return such rval_ref
from function you will get the standard reference-to-destroyed-temporary-fiasco.
Most of the time I would go with following pattern:
// Declarations
A a(B&&, C&&);
B b();
C c();
auto ret = a(b(), c());
You don't hold any refs to returned temporary objects, thus you avoid (inexperienced) programmer's error who wish to use a moved object.
auto bRet = b();
auto cRet = c();
auto aRet = a(std::move(b), std::move(c));
// Either these just fail (assert/exception), or you won't get
// your expected results due to their clean state.
bRet.foo();
cRet.bar();
Obviously there are (although rather rare) cases where a function truly returns a T&&
which is a reference to a non-temporary object that you can move into your object.
Regarding RVO: these mechanisms generally work and compiler can nicely avoid copying, but in cases where the return path is not obvious (exceptions, if
conditionals determining the named object you will return, and probably couple others) rrefs are your saviors (even if potentially more expensive).
I am using django with postgres in Docker containers. in the docker-compose file, add the following:
db:
image: postgres:10-alpine
environment:
- POSTGRES_DB=app
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=supersecretpassword
**ports:
- "6543:5432"**
which will add accessible port by your local machine. for myself, I connected DBeaver to it. this will prevent port clashes between your app request and local machine request. at first, I got a message saying that the port 5432 is in use (which is by django app) so I couldn't access by pgAdmin or DBeaver.
In my dimens.xml I have
<dimen name="test">48dp</dimen>
In code If I do
int valueInPixels = (int) getResources().getDimension(R.dimen.test)
this will return 72 which as docs state is multiplied by density of current phone (48dp x 1.5 in my case)
exactly as docs state :
Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.
so if you want exact dp value just as in xml just divide it with DisplayMetrics density
int dp = (int) (getResources().getDimension(R.dimen.test) / getResources().getDisplayMetrics().density)
dp will be 48 now
I use the following code to create PDF
protected void CreatePDF(Stream stream)
{
using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
{
var writer = PdfWriter.GetInstance(document, stream);
writer.PageEvent = new ITextEvents();
document.Open();
// instantiate custom tag processor and add to `HtmlPipelineContext`.
var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
tagProcessorFactory.AddProcessor(
new TableProcessor(),
new string[] { HTML.Tag.TABLE }
);
//Register Fonts.
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);
htmlPipelineContext.SetTagFactory(tagProcessorFactory);
var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);
// get an ICssResolver and add the custom CSS
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
cssResolver.AddCss(CSSSource, "utf-8", true);
var cssResolverPipeline = new CssResolverPipeline(
cssResolver, htmlPipeline
);
var worker = new XMLWorker(cssResolverPipeline, true);
var parser = new XMLParser(worker);
using (var stringReader = new StringReader(HTMLSource))
{
parser.Parse(stringReader);
document.Close();
HttpContext.Current.Response.ContentType = "application /pdf";
if (base.View)
HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
else
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.WriteFile(OutputPath);
HttpContext.Current.Response.End();
}
}
}
For this you just need to add content
attribute and font-family
attribute to the required element via :before or :after wherever applicable.
For example: I wanted to attach an attachment icon after all the a
element inside my post. So, first I need to search if such icon exists in fontawesome. Like in the case I found it here, i.e. fa fa-paperclip
. Then I would right click the icon there, and go the ::before
pseudo property to fetch out the content
tag it is using, which in my case I found to be \f0c6
. Then I would use that in my css like this:
.post a:after {
font-family: FontAwesome,
content: " \f0c6" /* I added a space before \ for better UI */
}
This was a fun question! Another way to handle this for variable length lists is to build a function that takes full advantage of the .format
method and list unpacking. In the following example I don't use any fancy formatting, but that can easily be changed to suit your needs.
list_1 = [1,2,3,4,5,6]
list_2 = [1,2,3,4,5,6,7,8]
# Create a function that can apply formatting to lists of any length:
def ListToFormattedString(alist):
# Create a format spec for each item in the input `alist`.
# E.g., each item will be right-adjusted, field width=3.
format_list = ['{:>3}' for item in alist]
# Now join the format specs into a single string:
# E.g., '{:>3}, {:>3}, {:>3}' if the input list has 3 items.
s = ','.join(format_list)
# Now unpack the input list `alist` into the format string. Done!
return s.format(*alist)
# Example output:
>>>ListToFormattedString(list_1)
' 1, 2, 3, 4, 5, 6'
>>>ListToFormattedString(list_2)
' 1, 2, 3, 4, 5, 6, 7, 8'
If you are on Windows and use Anaconda you can try running "pip install ..." command in Anaconda Prompt instead of cmd.exe, as user willliu1995 suggests here. This was the fastest solution for me, that does not require installation of additional components.
Apache Commons Lang has a StringUtils.left
method for this.
String upToNCharacters = StringUtils.left(s, n);
same as Igor but should work without line 2:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
You can directly delete the column with just
del variable_name['year']
Add this below code for where you likes to
example
p{
display: block; /* Fallback for non-webkit */
display: -webkit-box;
max-width: 400px;
margin: 0 auto;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
If you just want to change alignment of text just make a classes
.left {
text-align: left;
}
and span that class through the text
<span class='left'>aligned left</span>
In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.
Just as a random example:
// The callback interface
interface MyCallback {
void callbackCall();
}
// The class that takes the callback
class Worker {
MyCallback callback;
void onEvent() {
callback.callbackCall();
}
}
// Option 1:
class Callback implements MyCallback {
void callbackCall() {
// callback code goes here
}
}
worker.callback = new Callback();
// Option 2:
worker.callback = new MyCallback() {
void callbackCall() {
// callback code goes here
}
};
I probably messed up the syntax in option 2. It's early.
Here is my lightweight vanilla JavaScript approach, using Flexbox:
http://codepen.io/lingtalfi/pen/zoNeJp
It was tested successfully in Google Chrome 54, Firefox 50, Safari 10, don't know about other browsers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.rawgit.com/lingtalfi/simpledrag/master/simpledrag.js"></script>
<style type="text/css">
html, body {
height: 100%;
}
.panes-container {
display: flex;
width: 100%;
overflow: hidden;
}
.left-pane {
width: 18%;
background: #ccc;
}
.panes-separator {
width: 2%;
background: red;
position: relative;
cursor: col-resize;
}
.right-pane {
flex: auto;
background: #eee;
}
.panes-container,
.panes-separator,
.left-pane,
.right-pane {
margin: 0;
padding: 0;
height: 100%;
}
</style>
</head>
<body>
<div class="panes-container">
<div class="left-pane" id="left-pane">
<p>I'm the left pane</p>
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
<div class="panes-separator" id="panes-separator"></div>
<div class="right-pane" id="right-pane">
<p>And I'm the right pane</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. A accusantium at cum cupiditate dolorum, eius eum
eveniet facilis illum maiores molestiae necessitatibus optio possimus sequi sunt, vel voluptate. Asperiores,
voluptate!
</p>
</div>
</div>
<script>
var leftPane = document.getElementById('left-pane');
var rightPane = document.getElementById('right-pane');
var paneSep = document.getElementById('panes-separator');
// The script below constrains the target to move horizontally between a left and a right virtual boundaries.
// - the left limit is positioned at 10% of the screen width
// - the right limit is positioned at 90% of the screen width
var leftLimit = 10;
var rightLimit = 90;
paneSep.sdrag(function (el, pageX, startX, pageY, startY, fix) {
fix.skipX = true;
if (pageX < window.innerWidth * leftLimit / 100) {
pageX = window.innerWidth * leftLimit / 100;
fix.pageX = pageX;
}
if (pageX > window.innerWidth * rightLimit / 100) {
pageX = window.innerWidth * rightLimit / 100;
fix.pageX = pageX;
}
var cur = pageX / window.innerWidth * 100;
if (cur < 0) {
cur = 0;
}
if (cur > window.innerWidth) {
cur = window.innerWidth;
}
var right = (100-cur-2);
leftPane.style.width = cur + '%';
rightPane.style.width = right + '%';
}, null, 'horizontal');
</script>
</body>
</html>
This HTML code depends on the simpledrag vanilla JavaScript lightweight library (less than 60 lines of code).
you can use
<img className="image" src=`images/${this.props.image}`>
or
<img className="image" src={'images/'+this.props.image}>
or
render() {
let imageUrl = this.props.image ? "images/"+this.props.image : 'some placeholder url image';
return (
<div>
<img className="image" src={imageUrl} />
</div>
)
}
Dears,
Please try : npm install -g react-native-cli
If you get an error like Cannot find module ‘npmlog’ you can install npm directly using this command. If the above command run successfully then no need to run this command
curl -0 -L https://npmjs.org/install.sh | sudo sh
#For_Ubuntu.
Best regards.
PowerBI Embedded requires TLS 1.2.
The answer above by Etienne Faucher is your solution. quick link to above answer... quick link to above answer... ( https://stackoverflow.com/a/45442874 )
PowerBI Requires TLS 1.2 June 2020 - This Is your Answer - Consider Forcing your IIS runtime to get up to 4.6 to force the default TLS 1.2 behavior you are looking for from the framework. The above answer gives you a config change only solution.
Symptoms: Forced Closed Rejected TCP/IP Connection to Microsoft PowerBI Embedded that just shows up all of a sudden across your systems.
These PowerBI Calls just stop working with a Hard TCP/IP Close error like a firewall would block a connection. Usually the auth steps work - it is when you hit the service for specific workspace and report id's that it fails.
This is the 2020 note from Microsoft PowerBI about TLS 1.2 required
PowerBIClient
methods that show this problem
GetReportsInGroupAsync GetReportsInGroupAsAdminAsync GetReportsAsync GetReportsAsAdminAsync Microsoft.PowerBI.Api HttpClientHandler Force TLS 1.1 TLS 1.2
Search Error Terms to help people find this: System.Net.Http.HttpRequestException: An error occurred while sending the request System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Oddly enough it doesn't actually happen on every page and it doesn't seem to always work even when refreshed.
My solutions was to add {height: 100%;}
as well.
In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.
For an array:
var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();
As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.
But as we all know JavaScript is strange, so here are some weird bits:
array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!
This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()
). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.
So what are Objects?
Objects in JavaScript are just like arrays but the "index" can be any string.
var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK
You can even opt to not use the square brackets when working with objects!
console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";
You can go even further and define objects like so:
var newObject = {
a: 2,
};
newObject.a === 2; // true
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
Using CocoaPods with a Gemfile
With a Gemfile setup, you run bundle install
to install, or bundle update
to update within your Gemfile's constraints. From here on in however, you will need to remember to run bundle exec
before any terminal commands that have come in via bundler. Given that CocoaPods is included in the above this means any time you would write pod XX YY
you need to do bundle exec pod XX YY
.
Doing it without bundle exec
will bypass your Gemfile's specific versioning and will use the latest version of the library within RubyGems. This could potentially be the exact same version, but it can often not. If you are including CocoaPods plugins then they may also not be run.
This means you can be sure that foundational tooling for projects are versioned just like your personal libraries.
I'm not a WCF expert but I'm wondering if you aren't running into a DDOS protection on IIS. I know from experience that if you run a bunch of simultaneous connections from a single client to a server at some point the server stops responding to the calls as it suspects a DDOS attack. It will also hold the connections open until they time-out in order to slow the client down in his attacks.
Multiple connection coming from different machines/IP's should not be a problem however.
There's more info in this MSDN post:
http://msdn.microsoft.com/en-us/library/bb463275.aspx
Check out the MaxConcurrentSession sproperty.
Try to remove the view at onPause() of an activity and add onRestart()
LayoutYouAddedYourView.addView(YourCustomView); LayoutYouAddedYourView.removeView(YourCustomView);
The moment you add your view, onDraw() method would get called.
YourCustomView, is a class which extends the View class.
I'm resurrecting this because I was researching a non-JavaScript way to do this. I wasn't into the key handlers, and the CSS positioning stuff was causing tab ordering to break since CSS repositioning doesn't change tab order.
My solution is based on the response at https://stackoverflow.com/a/9491141.
The solution source is below. tabindex is used to correct tab behaviour of the hidden button, as well as aria-hidden to avoid having the button read out by screen readers / identified by assistive devices.
<form method="post" action="">
<button type="submit" name="useraction" value="2nd" class="default-button-handler" aria-hidden="true" tabindex="-1"></button>
<div class="form-group">
<label for="test-input">Focus into this input: </label>
<input type="text" id="test-input" class="form-control" name="test-input" placeholder="Focus in here and press enter / go" />
</div>
1st button in DOM 2nd button in DOM 3rd button in DOM
Essential CSS for this solution:
.default-button-handler {
width: 0;
height: 0;
padding: 0;
border: 0;
margin: 0;
}
In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as
save page as
filename : any_name.html
save as type : webpage complete.
Then you will get any_name.html
and any_name folder
.
See this:
In the Microsoft .NET framework, an assembly is a partially compiled code library for use in deployment, versioning and security
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
If you are using Mongoose,
try {
const data = await GPSDatas.aggregate([
{
$match: { createdAt : { $gt: new Date() }
},
{
$sort: { createdAt: 1 }
}
])
console.log(data)
} catch(error) {
console.log(error)
}
Edit
For angular 6.1 and newer, use the KeyValuePipe as suggested by Londeren.
For angular 6.0 and older
To make things easier, you can create a pipe.
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'getValues'})
export class GetValuesPipe implements PipeTransform {
transform(map: Map<any, any>): any[] {
let ret = [];
map.forEach((val, key) => {
ret.push({
key: key,
val: val
});
});
return ret;
}
}
<li *ngFor="let recipient of map |getValues">
As it it pure, it will not be triggered on every change detection, but only if the reference to the map
variable changes
Will be slightly neater using a CSS class instead of repeating inline styles.
CSS
input[type=submit] {
position: absolute;
left: -9999px;
}
HTML
<form ng-submit="myFunc()">
<input type="text" ng-model="name" />
<br />
<input type="text" ng-model="email" />
<input type="submit" />
</form>
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
Here is the code form https://github.com/ssnau/xkit/blob/master/util/is-promise.js
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
if an object with a then
method, it should be treat as a Promise
.
Have a look at Wikipedia:
Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A). These characters are based on printer commands: The line feed indicated that one line of paper should feed out of the printer, and a carriage return indicated that the printer carriage should return to the beginning of the current line.
I encountered the SSL error on a CentOS server running JDK 6.
My plan was to install a higher JDK version (JDK 7) to co-exist with JDK 6 but it turns out that merely installing the newer JDK with rpm -i
was not enough.
The JDK 7 installation would only succeed with the rpm -U
upgrade option as illustrated below.
wget -O /root/jdk-7u79-linux-x64.rpm --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; o raclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u79-b15/jdk-7u79-linux-x64.rpm"
rpm -ivh jdk-7u79-linux-x64.rpm
Preparing... ########################################### [100%]
file /etc/init.d/jexec from install of jdk-2000:1.7.0_79-fcs.x86_64 conflicts with file from package jdk-2000:1.6.0_43-fcs.x86_64
rpm -Uvh jdk-7u79-linux-x64.rpm
Preparing... ########################################### [100%]
1:jdk ########################################### [100%]
Unpacking JAR files...
rt.jar...
jsse.jar...
charsets.jar...
tools.jar...
localedata.jar...
jfxrt.jar...
java -version
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
Piping output to xargs
will concatenate each line of output to a single line with spaces:
grep pattern file | xargs
Or any command, eg. ls | xargs
. The default limit of xargs
output is ~4096 characters, but can be increased with eg. xargs -s 8192
.
Casting int to char is done simply by assigning with the type in parenthesis:
int i = 65535;
char c = (char)i;
Note: I thought that you might be losing data (as in the example), because the type sizes are different.
Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h>
functions like strcat
or sprintf
.
A slightly simpler method:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
According to the error message ("Could not find or load main class"), there are two categories of problems:
Main class could not be found when there is typo or wrong syntax in the fully qualified class name or it does not exist in the provided classpath.
Main class could not be loaded when the class cannot be initiated, typically the main class extends another class and that class does not exist in the provided classpath.
For example:
public class YourMain extends org.apache.camel.spring.Main
If camel-spring is not included, this error will be reported.
Now W3c provides an official difference on their site:
The answers to this question are a little out of date and missing potentially key steps, so this is an updated guide for installing an app from an external developer.
----- How to Resign an iOS App -----
Let's say you receive an app (e.g. MyApp.ipa) from another developer, and you want to be able to install and run it on your devices (by using ideviceinstaller, for example).
Prepare New Signing Assets
The first step is to attain a Provisioning Profile which includes all of the devices you wish to install and run on. Ensure that the profile contains a certificate that you have installed in your Keychain Access (e.g. iPhone Developer: Some Body (XXXXXXXXXX) ). Download the profile (MyProfile.mobileprovision) so you can replace the profile embedded in the app.
Next, we are going to prepare an entitlements file to include in the signing. Open up your terminal and run the following.
$ security cms -D -i path/to/MyProfile.mobileprovision > provision.plist
This will create an xml file describing your Provisioning Profile. Next, we want to extract the entitlements into a file.
$ /usr/libexec/PlistBuddy -x -c 'Print :Entitlements' provision.plist > entitlements.plist
Replace The Provisioning Profile and Resign App
If you are working with a .ipa file, first, unzip the app (if you have a .app instead, you can skip this step).
$ unzip MyApp.ipa
Your working directory will now contain Payload/
and Payload/MyApp.app/
. Next, remove the old code signature files.
$ rm -rf Payload/MyApp.app/_CodeSignature
Replace the existing provisioning profile (i.e. embedded.mobileprovision) with your own.
$ cp path/to/MyProfile.mobileprovision Payload/MyApp.app/embedded.mobileprovision
Now sign the app with the certificate included in your provisioning profile and the entitlements.plist that you created earlier.
$ /usr/bin/codesign -f -s "iPhone Developer: Some Body (XXXXXXXXXX)" --entitlements entitlements.plist Payload/MyApp.app
IMPORTANT: You must also resign all frameworks included in the app. You will find these in Payload/MyApp.app/Frameworks
. If the app is written in Swift or if it includes any additional frameworks these must be resigned or the app will install but not run.
$ /usr/bin/codesign -f -s "iPhone Developer: Some Body (XXXXXXXXXX)" --entitlements entitlements.plist Payload/MyApp.app/Frameworks/*
You can now rezip the app.
$ zip -qr MyApp-resigned.ipa Payload
Done
You may now remove the Payload
directory since you have your original app (MyApp.ipa) and your resigned version (MyApp-resigned.ipa). You can now install MyApp-resigned.ipa on any device included in your provisioning profile.
I have this issue too. I suspect there is an issue with DigitalOcean’s nameservers, so this will likely affect a lot of other people too. Here’s what I’ve done to temporarily get around it - but someone else might be able to advise on a better long-term fix:
Make sure your DNS Resolver config file is writable:
sudo chmod o+r /etc/resolv.conf
Temporarily change your DNS to use Google’s nameservers instead of DigitalOcean’s:
sudo nano /etc/resolv.conf
Change the IP address in the file to: 8.8.8.8
Press CTRL
+
X
to save the file.
This is only a temporary fix as this file is automatically written/updated by the server, however, I’ve not yet worked out what writes to it so that I can update it permanently.
$('#message').val('');
Explanation (from @BalusC):
textarea
is an input
element with a value. You actually want to "empty" the value. So as for every other input
element (input
, select
, textarea
) you need to use element.val('');
.
Also see docs
Example query:
SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;
I didn't wanna stop using var_dump($variable);die();
and using pre
tags and loops seems overkill to me, so since I am looking at the dump in a browser, I just right click the page and choose Inspect (I use Chrome). The Elements section of the Developer Tools show the variable in a very readable format.
The caller-saved / callee-saved terminology is based on a pretty braindead inefficient model of programming where callers actually do save/restore all the call-clobbered registers (instead of keeping long-term-useful values elsewhere), and callees actually do save/restore all the call-preserved registers (instead of just not using some or any of them).
Or you have to understand that "caller-saved" means "saved somehow if you want the value later".
In reality, efficient code lets values get destroyed when they're no longer needed. Compilers typically make functions that save a few call-preserved registers at the start of a function (and restore them at the end). Inside the function, they use those regs for values that need to survive across function calls.
I prefer "call-preserved" vs. "call-clobbered", which are unambiguous and self-describing once you've heard of the basic concept, and don't require any serious mental gymnastics to think about from the caller's perspective or the callee's perspective. (Both terms are from the same perspective).
Plus, these terms differ by more than one letter.
The terms volatile / non-volatile are pretty good, by analogy with storage which loses its value on power-loss or not, (like DRAM vs. Flash). But the C volatile
keyword has a totally different technical meaning, so that's a downside to "(non)-volatile" when describing C calling conventions.
From the callee's perspective, your function can freely overwrite (aka clobber) these registers without saving/restoring.
From a caller's perspective, call foo
destroys (aka clobbers) all the call-clobbered registers, or at least you have to assume it does.
You can write private helper functions that have a custom calling convention, e.g. you know they don't modify a certain register. But if all you know (or want to assume or depend on) is that the target function follows the normal calling convention, then you have to treat a function call as if it does destroy all the call-clobbered registers. That's literally what the name come from: a call clobbers those registers.
Some compilers that do inter-procedural optimization can also create internal-use-only definitions of functions that don't follow the ABI, using a custom calling convention.
From a callee's perspective, these registers can't be modified unless you save the original value somewhere so you can restore it before returning. Or for registers like the stack pointer (which is almost always call-preserved), you can subtract a known offset and add it back again before returning, instead of actually saving the old value anywhere. i.e. you can restore it by dead reckoning, unless you allocate a runtime-variable amount of stack space. Then typically you restore the stack pointer from another register.
A function that can benefit from using a lot of registers can save/restore some call-preserved registers just so it can use them as more temporaries, even if it doesn't make any function calls. Normally you'd only do this after running out of call-clobbered registers to use, because save/restore typically costs a push/pop at the start/end of the function. (Or if your function has multiple exit paths, a pop
in each of them.)
The name "caller-saved" is misleading: you don't have to specially save/restore them. Normally you arrange your code to have values that need to survive a function call in call-preserved registers, or somewhere on the stack, or somewhere else that you can reload from. It's normal to let a call
destroy temporary values.
See for example What registers are preserved through a linux x86-64 function call for the x86-64 System V ABI.
Also, arg-passing registers are always call-clobbered in all function-calling conventions I'm aware of. See Are rdi and rsi caller saved or callee saved registers?
But system-call calling conventions typically make all the registers except the return value call-preserved. (Usually including even condition-codes / flags.) See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64
hmm - something like this?
set host=%COMPUTERNAME%
echo %host%
EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:
@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%
In either case, 'host' is created as an environment variable.
if [ -z "$(ls -lA)" ]; then
echo "no files found"
else
echo "There are files"
fi
This will run the command and check whether the returned output (string) has a zero length. You might want to check the 'test' manual pages for other flags.
Use the "" around the argument that is being checked, otherwise empty results will result in a syntax error as there is no second argument (to check) given!
Note: that ls -la
always returns .
and ..
so using that will not work, see ls manual pages. Furthermore, while this might seem convenient and easy, I suppose it will break easily. Writing a small script/application that returns 0 or 1 depending on the result is much more reliable!
FileNotFound
is just an unfortunate exception used to indicate that the web server returned a 404.
http://filext.com/file-extension/FTL points to http://freemarker.sourceforge.net/ , does that help?
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
I had similar problem, the solution for Windows looks the same (my Jenkins is installed on a Windows machine):
Global settings:
Go to Manage jenkins -> Configure System -> Git installations
add there the git exe path (for example: C:\Program Files\Git\bin\git.exe
), or you can use environment variable.
For Jenkins version 2.121.3, Go to Manage jenkins -> Global tool configuration -> Git installations -> Path to Git executable: C:\Program Files\Git\bin\git.exe
Jenkins job side:
Go to Source code Management -> select git, add your repository, choose connection to repository (http/ssh) and add credentials and it should work.
$("#chk0") is refering to an element with the id chk0. You might try adding id's to the elements. Ids are unique even though the names are the same so that in jQuery you can access a single element by it's id.
If you created any view in Mysql databases then you can simply see it as you see your all tables in your particular database.
write:
--mysql> SHOW TABLES;
you will see list of tables and views of your database.
You should put your model class before create_all()
call, like this:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
If your models are declared in a separate module, import them before calling create_all()
.
Say, the User
model is in a file called models.py
,
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
# See important note below
from models import User
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
Important note: It is important that you import your models after initializing the db
object since, in your models.py
_you also need to import the db
object from this module.
Following @Tobu answer and @mipadi comment, in a more pythonic way, if not interested in the created flag, I would use:
customer.source, _ = Source.objects.get_or_create(name="Website")
I was having this same problem too, I while multiple canvas elements with position:absolute does the job, if you want to save the output into an image, that's not going to work.
So I went ahead and did a simple layering "system" to code as if each layer had its own code, but it all gets rendered into the same element.
https://github.com/federicojacobi/layeredCanvas
I intend to add extra capabilities, but for now it will do.
You can do multiple functions and call them in order to "fake" layers.
The Substring
method provides us a way to extract a particular string from the original string based on a starting position and length. If only one argument is provided, it is taken to be the starting position, and the remainder of the string is outputted.
PS > "test_string".Substring(0,4)
Test
PS > "test_string".Substring(4)
_stringPS >
But this is easier...
$s = 'Hello World is in here Hello World!'
$p = 'Hello World'
$s -match $p
And finally, to recurse through a directory selecting only the .txt files and searching for occurrence of "Hello World":
dir -rec -filter *.txt | Select-String 'Hello World'
Got an awesome function here.
<?php
function getBrowser() {
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version= "";
//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
}elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
}elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
// Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)){
$bname = 'Internet Explorer';
$ub = "MSIE";
}elseif(preg_match('/Firefox/i',$u_agent)){
$bname = 'Mozilla Firefox';
$ub = "Firefox";
}elseif(preg_match('/OPR/i',$u_agent)){
$bname = 'Opera';
$ub = "Opera";
}elseif(preg_match('/Chrome/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
$bname = 'Google Chrome';
$ub = "Chrome";
}elseif(preg_match('/Safari/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
$bname = 'Apple Safari';
$ub = "Safari";
}elseif(preg_match('/Netscape/i',$u_agent)){
$bname = 'Netscape';
$ub = "Netscape";
}elseif(preg_match('/Edge/i',$u_agent)){
$bname = 'Edge';
$ub = "Edge";
}elseif(preg_match('/Trident/i',$u_agent)){
$bname = 'Internet Explorer';
$ub = "MSIE";
}
// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
}else {
$version= $matches['version'][1];
}
}else {
$version= $matches['version'][0];
}
// check if we have a number
if ($version==null || $version=="") {$version="?";}
return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}
// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>
Remember that when you restart the database by removing .lock files by force, the data might get corrupted. Your server shouldn't be considered "healthy" if you restarted the server that way.
To amend the situation, either run
mongod --repair
or
> db.repairDatabase();
in the mongo shell to bring your database back to "healthy" state.
Just changing APP_TIMEZONE=Asia/Colombo in .env and run php artisan lumen-config:cache worked for me in lumen 5.7
You generally don't want to bloat production package with things that you only intend to use for Development purposes.
Use --save-dev
(or -D
) option to separate packages such as Unit Test frameworks (jest, jasmine, mocha, chai, etc.)
Any other packages that your app needs for Production, should be installed using --save
(or -S
).
npm install --save lodash //prod dependency
npm install -S moment // " "
npm install -S opentracing // " "
npm install -D jest //dev only dependency
npm install --save-dev typescript //dev only dependency
If you open the package.json
file then you will see these entries listed under two different sections:
"dependencies": {
"lodash": "4.x",
"moment": "2.x",
"opentracing": "^0.14.1"
},
"devDependencies": {
"jest": "22.x",
"typescript": "^2.8.3"
},
Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.
An update could be executed this way …
class UserRepository extends \Doctrine\ORM\EntityRepository
{
public function updateUserStatus($userId, $newStatus)
{
return $this->createQueryBuilder('u')
->update()
->set('u.isActive', '?1')
->setParameter(1, $qb->expr()->literal($newStatus))
->where('u.id = ?2')
->setParameter(2, $qb->expr()->literal($userId))
->getQuery()
->getSingleScalarResult()
;
}
AJAX action handling:
# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
# Row updated
}
Working example using Doctrine 2.5 (on top of Symfony3).
To get the desired effect, you should place the image tag inside the same div as your text. Then set the float: left
attribute on the image. Hope this helps!
Starting with Python 3, raw_input()
was renamed to input()
.
From What’s New In Python 3.0, Builtins section second item.
NOTE - See Edit 4 if 3 digit precision is important
var discount = (price / listprice).toFixed(2);
toFixed will round up or down for you depending on the values beyond 2 decimals.
Example: http://jsfiddle.net/calder12/tv9HY/
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Edit - As mentioned by others this converts the result to a string. To avoid this:
var discount = +((price / listprice).toFixed(2));
Edit 2- As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. If accuracy to this degree is important I've found this answer: https://stackoverflow.com/a/32605063/1726511 Which seems to work well with all the tests I've tried.
There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices.
Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. Geez so many reworks!
var discount = roundTo((price / listprice), 2);
function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}
See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/
Edit 4 - You guys are killing me. Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result.
function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if (n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(digits);
if (negative) {
n = (n * -1).toFixed(digits);
}
return n;
}
You can do it using javascript
Plain javascript
var iframe = document.getElementsByTagName('iframe')[0];
iframe.style.background = 'white';
iframe.contentWindow.document.body.style.backgroundColor = 'white';
jQuery
$('iframe').css('background', 'white');
$('iframe').contents().find('body').css('backgroundColor', 'white');
To change the time in the database use: http://laravel.com/docs/4.2/eloquent#timestamps
Providing A Custom Timestamp Format
If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:
class User extends Eloquent {
protected function getDateFormat()
{
return 'U';
}
}
https://laravel.com/docs/5.1/eloquent
If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:
class Flight extends Model
{
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'U';
}
this way is right with me:
private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
Based on a combination of a few of the answers here this is what worked for me.
<Switch
android:trackTintMode="src_over"
android:thumbTint="@color/white"
android:trackTint="@color/shadow"
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
None of the answers I read worked in PuTTY, so I found a comment on this article:
In the settings for your connection, under "Window->Behavior" you'll find a setting "System Menu Appears on ALT alone". Then CTRL + L, ALT, l (that's a lower case L) will scroll the screen and then clear the scrollback buffer.
(relevant to the OP because I am connecting to an Ubuntu server, but also apparently relevant no matter what your server is running.)
There are many other binaries that need to be linked so I think it's much better to try something like sudo update-alternatives --all
and choosing the right alternatives for everything else besides java
and javac
.
There is no i
in xpath is not entirely true. You can still use the count()
to find the index.
Consider the following page
<html>_x000D_
_x000D_
<head>_x000D_
<title>HTML Sample table</title>_x000D_
</head>_x000D_
_x000D_
<style>_x000D_
table, td, th {_x000D_
border: 1px solid black;_x000D_
font-size: 15px;_x000D_
font-family: Trebuchet MS, sans-serif;_x000D_
}_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
th, td {_x000D_
text-align: left;_x000D_
padding: 8px;_x000D_
}_x000D_
_x000D_
tr:nth-child(even){background-color: #f2f2f2}_x000D_
_x000D_
th {_x000D_
background-color: #4CAF50;_x000D_
color: white;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<body>_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Heading 1</th>_x000D_
<th>Heading 2</th>_x000D_
<th>Heading 3</th>_x000D_
<th>Heading 4</th>_x000D_
<th>Heading 5</th>_x000D_
<th>Heading 6</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data row 1 col 1</td>_x000D_
<td>Data row 1 col 2</td>_x000D_
<td>Data row 1 col 3</td>_x000D_
<td>Data row 1 col 4</td>_x000D_
<td>Data row 1 col 5</td>_x000D_
<td>Data row 1 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 2 col 1</td>_x000D_
<td>Data row 2 col 2</td>_x000D_
<td>Data row 2 col 3</td>_x000D_
<td>Data row 2 col 4</td>_x000D_
<td>Data row 2 col 5</td>_x000D_
<td>Data row 2 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 3 col 1</td>_x000D_
<td>Data row 3 col 2</td>_x000D_
<td>Data row 3 col 3</td>_x000D_
<td>Data row 3 col 4</td>_x000D_
<td>Data row 3 col 5</td>_x000D_
<td>Data row 3 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 4 col 1</td>_x000D_
<td>Data row 4 col 2</td>_x000D_
<td>Data row 4 col 3</td>_x000D_
<td>Data row 4 col 4</td>_x000D_
<td>Data row 4 col 5</td>_x000D_
<td>Data row 4 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 5 col 1</td>_x000D_
<td>Data row 5 col 2</td>_x000D_
<td>Data row 5 col 3</td>_x000D_
<td>Data row 5 col 4</td>_x000D_
<td>Data row 5 col 5</td>_x000D_
<td>Data row 5 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
</br>_x000D_
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Heading 7</th>_x000D_
<th>Heading 8</th>_x000D_
<th>Heading 9</th>_x000D_
<th>Heading 10</th>_x000D_
<th>Heading 11</th>_x000D_
<th>Heading 12</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data row 1 col 1</td>_x000D_
<td>Data row 1 col 2</td>_x000D_
<td>Data row 1 col 3</td>_x000D_
<td>Data row 1 col 4</td>_x000D_
<td>Data row 1 col 5</td>_x000D_
<td>Data row 1 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 2 col 1</td>_x000D_
<td>Data row 2 col 2</td>_x000D_
<td>Data row 2 col 3</td>_x000D_
<td>Data row 2 col 4</td>_x000D_
<td>Data row 2 col 5</td>_x000D_
<td>Data row 2 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 3 col 1</td>_x000D_
<td>Data row 3 col 2</td>_x000D_
<td>Data row 3 col 3</td>_x000D_
<td>Data row 3 col 4</td>_x000D_
<td>Data row 3 col 5</td>_x000D_
<td>Data row 3 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 4 col 1</td>_x000D_
<td>Data row 4 col 2</td>_x000D_
<td>Data row 4 col 3</td>_x000D_
<td>Data row 4 col 4</td>_x000D_
<td>Data row 4 col 5</td>_x000D_
<td>Data row 4 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 5 col 1</td>_x000D_
<td>Data row 5 col 2</td>_x000D_
<td>Data row 5 col 3</td>_x000D_
<td>Data row 5 col 4</td>_x000D_
<td>Data row 5 col 5</td>_x000D_
<td>Data row 5 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The page has 2 tables and has 6 columns each with unique column names and 6 rows with variable data. The last row has the Modify
button in both the tables.
Assuming that the user has to select the 4th Modify
button from the first table based on the heading
Use the xpath //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button
The count()
operator comes in handy in situations like these.
Logic:
Modify
button using //th[.='Heading 4']
count(//tr/th[.='Heading 4']/preceding-sibling::th)+1
Note: Index starts at
0
Get the rows for the corresponding header using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]
Get the Modify
button from the extracted node list using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button
You can write your own extension method
public static class IntegerExtensions
{
public static int ParseInt(this string value, int defaultValue = 0)
{
int parsedValue;
if (int.TryParse(value, out parsedValue))
{
return parsedValue;
}
return defaultValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return value.ParseInt();
}
}
And wherever in code just call
int myNumber = someString.ParseInt(); // Returns value or 0
int age = someString.ParseInt(18); // With default value 18
int? userId = someString.ParseNullableInt(); // Returns value or null
In this concrete case
int yourValue = TextBoxD1.Text.ParseInt();
You set these configs either in the /etc/ansible/ansible.cfg
or ~/.ansible.cfg
or ansible.cfg
(in your current directory) file
[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
tested with ansible 2.9.6 in ubuntu 20.04
There are different ways of counting a specific elements
library(plyr)
numbers =c(4,23,4,23,5,43,54,56,657,67,67,435,453,435,7,65,34,435)
print(length(which(numbers==435)))
#Sum counts number of TRUE's in a vector
print(sum(numbers==435))
print(sum(c(TRUE, FALSE, TRUE)))
#count is present in plyr library
#o/p of count is a DataFrame, freq is 1 of the columns of data frame
print(count(numbers[numbers==435]))
print(count(numbers[numbers==435])[['freq']])
I was also facing same issues, and after lot of research found the solution:
- Your min sdk version should be same as of the modules you are using eg: your module min sdk version is 14 and your app min sdk version is 9 It should be same.
- If build version of your app and modules not same. Again it should same ** In short, your app
build.gradle
file and manifest should have same configurations**- There's no duplicacy like same permissions added in manifest file twice, same activity mention twice.
- If you have delete any activity from your project, delete it from your manifest file as well.
- Sometimes its because of label, icon etc tag of manifest file:
a) Add the
xmlns:tools
line in the manifest tag.b) Add
tools:replace=
ortools:ignore=
in the application tag.
Example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.slinfy.ikharelimiteduk"
xmlns:tools="http://schemas.android.com/tools"
android:versionCode="1"
android:versionName="1.0" >
<application
tools:replace="icon, label"
android:label="myApp"
android:name="com.example.MyApplication"
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="@drawable/ic_launcher"
android:theme="@style/Theme.AppCompat" >
</application>
</manifest>
- If two dependencies are of not same version example: you are using dependency for appcompat v7:26.0.0 and for facebook com.facebook.android:facebook-android-sdk:[4,5) facebook uses cardview of version com.android.support:cardview-v7:25.3.1 and appcompat v7:26.0.0 uses cardview of version v7:26.0.0, So there is discripancy in two libraries and thus give error
Error:Execution failed for task ':app:processDebugManifest'.
Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-alpha1) from [com.android.support:appcompat-v7:26.0.0-alpha1] AndroidManifest.xml:27:9-38 is also present at [com.android.support:cardview-v7:25.3.1] AndroidManifest.xml:24:9-31 value=(25.3.1). Suggestion: add 'tools:replace="android:value"' to element at AndroidManifest.xml:25:5-27:41 to override.
So by using appcompat of version 25.3.1, We can avoid this error
By considering above points in mind, you will get rid of this irritating issue. You can check my blog too https://wordpress.com/post/dhingrakimmi.wordpress.com/23
Alternatively, if your cell is already a real date, just use .Value instead of .Value2:
excelApp.Range[namedRange].Value
{21/02/2013 00:00:00}
Date: {21/02/2013 00:00:00}
Day: 21
DayOfWeek: Thursday
DayOfYear: 52
Hour: 0
Kind: Unspecified
Millisecond: 0
Minute: 0
Month: 2
Second: 0
Ticks: 634970016000000000
TimeOfDay: {00:00:00}
Year: 2013
excelApp.Range[namedRange].Value2
41326.0
I had similar problems because of .gitignore for the /storage
folder on first machine, then cloned repository on second machine and laravel was revision to write down sessions cache
So, manually creating folder /storage/sessions
might be an solution..
Using no messy concatenations and padding :
'{:0{width}x}'.format(int(temp,2)), width=4)
Will give a hex representation with padding preserved
Have you tried following the advice on the linked help page? The help page at http://g.co/mapsJSApiErrors says:
ApiNotActivatedMapError
The Google Maps JavaScript API is not activated on your API project. You may need to enable the Google Maps JavaScript API under APIs in the Google Developers Console.
See Obtaining an API key.
So check that the key you are using has Google Maps JavaScript API enabled.
Actually it is quite simple. If you need to often serialize dates, then work with them as strings. You can easily convert them back as datetime objects if needed.
If you need to work mostly as datetime objects, then convert them as strings before serializing.
import json, datetime
date = str(datetime.datetime.now())
print(json.dumps(date))
"2018-12-01 15:44:34.409085"
print(type(date))
<class 'str'>
datetime_obj = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f')
print(datetime_obj)
2018-12-01 15:44:34.409085
print(type(datetime_obj))
<class 'datetime.datetime'>
As you can see, the output is the same in both cases. Only the type is different.
Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.
If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.
Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.
<StackPanel x:Name="myStackPanel">
<CheckBox x:Name="myCheckBox"
Content="My CheckBox" />
<Button Content="Click to Uncheck"
x:Name="myUncheckButton" />
<Button Content="Click to check the box in code."
Click="OnClick" />
<StackPanel.Triggers>
<EventTrigger RoutedEvent="Button.Click"
SourceName="myUncheckButton">
<EventTrigger.Actions>
<BeginStoryboard x:Name="myBeginStoryboard">
<Storyboard x:Name="myStoryboard">
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
Storyboard.TargetProperty="IsChecked">
<DiscreteBooleanKeyFrame KeyTime="00:00:00"
Value="False" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="CheckBox.Click"
SourceName="myCheckBox">
<EventTrigger.Actions>
<StopStoryboard BeginStoryboardName="myBeginStoryboard" />
</EventTrigger.Actions>
</EventTrigger>
</StackPanel.Triggers>
</StackPanel>
To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.
We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.
private void OnClick(object sender, RoutedEventArgs e)
{
myStoryboard.Remove(myStackPanel);
myCheckBox.IsChecked = true;
}
This has been happening to me after restarts since upgrading from OS X El Capitan (10.11) to macOS Sierra (10.12). The ssh-add
solution worked temporarily but would not persist across another restart.
The permanent solution was to edit (or create) ~/.ssh/config
and enable the UseKeychain
option.
Host *
UseKeychain yes
Related: macOS keeps asking my ssh passphrase since I updated to Sierra
I followed an example in another repository and wrapped the directory structure within a pair of triple backticks (```
):
```
project
¦ README.md
¦ file001.txt
¦
+---folder1
¦ ¦ file011.txt
¦ ¦ file012.txt
¦ ¦
¦ +---subfolder1
¦ ¦ file111.txt
¦ ¦ file112.txt
¦ ¦ ...
¦
+---folder2
¦ file021.txt
¦ file022.txt
```
You can now toggle column selection mode, which changes mouse gestures and arrow keys, via:
"editor.action.toggleColumnSelection"
Note: There is a "Column Selection" panel in the status bar after activation, which you can press to disable it again.
I didn't know about git branch -rd
, so the way I have solved issues like this for myself is to treat my repo as a remote repo and do a remote delete. git push . :refs/remotes/public/master
. If the other ways don't work and you have some weird reference you want to get rid of, this raw way is surefire. It gives you the exact precision to remove (or create!) any kind of reference.
Place this code on the top of your existing code
import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)
Expanding a little bit on the previous answer, you can make the footnote links clickable here as well. First define the footnote at the bottom like this
<a name="myfootnote1">1</a>: Footnote content goes here
Then reference it at some other place in the document like this
<sup>[1](#myfootnote1)</sup>
Now there is the pandas_profiling
package, which is a more complete alternative to df.describe()
.
If your pandas dataframe is df
, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.
import pandas_profiling
pandas_profiling.ProfileReport(df)
See the example notebook detailing the usage.
You could use the "Shown" event: MSDN - Form.Shown
"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."
if (10 < x || x < 20)
This statement will evaluate true for numbers between 10 and 20.
This is a rough equivalent to 10 < x < 20
You can always do this:
jQuery.fn.extend({
myfunction: function(param){
// code here
},
});
OR
jQuery.extend({
myfunction: function(param){
// code here
},
});
$(element).myfunction(param);
You can make the id the primary key, and set member_id to NOT NULL UNIQUE
. (Which you've done.) Columns that are NOT NULL UNIQUE
can be the target of foreign key references, just like a primary key can. (I'm pretty sure that's true of all SQL platforms.)
At the conceptual level, there's no difference between PRIMARY KEY
and NOT NULL UNIQUE
. At the physical level, this is a MySQL issue; other SQL platforms will let you use a sequence without making it the primary key.
But if performance is really important, you should think twice about widening your table by four bytes per row for that tiny visual convenience. In addition, if you switch to INNODB in order to enforce foreign key constraints, MySQL will use your primary key in a clustered index. Since you're not using your primary key, I imagine that could hurt performance.
If you call it like this: $ python myfile.py var1 var2 var3
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
Similar to arrays you also have sys.argv[0]
which is always the current working directory.
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
set Culture to english from web.config file
<globalization uiCulture="en-US" culture="en-US" />
for example if you set the culture to arabic the thime will be
?22?/09?/2017? 02:16:57 ?
and you get the error:Conversion failed when converting date and/or time from character string while inserting datetime
If your application third party redirect internally, so it is better to mock HttpContext in below way :
HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };
The concept is very well explained by the accepted answer, but I find that the more example one sees, the better it sinks in. Here's an incremental example:
1) Boss says "get me number of items we have in stock grouped by brand"
You say: "no problem"
SELECT
BRAND
,COUNT(ITEM_ID)
FROM
ITEMS
GROUP BY
BRAND;
Result:
+--------------+---------------+
| Brand | Count |
+--------------+---------------+
| H&M | 50 |
+--------------+---------------+
| Hugo Boss | 100 |
+--------------+---------------+
| No brand | 22 |
+--------------+---------------+
2) The boss says "Now get me a list of all items, with their brand AND number of items that the respective brand has"
You may try:
SELECT
ITEM_NR
,BRAND
,COUNT(ITEM_ID)
FROM
ITEMS
GROUP BY
BRAND;
But you get:
ORA-00979: not a GROUP BY expression
This is where the OVER (PARTITION BY BRAND)
comes in:
SELECT
ITEM_NR
,BRAND
,COUNT(ITEM_ID) OVER (PARTITION BY BRAND)
FROM
ITEMS;
Whic means:
COUNT(ITEM_ID)
- get the number of itemsOVER
- Over the set of rows(PARTITION BY BRAND)
- that have the same brandAnd the result is:
+--------------+---------------+----------+
| Items | Brand | Count() |
+--------------+---------------+----------+
| Item 1 | Hugo Boss | 100 |
+--------------+---------------+----------+
| Item 2 | Hugo Boss | 100 |
+--------------+---------------+----------+
| Item 3 | No brand | 22 |
+--------------+---------------+----------+
| Item 4 | No brand | 22 |
+--------------+---------------+----------+
| Item 5 | H&M | 50 |
+--------------+---------------+----------+
etc...
After sruggling for two days I found the solution for the problem.You can use the ObjectFactory class to workaround for the classes which doesn't have the @XmlRootElement. ObjectFactory has overloaded methods to wrap it around the JAXBElement.
Method:1 does the simple creation of the object.
Method:2 will wrap the object with @JAXBElement.
Always use Method:2 to avoid javax.xml.bind.MarshalException - with linked exception missing an @XmlRootElement annotation.
Please find the sample code below
Method:1 does the simple creation of the object
public GetCountry createGetCountry() {
return new GetCountry();
}
Method:2 will wrap the object with @JAXBElement.
@XmlElementDecl(namespace = "my/name/space", name = "getCountry")
public JAXBElement<GetCountry> createGetCountry(GetCountry value) {
return new JAXBElement<GetCountry>(_GetCountry_QNAME, GetCountry.class, null, value);
}
Working code sample:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
WebServiceTemplate springWSTemplate = context.getBean(WebServiceTemplate.class);
GetCountry request = new GetCountry();
request.setGuid("test_guid");
JAXBElement<GetCountryResponse> jaxbResponse = (JAXBElement<GetCountryResponse>)springWSTemplate .marshalSendAndReceive(new ObjectFactory().createGetCountry(request));
GetCountryResponse response = jaxbResponse.getValue();
For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin
to the PATH
. Use whatever directory you have this installed in.
Then you can run from any directory in command line:
httpd -k restart
The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?
If searching for an element is important, I'd recommend std::set
instead of std::vector
. Using this:
std::find(vec.begin(), vec.end(), x)
runs in O(n) time, but std::set
has its own find()
member (ie. myset.find(x)
) which runs in O(log n) time - that's much more efficient with large numbers of elements
std::set
also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()...
.
Given a first selector: SelectorA, you can find the next match of SelectorB as below:
Example with mouseover to change border-with:
$("SelectorA").on("mouseover", function() {
var i = $(this).find("SelectorB")[0];
$(i).css({"border" : "1px"});
});
}
General use example to change border-with:
var i = $("SelectorA").find("SelectorB")[0];
$(i).css({"border" : "1px"});
Try
SELECT NAME, count(*) as NUM FROM tbl GROUP BY NAME
To get the currently logged in user path:
System.getProperty("user.home");
Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET Client IDs - this might help you too:
<asp:DropDownList id="MyDropDown" runat="server" />
$("[id* = 'MyDropDown']").append("<option value='-1'> </option>"); //etc
Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"
You could use the rails_default_value gem. eg:
class Foo < ActiveRecord::Base
# ...
default :bar => 'some default value'
# ...
end
To be able to use 'ngModule'
, the 'FormsModule'
(from @angular/forms
) needs to be added to your import[]
array in the AppModule
(should be there by default in a CLI project).
In Python 3, print is a function, you need to call it like print("hello world")
.
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
To clarify, system variables are the same as environment variables. User environment variables are set per user and are different whenever a different user logs in. System wide environment variables are the same no matter what user logs on.
To access either the current value of a system wide variable or a user variable in Java, see below:
String javaHome = System.getenv("JAVA_HOME");
For more information on environment variables see this wikipedia page.
Also make sure the environment variable you are trying to read is properly set before invoking Java by doing a:
echo %MYENVVAR%
You should see the value of the environment variable. If not, you may need to reopen the shell (DOS) or log off and log back on.
In my case, a click on a button causes a (not wanted) reload of the page.
Here is my fix:
<button class="btn btn-success" onclick="javascript: return false;"
data-target="#modalID" data-toggle="modal">deaktivieren</button>
As toolkit mentions above, Apache Commons IO is the way to go, specifically FileUtils.copyFile(); it handles all the heavy lifting for you.
And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files; NIO can significantly increase file-copying performance, in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer. So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.
This works and shows more than 255 characters in the message box.
Sub TestStrLength()
Dim s As String
Dim i As Integer
s = ""
For i = 1 To 500
s = s & "1234567890"
Next i
MsgBox s
End Sub
The message box truncates the string to 1023 characters, but the string itself can be very large.
I would also recommend that instead of using fixed variables names with numbers (e.g. Var1
, Var2
, Var3
, ... Var255
) that you use an array. This is much shorter declaration and easier to use - loops.
Here's an example:
Sub StrArray()
Dim var(256) As Integer
Dim i As Integer
Dim s As String
For i = 1 To 256
var(i) = i
Next i
s = "Tims_pet_Robot"
For i = 1 To 256
s = s & " """ & var(i) & """"
Next i
SecondSub (s)
End Sub
Sub SecondSub(s As String)
MsgBox "String length = " & Len(s)
End Sub
Updated this to show that a string can be longer than 255 characters and used in a subroutine/function as a parameter that way. This shows that the string length is 1443 characters. The actual limit in VBA is 2GB per string.
Perhaps there is instead a problem with the API that you are using and that has a limit to the string (such as a fixed length string). The issue is not with VBA itself.
Ok, I see the problem is specifically with the Application.OnTime method itself. It is behaving like Excel functions in that they only accept strings that are up to 255 characters in length. VBA procedures and functions though do not have this limit as I have shown. Perhaps then this limit is imposed for any built-in Excel object method.
Update:
changed ...longer than 256 characters...
to ...longer than 255 characters...
This might be an old question, but there's an alternate method you can use that no one has mentioned. It's possible to specify the password directly in the connection URI. The documentation can be found here, alternatively here.
You can provide your username and password directly in the connection URI provided to psql
:
# postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
psql postgresql://username:password@localhost:5432/mydb
hadoop fs -du -s -h /path/to/dir
displays a directory's size in readable form.
Javascript provides more than one method to check the viewport width. As you noticed, innerWidth doesn't include the toolbar width, and toolbar widths will differ across systems. There is also the outerWidth option, which will include the toolbar width. The Mozilla Javascript API states:
Window.outerWidth gets the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles.
The state of javascript is such that one cannot rely on a specific meaning for outerWidth in every browser on every platform.
outerWidth
is not well supported on older mobile browsers, though it enjoys support across major desktop browsers and most newer smart phone browsers.
As ausi pointed out, matchMedia
would be a great choice as CSS is better standardised (matchMedia uses JS to read the viewport values detected by CSS). But even with accepted standards, retarded browsers still exist that ignore them (IE < 10 in this case, which makes matchMedia not very useful at least until XP dies).
In summary, if you are only developing for desktop browsers and newer mobile browsers, outerWidth should give you what you are looking for, with some caveats.
To add on the good answers above you can also avoid setting explicitly the action in HTML and use an event handler in javascript, using "this" as the form to create the "FormData" object
Html form :
<form id="mainForm" class="" novalidate>
<!--Whatever here...-->
</form>
In your JS :
$("#mainForm").submit(function( event ) {
event.preventDefault();
const formData = new URLSearchParams(new FormData(this));
fetch("http://localhost:8080/your/server",
{ method: 'POST',
mode : 'same-origin',
credentials: 'same-origin' ,
body : formData
})
.then(function(response) {
return response.text()
}).then(function(text) {
//text is the server's response
});
});
@JsonIgnoreProperties(ignoreUnknown = true)
worked well for me. I have a java application which runs on tomcat with jdk 1.7.
Here's an example:
public class Main {
public static void main(String[] args) {
double val1 = 100;
double val2 = 10;
char operation = 'd';
double result = 0;
switch (operation) {
case 'a':
result = val1 + val2; break;
case 's':
result = val1 - val2; break;
case 'd':
if (val2 != 0)
result = val1 / val2; break;
case 'm':
result = val1 * val2; break;
default: System.out.println("Not a defined operation");
}
System.out.println(result);
}
}
If (condition, condition_is_true, condition_is_false)
It will look like this in longer version:
If (condition_is_true) Then
Else (condition_is_false)
End If
this worked great:
UPDATE
table_Name
SET
column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
ID = @ID
To add to Reed Copsey's answer about using Task.FromResult
, you can improve performance even more if you cache the already completed task since all instances of completed tasks are the same:
public static class TaskExtensions
{
public static readonly Task CompletedTask = Task.FromResult(false);
}
With TaskExtensions.CompletedTask
you can use the same instance throughout the entire app domain.
The latest version of the .Net Framework (v4.6) adds just that with the Task.CompletedTask
static property
Task completedTask = Task.CompletedTask;
This is the best way
LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them
lp.removeViewAt(0); // and so on
If you have xml layout then no need to add dynamically.just call
lp.removeViewAt(0);
Yep, in Windows 7 64 bit you have C:\Program Files
and C:\Program Files (x86)
. You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin
to environment variable PATH.
Say we have two date select fields, field1, and field2. field2 date depends on field1
$('#field2').datepicker();
$('#field1').datepicker({
onSelect: function(dateText, inst) {
$('#field2').val("");
$('#field2').datepicker("option", "minDate", new Date(dateText));
}
});
Open a command prompt. Change to the eclipse home directory and type "eclipse -clean" e.g. C:/eclipse>eclipse -clean
This will ask for the workspace selection. It will also force to set it as the default workspace.
Then, go to eclipsehome-->configuration-->settings folder.
open org.eclipse.ui.de.prefs in a notepad.
set this property to true from false.
SHOW_WORKSPACE_SELECTION_DIALOG=true
You will be asked for a workspace selection everytime.
Here is a way to do it while passing in an extra argument:
https://stackoverflow.com/a/17813797/4533488 (thanks to Denis Pshenov)
<div ng-repeat="group in groups">
<li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
<span>{{friend.name}}</span>
<li>
</div>
With the backend:
$scope.weDontLike = function(name) {
return function(friend) {
return friend.name != name;
}
}
.
And yet another way with an in-template filter only:
https://stackoverflow.com/a/12528093/4533488 (thanks to mikel)
<div ng:app>
<div ng-controller="HelloCntl">
<ul>
<li ng-repeat="friend in friends | filter:{name:'!Adam'}">
<span>{{friend.name}}</span>
<span>{{friend.phone}}</span>
</li>
</ul>
</div>
You can use a bool combination query with must/must_not which gives great performance and returns all records where the field is not null and not empty.
bool must_not is like "NOT AND" which means field!="", bool must exist means its !=null.
so effectively enabling: where field1!=null and field1!=""
GET IndexName/IndexType/_search
{
"query": {
"bool": {
"must": [{
"bool": {
"must_not": [{
"term": { "YourFieldName": ""}
}]
}
}, {
"bool": {
"must": [{
"exists" : { "field" : "YourFieldName" }
}]
}
}]
}
}
}
ElasticSearch Version:
"version": {
"number": "5.6.10",
"lucene_version": "6.6.1"
}
you need the libblas and liblapack dev packages if you are using Ubuntu.
aptitude install libblas-dev liblapack-dev
pip install scipy
You can use the split()
function in just one line code
int noOccurence=string.split("#",-1).length-1;
Add include_directories("/your/path/here")
.
This will be similar to calling gcc
with -I/your/path/here/
option.
Make sure you put double quotes around the path. Other people didn't mention that and it made me stuck for 2 days. So this answer is for people who are very new to CMake and very confused.
If you're on windows you probably want the pywin32
library, which includes pythoncom
and a whole lot of other stuff that is pretty standard.
You should actually fix your database schema so that you have three tables:
shirt: shirt_id, shirt_name
color: color_id, color_name
shirtcolor: shirt_id, color_id
Then if you want to find all of the shirts that are red, you'd do a query like:
SELECT *
FROM shirt, color
WHERE color.color_name = 'red'
AND shirt.shirt_id = shirtcolor.shirt_id
AND color.color_id = shirtcolor.color_id
You can use apachectl -V
or apachectl -v
. Both of them will return the Apache version information!
xgqfrms:~/workspace $ apachectl -v_x000D_
_x000D_
Server version: Apache/2.4.7 (Ubuntu)_x000D_
Server built: Jul 15 2016 15:34:04_x000D_
_x000D_
_x000D_
xgqfrms:~/workspace $ apachectl -V_x000D_
_x000D_
Server version: Apache/2.4.7 (Ubuntu)_x000D_
Server built: Jul 15 2016 15:34:04_x000D_
Server's Module Magic Number: 20120211:27_x000D_
Server loaded: APR 1.5.1-dev, APR-UTIL 1.5.3_x000D_
Compiled using: APR 1.5.1-dev, APR-UTIL 1.5.3_x000D_
Architecture: 64-bit_x000D_
Server MPM: prefork_x000D_
threaded: no_x000D_
forked: yes (variable process count)_x000D_
Server compiled with...._x000D_
-D APR_HAS_SENDFILE_x000D_
-D APR_HAS_MMAP_x000D_
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)_x000D_
-D APR_USE_SYSVSEM_SERIALIZE_x000D_
-D APR_USE_PTHREAD_SERIALIZE_x000D_
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT_x000D_
-D APR_HAS_OTHER_CHILD_x000D_
-D AP_HAVE_RELIABLE_PIPED_LOGS_x000D_
-D DYNAMIC_MODULE_LIMIT=256_x000D_
-D HTTPD_ROOT="/etc/apache2"_x000D_
-D SUEXEC_BIN="/usr/lib/apache2/suexec"_x000D_
-D DEFAULT_PIDLOG="/var/run/apache2.pid"_x000D_
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"_x000D_
-D DEFAULT_ERRORLOG="logs/error_log"_x000D_
-D AP_TYPES_CONFIG_FILE="mime.types"_x000D_
-D SERVER_CONFIG_FILE="apache2.conf"
_x000D_
You may be more like using apache2 -V
or apache2 -v
. It seems easier to remember!
xgqfrms:~/workspace $ apache2 -v_x000D_
_x000D_
Server version: Apache/2.4.7 (Ubuntu)_x000D_
Server built: Jul 15 2016 15:34:04_x000D_
_x000D_
_x000D_
xgqfrms:~/workspace $ apache2 -V_x000D_
_x000D_
Server version: Apache/2.4.7 (Ubuntu)_x000D_
Server built: Jul 15 2016 15:34:04_x000D_
Server's Module Magic Number: 20120211:27_x000D_
Server loaded: APR 1.5.1-dev, APR-UTIL 1.5.3_x000D_
Compiled using: APR 1.5.1-dev, APR-UTIL 1.5.3_x000D_
Architecture: 64-bit_x000D_
Server MPM: prefork_x000D_
threaded: no_x000D_
forked: yes (variable process count)_x000D_
Server compiled with...._x000D_
-D APR_HAS_SENDFILE_x000D_
-D APR_HAS_MMAP_x000D_
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)_x000D_
-D APR_USE_SYSVSEM_SERIALIZE_x000D_
-D APR_USE_PTHREAD_SERIALIZE_x000D_
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT_x000D_
-D APR_HAS_OTHER_CHILD_x000D_
-D AP_HAVE_RELIABLE_PIPED_LOGS_x000D_
-D DYNAMIC_MODULE_LIMIT=256_x000D_
-D HTTPD_ROOT="/etc/apache2"_x000D_
-D SUEXEC_BIN="/usr/lib/apache2/suexec"_x000D_
-D DEFAULT_PIDLOG="/var/run/apache2.pid"_x000D_
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"_x000D_
-D DEFAULT_ERRORLOG="logs/error_log"_x000D_
-D AP_TYPES_CONFIG_FILE="mime.types"_x000D_
-D SERVER_CONFIG_FILE="apache2.conf"
_x000D_
It cannot be done. It is impossible.
If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the
libncurses5:i386
,libstdc++6:i386
, andzlib1g:i386
packages usingapt-get
:
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
Worth mentioning that the handlebar library https://github.com/jknack/handlebars.java can trivialize many transformation tasks include toCSV.
i founded this tool to auto generate wsdl to android code,
http://www.wsdl2code.com/Example.aspx
public void callWebService(){
SampleService srv1 = new SampleService();
Request req = new Request();
req.companyId = "1";
req.userName = "userName";
req.password = "pas";
Response response = srv1.ServiceSample(req);
}
ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60);
I already did post this answer somewhere, i will do it here again. This version doesn't use any major inbuilt method. You got the char array, convert it into a String. Hope it helps!
import java.util.Scanner;
public class SentenceToWord
{
public static int getNumberOfWords(String sentence)
{
int counter=0;
for(int i=0;i<sentence.length();i++)
{
if(sentence.charAt(i)==' ')
counter++;
}
return counter+1;
}
public static char[] getSubString(String sentence,int start,int end) //method to give substring, replacement of String.substring()
{
int counter=0;
char charArrayToReturn[]=new char[end-start];
for(int i=start;i<end;i++)
{
charArrayToReturn[counter++]=sentence.charAt(i);
}
return charArrayToReturn;
}
public static char[][] getWordsFromString(String sentence)
{
int wordsCounter=0;
int spaceIndex=0;
int length=sentence.length();
char wordsArray[][]=new char[getNumberOfWords(sentence)][];
for(int i=0;i<length;i++)
{
if(sentence.charAt(i)==' ' || i+1==length)
{
wordsArray[wordsCounter++]=getSubString(sentence, spaceIndex,i+1); //get each word as substring
spaceIndex=i+1; //increment space index
}
}
return wordsArray; //return the 2 dimensional char array
}
public static void main(String[] args)
{
System.out.println("Please enter the String");
Scanner input=new Scanner(System.in);
String userInput=input.nextLine().trim();
int numOfWords=getNumberOfWords(userInput);
char words[][]=new char[numOfWords+1][];
words=getWordsFromString(userInput);
System.out.println("Total number of words found in the String is "+(numOfWords));
for(int i=0;i<numOfWords;i++)
{
System.out.println(" ");
for(int j=0;j<words[i].length;j++)
{
System.out.print(words[i][j]);//print out each char one by one
}
}
}
}
Just to list some more differences:
Update:
This came from Maven: The Definitive Guide. Sorry, I totally forgot to cite it.
path.resolve('.')
is also a reliable and clean option, because we almost always require('path')
. It will give you absolute path of the directory from where it is called.
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if
like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
This regex selects all spaces, you can use this and replace it with a single space
\s+
example in python
result = re.sub('\s+',' ', data))
If an element has multiples classes "[class^='apple-']" dosen't work, e.g.
<div class="fruits apple-monkey"></div>
Here's my go with comments in the code.
I'm just brushing up by biatch skills so forgive any blatant errors.
I tried to write an all in one solution as best I can with a little modification where the user requires it.
Some important notes: Just change the variable recursive
to FALSE
if you only want the root directories files and folders processed. Otherwise, it goes through all folders and files.
C&C most welcome...
@echo off
title %~nx0
chcp 65001 >NUL
set "dir=c:\users\%username%\desktop"
::
:: Recursive Loop routine - First Written by Ste on - 2020.01.24 - Rev 1
::
setlocal EnableDelayedExpansion
rem THIS IS A RECURSIVE SOLUTION [ALBEIT IF YOU CHANGE THE RECURSIVE TO FALSE, NO]
rem By removing the /s switch from the first loop if you want to loop through
rem the base folder only.
set recursive=TRUE
if %recursive% equ TRUE ( set recursive=/s ) else ( set recursive= )
endlocal & set recursive=%recursive%
cd /d %dir%
echo Directory %cd%
for %%F in ("*") do (echo ? %%F) %= Loop through the current directory. =%
for /f "delims==" %%D in ('dir "%dir%" /ad /b %recursive%') do ( %= Loop through the sub-directories only if the recursive variable is TRUE. =%
echo Directory %%D
echo %recursive% | find "/s" >NUL 2>NUL && (
pushd %%D
cd /d %%D
for /f "delims==" %%F in ('dir "*" /b') do ( %= Then loop through each pushd' folder and work on the files and folders =%
echo %%~aF | find /v "d" >NUL 2>NUL && ( %= This will weed out the directories by checking their attributes for the lack of 'd' with the /v switch therefore you can now work on the files only. =%
rem You can do stuff to your files here.
rem Below are some examples of the info you can get by expanding the %%F variable.
rem Uncomment one at a time to see the results.
echo ? %%~F &rem expands %%F removing any surrounding quotes (")
rem echo ? %%~dF &rem expands %%F to a drive letter only
rem echo ? %%~fF &rem expands %%F to a fully qualified path name
rem echo ? %%~pF &rem expands %%A to a path only
rem echo ? %%~nF &rem expands %%F to a file name only
rem echo ? %%~xF &rem expands %%F to a file extension only
rem echo ? %%~sF &rem expanded path contains short names only
rem echo ? %%~aF &rem expands %%F to file attributes of file
rem echo ? %%~tF &rem expands %%F to date/time of file
rem echo ? %%~zF &rem expands %%F to size of file
rem echo ? %%~dpF &rem expands %%F to a drive letter and path only
rem echo ? %%~nxF &rem expands %%F to a file name and extension only
rem echo ? %%~fsF &rem expands %%F to a full path name with short names only
rem echo ? %%~dp$dir:F &rem searches the directories listed in the 'dir' environment variable and expands %%F to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
rem echo ? %%~ftzaF &rem expands %%F to a DIR like output line
)
)
popd
)
)
echo/ & pause & cls
Your code below is zooming the map to fit the specified bounds:
addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);
If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
}
If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.
If you will only ever have one marker, don't use fitBounds. Call setCenter
, setZoom
with the marker position and your desired zoom level.
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(your desired zoom);
}
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
_x000D_
<html>
<head>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(5);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
addMarker(27.703402, 85.311668, 'New Road');
// center = bounds.getCenter();
// map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
_x000D_
directly from this java oracle tutorial:
When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.
You can create a plethora of different chart types relatively quickly with loads of customizable options.
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
path = path.replace("\\", "/");
// or
path = path.replaceAll("\\\\", "/");
Find more details in the Docs
Use Compressor (Image compression library). Visit zetbaitsu/Compressor for code and documentation.
add dependency in gradle (app level)
dependencies {
implementation 'id.zelory:compressor:3.0.0'
}
To Compress Image use one of these approaches:
Compress Image File:
val compressedImageFile = Compressor.compress(context, actualImageFile)
Compress Image File to Bitmap:
val compressedImageFile = Compressor.compress(context, actualImageFile)
val bitmap = BitmapFactory.decodeFile(compressedImageFile.path)
Solution for IE8 and newer...
Issues worth noting:
Using background-color
to mask a border might not be the best solution. If you have a complex (or unknown) background color (or image), masking will ultimately fail. Also, if you resize the text, you'll notice that white background color (or whatever you set) will start covering up the text on the line above (or below).
You also don't want to "guesstimate" how wide the the sections are either, because it makes the styles very inflexible and almost impossible to implement on a responsive site where the width of the content is changing.
Solution:
(View JSFiddle)
Instead of "masking" a border with a background-color
, use your display
property.
HTML
<div class="group">
<div class="item line"></div>
<div class="item text">This is a test</div>
<div class="item line"></div>
</div>
CSS
.group { display: table; width: 100%; }
.item { display: table-cell; }
.text { white-space: nowrap; width: 1%; padding: 0 10px; }
.line { border-bottom: 1px solid #000; position: relative; top: -.5em; }
Resize your text by placing your font-size
property on the .group
element.
Limitations:
top
property on .line
element needs to be half of line-height
. So, if you have a line-height
of 1.5em
, then the top
should be -.75em
. This is a limitation because it's not automated, and if you are applying these styles on elements with different line-heights, then you might need to reapply your line-height
style.For me, these limitations outweigh the "issues" I noted at the beginning of my answer for most implementations.
In Swift 4 and 5. I created a closure variable containing two parameter dictionary and bool.
var completionHandler:([String:Any], Bool)->Void = { dict, success in
if success {
print(dict)
}
}
Calling the closure variable
self.completionHandler(["name":"Gurjinder singh"],true)
I use PLAY JSON library you can find the mavn repo for only the JSON library not the whole framework here
val json = "com.typesafe.play" %% "play-json" % version
val typesafe = "typesafe.com" at "http://repo.typesafe.com/typesafe/releases/"
A very good tutorials about how to use them, are available here:
http://mandubian.com/2012/09/08/unveiling-play-2-dot-1-json-api-part1-jspath-reads-combinators/
http://mandubian.com/2012/10/01/unveiling-play-2-dot-1-json-api-part2-writes-format-combinators/
http://mandubian.com/2012/10/29/unveiling-play-2-dot-1-json-api-part3-json-transformers/
I had the same issue today on windows 32 bit,with node 0.10.25, and grunt 0.4.5.
I followed dongho's answer, with just few extra steps. here are the steps I used to solve the error:
1) create your package.json
$ npm init
2) install grunt for this project, this will be installed under node_modules/. --save-dev will add this module to devDependency in your package.json
$ npm install grunt --save-dev
3) then create gruntfile.js
, with a sample code like this:
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
globals: {
jQuery: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['jshint']);
};
here, src/**/*.js
and test/**/*.js
should be the paths to actual JS files you are using in your project
4) run npm install grunt-contrib-jshint --save-dev
5) run npm install grunt-contrib-watch --save-dev
6) run $ grunt
Note: when you require common package like concat, uglify etc, you need to add those modules via npm install
, just the way we installed jshint and watch in step 4 & 5
If you use maven, create a directory called resources
in the main directory, and then copy your applicationContext.xml
into it.
From your java code call:
ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
You can try below solution inside some class:
int[] a = {10, 20, 30, 40, 50, 61};
// private visibility - or change it as needed
private void resizeArray(int newLength) {
a = Arrays.copyOf(a, a.length + newLength);
System.out.println("New length: " + a.length);
}
You have to create a crt bundle then it will be fine. You will be receiving three crt files. Use them all! If you only used the domain.crt then there will be warning on android but not on PC.
I am on nginx. I opened domain_name.crt and then opened positivesslca2.crt, select all and copy to the end of domain_name.crt. Then open AddTrustExternalCARoot.crt, copy to the end of domain_name.crt again. Then install the domain_name.crt
works good.
The tibble
package now has a dedicated function that converts row names to an explicit variable.
library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head
Gives:
das_Auto mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
I solved this issue with right click on project -> Set as Main Project.
That would only happen if PostCode
is missing a space.
You could add conditionality such that all of PostCode
is retrieved should a space not be found as follows
select SUBSTRING(PostCode, 1 ,
case when CHARINDEX(' ', PostCode ) = 0 then LEN(PostCode)
else CHARINDEX(' ', PostCode) -1 end)
As c-smile mentioned: Just need to remove the apostrophes in the url()
:
<div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div>
A simple formula to use is
=COUNTIF($B:$B,A1)
Formula specified is for cell A1. Simply copy and paste special - format to the whole of column A
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
To change the remote upstream:
git remote set-url origin <url>
To add more upstreams:
git remote add newplace <url>
So you can choose where to work
git push origin <branch>
or git push newplace <branch>
Try to not use setInterval
.
You can resend request to server after successful response with timeout.
jQuery:
sendRequest(); //call function
function sendRequest(){
$.ajax({
url: "test.php",
success:
function(result){
$('#links').text(result); //insert text of test.php into your div
setTimeout(function(){
sendRequest(); //this will send request again and again;
}, 5000);
}
});
}
According to Ruskins answer and the comments here I came up with the following (recursive) solution:
public static T GetParentOfType<T>(this Control control) where T : class
{
if (control?.Parent == null)
return null;
if (control.Parent is T parent)
return parent;
return GetParentOfType<T>(control.Parent);
}
A solution improving on the great one from @sparrow.
Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.
Let's suppose you want to call your new column simply, new_column
First make the list into a Series:
column_values = pd.Series(mylist)
Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column. In the following example we will position the new column in the first position from left (by setting loc=0)
df.insert(loc=0, column='new_column', value=column_values)
You could use
Calendar cal = Calendar.getInstance();
cal.setTime(beginupd);
long millis = cal.getTimeInMillis();
Multi-line string literals in vb.net using the XElement class.
Imports System.Xml.Linq
Public Sub Test()
dim sOderBy as string = ""
dim xe as XElement = <SQL>
SELECT * FROM <%= sTableName %>
<ORDER_BY> ORDER BY <%= sOrderBy %></ORDER_BY>
</SQL>
'** conditionally remove a section
if sOrderBy.Length = 0 then xe.<ORDER BY>.Remove
'** convert XElement value to a string
dim sSQL as String = xe.Value
End Sub
In iOS 6, the
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
is deprecated.
Use following code instead
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}
For iOS 6~8, the above method is still necessary, but you have to handle authorization.
_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
//[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
) {
// Will open an confirm dialog to get user's approval
[_locationManager requestWhenInUseAuthorization];
//[_locationManager requestAlwaysAuthorization];
} else {
[_locationManager startUpdatingLocation]; //Will update location immediately
}
This is the delegate method which handle user's authorization
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined: {
NSLog(@"User still thinking..");
} break;
case kCLAuthorizationStatusDenied: {
NSLog(@"User hates you");
} break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways: {
[_locationManager startUpdatingLocation]; //Will update location immediately
} break;
default:
break;
}
}
I was using nodemailer npm module. The below code solved the issue
tls: {
// do not fail on invalid certs
rejectUnauthorized: false
}
I think you should be able to follow the method used in this post. It looks really ugly, but I would think you could do it twice and get the result you want.
I wonder if this is actually a case where you'd be better off using DataContext.ExecuteCommand(...)
instead of converting to linq.
I've written a Visual Studio Code extension for changing case (not only upper case, many other options): https://github.com/wmaurer/vscode-change-case
To map the upper case command to a keybinding (e.g. Ctrl+T U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:
{
"key": "ctrl+t u",
"command": "extension.changeCase.upper",
"when": "editorTextFocus"
}
EDIT:
With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase
and editor.action.transformToLowercase
. These don't have default keybindings.
The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake-case, etc.
Use find to located it. It should be under /usr
somewhere:
find /usr -name java
When running the command, if there are too many "Permission denied" message obfuscating the actual found results then, simply redirect stderr to /dev/null
find /usr -name java 2> /dev/null
You have to add the size of the legend box to the ylim range
#Plot an empty graph and legend to get the size of the legend
x <-1:10
y <-11:20
plot(x,y,type="n", xaxt="n", yaxt="n")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"),plot = FALSE)
#custom ylim. Add the height of legend to upper bound of the range
my.range <- range(y)
my.range[2] <- 1.04*(my.range[2]+my.legend.size$rect$h)
#draw the plot with custom ylim
plot(x,y,ylim=my.range, type="l")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"))
Check if you are returning a @ResponseBody or a @ResponseStatus
I had a similar problem. My Controller looked like that:
@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
When calling with a POST request I always got the following error:
HTTP Status 405 - Request method 'POST' not supported
After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.
To fix this simply add a @ResponseBody
@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
or a @ResponseStatus to your method.
@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.
Here is an example with a Django view ...
def homepage(request):
request.session.setdefault('how_many_visits', 0)
request.session['how_many_visits'] += 1
print(request.session['how_many_visits'])
return render(request, 'home.html', {})
If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.
JSDoc 3 allows you to annotate your functions with the @access private
(previously the @private
tag) which is also useful for broadcasting your intent to other developers - http://usejsdoc.org/tags-access.html
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
It is because the Creation was delayed. If you want the picture to be loaded immediately, you can simply add this code into the init phase.
src.CacheOption = BitmapCacheOption.OnLoad;
like this:
src.BeginInit();
src.UriSource = new Uri("picture.jpg", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
Try GetElementsByTagName method of XMLDocument class to read specific data or LoadXml method to read all data to xml document.
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
Find Styles.xml in Values.(res/Values/Styles.xml) Change this
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to this:
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
Then clean and build project. Both of those you can do from build menu.
It worked for me.
Extending on Tadeck's Django answer above, the use of 'class Meta:' in Django is just normal Python too.
The internal class is a convenient namespace for shared data among the class instances (hence the name Meta for 'metadata' but you can call it anything you like). While in Django it's generally read-only configuration stuff, there is nothing to stop you changing it:
In [1]: class Foo(object):
...: class Meta:
...: metaVal = 1
...:
In [2]: f1 = Foo()
In [3]: f2 = Foo()
In [4]: f1.Meta.metaVal
Out[4]: 1
In [5]: f2.Meta.metaVal = 2
In [6]: f1.Meta.metaVal
Out[6]: 2
In [7]: Foo.Meta.metaVal
Out[7]: 2
You can explore it in Django directly too e.g:
In [1]: from django.contrib.auth.models import User
In [2]: User.Meta
Out[2]: django.contrib.auth.models.Meta
In [3]: User.Meta.__dict__
Out[3]:
{'__doc__': None,
'__module__': 'django.contrib.auth.models',
'abstract': False,
'verbose_name': <django.utils.functional.__proxy__ at 0x26a6610>,
'verbose_name_plural': <django.utils.functional.__proxy__ at 0x26a6650>}
However, in Django you are more likely to want to explore the _meta
attribute which is an Options
object created by the model metaclass
when a model is created. That is where you'll find all of the Django class 'meta' information. In Django, Meta
is just used to pass information into the process of creating the _meta
Options
object.
Making @sulai suggestion more generic :
@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
asyncTask.execute(params);
}