What is Node.js?
Q: The programming model is event driven, especially the way it handles I/O.
Correct. It uses call-backs, so any request to access the file system would cause a request to be sent to the file system and then Node.js would start processing its next request. It would only worry about the I/O request once it gets a response back from the file system, at which time it will run the callback code. However, it is possible to make synchronous I/O requests (that is, blocking requests). It is up to the developer to choose between asynchronous (callbacks) or synchronous (waiting).
Q: It uses JavaScript and the parser is V8.
Yes
Q: It can be easily used to create concurrent server applications.
Yes, although you'd need to hand-code quite a lot of JavaScript. It might be better to look at a framework, such as http://www.easynodejs.com/ - which comes with full online documentation and a sample application.
How do I find the current directory of a batch file, and then use it for the path?
ElektroStudios answer is a bit misleading.
"when you launch a bat file the working dir is the dir where it was launched"
This is true if the user clicks on the batch file in the explorer.
However, if the script is called from another script using the CALL command, the current working directory does not change.
Thus, inside your script, it is better to use %~dp0subfolder\file1.txt
Please also note that %~dp0 will end with a backslash when the current script is not in the current working directory.
Thus, if you need the directory name without a trailing backslash, you could use something like
call :GET_THIS_DIR
echo I am here: %THIS_DIR%
goto :EOF
:GET_THIS_DIR
pushd %~dp0
set THIS_DIR=%CD%
popd
goto :EOF
What exactly does numpy.exp() do?
It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5))
is similar to [math.e**x for x in range(5)]
.
How to load html string in a webview?
read from assets html file
ViewGroup webGroup;
String content = readContent("content/ganji.html");
final WebView webView = new WebView(this);
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
webGroup.addView(webView);
How do I tokenize a string sentence in NLTK?
As @PavelAnossov answered, the canonical answer, use the word_tokenize
function in nltk:
from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)
If your sentence is truly simple enough:
Using the string.punctuation
set, remove punctuation then split using the whitespace delimiter:
import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y
How do I sort a table in Excel if it has cell references in it?
I was hoping to find a why on here, but I think the answer is simpler than we are making it.
The cells should sort regardless of what page they are referencing in your workbook. What was causing the issue for us was any page name references on the current page.
EX: I am in the Today workbook, and I am referencing data for a sales rep on a different page.
If my criteria (The reps name) is in Today!C1 (Or $C1, $c$1) and I try to sort, the sheet will not recognize the action. But if you remove the name that is referencing the page you are on (Redundant reference really) this problem should stop.
So SUMIFS('Sales'!C1,'Sales'!A1,Today!C1) will now be SUMIFS('Sales'!C1,'Sales'!A1,C1)
If someone can enlighten to as why it works that way, that would be amazing.
Bin size in Matplotlib (Histogram)
I use quantiles to do bins uniform and fitted to sample:
bins=df['Generosity'].quantile([0,.05,0.1,0.15,0.20,0.25,0.3,0.35,0.40,0.45,0.5,0.55,0.6,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1]).to_list()
plt.hist(df['Generosity'], bins=bins, normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')
Converting serial port data to TCP/IP in a Linux environment
You don't need to write a program to do this in Linux. Just pipe the serial port through netcat:
netcat www.example.com port </dev/ttyS0 >/dev/ttyS0
Just replace the address and port information. Also, you may be using a different serial port (i.e. change the /dev/ttyS0
part). You can use the stty or setserial commands to change the parameters of the serial port (baud rate, parity, stop bits, etc.).
Parse RSS with jQuery
Use jFeed - a jQuery RSS/Atom plugin. According to the docs, it's as simple as:
jQuery.getFeed({
url: 'rss.xml',
success: function(feed) {
alert(feed.title);
}
});
Good examples using java.util.logging
java.util.logging
keeps you from having to tote one more jar file around with your application, and it works well with a good Formatter.
In general, at the top of every class, you should have:
private static final Logger LOGGER = Logger.getLogger( ClassName.class.getName() );
Then, you can just use various facilities of the Logger class.
Use Level.FINE
for anything that is debugging at the top level of execution flow:
LOGGER.log( Level.FINE, "processing {0} entries in loop", list.size() );
Use Level.FINER
/ Level.FINEST
inside of loops and in places where you may not always need to see that much detail when debugging basic flow issues:
LOGGER.log( Level.FINER, "processing[{0}]: {1}", new Object[]{ i, list.get(i) } );
Use the parameterized versions of the logging facilities to keep from generating tons of String concatenation garbage that GC will have to keep up with. Object[]
as above is cheap, on the stack allocation usually.
With exception handling, always log the complete exception details:
try {
...something that can throw an ignorable exception
} catch( Exception ex ) {
LOGGER.log( Level.SEVERE, ex.toString(), ex );
}
I always pass ex.toString()
as the message here, because then when I "grep -n
" for "Exception
" in log files, I can see the message too. Otherwise, it is going to be on the next line of output generated by the stack dump, and you have to have a more advanced RegEx to match that line too, which often gets you more output than you need to look through.
How to navigate through a vector using iterators? (C++)
Vector's iterators are random access iterators which means they look and feel like plain pointers.
You can access the nth element by adding n to the iterator returned from the container's begin()
method, or you can use operator []
.
std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();
int sixth = *(it + 5);
int third = *(2 + it);
int second = it[1];
Alternatively you can use the advance function which works with all kinds of iterators. (You'd have to consider whether you really want to perform "random access" with non-random-access iterators, since that might be an expensive thing to do.)
std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();
std::advance(it, 5);
int sixth = *it;
How to interpolate variables in strings in JavaScript, without concatenation?
You can use this javascript function to do this sort of templating. No need to include an entire library.
function createStringFromTemplate(template, variables) {
return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
return variables[varName];
});
}
createStringFromTemplate(
"I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
{
list_name : "this store",
var1 : "FOO",
var2 : "BAR",
var3 : "BAZ"
}
);
Output: "I would like to receive email updates from this store FOO BAR BAZ."
Using a function as an argument to the String.replace() function was part of the ECMAScript v3 spec. See this SO answer for more details.
Is ini_set('max_execution_time', 0) a bad idea?
Reason is to have some value other than zero.
General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.
- You can halt server, corrupt work of other people by memory
consuming script without even knowing it.
- You will not be seeing mistakes
where something, let's say, infinite loop happened, and it will be harder to diagnose.
- Such site may be easily DoSed by single user, when requesting pages with long execution time
How to get the changes on a branch in Git
git cherry branch [newbranch]
does exactly what you are asking, when you are in the master
branch.
I am also very fond of:
git diff --name-status branch [newbranch]
Which isn't exactly what you're asking, but is still very useful in the same context.
Pass variables to AngularJS controller, best practice?
You could create a basket service. And generally in JS you use objects instead of lots of parameters.
Here's an example: http://jsfiddle.net/2MbZY/
var app = angular.module('myApp', []);
app.factory('basket', function() {
var items = [];
var myBasketService = {};
myBasketService.addItem = function(item) {
items.push(item);
};
myBasketService.removeItem = function(item) {
var index = items.indexOf(item);
items.splice(index, 1);
};
myBasketService.items = function() {
return items;
};
return myBasketService;
});
function MyCtrl($scope, basket) {
$scope.newItem = {};
$scope.basket = basket;
}
In Python, how do I loop through the dictionary and change the value if it equals something?
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)
For what is worth if anyone should read again this topic(like me) the correct answer would be in DateTimeFormatter
definition, e.g.:
private static DateTimeFormatter DATE_FORMAT =
new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
One should set the optional fields if they will appear. And the rest of code should be exactly the same.
Multipart forms from C# client
Building on dnolans example, this is the version I could actually get to work (there were some errors with the boundary, encoding wasn't set) :-)
To send the data:
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("http://you.url.here");
oRequest.ContentType = "multipart/form-data; boundary=" + PostData.boundary;
oRequest.Method = "POST";
PostData pData = new PostData();
Encoding encoding = Encoding.UTF8;
Stream oStream = null;
/* ... set the parameters, read files, etc. IE:
pData.Params.Add(new PostDataParam("email", "[email protected]", PostDataParamType.Field));
pData.Params.Add(new PostDataParam("fileupload", "filename.txt", "filecontents" PostDataParamType.File));
*/
byte[] buffer = encoding.GetBytes(pData.GetPostData());
oRequest.ContentLength = buffer.Length;
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();
HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();
The PostData class should look like:
public class PostData
{
// Change this if you need to, not necessary
public static string boundary = "AaB03x";
private List<PostDataParam> m_Params;
public List<PostDataParam> Params
{
get { return m_Params; }
set { m_Params = value; }
}
public PostData()
{
m_Params = new List<PostDataParam>();
}
/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public string GetPostData()
{
StringBuilder sb = new StringBuilder();
foreach (PostDataParam p in m_Params)
{
sb.AppendLine("--" + boundary);
if (p.Type == PostDataParamType.File)
{
sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
sb.AppendLine("Content-Type: application/octet-stream");
sb.AppendLine();
sb.AppendLine(p.Value);
}
else
{
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
sb.AppendLine();
sb.AppendLine(p.Value);
}
}
sb.AppendLine("--" + boundary + "--");
return sb.ToString();
}
}
public enum PostDataParamType
{
Field,
File
}
public class PostDataParam
{
public PostDataParam(string name, string value, PostDataParamType type)
{
Name = name;
Value = value;
Type = type;
}
public PostDataParam(string name, string filename, string value, PostDataParamType type)
{
Name = name;
Value = value;
FileName = filename;
Type = type;
}
public string Name;
public string FileName;
public string Value;
public PostDataParamType Type;
}
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
Detect Route Change with react-router
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Sidebar from './Sidebar';
import Chat from './Chat';
<Router>
<Sidebar />
<Switch>
<Route path="/rooms/:roomId" component={Chat}>
</Route>
</Switch>
</Router>
import { useHistory } from 'react-router-dom';
function SidebarChat(props) {
**const history = useHistory();**
var openChat = function (id) {
**//To navigate**
history.push("/rooms/" + id);
}
}
**//To Detect the navigation change or param change**
import { useParams } from 'react-router-dom';
function Chat(props) {
var { roomId } = useParams();
var roomId = props.match.params.roomId;
useEffect(() => {
//Detect the paramter change
}, [roomId])
useEffect(() => {
//Detect the location/url change
}, [location])
}
Difference between OpenJDK and Adoptium/AdoptOpenJDK
In short:
- OpenJDK has multiple meanings and can refer to:
- free and open source implementation of the Java Platform, Standard Edition (Java SE)
- open source repository — the Java source code aka OpenJDK project
- prebuilt OpenJDK binaries maintained by Oracle
- prebuilt OpenJDK binaries maintained by the OpenJDK community
- AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)
Explanation:
Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.
OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at
http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.
OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.
Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.
AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.
OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.
Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".
Donald Smith, Java product manager at Oracle writes:
Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK",
either under the GPL or the commercial license, depending on your
situation. However, for historical reasons, while the small remaining
differences exist, we will refer to them separately as Oracle’s
OpenJDK builds and the Oracle JDK.
OpenJDK Providers and Comparison
----------------------------------------------------------------------------------------
| Provider | Free Builds | Free Binary | Extended | Commercial | Permissive |
| | from Source | Distributions | Updates | Support | License |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK | Yes | Yes | Yes | No | Yes |
| Amazon – Corretto | Yes | Yes | Yes | No | Yes |
| Azul Zulu | No | Yes | Yes | Yes | Yes |
| BellSoft Liberica | No | Yes | Yes | Yes | Yes |
| IBM | No | No | Yes | Yes | Yes |
| jClarity | No | No | Yes | Yes | Yes |
| OpenJDK | Yes | Yes | Yes | No | Yes |
| Oracle JDK | No | Yes | No** | Yes | No |
| Oracle OpenJDK | Yes | Yes | No | No | Yes |
| ojdkbuild | Yes | Yes | No | No | Yes |
| RedHat | Yes | Yes | Yes | Yes | Yes |
| SapMachine | Yes | Yes | Yes | Yes | Yes |
----------------------------------------------------------------------------------------
Free Builds from Source - the distribution source code is publicly available and one can assemble its own build
Free Binary Distributions - the distribution binaries are publicly available for download and usage
Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle
Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)
Permissive License - the distribution license is non-protective, e.g. Apache 2.0
Which Java Distribution Should I Use?
In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.
What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.
Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).
If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.
Additional information
Time to look beyond Oracle's JDK by Stephen Colebourne
Java Is Still Free by Java Champions community (published on September 17, 2018)
Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)
Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)
Using colors with printf
This is a little function that prints colored text using bash scripting. You may add as many styles as you want, and even print tabs and new lines:
#!/bin/bash
# prints colored text
print_style () {
if [ "$2" == "info" ] ; then
COLOR="96m";
elif [ "$2" == "success" ] ; then
COLOR="92m";
elif [ "$2" == "warning" ] ; then
COLOR="93m";
elif [ "$2" == "danger" ] ; then
COLOR="91m";
else #default color
COLOR="0m";
fi
STARTCOLOR="\e[$COLOR";
ENDCOLOR="\e[0m";
printf "$STARTCOLOR%b$ENDCOLOR" "$1";
}
print_style "This is a green text " "success";
print_style "This is a yellow text " "warning";
print_style "This is a light blue with a \t tab " "info";
print_style "This is a red text with a \n new line " "danger";
print_style "This has no color";
runOnUiThread in fragment
Use a Kotlin extension function
fun Fragment?.runOnUiThread(action: () -> Unit) {
this ?: return
if (!isAdded) return // Fragment not attached to an Activity
activity?.runOnUiThread(action)
}
Then, in any Fragment
you can just call runOnUiThread
. This keeps calls consistent across activities and fragments.
runOnUiThread {
// Call your code here
}
NOTE: If Fragment
is no longer attached to an Activity
, callback will not be called and no exception will be thrown
If you want to access this style from anywhere, you can add a common object and import the method:
object ThreadUtil {
private val handler = Handler(Looper.getMainLooper())
fun runOnUiThread(action: () -> Unit) {
if (Looper.myLooper() != Looper.getMainLooper()) {
handler.post(action)
} else {
action.invoke()
}
}
}
Using SSH keys inside docker container
You can use multi stage build to build containers
This is the approach you can take :-
Stage 1 building an image with ssh
FROM ubuntu as sshImage
LABEL stage=sshImage
ARG SSH_PRIVATE_KEY
WORKDIR /root/temp
RUN apt-get update && \
apt-get install -y git npm
RUN mkdir /root/.ssh/ &&\
echo "${SSH_PRIVATE_KEY}" > /root/.ssh/id_rsa &&\
chmod 600 /root/.ssh/id_rsa &&\
touch /root/.ssh/known_hosts &&\
ssh-keyscan github.com >> /root/.ssh/known_hosts
COPY package*.json ./
RUN npm install
RUN cp -R node_modules prod_node_modules
Stage 2: build your container
FROM node:10-alpine
RUN mkdir -p /usr/app
WORKDIR /usr/app
COPY ./ ./
COPY --from=sshImage /root/temp/prod_node_modules ./node_modules
EXPOSE 3006
CMD ["npm", "run", "dev"]
add env attribute in your compose file:
environment:
- SSH_PRIVATE_KEY=${SSH_PRIVATE_KEY}
then pass args from build script like this:
docker-compose build --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)"
And remove the intermediate container it for security.
This Will help you cheers.
Convert an array to string
You can join your array using the following:
string.Join(",", Client);
Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.
Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?
REST security is transport dependent while SOAP security is not.
REST inherits security measures from the underlying transport while SOAP defines its own via WS-Security.
When we talk about REST, over HTTP - all security measures applied HTTP are inherited and this is known as transport level security.
Transport level security, secures your message only while its on the wire - as soon as it leaves the wire, the message is no more secured.
But, with WS-Security, its message level security - even though the message leaves the transport channel it will be still protected. Also - with message level security you can partly encrypt the message [not the entire message, but only the parts you want] - but with transport level security you can't do it.
WS-Security has measures for authentication, integrity, confidentiality and non-repudiation while SSL doesn't support non repudiation [with 2-legged OAuth it does].
In performance-wise SSL is very much faster than WS-Security.
Thanks...
How do I create a ListView with rounded corners in Android?
Here is one way of doing it (Thanks to Android Documentation though!):
Add the following into a file (say customshape.xml) and then place it in (res/drawable/customshape.xml)
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#SomeGradientBeginColor"
android:endColor="#SomeGradientEndColor"
android:angle="270"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
Once you are done with creating this file, just set the background in one of the following ways:
Through Code:
listView.setBackgroundResource(R.drawable.customshape);
Through XML, just add the following attribute to the container (ex: LinearLayout or to any fields):
android:background="@drawable/customshape"
Hope someone finds it useful...
Hide div by default and show it on click with bootstrap
Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.
- You need to make sure the target
div
has an ID.
- Bootstrap has a
class
"collapse", this will hide your block by
default. If you want your div to be collapsible AND be shown by
default you need to add "in" class to the collapse. Otherwise the
toggle behavior will not work properly.
- Then, on your hyperlink (also works for buttons), add an href
attribute that points to your target div.
- Finally, add the attribute
data-toggle="collapse"
to instruct
Bootstrap to add an appropriate toggle script to this tag.
Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
This div (Bar) is shown by default and can toggle
</div>
What is the purpose of the "role" attribute in HTML?
Is this role attribute necessary?
Answer: Yes.
- The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
- Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.
It provides you:
- Accessibility
- Device adaptation
- Server-side processing
- Complex data description,...etc.
Center an element in Bootstrap 4 Navbar
make new style
.container {
position: relative;
}
.center-nav {
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
width: auto;
max-width: 200px;
text-align: center;
}
.center-nav li{
text-align: center;
width:100%;
}
Replace website name UL with below
<ul class="nav navbar-nav center-nav">
<li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
</ul>
Hope this helps..
VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory
Taking Shiraz's idea and running with it...
In your application, are you explicitly defining a domain User Account and Password to access AD?
When you are executing the application explicitly it may be inherently using your credentials (your currently logged in domain account) to interrogate AD. However, when calling the application from the script, I'm not sure if the application is in the System context.
A VBScript example would be as follows:
Dim objConnection As ADODB.Connection
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Properties("User ID") = "MyDomain\MyAccount"
objConnection.Properties("Password") = "MyPassword"
objConnection.Open "Active Directory Provider"
If this works, of course it would be best practice to create and use a service account specifically for this task, and to deny interactive login to that account.
write multiple lines in a file in python
Assuming you don't want a space at each new line use:
print("I'm going to write these to the file")
target.write("%s\n%s\n%s\n" % (line1, line2, line3))
This works for version 3.6
how to display variable value in alert box?
spans not have the value in html
one is the id
for span
tag
in javascript use
document.getElementById('one').innerText;
in jQuery use
$('#one').text()
function check() {
var content = document.getElementById("one").innerText;
alert(content);
}
or
function check() {
var content = $('#one').text();
alert(content);
}
Java Immutable Collections
Collection<String> c1 = new ArrayList<String>();
c1.add("foo");
Collection<String> c2 = Collections.unmodifiableList(c1);
c1
is mutable (i.e. neither unmodifiable nor immutable).
c2
is unmodifiable: it can't be changed itself, but if later on I change c1
then that change will be visible in c2
.
This is because c2
is simply a wrapper around c1
and not really an independent copy. Guava provides the ImmutableList
interface and some implementations. Those work by actually creating a copy of the input (unless the input is an immutable collection on its own).
Regarding your second question:
The mutability/immutability of a collection does not depend on the mutability/immutability of the objects contained therein. Modifying an object contained in a collection does not count as a "modification of the collection" for this description. Of course if you need a immutable collection, you usually also want it to contain immutable objects.
What's the canonical way to check for type in Python?
I think the cool thing about using a dynamic language like Python is you really shouldn't have to check something like that.
I would just call the required methods on your object and catch an AttributeError
. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing.
I've used this a lot when getting data off the web with urllib2.urlopen()
which returns a file like object. This can in turn can be passed to almost any method that reads from a file, because it implements the same read()
method as a real file.
But I'm sure there is a time and place for using isinstance()
, otherwise it probably wouldn't be there :)
Bypass popup blocker on window.open when JQuery event.preventDefault() is set
The observation that the event had to be initiated by the user helped me to figure out the first part of this, but even after that Chrome and Firefox still blocked the new window. The second part was adding target="_blank" to the link, which was mentioned in one comment.
In summary: you need to call window.open from an event initiated by the user, in this case clicking on a link, and that link needs to have target="_blank".
In the example below the link is using class="button-twitter".
$('.button-twitter').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var tweet_popup = window.open(href, 'tweet_popup', 'width=500,height=300');
});
Get the filePath from Filename using Java
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
How to Upload Image file in Retrofit 2
Retrofit 2.0 solution
@Multipart
@POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(@PartMap Map<String, RequestBody> map);
and
Map<String, RequestBody> params = new HashMap<>();
params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));
Call<CommonResponse> call = request.requestUpdateImage(params);
you can use
image/jpg
image/png
image/gif
Regex - Does not contain certain Characters
^[^<>]+$
The caret in the character class ([^
) means match anything but, so this means, beginning of string, then one or more of anything except <
and >
, then the end of the string.
ReactJS - Call One Component Method From Another Component
Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.
Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:
- Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
- add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
- if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.
UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:
let counter = 0;
function handleInstantiate() {
counter++;
}
constructor(props) {
super(props);
handleInstantiate();
}
JavaScript before leaving the page
This will alert on leaving current page
<script type='text/javascript'>
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
</script>
Python Save to file
You need to open the file again using open()
, but this time passing 'w'
to indicate that you want to write to the file. I would also recommend using with
to ensure that the file will be closed when you are finished writing to it.
with open('Failed.txt', 'w') as f:
for ip in [k for k, v in ips.iteritems() if v >=5]:
f.write(ip)
Naturally you may want to include newlines or other formatting in your output, but the basics are as above.
The same issue with closing your file applies to the reading code. That should look like this:
ips = {}
with open('today','r') as myFile:
for line in myFile:
parts = line.split(' ')
if parts[1] == 'Failure':
if parts[0] in ips:
ips[pars[0]] += 1
else:
ips[parts[0]] = 0
How to get a user's client IP address in ASP.NET?
Combining the answers from @Tony and @mangokun, I have created the following extension method:
public static class RequestExtensions
{
public static string GetIPAddress(this HttpRequest Request)
{
if (Request.Headers["CF-CONNECTING-IP"] != null) return Request.Headers["CF-CONNECTING-IP"].ToString();
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
}
return Request.UserHostAddress;
}
}
SQL Server 2008 R2 Express permissions -- cannot create database or modify users
In SSMS 2012, you'll have to use:
To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.
- Add "-m;" into parameters;
- Restart the service and logon this SQL instance by using windows authentication;
- The rest steps are same as above. Change your windows user account permission in security or reset SA account password.
- Last, remove "-m" parameter from "startup parameters";
Eclipse: "'Periodic workspace save.' has encountered a pro?blem."
Agree with @J-Dizzle,
I am a beginner in web-development and had a hard time solving this today.
Had similar problems when I was creating a SpringBoot project in STS.
Tried most of the solutions mentioned but they didn't work.
Tried removing .metadata
folder and re-building my springboot project but still nothing worked.
NOTE : I had multiple workspace in STS and this error occurred after migrating a project from one workspace to another.
Solution : All you need to do is restart your eclipse/STS IDE and it will work just fine.
How do I attach events to dynamic HTML elements with jQuery?
Sometimes doing this (the top-voted answer) is not always enough:
$('body').on('click', 'a.myclass', function() {
// do something
});
This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called "refreshes" the listener.
For example:
function RefreshSomeEventListener() {
// Remove handler from existing elements
$("#wrapper .specific-selector").off();
// Re-add event handler for all matching elements
$("#wrapper .specific-selector").on("click", function() {
// Handle event.
}
}
Because it is a function, whenever I set up my listener this way, I typically call it on document ready:
$(document).ready(function() {
// Other ready commands / code
// Call our function to setup initial listening
RefreshSomeEventListener();
});
Then, whenever you add some dynamically added element, call that method again:
function SomeMethodThatAddsElement() {
// Some code / AJAX / whatever.. Adding element dynamically
// Refresh our listener, so the new element is taken into account
RefreshSomeEventListener();
}
Hopefully this helps!
Regards,
Python spacing and aligning strings
You should be able to use the format method:
"Location: {0:20} Revision {1}".format(Location,Revision)
You will have to figure out the of the format length for each line depending on the length of the label. The User line will need a wider format width than the Location or District lines.
Last Run Date on a Stored Procedure in SQL Server
This works fine on 2005 (if the plan is in the cache)
USE YourDb;
SELECT qt.[text] AS [SP Name],
qs.last_execution_time,
qs.execution_count AS [Execution Count]
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.dbid = DB_ID()
AND objectid = OBJECT_ID('YourProc')
anaconda/conda - install a specific package version
There is no version 1.3.0
for rope
. 1.3.0
refers to the package cached-property
. The highest available version of rope
is 0.9.4
.
You can install different versions with conda install package=version
. But in this case there is only one version of rope
so you don't need that.
The reason you see the cached-property
in this listing is because it contains the string "rope"
: "cached-p rope erty"
py35_0
means that you need python version 3.5
for this specific version. If you only have python3.4
and the package is only for version 3.5
you cannot install it with conda.
I am not quite sure on the defaults
either. It should be an indication that this package is inside the default conda channel.
Laravel Soft Delete posts
In Laravel 5.5 Soft Deleted works ( for me ).
Data Base
deleted_at Field, default NULL value
Model
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
}
Controller
public function destroy($id)
{
User::find($id)->delete();
}
How to convert integer timestamp to Python datetime
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
What does set -e mean in a bash script?
cat a.sh
#! /bin/bash
#going forward report subshell or command exit value if errors
#set -e
(cat b.txt)
echo "hi"
./a.sh; echo $?
cat: b.txt: No such file or directory
hi
0
with set -e commented out we see that echo "hi" exit status being reported and hi is printed.
cat a.sh
#! /bin/bash
#going forward report subshell or command exit value if errors
set -e
(cat b.txt)
echo "hi"
./a.sh; echo $?
cat: b.txt: No such file or directory
1
Now we see b.txt error being reported instead and no hi printed.
So default behaviour of shell script is to ignore command errors and continue processing and report exit status of last command. If you want to exit on error and report its status we can use -e option.
What's the difference between import java.util.*; and import java.util.Date; ?
The toString()
implementation of java.util.Date
does not depend on the way the class is imported. It always returns a nice formatted date.
The toString()
you see comes from another class.
Specific import have precedence over wildcard imports.
in this case
import other.Date
import java.util.*
new Date();
refers to other.Date
and not java.util.Date
.
The odd thing is that
import other.*
import java.util.*
Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date
and java.util.Date
matches.
What are .a and .so files?
Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again.
The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file -o option in gcc. So, if there's any change in .so file, you don't need to recompile your main program.
But make sure that your main program is linked to the new .so file with ln command.
This will help you to build the .so files.
http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html
Hope this helps.
How to echo with different colors in the Windows command line
An option for non windows 10 users that doesn't require calling labels, avoiding the delays that go with doing so.
Below is a macro verison of a findstr colorprint routine
usage - where BF is replaced with the hex digit values of the background / Foreground colors:
%Col%{BF}{"string to print"}
@Echo off & CD "%TEMP%"
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")
Set "Col=For %%l in (1 2)Do if %%l==2 (Set "_Str="&(For /F "tokens=1,2 Delims={}" %%G in ("!oline!")Do Set "C_Out=%%G" & Set "_Str=%%~H")&(For %%s in (!_Str!)Do Set ".Str=%%s")&( <nul set /p ".=%DEL%" > "!_Str!" )&( findstr /v /a:!C_Out! /R "^$" "!_Str!" nul )&( del " !_Str!" > nul 2>&1 ))Else Set Oline="
Setlocal EnableDelayedExpansion
rem /* concatenation of multiple macro expansions requires the macro to be expanded within it's own code block. */
(%Col%{02}{"green on black,"}) & (%Col%{10}{black on blue})
Echo/& (%Col%{04}{red on black}) & (%Col%{34}{" red on blue"})
Goto :Eof
A more robust version of the macro replete with error handling.
@Echo off & PUSHD "%TEMP%"
rem /* Macro Definitions */
(Set \n=^^^
%= macro newline Do not modify =%
)
(Set LF=^
%= linefeed. Do not modify =%)
If "!![" == "[" (
Echo/%%COL%% macro must be defined prior to delayed expansion being enabled
Goto :end
)
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")
rem /* %hCol% - Alternate color macro; escaped for use in COL macro. No error checking. Usage: (%hCol:?=HEXVALUE%Output String) */
Set "hCol=For %%o in (1 2)Do if %%o==2 (^<nul set /p ".=%DEL%" ^> "!os!" ^& findstr /v /a:? /R "^$" "!os!" nul ^& del "!os!" ^> nul 2^>^&1 )Else Set os="
rem /* %TB% - used with substitution within COL macro to format help output; not fit for general use, */
Set "TB=^&^< nul Set /P "=.%DEL%!TAB!"^&"
rem /* %COL% - main color output macro. Usage: (%COL%{[a-f0-9][a-f0-9]}{String to Print}) */
Set COL=Set "_v=1"^&Set "Oline="^& For %%l in (1 2)Do if %%l==2 (%\n%
If not "!Oline!" == "" (%\n%
Set "_Str="%\n%
For /F "tokens=1,2 Delims={}" %%G in ("!oline!")Do (%\n%
Set "Hex=%%G"%\n%
Set "_Str=%%~H"%\n%
)%\n%
Echo/!Hex!^|findstr /RX "[0-9a-fA-F][0-9a-fA-F]" ^> nul ^|^| (Echo/^&(%hCol:?=04%Invalid - )%TB%(%hCol:?=06%Bad Hex value.)%TB%(%hCol:?=01%%%COL%%{!Hex!}{!_Str!})%TB:TAB=LF%(%hCol:?=02%!Usage!)^&Set "_Str="^&Set "_v=0")%\n%
If not "!_Str!" == "" (%\n%
^<nul set /p ".=%DEL%" ^> "!_Str!"%\n%
findstr /v /a:!Hex! /R "^$" "!_Str!" nul %\n%
del "!_Str!" ^> nul 2^>^&1%\n%
)Else If not !_v! EQU 0 (%\n%
Echo/^&(%hCol:?=04%Invalid -)%TB%(%hCol:?=06%Arg 2 absent.)%TB%(%hCol:?=01%%%COL%%!Oline!)%TB:TAB=LF%(%hCol:?=04%Input is required for output string.)%TB:TAB=LF%(%hCol:?=02%!Usage!)%\n%
)%\n%
)Else (Echo/^&(%hCol:?=04%Invalid -)%TB%(%hCol:?=06%No Args)%TB:TAB=!TAB!!TAB!%(%hCol:?=01%%%COL%%!Oline!)%TB:TAB=LF%(%hCol:?=02%!Usage!))%\n%
)Else Set Oline=
Set "usage=%%COL%%{[a-f0-9][a-f0-9]}{String to Print}"
For /F eol^=^%LF%%LF%^ delims^= %%A in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x09"') do Set "TAB=%%A"
rem /* removes escaping from macros to enable use outside of COL macro */
Set "hCol=%hCol:^=%"
Set "TB=%TB:^=%"
Setlocal EnableDelayedExpansion
rem /* usage examples */
(%COL%{02}{"green on black,"}) & (%COL%{10}{"black on blue"})
Echo/
(%COL%{04}{"red on black"}) & (%COL%{34}{" red on blue"})&(%COL%{40}{"black on red"})
Echo/& %COL%{03}{Demonstration of error handling-}
rem /* error handling */
Echo/%TB:TAB=!LF! % %hCol:?=20%Example 1 - No args
%COL%
Echo/%TB:TAB=!LF! % %hCol:?=20%Example 2 - Missing 2nd Arg
%COL%{ff}
Echo/%TB:TAB=!LF! % %hCol:?=20%Example 3 - Invalid hex value for 1st Arg
%COL%{HF}{string}
Echo/%TB:TAB=!LF! % %hCol:?=0d%Done
:end
POPD
Goto :Eof
Use NSInteger as array index
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
Inserting an image with PHP and FPDF
I figured it out, and it's actually pretty straight forward.
Set your variable:
$image1 = "img/products/image1.jpg";
Then ceate a cell, position it, then rather than setting where the image is, use the variable you created above with the following:
$this->Cell( 40, 40, $pdf->Image($image1, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'L', false );
Now the cell will move up and down with content if other cells around it move.
Hope this helps others in the same boat.
Calculate mean and standard deviation from a vector of samples in C++ using Boost
My answer is similar as Josh Greifer but generalised to sample covariance. Sample variance is just sample covariance but with the two inputs identical. This includes Bessel's correlation.
template <class Iter> typename Iter::value_type cov(const Iter &x, const Iter &y)
{
double sum_x = std::accumulate(std::begin(x), std::end(x), 0.0);
double sum_y = std::accumulate(std::begin(y), std::end(y), 0.0);
double mx = sum_x / x.size();
double my = sum_y / y.size();
double accum = 0.0;
for (auto i = 0; i < x.size(); i++)
{
accum += (x.at(i) - mx) * (y.at(i) - my);
}
return accum / (x.size() - 1);
}
splitting a number into the integer and decimal parts
This variant allows getting desired precision:
>>> a = 1234.5678
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
(1234, 0.0)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
(1234, 0.5)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
(1234, 0.5678)
Change the project theme in Android Studio?
In Manifest theme sets with style name (AppTheme and myDialog)/ You can set new styles in styles.xml
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyActivity2"
android:label="@string/title_activity_my_activity2"
android:theme="@style/myDialog"
>
</activity>
</application>
styles.xml example
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Black">
<!-- Customize your theme here. -->
</style>
<style name="myDialog" parent="android:Theme.Dialog">
</style>
In parent you set actualy the theme
How to compare arrays in JavaScript?
This method is one that only works on scalar arrays, like the second voted answer on this question.
_x000D_
_x000D_
var arrs = [
[[1, 2, 3], [1, 2, 3]], // true
[[1, 2, 3, 4], [1, 2, 3]], // false
[[1, 2, 3], [1, 2, 3, 4]], // false
]
const arraysEqual = (one, two) => (one.filter((i, n) => two[n] === i).length === one.length) && (two.filter((i, n) => one[n] === i).length === two.length)
arrs.forEach(arr => {
console.log(arraysEqual(arr[0], arr[1]))
})
_x000D_
_x000D_
_x000D_
Without ES6 syntax:
_x000D_
_x000D_
var arrs = [
[[1, 2, 3], [1, 2, 3]], // true
[[1, 2, 3, 4], [1, 2, 3]], // false
[[1, 2, 3], [1, 2, 3, 4]], // false
]
function arraysEqual(one, two) {
return (one.filter((i, n) => two[n] === i).length === one.length) && (two.filter((i, n) => one[n] === i).length === two.length)
}
arrs.forEach(arr => {
console.log(arraysEqual(arr[0], arr[1]))
})
_x000D_
_x000D_
_x000D_
Creating a ZIP archive in memory using System.IO.Compression
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program`enter code here`
{
static void Main(string[] args)
{
using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
{
writer.WriteLine("Information about this package.");
writer.WriteLine("========================");
}
}
}
}
}
}
SVN Commit failed, access forbidden
My issue was my SVN permissions.
I had the same problem "Access to '/svn/[my path]/!svn/me' forbidden" when trying to commit files to a project I had been working on daily for several months. After trying the steps above, I could not resolve the issue. I also tried pulling the project down from scratch, logging in/out of SVN, etc. Finally I contacted my company's IT department and there was a permissions issue that spontaneously emerged which changed my access from read/write to read-only access. The IT department refreshed my permissions and this solved the problem.
MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client
In addition to the above answers ;
After executing the below command
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'
If you get an error as :
[ERROR] Column count of mysql.user is wrong. Expected 42, found 44. The table is probably corrupted
Then try in the cmd as admin; set the path to MySQL server bin folder in the cmd
set path=%PATH%;D:\xampp\mysql\bin;
and then run the command :
mysql_upgrade --force -uroot -p
This should update the server and the system tables.
Then you should be able to successfully run the below commands in a Query in the Workbench :
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'
then remember to execute the following command:
flush privileges;
After all these steps should be able to successfully connect to your MySQL database.
Hope this helps...
Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration
for me i solved it like the following
In Visual Studio 2015 :
From View menu click Other Windows then click Package Manager Console
then run the following commands :
PM> enable-migrations
Migrations have already been enabled in project 'mvcproject'. To overwrite the existing migrations configuration, use the -Force parameter.
PM> enable-migrations -Force
Checking if the context targets an existing database...
Code First Migrations enabled for project mvcproject.
then add the migration name under the migration folder it will add the class you need in Solution Explorer by run the following command
PM>Add-migration AddColumnUser
Finally update the database
PM> update-database
Auto-size dynamic text to fill fixed size container
I got the same problem and the solution is basically use javascript to control font-size.
Check this example on codepen:
https://codepen.io/ThePostModernPlatonic/pen/BZKzVR
This is example is only for height, maybe you need to put some if's about the width.
try to resize it
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sem título</title>
<style>
</style>
</head>
<body>
<div style="height:100vh;background-color: tomato;" id="wrap">
<h1 class="quote" id="quotee" style="padding-top: 56px">Because too much "light" doesn't <em>illuminate</em> our paths and warm us, it only blinds and burns us.</h1>
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var multiplexador = 3;
initial_div_height = document.getElementById ("wrap").scrollHeight;
setInterval(function(){
var div = document.getElementById ("wrap");
var frase = document.getElementById ("quotee");
var message = "WIDTH div " + div.scrollWidth + "px. "+ frase.scrollWidth+"px. frase \n";
message += "HEIGHT div " + initial_div_height + "px. "+ frase.scrollHeight+"px. frase \n";
if (frase.scrollHeight < initial_div_height - 30){
multiplexador += 1;
$("#quotee").css("font-size", multiplexador);
}
console.log(message);
}, 10);
</script>
</html>
How do I load an org.w3c.dom.Document from XML in a string?
To manipulate XML in Java, I always tend to use the Transformer API:
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
public static Document loadXMLFrom(String xml) throws TransformerException {
Source source = new StreamSource(new StringReader(xml));
DOMResult result = new DOMResult();
TransformerFactory.newInstance().newTransformer().transform(source , result);
return (Document) result.getNode();
}
Check substring exists in a string in C
The same will be achived with this simpler code: Why use these:
int main(void)
{
char mainstring[]="The quick brown fox jumps over the lazy dog";
char substring[20];
int i=0;
puts("enter the sub stirng to find");
fgets(substring, sizeof(substring), stdin);
substring[strlen(substring)-1]='\0';
if (strstr(mainstring,substring))
{
printf("substring is present\t");
}
printf("and the sub string is:::");
printf("%s",substring,"\n");
return 0;
}
But the tricky part would be to report at which position in original string the substring starts...
How to convert number to words in java
In this post i have just update Yanick Rochon's code. I have make it workable with lower version of java 1.6 and i was getting the output for 1.00 = one and hundredth. So i have update the code. New i get the output for 1.00 = one and zero hundredth.
I don't not what should i do. Add a new answer or edit that post. As the answer is highly ranked so i have made a new post with updating the code. I have just change this two things have mention above.
/**
* This class will convert numeric values into an english representation
*
* For units, see : http://www.jimloy.com/math/billion.htm
*
* @author [email protected]
*/
public class NumberToWords {
static public class ScaleUnit {
private int exponent;
private String[] names;
private ScaleUnit(int exponent, String... names) {
this.exponent = exponent;
this.names = names;
}
public int getExponent() {
return exponent;
}
public String getName(int index) {
return names[index];
}
}
/**
* See http://www.wordiq.com/definition/Names_of_large_numbers
*/
static private ScaleUnit[] SCALE_UNITS = new ScaleUnit[] {
new ScaleUnit(63, "vigintillion", "decilliard"),
new ScaleUnit(60, "novemdecillion", "decillion"),
new ScaleUnit(57, "octodecillion", "nonilliard"),
new ScaleUnit(54, "septendecillion", "nonillion"),
new ScaleUnit(51, "sexdecillion", "octilliard"),
new ScaleUnit(48, "quindecillion", "octillion"),
new ScaleUnit(45, "quattuordecillion", "septilliard"),
new ScaleUnit(42, "tredecillion", "septillion"),
new ScaleUnit(39, "duodecillion", "sextilliard"),
new ScaleUnit(36, "undecillion", "sextillion"),
new ScaleUnit(33, "decillion", "quintilliard"),
new ScaleUnit(30, "nonillion", "quintillion"),
new ScaleUnit(27, "octillion", "quadrilliard"),
new ScaleUnit(24, "septillion", "quadrillion"),
new ScaleUnit(21, "sextillion", "trilliard"),
new ScaleUnit(18, "quintillion", "trillion"),
new ScaleUnit(15, "quadrillion", "billiard"),
new ScaleUnit(12, "trillion", "billion"),
new ScaleUnit(9, "billion", "milliard"),
new ScaleUnit(6, "million", "million"),
new ScaleUnit(3, "thousand", "thousand"),
new ScaleUnit(2, "hundred", "hundred"),
// new ScaleUnit(1, "ten", "ten"),
// new ScaleUnit(0, "one", "one"),
new ScaleUnit(-1, "tenth", "tenth"), new ScaleUnit(-2, "hundredth", "hundredth"),
new ScaleUnit(-3, "thousandth", "thousandth"),
new ScaleUnit(-4, "ten-thousandth", "ten-thousandth"),
new ScaleUnit(-5, "hundred-thousandth", "hundred-thousandth"),
new ScaleUnit(-6, "millionth", "millionth"),
new ScaleUnit(-7, "ten-millionth", "ten-millionth"),
new ScaleUnit(-8, "hundred-millionth", "hundred-millionth"),
new ScaleUnit(-9, "billionth", "milliardth"),
new ScaleUnit(-10, "ten-billionth", "ten-milliardth"),
new ScaleUnit(-11, "hundred-billionth", "hundred-milliardth"),
new ScaleUnit(-12, "trillionth", "billionth"),
new ScaleUnit(-13, "ten-trillionth", "ten-billionth"),
new ScaleUnit(-14, "hundred-trillionth", "hundred-billionth"),
new ScaleUnit(-15, "quadrillionth", "billiardth"),
new ScaleUnit(-16, "ten-quadrillionth", "ten-billiardth"),
new ScaleUnit(-17, "hundred-quadrillionth", "hundred-billiardth"),
new ScaleUnit(-18, "quintillionth", "trillionth"),
new ScaleUnit(-19, "ten-quintillionth", "ten-trillionth"),
new ScaleUnit(-20, "hundred-quintillionth", "hundred-trillionth"),
new ScaleUnit(-21, "sextillionth", "trilliardth"),
new ScaleUnit(-22, "ten-sextillionth", "ten-trilliardth"),
new ScaleUnit(-23, "hundred-sextillionth", "hundred-trilliardth"),
new ScaleUnit(-24, "septillionth", "quadrillionth"),
new ScaleUnit(-25, "ten-septillionth", "ten-quadrillionth"),
new ScaleUnit(-26, "hundred-septillionth", "hundred-quadrillionth"), };
static public enum Scale {
SHORT, LONG;
public String getName(int exponent) {
for (ScaleUnit unit : SCALE_UNITS) {
if (unit.getExponent() == exponent) {
return unit.getName(this.ordinal());
}
}
return "";
}
}
/**
* Change this scale to support American and modern British value (short scale) or Traditional
* British value (long scale)
*/
static public Scale SCALE = Scale.SHORT;
static abstract public class AbstractProcessor {
static protected final String SEPARATOR = " ";
static protected final int NO_VALUE = -1;
protected List<Integer> getDigits(long value) {
ArrayList<Integer> digits = new ArrayList<Integer>();
if (value == 0) {
digits.add(0);
} else {
while (value > 0) {
digits.add(0, (int) value % 10);
value /= 10;
}
}
return digits;
}
public String getName(long value) {
return getName(Long.toString(value));
}
public String getName(double value) {
return getName(Double.toString(value));
}
abstract public String getName(String value);
}
static public class UnitProcessor extends AbstractProcessor {
static private final String[] TOKENS = new String[] { "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
int offset = NO_VALUE;
int number;
if (value.length() > 3) {
number = Integer.valueOf(value.substring(value.length() - 3), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 100;
if (number < 10) {
offset = (number % 10) - 1;
// number /= 10;
} else if (number < 20) {
offset = (number % 20) - 1;
// number /= 100;
}
if (offset != NO_VALUE && offset < TOKENS.length) {
buffer.append(TOKENS[offset]);
}
return buffer.toString();
}
}
static public class TensProcessor extends AbstractProcessor {
static private final String[] TOKENS = new String[] { "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
static private final String UNION_SEPARATOR = "-";
private UnitProcessor unitProcessor = new UnitProcessor();
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
boolean tensFound = false;
int number;
if (value.length() > 3) {
number = Integer.valueOf(value.substring(value.length() - 3), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 100; // keep only two digits
if (number >= 20) {
buffer.append(TOKENS[(number / 10) - 2]);
number %= 10;
tensFound = true;
} else {
number %= 20;
}
if (number != 0) {
if (tensFound) {
buffer.append(UNION_SEPARATOR);
}
buffer.append(unitProcessor.getName(number));
}
return buffer.toString();
}
}
static public class HundredProcessor extends AbstractProcessor {
private int EXPONENT = 2;
private UnitProcessor unitProcessor = new UnitProcessor();
private TensProcessor tensProcessor = new TensProcessor();
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
int number;
if ("".equals(value)) {
number = 0;
} else if (value.length() > 4) {
number = Integer.valueOf(value.substring(value.length() - 4), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 1000; // keep at least three digits
if (number >= 100) {
buffer.append(unitProcessor.getName(number / 100));
buffer.append(SEPARATOR);
buffer.append(SCALE.getName(EXPONENT));
}
String tensName = tensProcessor.getName(number % 100);
if (!"".equals(tensName) && (number >= 100)) {
buffer.append(SEPARATOR);
}
buffer.append(tensName);
return buffer.toString();
}
}
static public class CompositeBigProcessor extends AbstractProcessor {
private HundredProcessor hundredProcessor = new HundredProcessor();
private AbstractProcessor lowProcessor;
private int exponent;
public CompositeBigProcessor(int exponent) {
if (exponent <= 3) {
lowProcessor = hundredProcessor;
} else {
lowProcessor = new CompositeBigProcessor(exponent - 3);
}
this.exponent = exponent;
}
public String getToken() {
return SCALE.getName(getPartDivider());
}
protected AbstractProcessor getHighProcessor() {
return hundredProcessor;
}
protected AbstractProcessor getLowProcessor() {
return lowProcessor;
}
public int getPartDivider() {
return exponent;
}
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
String high, low;
if (value.length() < getPartDivider()) {
high = "";
low = value;
} else {
int index = value.length() - getPartDivider();
high = value.substring(0, index);
low = value.substring(index);
}
String highName = getHighProcessor().getName(high);
String lowName = getLowProcessor().getName(low);
if (!"".equals(highName)) {
buffer.append(highName);
buffer.append(SEPARATOR);
buffer.append(getToken());
if (!"".equals(lowName)) {
buffer.append(SEPARATOR);
}
}
if (!"".equals(lowName)) {
buffer.append(lowName);
}
return buffer.toString();
}
}
static public class DefaultProcessor extends AbstractProcessor {
static private String MINUS = "minus";
static private String UNION_AND = "and";
static private String ZERO_TOKEN = "zero";
private AbstractProcessor processor = new CompositeBigProcessor(63);
@Override
public String getName(String value) {
boolean negative = false;
if (value.startsWith("-")) {
negative = true;
value = value.substring(1);
}
int decimals = value.indexOf(".");
String decimalValue = null;
if (0 <= decimals) {
decimalValue = value.substring(decimals + 1);
value = value.substring(0, decimals);
}
String name = processor.getName(value);
if ("".equals(name)) {
name = ZERO_TOKEN;
} else if (negative) {
name = MINUS.concat(SEPARATOR).concat(name);
}
if (!(null == decimalValue || "".equals(decimalValue))) {
String zeroDecimalValue = "";
for (int i = 0; i < decimalValue.length(); i++) {
zeroDecimalValue = zeroDecimalValue + "0";
}
if (decimalValue.equals(zeroDecimalValue)) {
name = name.concat(SEPARATOR).concat(UNION_AND).concat(SEPARATOR).concat(
"zero").concat(SEPARATOR).concat(
SCALE.getName(-decimalValue.length()));
} else {
name = name.concat(SEPARATOR).concat(UNION_AND).concat(SEPARATOR).concat(
processor.getName(decimalValue)).concat(SEPARATOR).concat(
SCALE.getName(-decimalValue.length()));
}
}
return name;
}
}
static public AbstractProcessor processor;
public static void main(String... args) {
processor = new DefaultProcessor();
long[] values = new long[] { 0, 4, 10, 12, 100, 108, 299, 1000, 1003, 2040, 45213, 100000,
100005, 100010, 202020, 202022, 999999, 1000000, 1000001, 10000000, 10000007,
99999999, Long.MAX_VALUE, Long.MIN_VALUE };
String[] strValues = new String[] { "0", "1.30", "0001.00", "3.141592" };
for (long val : values) {
System.out.println(val + " = " + processor.getName(val));
}
for (String strVal : strValues) {
System.out.println(strVal + " = " + processor.getName(strVal));
}
// generate a very big number...
StringBuilder bigNumber = new StringBuilder();
for (int d = 0; d < 66; d++) {
bigNumber.append((char) ((Math.random() * 10) + '0'));
}
bigNumber.append(".");
for (int d = 0; d < 26; d++) {
bigNumber.append((char) ((Math.random() * 10) + '0'));
}
System.out.println(bigNumber.toString() + " = " + processor.getName(bigNumber.toString()));
}
}
The output is
0 = zero
4 = four
10 = ten
12 = twelve
100 = one hundred
108 = one hundred eight
299 = two hundred ninety-nine
1000 = one thousand
1003 = one thousand three
2040 = two thousand fourty
45213 = fourty-five thousand two hundred thirteen
100000 = one hundred thousand
100005 = one hundred thousand five
100010 = one hundred thousand ten
202020 = two hundred two thousand twenty
202022 = two hundred two thousand twenty-two
999999 = nine hundred ninety-nine thousand nine hundred ninety-nine
1000000 = one million
1000001 = one million one
10000000 = ten million
10000007 = ten million seven
99999999 = ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine
9223372036854775807 = nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred seven
-9223372036854775808 = minus nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred eight
0.0 = zero and zero tenth
1.30 = one and thirty hundredth
0001.00 = one and zero hundredth
3.141592 = three and one hundred fourty-one thousand five hundred ninety-two millionth
354064188376576616844741830273568537829518115677552666352927559274.76892492652888527014418647 = three hundred fifty-four vigintillion sixty-four novemdecillion one hundred eighty-eight octodecillion three hundred seventy-six septendecillion five hundred seventy-six sexdecillion six hundred sixteen quindecillion eight hundred fourty-four quattuordecillion seven hundred fourty-one tredecillion eight hundred thirty duodecillion two hundred seventy-three undecillion five hundred sixty-eight decillion five hundred thirty-seven nonillion eight hundred twenty-nine octillion five hundred eighteen septillion one hundred fifteen sextillion six hundred seventy-seven quintillion five hundred fifty-two quadrillion six hundred sixty-six trillion three hundred fifty-two billion nine hundred twenty-seven million five hundred fifty-nine thousand two hundred seventy-four and seventy-six septillion eight hundred ninety-two sextillion four hundred ninety-two quintillion six hundred fifty-two quadrillion eight hundred eighty-eight trillion five hundred twenty-seven billion fourteen million four hundred eighteen thousand six hundred fourty-seven hundred-septillionth
How to replace a string in a SQL Server Table Column
all answers are great but I just want to give you a good example
select replace('this value from table', 'table', 'table but updated')
this SQL statement will replace the existence of the word "table"
(second parameter) inside the given statement(first parameter) with the third parameter
the initial value is this value from table
but after executing replace function it will be this value from table but updated
and here is a real example
UPDATE publication
SET doi = replace(doi, '10.7440/perifrasis', '10.25025/perifrasis')
WHERE doi like '10.7440/perifrasis%'
for example if we have this value
10.7440/perifrasis.2010.1.issue-1
it will become
10.25025/perifrasis.2010.1.issue-1
hope this gives you better visualization
Check if string is upper, lower, or mixed case in Python
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
Mysql adding user for remote access
In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:
my.cnf (my.ini on windows)
#Replace xxx with your IP Address
bind-address = xxx.xxx.xxx.xxx
then
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';
Then
GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;
Depending on your OS you may have to open port 3306 to allow remote connections.
SQL Query - Concatenating Results into One String
If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF
trick:
DECLARE @CodeNameString varchar(100)
SELECT
@CodeNameString = STUFF( (SELECT ',' + CodeName
FROM dbo.AccountCodes
ORDER BY Sort
FOR XML PATH('')),
1, 1, '')
The FOR XML PATH('')
basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3
etc.) and the STUFF
puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.
UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <
, >
or &
, then my current solution will in fact encode those into <
, >
, and &
.
If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.
Detect Scroll Up & Scroll down in ListView
Here is a working modified version from some of the above-indicated solutions.
Add another class ListView:
package com.example.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
public class ListView extends android.widget.ListView {
private OnScrollListener onScrollListener;
private OnDetectScrollListener onDetectScrollListener;
public ListView(Context context) {
super(context);
onCreate(context, null, null);
}
public ListView(Context context, AttributeSet attrs) {
super(context, attrs);
onCreate(context, attrs, null);
}
public ListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onCreate(context, attrs, defStyle);
}
@SuppressWarnings("UnusedParameters")
private void onCreate(Context context, AttributeSet attrs, Integer defStyle) {
setListeners();
}
private void setListeners() {
super.setOnScrollListener(new OnScrollListener() {
private int oldTop;
private int oldFirstVisibleItem;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (onScrollListener != null) {
onScrollListener.onScrollStateChanged(view, scrollState);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (onScrollListener != null) {
onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
if (onDetectScrollListener != null) {
onDetectedListScroll(view, firstVisibleItem);
}
}
private void onDetectedListScroll(AbsListView absListView, int firstVisibleItem) {
View view = absListView.getChildAt(0);
int top = (view == null) ? 0 : view.getTop();
if (firstVisibleItem == oldFirstVisibleItem) {
if (top > oldTop) {
onDetectScrollListener.onUpScrolling();
} else if (top < oldTop) {
onDetectScrollListener.onDownScrolling();
}
} else {
if (firstVisibleItem < oldFirstVisibleItem) {
onDetectScrollListener.onUpScrolling();
} else {
onDetectScrollListener.onDownScrolling();
}
}
oldTop = top;
oldFirstVisibleItem = firstVisibleItem;
}
});
}
@Override
public void setOnScrollListener(OnScrollListener onScrollListener) {
this.onScrollListener = onScrollListener;
}
public void setOnDetectScrollListener(OnDetectScrollListener onDetectScrollListener) {
this.onDetectScrollListener = onDetectScrollListener;
}
}
And an interface:
public interface OnDetectScrollListener {
void onUpScrolling();
void onDownScrolling();
}
And finally how to use:
com.example.view.ListView listView = (com.example.view.ListView) findViewById(R.id.list);
listView.setOnDetectScrollListener(new OnDetectScrollListener() {
@Override
public void onUpScrolling() {
/* do something */
}
@Override
public void onDownScrolling() {
/* do something */
}
});
In your XML layout:
<com.example.view.ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
This is my first topic, do not judge me harshly. =)
PHP, display image with Header()
Though weirdly named, you can use the getimagesize()
function. This will also give you mime information:
Array
(
[0] => 295 // width
[1] => 295 // height
[2] => 3 // http://php.net/manual/en/image.constants.php
[3] => width="295" height="295" // width and height as attr's
[bits] => 8
[mime] => image/png
)
Comparing two joda DateTime instances
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
How to copy a java.util.List into another java.util.List
Starting from Java 10:
List<E> oldList = List.of();
List<E> newList = List.copyOf(oldList);
List.copyOf()
returns an unmodifiable List
containing the elements of the given Collection
.
The given Collection
must not be null
, and it must not contain any null
elements.
Also, if you want to create a deep copy of a List
, you can find many good answers here.
JSON to string variable dump
something along this?
function dump(x, indent) {
var indent = indent || '';
var s = '';
if (Array.isArray(x)) {
s += '[';
for (var i=0; i<x.length; i++) {
s += dump(x[i], indent)
if (i < x.length-1) s += ', ';
}
s +=']';
} else if (x === null) {
s = 'NULL';
} else switch(typeof x) {
case 'undefined':
s += 'UNDEFINED';
break;
case 'object':
s += "{ ";
var first = true;
for (var p in x) {
if (!first) s += indent + ' ';
s += p + ': ';
s += dump(x[p], indent + ' ');
s += "\n"
first = false;
}
s += '}';
break;
case 'boolean':
s += (x) ? 'TRUE' : 'FALSE';
break;
case 'number':
s += x;
break;
case 'string':
s += '"' + x + '"';
break;
case 'function':
s += '<FUNCTION>';
break;
default:
s += x;
break;
}
return s;
}
Event handlers for Twitter Bootstrap dropdowns?
Try this:
$('div.btn-group ul.dropdown-menu li a').click(function (e) {
var $div = $(this).parent().parent().parent();
var $btn = $div.find('button');
$btn.html($(this).text() + ' <span class="caret"></span>');
$div.removeClass('open');
e.preventDefault();
return false;
});
Standardize data columns in R
Use the package "recommenderlab". Download and install the package.
This package has a command "Normalize" in built. It also allows you to choose one of the many methods for normalization namely 'center' or 'Z-score'
Follow the following example:
## create a matrix with ratings
m <- matrix(sample(c(NA,0:5),50, replace=TRUE, prob=c(.5,rep(.5/6,6))),nrow=5, ncol=10, dimnames = list(users=paste('u', 1:5, sep=”), items=paste('i', 1:10, sep=”)))
## do normalization
r <- as(m, "realRatingMatrix")
#here, 'centre' is the default method
r_n1 <- normalize(r)
#here "Z-score" is the used method used
r_n2 <- normalize(r, method="Z-score")
r
r_n1
r_n2
## show normalized data
image(r, main="Raw Data")
image(r_n1, main="Centered")
image(r_n2, main="Z-Score Normalization")
iterating and filtering two lists using java 8
if you have class with id and you want to filter by id
line1 : you mape all the id
line2: filter what is not exist in the map
Set<String> mapId = entityResponse.getEntities().stream().map(Entity::getId).collect(Collectors.toSet());
List<String> entityNotExist = entityValues.stream().filter(n -> !mapId.contains(n.getId())).map(DTOEntity::getId).collect(Collectors.toList());
Get free disk space
DriveInfo will help you with some of those (but it doesn't work with UNC paths), but really I think you will need to use GetDiskFreeSpaceEx. You can probably achieve some functionality with WMI. GetDiskFreeSpaceEx looks like your best bet.
Chances are you will probably have to clean up your paths to get it to work properly.
Android: Clear the back stack
i called activity_name.this.finish()
after starting new intent and it worked for me.
I tried "FLAG_ACTIVITY_CLEAR_TOP" and "FLAG_ACTIVITY_NEW_TASK"
But it won't work for me... I am not suggesting this solution for use but if setting flag won't work for you than you can try this..But still i recommend don't use it
How to execute a stored procedure within C# program
Using Dapper. so i added this i hope anyone help.
public void Insert(ProductName obj)
{
SqlConnection connection = new SqlConnection(Connection.GetConnectionString());
connection.Open();
connection.Execute("ProductName_sp", new
{ @Name = obj.Name, @Code = obj.Code, @CategoryId = obj.CategoryId, @CompanyId = obj.CompanyId, @ReorderLebel = obj.ReorderLebel, @logo = obj.logo,@Status=obj.Status, @ProductPrice = obj.ProductPrice,
@SellingPrice = obj.SellingPrice, @VatPercent = obj.VatPercent, @Description=obj.Description, @ColourId = obj.ColourId, @SizeId = obj.SizeId,
@BrandId = obj.BrandId, @DisCountPercent = obj.DisCountPercent, @CreateById =obj.CreateById, @StatementType = "Create" }, commandType: CommandType.StoredProcedure);
connection.Close();
}
React Error: Target Container is not a DOM Element
webpack solution
If you got this error while working in React with webpack and HMR.
You need to create template index.html
and save it in src
folder:
<html>
<body>
<div id="root"></root>
</body>
</html>
Now when we have template with id="root"
we need to tell webpack to generate index.html which will mirror our index.html
file.
To do that:
plugins: [
new HtmlWebpackPlugin({
title: "Application name",
template: './src/index.html'
})
],
template
property will tell webpack how to build index.html
file.
How can I add an item to a SelectList in ASP.net MVC
This is possible.
//Create the select list item you want to add
SelectListItem selListItem = new SelectListItem() { Value = "null", Text = "Select One" };
//Create a list of select list items - this will be returned as your select list
List<SelectListItem> newList = new List<SelectListItem>();
//Add select list item to list of selectlistitems
newList.Add(selListItem);
//Return the list of selectlistitems as a selectlist
return new SelectList(newList, "Value", "Text", null);
Efficiency of Java "Double Brace Initialization"?
Efficiency aside, I rarely find myself wishing for declarative collection creation outside of unit tests. I do believe that the double brace syntax is very readable.
Another way to achieve the declarative construction of lists specifically is to use Arrays.asList(T ...)
like so:
List<String> aList = Arrays.asList("vanilla", "strawberry", "chocolate");
The limitation of this approach is of course that you cannot control the specific type of list to be generated.
Prevent HTML5 video from being downloaded (right-click saved)?
@Clayton-Graul had what I was looking for, except I needed the CoffeeScript version for a site using AngularJS. Just in case you need that too, here's what you put in the AngularJS controller in question:
# This is how to we do JQuery ready() dom stuff
$ ->
# let's hide those annoying download video options.
# of course anyone who knows how can still download
# the video, but hey... more power to 'em.
$('#my-video').bind 'contextmenu', ->
false
"strange things are afoot at the circle k" (it's true)
How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)
I have been hit by an issue during uninstall of Node.js on my mac. I had some strange behavior like npm
is still their even after having removing it with all this.
It was because I had an old install done with macport. So you also have to uninstall it using port:
sudo port uninstall nodejs
It may have install many different versions of Node.js so uninstall them all (one by one).
Return value from a VBScript function
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
Best Practices: working with long, multiline strings in PHP?
you can also use:
<?php
ob_start();
echo "some text";
echo "\n";
// you can also use:
?>
some text can be also written here, or maybe HTML:
<div>whatever<\div>
<?php
echo "you can basically write whatever you want";
// and then:
$long_text = ob_get_clean();
What is the best way to trigger onchange event in react js
I know this answer comes a little late but I recently faced a similar problem. I wanted to trigger an event on a nested component. I had a list with radio and check box type widgets (they were divs that behaved like checkboxes and/or radio buttons) and in some other place in the application, if someone closed a toolbox, I needed to uncheck one.
I found a pretty simple solution, not sure if this is best practice but it works.
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
var node = document.getElementById('nodeMyComponentsEventIsConnectedTo');
node.dispatchEvent(event);
This triggered the click event on the domNode and my handler attached via react was indeed called so it behaves like I would expect if someone clicked on the element. I have not tested onChange but it should work, and not sure how this will fair in really old versions of IE but I believe the MouseEvent is supported in at least IE9 and up.
I eventually moved away from this for my particular use case because my component was very small (only a part of my application used react since i'm still learning it) and I could achieve the same thing another way without getting references to dom nodes.
UPDATE:
As others have stated in the comments, it is better to use this.refs.refname
to get a reference to a dom node. In this case, refname is the ref you attached to your component via <MyComponent ref='refname' />
.
Check if a number is int or float
Use isinstance.
>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True
So:
>>> if isinstance(x, int):
print 'x is a int!'
x is a int!
_EDIT:_
As pointed out, in case of long integers, the above won't work. So you need to do:
>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False
How to draw a filled circle in Java?
/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
g.setColor(Color.RED);
g.fillOval(50,50,20,20);
}
g.fillOval(x-axis,y-axis,width,height);
Automatically create requirements.txt
If Facing the same issue as mine i.e. not on the virtual environment and wants requirements.txt for a specific project or from the selected folder(includes children) and pipreqs is not supporting.
You can use :
import os
import sys
from fuzzywuzzy import fuzz
import subprocess
path = "C:/Users/Username/Desktop/DjangoProjects/restAPItest"
files = os.listdir(path)
pyfiles = []
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.py'):
pyfiles.append(os.path.join(root, file))
stopWords = ['from', 'import',',','.']
importables = []
for file in pyfiles:
with open(file) as f:
content = f.readlines()
for line in content:
if "import" in line:
for sw in stopWords:
line = ' '.join(line.split(sw))
importables.append(line.strip().split(' ')[0])
importables = set(importables)
subprocess.call(f"pip freeze > {path}/requirements.txt", shell=True)
with open(path+'/requirements.txt') as req:
modules = req.readlines()
modules = {m.split('=')[0].lower() : m for m in modules}
notList = [''.join(i.split('_')) for i in sys.builtin_module_names]+['os']
new_requirements = []
for req_module in importables:
try :
new_requirements.append(modules[req_module])
except KeyError:
for k,v in modules.items():
if len(req_module)>1 and req_module not in notList:
if fuzz.partial_ratio(req_module,k) > 90:
new_requirements.append(modules[k])
new_requirements = [i for i in set(new_requirements)]
new_requirements
with open(path+'/requirements.txt','w') as req:
req.write(''.join(new_requirements))
P.S: It may have a few additional libraries as it checks on fuzzylogic.
Using LINQ to remove elements from a List<T>
This is a very old question, but I found a really simple way to do this:
authorsList = authorsList.Except(authors).ToList();
Note that since the return variable authorsList
is a List<T>
, the IEnumerable<T>
returned by Except()
must be converted to a List<T>
.
Multiple radio button groups in one form
This is very simple you need to keep different names of every radio input group.
_x000D_
_x000D_
<input type="radio" name="price">Thousand<br>_x000D_
<input type="radio" name="price">Lakh<br>_x000D_
<input type="radio" name="price">Crore_x000D_
_x000D_
</br><hr>_x000D_
_x000D_
<input type="radio" name="gender">Male<br>_x000D_
<input type="radio" name="gender">Female<br>_x000D_
<input type="radio" name="gender">Other
_x000D_
_x000D_
_x000D_
I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"
As shown below, range
only supports integers:
>>> range(15.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>
However, c/10
is a float because /
always returns a float.
Before you put it in range
, you need to make c/10
an integer. This can be done by putting it in int
:
range(int(c/10))
or by using //
, which returns an integer:
range(c//10)
Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java
Java 8 Stream API
can be used for the purpose,
ArrayList<String> list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
list1.add("A");
list1.add("D");
list1.add("G");
ArrayList<String> list2 = new ArrayList<>();
list2.add("B");
list2.add("D");
list2.add("E");
list2.add("G");
List<String> noDup = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
noDup.forEach(System.out::println);
En passant, it shouldn't be forgetten that distinct()
makes use of hashCode()
.
How to parse XML using vba
You can use a XPath Query:
Dim objDom As Object '// DOMDocument
Dim xmlStr As String, _
xPath As String
xmlStr = _
"<PointN xsi:type='typens:PointN' " & _
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " & _
"xmlns:xs='http://www.w3.org/2001/XMLSchema'> " & _
" <X>24.365</X> " & _
" <Y>78.63</Y> " & _
"</PointN>"
Set objDom = CreateObject("Msxml2.DOMDocument.3.0") '// Using MSXML 3.0
'/* Load XML */
objDom.LoadXML xmlStr
'/*
' * XPath Query
' */
'/* Get X */
xPath = "/PointN/X"
Debug.Print objDom.SelectSingleNode(xPath).text
'/* Get Y */
xPath = "/PointN/Y"
Debug.Print objDom.SelectSingleNode(xPath).text
get jquery `$(this)` id
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
Live example
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
Live example
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
How to multiply duration by integer?
In Go, you can multiply variables of same type, so you need to have both parts of the expression the same type.
The simplest thing you can do is casting an integer to duration before multiplying, but that would violate unit semantics. What would be multiplication of duration by duration in term of units?
I'd rather convert time.Millisecond to an int64, and then multiply it by the number of milliseconds, then cast to time.Duration:
time.Duration(int64(time.Millisecond) * int64(rand.Int31n(1000)))
This way any part of the expression can be said to have a meaningful value according to its type. int64(time.Millisecond)
part is just a dimensionless value - the number of smallest units of time in the original value.
If walk a slightly simpler path:
time.Duration(rand.Int31n(1000)) * time.Millisecond
The left part of multiplication is nonsense - a value of type "time.Duration", holding something irrelevant to its type:
numberOfMilliseconds := 100
// just can't come up with a name for following:
someLHS := time.Duration(numberOfMilliseconds)
fmt.Println(someLHS)
fmt.Println(someLHS*time.Millisecond)
And it's not just semantics, there is actual functionality associated with types.
This code prints:
100ns
100ms
Interestingly, the code sample here uses the simplest code, with the same misleading semantics of Duration conversion: https://golang.org/pkg/time/#Duration
seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
How to run an .ipynb Jupyter Notebook from terminal?
In my case, the command that best suited me was:
jupyter nbconvert --execute --clear-output <notebook>.ipynb
Why? This command does not create extra files (just like a .py
file) and the output of the cells is overwritten everytime the notebook is executed.
If you run:
jupyter nbconvert --help
--clear-output
Clear output of current file and save in place, overwriting the existing notebook.
Getting HTML elements by their attribute names
Yes, the function is querySelectorAll
(or querySelector
for a single element), which allows you to use CSS selectors to find elements.
document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property="value"]'); // All with "property" set to "value" exactly.
(Complete list of attribute selectors on MDN.)
This finds all elements with the attribute property. It would be better to specify a tag name if possible:
document.querySelectorAll('span[property]');
You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:
var withProperty = [],
els = document.getElementsByTagName('span'), // or '*' for all types of element
i = 0;
for (i = 0; i < els.length; i++) {
if (els[i].hasAttribute('property')) {
withProperty.push(els[i]);
}
}
Libraries such as jQuery handle this for you; it's probably a good idea to let them do the heavy lifting.
For anyone dealing with ancient browsers, note that querySelectorAll
was introduced to Internet Explorer in v8 (2009) and fully supported in IE9. All modern browsers support it.
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true
In Sender
- Declare params to be sent. We can send String, Object,…
Sender.xhtml
<f:metadata>
<f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
- We’re going send param ID, it will be included with
“includeViewParams=true”
in return String of click button event
Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrData
Sender.xhtml
<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
<p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="??"
ajax="false"/>
</p:dataTable>
In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID
Sender_MB.java
public String clickBtnDetail(sender_DTO sender_dto) {
this._strID = sender_dto.getStrID();
return "Receiver?faces-redirect=true&includeViewParams=true";
}
The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*
In Recever
- Get viewParam
Receiver.xhtml
In Receiver we declare f:viewParam to get param from get request (receive), the name of param of receiver must be the same with sender (page)
Receiver.xhtml
<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>
It will get param ID from sender View and assign to receiver_MB._strID
- Use viewParam
In Receiver, we want to use this param in sql query before the page render, so that we use preRenderView event. We are not going to use constructor because constructor will be invoked before viewParam is received
So that we add
Receiver.xhtml
<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />
into f:metadata tag
Receiver.xhtml
<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
type="preRenderView" />
</f:metadata>
Now we want to use this param in our read database method, it is available to use
Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
if (FacesContext.getCurrentInstance().isPostback()) {
return;
}
readFromDatabase();
}
private void readFromDatabase() {
//use _strID to read and set property
}
How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?
fix json values,
it's add \ before u{xxx} to all +" "
$item = preg_replace_callback('/"(.+?)":"(u.+?)",/', function ($matches) {
$matches[2] = preg_replace('/(u)/', '\u', $matches[2]);
$matches[2] = preg_replace('/(")/', '"', $matches[2]);
$matches[2] = json_decode('"' . $matches[2] . '"');
return '"' . $matches[1] . '":"' . $matches[2] . '",';
}, $item);
Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?
I am answering this for the benefit of future community users. There were multiple issues. If you encounter this problem, I suggest you look for the following:
- Make sure your tnsnames.ora is complete and has the databases you wish to connect to
- Make sure you can tnsping the server you wish to connect to
- On the server, make sure it will be open on the port you desire with the specific application you are using.
Once I did these three things, I solved my problem.
Can constructors throw exceptions in Java?
Absolutely.
If the constructor doesn't receive valid input, or can't construct the object in a valid manner, it has no other option but to throw an exception and alert its caller.
Call Stored Procedure within Create Trigger in SQL Server
The following should do the trick - Only SqlServer
Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN
SET NOCOUNT ON;
Declare @id int
DECLARE @cDate as DateTime
set @cDate =(select Getdate())
select @id=deleted.Catagory_id from deleted
print @cDate
execute dbo.psp_Update_Category @id
END
Alter PROCEDURE dbo.psp_Update_Category
@id int
AS
BEGIN
DECLARE @cDate as DateTime
set @cDate =(select Getdate())
--Update Catagory_Master Set Modify_date=''+@cDate+'' Where Catagory_ID=@id --@UserID
Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END
Http Servlet request lose params from POST body after read it once
First of all we should not read parameters within the filter. Usually the headers are read in the filter to do few authentication tasks. Having said that one can read the HttpRequest body completely in the Filter or Interceptor by using the CharStreams:
String body = com.google.common.io.CharStreams.toString(request.getReader());
This does not affect the subsequent reads at all.
Warning: mysqli_query() expects parameter 1 to be mysqli, resource given
You are mixing mysqli and mysql extensions, which will not work.
You need to use
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");
mysqli
has many improvements over the original mysql
extension, so it is recommended that you use mysqli
.
Calculating Distance between two Latitude and Longitude GeoCoordinates
Calculating Distance between Latitude and Longitude points...
double Lat1 = Convert.ToDouble(latitude);
double Long1 = Convert.ToDouble(longitude);
double Lat2 = 30.678;
double Long2 = 45.786;
double circumference = 40000.0; // Earth's circumference at the equator in km
double distance = 0.0;
double latitude1Rad = DegreesToRadians(Lat1);
double latititude2Rad = DegreesToRadians(Lat2);
double longitude1Rad = DegreesToRadians(Long1);
double longitude2Rad = DegreesToRadians(Long2);
double logitudeDiff = Math.Abs(longitude1Rad - longitude2Rad);
if (logitudeDiff > Math.PI)
{
logitudeDiff = 2.0 * Math.PI - logitudeDiff;
}
double angleCalculation =
Math.Acos(
Math.Sin(latititude2Rad) * Math.Sin(latitude1Rad) +
Math.Cos(latititude2Rad) * Math.Cos(latitude1Rad) * Math.Cos(logitudeDiff));
distance = circumference * angleCalculation / (2.0 * Math.PI);
return distance;
How to stop a setTimeout loop?
Try something like this in case you want to stop the loop from inside the function:
let timer = setInterval(function(){
// Have some code to do something
if(/*someStopCondition*/){
clearInterval(timer)
}
},1000);
You can also wrap this inside a another function, just make sure you have a timer variable and use clearInterval(theTimerVariable) to stop the loop
What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?
Data type Range Storage
bigint -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) 8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes
smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes
tinyint 0 to 255 1 Byte
Example
The following example creates a table using the bigint, int, smallint, and tinyint data types. Values are inserted into each column and returned in the SELECT statement.
CREATE TABLE dbo.MyTable
(
MyBigIntColumn bigint
,MyIntColumn int
,MySmallIntColumn smallint
,MyTinyIntColumn tinyint
);
GO
INSERT INTO dbo.MyTable VALUES (9223372036854775807, 214483647,32767,255);
GO
SELECT MyBigIntColumn, MyIntColumn, MySmallIntColumn, MyTinyIntColumn
FROM dbo.MyTable;
How do I make a self extract and running installer
Okay I have got it working, hope this information is useful.
First of all I now realize that not only do self-extracting zip start extracting with doubleclick, but they require no extraction application to be installed on the users computer because the extractor code is in the archive itself. This means that you will get a different user experience depending on what you application you use to create the sfx
I went with WinRar as follows, this does not require you to create an sfx file, everything can be created via the gui:
- Select files, right click and select Add to Archive
- Use Browse.. to create the archive in the folder above
- Change Archive Format to Zip
- Enable Create SFX archive
- Select Advanced tab
- Select SFX Options
- Select Setup tab
- Enter setup.exe into the Run after Extraction field
- Select Modes tab
- Enable Unpack to temporary folder
- Select text and Icon tab
- Enter a more appropriate title for your task
- Select OK
- Select OK
The resultant exe unzips to a temporary folder and then starts the installer
List Git aliases
The following works under Linux, MacOSX and Windows (with msysgit).
Use git la to show aliases in .gitconfig
Did I hear 'bash scripting'? ;)
About the 'not needed' part in a comment above, I basically created a man page like overview for my aliases. Why all the fuss? Isn't that complete overkill?
Read on...
I have set the commands like this in my .gitconfig, separated like TAB=TAB:
[alias]
alias1 = foo -x -y --z-option
alias2 = bar -y --z-option --set-something
and simply defined another alias to grep the TAB= part of the defined aliases. (All other options don't have tabs before and after the '=' in their definition, just spaces.)
Comments not appended to an alias also have a TAB===== appended, so they are shown after grepping.
For better viewing I am piping the grep output into less, like this:
basic version: (black/white)
#.gitconfig
[alias]
# use 'git h <command>' for help, use 'git la' to list aliases =====
h = help #... <git-command-in-question>
la = "!grep '\t=' ~/.gitconfig | less"
The '\t=
' part matches TAB=.
To have an even better overview of what aliases I have, and since I use the bash console, I colored the output with terminal colors:
- all '=' are printed in red
- all '#' are printed in green
advanced version: (colored)
la = "!grep '\t=' ~/.gitconfig | sed -e 's/=/^[[0;31m=^[[0m/g' | sed -e 's/#.*/^[[0;32m&^[[0m/g' | less -R"
Basically the same as above, just sed usage is added to get the color codes into the output.
The -R
flag of less is needed to get the colors shown in less.
(I recently found out, that long commands with a scrollbar under their window are not shown correctly on mobile devices: They text is cut off and the scrollbar is simply missing. That might be the case with the last code snippet here, keep that in mind when looking at code snippets here while on the go.)
Why get such magic to work?
I have a like half a mile of aliases, tailored to my needs.
Also some of them change over time, so after all the best idea to have an up-to-date list at hand is parsing the .gitconfig.
A ****short**** excerpt from my .gitconfig aliases:
# choose =====
a = add #...
aa = add .
ai = add -i
# unchoose =====
rm = rm -r #... unversion and delete
rmc = rm -r --cached #... unversion, but leave in working copy
# do =====
c = commit -m #...
fc = commit -am "fastcommit"
ca = commit -am #...
mc = commit # think 'message-commit'
mca = commit -a
cam = commit --amend -C HEAD # update last commit
# undo =====
r = reset --hard HEAD
rv = revert HEAD
In my linux or mac workstations also further aliases exist in the .bashrc's, sort of like:
#.bashrc
alias g="git"
alias gh="git h"
alias gla="git la"
function gc { git c "$*" } # this is handy, just type 'gc this is my commitmessage' at prompt
That way no need to type git help submodule
, no need for git h submodule
, just gh submodule
is all that is needed to get the help. It is just some characters, but how often do you type them?
I use all of the following, of course only with shortcuts...
- add
- commit
- commit --amend
- reset --hard HEAD
- push
- fetch
- rebase
- checkout
- branch
- show-branch (in a lot of variations)
- shortlog
- reflog
- diff (in variations)
- log (in a lot of variations)
- status
- show
- notes
- ...
This was just from the top of my head.
I often have to use git without a gui, since a lot of the git commands are not implemented properly in any of the graphical frontends. But everytime I put them to use, it is mostly in the same manner.
On the 'not implemented' part mentioned in the last paragraph:
I have yet to find something that compares to this in a GUI:
sba = show-branch --color=always -a --more=10 --no-name
- show all local and remote branches as well as the commits they have within them
ccm = "!git reset --soft HEAD~ && git commit"
- change last commit message
From a point of view that is more simple:
How often do you type git add .
or git commit -am "..."
? Not counting even the rest...
Getting things to work like git aa
or git ca "..."
in windows,
or with bash aliases gaa
/g aa
or gca "..."
/g ca "..."
in linux and on mac's...
For my needs it seemed a smart thing to do, to tailor git commands like this...
... and for easier use I just helped myself for lesser used commands, so i dont have to consult the man pages everytime. Commands are predefined and looking them up is as easy as possible.
I mean, we are programmers after all? Getting things to work like we need them is our job.
Here is an additional screenshot, this works in Windows:
BONUS: If you are on linux or mac, colorized man pages can help you quite a bit:
colorized man pages
Convert line endings
Doing this with POSIX is tricky:
POSIX Sed does not support \r
or \15
. Even if it did, the in place
option -i
is not POSIX
POSIX Awk does support \r
and \15
, however the -i inplace
option
is not POSIX
d2u and dos2unix are not POSIX utilities, but ex is
POSIX ex does not support \r
, \15
, \n
or \12
To remove carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file
To add carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file
Is there a difference between "==" and "is"?
is
will return True
if two variables point to the same object, ==
if the objects referred to by the variables are equal.
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
# Make a new copy of list `a` via the slice operator,
# and assign it to variable `b`
>>> b = a[:]
>>> b is a
False
>>> b == a
True
In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
The same holds true for string literals:
>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True
Please see this question as well.
How to create a signed APK file using Cordova command line interface?
First Check your version code and version name if you are updating your app. And make sure you have a previous keystore.
If you are updating app then follow step 1,3,4.
Step 1:
Goto your cordova project for generate our release build:
D:\projects\Phonegap\Example> cordova build --release android
Then, we can find our unsigned APK file in platforms/android/ant-build. In our example, the file was
if u used ant-build
yourproject/platforms/android/ant-build/Example-release-unsigned.apk
OR
if u used gradle-build
yourProject/platforms/android/build/outputs/apk/Example-release-unsigned.apk
Step 2:
Key Generation:
Syntax:
keytool -genkey -v -keystore <keystoreName>.keystore -alias <Keystore AliasName> -keyalg <Key algorithm> -keysize <Key size> -validity <Key Validity in Days>
if keytool command not recognize do this step
Check that the directory the keytool executable is in is on your path. (For example, on my Windows 7 machine, it's in C:\Program Files (x86)\Java\jre6\bin.)
Example:
keytool -genkey -v -keystore NAME-mobileapps.keystore -alias NAMEmobileapps -keyalg RSA -keysize 2048 -validity 10000
keystore password? : xxxxxxx
What is your first and last name? : xxxxxx
What is the name of your organizational unit? : xxxxxxxx
What is the name of your organization? : xxxxxxxxx
What is the name of your City or Locality? : xxxxxxx
What is the name of your State or Province? : xxxxx
What is the two-letter country code for this unit? : xxx
Then the Key store has been generated with name as NAME-mobileapps.keystore
Step 3:
Place the generated keystore in
D:\projects\Phonegap\Example\platforms\android\ant-build
To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:
Syntax:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <keystorename <Unsigned APK file> <Keystore Alias name>
If it doesn't reconize do these steps
(1) Right click on "This PC" > right-click Properties > Advanced system settings > Environment Variables > select PATH then EDIT.
(2) Add your jdk bin folder path to environment variables, it should look like this:
"C:\Program Files\Java\jdk1.8.0_40\bin".
Example:
D:\projects\Phonegap\Example\platforms\android\ant-build> jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore NAME-mobileapps.keystore Example-release-unsigned.apk xxxxxmobileapps
Enter KeyPhrase as 'xxxxxxxx'
This signs the apk in place.
Step 4:
Finally, we need to run the zip align tool to optimize the APK:
if zipalign not recognize then
(1) goto your android sdk path and find zipalign it is usually in android-sdk\build-tools\23.0.3
(2) Copy zipalign file paste into your generate release apk folder usually in below path
yourproject/platforms/android/ant-build/Example-release-unsigned.apk
D:\projects\Phonegap\Example\platforms\android\ant-build> zipalign -v 4 Example-release-unsigned.apk Example.apk
OR
D:\projects\Phonegap\Example\platforms\android\ant-build> C:\Phonegap\adt-bundle-windows-x86_64-20140624\sdk\build-tools\android-4.4W\zipalign -v 4 Example-release-unsigned.apk Example.apk
Now we have our final release binary called example.apk and we can release this on the Google Play Store.
Centering the pagination in bootstrap
This this, it worked for me:
Style:
.pagination {
display: flex;
justify-content: center;
}
.pagination li {
display: block;
}
And blade:
<div class="pagination">
{{ $myCollection->render() }}
</div>
How to write std::string to file?
remove the ios::binary
from your modes in your ofstream and use studentPassword.c_str()
instead of (char *)&studentPassword
in your write.write()
Dynamically Add C# Properties at Runtime
you could deserialize your json string into a dictionary and then add new properties then serialize it.
var jsonString = @"{}";
var jsonDoc = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);
jsonDoc.Add("Name", "Khurshid Ali");
Console.WriteLine(JsonSerializer.Serialize(jsonDoc));
How does the 'binding' attribute work in JSF? When and how should it be used?
each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.
- Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
- The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.
http:..../somelink?componentId=123
would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123
The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.
How do I get the different parts of a Flask request's url?
You can examine the url through several Request
fields:
Imagine your application is listening on the following application root:
http://www.example.com/myapplication
And a user requests the following URI:
http://www.example.com/myapplication/foo/page.html?x=y
In this case the values of the above mentioned attributes would be the following:
path /foo/page.html
full_path /foo/page.html?x=y
script_root /myapplication
base_url http://www.example.com/myapplication/foo/page.html
url http://www.example.com/myapplication/foo/page.html?x=y
url_root http://www.example.com/myapplication/
You can easily extract the host part with the appropriate splits.
Using subprocess to run Python script on Windows
How about this:
import sys
import subprocess
theproc = subprocess.Popen("myscript.py", shell = True)
theproc.communicate() # ^^^^^^^^^^^^
This tells subprocess
to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.
Additionally, this will search the PATH for "myscript.py" - which could be desirable.
How to get domain root url in Laravel 4?
My hint:
FIND IF EXISTS in .env:
APP_URL=http://yourhost.dev
REPLACE TO (OR ADD)
APP_DOMAIN=yourhost.dev
FIND in config/app.php:
'url' => env('APP_URL'),
REPLACE TO
'domain' => env('APP_DOMAIN'),
'url' => 'http://' . env('APP_DOMAIN'),
USE:
Config::get('app.domain'); // yourhost.dev
Config::get('app.url') // http://yourhost.dev
Do your magic!
How to convert int to NSString?
Primitives can be converted to objects with @()
expression. So the shortest way is to transform int
to NSNumber
and pick up string representation with stringValue
method:
NSString *strValue = [@(myInt) stringValue];
or
NSString *strValue = @(myInt).stringValue;
extract month from date in python
Alternate solution
Create a column that will store the month:
data['month'] = data['date'].dt.month
Create a column that will store the year:
data['year'] = data['date'].dt.year
How do I check if a string contains another string in Objective-C?
For iOS 8.0+ and macOS 10.10+, you can use NSString's native containsString:
.
For older versions of iOS and macOS, you can create your own (obsolete) category for NSString:
@interface NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring;
@end
// - - - -
@implementation NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring
{
NSRange range = [self rangeOfString : substring];
BOOL found = ( range.location != NSNotFound );
return found;
}
@end
Note: Observe Daniel Galasko's comment below regarding naming
How to mock private method for testing using PowerMock?
With no argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");
With String
argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
.withArguments(anyString()).thenReturn("mocked result");
How to do integer division in javascript (Getting division answer in int not float)?
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be
used, for example, a radix of 16 (hexadecimal) indicates that the
number in the string should be parsed from a hexadecimal number to a
decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
UITableView example for Swift
// UITableViewCell set Identify "Cell"
// UITableView Name is tableReport
UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var tableReport: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Report Name"
return cell;
}
}
Tensorflow installation error: not a supported wheel on this platform
I too got the same problem
I downloaded get-pip.py
from https://bootstrap.pypa.io/get-pip.py
and then ran python2.7 get-pip.py
for installing pip2.7
and then ran the pip install
command with python2.7
as follows
For Ubuntu/Linux:
python2.7 -m pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl
For Mac OS X:
python2.7 -m pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
this should work just fine as it did for me :)
I followed these instructions from here
How to use UIVisualEffectView to Blur Image?
Here is how to use UIVibrancyEffect and UIBlurEffect with UIVisualEffectView
Objective-C:
// Blur effect
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
[blurEffectView setFrame:self.view.bounds];
[self.view addSubview:blurEffectView];
// Vibrancy effect
UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
UIVisualEffectView *vibrancyEffectView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
[vibrancyEffectView setFrame:self.view.bounds];
// Label for vibrant text
UILabel *vibrantLabel = [[UILabel alloc] init];
[vibrantLabel setText:@"Vibrant"];
[vibrantLabel setFont:[UIFont systemFontOfSize:72.0f]];
[vibrantLabel sizeToFit];
[vibrantLabel setCenter: self.view.center];
// Add label to the vibrancy view
[[vibrancyEffectView contentView] addSubview:vibrantLabel];
// Add the vibrancy view to the blur view
[[blurEffectView contentView] addSubview:vibrancyEffectView];
Swift 4:
// Blur Effect
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
view.addSubview(blurEffectView)
// Vibrancy Effect
let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
vibrancyEffectView.frame = view.bounds
// Label for vibrant text
let vibrantLabel = UILabel()
vibrantLabel.text = "Vibrant"
vibrantLabel.font = UIFont.systemFont(ofSize: 72.0)
vibrantLabel.sizeToFit()
vibrantLabel.center = view.center
// Add label to the vibrancy view
vibrancyEffectView.contentView.addSubview(vibrantLabel)
// Add the vibrancy view to the blur view
blurEffectView.contentView.addSubview(vibrancyEffectView)
static and extern global variables in C and C++
Global variables are not extern
nor static
by default on C and C++.
When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern
keyword) you will get a link error (symbol not found).
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and then define it, this time without the extern keyword, on a source file:
Header included by multiple files:
extern int varGlobal;
In one of your source files:
int varGlobal = 7;
How to extract Month from date in R
Her is another R base
approach:
From your example: Some date:
Some_date<-"01/01/1979"
We tell R, "That is a Date"
Some_date<-as.Date(Some_date)
We extract the month:
months(Some_date)
output: [1] "January"
Finally, we can convert it to a numerical variable:
as.numeric(as.factor(months(Some_date)))
outpt: [1] 1
Combine or merge JSON on node.js without jQuery
Underscore's extend
is the easiest and quickest way to achieve this, like James commented.
Here's an example using underscore:
var _ = require('underscore'), // npm install underscore to install
object1 = {name: "John"},
object2 = {location: "San Jose"};
var target = _.extend(object1, object2);
object 1 will get the properties of object2 and be returned and assigned to target.
You could do it like this as well, depending on whether you mind object1 being modified:
var target = {};
_.extend(target, object1, object2);
Keyboard shortcuts in WPF
How to associate the command with a MenuItem
:
<MenuItem Header="My command" Command="{x:Static local:MyWindow.MyCommand}"/>
Change project name on Android Studio
A very quick way to solve this as at November 2020 is by the following steps
hit the shift key twice, a pop up will show search for a file named "settings.gradle"
when it opens change the rootProject.name = "Old-name" to rootProject.name = "new name"
then sync.
hit the shift key twice, a pop up will show search for a file named "string.xml", when
it opens change <string "app_name">old-name to <string "app_name">new-name
close android studio
locate androidStudioProject directory on your machine, open it and find the project by its old name, rename it to the new name.
open Android Studio goto File > Open > "new name". open it from there.
this is currently working on Android Studio 4.1.1
How to count duplicate rows in pandas dataframe?
You can groupby
on all the columns and call size
the index indicates the duplicate values:
In [28]:
df.groupby(df.columns.tolist(),as_index=False).size()
Out[28]:
one three two
False False True 1
True False False 2
True True 1
dtype: int64
Move an item inside a list?
A slightly shorter solution, that only moves the item to the end, not anywhere is this:
l += [l.pop(0)]
For example:
>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]
Aligning label and textbox on same line (left and right)
You can do it with a table, like this:
<table width="100%">
<tr>
<td style="width: 50%">Left Text</td>
<td style="width: 50%; text-align: right;">Right Text</td>
</tr>
</table>
Or, you can do it with CSS like this:
<div style="float: left;">
Left text
</div>
<div style="float: right;">
Right text
</div>
Function to Calculate a CRC16 Checksum
for (pos = 0; pos < len; pos++) {
crc ^= (uint16_t)buf[pos]; // XOR byte into least sig. byte of crc
for (i = 8; i != 0; i--) { // Loop over each bit
if ((crc & 0x0001) != 0) { // If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= CRC16;
} else { // Else LSB is not set
crc >>= 1; // Just shift right
}
}
}
return crc;
Remove the last line from a file in Bash
awk 'NR>1{print buf}{buf = $0}'
Essentially, this code says the following:
For each line after the first, print the buffered line
for each line, reset the buffer
The buffer is lagged by one line, hence you end up printing lines 1 to n-1
Open URL in new window with JavaScript
Just use window.open()
function? The third parameter lets you specify window size.
Example
var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var URL = "https://www.linkedin.com/cws/share?mini=true&url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);