Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?
As a generic answer, not specifically directed at this task: In many cases, you can significantly speed up any program by making improvements at a high level. Like calculating data once instead of multiple times, avoiding unnecessary work completely, using caches in the best way, and so on. These things are much easier to do in a high level language.
Writing assembler code, it is possible to improve on what an optimising compiler does, but it is hard work. And once it's done, your code is much harder to modify, so it is much more difficult to add algorithmic improvements. Sometimes the processor has functionality that you cannot use from a high level language, inline assembly is often useful in these cases and still lets you use a high level language.
In the Euler problems, most of the time you succeed by building something, finding why it is slow, building something better, finding why it is slow, and so on and so on. That is very, very hard using assembler. A better algorithm at half the possible speed will usually beat a worse algorithm at full speed, and getting the full speed in assembler isn't trivial.
Command failed due to signal: Segmentation fault: 11
In my case, IGListKit refactored their class named IGListSectionController to ListSectionController , while I already had a class named ListSectionController. I used find and replace and didn't know I had a class with the same name.
class ListSectionController : ListSectionController
I read the error message in full and concluded that this error can also happen when you have Circular dependencies. This wasn't mentioned in any of the comments, I hope this helps.
Not receiving Google OAuth refresh token
Adding access_type=offline
to the authorisation Google authorisation URL did the trick for me. I am using Java and Spring framework.
This is the code that creates the client registration:
return CommonOAuth2Provider.GOOGLE
.getBuilder(client)
.scope("openid", "profile", "email", "https://www.googleapis.com/auth/gmail.send")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth?access_type=offline")
.clientId(clientId)
.redirectUriTemplate("{baseUrl}/{action}/oauth2/code/{registrationId}")
.clientSecret(clientSecret)
.build();
The important part here is the authorization URI, to which ?access_type=offline
is appended.
Getting windbg without the whole WDK?
Actually, Microsoft has now made the Debugging Tools downloadable separately from the SDK. Look for the section "Standalone Debugging Tools for Windows (WinDbg)" about mid-page:
"Could not find or load main class" Error while running java program using cmd prompt
One reason for this error might be
Could not find or load main class <class name>
Maybe you use your class name as different name and save the class name with another name you can save a java source file name by another name than class name. For example:
class A{
public static void main(String args[]) {
System.out.println("Hello world");
}
}
you can save as Hello.java
but,
To Compile : javac Hello.java
This will auto generate A.class file at same location.
Now To Run : java A
npm WARN package.json: No repository field
It's just a check as of NPM v1.2.20, they report this as a warning.
However, don't worry, there are sooooooo many packages which still don't have the repository
field in their package.json
. The field is used for informational purposes.
In the case you're a package author, put the repository
in your package.json
, like this:
"repository": {
"type": "git",
"url": "git://github.com/username/repository.git"
}
Read more about the repository
field, and see the logged bug for further details.
Additionally, as originally reported by @dan_nl, you can set private
key in your package.json
.
This will not only stop you from accidentally running npm publish
in your app, but will also stop NPM from printing warnings regarding package.json
problems.
{
"name": "my-super-amazing-app",
"version": "1.0.0",
"private": true
}
How to Fill an array from user input C#?
C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.
If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:
using Microsoft.VisualBasic;
You can do the following:
List<string> responses = new List<string>();
string response = "";
while(!(response = Interaction.InputBox("Please enter your information",
"Window Title",
"Default Text",
xPosition,
yPosition)).equals(""))
{
responses.Add(response);
}
responses.ToArray();
Specifying Font and Size in HTML table
Enclose your code with the html and body tags. Size attribute does not correspond to font-size and it looks like its domain does not go beyond value 7. Furthermore font tag is not supported in HTML5.
Consider this code for your case
<!DOCTYPE html>
<html>
<body>
<font size="2" face="Courier New" >
<table width="100%">
<tr>
<td><b>Client</b></td>
<td><b>InstanceName</b></td>
<td><b>dbname</b></td>
<td><b>Filename</b></td>
<td><b>KeyName</b></td>
<td><b>Rotation</b></td>
<td><b>Path</b></td>
</tr>
<tr>
<td>NEWDEV6</td>
<td>EXPRESS2012</td>
<td>master</td><td>master.mdf</td>
<td>test_key_16</td><td>0</td>
<td>d:\Program Files\Microsoft SQL Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td>
</tr>
</table>
</font>
<font size="5" face="Courier New" >
<table width="100%">
<tr>
<td><b>Client</b></td>
<td><b>InstanceName</b></td>
<td><b>dbname</b></td>
<td><b>Filename</b></td>
<td><b>KeyName</b></td>
<td><b>Rotation</b></td>
<td><b>Path</b></td></tr>
<tr>
<td>NEWDEV6</td>
<td>EXPRESS2012</td>
<td>master</td>
<td>master.mdf</td>
<td>test_key_16</td>
<td>0</td>
<td>d:\Program Files\Microsoft SQL Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td></tr>
</table></font>
</body>
</html>
Storing image in database directly or as base64 data?
Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.
Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.
How to start http-server locally
When you're running npm install
in the project's root, it installs all of the npm dependencies into the project's node_modules
directory.
If you take a look at the project's node_modules
directory, you should see a directory called http-server
, which holds the http-server
package, and a .bin
folder, which holds the executable binaries from the installed dependencies. The .bin
directory should have the http-server
binary (or a link to it).
So in your case, you should be able to start the http-server
by running the following from your project's root directory (instead of npm start
):
./node_modules/.bin/http-server -a localhost -p 8000 -c-1
This should have the same effect as running npm start
.
If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin
folder to your $PATH
environment variable:
export PATH=./node_modules/.bin:$PATH
This will put this folder on your path, and you should be able to simply run
http-server -a localhost -p 8000 -c-1
Content Type text/xml; charset=utf-8 was not supported by service
In my case, I had to specify messageEncoding to Mtom in app.config of the client application like that:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="IntegrationServiceSoap" messageEncoding="Mtom"/>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:29495/IntegrationService.asmx"
binding="basicHttpBinding" bindingConfiguration="IntegrationServiceSoap"
contract="IntegrationService.IntegrationServiceSoap" name="IntegrationServiceSoap" />
</client>
</system.serviceModel>
</configuration>
Both my client and server use basicHttpBinding.
I hope this helps the others :)
AngularJS: How to make angular load script inside ng-include?
The accepted answer won't work from 1.2.0-rc1+ (Github issue).
Here's a quick fix created by endorama:
/*global angular */
(function (ng) {
'use strict';
var app = ng.module('ngLoadScript', []);
app.directive('script', function() {
return {
restrict: 'E',
scope: false,
link: function(scope, elem, attr) {
if (attr.type === 'text/javascript-lazy') {
var code = elem.text();
var f = new Function(code);
f();
}
}
};
});
}(angular));
Simply add this file, load ngLoadScript
module as application dependency and use type="text/javascript-lazy"
as type for script you which to load lazily in partials:
<script type="text/javascript-lazy">
console.log("It works!");
</script>
Reason to Pass a Pointer by Reference in C++?
You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to.
This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
PL/SQL: numeric or value error: character string buffer too small
is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.
for example:
myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26
will fire such an error
Access Https Rest Service using Spring RestTemplate
Here is what I ended up with for the similar problem. The idea is the same as in @Avi's answer, but I also wanted to avoid the static "System.setProperty("https.protocols", "TLSv1");", so that any adjustments won't affect the system. Inspired by an answer from here http://www.coderanch.com/t/637177/Security/Disabling-handshake-message-Java
public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
try {
if (!(connection instanceof HttpsURLConnection)) {
throw new RuntimeException("An instance of HttpsURLConnection is expected");
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
httpsConnection.setHostnameVerifier((hostname, session) -> true);
super.prepareConnection(httpsConnection, httpMethod);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
/**
* We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
* see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
*/
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
this.delegate = delegate;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException {
final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
private Socket overrideProtocol(final Socket socket) {
if (!(socket instanceof SSLSocket)) {
throw new RuntimeException("An instance of SSLSocket is expected");
}
((SSLSocket) socket).setEnabledProtocols(new String[] {"SSLv3"});
return socket;
}
}
}
how to store Image as blob in Sqlite & how to retrieve it?
Here the code i used for my app
This code will take a image from url and convert is to a byte array
byte[] logoImage = getLogoImage(IMAGEURL);
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
To save the image to db i used this code.
public void insertUser(){
SQLiteDatabase db = dbHelper.getWritableDatabase();
String delSql = "DELETE FROM ACCOUNTS";
SQLiteStatement delStmt = db.compileStatement(delSql);
delStmt.execute();
String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
SQLiteStatement insertStmt = db.compileStatement(sql);
insertStmt.clearBindings();
insertStmt.bindString(1, Integer.toString(this.accId));
insertStmt.bindString(2,this.accName);
insertStmt.bindBlob(3, this.accImage);
insertStmt.executeInsert();
db.close();
}
To retrieve the image back this is code i used.
public Account getCurrentAccount() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
String sql = "SELECT * FROM ACCOUNTS";
Cursor cursor = db.rawQuery(sql, new String[] {});
if(cursor.moveToFirst()){
this.accId = cursor.getInt(0);
this.accName = cursor.getString(1);
this.accImage = cursor.getBlob(2);
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
if(cursor.getCount() == 0){
return null;
} else {
return this;
}
}
Finally to load this image to a imageview
logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage,
0,currentAccount.accImage.length));
MySQL - SELECT all columns WHERE one column is DISTINCT
Select the datecolumn of month so that u can get only one row per link, e.g.:
select link, min(datecolumn) from posted WHERE ad='$key' ORDER BY day, month
Good luck............
Or
u if you have date column as timestamp convert the format to date and perform distinct on link so that you can get distinct link values based on date instead datetime
composer laravel create project
No this step isn't equal to downloading the laravel.zip
by using the command
composer create-project laravel/laravel laravel
you actually download the laravel project as well as dependent packages so its one step ahead.
If you are using windows environment you can solve the problem by deleting the composer environment variable you created to install the composer. And this command will run properly.
Pandas: Convert Timestamp to datetime.date
You can convert a datetime.date object into a pandas Timestamp like this:
#!/usr/bin/env python3
# coding: utf-8
import pandas as pd
import datetime
# create a datetime data object
d_time = datetime.date(2010, 11, 12)
# create a pandas Timestamp object
t_stamp = pd.to_datetime('2010/11/12')
# cast `datetime_timestamp` as Timestamp object and compare
d_time2t_stamp = pd.to_datetime(d_time)
# print to double check
print(d_time)
print(t_stamp)
print(d_time2t_stamp)
# since the conversion succeds this prints `True`
print(d_time2t_stamp == t_stamp)
HTML5 Video not working in IE 11
I know this is old, but here is a additional thing if you still encounter problems with the solution above.
Just put in your <head>
:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
It will prevent IE to jump back to IE9 compatibility, thus breaking the video function.
Worked for me, so if you still have problems, consider checking this out.
Alternatively you can add this in PHP :
header('x-ua-compatible: ie=edge');
Or in a .htaccess file:
header set X-UA-Compatible "IE=Edge"
CSS @media print issues with background-color;
For chrome, I have used something like this and it worked out for me.
Within the body tag,
<body style="-webkit-print-color-adjust: exact;"> </body>
Or for a particular element, let's say if you have table and you want to fill a td i.e a cell,
<table><tr><td style="-webkit-print-color-adjust: exact;"></tr></table>
The point of test %eax %eax
You are right, that test
"and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test
instruction is used (and exist).
JE
jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF
flag is set. And as it is one of the flags that is set by test
, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.
For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.
Rails 3 execute custom sql query without a model
You could also use find_by_sql
# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
Converting 24 hour time to 12 hour time w/ AM & PM using Javascript
jQuery doesn't have any Date utilities at all. If you don't use any additional libraries, the usual way is to create a JavaScript Date
object and then extract the data from it and format it yourself.
For creating the Date
object you can either make sure that your date string in the JSON is in a form that Date
understands, which is IETF standard (which is basically RFC 822 section 5). So if you have the chance to change your JSON, that would be easiest. (EDIT: Your format may actually work the way it is.)
If you can't change your JSON, then you'll need to parse the string yourself and get day, mouth, year, hours, minutes and seconds as integers and create the Date
object with that.
Once you have your Date
object you'll need to extract the data you need and format it:
var myDate = new Date("4 Feb 2011, 19:00:00");
var hours = myDate.getHours();
var am = true;
if (hours > 12) {
am = false;
hours -= 12;
} else (hours == 12) {
am = false;
} else (hours == 0) {
hours = 12;
}
var minutes = myDate.getMinutes();
alert("It is " + hours + " " + (am ? "a.m." : "p.m.") + " and " + minutes + " minutes".);
Check if image exists on server using JavaScript?
If you are using React try this custom Image component:
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import defaultErrorImage from 'assets/images/default-placeholder-image.png';
const Image = ({ src, alt, className, onErrorImage }) => {
const imageEl = useRef(null);
return (
<img
src={src}
alt={alt}
className={className}
onError={() => {
imageEl.current.src = onErrorImage;
}}
ref={imageEl}
/>
);
};
Image.defaultProps = {
onErrorImage: defaultErrorImage,
};
Image.propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
className: PropTypes.string.isRequired,
onErrorImage: PropTypes.string,
};
export default Image;
Converting of Uri to String
You can use .toString
method to convert Uri to String in java
Uri uri = Uri.parse("Http://www.google.com");
String url = uri.toString();
This method convert Uri to String easily
How to open SharePoint files in Chrome/Firefox
Thanks to @LyphTEC that gave a very interesting way to open an Office file in edit mode!
It gave me the idea to change the function _DispEx
that is called when the user clicks on a file into a document library. By hacking the original function we can them be able to open a dialog (for Firefox/Chrome) and ask the user if he/she wants to readonly or edit the file:
See below the JavaScript code I used. My code is for Excel files, but it could be modified to work with Word documents too:
/**
* fix problem with Excel documents on Firefox/Chrome (see https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/)
* @param {HTMLElement} p the <A> element
* @param {HTMLEvent} a the click event
* @param {Boolean} h TRUE
* @param {Boolean} e FALSE
* @param {Boolean} g FALSE
* @param {Strin} k the ActiveX command (e.g. "SharePoint.OpenDocuments.3")
* @param {Number} c 0
* @param {String} o the activeX command, here we look at "SharePoint.OpenDocuments"
* @param {String} m
* @param {String} b the replacement URL to the xslviewer
*/
var bak_DispEx;
var modalOpenDocument; // it will be use with the modal
SP.SOD.executeOrDelayUntilEventNotified(function() {
bak_DispEx = _DispEx;
_DispEx=function(p, a, h, e, g, k, c, o, m, b, j, l, i, f, d) {
// if o==="SharePoint.OpenDocuments" && !IsClientAppInstalled(o)
// in that case we want to open ask the user if he/she wants to readonly or edit the file
var fileURL = b.replace(/.*_layouts\/xlviewer\.aspx\?id=(.*)/, "$1");
if (o === "SharePoint.OpenDocuments" && !IsClientAppInstalled(o) && /\.xlsx?$/.test(fileURL)) {
// if the URL doesn't start with http
if (!/^http/.test(fileURL)) {
fileURL = window.location.protocol + "//" + window.location.host + fileURL;
}
var ohtml = document.createElement('div');
ohtml.style.padding = "10px";
ohtml.style.display = "inline-block";
ohtml.style.width = "200px";
ohtml.style.width = "200px";
ohtml.innerHTML = '<style>'
+ '.opendocument_button { background-color:#fdfdfd; border:1px solid #ababab; color:#444; display:inline-block; padding: 7px 10px; }'
+ '.opendocument_button:hover { box-shadow: none }'
+ '#opendocument_readonly,#opendocument_edit { float:none; font-size: 100%; line-height: 1.15; margin: 0; overflow: visible; box-sizing: border-box; padding: 0; height:auto }'
+ '.opendocument_ul { list-style-type:none;margin-top:10px;margin-bottom:10px;padding-top:0;padding-bottom:0 }'
+ '</style>'
+ 'You are about to open:'
+ '<ul class="opendocument_ul">'
+ ' <li>Name: <b>'+fileURL.split("/").slice(-1)+'</b></li>'
+ ' <li>From: <b>'+window.location.hostname+'</b></li>'
+ '</ul>'
+ 'How would like to open this file?'
+ '<ul class="opendocument_ul">'
+ ' <li><label><input type="radio" name="opendocument_choices" id="opendocument_readonly" checked> Read Only</label></li>'
+ ' <li><label><input type="radio" name="opendocument_choices" id="opendocument_edit"> Edit</label></li>'
+ '</ul>'
+ '<div style="text-align: center;margin-top: 20px;"><button type="button" class="opendocument_button" style="background-color: #2d9f2d;color: #fff;" onclick="modalOpenDocument.close(document.getElementById(\'opendocument_edit\').checked)">Open</button> <button type="button" class="opendocument_button" style="margin-left:10px" onclick="modalOpenDocument.close(-1)">Cancel</button></div>';
// show the modal
modalOpenDocument=SP.UI.ModalDialog.showModalDialog({
html:ohtml,
dialogReturnValueCallback:function(ret) {
if (ret!==-1) {
if (ret === true) { // edit
// reformat the fileURL
var ext;
if (/\.xlsx?$/.test(b)) ext = "ms-excel";
if (/\.docx?$/.test(b)) ext = "ms-word"; // not currently supported
fileURL = ext + ":ofe|u|" + fileURL;
}
window.location.href = fileURL; // open the file
}
}
});
a.preventDefault();
a.stopImmediatePropagation()
a.cancelBubble = true;
a.returnValue = false;
return false;
}
return bak_DispEx.apply(this, arguments);
}
}, "sp.scriptloaded-core.js")
I use SP.SOD.executeOrDelayUntilEventNotified
to make sure the function will be executed when core.js
is loaded.
Cannot read property 'push' of undefined when combining arrays
Generally, Push method is used to add elements at the end of an array.
Here, you have used the push method to an object and not an array which is 'order'.
Steps to debug...
Change the object into an empty array,
var order = [], stack = [];
Now you can use the push method for this array as usual.
To use push method to this 'order' array; you should not use the array index when calling push method to an array. Just use the name of the array only.
var order = [], stack = [];
for(var i = 0; i<a.length; i++){
if(parseInt(a[i].daysleft) == 0){
order.push(a[i]);
}
if(parseInt(a[i].daysleft) > 0){
order.push(a[i]);
}
if(parseInt(a[i].daysleft) < 0){
order.push(a[i]);
}
}
$.ajax - dataType
contentType
is the HTTP header sent to the server, specifying a particular format.
Example: I'm sending JSON or XML
dataType
is you telling jQuery what kind of response to expect.
Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.
The $.ajax()
documentation has full descriptions of these as well.
In your particular case, the first is asking for the response to be in UTF-8
, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.
So the first would be:
success: function(data) {
// get data, e.g. data.title;
}
The second:
success: function(data) {
alert("Here's lots of data, just a string: " + data);
}
Bind TextBox on Enter-key press
Here is an approach that to me seems quite straightforward, and easier that adding an AttachedBehaviour (which is also a valid solution). We use the default UpdateSourceTrigger (LostFocus for TextBox), and then add an InputBinding to the Enter Key, bound to a command.
The xaml is as follows
<TextBox Grid.Row="0" Text="{Binding Txt1}" Height="30" Width="150">
<TextBox.InputBindings>
<KeyBinding Gesture="Enter"
Command="{Binding UpdateText1Command}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type TextBox}},Path=Text}" />
</TextBox.InputBindings>
</TextBox>
Then the Command methods are
Private Function CanExecuteUpdateText1(ByVal param As Object) As Boolean
Return True
End Function
Private Sub ExecuteUpdateText1(ByVal param As Object)
If TypeOf param Is String Then
Txt1 = CType(param, String)
End If
End Sub
And the TextBox is bound to the Property
Public Property Txt1 As String
Get
Return _txt1
End Get
Set(value As String)
_txt1 = value
OnPropertyChanged("Txt1")
End Set
End Property
So far this seems to work well and catches the Enter Key event in the TextBox.
Python: Get the first character of the first string in a list?
You almost had it right. The simplest way is
mylist[0][0] # get the first character from the first item in the list
but
mylist[0][:1] # get up to the first character in the first item in the list
would also work.
You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.
XML element with attribute and content using JAXB
The correct scheme should be:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport"
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<complexType name="sportType">
<simpleContent>
<extension base="string">
<attribute name="type" type="string" />
<attribute name="gender" type="string" />
</extension>
</simpleContent>
</complexType>
<element name="sports">
<complexType>
<sequence>
<element name="sport" minOccurs="0" maxOccurs="unbounded"
type="tns:sportType" />
</sequence>
</complexType>
</element>
Code generated for SportType will be:
package org.example.sport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
@XmlValue
protected String value;
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
public String getGender() {
return gender;
}
public void setGender(String value) {
this.gender = value;
}
}
get enum name from enum value
What you can do is
RelationActiveEnum ae = Enum.valueOf(RelationActiveEnum.class,
RelationActiveEnum.ACTIVE.name();
or
RelationActiveEnum ae = RelationActiveEnum.valueOf(
RelationActiveEnum.ACTIVE.name();
or
// not recommended as the ordinal might not match the value
RelationActiveEnum ae = RelationActiveEnum.values()[
RelationActiveEnum.ACTIVE.value];
By if you want to lookup by a field of an enum you need to construct a collection such as a List, an array or a Map.
public enum RelationActiveEnum {
Invited(0),
Active(1),
Suspended(2);
private final int code;
private RelationActiveEnum(final int code) {
this.code = code;
}
private static final Map<Integer, RelationActiveEnum> BY_CODE_MAP = new LinkedHashMap<>();
static {
for (RelationActiveEnum rae : RelationActiveEnum.values()) {
BY_CODE_MAP.put(rae.code, rae);
}
}
public static RelationActiveEnum forCode(int code) {
return BY_CODE_MAP.get(code);
}
}
allows you to write
String name = RelationActiveEnum.forCode(RelationActiveEnum.ACTIVE.code).name();
How to play a local video with Swift?
PlayerView for swift 4.2
import AVFoundation
import UIKit
class PlayerView: UIView {
var player: AVPlayer? {
get {
return playerLayer.player
}
set {
playerLayer.player = newValue
}
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
// Override UIView property
override static var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
NotificationCenter issue on Swift 3
For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:
// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
class MyReceivingClass {
// ---------------------------------------------
// INIT -> GOOD PLACE FOR REGISTERING
// ---------------------------------------------
init() {
// WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)
// Register without parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)
// Register WITH parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
}
// ---------------------------------------------
// DE-INIT -> LAST OPTION FOR RE-REGISTERING
// ---------------------------------------------
deinit {
NotificationCenter.default.removeObserver(self)
}
// either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'
// ---------------------------------------------
// HANDLE NOTIFICATION WITHOUT PARAMETER
// ---------------------------------------------
@objc func handleNotification() {
print("RECEIVED ANY NOTIFICATION")
}
// ---------------------------------------------
// HANDLE NOTIFICATION WITH PARAMETER
// ---------------------------------------------
@objc func handle(withNotification notification : NSNotification) {
print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
}
}
In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):
// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
print("POSTING")
// Define identifiyer
let notificationName = Notification.Name.UIApplicationWillResignActive
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
}
Export Postgresql table data using pgAdmin
- Right-click on your table and pick option
Backup
..
- On File Options, set Filepath/Filename and pick
PLAIN
for Format
- Ignore Dump Options #1 tab
- In Dump Options #2 tab, check
USE INSERT COMMANDS
- In Dump Options #2 tab, check
Use Column Inserts
if you want column names in your inserts.
- Hit
Backup
button
Compare two Timestamp in java
You can sort Timestamp as follows:
public int compare(Timestamp t1, Timestamp t2) {
long l1 = t1.getTime();
long l2 = t2.getTime();
if (l2 > l1)
return 1;
else if (l1 > l2)
return -1;
else
return 0;
}
Keyboard shortcut to comment lines in Sublime Text 2
For German keyboards use ctrl+shift+# to toggle a block comment and ctrl+# to toggle a line comment.
The shortcut in Preferences->Key Bindings - Default
is set to Ctrl+Shift+/ and Ctrl+/, but to actually use the functions, press the keys stated above.
SoapFault exception: Could not connect to host
In my case the host requires TLS 1.2 so needed to enforce using the crypto_method ssl param.
$client = new SoapClient($wsdl,
array(
'location' => $location,
'keep_alive' => false,
"stream_context" => stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
]
]),
'trace' => 1, // used for debug
)
);
How do you create optional arguments in php?
The default value of the argument must be a constant expression. It can't be a variable or a function call.
If you need this functionality however:
function foo($foo, $bar = false)
{
if(!$bar)
{
$bar = $foo;
}
}
Assuming $bar
isn't expected to be a boolean of course.
var.replace is not a function
probable issues:
- variable is NUMBER (instead of string);
num=35; num.replace(3,'three'); =====> ERROR
num=35; num.toString().replace(3,'three'); =====> CORRECT !!!!!!
num='35'; num.replace(3,'three'); =====> CORRECT !!!!!!
- variable is object (instead of string);
- variable is not defined;
Updating to latest version of CocoaPods?
If you got System Integrity Protection enabled or any other permission write error, which is enabled by default since macOS Sierra release, you should update CocoaPods, running this line in terminal:
sudo gem install cocoapods -n/usr/local/bin
After installing, check your pod version:
pod --version
You will get rid of this error:
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /usr/bin directory
And it will install latest CocoaPods:
Successfully installed cocoapods-x.x.x
Parsing documentation for cocoapods-x.x.x
Installing ri documentation for cocoapods-x.x.x
Done installing documentation for cocoapods after 4 seconds
1 gem installed
How to make layout with View fill the remaining space?
you can use high layout_weight attribute. Below you can see a layout where ListView takes all free space with buttons at bottom:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".ConfigurationActivity"
android:orientation="vertical"
>
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1000"
/>
<Button
android:id="@+id/btnCreateNewRule"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Create New Rule" />
<Button
android:id="@+id/btnConfigureOk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Ok" />
</LinearLayout>
Debugging Spring configuration
Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this
<category name="org.springframework.beans">
<priority value="debug" />
</category>
or
<category name="org.springframework">
<priority value="debug" />
</category>
I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest
{
@Autowired
private SpringDAO dao;
@Autowired
private ApplicationContext appContext;
@Test
public void checkConfig()
{
AnySpringBean bean = appContext.getBean(AnySpringBean.class);
Assert.assertNotNull(bean);
}
}
UPDATE
I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
UPDATE log4j config file
I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
</layout>
</appender>
<appender name="springAppender" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="C:/tomcatLogs/webApp/spring-details.log" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" />
</layout>
</appender>
<category name="org.springframework">
<priority value="debug" />
</category>
<category name="org.springframework.beans">
<priority value="debug" />
</category>
<category name="org.springframework.security">
<priority value="debug" />
</category>
<category
name="org.springframework.beans.CachedIntrospectionResults">
<priority value="debug" />
</category>
<category name="org.springframework.jdbc.core">
<priority value="debug" />
</category>
<category name="org.springframework.transaction.support.TransactionSynchronizationManager">
<priority value="debug" />
</category>
<root>
<priority value="debug" />
<appender-ref ref="springAppender" />
<!-- <appender-ref ref="STDOUT"/> -->
</root>
</log4j:configuration>
Get value (String) of ArrayList<ArrayList<String>>(); in Java
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething
is updated as well sonce both reference the same object, so when you access the second element myList.get(1)
(which does not exist anymore) you get the null.
Notice both collection.Add(listOfSomething);
save two references to the same arraylist object.
You need to create two different instances for two elements:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");
ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");
collection.Add(listOfSomething1);
collection.Add(listOfSomething2);
CSS class for pointer cursor
I don't have enough reputation to comment on the relevant answers, but to people reading this; adding .btn does not just add the pointer cursor but adds a lot of other styling as well. Which is great if it's a button and you want the bootstap button styling, but in other cases it would mess a lot up for other elements.
The best thing you can do, like Hari Das suggested, and which I also always do, is to add the following css:
.cursor-pointer {
cursor: pointer;
}
After which you can add it to any element
<div class="cursor-pointer"> .. </div>
Kubernetes service external ip pending
If you are not using GCE or EKS (you used kubeadm
) you can add an externalIPs
spec to your service YAML. You can use the IP associated with your node's primary interface such as eth0
. You can then access the service externally, using the external IP of the node.
...
spec:
type: LoadBalancer
externalIPs:
- 192.168.0.10
Difference between Java SE/EE/ME?
As I come across this question, I found the information provided on the Oracle's tutorial very complete and worth to share:
The Java Programming Language Platforms
There are four platforms of the Java programming language:
Java Platform, Standard Edition (Java SE)
Java Platform, Enterprise Edition (Java EE)
Java Platform, Micro Edition (Java ME)
JavaFX
All Java platforms consist of a Java Virtual Machine (VM) and an
application programming interface (API). The Java Virtual Machine is a
program, for a particular hardware and software platform, that runs
Java technology applications. An API is a collection of software
components that you can use to create other software components or
applications. Each Java platform provides a virtual machine and an
API, and this allows applications written for that platform to run on
any compatible system with all the advantages of the Java programming
language: platform-independence, power, stability,
ease-of-development, and security.
Java SE
When most people think of the Java programming language, they think of
the Java SE API. Java SE's API provides the core functionality of the
Java programming language. It defines everything from the basic types
and objects of the Java programming language to high-level classes
that are used for networking, security, database access, graphical
user interface (GUI) development, and XML parsing.
In addition to the core API, the Java SE platform consists of a
virtual machine, development tools, deployment technologies, and other
class libraries and toolkits commonly used in Java technology
applications.
Java EE
The Java EE platform is built on top of the Java SE platform. The Java
EE platform provides an API and runtime environment for developing and
running large-scale, multi-tiered, scalable, reliable, and secure
network applications.
Java ME
The Java ME platform provides an API and a small-footprint virtual
machine for running Java programming language applications on small
devices, like mobile phones. The API is a subset of the Java SE API,
along with special class libraries useful for small device application
development. Java ME applications are often clients of Java EE
platform services.
JavaFX
JavaFX is a platform for creating rich internet applications using a
lightweight user-interface API. JavaFX applications use
hardware-accelerated graphics and media engines to take advantage of
higher-performance clients and a modern look-and-feel as well as
high-level APIs for connecting to networked data sources. JavaFX
applications may be clients of Java EE platform services.
React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function
React components (both functional as well as class) must begin with a capital letter. Like
const App=(props)=><div>Hey</div>
class App extends React.Component{
render(){
return <div>Hey</div>
}
}
React identifies user-defined components by following this semantic. React's JSX transpiles to React.createElement function which returns an object representation of the dom node. The type property of this object tells whether it is a user-defined component or a dom element like div. Therefore it is important to follow this semantics
Since useState hook can only be used inside the functional component(or a custom hook) this is the reason why you are getting the error because react is not able to identify it as a user-defined component in the first place.
useState can also be used inside the custom hooks which is used for the reusability and the abstraction of logic. So according to the rules of hooks, the name of a custom hook must begin with a "use" prefix and must be in a camelCase
How do you discover model attributes in Rails?
For Schema related stuff
Model.column_names
Model.columns_hash
Model.columns
For instance variables/attributes in an AR object
object.attribute_names
object.attribute_present?
object.attributes
For instance methods without inheritance from super class
Model.instance_methods(false)
How to save password when using Subversion from the console
I'm using the TortoiseSVN client on Windows, and for me, setting store-passwords parameter as yes in %USERPROFILE%\AppData\Roaming\Subversion\config
does not help to store the password.
The password was successfully saved after removing this folder (just in case renaming):
%USERPROFILE%\AppData\Roaming\Subversion\auth
Environment:
Windows 7, TortoiseSVN 1.7.11 (Build 23600 - 64 bit, 2012-12-12T19:08:52), Subversion 1.7.8.
Underline text in UIlabel
Based on Kovpas & Damien Praca's Answers, here is an implementation of UILabelUnderligned which also support textAlignemnt.
#import <UIKit/UIKit.h>
@interface UILabelUnderlined : UILabel
@end
and the implementation:
#import "UILabelUnderlined.h"
@implementation DKUILabel
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);
CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA
CGContextSetLineWidth(ctx, 1.0f);
CGSize textSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];
// handle textAlignement
int alignementXOffset = 0;
switch (self.textAlignment) {
case UITextAlignmentLeft:
break;
case UITextAlignmentCenter:
alignementXOffset = (self.frame.size.width - textSize.width)/2;
break;
case UITextAlignmentRight:
alignementXOffset = self.frame.size.width - textSize.width;
break;
}
CGContextMoveToPoint(ctx, alignementXOffset, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, alignementXOffset+textSize.width, self.bounds.size.height - 1);
CGContextStrokePath(ctx);
[super drawRect:rect];
}
@end
How to add property to object in PHP >= 5.3 strict mode without generating error
If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass
objects (I believe) is when you cast an array as an object or when you create a new stdClass
object from scratch (and of course when you json_decode()
something - silly me for forgetting!).
Instead of:
$foo = new StdClass();
$foo->bar = '1234';
You'd do:
$foo = array('bar' => '1234');
$foo = (object)$foo;
Or if you already had an existing stdClass object:
$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;
Also as a 1 liner:
$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );
How to display pdf in php
if(isset($_GET['content'])){
$content = $_GET['content'];
$dir = $_GET['dir'];
header("Content-type:".$content);
@readfile($dir);
}
$directory = (file_exists("mydir/"))?"mydir/":die("file/directory doesn't exists");// checks directory if existing.
//the line above is just a one-line if statement (syntax: (conditon)?code here if true : code if false; )
if($handle = opendir($directory)){ //opens directory if existing.
while ($file = readdir($handle)) { //assign each file with link <a> tag with GET params
echo '<a target="_blank" href="?content=application/pdf&dir='.$directory.'">'.$file.'</a>';
}
}
if you click the link a new window will appear with the pdf file
Jackson and generic type reference
This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.
In this case, tester method needs to have access to Class, and you can construct
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, Foo.class)
and then
List<Foo> list = mapper.readValue(new File("input.json"), type);
The server committed a protocol violation. Section=ResponseStatusLine ERROR
A likely cause of this problem is Web Proxy Auto Discovery Protocol (WPAD) configuration on the network. The HTTP request will be transparently sent off to a proxy that can send back a response that the client won't accept or is not configured to accept. Before hacking your code to bits, check that WPAD is not in play, particularly if this just "started happening" out of the blue.
Whitespaces in java
boolean whitespaceSearchRegExp(String input) {
return java.util.regex.Pattern.compile("\\s").matcher(input).find();
}
SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?
Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:
Delivery -> Package (One -> Many)
CREATE TABLE Delivery(
Id INT IDENTITY PRIMARY KEY,
NoteNumber NVARCHAR(255) NOT NULL
)
CREATE TABLE Package(
Id INT IDENTITY PRIMARY KEY,
Status INT NOT NULL DEFAULT 0,
Delivery_Id INT NOT NULL,
CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)
The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).
So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.
Drop Down Menu/Text Field in one
I found this question and discussion very helpful and wanted to show the solution I ended up with. It is based on the answer given by @DevangRathod, but I used jQuery and made a couple tweaks to it, so wanted to show a fully commented sample to help anyone else working on something similar. I originally had been using the HTML5 data-list element, but was dissatisfied with that solution since it removes options from the drop down list that don't match text typed in the box. In my application, I wanted the full list to always be available.
Fully functional demo here: https://jsfiddle.net/abru77mm/
HTML:
<!--
Most style elements I left to the CSS file, but some are here.
Reason being that I am actually calculating my width dynamically
in my application so when I dynamically formulate this HTML, I
want the width and all the factors (such as padding and border
width and margin) that go into determining the proper widths to
be controlled by one piece of code, so those pieces are done in
the in-line style. Otherwise I leave the styling to the CSS file.
-->
<div class="data-list-input" style="width:190px;">
<select class="data-list-input" style="width:190px;">
<option value=""><Free Form Text></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<!-- Note that though the select/option allows for a different
display and internal value, there is no such distinction in the
text box, so for all the options (except the "none" option) the
value and content of the option should be identical. -->
</select>
<input class="data-list-input" style="width:160px;padding:4px 6px;border-width:1px;margin:0;" type="text" name="sex" required="required" value="">
</div>
JS:
jQuery(function() {
//keep the focus on the input box so that the highlighting
//I'm using doesn't give away the hidden select box to the user
$('select.data-list-input').focus(function() {
$(this).siblings('input.data-list-input').focus();
});
//when selecting from the select box, put the value in the input box
$('select.data-list-input').change(function() {
$(this).siblings('input.data-list-input').val($(this).val());
});
//When editing the input box, reset the select box setting to "free
//form input". This is important to do so that you can reselect the
//option you had selected if you want to.
$('input.data-list-input').change(function() {
$(this).siblings('select.data-list-input').val('');
});
});
CSS:
div.data-list-input
{
position: relative;
height: 20px;
display: inline-flex;
padding: 5px 0 5px 0;
}
select.data-list-input
{
position: absolute;
top: 5px;
left: 0px;
height: 20px;
}
input.data-list-input
{
position: absolute;
top: 0px;
left: 0px;
height: 20px;
}
Any comments for improvement on my implementation welcome. Hope someone finds this helpful.
how to return a char array from a function in C
Lazy notes in comments.
#include <stdio.h>
// for malloc
#include <stdlib.h>
// you need the prototype
char *substring(int i,int j,char *ch);
int main(void /* std compliance */)
{
int i=0,j=2;
char s[]="String";
char *test;
// s points to the first char, S
// *s "is" the first char, S
test=substring(i,j,s); // so s only is ok
// if test == NULL, failed, give up
printf("%s",test);
free(test); // you should free it
return 0;
}
char *substring(int i,int j,char *ch)
{
int k=0;
// avoid calc same things several time
int n = j-i+1;
char *ch1;
// you can omit casting - and sizeof(char) := 1
ch1=malloc(n*sizeof(char));
// if (!ch1) error...; return NULL;
// any kind of check missing:
// are i, j ok?
// is n > 0... ch[i] is "inside" the string?...
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return ch1;
}
Get first day of week in PHP?
A smart way of doing this is to let PHP handle timezone differences and Daylight Savings Time (DST). Let me show you how to do this.
This function will generate all days from Monday until Friday, inclusive (handy for generating work week days):
class DateTimeUtilities {
public static function getPeriodFromMondayUntilFriday($offset = 'now') {
$now = new \DateTimeImmutable($offset, new \DateTimeZone('UTC'));
$today = $now->setTime(0, 0, 1);
$daysFromMonday = $today->format('N') - 1;
$monday = $today->sub(new \DateInterval(sprintf('P%dD', $daysFromMonday)));
$saturday = $monday->add(new \DateInterval('P5D'));
return new \DatePeriod($monday, new \DateInterval('P1D'), $saturday);
}
}
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday() as $day) {
print $day->format('c');
print PHP_EOL;
}
This will return datetimes Monday-Friday for current week. To do the same for an arbitrary date, pass a date as a parameter to DateTimeUtilities ::getPeriodFromMondayUntilFriday
, thus:
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00') as $day) {
print $day->format('c');
print PHP_EOL;
}
//prints
//2017-01-02T00:00:01+00:00
//2017-01-03T00:00:01+00:00
//2017-01-04T00:00:01+00:00
//2017-01-05T00:00:01+00:00
//2017-01-06T00:00:01+00:00
Only interested in Monday, as the OP asked?
$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00
Laravel migration default value
In Laravel 6 you have to add 'change' to your migrations file as follows:
$table->enum('is_approved', array('0','1'))->default('0')->change();
jQuery Datepicker close datepicker after selected date
actually you don't need to replace this all....
there are 2 ways to do this. One is to use autoclose property, the other (alternativ) way is to use the on change property thats fired by the input when selecting a Date.
HTML
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
jQuery
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
this is all you have to do :)
HERE IS A FIDDLE to see whats happening.
Fiddleupdate on 13 of July 2016: CDN wasnt present anymore
According to your EDIT:
$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
Here you take the Input (that has no Close-Function) and create a Datepicker-Element. If the element changes you want to close it but you still try to close the Input (That has no close-function).
Binding a mouseup event to the document state may not be the best idea because you will fire all containing scripts on each click!
Thats it :)
EDIT: August 2017 (Added a StackOverFlowFiddle aka Snippet. Same as in Top of Post)
_x000D_
_x000D_
$(document).ready(function () {_x000D_
$('#example1').datepicker({_x000D_
format: "dd/mm/yyyy",_x000D_
autoclose: true_x000D_
});_x000D_
_x000D_
//Alternativ way_x000D_
$('#example2').datepicker({_x000D_
format: "dd/mm/yyyy"_x000D_
}).on('change', function(){_x000D_
$('.datepicker').hide();_x000D_
});_x000D_
});
_x000D_
.hero-unit{_x000D_
float: left;_x000D_
width: 210px;_x000D_
margin-right: 25px;_x000D_
}_x000D_
.hero-unit input{_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>_x000D_
<div class="container">_x000D_
<div class="hero-unit">_x000D_
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">_x000D_
</div>_x000D_
<div class="hero-unit">_x000D_
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
EDIT: December 2018 Obviously Bootstrap-Datepicker doesnt work with jQuery 3.x see this to fix
Argument list too long error for rm, cp, mv commands
I have faced a similar problem when there were millions of useless log files created by an application which filled up all inodes. I resorted to "locate", got all the files "located"d into a text file and then removed them one by one. Took a while but did the job!
Append String in Swift
Add this extension somewhere:
extension String {
mutating func addString(str: String) {
self = self + str
}
}
Then you can call it like:
var str1 = "hi"
var str2 = " my name is"
str1.addString(str2)
println(str1) //hi my name is
A lot of good Swift extensions like this are in my repo here, check them out: https://github.com/goktugyil/EZSwiftExtensions
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Angular JS POST request not sending JSON data
you can use your method by this way
var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();
$http({
url: '/api/apiControllerName/methodName',
method: 'POST',
params: {application:app, from:d1, to:d2},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
//timeout: 1,
//cache: false,
//transformRequest: false,
//transformResponse: false
}).then(function (results) {
return results;
}).catch(function (e) {
});
How to set background color in jquery
You can add your attribute on callback function ({key} , speed.callback,
like is
$('.usercontent').animate( {
backgroundColor:'#ddd',
},1000,function () {
$(this).css("backgroundColor","red")
});
Split by comma and strip whitespace in Python
I know this has already been answered, but if you end doing this a lot, regular expressions may be a better way to go:
>>> import re
>>> re.sub(r'\s', '', string).split(',')
['blah', 'lots', 'of', 'spaces', 'here']
The \s
matches any whitespace character, and we just replace it with an empty string ''
. You can find more info here: http://docs.python.org/library/re.html#re.sub
multiple where condition codeigniter
Try this
$data = array(
'email' =>$email,
'last_ip' => $last_ip
);
$where = array('username ' => $username , 'status ' => $status);
$this->db->where($where);
$this->db->update('table_user ', $data);
What does "<>" mean in Oracle
It means not equal to .
It's the same as != in C-like languages.
but <> is ISO Standard and
!= Not equal to (not ISO standard)
source command not found in sh shell
/bin/sh
is usually some other shell trying to mimic The Shell. Many distributions use /bin/bash
for sh
, it supports source
. On Ubuntu, though, /bin/dash
is used which does not support source
. Most shells use .
instead of source
. If you cannot edit the script, try to change the shell which runs it.
How to resize html canvas element?
This worked for me just now:
<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>
Multi-line string with extra space (preserved indentation)
Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like ex or cat
cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage
The string after <<
indicates where to stop.
To send these lines to a file, use:
cat > $FILE <<- EOM
Line 1.
Line 2.
EOM
You could also store these lines to a variable:
read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM
This stores the lines to the variable named VAR
.
When printing, remember the quotes around the variable otherwise you won't see the newline characters.
echo "$VAR"
Even better, you can use indentation to make it stand out more in your code. This time just add a -
after <<
to stop the tabs from appearing.
read -r -d '' VAR <<- EOM
This is line 1.
This is line 2.
Line 3.
EOM
But then you must use tabs, not spaces, for indentation in your code.
Spring @Autowired and @Qualifier
You can use @Qualifier
along with @Autowired
. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier
For Example in following case it is necessary provide a qualifier
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
EDIT:
In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
@RequiredArgsConstructor
public Payroll {
@Qualifier("employee") private final Person person;
}
provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):
# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
This was recently introduced in latest lombok 1.18.4.
NOTE
If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)
public Payroll {
@Autowired @Qualifier("employee") private final Person person;
}
or
public Payroll {
private final Person person;
@Autowired
@Qualifier("employee")
public void setPerson(Person person) {
this.person = person;
}
}
If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
<button> vs. <input type="button" />. Which to use?
<button>
- by default behaves like if it had a "type="submit" attribute
- can be used without a form as well as in forms.
- text or html content allowed
- css pseudo elements allowed (like :before)
- tag name is usually unique to a single form
vs.
<input type='button'>
- type should be set to 'submit' to behave as a submitting element
- can only be used in forms.
- only text content allowed
- no css pseudo elements
- same tag name as most of the forms elements (inputs)
--
in modern browsers, both elements are easily styleable with css but in most cases, button
element is preferred as you can style more with inner html and pseudo elements
Overlay a background-image with an rgba background-color
_x000D_
_x000D_
/* Working method */_x000D_
.tinted-image {_x000D_
background: _x000D_
/* top, transparent red, faked with gradient */ _x000D_
linear-gradient(_x000D_
rgba(255, 0, 0, 0.45), _x000D_
rgba(255, 0, 0, 0.45)_x000D_
),_x000D_
/* bottom, image */_x000D_
url(https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg);_x000D_
height: 1280px;_x000D_
width: 960px;_x000D_
background-size: cover;_x000D_
}_x000D_
_x000D_
.tinted-image p {_x000D_
color: #fff;_x000D_
padding: 100px;_x000D_
}
_x000D_
<div class="tinted-image">_x000D_
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam distinctio, temporibus tempora a eveniet quas qui veritatis sunt perferendis harum!</p>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_
source: https://css-tricks.com/tinted-images-multiple-backgrounds/
Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?
it is working in my google chrome browser version 11.0.696.60
I created a simple page with no other items just basic tags and no separate CSS file and got an image
this is what i setup:
<div id="placeholder" style="width: 60px; height: 60px; border: 1px solid black; background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div>
I put an id just in case there was a hidden id tag and it works
javascript unexpected identifier
It looks like there is an extra curly bracket in the code.
function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}
How to handle change of checkbox using jQuery?
It seems to me removeProp is not working properly in Chrome :
jsfiddle
$('#badBut1').click(function () {
checkit('Before');
if( $('#chk').prop('checked') )
{
$('#chk').removeProp('checked');
}else{
$('#chk').prop('checked', true);
}
checkit('After');
});
$('#But1').click(function () {
checkit('Before');
if( $('#chk').prop('checked') )
{
$('#chk').removeClass('checked').prop('checked',false);
}else{
$('#chk').addClass('checked').prop('checked', true);
}
checkit('After');
});
$('#But2').click(function () {
var chk1 = $('#chk').is(':checked');
console.log("Value : " + chk1);
});
$('#chk').on( 'change',function () {
checkit('Result');
});
function checkit(moment) {
var chk1 = $('#chk').is(':checked');
console.log(moment+", value = " + chk1);
};
How do I build an import library (.lib) AND a DLL in Visual C++?
By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.
Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.
You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.
Detect iPhone/iPad purely by css
This is how I handle iPhone (and similar) devices [not iPad]:
In my CSS file:
@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
/* CSS overrides for mobile here */
}
In the head of my HTML document:
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
Merge Cell values with PHPExcel - PHP
There is a specific method to do this:
$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');
You can also use:
$objPHPExcel->setActiveSheetIndex(0)->mergeCells('A1:C1');
That should do the trick.
Changing the width of Bootstrap popover
For people who prefer the JavaScript solution.
In Bootstrap 4 tip() became getTipElement() and it returns a no jQuery object. So in order to change the width of the popover in Bootstrap 4 you can use:
}).on("show.bs.popover", function() {
$($(this).data("bs.popover").getTipElement()).css("max-width", "405px");
});
How to flatten only some dimensions of a numpy array
Take a look at numpy.reshape .
>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)
>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape
# (5000, 25)
# One shape dimension can be -1.
# In this case, the value is inferred from
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)
Get input type="file" value when it has multiple files selected
The files selected are stored in an array: [input].files
For example, you can access the items
// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
For jQuery-comfortable people, it's similarly easy
// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
Detecting IE11 using CSS Capability/Feature Detection
In the light of the evolving thread, I have updated the below:
IE 6
* html .ie6 {property:value;}
or
.ie6 { _property:value;}
IE 7
*+html .ie7 {property:value;}
or
*:first-child+html .ie7 {property:value;}
IE 6 and 7
@media screen\9 {
.ie67 {property:value;}
}
or
.ie67 { *property:value;}
or
.ie67 { #property:value;}
IE 6, 7 and 8
@media \0screen\,screen\9 {
.ie678 {property:value;}
}
IE 8
html>/**/body .ie8 {property:value;}
or
@media \0screen {
.ie8 {property:value;}
}
IE 8 Standards Mode Only
.ie8 { property /*\**/: value\9 }
IE 8,9 and 10
@media screen\0 {
.ie8910 {property:value;}
}
IE 9 only
@media screen and (min-width:0\0) and (min-resolution: .001dpcm) {
// IE9 CSS
.ie9{property:value;}
}
IE 9 and above
@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
// IE9+ CSS
.ie9up{property:value;}
}
IE 9 and 10
@media screen and (min-width:0) {
.ie910{property:value;}
}
IE 10 only
_:-ms-lang(x), .ie10 { property:value\9; }
IE 10 and above
_:-ms-lang(x), .ie10up { property:value; }
or
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.ie10up{property:value;}
}
The use of -ms-high-contrast
means that MS Edge will not be targeted, as Edge does not support -ms-high-contrast
.
IE 11
_:-ms-fullscreen, :root .ie11up { property:value; }
Javascript alternatives
Modernizr runs quickly on page load to detect features; it then
creates a JavaScript object with the results, and adds classes to the
html element
Javascript:
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');
Adds (e.g) the below to html
element:
data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'
Allowing very targetted CSS selectors, e.g.:
html[data-useragent*='Chrome/13.0'] .nav{
background:url(img/radial_grad.png) center bottom no-repeat;
}
Footnote
If possible, identify and fix any issue(s) without hacks. Support progressive enhancement and graceful degradation. However, this is an 'ideal world' scenario not always obtainable, as such- the above should help provide some good options.
Attribution / Essential Reading
Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
Changing the selected option of an HTML Select element
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList
missing .forEach()
:
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})
How to get PID of process I've just started within java program?
In my testing all IMPL classes had the field "pid". This has worked for me:
public static int getPid(Process process) {
try {
Class<?> cProcessImpl = process.getClass();
Field fPid = cProcessImpl.getDeclaredField("pid");
if (!fPid.isAccessible()) {
fPid.setAccessible(true);
}
return fPid.getInt(process);
} catch (Exception e) {
return -1;
}
}
Just make sure the returned value is not -1. If it is, then parse the output of ps
.
Send parameter to Bootstrap modal window?
I have found this better way , no need to remove data , just call the source of the remote content each time
$(document).ready(function() {
$('.class').click(function() {
var id = this.id;
//alert(id);checking that have correct id
$("#iframe").attr("src","url?id=" + id);
$('#Modal').modal({
show: true
});
});
});
iPhone: Setting Navigation Bar Title
For all your Swift-ers out there, this worked perfectly for me. It's notably one of the shorter ways to accomplish setting the title, as well:
override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "presentLineItem" {
print("Setting Title")
var vc = segue.destinationViewController as! LineItemsTableViewController
vc.navigationItem.title = "Line Item"
}
}
What values can I pass to the event attribute of the f:ajax tag?
The event
attribute of <f:ajax>
can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on*
attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText>
component which renders <input type="text">
lists the following on*
attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):
blur
change
click
dblclick
focus
keydown
keypress
keyup
mousedown
mousemove
mouseout
mouseover
mouseup
select
Additionally, JSF has two more special event names for EditableValueHolder
and ActionSource
components, the real HTML DOM event being rendered depends on the component type:
valueChange
(will render as change
on text/select inputs and as click
on radio/checkbox inputs)
action
(will render as click
on command links/buttons)
The above two are the default events for the components in question.
Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange
or action
events, such as PrimeFaces <p:ajax>
which supports among others tabChange
, itemSelect
, itemUnselect
, dateSelect
, page
, sort
, filter
, close
, etc depending on the parent <p:xxx>
component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.
Create Elasticsearch curl query for not null and not empty("")
You can do that with bool query and combination of must and must_not like this:
GET index/_search
{
"query": {
"bool": {
"must": [
{"exists": {"field": "field1"}}
],
"must_not": [
{"term": {"field1": ""}}
]
}
}
}
I tested this with Elasticsearch 5.6.5 in Kibana.
Eclipse: All my projects disappeared from Project Explorer
This happened to me. I'm still not sure how, but the reason was that my workspace meta data had become corrupted, probably due to Eclipse being improperly shutdown. The solution, as explained here, is to:
Note, steps 2 & 3 are optional if Eclipse isn't crashing, but just not showing any projects.
- Close Eclipse.
- cd /home/user/workspace/.metadata/.plugins
- mv org.eclipse.core.resources org.eclipse.core.resources_bak
- Start Eclipse
- Do File->Import
- General->Existing Projects into Workspace
- Click the "Select root directory" field and browse to each subfolder in your workspace folder, and import.
For me, this was very tedious, since I had several dozen projects in my workspace, but it's the only solution I found short of restoring my entire workspace from a backup.
Edit: This answer is now quite old, and better solutions may now exist. Although I haven't had need to try it, I recommend attempting @antonagestam's solution first, as others have suggested it may be faster and more effective.
Edit: Since it's fairly simple, I'd recommend trying antonagestam's solution first. However, this problem recently re-occurred for me, and that solution did not work in my case. But neither did it interfere with this solution.
Turn a string into a valid filename?
I liked the python-slugify approach here but it was stripping dots also away which was not desired. So I optimized it for uploading a clean filename to s3 this way:
pip install python-slugify
Example code:
s = 'Very / Unsafe / file\nname hähä \n\r .txt'
clean_basename = slugify(os.path.splitext(s)[0])
clean_extension = slugify(os.path.splitext(s)[1][1:])
if clean_extension:
clean_filename = '{}.{}'.format(clean_basename, clean_extension)
elif clean_basename:
clean_filename = clean_basename
else:
clean_filename = 'none' # only unclean characters
Output:
>>> clean_filename
'very-unsafe-file-name-haha.txt'
This is so failsafe, it works with filenames without extension and it even works for only unsafe characters file names (result is none
here).
Find first element by predicate
No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:
List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
.peek(num -> System.out.println("will filter " + num))
.filter(x -> x > 5)
.findFirst()
.get();
System.out.println(a);
Which outputs:
will filter 1
will filter 10
10
You see that only the two first elements of the stream are actually processed.
So you can go with your approach which is perfectly fine.
Statically rotate font-awesome icons
If you want to rotate 45 degrees, you can use the CSS transform property:
.fa-rotate-45 {
-ms-transform:rotate(45deg); /* Internet Explorer 9 */
-webkit-transform:rotate(45deg); /* Chrome, Safari, Opera */
transform:rotate(45deg); /* Standard syntax */
}
Change keystore password from no password to a non blank password
this way worked better for me:
echo y | keytool -storepasswd -storepass 123456 -keystore /tmp/IT-Root-CA.keystore -import -alias IT-Root-CA -file /etc/pki/ca-trust/source/anchors/IT-Root-CA.crt
machine running:
[root@rhel80-68]# cat /etc/redhat-release
Red Hat Enterprise Linux release 8.1 (Ootpa)
Null vs. False vs. 0 in PHP
I have just wasted 1/2 a day trying to get either a 0
, null
, false
to return from strops
!
Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding:
Concept
take a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done.
Anyway here was the basis of the cosing:
if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ())
{
do this
} else {
or that
}
{
echo strpos(mydomain.co.uk, mydomain);
if ( strpos(mydomain, xmas) == null )
{
echo "\n1 is null";
}
if ( (strpos(mydomain.co.uk, mydomain)) == 0 )
{
echo "\n2 is 0";
} else {
echo "\n2 Something is WRONG";
}
if ( (mydomain.co.uk, mydomain)) != 0 )
{
echo "\n3 is 0";
} else {
echo "\n3 it is not 0";
}
if ( (mydomain.co.uk, mydomain)) == null )
{
echo "\n4 is null";
} else {
echo "\n4 Something is WRONG";
}
}
FINALLY after reading this Topic,
I found that this worked!!!
{
if ((mydomain.co.uk, mydomain)) !== false )
{
echo "\n5 is True";
} else {
echo "\n5 is False";
}
}
Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as false
, as its also can be a NULL
day!
After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as False
, NULL
and 0
are not all the same as True or False or NULL
?
How to find the kafka version in linux
If you want to check the version of a specific Kafka broker, run this CLI on the broker*
kafka-broker-api-versions.sh --bootstrap-server localhost:9092 --version
where localhost:9092
is the accessible <hostname|IP Address>:<port>
this API will check (localhost
can be used if it's the same host you're running this command on). Example of output:
2.4.0 (Commit:77a89fcf8d7fa018)
* Apache Kafka comes with a variety of console tools in the ./bin
sub-directory of your Kafka download; e.g. ~/kafka/bin/
How to edit my Excel dropdown list?
Attribute_Brands is a named range.
On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.
This will take you to the named range.
The data in it can be updated by typing new values into the cells.
The named range can be altered via the 'Insert - Name - Define' menu.
Align div with fixed position on the right side
Trying to do the same thing. If you want it to be aligned on the right side then set the value of right
to 0
. In case you need some padding from the right, set the value to the size of the padding you need.
Example:
.test {
position: fixed;
right: 20px; /* Padding from the right side */
}
Angular 4 checkbox change value
This it what you are looking for:
<input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" />
Inside your class:
checkValue(event: any){
console.log(event);
}
Also include FormsModule in app.module.ts
to make ngModel work !
Hope it Helps!
jQuery: Clearing Form Inputs
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
if ($_POST['action'] == 'addRunner')
I used the :not() on the selection to stop it from clearing the hidden field.
python xlrd unsupported format, or corrupt file.
I had a similar problem and it was related to the version. In a python terminal check:
>> import xlrd
>> xlrd.__VERSION__
If you have '0.9.0' you can open almost all files. If you have '0.6.0' which was what I found on Ubuntu, you may have problems with newest Excel files. You can download the latest version of xlrd using the Distutils standard.
PHP 7 RC3: How to install missing MySQL PDO
Since eggyal didn't provided his comment as answer after he gave right advice in a comment - i am posting it here: In my case I had to install module php-mysql
. See comments under the question for details.
How to implement a confirmation (yes/no) DialogPreference?
Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below
intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);
intentClearCookies.setIntent(clearcookies);
intentClearCookies.setTitle(R.string.ClearCookies);
intentClearCookies.setEnabled(true);
launchPrefCat.addPreference(intentClearCookies);
And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.
public class ClearCookies extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
showDialog();
}
/**
* @throws NotFoundException
*/
private void showDialog() throws NotFoundException {
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.ClearCookies))
.setMessage(
getResources().getString(R.string.ClearCookieQuestion))
.setIcon(
getResources().getDrawable(
android.R.drawable.ic_dialog_alert))
.setPositiveButton(
getResources().getString(R.string.PostiveYesButton),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
})
.setNegativeButton(
getResources().getString(R.string.NegativeNoButton),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
}).show();
}}
As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.
What is the behavior of integer division?
Will result always be the floor of the division?
No. The result varies, but variation happens only for negative values.
What is the defined behavior?
To make it clear floor rounds towards negative infinity,while integer division rounds towards zero (truncates)
For positive values they are the same
int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0
For negative value this is different
int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0
C++ string to double conversion
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.
With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)
#include <stdlib.h>
int main()
{
string word;
openfile >> word;
double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
previously (the function requires it)*/
return 0;
}
Copy Paste in Bash on Ubuntu on Windows
For just copying (possibly long) texts to the Windows clipboard, I have found that just piping the output to clip.exe
(including the .exe
file extension) works fine for me. So:
$ echo "Hello World" | clip.exe
lets me paste Hello World
using Ctrl-V anywhere else.
Now that I have posted this, I notice that related question Pipe from clipboard in linux subsytem for windows includes this and a command solution for pasting from the Windows clipboard as well.
Onclick on bootstrap button
Seem no solutions fix the problem:
$(".anima-area").on('click', function (e) {
return false; //return true;
});
$(".anima-area").on('click', function (e) {
e.preventDefault();
});
$(".anima-area").click(function (r) {
e.preventDefault();
});
$(".anima-area").click(function () {
return false; //return true;
});
Bootstrap button always maintain th pressed status and block all .click code.
If i remove .click function button comeback to work good.
window.onload vs $(document).ready()
The document.ready event occurs when the HTML document has been loaded, and the window.onload
event occurs always later, when all content (images, etc) has been loaded.
You can use the document.ready
event if you want to intervene "early" in the rendering process, without waiting for the images to load.
If you need the images (or any other "content") ready before your script "does something", you need to wait until window.onload
.
For instance, if you are implementing a "Slide Show" pattern, and you need to perform calculations based on image sizes, you may want to wait until window.onload
. Otherwise, you might experience some random problems, depending on how fast the images will get loaded. Your script would be running concurrently with the thread that loads images. If your script is long enough, or the server is fast enough, you may not notice a problem, if images happen to arrive in time. But the safest practice would be allowing for images to get loaded.
document.ready
could be a nice event for you to show some "loading..." sign to users, and upon window.onload
, you can complete any scripting that needed resources loaded, and then finally remove the "Loading..." sign.
Examples :-
// document ready events
$(document).ready(function(){
alert("document is ready..");
})
// using JQuery
$(function(){
alert("document is ready..");
})
// window on load event
function myFunction(){
alert("window is loaded..");
}
window.onload = myFunction;
How to save data file into .RData?
Just to add an additional function should you need it. You can include a variable in the named location, for example a date identifier
date <- yyyymmdd
save(city, file=paste0("c:\\myuser\\somelocation\\",date,"_RData.Data")
This was you can always keep a check of when it was run
PHP Get URL with Parameter
for complette URL with protocol, servername and parameters:
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'];
$url = $base_url . $_SERVER["REQUEST_URI"];
Open file by its full path in C++
Normally one uses the backslash character as the path separator in Windows. So:
ifstream file;
file.open("C:\\Demo.txt", ios::in);
Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt
.
GoogleTest: How to skip a test?
You can now use the GTEST_SKIP()
macro to conditionally skip a test at runtime. For example:
TEST(Foo, Bar)
{
if (blah)
GTEST_SKIP();
...
}
Note that this is a very recent feature so you may need to update your GoogleTest library to use it.
Add two textbox values and display the sum in a third textbox automatically
Try this: Open given fiddle in CHROME
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
HTML
<input type="text" id="txt1" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
<input type="text" id="txt3" />
DEMO HERE
Pointer to class data member "::*"
This is the simplest example I can think of that conveys the rare cases where this feature is pertinent:
#include <iostream>
class bowl {
public:
int apples;
int oranges;
};
int count_fruit(bowl * begin, bowl * end, int bowl::*fruit)
{
int count = 0;
for (bowl * iterator = begin; iterator != end; ++ iterator)
count += iterator->*fruit;
return count;
}
int main()
{
bowl bowls[2] = {
{ 1, 2 },
{ 3, 5 }
};
std::cout << "I have " << count_fruit(bowls, bowls + 2, & bowl::apples) << " apples\n";
std::cout << "I have " << count_fruit(bowls, bowls + 2, & bowl::oranges) << " oranges\n";
return 0;
}
The thing to note here is the pointer passed in to count_fruit. This saves you having to write separate count_apples and count_oranges functions.
GROUP_CONCAT ORDER BY
In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post: http://raxdb.com/blog/sorting-by-regex/
What causes signal 'SIGILL'?
Make sure that all functions with non-void return type have a return
statement.
While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.
Batch Files - Error Handling
A successful ping on your local network can be trapped using ERRORLEVEL
.
@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT
The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'
After a lot of trial and error, followed by a stagnant period while I waited for an opportunity to speak with our server guys, I finally had a chance to discuss the problem with them and asked them if they wouldn't mind switching our Sharepoint authentication over to Kerberos.
To my surprise, they said this wouldn't be a problem and was in fact easy to do. They enabled Kerberos and I modified my app.config as follows:
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
For reference, my full serviceModel entry in my app.config looks like this:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="TestServerReference" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2000000" maxBufferPoolSize="2000000" maxReceivedMessageSize="2000000"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://path/to/site/_vti_bin/Lists.asmx"
binding="basicHttpBinding" bindingConfiguration="TestServerReference"
contract="TestServerReference.ListsSoap" name="TestServerReference" />
</client>
</system.serviceModel>
After this, everything worked like a charm. I can now (finally!) utilize Sharepoint Web Services. So, if anyone else out there can't get their Sharepoint Web Services to work with NTLM, see if you can convince the sysadmins to switch over to Kerberos.
Copy and paste content from one file to another file in vi
These remaps work like a charm for me:
vmap <C-c> "*y " Yank current selection into system clipboard
nmap <C-c> "*Y " Yank current line into system clipboard (if nothing is selected)
nmap <C-v> "*p " Paste from system clipboard
So, when I'm at visual mode, I select the lines I want and press Ctrl + c and then Ctrl + v to insert the text in the receiver file. You could use "*y as well, but I think this is hard to remember sometimes.
This is also useful to copy text from Vim to clipboard.
Source: Copy and paste between sessions using a temporary file
Find which commit is currently checked out in Git
$ git rev-parse HEAD
273cf91b4057366a560b9ddcee8fe58d4c21e6cb
Update:
Alternatively (if you have tags):
(Good for naming a version, not very good for passing back to git.)
$ git describe
v0.1.49-localhost-ag-1-g273cf91
Or (as Mark suggested, listing here for completeness):
$ git show --oneline -s
c0235b7 Autorotate uploaded images based on EXIF orientation
How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?
You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.
Here is a complete example from your data that shows a bar of for each required value at each date:
import pylab as pl
import datetime
data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""
values = []
dates = []
for line in data.split("\n"):
x, y = line.split()
values.append(int(x))
dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()
You need to parse the date with strptime
and set the x-axis to use dates (as described in this answer).
If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)
EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks
(and move them by half the bar width):
fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)
How to undo 'git reset'?
1.Use git reflog
to get all references update.
2.git reset <id_of_commit_to_which_you_want_restore>
How to change the style of alert box?
One option is to use altertify, this gives a nice looking alert box.
Simply include the required libraries from here, and use the following piece of code to display the alert box.
alertify.confirm("This is a confirm dialog.",
function(){
alertify.success('Ok');
},
function(){
alertify.error('Cancel');
});
The output will look like this. To see it in action here is the demo
Dockerfile copy keep subdirectory structure
Remove star from COPY, with this Dockerfile:
FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*
Structure is there:
$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon
Step 0 : FROM ubuntu
---> d0955f21bf24
Step 1 : COPY files/ /files/
---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root 0 May 13 16:04 file1
-rw-r--r-- 1 root root 0 May 13 16:04 file2
/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root 0 May 13 16:04 file1
-rw-r--r-- 1 root root 0 May 13 16:04 file2
---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b
How to serialize Joda DateTime with Jackson JSON processor?
In the object you're mapping:
@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }
In CustomDateSerializer:
public class CustomDateSerializer extends JsonSerializer<DateTime> {
private static DateTimeFormatter formatter =
DateTimeFormat.forPattern("dd-MM-yyyy");
@Override
public void serialize(DateTime value, JsonGenerator gen,
SerializerProvider arg2)
throws IOException, JsonProcessingException {
gen.writeString(formatter.print(value));
}
}
Get host domain from URL?
You can use Request
object or Uri
object to get host of url.
Using Request.Url
string host = Request.Url.Host;
Using Uri
Uri myUri = new Uri("http://www.contoso.com:8080/");
string host = myUri.Host; // host is "www.contoso.com"
What does %s and %d mean in printf in the C language?
%s%d%s%d\n is a format string. It is used to specify how the information is formatted on an output. here the format string is supposed to print string followed by a digit followed by a string and then again a digit. The last symbol \n represents carriage return which marks the end of a line. In C, strings cannot be concatenated by + or , although you can combine different outputs on a single line by using the appropriate format strings (the use of format strings is to format output info.).
Laravel back button
Indeed using {{ URL:previous() }}
do work, but if you're using a same named route to display multiple views, it will take you back to the first endpoint of this route.
In my case, I have a named route, which based on a parameter selected by the user, can render 3 different views. Of course, I have a default case for the first enter in this route, when the user doesn't selected any option yet.
When I use URL:previous()
, Laravel take me back to the default view, even if the user has selected some other option. Only using javascript inside the button I accomplished to be returned to the correct view:
<a href="javascript:history.back()" class="btn btn-default">Voltar</a>
I'm tested this on Laravel 5.3, just for clarification.
How to generate a random String in Java
I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.
public class RandomNumberGenerator {
private static final Set<String> generatedNumbers = new HashSet<String>();
public RandomNumberGenerator() {
}
public static void main(String[] args) {
final int maxLength = 7;
final int maxTry = 10;
for (int i = 0; i < 10; i++) {
System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
}
}
public static String getRandomId(final int maxLength, final int maxTry) {
final Random random = new Random(System.nanoTime());
final int max = (int) Math.pow(10, maxLength);
final int maxMin = (int) Math.pow(10, maxLength-1);
int i = 0;
boolean unique = false;
int randomId = -1;
while (i < maxTry) {
randomId = random.nextInt(max - maxMin - 1) + maxMin;
synchronized (generatedNumbers) {
if (generatedNumbers.contains(randomId) == false) {
unique = true;
break;
}
}
i++;
}
if (unique == false) {
throw new RuntimeException("Cannot generate unique id!");
}
synchronized (generatedNumbers) {
generatedNumbers.add(String.valueOf(randomId));
}
return String.valueOf(randomId);
}
}
Why do people say that Ruby is slow?
Performance is almost always about good design and optimized database interactions. Ruby does what most web sites need quite fast, especially more recent versions; and the speed of development and ease of maintenance provides a large payoff in costs and in keeping customers happy. I find JAVA to have slow execution performance for some tasks, and given the difficulty of developing in JAVA, many developers create slow applications regardless of the theoretical speed capability as demonstrated in benchmarks (benchmarks are generally contrived to show a specific and narrow capability). When I need intensive processing that isn't well suited to my database's capabilities, I choose C or Objective-C or some other truly high performance compiled language for those tasks depending on the platform. If I need to create a databased web application, I use RoR or sometimes C# ASP.NET depending on other requirements; because all platforms have strengths and weaknesses. Execution speed of the things your application does is important, but after all, if execution performance of one narrow aspect of a language is all that counts; then I might still be using Assembler language for everything.
Change SVN repository URL
Given that the Apache Subversion server will be moved to this new DNS alias: sub.someaddress.com.tr
:
With Subversion 1.7 or higher, use svn relocate
. Relocate is used when the SVN server's location changes. switch
is only used if you want to change your local working copy to another branch or another path. If using TortoiseSVN, you may follow instructions from the TortoiseSVN Manual. If using the SVN command line interface, refer to this section of SVN's documentation. The command should look like this:
svn relocate svn://sub.someaddress.com.tr/project
Keep using /project
given that the actual contents of your repository probably won't change.
Note: svn relocate
is not available before version 1.7 (thanks to ColinM for the info). In older versions you would use:
svn switch --relocate OLD NEW
Angular2 get clicked element id
When your HTMLElement
doesn't have an id
, name
or class
to call,
then use
<input type="text" (click)="selectedInput($event)">
selectedInput(event: MouseEvent) {
log(event.srcElement) // HTMInputLElement
}
How can I change an element's class with JavaScript?
Here's a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
see jsfiddle
also see my answer here for creating a new class dynamically
Call break in nested if statements
Javascript will throw an exception if you attempt to use a break;
statement inside an if else. It is used mainly for loops. You can "break" out of an if else statement with a condition, which does not make sense to include a "break" statement.
JSFiddle
How to do a SOAP Web Service call from Java class?
I understand your problem boils down to how to call a SOAP (JAX-WS) web service from Java and get its returning object. In that case, you have two possible approaches:
- Generate the Java classes through
wsimport
and use them; or
- Create a SOAP client that:
- Serializes the service's parameters to XML;
- Calls the web method through HTTP manipulation; and
- Parse the returning XML response back into an object.
About the first approach (using wsimport
):
I see you already have the services' (entities or other) business classes, and it's a fact that the wsimport
generates a whole new set of classes (that are somehow duplicates of the classes you already have).
I'm afraid, though, in this scenario, you can only either:
- Adapt (edit) the
wsimport
generated code to make it use your business classes (this is difficult and somehow not worth it - bear in mind everytime the WSDL changes, you'll have to regenerate and readapt the code); or
- Give up and use the
wsimport
generated classes. (In this solution, you business code could "use" the generated classes as a service from another architectural layer.)
About the second approach (create your custom SOAP client):
In order to implement the second approach, you'll have to:
- Make the call:
- Use the SAAJ (SOAP with Attachments API for Java) framework (see below, it's shipped with Java SE 1.6 or above) to make the calls; or
- You can also do it through
java.net.HttpUrlconnection
(and some java.io
handling).
- Turn the objects into and back from XML:
- Use an OXM (Object to XML Mapping) framework such as JAXB to serialize/deserialize the XML from/into objects
- Or, if you must, manually create/parse the XML (this can be the best solution if the received object is only a little bit differente from the sent one).
Creating a SOAP client using classic java.net.HttpUrlConnection
is not that hard (but not that simple either), and you can find in this link a very good starting code.
I recommend you use the SAAJ framework:
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "https://www.w3schools.com/xml/tempconvert.asmx";
String soapAction = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "https://www.w3schools.com/xml/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="https://www.w3schools.com/xml/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:CelsiusToFahrenheit>
<myNamespace:Celsius>100</myNamespace:Celsius>
</myNamespace:CelsiusToFahrenheit>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);
soapBodyElem1.addTextNode("100");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
About using JAXB for serializing/deserializing, it is very easy to find information about it. You can start here: http://www.mkyong.com/java/jaxb-hello-world-example/.
How to use java.String.format in Scala?
You don't need to use numbers to indicate positioning. By default, the position of the argument is simply the order in which it appears in the string.
Here's an example of the proper way to use this:
String result = String.format("The format method is %s!", "great");
// result now equals "The format method is great!".
You will always use a %
followed by some other characters to let the method know how it should display the string. %s
is probably the most common, and it just means that the argument should be treated as a string.
I won't list every option, but I'll give a few examples just to give you an idea:
// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals "10 / 3 = 3.33"
// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals "Today we processed 1,000,000 transactions."
String.format
just uses a java.util.Formatter
, so for a full description of the options you can see the Formatter javadocs.
And, as BalusC mentions, you will see in the documentation that is possible to change the default argument ordering if you need to. However, probably the only time you'd need / want to do this is if you are using the same argument more than once.
What is the functionality of setSoTimeout and how it works?
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the
InputStream associated with this Socket will block for only this
amount of time. If the timeout expires, a
java.net.SocketTimeoutException is raised, though the Socket is still
valid. The option must be enabled prior to entering the blocking
operation to have effect. The timeout must be > 0. A timeout of zero
is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
How do I fire an event when a iframe has finished loading in jQuery?
I tried an out of the box approach to this, I havent tested this for PDF content but it did work for normal HTML based content, heres how:
Step 1: Wrap your Iframe in a div wrapper
Step 2: Add a background image to your div wrapper:
.wrapperdiv{
background-image:url(img/loading.gif);
background-repeat:no-repeat;
background-position:center center; /*Can place your loader where ever you like */
}
Step 3: in ur iframe tag add ALLOWTRANSPARENCY="false"
The idea is to show the loading animation in the wrapper div till the iframe loads after it has loaded the iframe would cover the loading animation.
Give it a try.